summaryrefslogtreecommitdiffstats
path: root/test/src/test-gen-c.cpp
blob: 4d5514d7db3913aa18453f3650f8ea2c22867ba0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
#include <string.h>
#include <stdlib.h> // malloc
#include <assert.h> // assert
#include <stdio.h>  // printf
#include <sstream> // stringstream
#include <deque> // deque
#include <boost/algorithm/string.hpp> // trim

#include <iostream>

#define USCXML_VERBOSE
//#define WITH_DM_ECMA_JSC

#include "uscxml/config.h"

#ifdef APPLE
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <pthread.h>
#endif

#ifndef AUTOINCLUDE_TEST
#include "test-c-machine.scxml.c"
//#include "/Users/sradomski/Documents/TK/Code/uscxml/build/cli-debug/test/gen/c/ecma/test-enc-ISO-8859-1.scxml.machine.c"
#endif

#include "uscxml/plugins/Factory.h"
#include "uscxml/plugins/IOProcessorImpl.h"
#include "uscxml/plugins/InvokerImpl.h"
#include "uscxml/util/UUID.h"

//#include "uscxml/plugins/invoker/dirmon/DirMonInvoker.h"
#include "uscxml/plugins/datamodel/promela/PromelaDataModel.h"

#ifdef FEATS_ON_CMD
#ifdef WITH_DM_ECMA_V8
#   if (V8_VERSION == 032317)
#       include "uscxml/plugins/datamodel/ecmascript/v8/032317/V8DataModel.h"
#   endif
#   if (V8_VERSION == 031405)
#       include "uscxml/plugins/datamodel/ecmascript/v8/031405/V8DataModel.h"
#   endif
#endif
#ifdef WITH_DM_ECMA_JSC
#include "uscxml/plugins/datamodel/ecmascript/JavaScriptCore/JSCDataModel.h"
#endif
#ifdef WITH_DM_LUA
#include "uscxml/plugins/datamodel/lua/LuaDataModel.h"
#endif
#endif

#include "uscxml/interpreter/InterpreterImpl.h"
#include "uscxml/interpreter/BasicEventQueue.h"
#include "uscxml/interpreter/BasicDelayedEventQueue.h"

#ifdef BUILD_PROFILING
#   include "uscxml/plugins/DataModel.h"
# endif

#define USER_DATA(ctx) ((StateMachine*)(((uscxml_ctx*)ctx)->user_data))

using namespace uscxml;

namespace XERCESC_NS {
class DOMDocument;
class DOMNode;
}


class StateMachine : public DataModelCallbacks, public IOProcessorCallbacks, public DelayedEventQueueCallbacks, public InvokerCallbacks {
public:
	StateMachine(const uscxml_machine* machine) : machine(machine), parentMachine(NULL), topMostMachine(NULL), invocation(NULL) {
		allMachines[sessionId] = this;
		topMostMachine = this;
		currentMachine = allMachines.begin();
		try {
			init();
		} catch (ErrorEvent e) {
			LOGD(USCXML_FATAL) << e;
		}
	}

	StateMachine(StateMachine* parent, const uscxml_machine* machine, const uscxml_elem_invoke* invoke) : machine(machine), invocation(invoke) {
		parentMachine = parent;
		topMostMachine = parent->topMostMachine;
		init();
	}

	ActionLanguage* getActionLanguage() {
		return NULL;
	}

	std::set<InterpreterMonitor*> getMonitors() {
		return std::set<InterpreterMonitor*>();
	}

	std::string getBaseURL() {
		return "";
	}

	virtual Logger getLogger() {
		return Logger::getDefault();
	}

	const std::string& getName() {
		return name;
	}

	const std::string& getSessionId() {
		return sessionId;
	}
	const std::map<std::string, IOProcessor>& getIOProcessors() {
		return ioProcs;
	}

	void enqueueInternal(const Event& event) {
		iq.push_back(event);
	}
	void enqueueExternal(const Event& event) {
		eq.push_back(event);
	}

	void enqueueAtInvoker(const std::string& invokeId, const Event& event) {
		if (invokers.find(invokeId) != invokers.end())
			invokers[invokeId].eventFromSCXML(event);
	}

	void enqueueAtParent(const Event& event) {
		if (parentMachine != NULL)
			parentMachine->enqueueExternal(event);
	}

	bool isInState(const std::string& stateId) {
		for (size_t i = 0; i < ctx.machine->nr_states; i++) {
			if (ctx.machine->states[i].name &&
			        strcmp(ctx.machine->states[i].name, stateId.c_str()) == 0 &&
			        BIT_HAS(i, ctx.config)) {

				return true;
			}
		}

		return false;
	}

