summaryrefslogtreecommitdiffstats
path: root/src/uscxml/Interpreter.h
blob: 673cba104332faad3104522688bce3ccb54f7a24 (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
#ifndef RUNTIME_H_SQ1MBKGN
#define RUNTIME_H_SQ1MBKGN

#include "uscxml/Common.h"
#include "uscxml/URL.h"

#include <boost/uuid/uuid_generators.hpp>
#include <boost/algorithm/string.hpp>

#include <iostream>
#include <set>
#include <map>

#include <XPath/XPath.hpp>
#include <DOM/Document.hpp>
#include <io/uri.hpp>

#include <DOM/SAX2DOM/SAX2DOM.hpp>
#include <SAX/helpers/CatchErrorHandler.hpp>

#include "uscxml/concurrency/tinythread.h"
#include "uscxml/concurrency/eventqueue/DelayedEventQueue.h"
#include "uscxml/concurrency/BlockingQueue.h"
#include "uscxml/Message.h"
#include "uscxml/Factory.h"

#include "uscxml/server/InterpreterServlet.h"

namespace uscxml {

class HTTPServletInvoker;
class InterpreterMonitor;

class NumAttr {
public:
	NumAttr(const std::string& str) {
		size_t valueStart = str.find_first_of("0123456789.");
		if (valueStart != std::string::npos) {
			size_t valueEnd = str.find_last_of("0123456789.");
			if (valueEnd != std::string::npos) {
				value = str.substr(valueStart, (valueEnd - valueStart) + 1);
				size_t unitStart = str.find_first_not_of(" \t", valueEnd + 1);
				if (unitStart != std::string::npos) {
					size_t unitEnd = str.find_last_of(" \t");
					if (unitEnd != std::string::npos && unitEnd > unitStart) {
						unit = str.substr(unitStart, unitEnd - unitStart);
					} else {
						unit = str.substr(unitStart, str.length() - unitStart);
					}
				}
			}
		}
	}

	std::string value;
	std::string unit;
};

class SCXMLParser : public Arabica::SAX2DOM::Parser<std::string> {
public:
	SCXMLParser(InterpreterImpl* interpreter);
	void startPrefixMapping(const std::string& /* prefix */, const std::string& /* uri */);

	Arabica::SAX::CatchErrorHandler<std::string> _errorHandler;
	InterpreterImpl* _interpreter;
};

enum Capabilities {
    CAN_NOTHING = 0,
    CAN_BASIC_HTTP = 1,
    CAN_GENERIC_HTTP = 2,
};

class InterpreterImpl : public boost::enable_shared_from_this<InterpreterImpl> {
public:

	enum Binding {
	    EARLY = 0,
	    LATE = 1
	};

	virtual ~InterpreterImpl();

	void start();
	static void run(void*);
	void join() {
		if (_thread != NULL) _thread->join();
	};
	bool isRunning() {
		return _running || !_done;
	}

	/// This one ought to be pure, but SWIG will generate gibberish if it is
	virtual void interpret() {};

	void addMonitor(InterpreterMonitor* monitor)             {
		_monitors.insert(monitor);
	}

	void removeMonitor(InterpreterMonitor* monitor)          {
		_monitors.erase(monitor);
	}

	void setBaseURI(std::string baseURI)                     {
		_baseURI = URL(baseURI);
	}
	URL getBaseURI()                                         {
		return _baseURI;
	}
	bool toAbsoluteURI(URL& uri);

	void setCmdLineOptions(int argc, char** argv);
	Data getCmdLineOptions() {
		return _cmdLineOptions;
	}

	InterpreterServlet* getHTTPServlet() {
		return _httpServlet;
	}

	DataModel getDataModel()                                 {
		return _dataModel;
	}
	void setParentQueue(uscxml::concurrency::BlockingQueue<SendRequest>* parentQueue) {
		_parentQueue = parentQueue;
	}
	std::string getXPathPrefix()                             {
		return _xpathPrefix;
	}
	std::string getXMLPrefix()                               {
		return _xmlNSPrefix;
	}
	Arabica::XPath::StandardNamespaceContext<std::string>& getNSContext() {
		return _nsContext;
	}
	std::string getXMLPrefixForNS(const std::string& ns)     {
		if (_nsToPrefix.find(ns) != _nsToPrefix.end())
			return _nsToPrefix[ns] + ":";
		return "";
	}

	void receiveInternal(const Event& event);
	void receive(const Event& event, bool toFront = false);

	Event getCurrentEvent() {
		return _currEvent;
	}

	Arabica::XPath::NodeSet<std::string> getConfiguration()  {
		return _configuration;
	}
	void setConfiguration(const std::vector<std::string>& states) {
		_userDefinedStartConfiguration = states;
	}
	void setInvokeRequest(const InvokeRequest& req) {
		_invokeReq = req;
	}

	Arabica::DOM::Node<std::string> getState(const std::string& stateId);
	Arabica::XPath::NodeSet<std::string> getStates(const std::vector<std::string>& stateIds);

	Arabica::DOM::Document<std::string>& getDocument()       {
		return _document;
	}

	void setCapabilities(unsigned int capabilities)          {
		_capabilities = capabilities;
	}

	void setName(const std::string& name);
	const std::string& getName()                             {
		return _name;
	}
	const std::string& getSessionId()                        {
		return _sessionId;
	}

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

	const std::map<std::string, Invoker>& getInvokers() {
		return _invokers;
	}

	bool runOnMainThread(int fps, bool blocking = true);

	static bool isMember(const Arabica::DOM::Node<std::string>& node, const Arabica::XPath::NodeSet<std::string>& set);

	void dump();
	bool hasLegalConfiguration();

	static bool isState(const Arabica::DOM::Node<std::string>& state);
	static bool isPseudoState(const Arabica::DOM::Node<std::string>& state);
	static bool isTransitionTarget(const Arabica::DOM::Node<std::string>& elem);
	static bool isTargetless(const Arabica::DOM::Node<std::string>& transition);
	static bool isAtomic(const Arabica::DOM::Node<std::string>& state);
	static bool isFinal(const Arabica::DOM::Node<std::string>& state);
	static bool isHistory(const Arabica::DOM::Node<std::string>& state);
	static bool isParallel(const Arabica::DOM::Node<std::string>& state);
	static bool isCompound(const Arabica::DOM::Node<std::string>& state);
	static bool isDescendant(const Arabica::DOM::Node<std::string>& s1, const Arabica::DOM::Node<std::string>& s2);

	static std::vector<std::string> tokenizeIdRefs(const std::string& idRefs);

	bool isInitial(const Arabica::DOM::Node<std::string>& state);
	Arabica::XPath::NodeSet<std::string> getInitialStates(Arabica::DOM::Node<std::string> state = Arabica::DOM::Node<std::string>());
	static Arabica::XPath::NodeSet<std::string> getChildStates(const Arabica::DOM::Node<std::string>& state);
	static Arabica::DOM::Node<std::string> getParentState(const Arabica::DOM::Node<std::string>& element);
	static Arabica::DOM::Node<std::string> getAncestorElement(const Arabica::DOM::Node<std::string>& node, const std::string tagName);
	Arabica::XPath::NodeSet<std::string> getTargetStates(const Arabica::DOM::Node<std::string>& transition);
	Arabica::DOM::Node<std::string> getSourceState(const Arabica::DOM::Node<std::string>& transition);

	static Arabica::XPath::NodeSet<std::string> filterChildElements(const std::string& tagname, const Arabica::DOM::Node<std::string>& node);
	static Arabica::XPath::NodeSet<std::string> filterChildElements(const std::string& tagName, const Arabica::XPath::NodeSet<std::string>& nodeSet);
	Arabica::DOM::Node<std::string> findLCCA(const Arabica::XPath::NodeSet<std::string>& states);
	Arabica::XPath::NodeSet<std::string> getProperAncestors(const Arabica::DOM::Node<std::string>& s1, const Arabica::DOM::Node<std::string>& s2);
	static const std::string getUUID();

protected:
	InterpreterImpl();
	void init();

	void normalize(Arabica::DOM::Element<std::string>& scxml);
	void initializeData(const Arabica::DOM::Element<std::string>& data);
	void setupIOProcessors();

	bool _stable;
	tthread::thread* _thread;
	tthread::recursive_mutex _mutex;
	tthread::recursive_mutex _ioProcMutex;

	URL _baseURI;
	Arabica::DOM::Document<std::string> _document;
	Arabica::DOM::Element<std::string> _scxml;
	Arabica::XPath::XPath<std::string> _xpath;
	Arabica::XPath::StandardNamespaceContext<std::string> _nsContext;
	std::string _xmlNSPrefix; // the actual prefix for elements in the xml file
	std::string _xpathPrefix; // prefix mapped for xpath, "scxml" is _xmlNSPrefix is empty but _nsURL set
	std::string _nsURL;       // ough to be "http://www.w3.org/2005/07/scxml"
	std::map<std::string, std::string> _nsToPrefix;

	bool _running;
	bool _done;
	bool _isInitialized;
	InterpreterImpl::Binding _binding;
	Arabica::XPath::NodeSet<std::string> _configuration;
	Arabica::XPath::NodeSet<std::string> _statesToInvoke;
	std::vector<std::string> _userDefinedStartConfiguration;
	InvokeRequest _invokeReq;

	DataModel _dataModel;
	std::map<std::string, Arabica::XPath::NodeSet<std::string> > _historyValue;

	std::list<Event > _internalQueue;
	uscxml::concurrency::BlockingQueue<Event> _externalQueue;
	uscxml::concurrency::BlockingQueue<SendRequest>* _parentQueue;
	DelayedEventQueue* _sendQueue;

	Event _currEvent;
	InterpreterServlet* _httpServlet;
	std::set<InterpreterMonitor*> _monitors;

	static URL toBaseURI(const URL& url);

	void executeContent(const Arabica::DOM::Node<std::string>& content, bool rethrow = false);
	void executeContent(const Arabica::DOM::NodeList<std::string>& content, bool rethrow = false);
	void executeContent(const Arabica::XPath::NodeSet<std::string>& content, bool rethrow = false);

	void processContentElement(const Arabica::DOM::Node<std::string>& element,
	                           Arabica::DOM::Document<std::string>& dom,
	                           std::string& text,
	                           Data& data);
	void processParamChilds(const Arabica::DOM::Node<std::string>& element, std::multimap<std::string, std::string>& params);

	void send(const Arabica::DOM::Node<std::string>& element);
	void invoke(const Arabica::DOM::Node<std::string>& element);
	void cancelInvoke(const Arabica::DOM::Node<std::string>& element);
	void returnDoneEvent(const Arabica::DOM::Node<std::string>& state);
	void internalDoneSend(const Arabica::DOM::Node<std::string>& state);
	static void delayedSend(void* userdata, std::string eventName);

	static bool nameMatch(const std::string& transitionEvent, const std::string& event);
	bool hasConditionMatch(const Arabica::DOM::Node<std::string>& conditional);
	bool isInFinalState(const Arabica::DOM::Node<std::string>& state);
	bool parentIsScxmlState(const Arabica::DOM::Node<std::string>& state);

	static boost::uuids::random_generator uuidGen;

	long _lastRunOnMainThread;
	std::string _name;
	std::string _sessionId;
	unsigned int _capabilities;

	Data _cmdLineOptions;

	IOProcessor getIOProcessor(const std::string& type);

	std::map<std::string, IOProcessor> _ioProcessors;
	std::map<std::string, std::pair<InterpreterImpl*, SendRequest> > _sendIds;
	std::map<std::string, Invoker> _invokers;
	std::map<std::string, Invoker> _autoForwardees;
	std::map<Arabica::DOM::Node<std::string>, ExecutableContent> _executableContent;

	/// TODO: We need to remember to adapt them when the DOM is operated upon
	std::map<std::string, Arabica::DOM::Node<std::string> > _cachedStates;
	std::map<std::string, URL> _cachedURLs;

	friend class SCXMLParser;
	friend class USCXMLInvoker;
	friend class SCXMLIOProcessor;
	friend class Interpreter;
};

class Interpreter {
public:
	static Interpreter fromDOM(const Arabica::DOM::Document<std::string>& dom);
	static Interpreter fromXML(const std::string& xml);
	static Interpreter fromURI(const std::string& uri);
	static Interpreter fromInputSource(Arabica::SAX::InputSource<std::string>& source);

	Interpreter() : _impl() {}
	Interpreter(boost::shared_ptr<InterpreterImpl> const impl) : _impl(impl) { }
	Interpreter(const Interpreter& other) : _impl(other._impl) { }
	virtual ~Interpreter() {};

	operator bool() const {
		return _impl;
	}
	bool operator< (const Interpreter& other) const     {
		return _impl < other._impl;
	}
	bool operator==(const Interpreter& other) const     {
		return _impl == other._impl;
	}
	bool operator!=(const Interpreter& other) const     {
		return _impl != other._impl;
	}
	Interpreter& operator= (const Interpreter& other)   {
		_impl = other._impl;
		return *this;
	}

	void start() {
		return _impl->start();
	}
	void join() {
		return _impl->join();
	};
	bool isRunning() {
		return _impl->isRunning();
	}

	void interpret() {
		_impl->interpret();
	};

	void addMonitor(InterpreterMonitor* monitor)             {
		return _impl->addMonitor(monitor);
	}

	void removeMonitor(InterpreterMonitor* monitor)          {
		return _impl->removeMonitor(monitor);
	}

	void setBaseURI(std::string baseURI)                     {
		return _impl->setBaseURI(baseURI);
	}
	URL getBaseURI()                                         {
		return _impl->getBaseURI();
	}
	bool toAbsoluteURI(URL& uri) {
		return _impl->toAbsoluteURI(uri);
	}

	void setCmdLineOptions(int argc, char** argv) {
		return _impl->setCmdLineOptions(argc, argv);
	}
	Data getCmdLineOptions() {
		return _impl->getCmdLineOptions();
	}

	InterpreterServlet* getHTTPServlet() {
		return _impl->getHTTPServlet();
	}

	DataModel getDataModel()                                 {
		return _impl->getDataModel();
	}
	void setParentQueue(uscxml::concurrency::BlockingQueue<SendRequest>* parentQueue) {
		return _impl->setParentQueue(parentQueue);
	}
	std::string getXPathPrefix()                             {
		return _impl->getXPathPrefix();
	}
	std::string getXMLPrefix()                               {
		return _impl->getXMLPrefix();
	}
	Arabica::XPath::StandardNamespaceContext<std::string>& getNSContext() {
		return _impl->getNSContext();
	}
	std::string getXMLPrefixForNS(const std::string& ns)     {
		return _impl->getXMLPrefixForNS(ns);
	}

	void inline receiveInternal(const Event& event) {
		return _impl->receiveInternal(event);
	}
	void receive(const Event& event, bool toFront = false)   {
		return _impl->receive(event, toFront);
	}

	Event getCurrentEvent() {
		return _impl->getCurrentEvent();
	}

	Arabica::XPath::NodeSet<std::string> getConfiguration()  {
		return _impl->getConfiguration();
	}
	void setConfiguration(const std::vector<std::string>& states) {
		return _impl->setConfiguration(states);
	}
	void setInvokeRequest(const InvokeRequest& req) {
		return _impl->setInvokeRequest(req);
	}

	Arabica::DOM::Node<std::string> getState(const std::string& stateId) {
		return _impl->getState(stateId);
	}
	Arabica::XPath::NodeSet<std::string> getStates(const std::vector<std::string>& stateIds) {
		return _impl->getStates(stateIds);
	}

	Arabica::DOM::Document<std::string>& getDocument()       {
		return _impl->getDocument();
	}

	void setCapabilities(unsigned int capabilities)          {
		return _impl->setCapabilities(capabilities);
	}

	void setName(const std::string& name) {
		return _impl->setName(name);
	}

	const std::string& getName()                             {
		return _impl->getName();
	}
	const std::string& getSessionId()                        {
		return _impl->getSessionId();
	}

	const std::map<std::string, IOProcessor>& getIOProcessors() {
		return _impl->getIOProcessors();
	}

	const std::map<std::string, Invoker>& getInvokers() {
		return _impl->getInvokers();
	}

	bool runOnMainThread(int fps, bool blocking = true) {
		return _impl->runOnMainThread(fps, blocking);
	}

	static bool isMember(const Arabica::DOM::Node<std::string>& node, const Arabica::XPath::NodeSet<std::string>& set) {
		return InterpreterImpl::isMember(node, set);
	}

	void dump() {
		return _impl->dump();
	}
	bool hasLegalConfiguration() {
		return _impl->hasLegalConfiguration();
	}

	static bool isState(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isState(state);
	}
	static bool isPseudoState(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isPseudoState(state);
	}
	static bool isTransitionTarget(const Arabica::DOM::Node<std::string>& elem) {
		return InterpreterImpl::isTransitionTarget(elem);
	}
	static bool isTargetless(const Arabica::DOM::Node<std::string>& transition) {
		return InterpreterImpl::isTargetless(transition);
	}
	static bool isAtomic(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isAtomic(state);
	}
	static bool isFinal(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isFinal(state);
	}
	static bool isHistory(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isHistory(state);
	}
	static bool isParallel(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isParallel(state);
	}
	static bool isCompound(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::isCompound(state);
	}
	static bool isDescendant(const Arabica::DOM::Node<std::string>& s1, const Arabica::DOM::Node<std::string>& s2) {
		return InterpreterImpl::isDescendant(s1, s2);
	}

	static std::vector<std::string> tokenizeIdRefs(const std::string& idRefs) {
		return InterpreterImpl::tokenizeIdRefs(idRefs);
	}

	bool isInitial(const Arabica::DOM::Node<std::string>& state) {
		return _impl->isInitial(state);
	}
	Arabica::XPath::NodeSet<std::string> getInitialStates(Arabica::DOM::Node<std::string> state = Arabica::DOM::Node<std::string>()) {
		return _impl->getInitialStates(state);
	}
	static Arabica::XPath::NodeSet<std::string> getChildStates(const Arabica::DOM::Node<std::string>& state) {
		return InterpreterImpl::getChildStates(state);
	}
	static Arabica::DOM::Node<std::string> getParentState(const Arabica::DOM::Node<std::string>& element) {
		return InterpreterImpl::getParentState(element);
	}
	static Arabica::DOM::Node<std::string> getAncestorElement(const Arabica::DOM::Node<std::string>& node, const std::string tagName) {
		return InterpreterImpl::getAncestorElement(node, tagName);
	}
	Arabica::XPath::NodeSet<std::string> getTargetStates(const Arabica::DOM::Node<std::string>& transition) {
		return _impl->getTargetStates(transition);
	}
	Arabica::DOM::Node<std::string> getSourceState(const Arabica::DOM::Node<std::string>& transition) {
		return _impl->getSourceState(transition);
	}

	static Arabica::XPath::NodeSet<std::string> filterChildElements(const std::string& tagname, const Arabica::DOM::Node<std::string>& node) {
		return InterpreterImpl::filterChildElements(tagname, node);
	}
	static Arabica::XPath::NodeSet<std::string> filterChildElements(const std::string& tagName, const Arabica::XPath::NodeSet<std::string>& nodeSet) {
		return InterpreterImpl::filterChildElements(tagName, nodeSet);
	}
	Arabica::DOM::Node<std::string> findLCCA(const Arabica::XPath::NodeSet<std::string>& states) {
		return _impl->findLCCA(states);
	}
	Arabica::XPath::NodeSet<std::string> getProperAncestors(const Arabica::DOM::Node<std::string>& s1, const Arabica::DOM::Node<std::string>& s2) {
		return _impl->getProperAncestors(s1, s2);
	}
	static const std::string getUUID() {
		return InterpreterImpl::getUUID();
	}

#ifndef SWIG
	boost::shared_ptr<InterpreterImpl> getImpl() {
		return _impl;
	}

	static std::map<std::string, boost::weak_ptr<InterpreterImpl> > getInstances() {
		tthread::lock_guard<tthread::recursive_mutex> lock(_instanceMutex);
		std::map<std::string, boost::weak_ptr<InterpreterImpl> >::iterator instIter = _instances.begin();
		while(instIter != _instances.end()) {
			if (!instIter->second.lock()) {
				_instances.erase(instIter++);
			} else {
				instIter++;
			}
		}
		return _instances;
	}

#endif

protected:
	boost::shared_ptr<InterpreterImpl> _impl;
	static std::map<std::string, boost::weak_ptr<InterpreterImpl> > _instances;
	static tthread::recursive_mutex _instanceMutex;
};

class InterpreterMonitor {
public:
	virtual ~InterpreterMonitor() {}
	virtual void onStableConfiguration(Interpreter interpreter) {}
	virtual void beforeCompletion(Interpreter interpreter) {}
	virtual void afterCompletion(Interpreter interpreter) {}
	virtual void beforeMicroStep(Interpreter interpreter) {}
	virtual void beforeTakingTransitions(Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& transitions) {}
	virtual void beforeEnteringStates(Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& statesToEnter) {}
	virtual void afterEnteringStates(Interpreter interpreter) {}
	virtual void beforeExitingStates(Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& statesToExit) {}
	virtual void afterExitingStates(Interpreter interpreter) {}
};

}

#endif