summaryrefslogtreecommitdiffstats
path: root/src/uscxml/transform/ChartToMinimalSCXML.cpp
blob: ecfa12b239c23d429f6b0d219ea1b89889ea3a6d (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
/**
 *  @file
 *  @author     2012-2014 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "uscxml/transform/ChartToMinimalSCXML.h"
#include "uscxml/transform/FlatStateIdentifier.h"
#include "uscxml/Convenience.h"
#include "uscxml/Factory.h"

#include <DOM/io/Stream.hpp>
#include <glog/logging.h>

#include <iostream>

namespace uscxml {

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

Transformer ChartToMinimalSCXML::transform(const Interpreter& other) {
	return boost::shared_ptr<TransformerImpl>(new ChartToMinimalSCXML(other));
}

ChartToMinimalSCXML::ChartToMinimalSCXML(const Interpreter& other) : TransformerImpl(), _retainAsComments(false), _step(1) {
	cloneFrom(other.getImpl());
	
	// a bit messy but needed for SCXML IO Processor with session id target
	_selfPtr = boost::shared_ptr<InterpreterImpl>(this, Deleter());
	Interpreter::addInstance(_selfPtr);
}

void ChartToMinimalSCXML::writeTo(std::ostream& stream) {

	addMonitor(this);
	
	{
		NodeSet<std::string> allElements = filterChildType(Node_base::ELEMENT_NODE, _scxml, true);
		size_t nrElements = 0;
		for (int i = 0; i < allElements.size(); i++) {
			if (!isInEmbeddedDocument(allElements[i]))
				nrElements++;
		}
		std::cerr << "Number of elements before reduction: " << nrElements + 1 << std::endl;
	}
	
	// test 278 - move embedded datas to topmost datamodel
	if (_binding == EARLY) {
		// move all data elements into topmost datamodel element
		NodeSet<std::string> datas = filterChildElements(_nsInfo.xmlNSPrefix + "data", _scxml, true);

		if (datas.size() > 0) {
			Node<std::string> topMostDatamodel;
			NodeSet<std::string> datamodels = filterChildElements(_nsInfo.xmlNSPrefix + "datamodel", _scxml, false);
			if (datamodels.size() > 0) {
				topMostDatamodel = datamodels[0];
			} else {
				topMostDatamodel = _document.createElementNS(_nsInfo.nsURL, "datamodel");
				_scxml.insertBefore(topMostDatamodel, _scxml.getFirstChild());
			}

			while(topMostDatamodel.hasChildNodes())
				topMostDatamodel.removeChild(topMostDatamodel.getFirstChild());
			
			for (int i = 0; i < datas.size(); i++) {
				if (!isInEmbeddedDocument(datas[i])) {
					topMostDatamodel.appendChild(datas[i]);
				}
			}
		}
	}
	
	char* waitForEnv = getenv("USCXML_MINIMIZE_WAIT_MS");
	_retainAsComments = envVarIsTrue("USCXML_MINIMIZE_RETAIN_AS_COMMENTS");
	
	long waitFor = -1;

	if (waitForEnv != NULL) {
		try {
			waitFor = strTo<long>(waitForEnv);
		} catch (...) {
			waitFor = 0;
		}
	}

	if (envVarIsTrue("USCXML_MINIMIZE_WAIT_FOR_COMPLETION")) {
		interpret();
	} else {
		start();
		if (waitFor < 0) {
			// wait for EOF / CTRL+D
			char c;
			while(true) {
				std::cin >> c;
				if(std::cin.eof())
					break;
			}
		} else {
			tthread::this_thread::sleep_for(tthread::chrono::milliseconds(waitFor));
		}
	}
	stop();
	
	removeUnvisited(_scxml);

	{
		NodeSet<std::string> allElements = filterChildType(Node_base::ELEMENT_NODE, _scxml, true);
		size_t nrElements = 0;
		for (int i = 0; i < allElements.size(); i++) {
			if (!isInEmbeddedDocument(allElements[i]))
				nrElements++;
		}
		std::cerr << "Number of elements after reduction: " << nrElements + 1 << std::endl;
	}

	// unset data model
	_dmCopy = DataModel();

	stream << _scxml;
}

void ChartToMinimalSCXML::removeUnvisited(Arabica::DOM::Node<std::string>& node) {
	if (node.getNodeType() != Node_base::ELEMENT_NODE)
		return;

	Element<std::string> elem(node);

	if (isInEmbeddedDocument(elem) ||
			(TAGNAME(elem) == _nsInfo.xmlNSPrefix + "param") ||
			(TAGNAME(elem) == _nsInfo.xmlNSPrefix + "donedata") ||
			(TAGNAME(elem) == _nsInfo.xmlNSPrefix + "datamodel") ||
			(TAGNAME(elem) == _nsInfo.xmlNSPrefix + "data") ||
			(TAGNAME(elem) == _nsInfo.xmlNSPrefix + "content")) {
		return;
	}

	// special handling for conditional blocks with if
	if (TAGNAME(elem) == _nsInfo.xmlNSPrefix + "if") {
		NodeSet<std::string> ifChilds = filterChildType(Node_base::ELEMENT_NODE, elem, false);
		Element<std::string> lastConditional = elem;
		bool hadVisitedChild = false;
		for (int j = 0; j < ifChilds.size(); j++) {
			Element<std::string> ifChildElem(ifChilds[j]);
			if (TAGNAME(ifChildElem) == _nsInfo.xmlNSPrefix + "else" || TAGNAME(ifChildElem) == _nsInfo.xmlNSPrefix + "elseif") {
				if (!hadVisitedChild && HAS_ATTR(lastConditional, "cond")) {
					lastConditional.setAttribute("cond", "false");
				}
				lastConditional = ifChildElem;
				hadVisitedChild = false;
			}
			if (_visited.find(ifChildElem) != _visited.end()) {
				_visited.insert(lastConditional);
				hadVisitedChild = true;
			}
		}
	}
	
	// test344
	if (_dmCopy &&
			TAGNAME(elem) == _nsInfo.xmlNSPrefix + "transition" &&
			HAS_ATTR(elem, "cond") &&
			!_dmCopy.isValidSyntax(ATTR(elem, "cond")))
		return;
	
	// detach unvisited nodes from DOM
	if (_visited.find(node) == _visited.end()) {
		std::cerr << DOMUtils::xPathForNode(node) << std::endl;
		if (_retainAsComments) {
			std::stringstream oldContent;
			oldContent << node;
			node.getParentNode().replaceChild(_document.createComment(boost::replace_all_copy(oldContent.str(),"--", "-")), node);
		} else {
			// removeChildren is not working as expected
//			node.getParentNode().replaceChild(_document.createTextNode(""), node);
			node.getParentNode().removeChild(node);
		}
		return;
	}

	// iterate and remove unvisited children
	NodeList<std::string> children = node.getChildNodes();
	for (int i = 0; i < children.getLength(); i++) {
		Node<std::string> child(children.item(i));
		removeUnvisited(child);
	}
}
	
void ChartToMinimalSCXML::markAsVisited(const Arabica::DOM::Element<std::string>& element) {
	if (_visited.find(element) != _visited.end())
		return;
	
	Arabica::DOM::Element<std::string> elem = const_cast<Arabica::DOM::Element<std::string>&>(element);
	
	_visited.insert(element);
	Node<std::string> parent = element.getParentNode();
	if (parent && parent.getNodeType() == Node_base::ELEMENT_NODE) {
		Arabica::DOM::Element<std::string> parentElem(parent);
		markAsVisited(parentElem);
	}
}
	
void ChartToMinimalSCXML::beforeExecutingContent(Interpreter interpreter, const Arabica::DOM::Element<std::string>& element) {
	markAsVisited(element);
	StateTransitionMonitor::beforeExecutingContent(interpreter, element);
}

void ChartToMinimalSCXML::beforeUninvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) {
	markAsVisited(invokeElem);
}

void ChartToMinimalSCXML::beforeTakingTransition(Interpreter interpreter, const Arabica::DOM::Element<std::string>& transition, bool moreComing) {
	NodeSet<std::string> targets = getTargetStates(transition);
	// we need this for history pseudo states
	for (int i = 0; i < targets.size(); i++) {
		markAsVisited(Arabica::DOM::Element<std::string>(targets[i]));
	}
	markAsVisited(transition);
	
	std::stringstream commentSS;
	if (HAS_ATTR(transition, "event")) {
		commentSS << " Step #" << _step++ << " - transition taken for event '" << _currEvent.name << "' ";
	} else {
		commentSS << " Step #" << _step++ << " - spontaneous transition taken ";
	}
	if (envVarIsTrue("USCXML_ANNOTATE_PROGRESS"))
		transition.getParentNode().insertBefore(_document.createComment(commentSS.str()), transition);

	StateTransitionMonitor::beforeTakingTransition(interpreter, transition, moreComing);
}

void ChartToMinimalSCXML::beforeEnteringState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) {
	markAsVisited(state);
	
	std::stringstream commentSS;
	commentSS << " Step #" << _step++ << " - state entered ";
	
	Arabica::DOM::Element<std::string> ncState = const_cast<Arabica::DOM::Element<std::string>&>(state);
	if (envVarIsTrue("USCXML_ANNOTATE_PROGRESS"))
		ncState.insertBefore(_document.createComment(commentSS.str()), ncState.getFirstChild());

	StateTransitionMonitor::beforeEnteringState(interpreter, state, moreComing);
}

void ChartToMinimalSCXML::beforeInvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) {
	markAsVisited(invokeElem);
}

void ChartToMinimalSCXML::beforeCompletion(Interpreter interpreter) {
	_dmCopy = _dataModel; // retain a copy;
}

void ChartToMinimalSCXML::executeContent(const Arabica::DOM::Element<std::string>& content, bool rethrow) {
	markAsVisited(content);
	InterpreterRC::executeContent(content, rethrow);
}

void ChartToMinimalSCXML::invoke(const Arabica::DOM::Element<std::string>& element) {
	markAsVisited(element);
	InterpreterRC::invoke(element);
}

void ChartToMinimalSCXML::cancelInvoke(const Arabica::DOM::Element<std::string>& element) {
	markAsVisited(element);
	InterpreterRC::cancelInvoke(element);
}

void ChartToMinimalSCXML::onStableConfiguration(uscxml::Interpreter interpreter) {
}

}