	XERCESC_NS::DOMDocument* getDocument() const {
		return NULL;
	}
	const std::map<std::string, Invoker>& getInvokers() {
		return invokers;
	}

	void init() {
		sessionId = uscxml::UUID::getUUID();
		isFinalized = false;

		// clear and initialize machine context
		memset(&ctx, 0, sizeof(uscxml_ctx));
		ctx.machine = machine;
		ctx.user_data = (void*)this;

		// register callbacks with scxml context
		ctx.is_matched = &isMatched;
		ctx.is_true = &isTrue;
		ctx.raise_done_event = &raiseDoneEvent;
		ctx.invoke = &invoke;
		ctx.exec_content_send = &execContentSend;
		ctx.exec_content_raise = &execContentRaise;
		ctx.exec_content_cancel = &execContentCancel;
		ctx.exec_content_log = &execContentLog;
		ctx.exec_content_assign = &execContentAssign;
		ctx.exec_content_foreach_init = &execContentForeachInit;
		ctx.exec_content_foreach_next = &execContentForeachNext;
		ctx.exec_content_foreach_done = &execContentForeachDone;
		ctx.dequeue_external = &dequeueExternal;
		ctx.dequeue_internal = &dequeueInternal;
		ctx.exec_content_init = &execContentInit;
		ctx.exec_content_script = &execContentScript;

		name = machine->name;

		// register IO Procs
		std::map<std::string, IOProcessorImpl*> allIOProcs = Factory::getInstance()->getIOProcessors();
		for (auto ioProcImpl : allIOProcs) {
			ioProcs[ioProcImpl.first] = Factory::getInstance()->createIOProcessor(ioProcImpl.first, this);
			std::list<std::string> names = ioProcImpl.second->getNames();
			for (auto name : names) {
				ioProcs[name] = ioProcs[ioProcImpl.first];
			}
		}

		delayQueue = DelayedEventQueue(std::shared_ptr<DelayedEventQueueImpl>(new BasicDelayedEventQueue(this)));
		dataModel = Factory::getInstance()->createDataModel(machine->datamodel, this);

		if (invocation != NULL) {
			/// test 226/240 - initialize from invoke request
			if (invocation->params != NULL) {
				const uscxml_elem_param* param = invocation->params;
				while(USCXML_ELEM_PARAM_IS_SET(param)) {
					std::string identifier;
					if (param->name != NULL) {
						identifier = param->name;
					} else if (param->location != NULL) {
						identifier = param->location;
					}
					invokeData[identifier] = parentMachine->dataModel.evalAsData(param->expr);
					param++;
				}
			}

			if (invocation->namelist != NULL) {
				const char* cPtr = invocation->namelist;
				const char* aPtr = invocation->namelist;
				while(cPtr) {
					while (isspace(*cPtr))
						cPtr++;
					aPtr = cPtr;
					while(*cPtr && !isspace(*cPtr))
						cPtr++;

					if (aPtr == cPtr)
						break;

					std::string identifier = std::string(aPtr, cPtr - aPtr);
					invokeData[identifier] = parentMachine->dataModel.evalAsData(identifier);
				}
			}
		}
	}

	virtual ~StateMachine() {
		if (parentMachine != NULL) {
			topMostMachine->allMachines.erase(topMostMachine->invocationIds[invocation]);
		}
//        finalize();

		delayQueue.cancelAllDelayed();

		while(eq.size() > 0) {
			eq.pop_front();
		}
		eq.clear();
		while(iq.size() > 0) {
			iq.pop_front();
		}
		iq.clear();
	}

	bool hasPendingWork() {
		return (iq.size() > 0 ||
		        eq.size() > 0 ||
		        ctx.flags & USCXML_CTX_SPONTANEOUS ||
		        ctx.flags == USCXML_CTX_PRISTINE ||
		        memcmp(ctx.config, ctx.invocations, sizeof(ctx.config)) != 0);
	}

	bool isDone() {
		return ctx.flags & USCXML_CTX_FINISHED;
	}

	void finalize() {
		if (isFinalized)
			return;

		delayQueue.cancelAllDelayed();

		if (parentMachine != NULL) {
			std::lock_guard<std::mutex> lock(mutex);

			Event done;
			done.invokeid = invokeId;
			done.name = "done.invoke." + invokeId;
			parentMachine->eq.push_back(done);
		}
		isFinalized = true;
	}

	void reset() {
		delayQueue.cancelAllDelayed();

		while(eq.size() > 0) {
			eq.pop_front();
		}
		while(iq.size() > 0) {
			iq.pop_front();
		}

		iq.clear();
		eq.clear();

		init();

	}

