summaryrefslogtreecommitdiffstats
path: root/src/uscxml/interpreter/InterpreterDraft7.cpp
blob: 5f07cfc4c9918b3a5cb454177460e1181dca3ba4 (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
#include "InterpreterDraft7.h"

#include <glog/logging.h>

namespace uscxml {

using namespace Arabica::XPath;
using namespace Arabica::DOM;

/**
procedure interpret(doc):
    if not valid(doc): failWithError()
    expandScxmlSource(doc)
    configuration = new OrderedSet()
    statesToInvoke = new OrderedSet()
    internalQueue = new Queue()
    externalQueue = new BlockingQueue()
    historyValue = new HashTable()
    datamodel = new Datamodel(doc)
    if doc.binding == "early":
        initializeDatamodel(datamodel, doc)
    running = true
    executeGlobalScriptElement(doc)
    enterStates([doc.initial.transition])
    mainEventLoop()
 */
void InterpreterDraft7::interpret() {
	if (!_isInitialized)
		init();

	if (!_scxml)
		return;

	_sessionId = getUUID();

	std::string datamodelName;
	if (datamodelName.length() == 0 && HAS_ATTR(_scxml, "datamodel"))
		datamodelName = ATTR(_scxml, "datamodel");
	if (datamodelName.length() == 0 && HAS_ATTR(_scxml, "profile")) // SCION SCXML uses profile to specify datamodel
		datamodelName = ATTR(_scxml, "profile");
	if(datamodelName.length() > 0)
		_dataModel = Factory::createDataModel(datamodelName, this);
	if(datamodelName.length() > 0  && !_dataModel) {
		LOG(ERROR) << "No datamodel for " << datamodelName << " registered";
	}

	if (_dataModel) {
		_dataModel.assign("_x.args", _cmdLineOptions);
		if (_httpServlet) {
			Data data;
			data.compound["location"] = Data(_httpServlet->getURL(), Data::VERBATIM);
			_dataModel.assign("_ioprocessors['http']", data);
		}
	}

	setupIOProcessors();

	_running = true;
	_binding = (HAS_ATTR(_scxml, "binding") && boost::iequals(ATTR(_scxml, "binding"), "late") ? LATE : EARLY);

	// @TODO: Reread http://www.w3.org/TR/scxml/#DataBinding

	if (_dataModel && _binding == EARLY) {
		// initialize all data elements
		NodeSet<std::string> dataElems = _xpath.evaluate("//" + _xpathPrefix + "data", _document).asNodeSet();
		for (unsigned int i = 0; i < dataElems.size(); i++) {
			initializeData(dataElems[i]);
		}
	} else if(_dataModel) {
		// initialize current data elements
		NodeSet<std::string> topDataElems = filterChildElements(_xmlNSPrefix + "data", filterChildElements(_xmlNSPrefix + "datamodel", _scxml));
		for (unsigned int i = 0; i < topDataElems.size(); i++) {
			initializeData(topDataElems[i]);
		}
	}

	// executeGlobalScriptElements
	NodeSet<std::string> globalScriptElems = _xpath.evaluate("/" + _xpathPrefix + "scxml/" + _xpathPrefix + "script", _document).asNodeSet();
	for (unsigned int i = 0; i < globalScriptElems.size(); i++) {
		if (_dataModel)
			executeContent(globalScriptElems[i]);
	}

	// initial transition might be implict
	NodeSet<std::string> initialTransitions = _xpath.evaluate("/" + _xpathPrefix + "scxml/" + _xpathPrefix + "initial/" + _xpathPrefix + "transition", _document).asNodeSet();
	if (initialTransitions.size() == 0) {
		Arabica::XPath::NodeSet<std::string> initialStates = getInitialStates();

		for (int i = 0; i < initialStates.size(); i++) {
			Arabica::DOM::Element<std::string> initialElem = _document.createElementNS(_nsURL, "initial");
			initialElem.setAttribute("generated", "true");
			Arabica::DOM::Element<std::string> transitionElem = _document.createElementNS(_nsURL, "transition");
			transitionElem.setAttribute("target", ATTR(initialStates[i], "id"));
			initialElem.appendChild(transitionElem);
			_scxml.appendChild(initialElem);
			initialTransitions.push_back(transitionElem);
		}
	}
	enterStates(initialTransitions);

	//  assert(hasLegalConfiguration());
	mainEventLoop();

	if (_parentQueue) {
		// send one final event to unblock eventual listeners
		Event quit;
		quit.name = "done.state.scxml";
		_parentQueue->push(quit);
	}

	// set datamodel to null from this thread
	if(_dataModel)
		_dataModel = DataModel();

}

/**
 * Called with a single data element from the topmost datamodel element.
 */
void InterpreterDraft7::initializeData(const Arabica::DOM::Node<std::string>& data) {
	if (!_dataModel) {
		LOG(ERROR) << "Cannot initialize data when no datamodel is given!";
		return;
	}
	try {
		if (!HAS_ATTR(data, "id")) {
			LOG(ERROR) << "Data element has no id!";
			return;
		}

		if (HAS_ATTR(data, "expr")) {
			std::string value = ATTR(data, "expr");
			_dataModel.assign(ATTR(data, "id"), value);
		} else if (HAS_ATTR(data, "src")) {
			URL srcURL(ATTR(data, "src"));
			if (!srcURL.isAbsolute())
				toAbsoluteURI(srcURL);

			std::stringstream ss;
			if (_cachedURLs.find(srcURL.asString()) != _cachedURLs.end()) {
				ss << _cachedURLs[srcURL.asString()];
			} else {
				ss << srcURL;
				_cachedURLs[srcURL.asString()] = srcURL;
			}
			_dataModel.assign(ATTR(data, "id"), ss.str());

		} else if (data.hasChildNodes()) {
			// search for the text node with the actual script
			NodeList<std::string> dataChilds = data.getChildNodes();
			for (int i = 0; i < dataChilds.getLength(); i++) {
				if (dataChilds.item(i).getNodeType() == Node_base::TEXT_NODE) {
					Data value = Data(dataChilds.item(i).getNodeValue());
					_dataModel.assign(ATTR(data, "id"), value);
					break;
				}
			}
		}

	} catch (Event e) {
		LOG(ERROR) << "Syntax error in data element:" << std::endl << e << std::endl;
	}
}

/**
procedure mainEventLoop():
    while running:
        enabledTransitions = null
        macrostepDone = false
        # Here we handle eventless transitions and transitions
        # triggered by internal events until macrostep is complete
        while running and not macrostepDone:
            enabledTransitions = selectEventlessTransitions()
            if enabledTransitions.isEmpty():
                if internalQueue.isEmpty():
                    macrostepDone = true
                else:
                    internalEvent = internalQueue.dequeue()
                    datamodel["_event"] = internalEvent
                    enabledTransitions = selectTransitions(internalEvent)
            if not enabledTransitions.isEmpty():
                microstep(enabledTransitions.toList())
        # either we're in a final state, and we break out of the loop
        if not running:
            break;
        # or we've completed a macrostep, so we start a new macrostep by waiting for an external event
        # Here we invoke whatever needs to be invoked. The implementation of 'invoke' is platform-specific
        for state in statesToInvoke:
            for inv in state.invoke:
                invoke(inv)
        statesToInvoke.clear()
        # Invoking may have raised internal error events and we iterate to handle them
        if not internalQueue.isEmpty():
            continue
       # A blocking wait for an external event.  Alternatively, if we have been invoked
       # our parent session also might cancel us.  The mechanism for this is platform specific,
       # but here we assume it’s a special event we receive
       externalEvent = externalQueue.dequeue()
       if isCancelEvent(externalEvent):
           running = false
           continue
       datamodel["_event"] = externalEvent
       for state in configuration:
           for inv in state.invoke:
              if inv.invokeid == externalEvent.invokeid:
                  applyFinalize(inv, externalEvent)
              if inv.autoforward:
                  send(inv.id, externalEvent)
       enabledTransitions = selectTransitions(externalEvent)
       if not enabledTransitions.isEmpty():
           microstep(enabledTransitions.toList())
    # End of outer while running loop.  If we get here, we have reached a top-level final state or have been cancelled
    exitInterpreter()
 */
void InterpreterDraft7::mainEventLoop() {
}

/**
procedure exitInterpreter():
    statesToExit = configuration.toList().sort(exitOrder)
    for s in statesToExit:
        for content in s.onexit:
            executeContent(content)
        for inv in s.invoke:
            cancelInvoke(inv)
        configuration.delete(s)
        if isFinalState(s) and isScxmlState(s.parent):
            returnDoneEvent(s.donedata)
 */
void InterpreterDraft7::exitInterpreter() {
}

/**
procedure microstep(enabledTransitions):
    exitStates(enabledTransitions)
    executeTransitionContent(enabledTransitions)
    enterStates(enabledTransitions)
 */
void InterpreterDraft7::microstep(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) {
}

/**
function selectEventlessTransitions():
    enabledTransitions = new OrderedSet()
    atomicStates = configuration.toList().filter(isAtomicState).sort(documentOrder)
    for state in atomicStates:
        loop: for s in [state].append(getProperAncestors(state, null)):
            for t in s.transition:
                if not t.event and conditionMatch(t):
                    enabledTransitions.add(t)
                    break loop
    enabledTransitions = filterPreempted(enabledTransitions)
    return enabledTransitions
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::selectEventlessTransitions() {
	return Arabica::XPath::NodeSet<std::string>();
}

/**
function selectTransitions(event):
    enabledTransitions = new OrderedSet()
    atomicStates = configuration.toList().filter(isAtomicState).sort(documentOrder)
    for state in atomicStates:
        loop: for s in [state].append(getProperAncestors(state, null)):
            for t in s.transition:
                if t.event and nameMatch(t.event, event.name) and conditionMatch(t):
                    enabledTransitions.add(t)
                    break loop
    enabledTransitions = removeConflictingTransitions(enabledTransitions)
    return enabledTransitions
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::selectTransitions(const std::string& event) {
	return Arabica::XPath::NodeSet<std::string>();
}

/**
procedure enterStates(enabledTransitions):
    statesToEnter = new OrderedSet()
    statesForDefaultEntry = new OrderedSet()
    computeEntrySet(enabledTransitions, statesToEnter, statesForDefaultEntry)
    for s in statesToEnter.toList().sort(entryOrder):
        configuration.add(s)
        statesToInvoke.add(s)
        if binding == "late" and s.isFirstEntry:
            initializeDataModel(datamodel.s,doc.s)
            s.isFirstEntry = false
        for content in s.onentry:
            executeContent(content)
        if statesForDefaultEntry.isMember(s):
            executeContent(s.initial.transition)
        if isFinalState(s):
            if isSCXMLElement(s.parent):
                running = false
            else:
                parent = s.parent
                grandparent = parent.parent
                internalQueue.enqueue(new Event("done.state." + parent.id, s.donedata))
                if isParallelState(grandparent):
                    if getChildStates(grandparent).every(isInFinalState):
                        internalQueue.enqueue(new Event("done.state." + grandparent.id))
 */
void InterpreterDraft7::enterStates(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) {
}

/**
procedure exitStates(enabledTransitions):
   statesToExit = computeExitSet(enabledTransitions)
   for s in statesToExit:
       statesToInvoke.delete(s)
   statesToExit = statesToExit.toList().sort(exitOrder)
   for s in statesToExit:
       for h in s.history:
           if h.type == "deep":
               f = lambda s0: isAtomicState(s0) and isDescendant(s0,s)
           else:
               f = lambda s0: s0.parent == s
            historyValue[h.id] = configuration.toList().filter(f)
   for s in statesToExit:
       for content in s.onexit:
           executeContent(content)
       for inv in s.invoke:
           cancelInvoke(inv)
       configuration.delete(s)
 */
void InterpreterDraft7::exitStates(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) {
}

/**
function computeExitSet(transitions)
   statesToExit = new OrderedSet
         for t in transitions:
             domain = getTransitionDomain(t)
       for s in configuration:
           if isDescendant(s,domain):
               statesToExit.add(s)
   return statesToExit
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::computeExitSet(const Arabica::XPath::NodeSet<std::string>& enabledTransitions,
        const Arabica::XPath::NodeSet<std::string>& statesToExit) {
	return Arabica::XPath::NodeSet<std::string>();
}

/**
 procedure computeEntrySet(transitions, statesToEnter, statesForDefaultEntry)
    for t in transitions:
         statesToEnter.union(getTargetStates(t.target))
     for s in statesToEnter:
         addDescendentStatesToEnter(s,statesToEnter,statesForDefaultEntry)
     for t in transitions:
         ancestor = getTransitionDomain(t)
         for s in getTargetStates(t.target)):
             addAncestorStatesToEnter(s, ancestor, statesToEnter, statesForDefaultEntry)
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::computeEntrySet(const Arabica::XPath::NodeSet<std::string>& transitions,
        const Arabica::XPath::NodeSet<std::string>& statesToEnter,
        const Arabica::XPath::NodeSet<std::string>& statesForDefaultEntry) {
	return Arabica::XPath::NodeSet<std::string>();
}

/**
function removeConflictingTransitions(enabledTransitions):
    filteredTransitions = new OrderedSet()
 // toList sorts the transitions in the order of the states that selected them
    for t1 in enabledTransitions.toList():
        t1Preempted = false;
        transitionsToRemove = new OrderedSet()
        for t2 in filteredTransitions.toList():
            if computeExitSet(t1).hasIntersection(computeExitSet(t2)):
                if isDescendent(t1.source, t2.source):
                    transitionsToRemove.add(t2)
                else:
                    t1Preempted = true
                    break
        if not t1Preempted:
            for t3 in transitionsToRemove.toList():
                filteredTransitions.delete(t3)
            filteredTransitions.add(t1)

    return filteredTransitions
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::removeConflictingTransitions(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) {
	return Arabica::XPath::NodeSet<std::string>();
}

/**
 function getTransitionDomain(t)
   tstates = getTargetStates(t.target)
   if not tstates
       return t.source
         elif t.type == "internal" and isCompoundState(t.source) and tstates.every(lambda s: isDescendant(s,t.source)):
       return t.source
   else:
       return findLCCA([t.source].append(tstates))
 */
Arabica::DOM::Node<std::string> InterpreterDraft7::getTransitionDomain(const Arabica::DOM::Node<std::string>& transition) {
	return Arabica::DOM::Node<std::string>();
}

/**
 procedure addDescendentStatesToEnter(state,statesToEnter,statesForDefaultEntry):
     if isHistoryState(state):
         if historyValue[state.id]:
             for s in historyValue[state.id]:
                 addDescendentStatesToEnter(s,statesToEnter,statesForDefaultEntry)
                 addAncestorStatesToEnter(s, state.parent, statesToEnter, statesForDefaultEntry)
         else:
             for t in state.transition:
                 for s in getTargetStates(t.target):
                     addDescendentStatesToEnter(s,statesToEnter,statesForDefaultEntry)
                     addAncestorStatesToEnter(s, state.parent, statesToEnter, statesForDefaultEntry)
     else:
         statesToEnter.add(state)
         if isCompoundState(state):
             statesForDefaultEntry.add(state)
             for s in getTargetStates(state.initial):
                 addDescendentStatesToEnter(s,statesToEnter,statesForDefaultEntry)
                 addAncestorStatesToEnter(s, state, statesToEnter, statesForDefaultEntry)
         else:
             if isParallelState(state):
                 for child in getChildStates(state):
                     if not statesToEnter.some(lambda s: isDescendant(s,child)):
                         addDescendentStatesToEnter(child,statesToEnter,statesForDefaultEntry)
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::addDescendentStatesToEnter(const Arabica::DOM::Node<std::string>& state,
        const Arabica::XPath::NodeSet<std::string>& statesToEnter,
        const Arabica::XPath::NodeSet<std::string>& statesForDefaultEntry) {
	return Arabica::XPath::NodeSet<std::string>();
}

/**
 procedure addAncestorsToEnter(state, ancestor, statesToEnter, statesForDefaultEntry)
    for anc in getProperAncestors(state,ancestor):
        statesToEnter.add(anc)
        if isParallelState(anc):
            for child in getChildStates(anc):
                if not statesToEnter.some(lambda s: isDescendant(s,child)):
                    addStatesToEnter(child,statesToEnter,statesForDefaultEntry)
 */
Arabica::XPath::NodeSet<std::string> InterpreterDraft7::addAncestorsStatesToEnter(const Arabica::DOM::Node<std::string>& state,
        const Arabica::DOM::Node<std::string>& ancestor,
        const Arabica::XPath::NodeSet<std::string>& statesToEnter,
        const Arabica::XPath::NodeSet<std::string>& statesForDefaultEntry) {
	return Arabica::XPath::NodeSet<std::string>();
}

}