	int step() {
		// advance current machine if there are multiple
		currentMachine++;
		if (currentMachine == allMachines.end())
			currentMachine = allMachines.begin();

		StateMachine* toRun = currentMachine->second;
		if (!toRun->hasPendingWork()) {
			return USCXML_ERR_IDLE;
		}

		// test 187
		if (toRun->isDone()) {
			toRun->finalize();
			return USCXML_ERR_IDLE;
		}

		state = uscxml_step(&toRun->ctx);
		return state;
	}

	// callbacks for scxml context

	static int isMatched(const uscxml_ctx* ctx, const uscxml_transition* t, const void* e) {
		Event* event = (Event*)e;
		return (nameMatch(t->event, event->name.c_str()));
	}

	static int isTrue(const uscxml_ctx* ctx, const char* expr) {
		try {
			return USER_DATA(ctx)->dataModel.evalAsBool(expr);
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
		}
		return false;
	}

	static int invoke(const uscxml_ctx* ctx, const uscxml_state* s, const uscxml_elem_invoke* invocation, unsigned char uninvoke) {
		std::map<std::string, StateMachine*> &allMachines = USER_DATA(ctx)->topMostMachine->allMachines;
		StateMachine* topMachine = USER_DATA(ctx)->topMostMachine;

		if (uninvoke) {
			if (invocation->machine != NULL) {
				if (topMachine->invocationIds.find(invocation) != topMachine->invocationIds.end() &&
				        allMachines.find(topMachine->invocationIds[invocation]) != allMachines.end()) {

					delete allMachines[topMachine->invocationIds[invocation]];
					topMachine->allMachines.erase(topMachine->invocationIds[invocation]);
					topMachine->invocationIds.erase(invocation);
				}
			} else {
				// TODO: Uninvoke other types of invokers

				return USCXML_ERR_UNSUPPORTED;
			}
		} else {
			// invocations
			if (invocation->machine != NULL) {
				// invoke a nested SCXML machine
				StateMachine* invokedMachine = NULL;
				try {
					invokedMachine = new StateMachine(USER_DATA(ctx), invocation->machine, invocation);
				} catch (Event e) {
					delete invokedMachine;
					return USCXML_ERR_EXEC_CONTENT;
				}
				if (invocation->id != NULL) {
					invokedMachine->invokeId = invocation->id;
				} else if (invocation->idlocation != NULL) {
					// test224
					invokedMachine->invokeId = (invocation->sourcename != NULL ? std::string(invocation->sourcename) + "." : "") + uscxml::UUID::getUUID();
					USER_DATA(ctx)->dataModel.assign(invocation->idlocation, Data(invokedMachine->invokeId, Data::VERBATIM));
				} else {
					invokedMachine->invokeId = uscxml::UUID::getUUID();
				}
				allMachines[invokedMachine->invokeId] = invokedMachine;
				topMachine->invocationIds[invocation] = invokedMachine->invokeId;

			} else if (Factory::getInstance()->hasInvoker(invocation->type)) {

				Event invokeEvent; // see BasicContentExecutor::384ff
				// TODO: Establish the invokeEvent
				if (invocation->params != NULL) {
				}
				Invoker inv = Factory::getInstance()->createInvoker(invocation->type, USER_DATA(ctx));
				inv.invoke("", invokeEvent);
				USER_DATA(ctx)->_invocations[invocation] = inv;
			} else {
				return USCXML_ERR_UNSUPPORTED;
			}
		}
		return USCXML_ERR_OK;
	}

	static int raiseDoneEvent(const uscxml_ctx* ctx, const uscxml_state* state, const uscxml_elem_donedata* donedata) {
		Event e;
		e.name = std::string("done.state.") + state->name;

		if (donedata) {
			if (donedata->content != NULL) {
				if (isNumeric(donedata->content, 10)) {
					// test 529
					e.data = Data(strTo<double>(donedata->content), Data::INTERPRETED);
				} else {
					e.data = Data(donedata->content, Data::VERBATIM);
				}
			} else if (donedata->contentexpr != NULL) {
				try {
					e.data = USER_DATA(ctx)->dataModel.getAsData(donedata->contentexpr);
				} catch (Event e) {
					execContentRaise(ctx, e.name.c_str());
				}
			} else {
				try {
					const uscxml_elem_param* param = donedata->params;
					while (param && USCXML_ELEM_PARAM_IS_SET(param)) {
						Data paramValue;
						if (param->expr != NULL) {
							paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->expr);
						} else if(param->location) {
							paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->location);
						}
						e.params.insert(std::make_pair(param->name, paramValue));
						param++;
					}
				} catch (Event e) {
					execContentRaise(ctx, e.name.c_str());
				}
			}
		}

#ifdef USCXML_VERBOSE
		printf("Raising Done Event: %s\n", e.name.c_str());
#endif
		USER_DATA(ctx)->iq.push_back(e);
		return USCXML_ERR_OK;
	}

	static int execContentSend(const uscxml_ctx* ctx, const uscxml_elem_send* send) {
		Event e;

		std::string sendid;
		if (send->id != NULL) {
			sendid = send->id;
		} else {
			sendid = uscxml::UUID::getUUID();
			if (send->idlocation != NULL) {
				USER_DATA(ctx)->dataModel.assign(send->idlocation, Data(sendid, Data::VERBATIM));
			} else {
				e.hideSendId = true;
			}
		}
		e.sendid = sendid;

		std::string target;
		if (send->target != NULL) {
			target = send->target;
		} else if (send->targetexpr != NULL) {
			target = USER_DATA(ctx)->dataModel.evalAsData(send->targetexpr).atom;
		} else {
			target = "#_external";
		}

		if (target.size() > 0 && (target[0] != '#' || target[1] != '_')) {
			std::cerr << "Target '" << target << "' is not supported yet" << std::endl;
			e.name = "error.execution";
			execContentRaise(ctx, e);
			return USCXML_ERR_INVALID_TARGET;
		}

		e.origintype = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor";

		std::string type;
		try {
			if (send->type != NULL) {
				type = send->type;
			} else if (send->typeexpr != NULL) {
				type = USER_DATA(ctx)->dataModel.evalAsData(send->typeexpr).atom;
			} else {
				type = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor";
			}
		} catch (Event exc) {
			e.name = "error.execution";
			execContentRaise(ctx, e);
			return USCXML_ERR_EXEC_CONTENT;
		}

		// only one somewhat supported
		if (type != "http://www.w3.org/TR/scxml/#SCXMLEventProcessor") {
			e.name = "error.execution";
			execContentRaise(ctx, e);
			return USCXML_ERR_INVALID_TARGET;
		}

		e.origintype = type;
		e.origin = "#_scxml_" + USER_DATA(ctx)->sessionId;
		e.invokeid = USER_DATA(ctx)->invokeId;

		if (send->eventexpr != NULL) {
			e.name = USER_DATA(ctx)->dataModel.evalAsData(send->eventexpr).atom;
		} else {
			e.name = send->event;
		}

		try {
			const uscxml_elem_param* param = send->params;
			while (param && USCXML_ELEM_PARAM_IS_SET(param)) {
				Data paramValue;
				if (param->expr != NULL) {
					paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->expr);
				} else if(param->location) {
					paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->location);
				}
				e.params.insert(std::make_pair(param->name, paramValue));
				param++;
			}
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
			return USCXML_ERR_EXEC_CONTENT;
		}

		try {
			if (send->namelist != NULL) {
				const char* bPtr = &send->namelist[0];
				const char* ePtr = bPtr;
				while(*ePtr != '\0') {
					ePtr++;
					if (*ePtr == ' ' || *ePtr == '\0') {
						std::string key(bPtr, ePtr - bPtr);
						e.params.insert(std::make_pair(key, USER_DATA(ctx)->dataModel.evalAsData(key)));
						if (*ePtr == '\0')
							break;
						bPtr = ++ePtr;
					}
				}
			}
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
			return USCXML_ERR_EXEC_CONTENT;
		}

		if (send->content != NULL) {
			try {
				// will it parse as json?
				Data d = USER_DATA(ctx)->dataModel.getAsData(send->content);
				if (!d.empty()) {
					e.data = d;
				}
			} catch (Event err) {
				e.data = Data(spaceNormalize(send->content), Data::VERBATIM);
			}
		}

		size_t delayMs = 0;
		if (send->delayexpr != NULL) {
			std::string delay = USER_DATA(ctx)->dataModel.evalAsData(send->delayexpr).atom;
			if (delay.size() > 0) {
				boost::trim(delay);

				NumAttr delayAttr(delay);
				if (iequals(delayAttr.unit, "ms")) {
					delayMs = strTo<uint32_t>(delayAttr.value);
				} else if (iequals(delayAttr.unit, "s")) {
					delayMs = strTo<double>(delayAttr.value) * 1000;
				} else if (delayAttr.unit.length() == 0) { // unit less delay is interpreted as milliseconds
					delayMs = strTo<uint32_t>(delayAttr.value);
				} else {
					std::cerr << "Cannot make sense of delay value " << delay << ": does not end in 's' or 'ms'";
				}
			}
		} else if (send->delay > 0) {
			delayMs = send->delay;
		}

		if (USER_DATA(ctx)->invokeId.size() > 0) {
			e.invokeid = USER_DATA(ctx)->invokeId;
		}

		USER_DATA(ctx)->sendUUIDs[e.getUUID()] = std::make_tuple(e.sendid, target, type);
		if (delayMs > 0) {
			USER_DATA(ctx)->delayQueue.enqueueDelayed(e, delayMs, e.getUUID());
		} else {
			USER_DATA(ctx)->eventReady(e, e.getUUID());
		}

		return USCXML_ERR_OK;
	}

	static int execContentRaise(const uscxml_ctx* ctx, Event& e) {
		if (boost::starts_with(e.name, "error.")) {
			e.eventType = Event::PLATFORM;
		} else {
			e.eventType = Event::INTERNAL;
		}
		USER_DATA(ctx)->iq.push_back(e);
		return USCXML_ERR_OK;
	}

	static int execContentRaise(const uscxml_ctx* ctx, const char* event) {
		Event e;
		e.name = event;
		return execContentRaise(ctx, e);
	}

	static int execContentCancel(const uscxml_ctx* ctx, const char* sendid, const char* sendidexpr) {
		std::string eventId;
		if (sendid != NULL) {
			eventId = sendid;
		} else if (sendidexpr != NULL) {
			eventId = USER_DATA(ctx)->dataModel.evalAsData(sendidexpr).atom;
		}

		if (eventId.length() > 0) {
			// find all events with given id
			for (auto evIter = USER_DATA(ctx)->sendUUIDs.begin(); evIter != USER_DATA(ctx)->sendUUIDs.end(); evIter++) {
				std::string sendid = std::get<0>(evIter->second);
				if (eventId == sendid) {
					USER_DATA(ctx)->delayQueue.cancelDelayed(evIter->first);
				}
			}

		} else {
			execContentRaise(ctx, "error.execution");
			return USCXML_ERR_EXEC_CONTENT;
		}
		return USCXML_ERR_OK;
	}

	static int execContentLog(const uscxml_ctx* ctx, const char* label, const char* expr) {
		try {
			if (label != NULL) {
				printf("%s%s", label, (expr != NULL ? ": " : ""));
			}
			if (expr != NULL) {
				std::string msg = USER_DATA(ctx)->dataModel.evalAsData(expr).atom;
				printf("%s", msg.c_str());
			}
			if (label != NULL || expr != NULL) {
				printf("\n");
			}
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
			return USCXML_ERR_EXEC_CONTENT;
		}
		return USCXML_ERR_OK;
	}

	static int execContentAssign(const uscxml_ctx* ctx, const uscxml_elem_assign* assign) {
		std::string key = assign->location;
		if (key == "_sessionid" || key == "_name" || key == "_ioprocessors" || key == "_invokers" || key == "_event") {
			execContentRaise(ctx, "error.execution");
			return USCXML_ERR_EXEC_CONTENT;
		}

		try {
//			Data d = USER_DATA(ctx)->dataModel.getStringAsData(expr);
			if (assign->expr != NULL) {
//				USER_DATA(ctx)->dataModel.assign(key,
//				                                 USER_DATA(ctx)->dataModel.evalAsData(assign->expr));
				USER_DATA(ctx)->dataModel.assign(key, Data(assign->expr, Data::INTERPRETED));
			} else if (assign->content != NULL) {
				Data d = Data(assign->content, Data::INTERPRETED);
				USER_DATA(ctx)->dataModel.assign(key, d);
			}
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
			return USCXML_ERR_EXEC_CONTENT;
		}
		return USCXML_ERR_OK;
	}

	static int execContentForeachInit(const uscxml_ctx* ctx, const uscxml_elem_foreach* foreach) {
		try {
			scxml_foreach_info* feInfo = (scxml_foreach_info*)malloc(sizeof(scxml_foreach_info));
			USER_DATA(ctx)->foreachInfo[foreach] = feInfo;

			feInfo->iterations = USER_DATA(ctx)->dataModel.getLength(foreach->array);
			feInfo->currIteration = 0;
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
			return USCXML_ERR_EXEC_CONTENT;
		}
		return USCXML_ERR_OK;
	}

	static int execContentForeachNext(const uscxml_ctx* ctx, const uscxml_elem_foreach* foreach) {
		try {
			scxml_foreach_info* feInfo = USER_DATA(ctx)->foreachInfo[foreach];
			if (feInfo->currIteration < feInfo->iterations) {
				USER_DATA(ctx)->dataModel.setForeach((foreach->item != NULL ? foreach->item : ""),
				                                     (foreach->array != NULL ? foreach->array : ""),
					                                     (foreach->index != NULL ? foreach->index : ""),
						                                     feInfo->currIteration);
				feInfo->currIteration++;
				return USCXML_ERR_OK;
			}
		} catch (Event e) {
			execContentRaise(ctx, e.name.c_str());
			free(USER_DATA(ctx)->foreachInfo[foreach]);
			USER_DATA(ctx)->foreachInfo.erase(foreach);
			return USCXML_ERR_EXEC_CONTENT;
		}
		return USCXML_ERR_FOREACH_DONE;
	}

	static int execContentForeachDone(const uscxml_ctx* ctx, const uscxml_elem_foreach* foreach) {
		free(USER_DATA(ctx)->foreachInfo[foreach]);
		USER_DATA(ctx)->foreachInfo.erase(foreach);
		return USCXML_ERR_OK;
	}

	static int execContentInit(const uscxml_ctx* ctx, const uscxml_elem_data* data) {
		while(USCXML_ELEM_DATA_IS_SET(data)) {
			if (USER_DATA(ctx)->invokeData.find(data->id) != USER_DATA(ctx)->invokeData.end()) {
				// passed via param or namelist: test245
				try {
					USER_DATA(ctx)->dataModel.init(data->id, USER_DATA(ctx)->invokeData[data->id]);
				} catch (Event e) {
					execContentRaise(ctx, e.name.c_str());
				}
			} else {
				Data d;
				std::stringstream content;

				try {
					if (data->expr != NULL) {
						d = Data(data->expr, Data::INTERPRETED);
//						d = USER_DATA(ctx)->dataModel.evalAsData(data->expr);

					} else if (data->content != NULL || data->src != NULL) {
						if (data->content) {
							content << data->content;
						} else {
// avoid dependency on URL.cpp -> urlparser -> curl
#if 0
							URL sourceURL(data->src);
							if (USER_DATA(ctx)->baseURL.size() > 0) {
								sourceURL = URL::resolve(sourceURL, USER_DATA(ctx)->baseURL);
							} else {
								sourceURL = URL::resolveWithCWD(sourceURL);
							}
							content << sourceURL.getInContent();
#endif
						}
						/**
						 * first attempt to parse as structured data, we will try
						 * as space normalized string literals if this fails below
						 */
						d = USER_DATA(ctx)->dataModel.getAsData(content.str());
						if (d.empty()) {
							d = Data(escape(spaceNormalize(content.str())), Data::VERBATIM);
						}
					} else {
						// leave d undefined
					}
					// this might fail with an unquoted string literal in content
					USER_DATA(ctx)->dataModel.init(data->id, d);

				} catch (Event e) {
					if (content.str().size() > 0) {
						try {
							d = Data(escape(spaceNormalize(content.str())), Data::VERBATIM);
							USER_DATA(ctx)->dataModel.init(data->id, d);
						} catch (Event e) {
							execContentRaise(ctx, e.name.c_str());
						}
					} else {
						execContentRaise(ctx, e.name.c_str());
					}
				}
			}
			data++;
		}
		return USCXML_ERR_OK;
	}

	static int execContentScript(const uscxml_ctx* ctx, const char* src, const char* content) {
		if (content != NULL) {
			USER_DATA(ctx)->dataModel.evalAsData(content);
		} else if (src != NULL) {
			return USCXML_ERR_UNSUPPORTED;
		}
		return USCXML_ERR_OK;
	}

	static void* dequeueExternal(const uscxml_ctx* ctx) {
		std::lock_guard<std::mutex> lock(USER_DATA(ctx)->mutex);
		if (USER_DATA(ctx)->eq.size() == 0)
			return NULL;

		// set event
		USER_DATA(ctx)->currEvent = USER_DATA(ctx)->eq.front();
		USER_DATA(ctx)->eq.pop_front();

		// get an alias
		const Event& e = USER_DATA(ctx)->currEvent;
		USER_DATA(ctx)->dataModel.setEvent(e);

		std::map<std::string, StateMachine*>& allMachines = USER_DATA(ctx)->topMostMachine->allMachines;
		if (e.invokeid.size() > 0 && allMachines.find(e.invokeid) != allMachines.end()) {
			// we need to check for finalize content
			StateMachine* invokedMachine = allMachines[e.invokeid];
			if (invokedMachine->invocation != NULL && invokedMachine->invocation->finalize != NULL)
				invokedMachine->invocation->finalize(ctx,
				                                     invokedMachine->invocation,
				                                     &e);
		}

		// auto forward event
		for (std::map<std::string, StateMachine*>::iterator machIter = allMachines.begin(); machIter != allMachines.end(); machIter++) {
			if (machIter->second->parentMachine != NULL &&
			        machIter->second->parentMachine == USER_DATA(ctx) &&
			        machIter->second->invocation->autoforward) {
				std::lock_guard<std::mutex> lock(machIter->second->mutex);

				Event e2(e);
				machIter->second->eq.push_back(e2);
			}
		}

#ifdef USCXML_VERBOSE
		printf("Popping External Event: %s\n", e.name.c_str());
#endif
		return &USER_DATA(ctx)->currEvent;
	}

	static void* dequeueInternal(const uscxml_ctx* ctx) {
		if (USER_DATA(ctx)->iq.size() == 0)
			return NULL;
		// set event
		USER_DATA(ctx)->currEvent = USER_DATA(ctx)->iq.front();
		USER_DATA(ctx)->iq.pop_front();

		// get an alias
		const Event& e = USER_DATA(ctx)->currEvent;
		USER_DATA(ctx)->dataModel.setEvent(e);

#ifdef USCXML_VERBOSE
		printf("Popping Internal Event: %s\n", e.name.c_str());
#endif
		return &USER_DATA(ctx)->currEvent;
	}

	void eventReady(Event& e, const std::string& eventUUID) {
		std::lock_guard<std::mutex> lock(mutex);

		//std::make_tuple(e.sendid, target, type);

		std::string sendid = std::get<0>(sendUUIDs[e.getUUID()]);
		std::string target = std::get<1>(sendUUIDs[e.getUUID()]);
		std::string type = std::get<2>(sendUUIDs[e.getUUID()]);

		if (target == "#_internal") {
			e.eventType = Event::INTERNAL;
#ifdef USCXML_VERBOSE
			printf("Pushing Internal Event: %s\n", e.name.c_str());
#endif
			iq.push_back(e);
		} else if (target == "#_external") {
			e.eventType = Event::EXTERNAL;
#ifdef USCXML_VERBOSE
			printf("Pushing External Event: %s\n", e.name.c_str());
#endif
			eq.push_back(e);
		} else if (target == "#_parent") {
			e.eventType = Event::EXTERNAL;
			if (parentMachine != NULL) {
				parentMachine->eq.push_back(e);
			}
			// TODO: handle invalid parent
		} else if (target.substr(0,8) == "#_scxml_") {
			std::string sessionId = target.substr(8);
			bool sessionFound = false;
			for (std::map<std::string, StateMachine*>::iterator machIter = topMostMachine->allMachines.begin();
			        machIter != topMostMachine->allMachines.end(); machIter++) {
				if (machIter->second->sessionId == sessionId) {
					e.eventType = Event::EXTERNAL;
					machIter->second->eq.push_back(e);
					sessionFound = true;
					break;
				}
			}
			if (!sessionFound) {
				// test496
				execContentRaise(&ctx, "error.communication");
			}
		} else if (target.substr(0,2) == "#_") {
			e.eventType = Event::EXTERNAL;
			std::string targetId = target.substr(2);
			if (topMostMachine->allMachines.find(targetId) != topMostMachine->allMachines.end()) {
				topMostMachine->allMachines[targetId]->eq.push_back(e);
			} else {
				execContentRaise(&ctx, "error.communication");
			}
		} else {
			assert(false);
		}
		monitor.notify_all();
	}

	static std::string spaceNormalize(const std::string& text) {
		std::stringstream content;
		std::string seperator;

		size_t start = 0;
		for (size_t i = 0; i < text.size(); i++) {
			if (isspace(text[i])) {
				if (i > 0 && start < i) {
					content << seperator << text.substr(start, i - start);
					seperator = " ";
				}
				while(isspace(text[++i])); // skip whitespaces
				start = i;
			} else if (i + 1 == text.size()) {
				content << seperator << text.substr(start, i + 1 - start);
			}
		}
		return content.str();
	}

	// TODO: isolate InterpreterImpl to reduce header deps on libxml/parser.h
	static bool nameMatch(const std::string& eventDescs, const std::string& eventName) {
		if(eventDescs.length() == 0 || eventName.length() == 0)
			return false;

		// naive case of single descriptor and exact match
		if (iequals(eventDescs, eventName))
			return true;

		size_t start = 0;
		std::string eventDesc;
		for (size_t i = 0; i < eventDescs.size(); i++) {
			if (isspace(eventDescs[i])) {
				if (i > 0 && start < i - 1) {
					eventDesc = eventDescs.substr(start, i - start);
				}
				while(isspace(eventDescs[++i])); // skip whitespaces
				start = i;
			} else if (i + 1 == eventDescs.size()) {
				eventDesc = eventDescs.substr(start, i + 1 - start);
			}

			if (eventDesc.size() > 0) {
				// remove optional trailing .* for CCXML compatibility
				if (eventDesc.find("*", eventDesc.size() - 1) != std::string::npos)
					eventDesc = eventDesc.substr(0, eventDesc.size() - 1);
				if (eventDesc.find(".", eventDesc.size() - 1) != std::string::npos)
					eventDesc = eventDesc.substr(0, eventDesc.size() - 1);

				// was eventDesc the * wildcard
				if (eventDesc.size() == 0)
					return true;

				// eventDesc has to be a real prefix of event now and therefore shorter
				if (eventDesc.size() > eventName.size())
					goto NEXT_DESC;

				// are they already equal?
				if (iequals(eventDesc, eventName))
					return true;

				if (eventName.find(eventDesc) == 0) {
					if (eventName.find(".", eventDesc.size()) == eventDesc.size())
						return true;
				}
NEXT_DESC:
				eventDesc = "";
			}
		}
		return false;
	}

	Event currEvent;

	std::map<const uscxml_elem_invoke*, std::string> invocationIds;
	std::map<std::string, StateMachine*> allMachines;

	bool isFinalized;
	int state;
	uscxml_ctx ctx;
	const uscxml_machine* machine;

	StateMachine* parentMachine;
	StateMachine* topMostMachine;
	std::map<std::string, StateMachine* >::iterator currentMachine; // next machine to advance

	std::string baseURL;
	std::string sessionId;
	std::string name;

	// in case we were invoked
	std::string invokeId;
	const uscxml_elem_invoke* invocation;
	std::map<std::string, Data> invokeData;

	std::map<const uscxml_elem_invoke*, Invoker> _invocations;

	std::deque<Event> iq;
	std::deque<Event> eq;

	DataModel dataModel;
	std::map<std::string, IOProcessor> ioProcs;
	std::map<std::string, Invoker> invokers;

protected:
	struct scxml_foreach_info {
		size_t iterations;
		size_t currIteration;
	};

//	X xmlPrefix;
//	XERCESC_NS::DOMDocument* document;

	DelayedEventQueue delayQueue;
	std::map<std::string, std::tuple<std::string, std::string, std::string> > sendUUIDs;
	std::map<const uscxml_elem_foreach*, scxml_foreach_info*> foreachInfo;

	std::condition_variable monitor;
	std::mutex mutex;
};


int main(int argc, char** argv) {

	int err = 0;
	size_t benchmarkRuns = 1;
	const char* envBenchmarkRuns = getenv("USCXML_BENCHMARK_ITERATIONS");
	if (envBenchmarkRuns != NULL) {
		benchmarkRuns = strTo<size_t>(envBenchmarkRuns);
	}

	// start the webserver for the basichttp tests
//    HTTPServer::getInstance(3453, 3454, NULL);

	size_t remainingRuns = benchmarkRuns;

	size_t microSteps = 0;

#ifdef FEATS_ON_CMD
	Factory::getInstance()->registerDataModel(new PromelaDataModel());
#ifdef WITH_DM_ECMA_V8
	Factory::getInstance()->registerDataModel(new V8DataModel());
#endif
#ifdef WITH_DM_ECMA_JSC
	Factory::getInstance()->registerDataModel(new JSCDataModel());
#endif
#ifdef WITH_DM_LUA
	Factory::getInstance()->registerDataModel(new LuaDataModel());
#endif
#endif

	StateMachine rootMachine(&USCXML_MACHINE);

	while(remainingRuns-- > 0) {

		microSteps = 0;

		for (;;) {
			err = rootMachine.step();
			if (rootMachine.isDone())
				break;
			microSteps++;
		}
		microSteps++;

		assert(rootMachine.ctx.flags & USCXML_CTX_TOP_LEVEL_FINAL);

		size_t passIdx = 0;
		for (size_t i = 0; i < rootMachine.ctx.machine->nr_states; i++) {
			if (rootMachine.ctx.machine->states[i].name && strcmp(rootMachine.ctx.machine->states[i].name, "pass") == 0) {
				passIdx = i;
				break;
			}
		}

		if(!BIT_HAS(passIdx, rootMachine.ctx.config)) {
			std::cerr << "Interpreter did not end in pass" << std::endl;
			exit(EXIT_FAILURE);
		}
		rootMachine.reset();
	}

	return EXIT_SUCCESS;
}