diff options
author | Stefan Radomski <github@mintwerk.de> | 2016-05-12 13:12:33 (GMT) |
---|---|---|
committer | Stefan Radomski <github@mintwerk.de> | 2016-05-12 13:12:33 (GMT) |
commit | b62e7979600feee23dc7cdb61042a8fc7673122b (patch) | |
tree | f7351372f37979dd2d048e0b68a16a4cd3b2aadb /test/src | |
parent | 1b11b310be61e51b3ac5ebb83f7c8a33aef3d6e8 (diff) | |
download | uscxml-b62e7979600feee23dc7cdb61042a8fc7673122b.zip uscxml-b62e7979600feee23dc7cdb61042a8fc7673122b.tar.gz uscxml-b62e7979600feee23dc7cdb61042a8fc7673122b.tar.bz2 |
Major Refactoring v2.0
Diffstat (limited to 'test/src')
38 files changed, 997 insertions, 6596 deletions
diff --git a/test/src/issues/test-issue56.cpp b/test/src/issues/test-issue56.cpp deleted file mode 100644 index 0330512..0000000 --- a/test/src/issues/test-issue56.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "uscxml/Interpreter.h" - -using namespace uscxml; - -// -- Issue 56 on github -int main(int argc, char** argv) { - std::deque<std::string> messageQueue; - messageQueue.push_back("a"); - messageQueue.push_back("b"); - messageQueue.push_back("c"); - messageQueue.push_back("d"); - - const char* scxmlContent = - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\" initial=\"initial_state\">" - " <state id=\"initial_state\">" - " <transition event=\"a\" target=\"parallel_state\"/>" - " </state>" - " <parallel id=\"parallel_state\">" - " <transition event=\"done.state.parallel_state\" target=\"join_state\"/>" - " <state id=\"p1out\" initial=\"p1\">" - " <state id=\"p1\">" - " <transition event=\"b\" target=\"p11\"/>" - " </state>" - " <final id=\"p11\"/>" - " </state>" - " <state id=\"p2out\" initial=\"p2\">" - " <state id=\"p2\">" - " <transition event=\"c\" target=\"p21\"/>" - " </state>" - " <final id=\"p21\"/>" - " </state>" - " </parallel>" - " <state id=\"join_state\">" - " <transition event=\"d\" target=\"final_state\"/>" - " </state>" - " <final id=\"final_state\"/>" - "</scxml>"; - - std::string msg; - - uscxml::Interpreter scxml = uscxml::Interpreter::fromXML(scxmlContent, ""); - scxml.addMonitor(new StateTransitionMonitor()); - - uscxml::InterpreterState state; - // assume initial stable configuration - do { - state = scxml.step(); - } while(state > 0); - - while(state != uscxml::USCXML_FINISHED && !messageQueue.empty()) { - msg = messageQueue.front(); - messageQueue.pop_front(); - - scxml.receive(uscxml::Event(msg, uscxml::Event::EXTERNAL)); - - // step to next stable configuration - do { - state = scxml.step(); - } while(state > 0); - - } - - return EXIT_SUCCESS; - -}
\ No newline at end of file diff --git a/test/src/issues/test-issue62.cpp b/test/src/issues/test-issue62.cpp deleted file mode 100644 index db44dad..0000000 --- a/test/src/issues/test-issue62.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "uscxml/Interpreter.h" -#include "glog/logging.h" - -using namespace uscxml; - -int main(int argc, char** argv) { - google::LogToStderr(); - google::InitGoogleLogging(argv[0]); - - const char* scxmlContent = - "<scxml datamodel=\"lua\" initial=\"init\" name=\"scxml_root\" version=\"1.0\" xmlns=\"http://www.w3.org/2005/07/scxml\"> " - " <state id=\"init\"> " - " <transition target=\"InvokeParent\"/> " - " </state> " - " <final id=\"FinalShape1\"/> " - " <state id=\"InvokeParent\"> " - " <invoke autoforward=\"true\" id=\"test_invoke\" type=\"scxml\"> " - " <content> " - " <scxml datamodel=\"lua\" initial=\"On\" name=\"ScxmlShape1\" version=\"1.0\" xmlns=\"http://www.w3.org/2005/07/scxml\"> " - " <state id=\"On\"> " - " <onentry> " - " <script>print('TEST LOGGING FROM INVOKE SOURCE')</script> " - " </onentry> " - " <transition target=\"Off\"/> " - " </state> " - " <state id=\"Off\"> " - " <transition event=\"inside_invoke\" target=\"End\"/> " - " </state> " - " <final id=\"End\"/> " - " </scxml> " - " </content> " - " </invoke> " - " <transition event=\"done.invoke.test_invoke\" target=\"FinalShape1\"/> " - " <transition event=\"move_here\" target=\"StateXXX\"/> " - " </state> " - " <state id=\"StateXXX\"> " - " <transition target=\"FinalShape1\"/> " - " </state> " - "</scxml> "; - - std::string msg; - - uscxml::Interpreter scxml = uscxml::Interpreter(uscxml::Interpreter::fromXML(scxmlContent, "")); - std::list<InterpreterIssue> issues = scxml.validate(); - for (std::list<InterpreterIssue>::iterator issueIter = issues.begin(); issueIter != issues.end(); issueIter++) { - std::cout << *issueIter; - } - - scxml.addMonitor(new StateTransitionMonitor()); - - uscxml::InterpreterState state; - - // assume initial stable configuration - do { - state = scxml.step(); - } while(state > 0); - - scxml.receive(Event("move_here")); - scxml.receive(Event("inside_invoke")); - - while(state != uscxml::USCXML_FINISHED) { - do { - state = scxml.step(true); - } while(state > 0); - } - - std::cout << "************************************" << std::endl; - std::cout << "Successfully finished state machine!" << std::endl; - - return EXIT_SUCCESS; - -}
\ No newline at end of file diff --git a/test/src/issues/test-issue63.cpp b/test/src/issues/test-issue63.cpp deleted file mode 100644 index 5cedcad..0000000 --- a/test/src/issues/test-issue63.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include "uscxml/Interpreter.h" - -#include "glog/logging.h" - -using namespace uscxml; - -int main(int argc, char** argv) { - google::LogToStderr(); - google::InitGoogleLogging(argv[0]); - - const char* scxmlContent = - "<scxml datamodel=\"lua\" initial=\"init\" name=\"scxml_root\" version=\"1.0\" xmlns=\"http://www.w3.org/2005/07/scxml\">" - " <state id=\"init\"> " - " <onentry> <script> print('Hello, World!') </script> </onentry> " - " <onentry> <script> print(\"Hello, World!\") </script> </onentry> " - " <onentry> <script> print('Hello, "World"') </script> </onentry> " - " <onentry> <script><![CDATA[ print('Hello, \"World\"') ]]></script> </onentry> " - " <onentry> <script> print("Hello, world!") </script> </onentry> " - " <transition target=\"FinalShape1\"/> " - " <transition cond=\"_event.data=="string value"\" event=\"test\" target=\"FinalShape1\"/> " - " </state> " - " <final id=\"FinalShape1\"/> " - "</scxml> "; - - std::string msg; - - uscxml::Interpreter scxml = uscxml::Interpreter(uscxml::Interpreter::fromXML(scxmlContent, "")); - - std::list<InterpreterIssue> issues = scxml.validate(); - for (std::list<InterpreterIssue>::iterator issueIter = issues.begin(); issueIter != issues.end(); issueIter++) { - std::cout << *issueIter << std::endl; - } - - scxml.addMonitor(new StateTransitionMonitor()); - - uscxml::InterpreterState state; - - do { - - state = scxml.step(); - } while(state != uscxml::USCXML_FINISHED && state != uscxml::USCXML_DESTROYED); - - std::cout << "************************************" << std::endl; - std::cout << "Successfully finished state machine!" << std::endl; - - return EXIT_SUCCESS; - -}
\ No newline at end of file diff --git a/test/src/issues/test-issue64.scxml b/test/src/issues/test-issue64.scxml deleted file mode 100644 index 0969b5f..0000000 --- a/test/src/issues/test-issue64.scxml +++ /dev/null @@ -1,16 +0,0 @@ -<scxml datamodel="lua" initial="start" name="root" version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> - <final id="end"/> - <state id="start"> - <invoke id="test_invoke" type="scxml"> - <content> - <scxml datamodel="lua" name="scxml_invoke" version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> - <state id="start"> - <transition target="end"/> - </state> - <final id="end"/> - </scxml> - </content> - </invoke> - <transition event="done.invoke.test_invoke" target="end"/> - </state> -</scxml> diff --git a/test/src/issues/test-issue67.scxml b/test/src/issues/test-issue67.scxml deleted file mode 100644 index e1fc5fa..0000000 --- a/test/src/issues/test-issue67.scxml +++ /dev/null @@ -1,36 +0,0 @@ -<scxml datamodel="lua" initial="main" name="root" version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> - <datamodel> - <data expr="1" id="i_GLOBAL_VAR"/> - </datamodel> - <state id="main" initial="start"> - <transition event="error.*" target="Fail"/> - <transition cond="i_GLOBAL_VAR==2" event="completed" target="Pass"/> - <transition event="completed" target="Fail"/> - <state id="start"> - <invoke id="test_invoke" namelist="i_GLOBAL_VAR" type="scxml"> - <content> - <scxml datamodel="lua" initial="InvokeStart" name="scxml_invoke" version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> - <datamodel> - <data expr="0" id="i_GLOBAL_VAR"/> - </datamodel> - <final id="InvokeEnd"> - <onentry> - <send event="completed" namelist="i_GLOBAL_VAR" target="#_parent"/> - </onentry> - </final> - <state id="InvokeStart"> - <onentry> - <assign expr="i_GLOBAL_VAR*2" location="i_GLOBAL_VAR"/> - <log expr="i_GLOBAL_VAR" label="INVOKE-i_GLOBAL_VAR"/> - </onentry> - <transition target="InvokeEnd"/> - </state> - </scxml> - </content> - <finalize/> - </invoke> - </state> - </state> - <final id="Fail"/> - <final id="Pass"/> -</scxml> diff --git a/test/src/issues/test-issue68.scxml b/test/src/issues/test-issue68.scxml deleted file mode 100644 index cd99bc0..0000000 --- a/test/src/issues/test-issue68.scxml +++ /dev/null @@ -1,29 +0,0 @@ -<scxml datamodel="lua" initial="work" name="root" version="1.0" xmlns="http://www.w3.org/2005/07/scxml"> - <datamodel> - <data expr="0" id="testvar1"/> - </datamodel> - <state id="work" initial="act1"> - <transition event="OnTimer" target="fail"/> - <transition cond="testvar1>3" target="pass"/> - <state id="act1"> - <onentry> - <send delay="3000ms" event="OnTimer" id="ID_OnTimer"/> - <send delay="300ms" event="OnDone"/> - <assign expr="testvar1 + 1" location="testvar1"/> - <log expr="testvar1" /> - </onentry> - <onexit> - <cancel sendid="ID_OnTimer"/> - </onexit> - <transition event="OnDone" target="act2"/> - </state> - <state id="act2"> - <onentry> - <send delay="1000ms" event="Back"/> - </onentry> - <transition event="Back" target="act1"/> - </state> - </state> - <final id="fail"/> - <final id="pass"/> -</scxml> diff --git a/test/src/test-arabica-events.cpp b/test/src/test-arabica-events.cpp deleted file mode 100644 index bcec093..0000000 --- a/test/src/test-arabica-events.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include <iostream> - -#include "uscxml/config.h" -#include "uscxml/Common.h" -#include <DOM/Document.hpp> -#include <XPath/XPath.hpp> -#include <DOM/SAX2DOM/SAX2DOM.hpp> -#include <SAX/helpers/CatchErrorHandler.hpp> -#include <DOM/Events/EventTarget.hpp> -#include <DOM/Events/EventListener.hpp> - -using namespace Arabica::DOM; - -class CapturingEventListener : public Events::EventListener<std::string> { -public: - void handleEvent(Events::Event<std::string>& event) { - std::cout << "Handling captured event " << event.getType() << std::endl; - } -}; - -class BubblingEventListener : public Events::EventListener<std::string> { -public: - void handleEvent(Events::Event<std::string>& event) { - std::cout << "Handling bubbling event " << event.getType() << std::endl; - } -}; - -int main(int argc, char** argv) { - if (argc != 2) { - std::cerr << "Expected path to test-arabica-events.xml" << std::endl; - exit(EXIT_FAILURE); - } - - Arabica::SAX::InputSource<std::string> inputSource(argv[1]); - - Arabica::SAX2DOM::Parser<std::string> domParser; - Arabica::SAX::CatchErrorHandler<std::string> errorHandler; - domParser.setErrorHandler(errorHandler); - if(!domParser.parse(inputSource)) { - return -1; - } - Document<std::string> doc = domParser.getDocument(); - Element<std::string> elem = doc.getDocumentElement(); - - CapturingEventListener cel; - BubblingEventListener bel; - - Events::EventTarget<std::string> eventTarget(elem); - eventTarget.addEventListener("DOMNodeInserted", cel, true); - eventTarget.addEventListener("DOMNodeInserted", bel, false); - eventTarget.addEventListener("DOMNodeRemoved", cel, true); - eventTarget.addEventListener("DOMNodeRemoved", bel, false); - eventTarget.addEventListener("DOMAttrModified", cel, true); - eventTarget.addEventListener("DOMAttrModified", bel, false); - - Arabica::XPath::XPath<std::string> xpath; - Arabica::XPath::NodeSet<std::string> divs = xpath.evaluate("//div", doc).asNodeSet(); - - for (size_t i = 0; i < divs.size(); i++) { - Element<std::string> divElem = Element<std::string>(divs[i]); - divElem.setAttribute("foo", "true"); - divElem.setAttribute("foo", "false"); - - Element<std::string> fooElem = divElem.getOwnerDocument().createElement("foo"); - divElem.appendChild(fooElem); - divElem.removeChild(fooElem); - } - - -}
\ No newline at end of file diff --git a/test/src/test-arabica-namespaces.cpp b/test/src/test-arabica-namespaces.cpp deleted file mode 100644 index 5d5d90d..0000000 --- a/test/src/test-arabica-namespaces.cpp +++ /dev/null @@ -1,215 +0,0 @@ -#include <iostream> - -#include "uscxml/config.h" -#include "uscxml/Common.h" -#include <DOM/Document.hpp> -#include <XPath/XPath.hpp> -#include <DOM/SAX2DOM/SAX2DOM.hpp> -#include <DOM/io/Stream.hpp> -#include "uscxml/Interpreter.h" -#include "uscxml/dom/DOMUtils.h" -#include "uscxml/dom/NameSpacingParser.h" - -using namespace Arabica::DOM; -using namespace Arabica::XPath; -using namespace uscxml; - -#define VALIDATE \ -std::pair<Document<std::string>, NameSpaceInfo> parsed = parse(xmlSS.str());\ -Document<std::string> origDoc = parsed.first;\ -NameSpaceInfo origNS = parsed.second;\ -validateRootFoo(parsed);\ -insertBar(parsed);\ -std::cout << parsed.first << std::endl;\ -validateRootFooBar(parsed);\ -parsed = cloneDocument(parsed);\ -insertBaz(parsed);\ -std::cout << parsed.first << std::endl;\ -validateRootFooBarBaz(parsed);\ -assert(DOMUtils::filterChildElements(origNS.xmlNSPrefix + "bar", origDoc.getDocumentElement()).size() == 3);\ -assert(DOMUtils::filterChildElements(origNS.xmlNSPrefix + "baz", origDoc.getDocumentElement()).size() == 0); - - -/** - Test DOM manipulations and document cloning with different namespace scenarios - */ - -static Arabica::XPath::XPath<std::string> _xpath; - -std::pair<Document<std::string>, NameSpaceInfo> parse(const std::string xmlString) { - NameSpacingParser parser = NameSpacingParser::fromXML(xmlString); - if (parser.errorsReported()) - assert(false); - return std::make_pair(parser.getDocument(), parser.nameSpace); -} - -std::pair<Document<std::string>, NameSpaceInfo> cloneDocument(std::pair<Document<std::string>, NameSpaceInfo>& parsed) { - - NameSpaceInfo nsInfo = parsed.second; - Document<std::string> document = parsed.first; - - Document<std::string> clonedDocument; - DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation(); - clonedDocument = domFactory.createDocument(document.getNamespaceURI(), "", 0); - - Node<std::string> child = document.getFirstChild(); - while (child) { - Node<std::string> newNode = clonedDocument.importNode(child, true); - clonedDocument.appendChild(newNode); - child = child.getNextSibling(); - } - - return std::make_pair(clonedDocument, nsInfo); -} - -void insertBar(std::pair<Document<std::string>, NameSpaceInfo>& parsed) { - NameSpaceInfo nsInfo = parsed.second; - Document<std::string> document = parsed.first; - - Node<std::string> root = document.getDocumentElement(); - for (size_t i = 0; i < 3; i++) { - Element<std::string> bar = document.createElementNS(nsInfo.nsURL, "bar"); -// if (nsInfo.nsToPrefix.find(nsInfo.nsURL) != nsInfo.nsToPrefix.end()) - nsInfo.setPrefix(bar); - root.appendChild(bar); - } -} - -void insertBaz(std::pair<Document<std::string>, NameSpaceInfo>& parsed) { - NameSpaceInfo nsInfo = parsed.second; - Document<std::string> document = parsed.first; - - Node<std::string> root = document.getDocumentElement(); - for (size_t i = 0; i < 3; i++) { - Element<std::string> baz = document.createElementNS(nsInfo.nsURL, "baz"); - nsInfo.setPrefix(baz); - root.appendChild(baz); - } -} - -static void validateRootFoo(std::pair<Document<std::string>, NameSpaceInfo>& parsed) { - - NameSpaceInfo nsInfo = parsed.second; - Document<std::string> document = parsed.first; - - Node<std::string> root = document.getDocumentElement(); - _xpath.setNamespaceContext(*nsInfo.getNSContext()); - - assert(TAGNAME_CAST(root) == nsInfo.xmlNSPrefix + "root"); - assert(LOCALNAME_CAST(root) == "root"); - NodeSet<std::string> foosFiltered = DOMUtils::filterChildElements(nsInfo.xmlNSPrefix + "foo", root); - assert(foosFiltered.size() == 3); - NodeSet<std::string> foosXPath = _xpath.evaluate("//" + nsInfo.xpathPrefix + "foo", root).asNodeSet(); - assert(foosXPath.size() == 3); - - for (size_t i = 0; i < 3; i++) { - assert(foosFiltered[i] == foosXPath[i]); - assert(TAGNAME_CAST(foosFiltered[i]) == nsInfo.xmlNSPrefix + "foo"); - assert(LOCALNAME_CAST(foosFiltered[i]) == "foo"); - } - -} - -static void validateRootFooBar(std::pair<Document<std::string>, NameSpaceInfo>& parsed) { - validateRootFoo(parsed); - - NameSpaceInfo nsInfo = parsed.second; - Document<std::string> document = parsed.first; - - Node<std::string> root = document.getDocumentElement(); - _xpath.setNamespaceContext(*nsInfo.getNSContext()); - - NodeSet<std::string> barsFiltered = DOMUtils::filterChildElements(nsInfo.xmlNSPrefix + "bar", root); - assert(barsFiltered.size() == 3); - NodeSet<std::string> barsXPath = _xpath.evaluate("//" + nsInfo.xpathPrefix + "bar", root).asNodeSet(); - assert(barsXPath.size() == 3); - - for (size_t i = 0; i < 3; i++) { - assert(barsFiltered[i] == barsXPath[i]); - assert(TAGNAME_CAST(barsFiltered[i]) == nsInfo.xmlNSPrefix + "bar"); - assert(LOCALNAME_CAST(barsFiltered[i]) == "bar"); - } - -} - -static void validateRootFooBarBaz(std::pair<Document<std::string>, NameSpaceInfo>& parsed) { - validateRootFooBar(parsed); - - NameSpaceInfo nsInfo = parsed.second; - Document<std::string> document = parsed.first; - - Node<std::string> root = document.getDocumentElement(); - _xpath.setNamespaceContext(*nsInfo.getNSContext()); - - assert(TAGNAME_CAST(root) == nsInfo.xmlNSPrefix + "root"); - assert(LOCALNAME_CAST(root) == "root"); - - NodeSet<std::string> bazsFiltered = DOMUtils::filterChildElements(nsInfo.xmlNSPrefix + "baz", root); - assert(bazsFiltered.size() == 3); - NodeSet<std::string> bazsXPath = _xpath.evaluate("//" + nsInfo.xpathPrefix + "baz", root).asNodeSet(); - assert(bazsXPath.size() == 3); - - for (size_t i = 0; i < 3; i++) { - assert(bazsFiltered[i] == bazsXPath[i]); - assert(TAGNAME_CAST(bazsFiltered[i]) == nsInfo.xmlNSPrefix + "baz"); - assert(LOCALNAME_CAST(bazsFiltered[i]) == "baz"); - } - -} - -int main(int argc, char** argv) { - - // No namespaces at all - { - std::stringstream xmlSS; - xmlSS << "<root><foo /><foo /><foo /></root>" << std::endl; - VALIDATE - } - - // default namespace - { - std::stringstream xmlSS; - xmlSS << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\ - <root xmlns=\"http://www.w3.org/2005/07/scxml\">\ - <foo /><foo /><foo />\ - </root>\ - " << std::endl; - VALIDATE - } - - // explicit namespaces - { - std::stringstream xmlSS; - xmlSS << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\ - <scxml:root xmlns:scxml=\"http://www.w3.org/2005/07/scxml\">\ - <scxml:foo /><scxml:foo /><scxml:foo />\ - </scxml:root>\ - " << std::endl; - VALIDATE - } - - // mixed namespaces - { - std::stringstream xmlSS; - xmlSS << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\ - <scxml:root xmlns:scxml=\"http://www.w3.org/2005/07/scxml\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\ - <xhtml:foo /><xhtml:foo /><xhtml:foo />\ - <scxml:foo /><scxml:foo /><scxml:foo />\ - </scxml:root>\ - " << std::endl; - VALIDATE - } - - // mixed namespaces with different default NS - { - std::stringstream xmlSS; - xmlSS << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\ - <scxml:root xmlns:scxml=\"http://www.w3.org/2005/07/scxml\" xmlns=\"http://www.w3.org/1999/xhtml\">\ - <foo /><foo /><foo />\ - <scxml:foo /><scxml:foo /><scxml:foo />\ - </scxml:root>\ - " << std::endl; - VALIDATE - } - -}
\ No newline at end of file diff --git a/test/src/test-arabica-parsing.cpp b/test/src/test-arabica-parsing.cpp deleted file mode 100644 index 24275fc..0000000 --- a/test/src/test-arabica-parsing.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include <iostream> - -#include "uscxml/config.h" -#include "uscxml/Common.h" -#include <DOM/Document.hpp> -#include <XPath/XPath.hpp> -#include <DOM/SAX2DOM/SAX2DOM.hpp> -#include <DOM/io/Stream.hpp> -#include <SAX/helpers/CatchErrorHandler.hpp> -#include <DOM/Events/EventTarget.hpp> -#include <DOM/Events/EventListener.hpp> - -using namespace Arabica::DOM; - -int main(int argc, char** argv) { - - { - std::stringstream* ss = new std::stringstream(); - (*ss) << "<root>\n<![CDATA[\n< \" ' < > &\n]]>\n</root>"; - // we need an auto_ptr for arabica to assume ownership - std::auto_ptr<std::istream> ssPtr(ss); - Arabica::SAX::InputSource<std::string> inputSource(ssPtr); - - Arabica::SAX2DOM::Parser<std::string> domParser; - Arabica::SAX::CatchErrorHandler<std::string> errorHandler; - domParser.setErrorHandler(errorHandler); - - if(!domParser.parse(inputSource)) { - std::cout << errorHandler.errors(); - return -1; - } - std::cout << domParser.getDocument().getDocumentElement().getFirstChild().getNodeValue() << std::endl; - std::cout << domParser.getDocument() << std::endl; - } - { - Arabica::SAX::InputSource<std::string> inputSource; - inputSource.setSystemId("/Users/sradomski/Documents/TK/Code/uscxml/test/samples/uscxml/arabica/test-arabica-parsing.xml"); - - Arabica::SAX2DOM::Parser<std::string> domParser; - Arabica::SAX::CatchErrorHandler<std::string> errorHandler; - domParser.setErrorHandler(errorHandler); - - if(!domParser.parse(inputSource)) { - std::cout << errorHandler.errors(); - return -1; - } - std::cout << domParser.getDocument() << std::endl; - } - -}
\ No newline at end of file diff --git a/test/src/test-arabica-xpath.cpp b/test/src/test-arabica-xpath.cpp deleted file mode 100644 index 9e21624..0000000 --- a/test/src/test-arabica-xpath.cpp +++ /dev/null @@ -1,212 +0,0 @@ -#include <iostream> - -#include <XPath/XPath.hpp> -#include <DOM/Simple/DOMImplementation.hpp> -#include <DOM/io/Stream.hpp> -#include <iostream> -#include <string> -#include "uscxml/dom/DOMUtils.h" - -#define string_type std::string -#define string_adaptor Arabica::default_string_adaptor<std::string> - -typedef string_adaptor SA; - -class NodeSetVariableResolver : public Arabica::XPath::VariableResolver<string_type, string_adaptor> { - //typedef string_adaptorstring_adaptor; -public: - virtual Arabica::XPath::XPathValue<string_type, string_adaptor> resolveVariable(const string_type& /* namepace_uri */, - const string_type& name) const { - using namespace Arabica::XPath; - VarMap::const_iterator n = map_.find(name); - if(n == map_.end()) - throw UnboundVariableException(string_adaptor::asStdString(name)); - return XPathValue<string_type, string_adaptor>(new NodeSetValue<string_type, string_adaptor>((*n).second)); - } // resolveVariable - - void setVariable(const string_type& name, const Arabica::XPath::NodeSet<string_type, string_adaptor>& value) { - map_[name] = value; - } // setVariable - -private: - typedef std::map<string_type, Arabica::XPath::NodeSet<string_type, string_adaptor> > VarMap; - VarMap map_; -}; // class NodeSetVariableResolver - -Arabica::XPath::XPath<string_type, string_adaptor> parser; -Arabica::DOM::DOMImplementation<string_type, string_adaptor> factory_; -Arabica::DOM::Document<string_type, string_adaptor> document_; - -Arabica::DOM::Element<string_type, string_adaptor> root_; -Arabica::DOM::Element<string_type, string_adaptor> element1_; -Arabica::DOM::Element<string_type, string_adaptor> element2_; -Arabica::DOM::Element<string_type, string_adaptor> element3_; -Arabica::DOM::Element<string_type, string_adaptor> spinkle_; - -Arabica::DOM::Attr<string_type, string_adaptor> attr_; -Arabica::DOM::Text<string_type, string_adaptor> text_; -Arabica::DOM::Comment<string_type, string_adaptor> comment_; -Arabica::DOM::ProcessingInstruction<string_type, string_adaptor> processingInstruction_; -Arabica::DOM::Document<string_type, string_adaptor> chapters_; -Arabica::DOM::Document<string_type, string_adaptor> numbers_; - -class StringVariableResolver : public Arabica::XPath::VariableResolver<string_type, string_adaptor> { -public: - virtual Arabica::XPath::XPathValue<string_type, string_adaptor> resolveVariable(const string_type& /* namespace_uri */, - const string_type& name) const { - using namespace Arabica::XPath; - VarMap::const_iterator n = map_.find(name); - if(n == map_.end()) - throw UnboundVariableException(string_adaptor::asStdString(name)); - return XPathValue<string_type, string_adaptor>(new StringValue<string_type, string_adaptor>((*n).second)); - } // resolveVariable - - void setVariable(const string_type& name, const string_type& value) { - map_[name] = value; - } // setVariable - -private: - typedef std::map<string_type, string_type> VarMap; - VarMap map_; -}; // StringVariableResolver - - -int main(int argc, char** argv) { - - factory_ = Arabica::SimpleDOM::DOMImplementation<string_type, string_adaptor>::getDOMImplementation(); - document_ = factory_.createDocument(SA::construct_from_utf8(""), SA::construct_from_utf8(""), 0); - root_ = document_.createElement("root"); - document_.appendChild(root_); - assert(root_); - - element1_ = document_.createElement(SA::construct_from_utf8("child1")); - element2_ = document_.createElement(SA::construct_from_utf8("child2")); - element3_ = document_.createElement(SA::construct_from_utf8("child3")); - - element1_.setAttribute(SA::construct_from_utf8("one"), SA::construct_from_utf8("1")); - - element2_.setAttribute(SA::construct_from_utf8("one"), SA::construct_from_utf8("1")); - element2_.setAttribute(SA::construct_from_utf8("two"), SA::construct_from_utf8("1")); - element2_.setAttribute(SA::construct_from_utf8("three"), SA::construct_from_utf8("1")); - element2_.setAttribute(SA::construct_from_utf8("four"), SA::construct_from_utf8("1")); - - text_ = document_.createTextNode(SA::construct_from_utf8("data")); - comment_ = document_.createComment(SA::construct_from_utf8("comment")); - processingInstruction_ = document_.createProcessingInstruction(SA::construct_from_utf8("target"), SA::construct_from_utf8("data")); - element2_.appendChild(text_); - spinkle_ = document_.createElement(SA::construct_from_utf8("spinkle")); - element2_.appendChild(spinkle_); - element2_.appendChild(comment_); - element2_.appendChild(processingInstruction_); - - attr_ = element1_.getAttributeNode(SA::construct_from_utf8("one")); - - root_.appendChild(element1_); - root_.appendChild(element2_); - root_.appendChild(element3_); - - chapters_ = factory_.createDocument(SA::construct_from_utf8(""), SA::construct_from_utf8(""), 0); - chapters_.appendChild(chapters_.createElement(SA::construct_from_utf8("document"))); - chapters_.getFirstChild().appendChild(chapters_.createElement(SA::construct_from_utf8("chapter"))).appendChild(chapters_.createTextNode(SA::construct_from_utf8("one"))); - chapters_.getFirstChild().appendChild(chapters_.createElement(SA::construct_from_utf8("chapter"))).appendChild(chapters_.createTextNode(SA::construct_from_utf8("two"))); - chapters_.getFirstChild().appendChild(chapters_.createElement(SA::construct_from_utf8("chapter"))).appendChild(chapters_.createTextNode(SA::construct_from_utf8("three"))); - chapters_.getFirstChild().appendChild(chapters_.createElement(SA::construct_from_utf8("chapter"))).appendChild(chapters_.createTextNode(SA::construct_from_utf8("four"))); - chapters_.getFirstChild().appendChild(chapters_.createElement(SA::construct_from_utf8("chapter"))).appendChild(chapters_.createTextNode(SA::construct_from_utf8("five"))); - - numbers_ = factory_.createDocument(SA::construct_from_utf8(""), SA::construct_from_utf8(""), 0); - numbers_.appendChild(numbers_.createElement(SA::construct_from_utf8("doc"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("1"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("2"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("3"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("4"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("5"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("6"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("7"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("8"))); - numbers_.getFirstChild().appendChild(numbers_.createElement(SA::construct_from_utf8("number"))).appendChild(numbers_.createTextNode(SA::construct_from_utf8("9"))); - std::cout << document_ << std::endl; - std::cout << numbers_ << std::endl; - std::cout << chapters_ << std::endl; - - if (true) { - using namespace Arabica::XPath; - using namespace Arabica::DOM; - XPathValue<string_type, string_adaptor> result = parser.evaluate(SA::construct_from_utf8("//*"), document_); - for(int i = 0; i < result.asNodeSet().size(); i++) { - Node<string_type, string_adaptor> node = result.asNodeSet()[i]; - std::string xpathExpr = uscxml::DOMUtils::xPathForNode(node); - if (xpathExpr.size()) { - XPathValue<string_type, string_adaptor> innerResult = parser.evaluate(xpathExpr, document_); - assert(innerResult.asNodeSet().size() > 0); - assert(innerResult.asNodeSet().size() == 1); - assert(innerResult.asNodeSet()[0] == node); - } else { - assert(node.getNodeType() != Node_base::ELEMENT_NODE); - } - } - } - - if (false) { - using namespace Arabica::XPath; - StringVariableResolver svr; - svr.setVariable(SA::construct_from_utf8("index"), SA::construct_from_utf8("1")); - - parser.setVariableResolver(svr); - XPathValue<string_type, string_adaptor> result = parser.evaluate(SA::construct_from_utf8("/root/*[@two = $index]"), document_); - assert(NODE_SET == result.type()); - assert(element2_ == result.asNodeSet()[0]); - - parser.resetVariableResolver(); - } // test18 - - if (false) { - using namespace Arabica::XPath; - XPathExpression<string_type, string_adaptor> xpath = parser.compile(SA::construct_from_utf8("root/*[position() = 2]")); - XPathValue<string_type, string_adaptor> result = xpath.evaluate(document_); - - assert(NODE_SET == result.type()); - assert(1 == result.asNodeSet().size()); - Arabica::DOM::Node<string_type, string_adaptor> n = result.asNodeSet()[0]; - assert(element2_ == n); - } // test19 - - if (false) { - using namespace Arabica::XPath; - Arabica::DOM::DocumentFragment<string_type, string_adaptor> frag = document_.createDocumentFragment(); - frag.appendChild(document_.createElement(SA::construct_from_utf8("foo"))); - - NodeSetVariableResolver svr; - NodeSet<string_type, string_adaptor> ns; - ns.push_back(frag); - svr.setVariable(SA::construct_from_utf8("fruit"), ns); - parser.setVariableResolver(svr); - - XPathValue<string_type, string_adaptor> result = parser.evaluate_expr(SA::construct_from_utf8("$fruit/foo|/root/child3"), document_); - assert(NODE_SET == result.type()); - assert(2 == result.asNodeSet().size()); - assert(element3_ == result.asNodeSet()[0]); - } // testUnion11 - - if (false) { - using namespace Arabica::XPath; - XPathValue<string_type, string_adaptor> result = parser.evaluate_expr(SA::construct_from_utf8("local-name(/root)"), document_); - assert(STRING == result.type()); - assert(SA::construct_from_utf8("root") == result.asString()); - } // testLocalNameFn1 - - if (0) { - using namespace Arabica::XPath; - Arabica::DOM::DocumentFragment<std::string> frag = document_.createDocumentFragment(); - frag.appendChild(document_.createElement("foo")); - - NodeSetVariableResolver svr; - NodeSet<string_type, string_adaptor> ns; - ns.push_back(frag); - svr.setVariable("fruit", ns); - parser.setVariableResolver(svr); - - XPathValue<string_type, string_adaptor> result = parser.evaluate(SA::construct_from_utf8("local-name($fruit/foo) == 'foo'"), document_); - std::cout << result.asBool() << std::endl; - } - -}
\ No newline at end of file diff --git a/test/src/test-base64.cpp b/test/src/test-base64.cpp deleted file mode 100644 index 4981a26..0000000 --- a/test/src/test-base64.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "uscxml/util/Base64.hpp" -#include <assert.h> - -#define SOURCE_LEN 10 - -int main(int argc, char** argv) { - std::string data; - std::string base64CPP; - std::string base64C; - - char buffer[SOURCE_LEN]; - for (size_t i = 0; i < SOURCE_LEN; i++) { - buffer[i] = (char)55; - } - - base64C = uscxml::base64Encode(buffer, SOURCE_LEN); - -}
\ No newline at end of file diff --git a/test/src/test-c-inline.c b/test/src/test-c-inline.c deleted file mode 100644 index 7b375a9..0000000 --- a/test/src/test-c-inline.c +++ /dev/null @@ -1,191 +0,0 @@ -//#include <stdlib.h> // EXIT_SUCCESS -//#include <stdio.h> // printf -#include <string.h> // memset - -#undef ON_AVR - -/** - * Preprocess: - * uscxml-transform -tc -i ./gadget-inline-avr.c -o ./gadget-inline-avr.c.scxml.c - */ - -/** INLINE SCXML BEGIN - -<scxml> - <parallel> - <onentry> - <raise event="blueHigh" /> - </onentry> - <!-- - 1 X X X X - ^ ^^^ ^^^ - | | | - | | Action - | Color - Here comes the signal! - - Colors: - blue 1,1 - red 1,0 - green 0,1 - ESC! 0,0 - - Actions: - dimUp: 0,1 - dimDown: 0,0 - turnOn: 1,1 - turnDown: 1,0 - - ESC!: - 0,0 All off - 1,1 All on - - IR emitter is either Color + Action or Special - --> - <state id="interaction"> - <transition event="blueHigh"> - <!-- Receiver beware, here it comes --> - <raise event="IROn" /> - - <!-- color blue --> - <raise event="IROn" /> - <raise event="IROn" /> - - <!-- action dimUp --> - <raise event="IROff" /> - <raise event="IROn" /> - - <!-- make sure to turn LED off --> - <raise event="IROff" /> - - </transition> - </state> - - <state id="periphery"> - <transition event="IROn" target="IRLedOn" type="internal" /> - <transition event="IROff" target="IRLedOff" type="internal" /> - - <!-- These are the lines we will connect to the IR emitter --> - <state id="IRLedOff"> - <onentry>ledOff();</onentry> - </state> - <state id="IRLedOn"> - <onentry>ledOn();</onentry> - </state> - </state> - </parallel> -</scxml> -INLINE SCXML END */ - -#define IQ_LENGTH 10 -#define EQ_LENGTH 10 - -const char* iQ[IQ_LENGTH]; -size_t iwPtr = 0; -size_t irPtr = 0; - -const char* eQ[EQ_LENGTH]; -size_t ewPtr = 0; -size_t erPtr = 0; - - -void ledOn() { - printf("Turned on LED!\n"); -} - -void ledOff() { - printf("Turned off LED!\n"); -} - -#include "test-c-inline.c.scxml.c" - -void* dequeue_internal(const uscxml_ctx* ctx) { - if (iwPtr != irPtr) { - size_t tmp = irPtr; - irPtr = (irPtr + 1 >= IQ_LENGTH ? 0 : irPtr + 1); - return iQ[tmp]; - } - return NULL; -} - -void* dequeue_external(const uscxml_ctx* ctx) { - if (ewPtr != erPtr) { - size_t tmp = erPtr; - irPtr = (erPtr + 1 >= EQ_LENGTH ? 0 : erPtr + 1); - return eQ[tmp]; - } - return NULL; -} - -int is_matched(const uscxml_ctx* ctx, const uscxml_transition* transition, const void* event) { - char* tPtr1 = (char*)event; - char* tPtr2 = (char*)transition->event; - while(*tPtr1 && *tPtr2) { - if (tPtr1 != tPtr2) - return 0; - tPtr1++; - tPtr2++; - } - return 1; -} - -int raise(const uscxml_ctx* ctx, const char* event) { - iQ[iwPtr] = event; - iwPtr = (iwPtr + 1 >= IQ_LENGTH ? 0 : iwPtr + 1); - return USCXML_ERR_OK; -} - -int send(const uscxml_ctx* ctx, const char* event) { - eQ[ewPtr] = event; - ewPtr = (ewPtr + 1 >= IQ_LENGTH ? 0 : ewPtr + 1); - return USCXML_ERR_OK; -} - -int main(int argc, char** argv) { - -#ifdef ON_AVR - int ir_led = 9; - int blue_touch = 1; - int red_touch = 2; - int yellow_touch = 3; - - pinMode(ir_led, OUTPUT); - pinMode(blue_touch, INPUT); - pinMode(red_touch, INPUT); - pinMode(yellow_touch, INPUT); - -#endif - - - uscxml_ctx ctx; - int err = USCXML_ERR_OK; - - memset(&ctx, 0, sizeof(uscxml_ctx)); - ctx.machine = &USCXML_MACHINE; - - ctx.exec_content_raise = raise; - ctx.dequeue_internal = dequeue_internal; - ctx.dequeue_external = dequeue_external; - ctx.is_matched = is_matched; - - while(err != USCXML_ERR_DONE) { - - err = uscxml_step(&ctx); -#ifdef ON_AVR - if (err == USCXML_IDLE) { - if (digitalRead(blue) == HIGH) { - send(ctx, "blueHigh"); - } - if (digitalRead(blue) == HIGH) { - send(ctx, "redHigh"); - } - if (digitalRead(blue) == HIGH) { - send(ctx, "greenHigh"); - } - } - delay(20); -#endif - } - - return 0; -} diff --git a/test/src/test-c-inline.c.scxml.c b/test/src/test-c-inline.c.scxml.c deleted file mode 100644 index f3d8b01..0000000 --- a/test/src/test-c-inline.c.scxml.c +++ /dev/null @@ -1,1112 +0,0 @@ -/** - Generated from source: - file:///Users/sradomski/Documents/TK/Code/uscxml/test/src/test-c-inline.c -*/ - -#ifndef USCXML_NO_STDTYPES_H -# include <stdint.h> /* explicit types */ -#endif -#include <stddef.h> /* NULL */ - -#ifndef USCXML_NO_GEN_C_MACROS - -/** - * All macros used for the scxml types and functions - * - * ** IMPORTANT: Make sure to set the following macros prior to including. ** - * They are used to represent the machine in the types to follow - * and to allocate stack memory during a micro-step function. - * When in doubt, overprovide. - * - * USCXML_NR_STATES_TYPE - * as the smallest type for positive integers that can contain the - * largest number of states from an individual state machine. E.g.: - * < 2^8 states => uint8_t - * < 2^16 states => uint16_t - * < 2^32 states => uint32_t - */ - -#ifndef USCXML_NR_STATES_TYPE -# define USCXML_NR_STATES_TYPE uint8_t -#endif - -/** - * USCXML_NR_TRANS_TYPE - * the same as above but for the number of transitions. - */ - -#ifndef USCXML_NR_TRANS_TYPE -# define USCXML_NR_TRANS_TYPE uint8_t -#endif - -/** - * USCXML_MAX_NR_STATES_BYTES - * the smallest multiple of 8 that, if multiplied by 8, - * is larger than USCXML_NR_STATES_TYPE, e.g: - * 1-8 states => 1 - * 9-16 states => 2 - * 17-24 states => 3 - * 25-32 states => 4 - * ... - */ - -#ifndef USCXML_MAX_NR_STATES_BYTES -# define USCXML_MAX_NR_STATES_BYTES 1 -#endif - -/** - * USCXML_MAX_NR_TRANS_BYTES - * same as above but for transitions. - */ - -#ifndef USCXML_MAX_NR_TRANS_BYTES -# define USCXML_MAX_NR_TRANS_BYTES 1 -#endif - -/** - * USCXML_NUMBER_STATES / USCXML_NUMBER_TRANS - * Per default the number of states / transitions is retrieved from the machine - * info in the uscxml_ctx struct, but you can also hard-code it per macro. - */ - -#ifndef USCXML_NUMBER_STATES -# define USCXML_NUMBER_STATES (ctx->machine->nr_states) -#endif - -#ifndef USCXML_NUMBER_TRANS -# define USCXML_NUMBER_TRANS (ctx->machine->nr_transitions) -#endif - -/** - * USCXML_GET_STATE / USCXML_GET_TRANS - * Per default an individual state or transitions is retrieved from the machine - * info in the uscxml_ctx struct, but you can also hard-code it per macro. - */ - -#ifndef USCXML_GET_STATE -# define USCXML_GET_STATE(i) (ctx->machine->states[i]) -#endif - -#ifndef USCXML_GET_TRANS -# define USCXML_GET_TRANS(i) (ctx->machine->transitions[i]) -#endif - - -/* Common macros below */ - -#define BIT_HAS(idx, bitset) ((bitset[idx >> 3] & (1 << (idx & 7))) != 0) -#define BIT_SET_AT(idx, bitset) bitset[idx >> 3] |= (1 << (idx & 7)); -#define BIT_CLEAR(idx, bitset) bitset[idx >> 3] &= (1 << (idx & 7)) ^ 0xFF; - -#ifdef __GNUC__ -# define likely(x) (__builtin_expect(!!(x), 1)) -# define unlikely(x) (__builtin_expect(!!(x), 0)) -#else -# define likely(x) (x) -# define unlikely(x) (x) -#endif - -/* error return codes */ -#define USCXML_ERR_OK 0 -#define USCXML_ERR_IDLE 1 -#define USCXML_ERR_DONE 2 -#define USCXML_ERR_MISSING_CALLBACK 3 -#define USCXML_ERR_FOREACH_DONE 4 -#define USCXML_ERR_EXEC_CONTENT 5 -#define USCXML_ERR_INVALID_TARGET 6 -#define USCXML_ERR_INVALID_TYPE 7 -#define USCXML_ERR_UNSUPPORTED 8 -#define USCXML_ERR_MACRO 9 - -#define USCXML_TRANS_SPONTANEOUS 0x01 -#define USCXML_TRANS_TARGETLESS 0x02 -#define USCXML_TRANS_INTERNAL 0x04 -#define USCXML_TRANS_HISTORY 0x08 -#define USCXML_TRANS_INITIAL 0x10 - -#define USCXML_STATE_ATOMIC 0x01 -#define USCXML_STATE_PARALLEL 0x02 -#define USCXML_STATE_COMPOUND 0x03 -#define USCXML_STATE_FINAL 0x04 -#define USCXML_STATE_HISTORY_DEEP 0x05 -#define USCXML_STATE_HISTORY_SHALLOW 0x06 -#define USCXML_STATE_INITIAL 0x07 -#define USCXML_STATE_HAS_HISTORY 0x80 /* highest bit */ -#define USCXML_STATE_MASK(t) (t & 0x7F) /* mask highest bit */ - -#define USCXML_CTX_PRISTINE 0x00 -#define USCXML_CTX_SPONTANEOUS 0x01 -#define USCXML_CTX_INITIALIZED 0x02 -#define USCXML_CTX_TOP_LEVEL_FINAL 0x04 -#define USCXML_CTX_TRANSITION_FOUND 0x08 -#define USCXML_CTX_FINISHED 0x10 - -#define USCXML_ELEM_DATA_IS_SET(data) (data->id != NULL) -#define USCXML_ELEM_DONEDATA_IS_SET(donedata) (donedata->content != NULL || donedata->contentexpr != NULL || donedata->params != NULL) -#define USCXML_ELEM_PARAM_IS_SET(param) (param->name != NULL) -#define USCXML_MACHINE_IS_SET(machine) (machine->nr_states > 0) - -#define USCXML_NO_GEN_C_MACROS -#endif - - -#ifndef USCXML_NO_GEN_C_TYPES - -/** - * All types required to represent an SCXML state chart. - * Just predefine the USCXML_NO_GEN_C_TYPES macro if you do not need them. - */ - -typedef struct uscxml_machine uscxml_machine; -typedef struct uscxml_transition uscxml_transition; -typedef struct uscxml_state uscxml_state; -typedef struct uscxml_ctx uscxml_ctx; -typedef struct uscxml_elem_invoke uscxml_elem_invoke; - -typedef struct uscxml_elem_send uscxml_elem_send; -typedef struct uscxml_elem_param uscxml_elem_param; -typedef struct uscxml_elem_data uscxml_elem_data; -typedef struct uscxml_elem_assign uscxml_elem_assign; -typedef struct uscxml_elem_donedata uscxml_elem_donedata; -typedef struct uscxml_elem_foreach uscxml_elem_foreach; - -typedef void* (*dequeue_internal_t)(const uscxml_ctx* ctx); -typedef void* (*dequeue_external_t)(const uscxml_ctx* ctx); -typedef int (*is_enabled_t)(const uscxml_ctx* ctx, const uscxml_transition* transition); -typedef int (*is_matched_t)(const uscxml_ctx* ctx, const uscxml_transition* transition, const void* event); -typedef int (*is_true_t)(const uscxml_ctx* ctx, const char* expr); -typedef int (*exec_content_t)(const uscxml_ctx* ctx, const uscxml_state* state, const void* event); -typedef int (*raise_done_event_t)(const uscxml_ctx* ctx, const uscxml_state* state, const uscxml_elem_donedata* donedata); -typedef int (*invoke_t)(const uscxml_ctx* ctx, const uscxml_state* s, const uscxml_elem_invoke* invocation, unsigned char uninvoke); - -typedef int (*exec_content_log_t)(const uscxml_ctx* ctx, const char* label, const char* expr); -typedef int (*exec_content_raise_t)(const uscxml_ctx* ctx, const char* event); -typedef int (*exec_content_send_t)(const uscxml_ctx* ctx, const uscxml_elem_send* send); -typedef int (*exec_content_foreach_init_t)(const uscxml_ctx* ctx, const uscxml_elem_foreach* foreach); -typedef int (*exec_content_foreach_next_t)(const uscxml_ctx* ctx, const uscxml_elem_foreach* foreach); -typedef int (*exec_content_foreach_done_t)(const uscxml_ctx* ctx, const uscxml_elem_foreach* foreach); -typedef int (*exec_content_assign_t)(const uscxml_ctx* ctx, const uscxml_elem_assign* assign); -typedef int (*exec_content_init_t)(const uscxml_ctx* ctx, const uscxml_elem_data* data); -typedef int (*exec_content_cancel_t)(const uscxml_ctx* ctx, const char* sendid, const char* sendidexpr); -typedef int (*exec_content_finalize_t)(const uscxml_ctx* ctx, const uscxml_elem_invoke* invoker, const void* event); -typedef int (*exec_content_script_t)(const uscxml_ctx* ctx, const char* src, const char* content); - -/** - * A single SCXML state-machine. - */ -struct uscxml_machine { - unsigned char flags; /* Unused */ - USCXML_NR_STATES_TYPE nr_states; /* Make sure to set type per macro! */ - USCXML_NR_TRANS_TYPE nr_transitions; /* Make sure to set type per macro! */ - const char* name; - const char* datamodel; - const char* uuid; /* currently MD5 sum */ - const uscxml_state* states; - const uscxml_transition* transitions; - const uscxml_machine* parent; - const uscxml_elem_donedata* donedata; - const exec_content_t script; /* Global script elements */ -}; - -/** - * All information pertaining to a <data> element. - * With late data binding, blocks of data elements are separated by NULL - * use USCXML_ELEM_DATA_IS_SET to test for end of a block. - */ -struct uscxml_elem_data { - const char* id; - const char* src; - const char* expr; - const char* content; -}; - -/** - * All information pertaining to an <assign> element. - */ -struct uscxml_elem_assign { - const char* location; - const char* expr; - const char* content; -}; - -/** - * All information pertaining to any state element. - */ -struct uscxml_state { - const char* name; /* eventual name */ - const USCXML_NR_STATES_TYPE parent; /* parent */ - const exec_content_t on_entry; /* on entry handlers */ - const exec_content_t on_exit; /* on exit handlers */ - const invoke_t invoke; /* invocations */ - const char children[USCXML_MAX_NR_STATES_BYTES]; /* all children */ - const char completion[USCXML_MAX_NR_STATES_BYTES]; /* default completion */ - const char ancestors[USCXML_MAX_NR_STATES_BYTES]; /* all ancestors */ - const uscxml_elem_data* data; /* data with late binding */ - const unsigned char type; /* One of USCXML_STATE_* */ -}; - -/** - * All information pertaining to a <transitions> element. - */ -struct uscxml_transition { - const USCXML_NR_STATES_TYPE source; - const char target[USCXML_MAX_NR_STATES_BYTES]; - const char* event; - const char* condition; - const is_enabled_t is_enabled; - const exec_content_t on_transition; - const unsigned char type; - const char conflicts[USCXML_MAX_NR_TRANS_BYTES]; - const char exit_set[USCXML_MAX_NR_STATES_BYTES]; -}; - -/** - * All information pertaining to a <foreach> element. - */ -struct uscxml_elem_foreach { - const char* array; - const char* item; - const char* index; -}; - -/** - * All information pertaining to a <param> element. - * Blocks of params are separated by NULL params, use - * USCXML_ELEM_PARAM_IS_SET to test for end of a block. - */ -struct uscxml_elem_param { - const char* name; - const char* expr; - const char* location; -}; - -/** - * All information pertaining to a <donedata> element. - */ -struct uscxml_elem_donedata { - const USCXML_NR_STATES_TYPE source; - const char* content; - const char* contentexpr; - const uscxml_elem_param* params; -}; - -/** - * All information pertaining to an <invoke> element. - */ -struct uscxml_elem_invoke { - const uscxml_machine* machine; - const char* type; - const char* typeexpr; - const char* src; - const char* srcexpr; - const char* id; - const char* idlocation; - const char* sourcename; - const char* namelist; - const unsigned char autoforward; - const uscxml_elem_param* params; - exec_content_finalize_t finalize; - const char* content; - const char* contentexpr; -}; - -/** - * All information pertaining to a <send> element. - */ -struct uscxml_elem_send { - const char* event; - const char* eventexpr; - const char* target; - const char* targetexpr; - const char* type; - const char* typeexpr; - const char* id; - const char* idlocation; - const char* delay; - const char* delayexpr; - const char* namelist; /* not space-separated, still as in attribute value */ - const char* content; - const char* contentexpr; - const uscxml_elem_param* params; -}; - -/** - * Represents an instance of a state-chart at runtime/ - */ -struct uscxml_ctx { - unsigned char flags; - const uscxml_machine* machine; - - char config[USCXML_MAX_NR_STATES_BYTES]; /* Make sure these macros specify a sufficient size */ - char history[USCXML_MAX_NR_STATES_BYTES]; - char invocations[USCXML_MAX_NR_STATES_BYTES]; - char initialized_data[USCXML_MAX_NR_STATES_BYTES]; - - void* user_data; - void* event; - - dequeue_internal_t dequeue_internal; - dequeue_external_t dequeue_external; - is_matched_t is_matched; - is_true_t is_true; - raise_done_event_t raise_done_event; - - exec_content_log_t exec_content_log; - exec_content_raise_t exec_content_raise; - exec_content_send_t exec_content_send; - exec_content_foreach_init_t exec_content_foreach_init; - exec_content_foreach_next_t exec_content_foreach_next; - exec_content_foreach_done_t exec_content_foreach_done; - exec_content_assign_t exec_content_assign; - exec_content_init_t exec_content_init; - exec_content_cancel_t exec_content_cancel; - exec_content_script_t exec_content_script; - - invoke_t invoke; -}; - -#define USCXML_NO_GEN_C_TYPES -#endif - -/* forward declare machines to allow references */ -extern const uscxml_machine _uscxml_C4473F72_machine; - -#ifndef USCXML_NO_ELEM_INFO - -static const uscxml_elem_donedata _uscxml_C4473F72_elem_donedatas[1] = { - /* source, content, contentexpr, params */ - { 0, NULL, NULL, NULL } -}; - -#endif - -#ifndef USCXML_NO_ELEM_INFO - -#endif - -#ifndef USCXML_NO_EXEC_CONTENT - -static int _uscxml_C4473F72_scxml0_parallel0_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - int err = USCXML_ERR_OK; - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "blueHigh")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - return USCXML_ERR_OK; -} - -static int _uscxml_C4473F72_scxml0_parallel0_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - _uscxml_C4473F72_scxml0_parallel0_on_entry_0(ctx, state, event); - return USCXML_ERR_OK; -} - -static int _uscxml_C4473F72_IRLedOff_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - int err = USCXML_ERR_OK; -ledOff(); return USCXML_ERR_OK; -} - -static int _uscxml_C4473F72_IRLedOff_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - _uscxml_C4473F72_IRLedOff_on_entry_0(ctx, state, event); - return USCXML_ERR_OK; -} - -static int _uscxml_C4473F72_IRLedOn_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - int err = USCXML_ERR_OK; -ledOn(); return USCXML_ERR_OK; -} - -static int _uscxml_C4473F72_IRLedOn_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - _uscxml_C4473F72_IRLedOn_on_entry_0(ctx, state, event); - return USCXML_ERR_OK; -} - -static int _uscxml_C4473F72_interaction_transition0_on_trans(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - int err = USCXML_ERR_OK; - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "IROn")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "IROn")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "IROn")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "IROff")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "IROn")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "IROff")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - return USCXML_ERR_OK; -} - -#endif - -#ifndef USCXML_NO_ELEM_INFO - -static const uscxml_state _uscxml_C4473F72_states[6] = { - { /* state number 0 */ - /* name */ NULL, - /* parent */ 0, - /* onentry */ NULL, - /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x02 /* 010000 */ }, - /* completion */ { 0x02 /* 010000 */ }, - /* ancestors */ { 0x00 /* 000000 */ }, - /* data */ NULL, - /* type */ USCXML_STATE_COMPOUND, - }, - { /* state number 1 */ - /* name */ "0a3ff41d-98e6-40fe-b147-cf397c12eb55", - /* parent */ 0, - /* onentry */ _uscxml_C4473F72_scxml0_parallel0_on_entry, - /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x0c /* 001100 */ }, - /* completion */ { 0x0c /* 001100 */ }, - /* ancestors */ { 0x01 /* 100000 */ }, - /* data */ NULL, - /* type */ USCXML_STATE_PARALLEL, - }, - { /* state number 2 */ - /* name */ "interaction", - /* parent */ 1, - /* onentry */ NULL, - /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x00 /* 000000 */ }, - /* completion */ { 0x00 /* 000000 */ }, - /* ancestors */ { 0x03 /* 110000 */ }, - /* data */ NULL, - /* type */ USCXML_STATE_ATOMIC, - }, - { /* state number 3 */ - /* name */ "periphery", - /* parent */ 1, - /* onentry */ NULL, - /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x30 /* 000011 */ }, - /* completion */ { 0x10 /* 000010 */ }, - /* ancestors */ { 0x03 /* 110000 */ }, - /* data */ NULL, - /* type */ USCXML_STATE_COMPOUND, - }, - { /* state number 4 */ - /* name */ "IRLedOff", - /* parent */ 3, - /* onentry */ _uscxml_C4473F72_IRLedOff_on_entry, - /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x00 /* 000000 */ }, - /* completion */ { 0x00 /* 000000 */ }, - /* ancestors */ { 0x0b /* 110100 */ }, - /* data */ NULL, - /* type */ USCXML_STATE_ATOMIC, - }, - { /* state number 5 */ - /* name */ "IRLedOn", - /* parent */ 3, - /* onentry */ _uscxml_C4473F72_IRLedOn_on_entry, - /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x00 /* 000000 */ }, - /* completion */ { 0x00 /* 000000 */ }, - /* ancestors */ { 0x0b /* 110100 */ }, - /* data */ NULL, - /* type */ USCXML_STATE_ATOMIC, - } -}; - -#endif - -#ifndef USCXML_NO_ELEM_INFO - -static const uscxml_transition _uscxml_C4473F72_transitions[3] = { - { /* transition number 0 with priority 0 - target: - */ - /* source */ 2, - /* target */ { NULL }, - /* event */ "blueHigh", - /* condition */ NULL, - /* is_enabled */ NULL, - /* ontrans */ _uscxml_C4473F72_interaction_transition0_on_trans, - /* type */ USCXML_TRANS_TARGETLESS, - /* conflicts */ { 0x01 /* 100 */ }, - /* exit set */ { 0x00 /* 000000 */ } - }, - { /* transition number 1 with priority 1 - target: IRLedOn - */ - /* source */ 3, - /* target */ { 0x20 /* 000001 */ }, - /* event */ "IROn", - /* condition */ NULL, - /* is_enabled */ NULL, - /* ontrans */ NULL, - /* type */ USCXML_TRANS_INTERNAL, - /* conflicts */ { 0x06 /* 011 */ }, - /* exit set */ { 0x30 /* 000011 */ } - }, - { /* transition number 2 with priority 2 - target: IRLedOff - */ - /* source */ 3, - /* target */ { 0x10 /* 000010 */ }, - /* event */ "IROff", - /* condition */ NULL, - /* is_enabled */ NULL, - /* ontrans */ NULL, - /* type */ USCXML_TRANS_INTERNAL, - /* conflicts */ { 0x06 /* 011 */ }, - /* exit set */ { 0x30 /* 000011 */ } - } -}; - -#endif - -#ifndef USCXML_NO_ELEM_INFO - -#ifndef USCXML_MACHINE -# define USCXML_MACHINE _uscxml_C4473F72_machine -#endif -#define USCXML_MACHINE_0 _uscxml_C4473F72_machine - -const uscxml_machine _uscxml_C4473F72_machine = { - /* flags */ 0, - /* nr_states */ 6, - /* nr_transitions */ 3, - /* name */ "", - /* datamodel */ "null", - /* uuid */ "C4473F72ECDBC2BBAE099A8F6849A804", - /* states */ &_uscxml_C4473F72_states[0], - /* transitions */ &_uscxml_C4473F72_transitions[0], - /* parent */ NULL, - /* donedata */ &_uscxml_C4473F72_elem_donedatas[0], - /* script */ NULL -}; - -#endif - -#ifdef USCXML_VERBOSE -/** - * Print name of states contained in a (debugging). - */ -static void printStateNames(const uscxml_ctx* ctx, const char* a, size_t length) { - size_t i; - const char* seperator = ""; - for (i = 0; i < length; i++) { - if (BIT_HAS(i, a)) { - printf("%s%s", seperator, (USCXML_GET_STATE(i).name != NULL ? USCXML_GET_STATE(i).name : "UNK")); - seperator = ", "; - } - } - printf("\n"); -} - -/** - * Print bits set in a in a binary representation (debugging). - */ -static void printBitsetIndices(const char* a, size_t length) { - size_t i; - const char* seperator = ""; - for (i = 0; i < length; i++) { - if (BIT_HAS(i, a)) { - printf("%s%lu", seperator, i); - seperator = ", "; - } - } - printf("\n"); -} -#endif - -#ifndef USCXML_NO_BIT_OPERATIONS -/** - * Return true if there is a common bit in a and b. - */ -static int bit_has_and(const char* a, const char* b, size_t i) { - while(i--) { - if (a[i] & b[i]) - return 1; - } - return 0; -} - -/** - * Set all bits to 0, this corresponds to memset(a, 0, i), - * but does not require string.h or cstring. - */ -static void bit_clear_all(char* a, size_t i) { - while(i--) { - a[i] = 0; - } -} - -/** - * Return true if there is any bit set in a. - */ -static int bit_has_any(const char* a, size_t i) { - while(i--) { - if (a[i] > 0) - return 1; - } - return 0; -} - -/** - * Set all bits from given mask in dest, this is |= for bit arrays. - */ -static void bit_or(char* dest, const char* mask, size_t i) { - while(i--) { - dest[i] |= mask[i]; - } -} - -/** - * Copy all bits from source to dest, this corresponds to memcpy(a, b, i), - * but does not require string.h or cstring. - */ -static void bit_copy(char* dest, const char* source, size_t i) { - while(i--) { - dest[i] = source[i]; - } -} - -/** - * Unset bits from mask in dest. - */ -static void bit_and_not(char* dest, const char* mask, size_t i) { - while(i--) { - dest[i] &= ~mask[i]; - } -} - -/** - * Set bits from mask in dest. - */ -static void bit_and(char* dest, const char* mask, size_t i) { - while(i--) { - dest[i] &= mask[i]; - }; -} - -#define USCXML_NO_BIT_OPERATIONS -#endif - -#ifndef USCXML_NO_STEP_FUNCTION -int uscxml_step(uscxml_ctx* ctx) { - - USCXML_NR_STATES_TYPE i, j, k; - USCXML_NR_STATES_TYPE nr_states_bytes = ((USCXML_NUMBER_STATES + 7) & ~7) >> 3; - USCXML_NR_TRANS_TYPE nr_trans_bytes = ((USCXML_NUMBER_TRANS + 7) & ~7) >> 3; - int err = USCXML_ERR_OK; - char conflicts [USCXML_MAX_NR_TRANS_BYTES]; - char trans_set [USCXML_MAX_NR_TRANS_BYTES]; - char target_set [USCXML_MAX_NR_STATES_BYTES]; - char exit_set [USCXML_MAX_NR_STATES_BYTES]; - char entry_set [USCXML_MAX_NR_STATES_BYTES]; - char tmp_states [USCXML_MAX_NR_STATES_BYTES]; - -#ifdef USCXML_VERBOSE - printf("Config: "); - printStateNames(ctx, ctx->config, USCXML_NUMBER_STATES); -#endif - - if (ctx->flags & USCXML_CTX_FINISHED) - return USCXML_ERR_DONE; - - if (ctx->flags & USCXML_CTX_TOP_LEVEL_FINAL) { - /* exit all remaining states */ - i = USCXML_NUMBER_STATES; - while(i-- > 0) { - if (BIT_HAS(i, ctx->config)) { - /* call all on exit handlers */ - if (USCXML_GET_STATE(i).on_exit != NULL) { - if unlikely((err = USCXML_GET_STATE(i).on_exit(ctx, &USCXML_GET_STATE(i), ctx->event)) != USCXML_ERR_OK) - return err; - } - } - if (BIT_HAS(i, ctx->invocations)) { - if (USCXML_GET_STATE(i).invoke != NULL) - USCXML_GET_STATE(i).invoke(ctx, &USCXML_GET_STATE(i), NULL, 1); - BIT_CLEAR(i, ctx->invocations); - } - } - ctx->flags |= USCXML_CTX_FINISHED; - return USCXML_ERR_DONE; - } - - bit_clear_all(target_set, nr_states_bytes); - bit_clear_all(trans_set, nr_trans_bytes); - if unlikely(ctx->flags == USCXML_CTX_PRISTINE) { - if (ctx->machine->script != NULL) - ctx->machine->script(ctx, &ctx->machine->states[0], NULL); - bit_or(target_set, ctx->machine->states[0].completion, nr_states_bytes); - ctx->flags |= USCXML_CTX_SPONTANEOUS | USCXML_CTX_INITIALIZED; - goto ESTABLISH_ENTRY_SET; - } - -DEQUEUE_EVENT: - if (ctx->flags & USCXML_CTX_SPONTANEOUS) { - ctx->event = NULL; - goto SELECT_TRANSITIONS; - } - if (ctx->dequeue_internal != NULL && (ctx->event = ctx->dequeue_internal(ctx)) != NULL) { - goto SELECT_TRANSITIONS; - } - - /* manage invocations */ - for (i = 0; i < USCXML_NUMBER_STATES; i++) { - /* uninvoke */ - if (!BIT_HAS(i, ctx->config) && BIT_HAS(i, ctx->invocations)) { - if (USCXML_GET_STATE(i).invoke != NULL) - USCXML_GET_STATE(i).invoke(ctx, &USCXML_GET_STATE(i), NULL, 1); - BIT_CLEAR(i, ctx->invocations) - } - /* invoke */ - if (BIT_HAS(i, ctx->config) && !BIT_HAS(i, ctx->invocations)) { - if (USCXML_GET_STATE(i).invoke != NULL) - USCXML_GET_STATE(i).invoke(ctx, &USCXML_GET_STATE(i), NULL, 0); - BIT_SET_AT(i, ctx->invocations) - } - } - - if (ctx->dequeue_external != NULL && (ctx->event = ctx->dequeue_external(ctx)) != NULL) { - goto SELECT_TRANSITIONS; - } - - if (ctx->dequeue_external == NULL) { - return USCXML_ERR_DONE; - } - return USCXML_ERR_IDLE; - -SELECT_TRANSITIONS: - bit_clear_all(conflicts, nr_trans_bytes); - bit_clear_all(exit_set, nr_states_bytes); - for (i = 0; i < USCXML_NUMBER_TRANS; i++) { - /* never select history or initial transitions automatically */ - if unlikely(USCXML_GET_TRANS(i).type & (USCXML_TRANS_HISTORY | USCXML_TRANS_INITIAL)) - continue; - - /* is the transition active? */ - if (BIT_HAS(USCXML_GET_TRANS(i).source, ctx->config)) { - /* is it non-conflicting? */ - if (!BIT_HAS(i, conflicts)) { - /* is it spontaneous with an event or vice versa? */ - if ((USCXML_GET_TRANS(i).event == NULL && ctx->event == NULL) || - (USCXML_GET_TRANS(i).event != NULL && ctx->event != NULL)) { - /* is it enabled? */ - if ((ctx->event == NULL || ctx->is_matched(ctx, &USCXML_GET_TRANS(i), ctx->event) > 0) && - (USCXML_GET_TRANS(i).condition == NULL || - USCXML_GET_TRANS(i).is_enabled(ctx, &USCXML_GET_TRANS(i)) > 0)) { - /* remember that we found a transition */ - ctx->flags |= USCXML_CTX_TRANSITION_FOUND; - - /* transitions that are pre-empted */ - bit_or(conflicts, USCXML_GET_TRANS(i).conflicts, nr_trans_bytes); - - /* states that are directly targeted (resolve as entry-set later) */ - bit_or(target_set, USCXML_GET_TRANS(i).target, nr_states_bytes); - - /* states that will be left */ - bit_or(exit_set, USCXML_GET_TRANS(i).exit_set, nr_states_bytes); - - BIT_SET_AT(i, trans_set); - } - } - } - } - } - bit_and(exit_set, ctx->config, nr_states_bytes); - - if (ctx->flags & USCXML_CTX_TRANSITION_FOUND) { - ctx->flags |= USCXML_CTX_SPONTANEOUS; - ctx->flags &= ~USCXML_CTX_TRANSITION_FOUND; - } else { - ctx->flags &= ~USCXML_CTX_SPONTANEOUS; - goto DEQUEUE_EVENT; - } - -#ifdef USCXML_VERBOSE - printf("Targets: "); - printStateNames(ctx, target_set, USCXML_NUMBER_STATES); -#endif - -#ifdef USCXML_VERBOSE - printf("Exiting: "); - printStateNames(ctx, exit_set, USCXML_NUMBER_STATES); -#endif - -#ifdef USCXML_VERBOSE - printf("History: "); - printStateNames(ctx, ctx->history, USCXML_NUMBER_STATES); -#endif - -/* REMEMBER_HISTORY: */ - for (i = 0; i < USCXML_NUMBER_STATES; i++) { - if unlikely(USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_HISTORY_SHALLOW || - USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_HISTORY_DEEP) { - /* a history state whose parent is about to be exited */ - if unlikely(BIT_HAS(USCXML_GET_STATE(i).parent, exit_set)) { - bit_copy(tmp_states, USCXML_GET_STATE(i).completion, nr_states_bytes); - - /* set those states who were enabled */ - bit_and(tmp_states, ctx->config, nr_states_bytes); - - /* clear current history with completion mask */ - bit_and_not(ctx->history, USCXML_GET_STATE(i).completion, nr_states_bytes); - - /* set history */ - bit_or(ctx->history, tmp_states, nr_states_bytes); - } - } - } - -ESTABLISH_ENTRY_SET: - /* calculate new entry set */ - bit_copy(entry_set, target_set, nr_states_bytes); - - /* iterate for ancestors */ - for (i = 0; i < USCXML_NUMBER_STATES; i++) { - if (BIT_HAS(i, entry_set)) { - bit_or(entry_set, USCXML_GET_STATE(i).ancestors, nr_states_bytes); - } - } - - /* iterate for descendants */ - for (i = 0; i < USCXML_NUMBER_STATES; i++) { - if (BIT_HAS(i, entry_set)) { - switch (USCXML_STATE_MASK(USCXML_GET_STATE(i).type)) { - case USCXML_STATE_PARALLEL: { - bit_or(entry_set, USCXML_GET_STATE(i).completion, nr_states_bytes); - break; - } - case USCXML_STATE_HISTORY_SHALLOW: - case USCXML_STATE_HISTORY_DEEP: { - if (!bit_has_and(USCXML_GET_STATE(i).completion, ctx->history, nr_states_bytes) && - !BIT_HAS(USCXML_GET_STATE(i).parent, ctx->config)) { - /* nothing set for history, look for a default transition */ - for (j = 0; j < USCXML_NUMBER_TRANS; j++) { - if unlikely(ctx->machine->transitions[j].source == i) { - bit_or(entry_set, ctx->machine->transitions[j].target, nr_states_bytes); - if(USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_HISTORY_DEEP && - !bit_has_and(ctx->machine->transitions[j].target, USCXML_GET_STATE(i).children, nr_states_bytes)) { - for (k = i + 1; k < USCXML_NUMBER_STATES; k++) { - if (BIT_HAS(k, ctx->machine->transitions[j].target)) { - bit_or(entry_set, ctx->machine->states[k].ancestors, nr_states_bytes); - break; - } - } - } - BIT_SET_AT(j, trans_set); - break; - } - /* Note: SCXML mandates every history to have a transition! */ - } - } else { - bit_copy(tmp_states, USCXML_GET_STATE(i).completion, nr_states_bytes); - bit_and(tmp_states, ctx->history, nr_states_bytes); - bit_or(entry_set, tmp_states, nr_states_bytes); - if (USCXML_GET_STATE(i).type == (USCXML_STATE_HAS_HISTORY | USCXML_STATE_HISTORY_DEEP)) { - /* a deep history state with nested histories -> more completion */ - for (j = i + 1; j < USCXML_NUMBER_STATES; j++) { - if (BIT_HAS(j, USCXML_GET_STATE(i).completion) && - BIT_HAS(j, entry_set) && - (ctx->machine->states[j].type & USCXML_STATE_HAS_HISTORY)) { - for (k = j + 1; k < USCXML_NUMBER_STATES; k++) { - /* add nested history to entry_set */ - if ((USCXML_STATE_MASK(ctx->machine->states[k].type) == USCXML_STATE_HISTORY_DEEP || - USCXML_STATE_MASK(ctx->machine->states[k].type) == USCXML_STATE_HISTORY_SHALLOW) && - BIT_HAS(k, ctx->machine->states[j].children)) { - /* a nested history state */ - BIT_SET_AT(k, entry_set); - } - } - } - } - } - } - break; - } - case USCXML_STATE_INITIAL: { - for (j = 0; j < USCXML_NUMBER_TRANS; j++) { - if (ctx->machine->transitions[j].source == i) { - BIT_SET_AT(j, trans_set); - BIT_CLEAR(i, entry_set); - bit_or(entry_set, ctx->machine->transitions[j].target, nr_states_bytes); - for (k = i + 1; k < USCXML_NUMBER_STATES; k++) { - if (BIT_HAS(k, ctx->machine->transitions[j].target)) { - bit_or(entry_set, ctx->machine->states[k].ancestors, nr_states_bytes); - } - } - } - } - break; - } - case USCXML_STATE_COMPOUND: { /* we need to check whether one child is already in entry_set */ - if (!bit_has_and(entry_set, USCXML_GET_STATE(i).children, nr_states_bytes) && - (!bit_has_and(ctx->config, USCXML_GET_STATE(i).children, nr_states_bytes) || - bit_has_and(exit_set, USCXML_GET_STATE(i).children, nr_states_bytes))) - { - bit_or(entry_set, USCXML_GET_STATE(i).completion, nr_states_bytes); - if (!bit_has_and(USCXML_GET_STATE(i).completion, USCXML_GET_STATE(i).children, nr_states_bytes)) { - /* deep completion */ - for (j = i + 1; j < USCXML_NUMBER_STATES; j++) { - if (BIT_HAS(j, USCXML_GET_STATE(i).completion)) { - bit_or(entry_set, ctx->machine->states[j].ancestors, nr_states_bytes); - break; /* completion of compound is single state */ - } - } - } - } - break; - } - } - } - } - -#ifdef USCXML_VERBOSE - printf("Transitions: "); - printBitsetIndices(trans_set, sizeof(char) * 8 * nr_trans_bytes); -#endif - -/* EXIT_STATES: */ - i = USCXML_NUMBER_STATES; - while(i-- > 0) { - if (BIT_HAS(i, exit_set) && BIT_HAS(i, ctx->config)) { - /* call all on exit handlers */ - if (USCXML_GET_STATE(i).on_exit != NULL) { - if unlikely((err = USCXML_GET_STATE(i).on_exit(ctx, &USCXML_GET_STATE(i), ctx->event)) != USCXML_ERR_OK) - return err; - } - BIT_CLEAR(i, ctx->config); - } - } - -/* TAKE_TRANSITIONS: */ - for (i = 0; i < USCXML_NUMBER_TRANS; i++) { - if (BIT_HAS(i, trans_set) && (USCXML_GET_TRANS(i).type & (USCXML_TRANS_HISTORY | USCXML_TRANS_INITIAL)) == 0) { - /* call executable content in transition */ - if (USCXML_GET_TRANS(i).on_transition != NULL) { - if unlikely((err = USCXML_GET_TRANS(i).on_transition(ctx, - &ctx->machine->states[USCXML_GET_TRANS(i).source], - ctx->event)) != USCXML_ERR_OK) - return err; - } - } - } - -#ifdef USCXML_VERBOSE - printf("Entering: "); - printStateNames(ctx, entry_set, USCXML_NUMBER_STATES); -#endif - -/* ENTER_STATES: */ - for (i = 0; i < USCXML_NUMBER_STATES; i++) { - if (BIT_HAS(i, entry_set) && !BIT_HAS(i, ctx->config)) { - /* these are no proper states */ - if unlikely(USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_HISTORY_DEEP || - USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_HISTORY_SHALLOW || - USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_INITIAL) - continue; - - BIT_SET_AT(i, ctx->config); - - /* initialize data */ - if (!BIT_HAS(i, ctx->initialized_data)) { - if unlikely(USCXML_GET_STATE(i).data != NULL && ctx->exec_content_init != NULL) { - ctx->exec_content_init(ctx, USCXML_GET_STATE(i).data); - } - BIT_SET_AT(i, ctx->initialized_data); - } - - if (USCXML_GET_STATE(i).on_entry != NULL) { - if unlikely((err = USCXML_GET_STATE(i).on_entry(ctx, &USCXML_GET_STATE(i), ctx->event)) != USCXML_ERR_OK) - return err; - } - - /* take history and initial transitions */ - for (j = 0; j < USCXML_NUMBER_TRANS; j++) { - if unlikely(BIT_HAS(j, trans_set) && - (ctx->machine->transitions[j].type & (USCXML_TRANS_HISTORY | USCXML_TRANS_INITIAL)) && - ctx->machine->states[ctx->machine->transitions[j].source].parent == i) { - /* call executable content in transition */ - if (ctx->machine->transitions[j].on_transition != NULL) { - if unlikely((err = ctx->machine->transitions[j].on_transition(ctx, - &USCXML_GET_STATE(i), - ctx->event)) != USCXML_ERR_OK) - return err; - } - } - } - - /* handle final states */ - if unlikely(USCXML_STATE_MASK(USCXML_GET_STATE(i).type) == USCXML_STATE_FINAL) { - if unlikely(USCXML_GET_STATE(i).ancestors[0] == 0x01) { - ctx->flags |= USCXML_CTX_TOP_LEVEL_FINAL; - } else { - /* raise done event */ - const uscxml_elem_donedata* donedata = &ctx->machine->donedata[0]; - while(USCXML_ELEM_DONEDATA_IS_SET(donedata)) { - if unlikely(donedata->source == i) - break; - donedata++; - } - ctx->raise_done_event(ctx, &ctx->machine->states[USCXML_GET_STATE(i).parent], (USCXML_ELEM_DONEDATA_IS_SET(donedata) ? donedata : NULL)); - } - - /** - * are we the last final state to leave a parallel state?: - * 1. Gather all parallel states in our ancestor chain - * 2. Find all states for which these parallels are ancestors - * 3. Iterate all active final states and remove their ancestors - * 4. If a state remains, not all children of a parallel are final - */ - for (j = 0; j < USCXML_NUMBER_STATES; j++) { - if unlikely(USCXML_STATE_MASK(ctx->machine->states[j].type) == USCXML_STATE_PARALLEL && - BIT_HAS(j, USCXML_GET_STATE(i).ancestors)) { - bit_clear_all(tmp_states, nr_states_bytes); - for (k = 0; k < USCXML_NUMBER_STATES; k++) { - if unlikely(BIT_HAS(j, ctx->machine->states[k].ancestors) && BIT_HAS(k, ctx->config)) { - if (USCXML_STATE_MASK(ctx->machine->states[k].type) == USCXML_STATE_FINAL) { - bit_and_not(tmp_states, ctx->machine->states[k].ancestors, nr_states_bytes); - } else { - BIT_SET_AT(k, tmp_states); - } - } - } - if unlikely(!bit_has_any(tmp_states, nr_states_bytes)) { - ctx->raise_done_event(ctx, &ctx->machine->states[j], NULL); - } - } - } - - } - - } - } - - return USCXML_ERR_OK; -} - -#define USCXML_NO_STEP_FUNCTION -#endif - diff --git a/test/src/test-c-machine.scxml.c b/test/src/test-c-machine.scxml.c index b75c6a5..4cfc37c 100644 --- a/test/src/test-c-machine.scxml.c +++ b/test/src/test-c-machine.scxml.c @@ -1,6 +1,6 @@ /** Generated from source: - file:///Users/sradomski/Documents/TK/Code/uscxml/test/w3c/ecma/test144.scxml + file:///Users/sradomski/Documents/TK/Code/uscxml2/test/w3c/lua/test240.scxml */ #ifndef USCXML_NO_STDTYPES_H @@ -208,7 +208,7 @@ struct uscxml_machine { }; /** - * All information pertaining to a <data> element. + * All information pertaining to a <data> element-> * With late data binding, blocks of data elements are separated by NULL * use USCXML_ELEM_DATA_IS_SET to test for end of a block. */ @@ -220,7 +220,7 @@ struct uscxml_elem_data { }; /** - * All information pertaining to an <assign> element. + * All information pertaining to an <assign> element-> */ struct uscxml_elem_assign { const char* location; @@ -229,7 +229,7 @@ struct uscxml_elem_assign { }; /** - * All information pertaining to any state element. + * All information pertaining to any state element-> */ struct uscxml_state { const char* name; /* eventual name */ @@ -237,30 +237,30 @@ struct uscxml_state { const exec_content_t on_entry; /* on entry handlers */ const exec_content_t on_exit; /* on exit handlers */ const invoke_t invoke; /* invocations */ - const char children[USCXML_MAX_NR_STATES_BYTES]; /* all children */ - const char completion[USCXML_MAX_NR_STATES_BYTES]; /* default completion */ - const char ancestors[USCXML_MAX_NR_STATES_BYTES]; /* all ancestors */ + const unsigned char children[USCXML_MAX_NR_STATES_BYTES]; /* all children */ + const unsigned char completion[USCXML_MAX_NR_STATES_BYTES]; /* default completion */ + const unsigned char ancestors[USCXML_MAX_NR_STATES_BYTES]; /* all ancestors */ const uscxml_elem_data* data; /* data with late binding */ const unsigned char type; /* One of USCXML_STATE_* */ }; /** - * All information pertaining to a <transitions> element. + * All information pertaining to a <transitions> element-> */ struct uscxml_transition { const USCXML_NR_STATES_TYPE source; - const char target[USCXML_MAX_NR_STATES_BYTES]; + const unsigned char target[USCXML_MAX_NR_STATES_BYTES]; const char* event; const char* condition; const is_enabled_t is_enabled; const exec_content_t on_transition; const unsigned char type; - const char conflicts[USCXML_MAX_NR_TRANS_BYTES]; - const char exit_set[USCXML_MAX_NR_STATES_BYTES]; + const unsigned char conflicts[USCXML_MAX_NR_TRANS_BYTES]; + const unsigned char exit_set[USCXML_MAX_NR_STATES_BYTES]; }; /** - * All information pertaining to a <foreach> element. + * All information pertaining to a <foreach> element-> */ struct uscxml_elem_foreach { const char* array; @@ -269,7 +269,7 @@ struct uscxml_elem_foreach { }; /** - * All information pertaining to a <param> element. + * All information pertaining to a <param> element-> * Blocks of params are separated by NULL params, use * USCXML_ELEM_PARAM_IS_SET to test for end of a block. */ @@ -280,7 +280,7 @@ struct uscxml_elem_param { }; /** - * All information pertaining to a <donedata> element. + * All information pertaining to a <donedata> element-> */ struct uscxml_elem_donedata { const USCXML_NR_STATES_TYPE source; @@ -290,7 +290,7 @@ struct uscxml_elem_donedata { }; /** - * All information pertaining to an <invoke> element. + * All information pertaining to an <invoke> element-> */ struct uscxml_elem_invoke { const uscxml_machine* machine; @@ -310,7 +310,7 @@ struct uscxml_elem_invoke { }; /** - * All information pertaining to a <send> element. + * All information pertaining to a <send> element-> */ struct uscxml_elem_send { const char* event; @@ -336,10 +336,10 @@ struct uscxml_ctx { unsigned char flags; const uscxml_machine* machine; - char config[USCXML_MAX_NR_STATES_BYTES]; /* Make sure these macros specify a sufficient size */ - char history[USCXML_MAX_NR_STATES_BYTES]; - char invocations[USCXML_MAX_NR_STATES_BYTES]; - char initialized_data[USCXML_MAX_NR_STATES_BYTES]; + unsigned char config[USCXML_MAX_NR_STATES_BYTES]; /* Make sure these macros specify a sufficient size */ + unsigned char history[USCXML_MAX_NR_STATES_BYTES]; + unsigned char invocations[USCXML_MAX_NR_STATES_BYTES]; + unsigned char initialized_data[USCXML_MAX_NR_STATES_BYTES]; void* user_data; void* event; @@ -368,11 +368,44 @@ struct uscxml_ctx { #endif /* forward declare machines to allow references */ -extern const uscxml_machine _uscxml_7B67993D_machine; +extern const uscxml_machine _uscxml_F2DFDF85_machine; +extern const uscxml_machine _uscxml_88325DE6_machine; +extern const uscxml_machine _uscxml_8B0504D7_machine; #ifndef USCXML_NO_ELEM_INFO -static const uscxml_elem_donedata _uscxml_7B67993D_elem_donedatas[1] = { +static const uscxml_elem_data _uscxml_F2DFDF85_elem_datas[2] = { + /* id, src, expr, content */ + { "Var1", NULL, "1", NULL }, + { NULL, NULL, NULL, NULL } +}; + +static const uscxml_elem_param _uscxml_F2DFDF85_elem_params[2] = { + /* name, expr, location */ + { "Var1", "1", NULL }, + { NULL, NULL, NULL } +}; + +static const uscxml_elem_send _uscxml_F2DFDF85_elem_sends[1] = { + { + /* event */ "timeout", + /* eventexpr */ NULL, + /* target */ NULL, + /* targetexpr */ NULL, + /* type */ NULL, + /* typeexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* delay */ "2000", + /* delayexpr */ NULL, + /* namelist */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + /* params */ NULL + } +}; + +static const uscxml_elem_donedata _uscxml_F2DFDF85_elem_donedatas[1] = { /* source, content, contentexpr, params */ { 0, NULL, NULL, NULL } }; @@ -381,31 +414,71 @@ static const uscxml_elem_donedata _uscxml_7B67993D_elem_donedatas[1] = { #ifndef USCXML_NO_ELEM_INFO +static const uscxml_elem_invoke _uscxml_F2DFDF85_elem_invokes[2] = { + { + /* machine */ &_uscxml_88325DE6_machine, + /* type */ "http://www.w3.org/TR/scxml/", + /* typeexpr */ NULL, + /* src */ NULL, + /* srcexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* sourcename */ "s01", + /* namelist */ "Var1", + /* autoforward */ 0, + /* params */ NULL, + /* finalize */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + }, + { + /* machine */ &_uscxml_8B0504D7_machine, + /* type */ "http://www.w3.org/TR/scxml/", + /* typeexpr */ NULL, + /* src */ NULL, + /* srcexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* sourcename */ "s02", + /* namelist */ NULL, + /* autoforward */ 0, + /* params */ &_uscxml_F2DFDF85_elem_params[0], + /* finalize */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + } +}; + #endif #ifndef USCXML_NO_EXEC_CONTENT -static int _uscxml_7B67993D_s0_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { +static int _uscxml_F2DFDF85_s0_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { int err = USCXML_ERR_OK; - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "foo")) != USCXML_ERR_OK) return err; - } else { - return USCXML_ERR_MISSING_CALLBACK; - } - if likely(ctx->exec_content_raise != NULL) { - if unlikely((ctx->exec_content_raise(ctx, "bar")) != USCXML_ERR_OK) return err; + if likely(ctx->exec_content_send != NULL) { + if ((ctx->exec_content_send(ctx, &_uscxml_F2DFDF85_elem_sends[0])) != USCXML_ERR_OK) return err; } else { return USCXML_ERR_MISSING_CALLBACK; } return USCXML_ERR_OK; } -static int _uscxml_7B67993D_s0_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - _uscxml_7B67993D_s0_on_entry_0(ctx, state, event); +static int _uscxml_F2DFDF85_s0_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + _uscxml_F2DFDF85_s0_on_entry_0(ctx, state, event); + return USCXML_ERR_OK; +} + +static int _uscxml_F2DFDF85_s01_invoke(const uscxml_ctx* ctx, const uscxml_state* s, const uscxml_elem_invoke* invocation, unsigned char uninvoke) { + ctx->invoke(ctx, s, &_uscxml_F2DFDF85_elem_invokes[0], uninvoke); + return USCXML_ERR_OK; } +static int _uscxml_F2DFDF85_s02_invoke(const uscxml_ctx* ctx, const uscxml_state* s, const uscxml_elem_invoke* invocation, unsigned char uninvoke) { + ctx->invoke(ctx, s, &_uscxml_F2DFDF85_elem_invokes[1], uninvoke); -static int _uscxml_7B67993D_pass_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + return USCXML_ERR_OK; +} +static int _uscxml_F2DFDF85_pass_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { int err = USCXML_ERR_OK; if likely(ctx->exec_content_log != NULL) { if unlikely((ctx->exec_content_log(ctx, "Outcome", "'pass'")) != USCXML_ERR_OK) return err; @@ -415,12 +488,12 @@ static int _uscxml_7B67993D_pass_on_entry_0(const uscxml_ctx* ctx, const uscxml_ return USCXML_ERR_OK; } -static int _uscxml_7B67993D_pass_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - _uscxml_7B67993D_pass_on_entry_0(ctx, state, event); +static int _uscxml_F2DFDF85_pass_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + _uscxml_F2DFDF85_pass_on_entry_0(ctx, state, event); return USCXML_ERR_OK; } -static int _uscxml_7B67993D_fail_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { +static int _uscxml_F2DFDF85_fail_on_entry_0(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { int err = USCXML_ERR_OK; if likely(ctx->exec_content_log != NULL) { if unlikely((ctx->exec_content_log(ctx, "Outcome", "'fail'")) != USCXML_ERR_OK) return err; @@ -430,8 +503,8 @@ static int _uscxml_7B67993D_fail_on_entry_0(const uscxml_ctx* ctx, const uscxml_ return USCXML_ERR_OK; } -static int _uscxml_7B67993D_fail_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { - _uscxml_7B67993D_fail_on_entry_0(ctx, state, event); +static int _uscxml_F2DFDF85_fail_on_entry(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + _uscxml_F2DFDF85_fail_on_entry_0(ctx, state, event); return USCXML_ERR_OK; } @@ -439,64 +512,76 @@ static int _uscxml_7B67993D_fail_on_entry(const uscxml_ctx* ctx, const uscxml_st #ifndef USCXML_NO_ELEM_INFO -static const uscxml_state _uscxml_7B67993D_states[5] = { +static const uscxml_state _uscxml_F2DFDF85_states[6] = { { /* state number 0 */ /* name */ NULL, /* parent */ 0, /* onentry */ NULL, /* onexit */ NULL, /* invoke */ NULL, - /* children */ { 0x1e /* 01111 */ }, - /* completion */ { 0x02 /* 01000 */ }, - /* ancestors */ { 0x00 /* 00000 */ }, - /* data */ NULL, + /* children */ { 0x32 /* 010011 */ }, + /* completion */ { 0x02 /* 010000 */ }, + /* ancestors */ { 0x00 /* 000000 */ }, + /* data */ &_uscxml_F2DFDF85_elem_datas[0], /* type */ USCXML_STATE_COMPOUND, }, { /* state number 1 */ /* name */ "s0", /* parent */ 0, - /* onentry */ _uscxml_7B67993D_s0_on_entry, + /* onentry */ _uscxml_F2DFDF85_s0_on_entry, /* onexit */ NULL, /* invoke */ NULL, - /* children */ { 0x00 /* 00000 */ }, - /* completion */ { 0x00 /* 00000 */ }, - /* ancestors */ { 0x01 /* 10000 */ }, + /* children */ { 0x0c /* 001100 */ }, + /* completion */ { 0x04 /* 001000 */ }, + /* ancestors */ { 0x01 /* 100000 */ }, /* data */ NULL, - /* type */ USCXML_STATE_ATOMIC, + /* type */ USCXML_STATE_COMPOUND, }, { /* state number 2 */ - /* name */ "s1", - /* parent */ 0, + /* name */ "s01", + /* parent */ 1, /* onentry */ NULL, /* onexit */ NULL, - /* invoke */ NULL, - /* children */ { 0x00 /* 00000 */ }, - /* completion */ { 0x00 /* 00000 */ }, - /* ancestors */ { 0x01 /* 10000 */ }, + /* invoke */ _uscxml_F2DFDF85_s01_invoke, + /* children */ { 0x00 /* 000000 */ }, + /* completion */ { 0x00 /* 000000 */ }, + /* ancestors */ { 0x03 /* 110000 */ }, /* data */ NULL, /* type */ USCXML_STATE_ATOMIC, }, { /* state number 3 */ + /* name */ "s02", + /* parent */ 1, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ _uscxml_F2DFDF85_s02_invoke, + /* children */ { 0x00 /* 000000 */ }, + /* completion */ { 0x00 /* 000000 */ }, + /* ancestors */ { 0x03 /* 110000 */ }, + /* data */ NULL, + /* type */ USCXML_STATE_ATOMIC, + }, + { /* state number 4 */ /* name */ "pass", /* parent */ 0, - /* onentry */ _uscxml_7B67993D_pass_on_entry, + /* onentry */ _uscxml_F2DFDF85_pass_on_entry, /* onexit */ NULL, /* invoke */ NULL, - /* children */ { 0x00 /* 00000 */ }, - /* completion */ { 0x00 /* 00000 */ }, - /* ancestors */ { 0x01 /* 10000 */ }, + /* children */ { 0x00 /* 000000 */ }, + /* completion */ { 0x00 /* 000000 */ }, + /* ancestors */ { 0x01 /* 100000 */ }, /* data */ NULL, /* type */ USCXML_STATE_FINAL, }, - { /* state number 4 */ + { /* state number 5 */ /* name */ "fail", /* parent */ 0, - /* onentry */ _uscxml_7B67993D_fail_on_entry, + /* onentry */ _uscxml_F2DFDF85_fail_on_entry, /* onexit */ NULL, /* invoke */ NULL, - /* children */ { 0x00 /* 00000 */ }, - /* completion */ { 0x00 /* 00000 */ }, - /* ancestors */ { 0x01 /* 10000 */ }, + /* children */ { 0x00 /* 000000 */ }, + /* completion */ { 0x00 /* 000000 */ }, + /* ancestors */ { 0x01 /* 100000 */ }, /* data */ NULL, /* type */ USCXML_STATE_FINAL, } @@ -506,58 +591,71 @@ static const uscxml_state _uscxml_7B67993D_states[5] = { #ifndef USCXML_NO_ELEM_INFO -static const uscxml_transition _uscxml_7B67993D_transitions[4] = { - { /* transition number 0 with priority 0 - target: s1 +static const uscxml_transition _uscxml_F2DFDF85_transitions[5] = { + { /* transition number 1 with priority 0 + target: s02 */ - /* source */ 1, - /* target */ { 0x04 /* 00100 */ }, - /* event */ "foo", + /* source */ 2, + /* target */ { 0x08 /* 000100 */ }, + /* event */ "success", /* condition */ NULL, /* is_enabled */ NULL, /* ontrans */ NULL, /* type */ 0, - /* conflicts */ { 0x0f /* 1111 */ }, - /* exit set */ { 0x1e /* 01111 */ } + /* conflicts */ { 0x1f /* 11111 */ }, + /* exit set */ { 0x0c /* 001100 */ } }, - { /* transition number 1 with priority 1 + { /* transition number 2 with priority 1 target: fail */ - /* source */ 1, - /* target */ { 0x10 /* 00001 */ }, - /* event */ "*", + /* source */ 2, + /* target */ { 0x20 /* 000001 */ }, + /* event */ "failure", /* condition */ NULL, /* is_enabled */ NULL, /* ontrans */ NULL, /* type */ 0, - /* conflicts */ { 0x0f /* 1111 */ }, - /* exit set */ { 0x1e /* 01111 */ } + /* conflicts */ { 0x1f /* 11111 */ }, + /* exit set */ { 0x3e /* 011111 */ } }, - { /* transition number 2 with priority 2 + { /* transition number 3 with priority 2 target: pass */ - /* source */ 2, - /* target */ { 0x08 /* 00010 */ }, - /* event */ "bar", + /* source */ 3, + /* target */ { 0x10 /* 000010 */ }, + /* event */ "success", /* condition */ NULL, /* is_enabled */ NULL, /* ontrans */ NULL, /* type */ 0, - /* conflicts */ { 0x0f /* 1111 */ }, - /* exit set */ { 0x1e /* 01111 */ } + /* conflicts */ { 0x1f /* 11111 */ }, + /* exit set */ { 0x3e /* 011111 */ } }, - { /* transition number 3 with priority 3 + { /* transition number 4 with priority 3 target: fail */ - /* source */ 2, - /* target */ { 0x10 /* 00001 */ }, - /* event */ "*", + /* source */ 3, + /* target */ { 0x20 /* 000001 */ }, + /* event */ "failure", + /* condition */ NULL, + /* is_enabled */ NULL, + /* ontrans */ NULL, + /* type */ 0, + /* conflicts */ { 0x1f /* 11111 */ }, + /* exit set */ { 0x3e /* 011111 */ } + }, + { /* transition number 0 with priority 4 + target: fail + */ + /* source */ 1, + /* target */ { 0x20 /* 000001 */ }, + /* event */ "timeout", /* condition */ NULL, /* is_enabled */ NULL, /* ontrans */ NULL, /* type */ 0, - /* conflicts */ { 0x0f /* 1111 */ }, - /* exit set */ { 0x1e /* 01111 */ } + /* conflicts */ { 0x1f /* 11111 */ }, + /* exit set */ { 0x3e /* 011111 */ } } }; @@ -566,21 +664,390 @@ static const uscxml_transition _uscxml_7B67993D_transitions[4] = { #ifndef USCXML_NO_ELEM_INFO #ifndef USCXML_MACHINE -# define USCXML_MACHINE _uscxml_7B67993D_machine +# define USCXML_MACHINE _uscxml_F2DFDF85_machine #endif -#define USCXML_MACHINE_0 _uscxml_7B67993D_machine +#define USCXML_MACHINE_0 _uscxml_F2DFDF85_machine +#define USCXML_MACHINE_TEST240_SCXML _uscxml_F2DFDF85_machine -const uscxml_machine _uscxml_7B67993D_machine = { +const uscxml_machine _uscxml_F2DFDF85_machine = { /* flags */ 0, - /* nr_states */ 5, - /* nr_transitions */ 4, - /* name */ "", - /* datamodel */ "ecmascript", - /* uuid */ "7B67993D8309FD356AECB23C2C98EE79", - /* states */ &_uscxml_7B67993D_states[0], - /* transitions */ &_uscxml_7B67993D_transitions[0], + /* nr_states */ 6, + /* nr_transitions */ 5, + /* name */ "test240.scxml", + /* datamodel */ "lua", + /* uuid */ "F2DFDF85E1407B6D03CC162B96F43FC7", + /* states */ &_uscxml_F2DFDF85_states[0], + /* transitions */ &_uscxml_F2DFDF85_transitions[0], /* parent */ NULL, - /* donedata */ &_uscxml_7B67993D_elem_donedatas[0], + /* donedata */ &_uscxml_F2DFDF85_elem_donedatas[0], + /* script */ NULL +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +static const uscxml_elem_data _uscxml_88325DE6_elem_datas[2] = { + /* id, src, expr, content */ + { "Var1", NULL, "0", NULL }, + { NULL, NULL, NULL, NULL } +}; + +static const uscxml_elem_send _uscxml_88325DE6_elem_sends[2] = { + { + /* event */ "success", + /* eventexpr */ NULL, + /* target */ "#_parent", + /* targetexpr */ NULL, + /* type */ NULL, + /* typeexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* delay */ NULL, + /* delayexpr */ NULL, + /* namelist */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + /* params */ NULL + }, + { + /* event */ "failure", + /* eventexpr */ NULL, + /* target */ "#_parent", + /* targetexpr */ NULL, + /* type */ NULL, + /* typeexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* delay */ NULL, + /* delayexpr */ NULL, + /* namelist */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + /* params */ NULL + } +}; + +static const uscxml_elem_donedata _uscxml_88325DE6_elem_donedatas[1] = { + /* source, content, contentexpr, params */ + { 0, NULL, NULL, NULL } +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +#endif + +#ifndef USCXML_NO_EXEC_CONTENT + +static int _uscxml_88325DE6_sub01_transition0_is_enabled(const uscxml_ctx* ctx, const uscxml_transition* transition) { + if likely(ctx->is_true != NULL) { + return (ctx->is_true(ctx, "Var1==1")); + } + return USCXML_ERR_MISSING_CALLBACK; +} +static int _uscxml_88325DE6_sub01_transition0_on_trans(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + int err = USCXML_ERR_OK; + if likely(ctx->exec_content_send != NULL) { + if ((ctx->exec_content_send(ctx, &_uscxml_88325DE6_elem_sends[0])) != USCXML_ERR_OK) return err; + } else { + return USCXML_ERR_MISSING_CALLBACK; + } + return USCXML_ERR_OK; +} + +static int _uscxml_88325DE6_sub01_transition1_on_trans(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + int err = USCXML_ERR_OK; + if likely(ctx->exec_content_send != NULL) { + if ((ctx->exec_content_send(ctx, &_uscxml_88325DE6_elem_sends[1])) != USCXML_ERR_OK) return err; + } else { + return USCXML_ERR_MISSING_CALLBACK; + } + return USCXML_ERR_OK; +} + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +static const uscxml_state _uscxml_88325DE6_states[3] = { + { /* state number 0 */ + /* name */ NULL, + /* parent */ 0, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ NULL, + /* children */ { 0x06 /* 011 */ }, + /* completion */ { 0x02 /* 010 */ }, + /* ancestors */ { 0x00 /* 000 */ }, + /* data */ &_uscxml_88325DE6_elem_datas[0], + /* type */ USCXML_STATE_COMPOUND, + }, + { /* state number 1 */ + /* name */ "sub01", + /* parent */ 0, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ NULL, + /* children */ { 0x00 /* 000 */ }, + /* completion */ { 0x00 /* 000 */ }, + /* ancestors */ { 0x01 /* 100 */ }, + /* data */ NULL, + /* type */ USCXML_STATE_ATOMIC, + }, + { /* state number 2 */ + /* name */ "subFinal1", + /* parent */ 0, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ NULL, + /* children */ { 0x00 /* 000 */ }, + /* completion */ { 0x00 /* 000 */ }, + /* ancestors */ { 0x01 /* 100 */ }, + /* data */ NULL, + /* type */ USCXML_STATE_FINAL, + } +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +static const uscxml_transition _uscxml_88325DE6_transitions[2] = { + { /* transition number 0 with priority 0 + target: subFinal1 + */ + /* source */ 1, + /* target */ { 0x04 /* 001 */ }, + /* event */ NULL, + /* condition */ "Var1==1", + /* is_enabled */ _uscxml_88325DE6_sub01_transition0_is_enabled, + /* ontrans */ _uscxml_88325DE6_sub01_transition0_on_trans, + /* type */ USCXML_TRANS_SPONTANEOUS, + /* conflicts */ { 0x03 /* 11 */ }, + /* exit set */ { 0x06 /* 011 */ } + }, + { /* transition number 1 with priority 1 + target: subFinal1 + */ + /* source */ 1, + /* target */ { 0x04 /* 001 */ }, + /* event */ NULL, + /* condition */ NULL, + /* is_enabled */ NULL, + /* ontrans */ _uscxml_88325DE6_sub01_transition1_on_trans, + /* type */ USCXML_TRANS_SPONTANEOUS, + /* conflicts */ { 0x03 /* 11 */ }, + /* exit set */ { 0x06 /* 011 */ } + } +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +#ifndef USCXML_MACHINE +# define USCXML_MACHINE _uscxml_88325DE6_machine +#endif +#define USCXML_MACHINE_1 _uscxml_88325DE6_machine +#define USCXML_MACHINE_TEST240_SCXML_S01_INVOKE0_CONTENT0_SCXML0 _uscxml_88325DE6_machine + +const uscxml_machine _uscxml_88325DE6_machine = { + /* flags */ 0, + /* nr_states */ 3, + /* nr_transitions */ 2, + /* name */ "test240.scxml.s01_invoke0_content0_scxml0", + /* datamodel */ "lua", + /* uuid */ "88325DE699193976BBBCF380C181A014", + /* states */ &_uscxml_88325DE6_states[0], + /* transitions */ &_uscxml_88325DE6_transitions[0], + /* parent */ &_uscxml_F2DFDF85_machine, + /* donedata */ &_uscxml_88325DE6_elem_donedatas[0], + /* script */ NULL +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +static const uscxml_elem_data _uscxml_8B0504D7_elem_datas[2] = { + /* id, src, expr, content */ + { "Var1", NULL, "0", NULL }, + { NULL, NULL, NULL, NULL } +}; + +static const uscxml_elem_send _uscxml_8B0504D7_elem_sends[2] = { + { + /* event */ "success", + /* eventexpr */ NULL, + /* target */ "#_parent", + /* targetexpr */ NULL, + /* type */ NULL, + /* typeexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* delay */ NULL, + /* delayexpr */ NULL, + /* namelist */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + /* params */ NULL + }, + { + /* event */ "failure", + /* eventexpr */ NULL, + /* target */ "#_parent", + /* targetexpr */ NULL, + /* type */ NULL, + /* typeexpr */ NULL, + /* id */ NULL, + /* idlocation */ NULL, + /* delay */ NULL, + /* delayexpr */ NULL, + /* namelist */ NULL, + /* content */ NULL, + /* contentexpr */ NULL, + /* params */ NULL + } +}; + +static const uscxml_elem_donedata _uscxml_8B0504D7_elem_donedatas[1] = { + /* source, content, contentexpr, params */ + { 0, NULL, NULL, NULL } +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +#endif + +#ifndef USCXML_NO_EXEC_CONTENT + +static int _uscxml_8B0504D7_sub02_transition0_is_enabled(const uscxml_ctx* ctx, const uscxml_transition* transition) { + if likely(ctx->is_true != NULL) { + return (ctx->is_true(ctx, "Var1==1")); + } + return USCXML_ERR_MISSING_CALLBACK; +} +static int _uscxml_8B0504D7_sub02_transition0_on_trans(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + int err = USCXML_ERR_OK; + if likely(ctx->exec_content_send != NULL) { + if ((ctx->exec_content_send(ctx, &_uscxml_8B0504D7_elem_sends[0])) != USCXML_ERR_OK) return err; + } else { + return USCXML_ERR_MISSING_CALLBACK; + } + return USCXML_ERR_OK; +} + +static int _uscxml_8B0504D7_sub02_transition1_on_trans(const uscxml_ctx* ctx, const uscxml_state* state, const void* event) { + int err = USCXML_ERR_OK; + if likely(ctx->exec_content_send != NULL) { + if ((ctx->exec_content_send(ctx, &_uscxml_8B0504D7_elem_sends[1])) != USCXML_ERR_OK) return err; + } else { + return USCXML_ERR_MISSING_CALLBACK; + } + return USCXML_ERR_OK; +} + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +static const uscxml_state _uscxml_8B0504D7_states[3] = { + { /* state number 0 */ + /* name */ NULL, + /* parent */ 0, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ NULL, + /* children */ { 0x06 /* 011 */ }, + /* completion */ { 0x02 /* 010 */ }, + /* ancestors */ { 0x00 /* 000 */ }, + /* data */ &_uscxml_8B0504D7_elem_datas[0], + /* type */ USCXML_STATE_COMPOUND, + }, + { /* state number 1 */ + /* name */ "sub02", + /* parent */ 0, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ NULL, + /* children */ { 0x00 /* 000 */ }, + /* completion */ { 0x00 /* 000 */ }, + /* ancestors */ { 0x01 /* 100 */ }, + /* data */ NULL, + /* type */ USCXML_STATE_ATOMIC, + }, + { /* state number 2 */ + /* name */ "subFinal2", + /* parent */ 0, + /* onentry */ NULL, + /* onexit */ NULL, + /* invoke */ NULL, + /* children */ { 0x00 /* 000 */ }, + /* completion */ { 0x00 /* 000 */ }, + /* ancestors */ { 0x01 /* 100 */ }, + /* data */ NULL, + /* type */ USCXML_STATE_FINAL, + } +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +static const uscxml_transition _uscxml_8B0504D7_transitions[2] = { + { /* transition number 0 with priority 0 + target: subFinal2 + */ + /* source */ 1, + /* target */ { 0x04 /* 001 */ }, + /* event */ NULL, + /* condition */ "Var1==1", + /* is_enabled */ _uscxml_8B0504D7_sub02_transition0_is_enabled, + /* ontrans */ _uscxml_8B0504D7_sub02_transition0_on_trans, + /* type */ USCXML_TRANS_SPONTANEOUS, + /* conflicts */ { 0x03 /* 11 */ }, + /* exit set */ { 0x06 /* 011 */ } + }, + { /* transition number 1 with priority 1 + target: subFinal2 + */ + /* source */ 1, + /* target */ { 0x04 /* 001 */ }, + /* event */ NULL, + /* condition */ NULL, + /* is_enabled */ NULL, + /* ontrans */ _uscxml_8B0504D7_sub02_transition1_on_trans, + /* type */ USCXML_TRANS_SPONTANEOUS, + /* conflicts */ { 0x03 /* 11 */ }, + /* exit set */ { 0x06 /* 011 */ } + } +}; + +#endif + +#ifndef USCXML_NO_ELEM_INFO + +#ifndef USCXML_MACHINE +# define USCXML_MACHINE _uscxml_8B0504D7_machine +#endif +#define USCXML_MACHINE_2 _uscxml_8B0504D7_machine +#define USCXML_MACHINE_TEST240_SCXML_S02_INVOKE0_CONTENT0_SCXML0 _uscxml_8B0504D7_machine + +const uscxml_machine _uscxml_8B0504D7_machine = { + /* flags */ 0, + /* nr_states */ 3, + /* nr_transitions */ 2, + /* name */ "test240.scxml.s02_invoke0_content0_scxml0", + /* datamodel */ "lua", + /* uuid */ "8B0504D789C25925F9E8A0C290F83773", + /* states */ &_uscxml_8B0504D7_states[0], + /* transitions */ &_uscxml_8B0504D7_transitions[0], + /* parent */ &_uscxml_F2DFDF85_machine, + /* donedata */ &_uscxml_8B0504D7_elem_donedatas[0], /* script */ NULL }; @@ -590,7 +1057,7 @@ const uscxml_machine _uscxml_7B67993D_machine = { /** * Print name of states contained in a (debugging). */ -static void printStateNames(const uscxml_ctx* ctx, const char* a, size_t length) { +static void printStateNames(const uscxml_ctx* ctx, const unsigned char* a, size_t length) { size_t i; const char* seperator = ""; for (i = 0; i < length; i++) { @@ -605,7 +1072,7 @@ static void printStateNames(const uscxml_ctx* ctx, const char* a, size_t length) /** * Print bits set in a in a binary representation (debugging). */ -static void printBitsetIndices(const char* a, size_t length) { +static void printBitsetIndices(const unsigned char* a, size_t length) { size_t i; const char* seperator = ""; for (i = 0; i < length; i++) { @@ -622,7 +1089,7 @@ static void printBitsetIndices(const char* a, size_t length) { /** * Return true if there is a common bit in a and b. */ -static int bit_has_and(const char* a, const char* b, size_t i) { +static int bit_has_and(const unsigned char* a, const unsigned char* b, size_t i) { while(i--) { if (a[i] & b[i]) return 1; @@ -634,7 +1101,7 @@ static int bit_has_and(const char* a, const char* b, size_t i) { * Set all bits to 0, this corresponds to memset(a, 0, i), * but does not require string.h or cstring. */ -static void bit_clear_all(char* a, size_t i) { +static void bit_clear_all(unsigned char* a, size_t i) { while(i--) { a[i] = 0; } @@ -643,7 +1110,7 @@ static void bit_clear_all(char* a, size_t i) { /** * Return true if there is any bit set in a. */ -static int bit_has_any(const char* a, size_t i) { +static int bit_has_any(unsigned const char* a, size_t i) { while(i--) { if (a[i] > 0) return 1; @@ -654,7 +1121,7 @@ static int bit_has_any(const char* a, size_t i) { /** * Set all bits from given mask in dest, this is |= for bit arrays. */ -static void bit_or(char* dest, const char* mask, size_t i) { +static void bit_or(unsigned char* dest, const unsigned char* mask, size_t i) { while(i--) { dest[i] |= mask[i]; } @@ -664,7 +1131,7 @@ static void bit_or(char* dest, const char* mask, size_t i) { * Copy all bits from source to dest, this corresponds to memcpy(a, b, i), * but does not require string.h or cstring. */ -static void bit_copy(char* dest, const char* source, size_t i) { +static void bit_copy(unsigned char* dest, const unsigned char* source, size_t i) { while(i--) { dest[i] = source[i]; } @@ -673,7 +1140,7 @@ static void bit_copy(char* dest, const char* source, size_t i) { /** * Unset bits from mask in dest. */ -static void bit_and_not(char* dest, const char* mask, size_t i) { +static void bit_and_not(unsigned char* dest, const unsigned char* mask, size_t i) { while(i--) { dest[i] &= ~mask[i]; } @@ -682,7 +1149,7 @@ static void bit_and_not(char* dest, const char* mask, size_t i) { /** * Set bits from mask in dest. */ -static void bit_and(char* dest, const char* mask, size_t i) { +static void bit_and(unsigned char* dest, const unsigned char* mask, size_t i) { while(i--) { dest[i] &= mask[i]; }; @@ -698,12 +1165,12 @@ int uscxml_step(uscxml_ctx* ctx) { USCXML_NR_STATES_TYPE nr_states_bytes = ((USCXML_NUMBER_STATES + 7) & ~7) >> 3; USCXML_NR_TRANS_TYPE nr_trans_bytes = ((USCXML_NUMBER_TRANS + 7) & ~7) >> 3; int err = USCXML_ERR_OK; - char conflicts [USCXML_MAX_NR_TRANS_BYTES]; - char trans_set [USCXML_MAX_NR_TRANS_BYTES]; - char target_set [USCXML_MAX_NR_STATES_BYTES]; - char exit_set [USCXML_MAX_NR_STATES_BYTES]; - char entry_set [USCXML_MAX_NR_STATES_BYTES]; - char tmp_states [USCXML_MAX_NR_STATES_BYTES]; + unsigned char conflicts [USCXML_MAX_NR_TRANS_BYTES]; + unsigned char trans_set [USCXML_MAX_NR_TRANS_BYTES]; + unsigned char target_set [USCXML_MAX_NR_STATES_BYTES]; + unsigned char exit_set [USCXML_MAX_NR_STATES_BYTES]; + unsigned char entry_set [USCXML_MAX_NR_STATES_BYTES]; + unsigned char tmp_states [USCXML_MAX_NR_STATES_BYTES]; #ifdef USCXML_VERBOSE printf("Config: "); @@ -744,6 +1211,7 @@ int uscxml_step(uscxml_ctx* ctx) { goto ESTABLISH_ENTRY_SET; } +DEQUEUE_EVENT: if (ctx->flags & USCXML_CTX_SPONTANEOUS) { ctx->event = NULL; goto SELECT_TRANSITIONS; @@ -794,7 +1262,8 @@ SELECT_TRANSITIONS: (USCXML_GET_TRANS(i).event != NULL && ctx->event != NULL)) { /* is it enabled? */ if ((ctx->event == NULL || ctx->is_matched(ctx, &USCXML_GET_TRANS(i), ctx->event) > 0) && - (USCXML_GET_TRANS(i).condition == NULL || USCXML_GET_TRANS(i).is_enabled(ctx, &USCXML_GET_TRANS(i)) > 0)) { + (USCXML_GET_TRANS(i).condition == NULL || + USCXML_GET_TRANS(i).is_enabled(ctx, &USCXML_GET_TRANS(i)) > 0)) { /* remember that we found a transition */ ctx->flags |= USCXML_CTX_TRANSITION_FOUND; @@ -820,6 +1289,7 @@ SELECT_TRANSITIONS: ctx->flags &= ~USCXML_CTX_TRANSITION_FOUND; } else { ctx->flags &= ~USCXML_CTX_SPONTANEOUS; + goto DEQUEUE_EVENT; } #ifdef USCXML_VERBOSE diff --git a/test/src/test-cmdline-parsing.cpp b/test/src/test-cmdline-parsing.cpp deleted file mode 100644 index edf90bc..0000000 --- a/test/src/test-cmdline-parsing.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/Interpreter.h" -#include <glog/logging.h> - -#include <boost/algorithm/string.hpp> - -int main(int argc, char** argv) { - using namespace uscxml; - - if (true) { - int testArgc = 10; - const char* testArgv[] = { - "test-cmdline-parsing", - "--verbose", - "--port=80", - "--ssl-port=8080", - "--certificate=/foo/bar.pem", - "--private-key=/foo/bar.priv", - "--public-key=/foo/bar.pub", - "--plugin-path=/foo/plugins", - "--loglevel=10", - "--disable-http", - 0 - }; - InterpreterOptions options = InterpreterOptions::fromCmdLine(testArgc, (char **)testArgv); - assert(options.verbose); - assert(options.httpPort == 80); - assert(options.httpsPort == 8080); - assert(boost::equals(options.certificate, "/foo/bar.pem")); - assert(boost::equals(options.privateKey, "/foo/bar.priv")); - assert(boost::equals(options.publicKey, "/foo/bar.pub")); - assert(boost::equals(options.pluginPath, "/foo/plugins")); - assert(options.logLevel == 10); - assert(!options.withHTTP); - assert(!options); // invalid as no SCXML document is given - } - - if (true) { - int testArgc = 3; - const char* testArgv[] = { - "test-cmdline-parsing", - "--verbose", - "/foo/bar.scxml", - 0 - }; - InterpreterOptions options = InterpreterOptions::fromCmdLine(testArgc, (char **)testArgv); - assert(options); - assert(options.verbose); - assert(options.interpreters.size() == 1); - assert(options.interpreters.front().first == "/foo/bar.scxml"); - } - - if (true) { - int testArgc = 7; - const char* testArgv[] = { - "test-cmdline-parsing", - "--port=80", - "/foo/bar1.scxml", - "--disable-http", - "/foo/bar2.scxml", - "/foo/bar3.scxml", - "--disable-http", - 0 - }; - InterpreterOptions options = InterpreterOptions::fromCmdLine(testArgc, (char **)testArgv); - assert(options); - assert(options.httpPort == 80); - assert(options.interpreters.size() == 3); - assert(options.interpreters[0].first == "/foo/bar1.scxml"); - assert(options.interpreters[1].first == "/foo/bar2.scxml"); - assert(options.interpreters[2].first == "/foo/bar3.scxml"); - - assert(!options.interpreters[0].second->withHTTP); - assert(options.interpreters[1].second->withHTTP); - assert(!options.interpreters[2].second->withHTTP); - } - - if (true) { - int testArgc = 5; - const char* testArgv[] = { - "test-cmdline-parsing", - "--port=80", - "/foo/bar1.scxml", - "--vrml-path=/foo/bar.test", - "--tmp-path=/foo/bar.test", - 0 - }; - InterpreterOptions options = InterpreterOptions::fromCmdLine(testArgc, (char **)testArgv); - assert(options); - assert(options.httpPort == 80); - assert(options.interpreters.size() == 1); - assert(options.interpreters[0].first == "/foo/bar1.scxml"); - - assert(options.interpreters[0].second->additionalParameters.find("vrml-path") - != options.interpreters[0].second->additionalParameters.end()); - assert(options.interpreters[0].second->additionalParameters.find("tmp-path") - != options.interpreters[0].second->additionalParameters.end()); - } - - return EXIT_SUCCESS; -}
\ No newline at end of file diff --git a/test/src/test-datamodel.cpp b/test/src/test-datamodel.cpp deleted file mode 100644 index 0c02ae8..0000000 --- a/test/src/test-datamodel.cpp +++ /dev/null @@ -1,527 +0,0 @@ -#include "uscxml/URL.h" -#include "uscxml/Message.h" -#include "uscxml/Interpreter.h" -#include "uscxml/Factory.h" -#include "uscxml/server/HTTPServer.h" - -#include <SAX/helpers/InputSourceResolver.hpp> - -#include <assert.h> -#include <boost/algorithm/string.hpp> -#include <iostream> - -using namespace uscxml; -using namespace boost; - -class TestDataModelExtension : public DataModelExtension { -public: - TestDataModelExtension() {} - - std::string provides() { - return "_x.platform.pool"; - } - - Data getValueOf(const std::string& member) { - return Data(true); - } - - void setValueOf(const std::string& member, const Data& data) { - std::cout << "Setting " << member << " to " << std::endl << Data::toJSON(data); - } -}; - -int main(int argc, char** argv) { -#ifdef _WIN32 - WSADATA wsaData; - WSAStartup(MAKEWORD(2, 2), &wsaData); -#endif - - { - char* testData = (char*)malloc(1024); - for (size_t i = 0; i < 1024; i++) { - testData[i] = (char)i; - } - - Data data(testData, 1024, "", false); - Blob blob = data.getBinary(); - char* otherData = blob.getData(); - - for (size_t i = 0; i < 1024; i++) { - assert(testData[i] == otherData[i]); - } - - } - - Interpreter interpreter = Interpreter::fromXML("<scxml></scxml>", ""); - DataModel dm(Factory::getInstance()->createDataModel("ecmascript", interpreter.getImpl().get())); - dm.evalAsString("var foo = 12"); - - // TypedArray tests - // taken from https://bitbucket.org/lindenlab/llsd/src/ - { - - dm.evalAsBool("var a;"); - - dm.evalAsBool("Int8Array.BYTES_PER_ELEMENT == 1"); - dm.evalAsBool("a = new Int8Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 1;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 8;")); - - dm.evalAsBool("Uint8Array.BYTES_PER_ELEMENT == 1"); - dm.evalAsBool("a = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 1;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 8;")); - - dm.evalAsBool("Int16Array.BYTES_PER_ELEMENT == 2"); - dm.evalAsBool("a = new Int16Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 2;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 16;")); - - dm.evalAsBool("Uint16Array.BYTES_PER_ELEMENT == 2"); - dm.evalAsBool("a = new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 2;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 16;")); - - dm.evalAsBool("Int32Array.BYTES_PER_ELEMENT == 4"); - dm.evalAsBool("a = new Int32Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 4;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 32;")); - - dm.evalAsBool("Uint32Array.BYTES_PER_ELEMENT == 4"); - dm.evalAsBool("a = new Uint32Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 4;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 32;")); - - dm.evalAsBool("Float32Array.BYTES_PER_ELEMENT == 4"); - dm.evalAsBool("a = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 4;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 32;")); - - dm.evalAsBool("Float64Array.BYTES_PER_ELEMENT == 8"); - dm.evalAsBool("a = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8]);"); - assert(dm.evalAsBool("a.BYTES_PER_ELEMENT == 8;")); - assert(dm.evalAsBool("a.byteOffset == 0;")); - assert(dm.evalAsBool("a.byteLength == 64;")); - - } - - // ArrayBufferView - { - dm.evalAsBool("var ab = new ArrayBuffer(48);"); - dm.evalAsBool("var i32 = new Int32Array(ab, 16);"); - dm.evalAsBool("i32.set([1, 2, 3, 4, 5, 6, 7, 8]);"); - -// assert(dm.evalAsBool("i32.buffer == ab;")); - assert(dm.evalAsBool("i32.byteOffset == 16;")); - assert(dm.evalAsBool("i32.byteLength == 32;")); - - dm.evalAsBool("var da = new DataView(i32.buffer, 8);"); -// assert(dm.evalAsBool("da.buffer == ab;")); - assert(dm.evalAsBool("da.byteOffset == 8;")); - assert(dm.evalAsBool("da.byteLength == 40;")); - - } - - // TypedArray constructors - { - assert(dm.evalAsBool("new Int8Array([0, 0, 0]).length == 3")); - dm.evalAsBool("var rawbuf = (new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7])).buffer"); - - dm.evalAsBool("var int8 = new Int8Array(4);"); - assert(dm.evalAsBool("int8.BYTES_PER_ELEMENT == 1;")); - assert(dm.evalAsBool("int8.length == 4;")); - assert(dm.evalAsBool("int8.byteLength == 4;")); - assert(dm.evalAsBool("int8.byteOffset == 0;")); -// assert(dm.evalAsBool("int8.get(-1) == undefined;")); -// assert(dm.evalAsBool("int8.get(4) == undefined;")); - - dm.evalAsBool("var int8 = new Int8Array([1, 2, 3, 4, 5, 6]);"); - assert(dm.evalAsBool("int8.length == 6;")); - assert(dm.evalAsBool("int8.byteLength == 6;")); - assert(dm.evalAsBool("int8.byteOffset == 0;")); - assert(dm.evalAsBool("int8.get(3) == 4")); - // assert(dm.evalAsBool("int8.get(-1) == undefined;")); - // assert(dm.evalAsBool("int8.get(6) == undefined;")); - - dm.evalAsBool("var int8 = new Int8Array(rawbuf, 2);"); - assert(dm.evalAsBool("int8.length == 6;")); - assert(dm.evalAsBool("int8.byteLength == 6;")); - assert(dm.evalAsBool("int8.byteOffset == 2;")); - assert(dm.evalAsBool("int8.get(5) == 7")); - dm.evalAsBool("int8.set(0, 112)"); - assert(dm.evalAsBool("int8.get(0) == 112")); - // assert(dm.evalAsBool("int8.get(-1) == undefined;")); - // assert(dm.evalAsBool("int8.get(6) == undefined;")); - - dm.evalAsBool("var int8 = new Int8Array(rawbuf, 8);"); - assert(dm.evalAsBool("int8.length == 0;")); - - dm.evalAsBool("var int8 = new Int8Array(rawbuf, 2, 4);"); - assert(dm.evalAsBool("int8.length == 4;")); - assert(dm.evalAsBool("int8.byteLength == 4;")); - assert(dm.evalAsBool("int8.byteOffset == 2;")); - assert(dm.evalAsBool("int8.get(3) == 5")); - dm.evalAsBool("int8.set(0, 113)"); - assert(dm.evalAsBool("int8.get(0) == 113")); - // assert(dm.evalAsBool("int8.get(-1) == undefined;")); - // assert(dm.evalAsBool("int8.get(4) == undefined;")); - - } - - // TypedArray conversions - { - dm.evalAsBool("\ - function checkArray(typed_array, test) {\ - if(typed_array.length != test.length) { return false; }\ - for (var i = 0; i < test.length; i += 1) {\ - if(typed_array.get(i) != test[i]) { print(\"index \" + i + \": \" + typed_array.get(i) + \" != \" + test[i]); return false; }\ - }\ - return true;\ - }\ - "); - - dm.evalAsBool("var uint8 = new Uint8Array([1, 2, 3, 4]);"); - dm.evalAsBool("var uint16 = new Uint16Array(uint8.buffer);"); - dm.evalAsBool("var uint32 = new Uint32Array(uint8.buffer);"); - - assert(dm.evalAsBool("checkArray(uint8, [1, 2, 3, 4]);")); - dm.evalAsBool("uint16.set(0, 0xffff);"); - assert(dm.evalAsBool("checkArray(uint8, [0xff, 0xff, 3, 4]);")); - dm.evalAsBool("uint16.set(1, 0xeeee);"); - assert(dm.evalAsBool("checkArray(uint8, [0xff, 0xff, 0xee, 0xee]);")); - dm.evalAsBool("uint32.set(0, 0x11111111);"); - assert(dm.evalAsBool("uint16.get(0) == 0x1111;")); - assert(dm.evalAsBool("uint16.get(1) == 0x1111;")); - assert(dm.evalAsBool("checkArray(uint8, [0x11, 0x11, 0x11, 0x11]);")); - - } - - // TypedArray signed/unsigned conversions - { - dm.evalAsBool("var int8 = new Int8Array(1)"); - dm.evalAsBool("var uint8 = new Uint8Array(int8.buffer);"); - dm.evalAsBool("uint8.set(0, 123);"); - assert(dm.evalAsBool("int8.get(0) == 123;")); - dm.evalAsBool("uint8.set(0, 161);"); - assert(dm.evalAsBool("int8.get(0) == -95;")); - dm.evalAsBool("int8.set(0, -120);"); - assert(dm.evalAsBool("uint8.get(0) == 136;")); - dm.evalAsBool("int8.set(0, -1);"); - assert(dm.evalAsBool("uint8.get(0) == 0xff;")); - - dm.evalAsBool("var int16 = new Int16Array(1)"); - dm.evalAsBool("uint16 = new Uint16Array(int16.buffer);"); - dm.evalAsBool("uint16.set(0, 3210);"); - assert(dm.evalAsBool("int16.get(0) == 3210;")); - dm.evalAsBool("uint16.set(0, 49232);"); - assert(dm.evalAsBool("int16.get(0), -16304;")); - dm.evalAsBool("int16.set(0, -16384);"); - assert(dm.evalAsBool("uint16.get(0) == 49152;")); - dm.evalAsBool("int16.set(0, -1);"); - assert(dm.evalAsBool("uint16.get(0) == 0xffff;")); - - dm.evalAsBool("var int32 = new Int32Array(1)"); - dm.evalAsBool("var uint32 = new Uint32Array(int32.buffer)"); - dm.evalAsBool("uint32.set(0, 0x80706050)"); - assert(dm.evalAsBool("int32.get(0) == -2140118960")); - dm.evalAsBool("int32.set(0, -2023406815);"); - assert(dm.evalAsBool("uint32.get(0) == 0x87654321;")); - dm.evalAsBool("int32.set(0, -1);"); - assert(dm.evalAsBool("uint32.get(0) == 0xffffffff;")); - } - - // IEEE754 single precision parsing - { - dm.evalAsBool("\ - function fromBytes(bytes) {\ - var uint8 = new Uint8Array(bytes),\ - dv = new DataView(uint8.buffer);\ - return dv.getFloat32(0);\ - }\ - "); - -#if 0 - assert(dm.evalAsBool("fromBytes([0xff, 0xff, 0xff, 0xff]) == NaN;")); - assert(dm.evalAsBool("fromBytes([0xff, 0xc0, 0x00, 0x01]) == NaN;")); - - assert(dm.evalAsBool("fromBytes([0xff, 0xc0, 0x00, 0x00]) == NaN;")); - assert(dm.evalAsBool("fromBytes([0xff, 0xbf, 0xff, 0xff]) == NaN;")); - assert(dm.evalAsBool("fromBytes([0xff, 0x80, 0x00, 0x01]) == NaN;")); - - assert(dm.evalAsBool("fromBytes([0xff, 0x80, 0x00, 0x00]) == -Infinity;")); - - assert(dm.evalAsBool("fromBytes([0xff, 0x7f, 0xff, 0xff]) == -3.4028234663852886E+38;")); - assert(dm.evalAsBool("fromBytes([0x80, 0x80, 0x00, 0x00]) == -1.1754943508222875E-38;")); - - assert(dm.evalAsBool("fromBytes([0x80, 0x7f, 0xff, 0xff]) == -1.1754942106924411E-38;")); - assert(dm.evalAsBool("fromBytes([0x80, 0x00, 0x00, 0x01]) == -1.4012984643248170E-45;")); - - assert(dm.evalAsBool("isNegativeZero(fromBytes([0x80, 0x00, 0x00, 0x00]));")); - assert(dm.evalAsBool("isPositiveZero(fromBytes([0x00, 0x00, 0x00, 0x00]));")); - - assert(dm.evalAsBool("fromBytes([0x00, 0x00, 0x00, 0x01]) == 1.4012984643248170E-45;")); - assert(dm.evalAsBool("fromBytes([0x00, 0x7f, 0xff, 0xff]) == 1.1754942106924411E-38;")); - - assert(dm.evalAsBool("fromBytes([0x00, 0x80, 0x00, 0x00]) == 1.1754943508222875E-38;")); - assert(dm.evalAsBool("fromBytes([0x7f, 0x7f, 0xff, 0xff]) == 3.4028234663852886E+38;")); - - assert(dm.evalAsBool("fromBytes([0x7f, 0x80, 0x00, 0x00]) == +Infinity;")); - - assert(dm.evalAsBool("fromBytes([0x7f, 0x80, 0x00, 0x01]) == NaN;")); - assert(dm.evalAsBool("fromBytes([0x7f, 0xbf, 0xff, 0xff]) == NaN;")); - assert(dm.evalAsBool("fromBytes([0x7f, 0xc0, 0x00, 0x00]) == NaN;")); - assert(dm.evalAsBool("fromBytes([0x7f, 0xff, 0xff, 0xff]) == NaN;")); -#endif - - } - - // TypedArray setting - { - dm.evalAsBool("var a = new Int32Array([1, 2, 3, 4, 5]);"); - dm.evalAsBool("var b = new Int32Array(5);"); - dm.evalAsBool("b.set(a);"); - assert(dm.evalAsBool("checkArray(b, [1, 2, 3, 4, 5]);")); - - dm.evalAsBool("b.set(new Int32Array([99, 98]), 2);"); - assert(dm.evalAsBool("checkArray(b, [1, 2, 99, 98, 5]);")); - - dm.evalAsBool("b.set(new Int32Array([99, 98, 97]), 2);"); - assert(dm.evalAsBool("checkArray(b, [1, 2, 99, 98, 97]);")); - - // ab = [ 0, 1, 2, 3, 4, 5, 6, 7 ] - // a1 = [ ^, ^, ^, ^, ^, ^, ^, ^ ] - // a2 = [ ^, ^, ^, ^ ] - dm.evalAsBool("var ab = new ArrayBuffer(8);"); - dm.evalAsBool("var a1 = new Uint8Array(ab);"); - dm.evalAsBool("for (var i = 0; i < a1.length; i += 1) { a1.set(i, i); }"); - dm.evalAsBool("var a2 = new Uint8Array(ab, 4);"); - dm.evalAsBool("a1.set(a2, 2);"); - assert(dm.evalAsBool("checkArray(a1, [0, 1, 4, 5, 6, 7, 6, 7]);")); - assert(dm.evalAsBool("checkArray(a2, [6, 7, 6, 7]);")); - - } - - // TypedArray.subarray - { - dm.evalAsBool("var a = new Int32Array([1, 2, 3, 4, 5]);"); - assert(dm.evalAsBool("checkArray(a.subarray(3), [4, 5]);")); - assert(dm.evalAsBool("checkArray(a.subarray(1, 3), [2, 3]);")); - assert(dm.evalAsBool("checkArray(a.subarray(-3), [3, 4, 5]);")); - assert(dm.evalAsBool("checkArray(a.subarray(-3, -1), [3, 4]);")); -// assert(dm.evalAsBool("checkArray(a.subarray(3, 2), []);")); -// assert(dm.evalAsBool("checkArray(a.subarray(-2, -3), []);")); -// assert(dm.evalAsBool("checkArray(a.subarray(4, 1), []);")); -// assert(dm.evalAsBool("checkArray(a.subarray(-1, -4), []);")); - - } - - // DataView constructors - { - dm.evalAsBool("var d = new DataView(new ArrayBuffer(8));"); - - dm.evalAsBool("d.setUint32(0, 0x12345678);"); - assert(dm.evalAsBool("d.getUint32(0), 0x12345678;")); - - dm.evalAsBool("d.setUint32(0, 0x12345678, true);"); - assert(dm.evalAsBool("d.getUint32(0, true), 0x12345678;")); - - dm.evalAsBool("d.setUint32(0, 0x12345678, true);"); - assert(dm.evalAsBool("d.getUint32(0), 0x78563412;")); - - dm.evalAsBool("d.setUint32(0, 0x12345678);"); - assert(dm.evalAsBool("d.getUint32(0, true), 0x78563412;")); - -// assertThrows('no arguments', TypeError, function() { return new DataView(); }); -// assertThrows('non-ArrayBuffer argument', TypeError, function() { return new DataView([]); }); -// assertThrows('non-ArrayBuffer argument', TypeError, function() { return new DataView("bogus"); }); - - } - - // DataView accessors - { - dm.evalAsBool("var u = new Uint8Array(8), d = new DataView(u.buffer);"); - assert(dm.evalAsBool("checkArray(u, [0, 0, 0, 0, 0, 0, 0, 0]);")); - - dm.evalAsBool("d.setUint8(0, 255);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0, 0, 0, 0, 0, 0, 0]);")); - - dm.evalAsBool("d.setInt8(1, -1);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0xff, 0, 0, 0, 0, 0, 0]);")); - - dm.evalAsBool("d.setUint16(2, 0x1234);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0xff, 0x12, 0x34, 0, 0, 0, 0]);")); - - dm.evalAsBool("d.setInt16(4, -1);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0xff, 0x12, 0x34, 0xff, 0xff, 0, 0]);")); - - dm.evalAsBool("d.setUint32(1, 0x12345678);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0x12, 0x34, 0x56, 0x78, 0xff, 0, 0]);")); - - dm.evalAsBool("d.setInt32(4, -2023406815);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0x12, 0x34, 0x56, 0x87, 0x65, 0x43, 0x21]);")); - - dm.evalAsBool("d.setFloat32(2, 1.2E+38);"); - assert(dm.evalAsBool("checkArray(u, [0xff, 0x12, 0x7e, 0xb4, 0x8e, 0x52, 0x43, 0x21]);")); - - dm.evalAsBool("d.setFloat64(0, -1.2345678E+301);"); - assert(dm.evalAsBool("checkArray(u, [0xfe, 0x72, 0x6f, 0x51, 0x5f, 0x61, 0x77, 0xe5]);")); - - dm.evalAsBool("u.set([0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87]);"); - assert(dm.evalAsBool("d.getUint8(0) == 128;")); - assert(dm.evalAsBool("d.getInt8(1) == -127;")); - assert(dm.evalAsBool("d.getUint16(2) == 33411;")); - assert(dm.evalAsBool("d.getInt16(3) == -31868;")); - assert(dm.evalAsBool("d.getUint32(4) == 2223343239;")); - assert(dm.evalAsBool("d.getInt32(2) == -2105310075;")); - assert(dm.evalAsBool("d.getFloat32(2) == -1.932478247535851e-37;")); - assert(dm.evalAsBool("d.getFloat64(0) == -3.116851295377095e-306;")); - - } - - // DataView endian - { - dm.evalAsBool("var rawbuf = (new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7])).buffer;"); - dm.evalAsBool("var d;"); - - dm.evalAsBool("d = new DataView(rawbuf);"); - assert(dm.evalAsBool("d.byteLength == 8;")); - assert(dm.evalAsBool("d.byteOffset == 0;")); -// assertThrows('bounds for buffer', DOMException, d.getUint8.bind(d), -2); // Chrome bug for index -1? -// assertThrows('bounds for buffer', DOMException, d.getUint8.bind(d), 8); -// assertThrows('bounds for buffer', DOMException, d.setUint8.bind(d), -2, 0); -// assertThrows('bounds for buffer', DOMException, d.setUint8.bind(d), 8, 0); - - dm.evalAsBool("d = new DataView(rawbuf, 2);"); - assert(dm.evalAsBool("d.byteLength == 6;")); - assert(dm.evalAsBool("d.byteOffset == 2;")); - assert(dm.evalAsBool("d.getUint8(5) == 7;")); -// assertThrows('bounds for buffer, byteOffset', DOMException, d.getUint8.bind(d), -2); -// assertThrows('bounds for buffer, byteOffset', DOMException, d.getUint8.bind(d), 6); -// assertThrows('bounds for buffer, byteOffset', DOMException, d.setUint8.bind(d), -2, 0); -// assertThrows('bounds for buffer, byteOffset', DOMException, d.setUint8.bind(d), 6, 0); - - dm.evalAsBool("d = new DataView(rawbuf, 8);"); - assert(dm.evalAsBool("d.byteLength == 0;")); - -// assertThrows('invalid byteOffset', DOMException, function() { return new DataView(rawbuf, -1); }); -// assertThrows('invalid byteOffset', DOMException, function() { return new DataView(rawbuf, 9); }); -// assertThrows('invalid byteOffset', DOMException, function() { return new DataView(rawbuf, -1); }); - - dm.evalAsBool("d = new DataView(rawbuf, 2, 4);"); - assert(dm.evalAsBool("d.byteLength == 4;")); - assert(dm.evalAsBool("d.byteOffset == 2;")); - assert(dm.evalAsBool("d.getUint8(3) == 5;")); -// assertThrows('bounds for buffer, byteOffset, length', DOMException, function() { return d.getUint8(-2); }); -// assertThrows('bounds for buffer, byteOffset, length', DOMException, d.getUint8.bind(d), 4); -// assertThrows('bounds for buffer, byteOffset, length', DOMException, d.setUint8.bind(d), -2, 0); -// assertThrows('bounds for buffer, byteOffset, length', DOMException, d.setUint8.bind(d), 4, 0); - -// assertThrows('invalid byteOffset+length', DOMException, function() { return new DataView(rawbuf, 0, 9); }); -// assertThrows('invalid byteOffset+length', DOMException, function() { return new DataView(rawbuf, 8, 1); }); -// assertThrows('invalid byteOffset+length', DOMException, function() { return new DataView(rawbuf, 9, -1); }); - - } - - // Typed Array getters/setters - { - - dm.evalAsBool("var bytes = new Uint8Array([1, 2, 3, 4]);"); - dm.evalAsBool("var uint32s = new Uint32Array(bytes.buffer);"); - - assert(dm.evalAsBool("bytes[1] == 2;")); - dm.evalAsBool("uint32s[0] = 0xffffffff;"); - assert(dm.evalAsBool("bytes[1] == 0xff;")); - - } - - // string replacement - { - std::string content = "$"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 0); - std::cout << content << std::endl; - assert(boost::equals(content, "$")); - } - - { - std::string content = "$sadf ${foo}"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 1); - std::cout << content << std::endl; - assert(boost::equals(content, "$sadf 12")); - } - - { - std::string content = "${"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 0); - std::cout << content << std::endl; - assert(boost::equals(content, "${")); - } - - { - std::string content = "${foo}"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 1); - std::cout << content << std::endl; - assert(boost::equals(content, "12")); - } - - { - std::string content = "${bar}"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 0); - std::cout << content << std::endl; - assert(boost::equals(content, "${bar}")); - } - - { - std::string content = "There are ${bar} monkeys! Really ${foo} monkeys!"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 1); - std::cout << content << std::endl; - assert(boost::equals(content, "There are ${bar} monkeys! Really 12 monkeys!")); - } - - { - std::string content = "There are ${foo} monkeys! Really ${foo} monkeys!"; - int rplc = dm.replaceExpressions(content); - assert(rplc == 2); - std::cout << content << std::endl; - assert(boost::equals(content, "There are 12 monkeys! Really 12 monkeys!")); - } - - { - std::string xml = - "<scxml datamodel=\"ecmascript\">" - " <script src=\"http://uscxml.tk.informatik.tu-darmstadt.de/scripts/dump.js\" />" - " <state id=\"s1\">" - " <onentry>" - " <script>_x.platform.pool('memeber.second', { foo: 12, bar: 34})</script>" - " <log label=\"ext\" expr=\"dump(_x.platform.pool('member.first'))\" />" - " </onentry>" - " <transition target=\"done\" />" - " </state>" - " <final id=\"done\" />" - "</scxml>"; - - TestDataModelExtension ext; - Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addDataModelExtension(&ext); - - InterpreterState state; - - do { - state = interpreter.step(); - } while (state != USCXML_FINISHED && state!= USCXML_DESTROYED); - - - } -}
\ No newline at end of file diff --git a/test/src/test-dirmon.cpp b/test/src/test-dirmon.cpp deleted file mode 100644 index 078c50f..0000000 --- a/test/src/test-dirmon.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/Message.h" -#include "uscxml/concurrency/tinythread.h" -#include <assert.h> -#include <boost/algorithm/string.hpp> -#include <iostream> -#include "uscxml/plugins/invoker/filesystem/dirmon/DirMonInvoker.h" - -#include <sys/types.h> -#include <sys/event.h> -#include <sys/time.h> -#include <sys/stat.h> -#include <unistd.h> -#include <fcntl.h> -#include <stdio.h> -#include <stdlib.h> -#include <dirent.h> -#include <string.h> -#include <iostream> - -using namespace uscxml; -using namespace boost; - -class Watcher : public DirectoryWatchMonitor { - void handleChanges(DirectoryWatch::Action action, const std::string dir, const std::string file, struct stat fileStat) { - std::cout << "Monitor on " << dir << ": " << action << " for " << file << std::endl; - } -}; - -int main(int argc, char** argv) { - - int mDescriptor = kqueue(); - - struct kevent filters[2]; - struct kevent event; - - struct timespec mTimeOut; - mTimeOut.tv_sec = 20; - mTimeOut.tv_nsec = 20000000; - - int fd1 = open("/Users/sradomski/Desktop/wrls", O_RDONLY); - int fd2 = open("/Users/sradomski/Desktop/tmp", O_RDONLY); - - EV_SET(&filters[0], fd1, EVFILT_VNODE, - EV_ADD | EV_ENABLE | EV_ONESHOT, - NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE, - 0, NULL); - EV_SET(&filters[1], fd2, EVFILT_VNODE, - EV_ADD | EV_ENABLE | EV_ONESHOT, - NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE, - 0, NULL); - - int nev = 0; - while(true) { - nev = kevent(mDescriptor, filters, 2, &event, 1, &mTimeOut); - if(nev == -1) - perror("kevent"); - else if (nev > 0) { - if (event.fflags & NOTE_DELETE) { - fprintf(stderr, "NOTE_DELETE "); - } - if (event.fflags & NOTE_EXTEND) { - fprintf(stderr, "NOTE_EXTEND "); - } - if (event.fflags & NOTE_WRITE) { - fprintf(stderr, "NOTE_WRITE "); - } - if (event.fflags & NOTE_ATTRIB) { - fprintf(stderr, "NOTE_ATTRIB "); - } - if (event.fflags & NOTE_RENAME) { - fprintf(stderr, "NOTE_RENAME "); - } - } - } - -// Watcher watcher; -// DirectoryWatch* dw = new DirectoryWatch("/Users/sradomski/Desktop/tmp", true); -// dw->addMonitor(&watcher); -// while(true) { -// dw->updateEntries(); -// } -}
\ No newline at end of file diff --git a/test/src/test-doneevent.cpp b/test/src/test-doneevent.cpp deleted file mode 100644 index 0330512..0000000 --- a/test/src/test-doneevent.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "uscxml/Interpreter.h" - -using namespace uscxml; - -// -- Issue 56 on github -int main(int argc, char** argv) { - std::deque<std::string> messageQueue; - messageQueue.push_back("a"); - messageQueue.push_back("b"); - messageQueue.push_back("c"); - messageQueue.push_back("d"); - - const char* scxmlContent = - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - "<scxml xmlns=\"http://www.w3.org/2005/07/scxml\" version=\"1.0\" initial=\"initial_state\">" - " <state id=\"initial_state\">" - " <transition event=\"a\" target=\"parallel_state\"/>" - " </state>" - " <parallel id=\"parallel_state\">" - " <transition event=\"done.state.parallel_state\" target=\"join_state\"/>" - " <state id=\"p1out\" initial=\"p1\">" - " <state id=\"p1\">" - " <transition event=\"b\" target=\"p11\"/>" - " </state>" - " <final id=\"p11\"/>" - " </state>" - " <state id=\"p2out\" initial=\"p2\">" - " <state id=\"p2\">" - " <transition event=\"c\" target=\"p21\"/>" - " </state>" - " <final id=\"p21\"/>" - " </state>" - " </parallel>" - " <state id=\"join_state\">" - " <transition event=\"d\" target=\"final_state\"/>" - " </state>" - " <final id=\"final_state\"/>" - "</scxml>"; - - std::string msg; - - uscxml::Interpreter scxml = uscxml::Interpreter::fromXML(scxmlContent, ""); - scxml.addMonitor(new StateTransitionMonitor()); - - uscxml::InterpreterState state; - // assume initial stable configuration - do { - state = scxml.step(); - } while(state > 0); - - while(state != uscxml::USCXML_FINISHED && !messageQueue.empty()) { - msg = messageQueue.front(); - messageQueue.pop_front(); - - scxml.receive(uscxml::Event(msg, uscxml::Event::EXTERNAL)); - - // step to next stable configuration - do { - state = scxml.step(); - } while(state > 0); - - } - - return EXIT_SUCCESS; - -}
\ No newline at end of file diff --git a/test/src/test-eventdelay.cpp b/test/src/test-eventdelay.cpp deleted file mode 100644 index ce6c923..0000000 --- a/test/src/test-eventdelay.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "uscxml/concurrency/DelayedEventQueue.h" -#include <iostream> - -int eventCalled = 0; - -#include <sstream> - -static void callback(void* userData, const std::string eventId) { -// std::cout << eventId << ": " << (const char*)userData << std::endl; - std::cout << eventId << std::endl << std::flush; - eventCalled++; -} - -int main(int argc, char** argv) { - - using namespace uscxml; - DelayedEventQueue* eq = new DelayedEventQueue(); - - std::cout << "Starting" << std::endl; - eq->start(); - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(10)); - -// eq->addEvent("foo", callback, 200, (void*)"event foo"); -// eq->addEvent("bar", callback, 400, (void*)"event bar"); -// eq->addEvent("bar", callback, 600, (void*)"event bar"); -// eq->cancelEvent("bar"); -// eq->addEvent("bar", callback, 300, (void*)"event bar"); -// eq->addEvent("baz", callback, 400, (void*)"event baz"); - - for (unsigned int i = 0; i <= 2000; i += 200) { -// eq->stop(); - std::stringstream ss; - ss << i; - eq->addEvent(ss.str(), callback, i, NULL); - std::cout << "Added " << i << std::endl; -// eq->start(); - } - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(2000)); - -}
\ No newline at end of file diff --git a/test/src/test-expect.cpp b/test/src/test-expect.cpp deleted file mode 100644 index 8b1303e..0000000 --- a/test/src/test-expect.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include <tcl.h> -#include <expect_tcl.h> -#include <expect.h> -#include <stdlib.h> - -int main(int argc, char** argv) { - int rc = 0; - - Tcl_Interp *interp = Tcl_CreateInterp(); - Tcl_FindExecutable(argv[0]); - - if (Tcl_Init(interp) == TCL_ERROR) { - fprintf(stderr,"Tcl_Init failed: %s\n",Tcl_GetStringResult (interp)); - (void) exit(1); - } - - if (Expect_Init(interp) == TCL_ERROR) { - fprintf(stderr,"Expect_Init failed: %s\n",Tcl_GetStringResult (interp)); - (void) exit(1); - } - - exp_loguser = 1; - exp_is_debugging = 1; - exp_timeout = 3; - - FILE *fp; - int ec; -// char* program = "/usr/bin/telnet localhost 80"; -// if (0 > (ec = exp_spawnl("sh","sh","-c",program,(char *)0))) -// exit(0); -// if (NULL == (fp = fdopen(ec,"r+"))) -// exit(0); -// setbuf(fp,(char *)0); - - if (0 > (ec = exp_spawnl("/usr/bin/telnet", "/usr/bin/telnet","localhost", "80", (char *)0))) - exit(0); - if (NULL == (fp = fdopen(ec,"r+"))) - exit(0); - setbuf(fp,(char *)0); - - switch (exp_fexpectl(fp, - exp_glob, "qConnected to", 1, - exp_glob, "qConnection failed", 2, - exp_end)) { - case 1: - printf("SUCCESS!"); - fprintf(fp, "%s\r", "GET /"); - - break; - case 2: - printf("FAIL!"); - break; - - default: - break; - } - exit(EXIT_SUCCESS); -}
\ No newline at end of file diff --git a/test/src/test-ffmpeg.cpp b/test/src/test-ffmpeg.cpp deleted file mode 100644 index 1c99aa5..0000000 --- a/test/src/test-ffmpeg.cpp +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Copyright (c) 2003 Fabrice Bellard - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** - * @file - * libavformat API example. - * - * Output a media file in any supported libavformat format. - * The default codecs are used. - * @example doc/examples/muxing.c - */ - -#include <fstream> -#include <sstream> - -extern "C" { -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <math.h> - -#include <libavutil/opt.h> -#include <libavutil/mathematics.h> -#include <libavformat/avformat.h> -#include <libswscale/swscale.h> -#include <libswresample/swresample.h> -} -/* 5 seconds stream duration */ -#define STREAM_FRAME_RATE 25 /* 25 images/s */ -#define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */ -#define BMP_FORMAT AV_PIX_FMT_RGB24 - -static int sws_flags = SWS_BICUBIC; - -/* Add an output stream. */ -static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec, - enum AVCodecID codec_id) { - AVCodecContext *c; - AVStream *st; - - /* find the encoder */ - *codec = avcodec_find_encoder(codec_id); - if (!(*codec)) { - fprintf(stderr, "Could not find encoder for '%s'\n", - avcodec_get_name(codec_id)); - exit(1); - } - - st = avformat_new_stream(oc, *codec); - if (!st) { - fprintf(stderr, "Could not allocate stream\n"); - exit(1); - } - st->id = oc->nb_streams-1; - c = st->codec; - - switch ((*codec)->type) { - case AVMEDIA_TYPE_AUDIO: - c->sample_fmt = AV_SAMPLE_FMT_FLTP; - c->bit_rate = 64000; - c->sample_rate = 44100; - c->channels = 2; - break; - - case AVMEDIA_TYPE_VIDEO: - c->codec_id = codec_id; - - c->bit_rate = 400000; - /* Resolution must be a multiple of two. */ - c->width = 352; - c->height = 288; - /* timebase: This is the fundamental unit of time (in seconds) in terms - * of which frame timestamps are represented. For fixed-fps content, - * timebase should be 1/framerate and timestamp increments should be - * identical to 1. */ - c->time_base.den = STREAM_FRAME_RATE; - c->time_base.num = 1; - c->gop_size = 12; /* emit one intra frame every twelve frames at most */ - c->pix_fmt = STREAM_PIX_FMT; - if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) { - /* just for testing, we also add B frames */ - c->max_b_frames = 2; - } - if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) { - /* Needed to avoid using macroblocks in which some coeffs overflow. - * This does not happen with normal video, it just happens here as - * the motion of the chroma plane does not match the luma plane. */ - c->mb_decision = 2; - } - break; - - default: - break; - } - - /* Some formats want stream headers to be separate. */ - if (oc->oformat->flags & AVFMT_GLOBALHEADER) - c->flags |= CODEC_FLAG_GLOBAL_HEADER; - - return st; -} - - -/**************************************************************/ -/* video output */ - -static AVFrame *frame; -static AVPicture src_picture, dst_picture; -static int frame_count; - -static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st) { - int ret; - AVCodecContext *c = st->codec; - - /* open the codec */ - ret = avcodec_open2(c, codec, NULL); - if (ret < 0) { - fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret)); - exit(1); - } - - /* allocate and init a re-usable frame */ - frame = avcodec_alloc_frame(); - if (!frame) { - fprintf(stderr, "Could not allocate video frame\n"); - exit(1); - } - - /* Allocate the encoded raw picture. */ - ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height); - if (ret < 0) { - fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret)); - exit(1); - } - - /* If the output format is not YUV420P, then a temporary YUV420P - * picture is needed too. It is then converted to the required - * output format. */ - if (c->pix_fmt != BMP_FORMAT) { - ret = avpicture_alloc(&src_picture, BMP_FORMAT, c->width, c->height); - if (ret < 0) { - fprintf(stderr, "Could not allocate temporary picture: %s\n", - av_err2str(ret)); - exit(1); - } - } - - /* copy data and linesize picture pointers to frame */ - *((AVPicture *)frame) = dst_picture; -} - - -/* Prepare a dummy image. */ -static void fill_rgba_image(AVPicture *pict, int frame_index, - int width, int height) { - int x, y, i; - - i = frame_index; - - std::stringstream ssFilename; - ssFilename << "/Users/sradomski/Desktop/ctrl/" << (i % 125) << ".bmp"; - - std::ifstream file(ssFilename.str().c_str()); - - file.seekg(0, std::ios::end); - size_t length = file.tellg(); - file.seekg(0, std::ios::beg); - - char* buffer = (char*)malloc(length); - file.read(buffer, length); - - uint32_t offset = 0; - offset += buffer[10] << 0; - offset += buffer[11] << 8; - offset += buffer[12] << 16; - offset += buffer[13] << 24; - offset--; - - for (y = 0; y < height; y++) { - for (x = 0; x < width; x++) { - pict->data[0][y * pict->linesize[0] + x * 3] = buffer[offset++]; - pict->data[0][y * pict->linesize[0] + x * 3 + 1] = buffer[offset++]; - pict->data[0][y * pict->linesize[0] + x * 3 + 2] = buffer[offset++]; - } - } - - free(buffer); -} - -static void write_video_frame(AVFormatContext *oc, AVStream *st) { - int ret; - static struct SwsContext *sws_ctx; - AVCodecContext *c = st->codec; - - if (c->pix_fmt != BMP_FORMAT) { - /* as we only generate a YUV420P picture, we must convert it - * to the codec pixel format if needed */ - if (!sws_ctx) { - sws_ctx = sws_getContext(c->width, c->height, BMP_FORMAT, - c->width, c->height, c->pix_fmt, - sws_flags, NULL, NULL, NULL); - if (!sws_ctx) { - fprintf(stderr, - "Could not initialize the conversion context\n"); - exit(1); - } - } - fill_rgba_image(&src_picture, frame_count, c->width, c->height); - sws_scale(sws_ctx, - (const uint8_t * const *)src_picture.data, src_picture.linesize, - 0, c->height, dst_picture.data, dst_picture.linesize); - } else { - fill_rgba_image(&dst_picture, frame_count, c->width, c->height); - } - - if (oc->oformat->flags & AVFMT_RAWPICTURE) { - /* Raw video case - directly store the picture in the packet */ - AVPacket pkt; - av_init_packet(&pkt); - - pkt.flags |= AV_PKT_FLAG_KEY; - pkt.stream_index = st->index; - pkt.data = dst_picture.data[0]; - pkt.size = sizeof(AVPicture); - - ret = av_interleaved_write_frame(oc, &pkt); - } else { - AVPacket pkt = { 0 }; - int got_packet; - av_init_packet(&pkt); - - /* encode the image */ - ret = avcodec_encode_video2(c, &pkt, frame, &got_packet); - if (ret < 0) { - fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret)); - exit(1); - } - /* If size is zero, it means the image was buffered. */ - - if (!ret && got_packet && pkt.size) { - pkt.stream_index = st->index; - - /* Write the compressed frame to the media file. */ - ret = av_interleaved_write_frame(oc, &pkt); - } else { - ret = 0; - } - } - if (ret != 0) { - fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret)); - exit(1); - } - frame_count++; -} - -static void close_video(AVFormatContext *oc, AVStream *st) { - avcodec_close(st->codec); - av_free(src_picture.data[0]); - av_free(dst_picture.data[0]); - av_free(frame); -} - -/**************************************************************/ -/* media file output */ - -int main(int argc, char **argv) { - const char *filename; - AVOutputFormat *fmt; - AVFormatContext *oc; - AVStream *video_st; - AVCodec *video_codec; - int ret; - - /* Initialize libavcodec, and register all codecs and formats. */ - av_register_all(); - - filename = "/Users/sradomski/Desktop/test.mpg"; - - /* allocate the output media context */ - avformat_alloc_output_context2(&oc, NULL, NULL, filename); - if (!oc) { - printf("Could not deduce output format from file extension: using MPEG.\n"); - avformat_alloc_output_context2(&oc, NULL, "mpeg", filename); - } - if (!oc) { - return 1; - } - fmt = oc->oformat; - - /* Add the audio and video streams using the default format codecs - * and initialize the codecs. */ - video_st = NULL; - - if (fmt->video_codec != AV_CODEC_ID_NONE) { - video_st = add_stream(oc, &video_codec, fmt->video_codec); - } - - /* Now that all the parameters are set, we can open the audio and - * video codecs and allocate the necessary encode buffers. */ - if (video_st) - open_video(oc, video_codec, video_st); - - /* open the output file, if needed */ - if (!(fmt->flags & AVFMT_NOFILE)) { - ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE); - if (ret < 0) { - fprintf(stderr, "Could not open '%s': %s\n", filename, - av_err2str(ret)); - return 1; - } - } - - /* Write the stream header, if any. */ - ret = avformat_write_header(oc, NULL); - if (ret < 0) { - fprintf(stderr, "Error occurred when opening output file: %s\n", - av_err2str(ret)); - return 1; - } - - if (frame) - frame->pts = 0; - for (size_t i = 0; i < 125; i++) { - write_video_frame(oc, video_st); - frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base); - } - - /* Write the trailer, if any. The trailer must be written before you - * close the CodecContexts open when you wrote the header; otherwise - * av_write_trailer() may try to use memory that was freed on - * av_codec_close(). */ - av_write_trailer(oc); - - /* Close each codec. */ - if (video_st) - close_video(oc, video_st); - - if (!(fmt->flags & AVFMT_NOFILE)) - /* Close the output file. */ - avio_close(oc->pb); - - /* free the stream */ - avformat_free_context(oc); - - return 0; -} diff --git a/test/src/test-flat-stateid.cpp b/test/src/test-flat-stateid.cpp deleted file mode 100644 index 10d83eb..0000000 --- a/test/src/test-flat-stateid.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include "uscxml/transform/FlatStateIdentifier.h" -#include "uscxml/transform/ChartToPromela.h" -#include <cassert> - -int main(int argc, char** argv) { - - std::list<std::string>::const_iterator listIter; - - { - std::string stateId = "active:{}"; - uscxml::FlatStateIdentifier flat1(stateId); - assert(flat1.getActive().size() == 0); - assert(flat1.getVisited().size() == 0); - assert(flat1.getHistory().size() == 0); - - uscxml::FlatStateIdentifier flat2(flat1.getActive(), flat1.getVisited(), flat1.getHistory()); - assert(flat2.getStateId() == stateId); - } - - { - std::string stateId = "active:{s1};visited:{s1,s2}"; - uscxml::FlatStateIdentifier flat1(stateId); - assert(flat1.getActive().size() == 1); - assert(flat1.getVisited().size() == 2); - assert(flat1.getHistory().size() == 0); - - uscxml::FlatStateIdentifier flat2(flat1.getActive(), flat1.getVisited(), flat1.getHistory()); - assert(flat2.getStateId() == stateId); - } - - { - - std::string stateId = "active:{s0,s1,s2};visited:{s0,s1,s2};history:{h0:{s1,s2},h1:{s2,s3}}"; - uscxml::FlatStateIdentifier flat1(stateId); - - listIter = flat1.getActive().begin(); - assert(*listIter++ == "s0"); - assert(*listIter++ == "s1"); - assert(*listIter++ == "s2"); - - listIter = flat1.getVisited().begin(); - assert(*listIter++ == "s0"); - assert(*listIter++ == "s1"); - assert(*listIter++ == "s2"); - - assert(flat1.getHistory().find("h0") != flat1.getHistory().end()); - listIter = flat1.getHistory().at("h0").begin(); - assert(*listIter++ == "s1"); - assert(*listIter++ == "s2"); - - assert(flat1.getHistory().find("h1") != flat1.getHistory().end()); - listIter = flat1.getHistory().at("h1").begin(); - assert(*listIter++ == "s2"); - assert(*listIter++ == "s3"); - - uscxml::FlatStateIdentifier flat2(flat1.getActive(), flat1.getVisited(), flat1.getHistory()); - assert(flat2.getStateId() == stateId); - } - - { - uscxml::HistoryTransitionClass histClass1("history:{h0:{s1, s4, s6}}", "history:{h0:{s0, s6}}"); - - // these will match - uscxml::HistoryTransitionClass histClass1Match1("history:{h0:{s1, s2, s3}}", "history:{h0:{s0}}"); - assert(histClass1.matches(histClass1Match1)); - - histClass1.merge(histClass1Match1); - assert(histClass1.toRemember.at("h0").find("s0") != histClass1.toRemember.at("h0").end()); - assert(histClass1.toRemember.at("h0").size() == 1); - - assert(histClass1.toForget.at("h0").find("s1") != histClass1.toForget.at("h0").end()); - assert(histClass1.toForget.at("h0").find("s2") != histClass1.toForget.at("h0").end()); - assert(histClass1.toForget.at("h0").find("s3") != histClass1.toForget.at("h0").end()); - - uscxml::HistoryTransitionClass histClass1NoMatch1("history:{h0:{s0}}", "history:{h0:{s1}}"); - assert(!histClass1.matches(histClass1NoMatch1)); - - uscxml::HistoryTransitionClass histClass1NoMatch2("history:{h0:{s1, s2, s3}}", "history:{h0:{s4}}"); - assert(!histClass1.matches(histClass1NoMatch2)); - - uscxml::HistoryTransitionClass histClass1NoMatch3("history:{h0:{s1, s2, s6}}", "history:{h0:{s0}}"); - assert(!histClass1.matches(histClass1NoMatch3)); - - } - -}
\ No newline at end of file diff --git a/test/src/test-c-machine.cpp b/test/src/test-gen-c.cpp index 9ee3f1f..8f70b26 100644 --- a/test/src/test-c-machine.cpp +++ b/test/src/test-gen-c.cpp @@ -20,16 +20,15 @@ #include "test-c-machine.scxml.c" #endif -#include "uscxml/Convenience.h" -#include "uscxml/URL.h" -#include "uscxml/concurrency/Timer.h" +#include "uscxml/util/URL.h" +//#include "uscxml/concurrency/Timer.h" //#include "uscxml/dom/DOMUtils.h" -#include "uscxml/Factory.h" +#include "uscxml/plugins/Factory.h" //#include "uscxml/Interpreter.h" -#include "uscxml/UUID.h" +#include "uscxml/util/UUID.h" -#include "uscxml/concurrency/DelayedEventQueue.h" -#include "uscxml/concurrency/tinythread.h" +#include "uscxml/interpreter/InterpreterImpl.h" +#include "uscxml/interpreter/EventQueueImpl.h" #ifdef BUILD_PROFILING # include "uscxml/plugins/DataModel.h" @@ -39,7 +38,7 @@ using namespace uscxml; -class StateMachine : public InterpreterInfo { +class StateMachine : public DataModelCallbacks, public DelayedEventQueueCallbacks { public: StateMachine(const uscxml_machine* machine) : machine(machine), parentMachine(NULL), topMostMachine(NULL), invocation(NULL) { allMachines[sessionId] = this; @@ -54,10 +53,40 @@ public: init(); } + const std::string& getName() { + return name; + } + + const std::string& getSessionId() { + return sessionId; + } + const std::map<std::string, IOProcessor>& getIOProcessors() { + return ioProcs; + } + + 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::DOMDocument* getDocument() const { + return document; + } + const std::map<std::string, Invoker>& getInvokers() { + return invokers; + } + void init() { sessionId = UUID::getUUID(); isFinalized = false; - currEvent = NULL; // clear and initialize machine context memset(&ctx, 0, sizeof(uscxml_ctx)); @@ -84,7 +113,7 @@ public: name = machine->name; - delayQueue.start(); + delayQueue = DelayedEventQueue(std::shared_ptr<DelayedEventQueueImpl>(new DelayedEventQueueImpl(this))); dataModel = Factory::getInstance()->createDataModel(machine->datamodel, this); if (invocation != NULL) { @@ -98,7 +127,7 @@ public: } else if (param->location != NULL) { identifier = param->location; } - invokeData[identifier] = parentMachine->dataModel.getStringAsData(param->expr); + invokeData[identifier] = parentMachine->dataModel.getAsData(param->expr); param++; } } @@ -117,7 +146,7 @@ public: break; std::string identifier = std::string(aPtr, cPtr - aPtr); - invokeData[identifier] = parentMachine->dataModel.getStringAsData(identifier); + invokeData[identifier] = parentMachine->dataModel.getAsData(identifier); } } } @@ -129,16 +158,13 @@ public: } // finalize(); - delayQueue.stop(); - delayQueue.cancelAllEvents(); + delayQueue.cancelAllDelayed(); while(eq.size() > 0) { - delete eq.front(); eq.pop_front(); } eq.clear(); while(iq.size() > 0) { - delete iq.front(); iq.pop_front(); } iq.clear(); @@ -160,30 +186,26 @@ public: if (isFinalized) return; - delayQueue.stop(); - delayQueue.cancelAllEvents(); + delayQueue.cancelAllDelayed(); if (parentMachine != NULL) { - tthread::lock_guard<tthread::mutex> lock(mutex); + std::lock_guard<std::mutex> lock(mutex); - Event* done = new Event(); - done->invokeid = invokeId; - done->name = "done.invoke." + invokeId; + Event done; + done.invokeid = invokeId; + done.name = "done.invoke." + invokeId; parentMachine->eq.push_back(done); } isFinalized = true; } void reset() { - delayQueue.stop(); - delayQueue.cancelAllEvents(); + delayQueue.cancelAllDelayed(); while(eq.size() > 0) { - delete eq.front(); eq.pop_front(); } while(iq.size() > 0) { - delete iq.front(); iq.pop_front(); } @@ -212,42 +234,9 @@ public: } state = uscxml_step(&toRun->ctx); - if (toRun->currEvent != NULL) { - delete toRun->currEvent; - toRun->currEvent = NULL; - } - return state; } - // InterpreterInfo - NameSpaceInfo getNameSpaceInfo() const { - return nsInfo; - } - const std::string& getName() { - return name; - } - const std::string& getSessionId() { - return sessionId; - } - const std::map<std::string, IOProcessor>& getIOProcessors() { - return ioProcs; - } - const std::map<std::string, Invoker>& getInvokers() { - return invokers; - } - Arabica::DOM::Document<std::string> getDocument() const { - return document; - } - - bool isInState(const std::string& stateId) { - for (size_t i = 0 ; i < ctx.machine->nr_states; i++) { - if (ctx.machine->states[i].name != NULL && BIT_HAS(i, ctx.config) && stateId == ctx.machine->states[i].name) - return true; - } - return false; - } - // callbacks for scxml context static int isMatched(const uscxml_ctx* ctx, const uscxml_transition* t, const void* e) { @@ -298,8 +287,7 @@ public: invokedMachine->invokeId = (invocation->sourcename != NULL ? std::string(invocation->sourcename) + "." : "") + UUID::getUUID(); USER_DATA(ctx)->dataModel.assign(invocation->idlocation, Data(invokedMachine->invokeId, Data::VERBATIM)); } else { - delete invokedMachine; - return USCXML_ERR_UNSUPPORTED; + invokedMachine->invokeId = UUID::getUUID(); } allMachines[invokedMachine->invokeId] = invokedMachine; topMachine->invocationIds[invocation] = invokedMachine->invokeId; @@ -311,15 +299,15 @@ public: } static int raiseDoneEvent(const uscxml_ctx* ctx, const uscxml_state* state, const uscxml_elem_donedata* donedata) { - Event* e = new Event(); - e->name = std::string("done.state.") + state->name; + Event e; + e.name = std::string("done.state.") + state->name; if (donedata) { if (donedata->content != NULL) { - e->data = Data(donedata->content, Data::VERBATIM); + e.data = Data(donedata->content, Data::VERBATIM); } else if (donedata->contentexpr != NULL) { try { - e->data = USER_DATA(ctx)->dataModel.getStringAsData(donedata->contentexpr); + e.data = USER_DATA(ctx)->dataModel.getAsData(donedata->contentexpr); } catch (Event e) { execContentRaise(ctx, e.name.c_str()); } @@ -329,11 +317,11 @@ public: while (param && USCXML_ELEM_PARAM_IS_SET(param)) { Data paramValue; if (param->expr != NULL) { - paramValue = USER_DATA(ctx)->dataModel.getStringAsData(param->expr); + paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->expr); } else if(param->location) { - paramValue = USER_DATA(ctx)->dataModel.getStringAsData(param->location); + paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->location); } - e->params.insert(std::make_pair(param->name, paramValue)); + e.params.insert(std::make_pair(param->name, paramValue)); param++; } } catch (Event e) { @@ -343,14 +331,14 @@ public: } #ifdef USCXML_VERBOSE - printf("Raising Done Event: %s\n", e->name.c_str()); + 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) { - SendRequest* e = new SendRequest(); + Event e; std::string sendid; if (send->id != NULL) { @@ -360,57 +348,58 @@ public: if (send->idlocation != NULL) { USER_DATA(ctx)->dataModel.assign(send->idlocation, Data(sendid, Data::VERBATIM)); } else { - e->hideSendId = true; + e.hideSendId = true; } } - e->sendid = sendid; + e.sendid = sendid; std::string target; if (send->target != NULL) { - e->target = send->target; + target = send->target; } else if (send->targetexpr != NULL) { - e->target = USER_DATA(ctx)->dataModel.evalAsString(send->targetexpr); + target = USER_DATA(ctx)->dataModel.evalAsData(send->targetexpr).atom; } else { - e->target = "#_external"; + target = "#_external"; } - if (e->target.size() > 0 && (e->target[0] != '#' || e->target[1] != '_')) { - e->name = "error.execution"; + if (target.size() > 0 && (target[0] != '#' || target[1] != '_')) { + e.name = "error.execution"; execContentRaise(ctx, e); return USCXML_ERR_INVALID_TARGET; } - e->origintype = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor"; - e->origin = e->target; + e.origintype = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor"; +// e.origin = target; + std::string type; try { if (send->type != NULL) { - e->type = send->type; + type = send->type; } else if (send->typeexpr != NULL) { - e->type = USER_DATA(ctx)->dataModel.evalAsString(send->typeexpr); + type = USER_DATA(ctx)->dataModel.evalAsData(send->typeexpr).atom; } else { - e->type = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor"; + type = "http://www.w3.org/TR/scxml/#SCXMLEventProcessor"; } } catch (Event exc) { - e->name = "error.execution"; + e.name = "error.execution"; execContentRaise(ctx, e); return USCXML_ERR_EXEC_CONTENT; } // only one somewhat supported - if (e->type != "http://www.w3.org/TR/scxml/#SCXMLEventProcessor") { - e->name = "error.execution"; + if (type != "http://www.w3.org/TR/scxml/#SCXMLEventProcessor") { + e.name = "error.execution"; execContentRaise(ctx, e); return USCXML_ERR_INVALID_TARGET; } - e->origintype = e->type; - e->invokeid = USER_DATA(ctx)->invokeId; + e.origintype = type; + e.invokeid = USER_DATA(ctx)->invokeId; if (send->eventexpr != NULL) { - e->name = USER_DATA(ctx)->dataModel.evalAsString(send->eventexpr); + e.name = USER_DATA(ctx)->dataModel.evalAsData(send->eventexpr).atom; } else { - e->name = send->event; + e.name = send->event; } try { @@ -418,11 +407,11 @@ public: while (param && USCXML_ELEM_PARAM_IS_SET(param)) { Data paramValue; if (param->expr != NULL) { - paramValue = USER_DATA(ctx)->dataModel.getStringAsData(param->expr); + paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->expr); } else if(param->location) { - paramValue = USER_DATA(ctx)->dataModel.getStringAsData(param->location); + paramValue = USER_DATA(ctx)->dataModel.evalAsData(param->location); } - e->params.insert(std::make_pair(param->name, paramValue)); + e.params.insert(std::make_pair(param->name, paramValue)); param++; } } catch (Event e) { @@ -438,7 +427,7 @@ public: ePtr++; if (*ePtr == ' ' || *ePtr == '\0') { std::string key(bPtr, ePtr - bPtr); - e->params.insert(std::make_pair(key, USER_DATA(ctx)->dataModel.getStringAsData(key))); + e.params.insert(std::make_pair(key, USER_DATA(ctx)->dataModel.evalAsData(key))); if (*ePtr == '\0') break; bPtr = ++ePtr; @@ -452,18 +441,18 @@ public: if (send->content != NULL) { // will it parse as json? - Data d = Data::fromJSON(send->content); + Data d = USER_DATA(ctx)->dataModel.getAsData(send->content); if (!d.empty()) { - e->data = d; + e.data = d; } else { - e->data = Data(spaceNormalize(send->content), Data::VERBATIM); + e.data = Data(spaceNormalize(send->content), Data::VERBATIM); } } size_t delayMs = 0; std::string delay; if (send->delayexpr != NULL) { - delay = USER_DATA(ctx)->dataModel.evalAsString(send->delayexpr); + delay = USER_DATA(ctx)->dataModel.evalAsData(send->delayexpr).atom; } else if (send->delay != NULL) { delay = send->delay; } @@ -483,32 +472,32 @@ public: } if (USER_DATA(ctx)->invokeId.size() > 0) { - e->invokeid = USER_DATA(ctx)->invokeId; + e.invokeid = USER_DATA(ctx)->invokeId; } - USER_DATA(ctx)->sendIds[sendid] = e; + USER_DATA(ctx)->sendUUIDs[e.uuid] = std::make_tuple(e.sendid, target, type); if (delayMs > 0) { - USER_DATA(ctx)->delayQueue.addEvent(sendid, delayedSend, delayMs, (void*)ctx); + USER_DATA(ctx)->delayQueue.enqueueDelayed(e, delayMs, e.uuid); } else { - delayedSend((void*)ctx, sendid); + USER_DATA(ctx)->eventReady(e, e.uuid); } return USCXML_ERR_OK; } - static int execContentRaise(const uscxml_ctx* ctx, Event* e) { - if (boost::starts_with(e->name, "error.")) { - e->eventType = Event::PLATFORM; + 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; + 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 = new Event(); - e->name = event; + Event e; + e.name = event; return execContentRaise(ctx, e); } @@ -517,11 +506,18 @@ public: if (sendid != NULL) { eventId = sendid; } else if (sendidexpr != NULL) { - eventId = USER_DATA(ctx)->dataModel.evalAsString(sendidexpr); + eventId = USER_DATA(ctx)->dataModel.evalAsData(sendidexpr).atom; } if (eventId.length() > 0) { - USER_DATA(ctx)->delayQueue.cancelEvent(eventId); + // 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; @@ -535,7 +531,7 @@ public: printf("%s%s", label, (expr != NULL ? ": " : "")); } if (expr != NULL) { - std::string msg = USER_DATA(ctx)->dataModel.evalAsString(expr); + std::string msg = USER_DATA(ctx)->dataModel.evalAsData(expr).atom; printf("%s", msg.c_str()); } if (label != NULL || expr != NULL) { @@ -558,8 +554,8 @@ public: try { // Data d = USER_DATA(ctx)->dataModel.getStringAsData(expr); if (assign->expr != NULL) { - Data d = Data(assign->expr, Data::INTERPRETED); - USER_DATA(ctx)->dataModel.assign(key, d); + USER_DATA(ctx)->dataModel.assign(key, + USER_DATA(ctx)->dataModel.evalAsData(assign->expr)); } else if (assign->content != NULL) { Data d = Data(assign->content, Data::INTERPRETED); USER_DATA(ctx)->dataModel.assign(key, d); @@ -626,7 +622,7 @@ public: 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) { @@ -634,20 +630,20 @@ public: } else { URL sourceURL(data->src); if (USER_DATA(ctx)->baseURL.size() > 0) { - sourceURL.toAbsolute(USER_DATA(ctx)->baseURL); + sourceURL = URL::resolve(sourceURL, USER_DATA(ctx)->baseURL); } else { - sourceURL.toAbsoluteCwd(); + sourceURL = URL::resolveWithCWD(sourceURL); } - content << sourceURL; + content << sourceURL.getInContent(); } /** * first attempt to parse as structured data, we will try * as space normalized string literals if this fails below */ - d = USER_DATA(ctx)->dataModel.getStringAsData(content.str()); + d = USER_DATA(ctx)->dataModel.getAsData(content.str()); } else { - d = Data("undefined", Data::INTERPRETED); + // leave d undefined } // this might fail with an unquoted string literal in content USER_DATA(ctx)->dataModel.init(data->id, d); @@ -672,7 +668,7 @@ public: static int execContentScript(const uscxml_ctx* ctx, const char* src, const char* content) { if (content != NULL) { - USER_DATA(ctx)->dataModel.eval(Arabica::DOM::Element<std::string>(), content); + USER_DATA(ctx)->dataModel.evalAsData(content); } else if (src != NULL) { return USCXML_ERR_UNSUPPORTED; } @@ -680,23 +676,26 @@ public: } static void* dequeueExternal(const uscxml_ctx* ctx) { - tthread::lock_guard<tthread::mutex> lock(USER_DATA(ctx)->mutex); + std::lock_guard<std::mutex> lock(USER_DATA(ctx)->mutex); if (USER_DATA(ctx)->eq.size() == 0) return NULL; - Event* e = USER_DATA(ctx)->eq.front(); + // set event + USER_DATA(ctx)->currEvent = USER_DATA(ctx)->eq.front(); USER_DATA(ctx)->eq.pop_front(); - USER_DATA(ctx)->currEvent = e; - USER_DATA(ctx)->dataModel.setEvent(*e); + + // 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()) { + if (e.invokeid.size() > 0 && allMachines.find(e.invokeid) != allMachines.end()) { // we need to check for finalize content - StateMachine* invokedMachine = allMachines[e->invokeid]; + StateMachine* invokedMachine = allMachines[e.invokeid]; if (invokedMachine->invocation != NULL && invokedMachine->invocation->finalize != NULL) invokedMachine->invocation->finalize(ctx, invokedMachine->invocation, - e); + &e); } // auto forward event @@ -704,63 +703,70 @@ public: if (machIter->second->parentMachine != NULL && machIter->second->parentMachine == USER_DATA(ctx) && machIter->second->invocation->autoforward) { - tthread::lock_guard<tthread::mutex> lock(machIter->second->mutex); + std::lock_guard<std::mutex> lock(machIter->second->mutex); - Event* ne = new Event(*e); - machIter->second->eq.push_back(ne); + Event e2(e); + machIter->second->eq.push_back(e2); } } #ifdef USCXML_VERBOSE - printf("Popping External Event: %s\n", e->name.c_str()); + printf("Popping External Event: %s\n", e.name.c_str()); #endif - return e; + return &USER_DATA(ctx)->currEvent; } static void* dequeueInternal(const uscxml_ctx* ctx) { if (USER_DATA(ctx)->iq.size() == 0) return NULL; - Event* e = USER_DATA(ctx)->iq.front(); + // set event + USER_DATA(ctx)->currEvent = USER_DATA(ctx)->iq.front(); USER_DATA(ctx)->iq.pop_front(); - USER_DATA(ctx)->currEvent = e; - USER_DATA(ctx)->dataModel.setEvent(*e); + + // 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()); + printf("Popping Internal Event: %s\n", e.name.c_str()); #endif - return e; + return &USER_DATA(ctx)->currEvent; } - static void delayedSend(void* ctx, std::string eventName) { - tthread::lock_guard<tthread::mutex> lock(USER_DATA(ctx)->mutex); + void eventReady(Event& e, const std::string& eventUUID) { + std::lock_guard<std::mutex> lock(mutex); + + //std::make_tuple(e.sendid, target, type); - SendRequest* sr = USER_DATA(ctx)->sendIds[eventName]; - Event* e = new Event(*sr); + std::string sendid = std::get<0>(sendUUIDs[e.uuid]); + std::string target = std::get<1>(sendUUIDs[e.uuid]); + std::string type = std::get<2>(sendUUIDs[e.uuid]); - if (sr->target == "#_internal") { - e->eventType = Event::INTERNAL; + if (target == "#_internal") { + e.eventType = Event::INTERNAL; #ifdef USCXML_VERBOSE - printf("Pushing Internal Event: %s\n", e->name.c_str()); + printf("Pushing Internal Event: %s\n", e.name.c_str()); #endif - USER_DATA(ctx)->iq.push_back(e); - } else if (sr->target == "#_external") { - e->eventType = Event::EXTERNAL; + 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()); + printf("Pushing External Event: %s\n", e.name.c_str()); #endif - USER_DATA(ctx)->eq.push_back(e); - } else if (sr->target == "#_parent") { - e->eventType = Event::EXTERNAL; - if (USER_DATA(ctx)->parentMachine != NULL) { - USER_DATA(ctx)->parentMachine->eq.push_back(e); + 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 (sr->target.substr(0,8) == "#_scxml_") { - std::string sessionId = sr->target.substr(8); + } else if (target.substr(0,8) == "#_scxml_") { + std::string sessionId = target.substr(8); bool sessionFound = false; - for (std::map<std::string, StateMachine*>::iterator machIter = USER_DATA(ctx)->topMostMachine->allMachines.begin(); - machIter != USER_DATA(ctx)->topMostMachine->allMachines.end(); machIter++) { + 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; + e.eventType = Event::EXTERNAL; machIter->second->eq.push_back(e); sessionFound = true; break; @@ -768,21 +774,20 @@ public: } if (!sessionFound) { // test496 - execContentRaise((uscxml_ctx*)ctx, "error.communication"); + execContentRaise(&ctx, "error.communication"); } - } else if (sr->target.substr(0,2) == "#_") { - e->eventType = Event::EXTERNAL; - std::string targetId = sr->target.substr(2); - if (USER_DATA(ctx)->topMostMachine->allMachines.find(targetId) != USER_DATA(ctx)->topMostMachine->allMachines.end()) { - USER_DATA(ctx)->topMostMachine->allMachines[targetId]->eq.push_back(e); + } 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((uscxml_ctx*)ctx, "error.communication"); + execContentRaise(&ctx, "error.communication"); } } else { assert(false); } - USER_DATA(ctx)->monitor.notify_all(); - delete sr; + monitor.notify_all(); } static std::string spaceNormalize(const std::string& text) { @@ -857,7 +862,7 @@ NEXT_DESC: return false; } - Event* currEvent; + Event currEvent; std::map<const uscxml_elem_invoke*, std::string> invocationIds; std::map<std::string, StateMachine*> allMachines; @@ -880,8 +885,8 @@ NEXT_DESC: const uscxml_elem_invoke* invocation; std::map<std::string, Data> invokeData; - std::deque<Event*> iq; - std::deque<Event*> eq; + std::deque<Event> iq; + std::deque<Event> eq; DataModel dataModel; @@ -891,17 +896,17 @@ protected: size_t currIteration; }; - NameSpaceInfo nsInfo; + X xmlPrefix; std::map<std::string, IOProcessor> ioProcs; std::map<std::string, Invoker> invokers; - Arabica::DOM::Document<std::string> document; + xercesc::DOMDocument* document; DelayedEventQueue delayQueue; - std::map<std::string, SendRequest*> sendIds; + std::map<std::string, std::tuple<std::string, std::string, std::string> > sendUUIDs; std::map<const uscxml_elem_foreach*, scxml_foreach_info*> foreachInfo; - tthread::condition_variable monitor; - tthread::mutex mutex; + std::condition_variable monitor; + std::mutex mutex; }; @@ -916,20 +921,12 @@ int main(int argc, char** argv) { size_t remainingRuns = benchmarkRuns; - double avg = 0; size_t microSteps = 0; -#ifdef BUILD_PROFILING - double avgDm = 0; -#endif StateMachine rootMachine(&USCXML_MACHINE); - Timer tTotal; - tTotal.start(); while(remainingRuns-- > 0) { - Timer t; - t.start(); microSteps = 0; @@ -937,21 +934,12 @@ int main(int argc, char** argv) { err = rootMachine.step(); if (rootMachine.isDone()) break; - t.stop(); microSteps++; - - t.start(); } microSteps++; assert(rootMachine.ctx.flags & USCXML_CTX_TOP_LEVEL_FINAL); - t.stop(); - avg += t.elapsed; -#ifdef BUILD_PROFILING - avgDm += rootMachine.dataModel.timer.elapsed; - rootMachine.dataModel.timer.elapsed = 0; -#endif 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) { @@ -966,16 +954,6 @@ int main(int argc, char** argv) { } rootMachine.reset(); } - tTotal.stop(); - std::cout << benchmarkRuns << " iterations" << std::endl; - std::cout << tTotal.elapsed * 1000.0 << " ms in total" << std::endl; - std::cout << (avg * 1000.0) / (double)benchmarkRuns << " ms per execution" << std::endl; - std::cout << microSteps << " microsteps per iteration" << std::endl; - std::cout << (avg * 1000.0) / ((double)benchmarkRuns * (double)microSteps) << " ms per microstep" << std::endl; -#ifdef BUILD_PROFILING - std::cout << (avgDm * 1000.0) / (double)benchmarkRuns << " ms in dataModel" << std::endl; - std::cout << ((avg - avgDm) * 1000.0) / ((double)benchmarkRuns * (double)microSteps) << " ms per microstep \\wo dataModel" << std::endl; -#endif - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(100)); + return EXIT_SUCCESS; } diff --git a/test/src/test-instant-messaging.cpp b/test/src/test-instant-messaging.cpp deleted file mode 100644 index 4375e94..0000000 --- a/test/src/test-instant-messaging.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* - * pidgin - * - * Pidgin is the legal property of its developers, whose names are too numerous - * to list here. Please refer to the COPYRIGHT file distributed with this - * source distribution. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * 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. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA - * - */ - -#include "purple.h" - -#include <glib.h> - -#include <signal.h> -#include <string.h> -#ifndef _WIN32 -#include <unistd.h> -#else -#include "win32/win32dep.h" -#endif - -#define CUSTOM_USER_DIRECTORY "/dev/null" -#define CUSTOM_PLUGIN_PATH "" -#define PLUGIN_SAVE_PREF "/purple/nullclient/plugins/saved" -#define UI_ID "nullclient" - -/** - * The following eventloop functions are used in both pidgin and purple-text. If your - * application uses glib mainloop, you can safely use this verbatim. - */ -#define PURPLE_GLIB_READ_COND (G_IO_IN | G_IO_HUP | G_IO_ERR) -#define PURPLE_GLIB_WRITE_COND (G_IO_OUT | G_IO_HUP | G_IO_ERR | G_IO_NVAL) - -typedef struct _PurpleGLibIOClosure { - PurpleInputFunction function; - guint result; - gpointer data; -} PurpleGLibIOClosure; - -static void purple_glib_io_destroy(gpointer data) { - g_free(data); -} - -static gboolean purple_glib_io_invoke(GIOChannel *source, GIOCondition condition, gpointer data) { - PurpleGLibIOClosure *closure = (PurpleGLibIOClosure*)data; - int purple_cond = 0; - - if (condition & PURPLE_GLIB_READ_COND) - purple_cond |= PURPLE_INPUT_READ; - if (condition & PURPLE_GLIB_WRITE_COND) - purple_cond |= PURPLE_INPUT_WRITE; - - closure->function(closure->data, g_io_channel_unix_get_fd(source), - (PurpleInputCondition)purple_cond); - - return TRUE; -} - -static guint glib_input_add(gint fd, PurpleInputCondition condition, PurpleInputFunction function, - gpointer data) { - PurpleGLibIOClosure *closure = g_new0(PurpleGLibIOClosure, 1); - GIOChannel *channel; - int cond = 0; - - closure->function = function; - closure->data = data; - - if (condition & PURPLE_INPUT_READ) - cond |= PURPLE_GLIB_READ_COND; - if (condition & PURPLE_INPUT_WRITE) - cond |= PURPLE_GLIB_WRITE_COND; - -#if defined _WIN32 && !defined WINPIDGIN_USE_GLIB_IO_CHANNEL - channel = wpurple_g_io_channel_win32_new_socket(fd); -#else - channel = g_io_channel_unix_new(fd); -#endif - closure->result = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, (GIOCondition)cond, - purple_glib_io_invoke, closure, purple_glib_io_destroy); - - g_io_channel_unref(channel); - return closure->result; -} - -static PurpleEventLoopUiOps glib_eventloops = { - g_timeout_add, - g_source_remove, - glib_input_add, - g_source_remove, - NULL, - g_timeout_add_seconds, - - /* padding */ - NULL, - NULL, - NULL -}; -/*** End of the eventloop functions. ***/ - -/*** Conversation uiops ***/ -static void -null_write_conv(PurpleConversation *conv, const char *who, const char *alias, - const char *message, PurpleMessageFlags flags, time_t mtime) { - const char *name; - if (alias && *alias) - name = alias; - else if (who && *who) - name = who; - else - name = NULL; - - printf("(%s) %s %s: %s\n", purple_conversation_get_name(conv), - purple_utf8_strftime("(%H:%M:%S)", localtime(&mtime)), - name, message); -} - -static PurpleConversationUiOps null_conv_uiops = { - NULL, /* create_conversation */ - NULL, /* destroy_conversation */ - NULL, /* write_chat */ - NULL, /* write_im */ - null_write_conv, /* write_conv */ - NULL, /* chat_add_users */ - NULL, /* chat_rename_user */ - NULL, /* chat_remove_users */ - NULL, /* chat_update_user */ - NULL, /* present */ - NULL, /* has_focus */ - NULL, /* custom_smiley_add */ - NULL, /* custom_smiley_write */ - NULL, /* custom_smiley_close */ - NULL, /* send_confirm */ - NULL, - NULL, - NULL, - NULL -}; - -static void -null_ui_init(void) { - /** - * This should initialize the UI components for all the modules. Here we - * just initialize the UI for conversations. - */ - purple_conversations_set_ui_ops(&null_conv_uiops); -} - -static PurpleCoreUiOps null_core_uiops = { - NULL, - NULL, - null_ui_init, - NULL, - - /* padding */ - NULL, - NULL, - NULL, - NULL -}; - -static void -init_libpurple(void) { - /* Set a custom user directory (optional) */ - purple_util_set_user_dir(CUSTOM_USER_DIRECTORY); - - /* We do not want any debugging for now to keep the noise to a minimum. */ - purple_debug_set_enabled(FALSE); - - /* Set the core-uiops, which is used to - * - initialize the ui specific preferences. - * - initialize the debug ui. - * - initialize the ui components for all the modules. - * - uninitialize the ui components for all the modules when the core terminates. - */ - purple_core_set_ui_ops(&null_core_uiops); - - /* Set the uiops for the eventloop. If your client is glib-based, you can safely - * copy this verbatim. */ - purple_eventloop_set_ui_ops(&glib_eventloops); - - /* Set path to search for plugins. The core (libpurple) takes care of loading the - * core-plugins, which includes the protocol-plugins. So it is not essential to add - * any path here, but it might be desired, especially for ui-specific plugins. */ - purple_plugins_add_search_path(CUSTOM_PLUGIN_PATH); - - /* Now that all the essential stuff has been set, let's try to init the core. It's - * necessary to provide a non-NULL name for the current ui to the core. This name - * is used by stuff that depends on this ui, for example the ui-specific plugins. */ - if (!purple_core_init(UI_ID)) { - /* Initializing the core failed. Terminate. */ - fprintf(stderr, - "libpurple initialization failed. Dumping core.\n" - "Please report this!\n"); - abort(); - } - - /* Load the preferences. */ - purple_prefs_load(); - - /* Load the desired plugins. The client should save the list of loaded plugins in - * the preferences using purple_plugins_save_loaded(PLUGIN_SAVE_PREF) */ - purple_plugins_load_saved(PLUGIN_SAVE_PREF); -} - -static void -signed_on(PurpleConnection *gc, gpointer null) { - PurpleAccount *account = purple_connection_get_account(gc); - printf("Account connected: %s %s\n", purple_account_get_username(account), purple_account_get_protocol_id(account)); -} - -static void -buddy_signed_on(PurpleBuddy *buddy) { - PurpleConnection *gc = purple_account_get_connection(purple_buddy_get_account(buddy)); - PurplePlugin* prpl = purple_connection_get_prpl(gc); - PurplePluginProtocolInfo* prpl_info = PURPLE_PLUGIN_PROTOCOL_INFO(prpl); - - if (prpl_info->send_file && (prpl_info->can_receive_file && prpl_info->can_receive_file(gc, "sradomski@localhost"))) { - prpl_info->send_file(gc, "sradomski@localhost", "/Users/sradomski/Documents/W3C Standards.pdf"); - } - -} - -static void -connect_to_signals_for_demonstration_purposes_only(void) { - static int handle; - purple_signal_connect(purple_connections_get_handle(), "signed-on", &handle, - PURPLE_CALLBACK(signed_on), NULL); - purple_signal_connect(purple_blist_get_handle(), "buddy-signed-on", &handle, - PURPLE_CALLBACK(buddy_signed_on), NULL); -} - -int main(int argc, char *argv[]) { - GList *iter; - GMainLoop *loop = g_main_loop_new(NULL, FALSE); - PurpleAccount *account; - PurpleSavedStatus *status; - -#ifndef _WIN32 - /* libpurple's built-in DNS resolution forks processes to perform - * blocking lookups without blocking the main process. It does not - * handle SIGCHLD itself, so if the UI does not you quickly get an army - * of zombie subprocesses marching around. - */ - signal(SIGCHLD, SIG_IGN); -#endif - - init_libpurple(); - - printf("libpurple initialized.\n"); - - iter = purple_plugins_get_protocols(); - - /* Create the account */ - account = purple_account_new("uscxml@localhost", "prpl-jabber"); - - /* Get the password for the account */ - purple_account_set_password(account, "password"); - - /* It's necessary to enable the account first. */ - purple_account_set_enabled(account, UI_ID, TRUE); - - /* Now, to connect the account(s), create a status and activate it. */ - status = purple_savedstatus_new(NULL, PURPLE_STATUS_AVAILABLE); - purple_savedstatus_activate(status); - - connect_to_signals_for_demonstration_purposes_only(); - - g_main_loop_run(loop); - - return 0; -} - diff --git a/test/src/test-lifecycle.cpp b/test/src/test-lifecycle.cpp index e61d6db..528d903 100644 --- a/test/src/test-lifecycle.cpp +++ b/test/src/test-lifecycle.cpp @@ -1,21 +1,10 @@ #include "uscxml/config.h" #include "uscxml/Interpreter.h" -#include <glog/logging.h> +#include "uscxml/interpreter/InterpreterMonitor.h" +#include <easylogging++.h> -#include "uscxml/plugins/invoker/filesystem/dirmon/DirMonInvoker.h" #include <boost/algorithm/string.hpp> - -#ifdef HAS_SIGNAL_H -#include <signal.h> -#endif - -#ifdef HAS_EXECINFO_H -#include <execinfo.h> -#endif - -#ifdef HAS_DLFCN_H -#include <dlfcn.h> -#endif +#include <xercesc/util/PlatformUtils.hpp> #ifdef _WIN32 #include "XGetopt.h" @@ -23,74 +12,9 @@ int startedAt; int lastTransitionAt; -bool testIssue56(); - -#ifdef HAS_EXECINFO_H -void printBacktrace(void** array, int size) { - char** messages = backtrace_symbols(array, size); - for (size_t i = 0; i < size && messages != NULL; ++i) { - std::cerr << "\t" << messages[i] << std::endl; - } - std::cerr << std::endl; - free(messages); -} - -#ifdef HAS_DLFCN_H -// see https://gist.github.com/nkuln/2020860 -typedef void (*cxa_throw_type)(void *, void *, void (*) (void *)); -cxa_throw_type orig_cxa_throw = 0; - -void load_orig_throw_code() { - orig_cxa_throw = (cxa_throw_type) dlsym(RTLD_NEXT, "__cxa_throw"); -} - -extern "C" -CXA_THROW_SIGNATURE { - std::cerr << __FUNCTION__ << " will throw exception from " << std::endl; - if (orig_cxa_throw == 0) - load_orig_throw_code(); - - void *array[50]; - size_t size = backtrace(array, 50); - printBacktrace(array, size); - orig_cxa_throw(thrown_exception, pvtinfo, dest); -} -#endif -#endif - - -// see http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c -void customTerminate() { - static bool tried_throw = false; - try { - // try once to re-throw currently active exception - if (!tried_throw) { - throw; - tried_throw = true; - } else { - tried_throw = false; - }; - } catch (const std::exception &e) { - std::cerr << __FUNCTION__ << " caught unhandled exception. what(): " - << e.what() << std::endl; - } catch (const uscxml::Event &e) { - std::cerr << __FUNCTION__ << " caught unhandled exception. Event: " - << e << std::endl; - } catch (...) { - std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." - << std::endl; - } - -#ifdef HAS_EXECINFO_H - void * array[50]; - int size = backtrace(array, 50); - - printBacktrace(array, size); -#endif - abort(); -} using namespace uscxml; +using namespace xercesc; enum CallbackType { USCXML_BEFOREPROCESSINGEVENT, @@ -124,73 +48,67 @@ std::list<CallbackType> callBackSeq; class SequenceCheckingMonitor : public InterpreterMonitor { - virtual void beforeProcessingEvent(Interpreter interpreter, const Event& event) { + virtual void beforeProcessingEvent(const Event& event) { CHECK_CALLBACK_TYPE(USCXML_BEFOREPROCESSINGEVENT); } - virtual void beforeMicroStep(Interpreter interpreter) { + virtual void beforeMicroStep() { CHECK_CALLBACK_TYPE(USCXML_BEFOREMICROSTEP); } - virtual void beforeExitingState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) { - if (!moreComing) - CHECK_CALLBACK_TYPE(USCXML_BEFOREEXITINGSTATE); + virtual void beforeExitingState(const xercesc::DOMElement* state) { + CHECK_CALLBACK_TYPE(USCXML_BEFOREEXITINGSTATE); } - virtual void afterExitingState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) { - if (!moreComing) - CHECK_CALLBACK_TYPE(USCXML_AFTEREXITINGSTATE); + virtual void afterExitingState(const xercesc::DOMElement* state) { + CHECK_CALLBACK_TYPE(USCXML_AFTEREXITINGSTATE); } - virtual void beforeExecutingContent(Interpreter interpreter, const Arabica::DOM::Element<std::string>& element) { + virtual void beforeExecutingContent(const xercesc::DOMElement* element) { CHECK_CALLBACK_TYPE(USCXML_BEFOREEXECUTINGCONTENT); } - virtual void afterExecutingContent(Interpreter interpreter, const Arabica::DOM::Element<std::string>& element) { + virtual void afterExecutingContent(const xercesc::DOMElement* element) { CHECK_CALLBACK_TYPE(USCXML_AFTEREXECUTINGCONTENT); } - virtual void beforeUninvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) { + virtual void beforeUninvoking(const xercesc::DOMElement* invokeElem, const std::string& invokeid) { CHECK_CALLBACK_TYPE(USCXML_BEFOREUNINVOKING); } - virtual void afterUninvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) { + virtual void afterUninvoking(const xercesc::DOMElement* invokeElem, const std::string& invokeid) { CHECK_CALLBACK_TYPE(USCXML_AFTERUNINVOKING); } - virtual void beforeTakingTransition(Interpreter interpreter, const Arabica::DOM::Element<std::string>& transition, bool moreComing) { - if (!moreComing) - CHECK_CALLBACK_TYPE(USCXML_BEFORETAKINGTRANSITION); + virtual void beforeTakingTransition(const xercesc::DOMElement* transition) { + CHECK_CALLBACK_TYPE(USCXML_BEFORETAKINGTRANSITION); } - virtual void afterTakingTransition(Interpreter interpreter, const Arabica::DOM::Element<std::string>& transition, bool moreComing) { - if (!moreComing) - CHECK_CALLBACK_TYPE(USCXML_AFTERTAKINGTRANSITION); + virtual void afterTakingTransition(const xercesc::DOMElement* transition) { + CHECK_CALLBACK_TYPE(USCXML_AFTERTAKINGTRANSITION); } - virtual void beforeEnteringState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) { - if (!moreComing) - CHECK_CALLBACK_TYPE(USCXML_BEFOREENTERINGSTATE); + virtual void beforeEnteringState(const xercesc::DOMElement* state) { + CHECK_CALLBACK_TYPE(USCXML_BEFOREENTERINGSTATE); } - virtual void afterEnteringState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) { - if (!moreComing) - CHECK_CALLBACK_TYPE(USCXML_AFTERENTERINGSTATE); + virtual void afterEnteringState(const xercesc::DOMElement* state) { + CHECK_CALLBACK_TYPE(USCXML_AFTERENTERINGSTATE); } - virtual void beforeInvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) { + virtual void beforeInvoking(const xercesc::DOMElement* invokeElem, const std::string& invokeid) { CHECK_CALLBACK_TYPE(USCXML_BEFOREINVOKING); } - virtual void afterInvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) { + virtual void afterInvoking(const xercesc::DOMElement* invokeElem, const std::string& invokeid) { CHECK_CALLBACK_TYPE(USCXML_AFTERINVOKING); } - virtual void afterMicroStep(Interpreter interpreter) { + virtual void afterMicroStep() { CHECK_CALLBACK_TYPE(USCXML_AFTERMICROSTEP); } - virtual void onStableConfiguration(Interpreter interpreter) { + virtual void onStableConfiguration() { CHECK_CALLBACK_TYPE(USCXML_ONSTABLECONFIGURATION); } - virtual void beforeCompletion(Interpreter interpreter) { + virtual void beforeCompletion() { CHECK_CALLBACK_TYPE(USCXML_BEFORECOMPLETION); } - virtual void afterCompletion(Interpreter interpreter) { + virtual void afterCompletion() { CHECK_CALLBACK_TYPE(USCXML_AFTERCOMPLETION); } @@ -199,16 +117,7 @@ class SequenceCheckingMonitor : public InterpreterMonitor { int main(int argc, char** argv) { - std::set_terminate(customTerminate); - -#if defined(HAS_SIGNAL_H) && !defined(WIN32) - signal(SIGPIPE, SIG_IGN); -#endif - - google::InitGoogleLogging(argv[0]); - google::LogToStderr(); - - SequenceCheckingMonitor* mon = new SequenceCheckingMonitor(); + SequenceCheckingMonitor mon; int iterations = 1; @@ -230,7 +139,7 @@ int main(int argc, char** argv) { try { const char* xml = "<invalid />"; Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addMonitor(mon); + interpreter.setMonitor(&mon); assert(interpreter.getState() == USCXML_INSTANTIATED); interpreter.step(); assert(false); @@ -250,7 +159,7 @@ int main(int argc, char** argv) { " <final id=\"done\" />" "</scxml>"; Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addMonitor(mon); + interpreter.setMonitor(&mon); assert(interpreter.getState() == USCXML_INSTANTIATED); interpreter.step(); assert(false); @@ -273,39 +182,42 @@ int main(int argc, char** argv) { "</scxml>"; Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addMonitor(mon); + interpreter.setMonitor(&mon); - callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); - callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREMICROSTEP); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // scxml callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // start + callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_AFTERMICROSTEP); callBackSeq.push_back(USCXML_BEFOREMICROSTEP); - callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); + callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); // start callBackSeq.push_back(USCXML_AFTEREXITINGSTATE); callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // s2 callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); callBackSeq.push_back(USCXML_AFTERMICROSTEP); callBackSeq.push_back(USCXML_BEFOREMICROSTEP); - callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); + callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); // s2 callBackSeq.push_back(USCXML_AFTEREXITINGSTATE); callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // final callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); callBackSeq.push_back(USCXML_AFTERMICROSTEP); - callBackSeq.push_back(USCXML_BEFORECOMPLETION); + callBackSeq.push_back(USCXML_BEFORECOMPLETION); // interpreter is finalizing callBackSeq.push_back(USCXML_AFTERCOMPLETION); assert(interpreter.getState() == USCXML_INSTANTIATED); assert(interpreter.step() == USCXML_INITIALIZED); - assert(interpreter.step() == USCXML_MICROSTEPPED); - assert(interpreter.step() == USCXML_MICROSTEPPED); - assert(interpreter.step() == USCXML_FINISHED); + assert(interpreter.step() == USCXML_MICROSTEPPED); // initial config + assert(interpreter.step() == USCXML_MICROSTEPPED); // s2 + assert(interpreter.step() == USCXML_MICROSTEPPED); // done + assert(interpreter.step() == USCXML_FINISHED); // cleaned up assert(callBackSeq.empty()); } @@ -320,19 +232,21 @@ int main(int argc, char** argv) { "</scxml>"; Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addMonitor(mon); + interpreter.setMonitor(&mon); - callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); - callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREMICROSTEP); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // scxml + callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // start callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_AFTERMICROSTEP); callBackSeq.push_back(USCXML_BEFOREMICROSTEP); - callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); + callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); // start callBackSeq.push_back(USCXML_AFTEREXITINGSTATE); callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // done callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); callBackSeq.push_back(USCXML_AFTERMICROSTEP); @@ -342,20 +256,24 @@ int main(int argc, char** argv) { assert(interpreter.getState() == USCXML_INSTANTIATED); assert(interpreter.step() == USCXML_INITIALIZED); assert(interpreter.step() == USCXML_MICROSTEPPED); + assert(interpreter.step() == USCXML_MICROSTEPPED); assert(interpreter.step() == USCXML_FINISHED); + assert(callBackSeq.empty()); interpreter.reset(); - callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); - callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREMICROSTEP); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // scxml + callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // start callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_AFTERMICROSTEP); callBackSeq.push_back(USCXML_BEFOREMICROSTEP); - callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); + callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); // start callBackSeq.push_back(USCXML_AFTEREXITINGSTATE); callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // done callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); callBackSeq.push_back(USCXML_AFTERMICROSTEP); @@ -365,6 +283,7 @@ int main(int argc, char** argv) { assert(interpreter.getState() == USCXML_INSTANTIATED); assert(interpreter.step() == USCXML_INITIALIZED); assert(interpreter.step() == USCXML_MICROSTEPPED); + assert(interpreter.step() == USCXML_MICROSTEPPED); assert(interpreter.step() == USCXML_FINISHED); } @@ -385,17 +304,19 @@ int main(int argc, char** argv) { "</scxml>"; Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addMonitor(mon); - - callBackSeq.push_back(USCXML_BEFORETAKINGTRANSITION); - callBackSeq.push_back(USCXML_AFTERTAKINGTRANSITION); - callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); - callBackSeq.push_back(USCXML_BEFOREEXECUTINGCONTENT); + interpreter.setMonitor(&mon); + callBackSeq.push_back(USCXML_BEFOREMICROSTEP); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // scxml + callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); + callBackSeq.push_back(USCXML_BEFOREENTERINGSTATE); // start + callBackSeq.push_back(USCXML_BEFOREEXECUTINGCONTENT); // send callBackSeq.push_back(USCXML_AFTEREXECUTINGCONTENT); callBackSeq.push_back(USCXML_AFTERENTERINGSTATE); - callBackSeq.push_back(USCXML_ONSTABLECONFIGURATION); + callBackSeq.push_back(USCXML_AFTERMICROSTEP); + callBackSeq.push_back(USCXML_ONSTABLECONFIGURATION); callBackSeq.push_back(USCXML_BEFOREPROCESSINGEVENT); + callBackSeq.push_back(USCXML_BEFOREMICROSTEP); callBackSeq.push_back(USCXML_BEFOREEXITINGSTATE); callBackSeq.push_back(USCXML_AFTEREXITINGSTATE); @@ -419,8 +340,10 @@ int main(int argc, char** argv) { assert(interpreter.getState() == USCXML_INSTANTIATED); assert(interpreter.step() == USCXML_INITIALIZED); + assert(interpreter.step() == USCXML_MICROSTEPPED); + assert(interpreter.step() == USCXML_MACROSTEPPED); assert(interpreter.step() == USCXML_IDLE); - assert(interpreter.step(true) == USCXML_MACROSTEPPED); + assert(interpreter.step(true) == USCXML_MICROSTEPPED); assert(interpreter.step() == USCXML_MICROSTEPPED); assert(interpreter.step() == USCXML_FINISHED); } diff --git a/test/src/test-misc.cpp b/test/src/test-misc.cpp deleted file mode 100644 index 504b6a6..0000000 --- a/test/src/test-misc.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/Common.h" -#include "uscxml/concurrency/Timer.h" -#include "uscxml/concurrency/tinythread.h" - -#include <iostream> - -using namespace uscxml; - -Timer t1; - -bool testTimers() { - { - Measurement m(&t1); - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(1000)); - } - std::cout << t1.elapsed << std::endl; - return true; -} - -int main(int argc, char** argv) { - testTimers(); - return 0; -}
\ No newline at end of file diff --git a/test/src/test-mmi.cpp b/test/src/test-mmi.cpp deleted file mode 100644 index 52deeef..0000000 --- a/test/src/test-mmi.cpp +++ /dev/null @@ -1,775 +0,0 @@ -#include <iostream> -#include <string> - -#include "uscxml/messages/MMIMessages.h" - -#include <SAX/helpers/InputSourceResolver.hpp> -#include <DOM/SAX2DOM/SAX2DOM.hpp> -#include <DOM/io/Stream.hpp> - -#include <assert.h> -#include <boost/algorithm/string.hpp> - -using namespace uscxml; -using namespace boost; - -Arabica::DOM::Document<std::string> xmlToDoc(const std::string& xml) { - std::stringstream* ss = new std::stringstream(); - (*ss) << xml; - std::auto_ptr<std::istream> ssPtr(ss); - Arabica::SAX::InputSource<std::string> inputSource; - inputSource.setByteStream(ssPtr); - - Arabica::SAX2DOM::Parser<std::string> parser; - parser.parse(inputSource); - return parser.getDocument(); -} - -int main(int argc, char** argv) { - { - // --- NewContextRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"><mmi:NewContextRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:RequestID=\"request-1\"></mmi:NewContextRequest></mmi:mmi>"; - - NewContextRequest msg = NewContextRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "NewContextRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.data, "")); - - NewContextRequest msg2 = NewContextRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "NewContextRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.data, "")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.newcontext"); - assert(ev.origin == msg.source); - } - - { - // --- NewContextResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:NewContextResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:RequestID=\"request-1\" mmi:Status=\"success\" mmi:Context=\"URI-1\"> </mmi:NewContextResponse></mmi:mmi>"; - NewContextResponse msg = NewContextResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "NewContextResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(msg.status == StatusResponse::SUCCESS); - assert(boost::iequals(msg.statusInfo, "")); - assert(boost::iequals(msg.context, "URI-1")); - assert(boost::iequals(msg.data, "")); - - NewContextResponse msg2 = NewContextResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "NewContextResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(msg2.status == StatusResponse::SUCCESS); - assert(boost::iequals(msg2.statusInfo, "")); - assert(boost::iequals(msg2.context, "URI-1")); - assert(boost::iequals(msg2.data, "")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.newcontext"); - assert(ev.origin == msg.source); - - } - - { - // --- PrepareRequest ContentURL - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:PrepareRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"URI-1\" mmi:RequestID=\"request-1\"> <mmi:ContentURL mmi:href=\"someContentURI\" mmi:max-age=\"\" mmi:fetchtimeout=\"1s\"/> </mmi:PrepareRequest></mmi:mmi>"; - PrepareRequest msg = PrepareRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "PrepareRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "URI-1")); - assert(boost::iequals(msg.data, "")); - assert(boost::iequals(msg.content, "")); - assert(boost::iequals(msg.contentURL.href, "someContentURI")); - assert(boost::iequals(msg.contentURL.maxAge, "")); - assert(boost::iequals(msg.contentURL.fetchTimeout, "1s")); - - PrepareRequest msg2 = PrepareRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "PrepareRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "URI-1")); - assert(boost::iequals(msg2.data, "")); - assert(boost::iequals(msg2.content, "")); - assert(boost::iequals(msg2.contentURL.href, "someContentURI")); - assert(boost::iequals(msg2.contentURL.maxAge, "")); - assert(boost::iequals(msg2.contentURL.fetchTimeout, "1s")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.prepare"); - assert(ev.origin == msg.source); - - } - - { - // --- PrepareRequest Content - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\" xmlns:vxml=\"http://www.w3.org/2001/vxml\"> <mmi:PrepareRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"URI-1\" mmi:RequestID=\"request-1\" > <mmi:content> <vxml:vxml version=\"2.0\"> <vxml:form> <vxml:block>Hello World!</vxml:block> </vxml:form> </vxml:vxml> </mmi:content> </mmi:PrepareRequest></mmi:mmi>"; - PrepareRequest msg = PrepareRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "PrepareRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "URI-1")); - assert(msg.contentDOM); - - PrepareRequest msg2 = PrepareRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "PrepareRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "URI-1")); - assert(msg2.content.size() > 0); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.prepare"); - assert(ev.origin == msg.source); - - } - - { - // --- PrepareResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:PrepareResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\" mmi:Status=\"success\"/></mmi:mmi>"; - PrepareResponse msg = PrepareResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "PrepareResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.status == StatusResponse::SUCCESS); - - PrepareResponse msg2 = PrepareResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "PrepareResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.prepare"); - assert(ev.origin == msg.source); - - } - - { - // --- PrepareResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:PrepareResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\" mmi:Status=\"failure\"> <mmi:statusInfo> NotAuthorized </mmi:statusInfo> </mmi:PrepareResponse></mmi:mmi>"; - PrepareResponse msg = PrepareResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "PrepareResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(boost::iequals(msg.statusInfo, " NotAuthorized ")); - assert(msg.status == StatusResponse::FAILURE); - - PrepareResponse msg2 = PrepareResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "PrepareResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(boost::iequals(msg2.statusInfo, " NotAuthorized ")); - assert(msg2.status == StatusResponse::FAILURE); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.prepare"); - assert(ev.origin == msg.source); - - } - - { - // --- StartRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:StartRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"URI-1\" mmi:RequestID=\"request-1\"> <mmi:ContentURL mmi:href=\"someContentURI\" mmi:max-age=\"\" mmi:fetchtimeout=\"1s\"/> </mmi:StartRequest></mmi:mmi>"; - StartRequest msg = StartRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "StartRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "URI-1")); - - StartRequest msg2 = StartRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "StartRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "URI-1")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.start"); - assert(ev.origin == msg.source); - - } - - { - // --- StartRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:StartRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"URI-1\" mmi:RequestID=\"request-1\"> <mmi:ContentURL mmi:href=\"someContentURI\" mmi:max-age=\"\" mmi:fetchtimeout=\"1s\"/> <mmi:Data> { \"foo\": 12 } </mmi:Data> </mmi:StartRequest></mmi:mmi>"; - StartRequest msg = StartRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "StartRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "URI-1")); - - StartRequest msg2 = StartRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "StartRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "URI-1")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.start"); - assert(ev.data.compound["foo"] == 12); - assert(ev.origin == msg.source); - - } - - - - { - // --- StartResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:StartResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\" mmi:Status=\"failure\"> <mmi:statusInfo> NotAuthorized </mmi:statusInfo> </mmi:StartResponse></mmi:mmi>"; - StartResponse msg = StartResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "StartResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(boost::iequals(msg.statusInfo, " NotAuthorized ")); - assert(msg.status == StatusResponse::FAILURE); - - StartResponse msg2 = StartResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "StartResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(boost::iequals(msg2.statusInfo, " NotAuthorized ")); - assert(msg2.status == StatusResponse::FAILURE); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.start"); - assert(ev.origin == msg.source); - - } - - { - // --- DoneNotification - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\" xmlns:emma=\"http://www.w3.org/2003/04/emma\"> <mmi:DoneNotification mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:Status=\"success\" mmi:RequestID=\"request-1\" mmi:Confidential=\"true\"> <mmi:Data> <emma:emma version=\"1.0\"> <emma:interpretation id=\"int1\" emma:medium=\"acoustic\" emma:confidence=\".75\" emma:mode=\"voice\" emma:tokens=\"flights from boston to denver\"> <origin>Boston</origin> <destination>Denver</destination> </emma:interpretation> </emma:emma> </mmi:Data> </mmi:DoneNotification></mmi:mmi>"; - DoneNotification msg = DoneNotification::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "DoneNotification")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.data.size() > 0); - assert(msg.status == StatusResponse::SUCCESS); - - DoneNotification msg2 = DoneNotification::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "DoneNotification")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.data.size() > 0); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.notification.done"); - assert(ev.origin == msg.source); - - } - - { - // --- DoneNotification - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\" xmlns:emma=\"http://www.w3.org/2003/04/emma\"> <mmi:DoneNotification mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:Status=\"success\" mmi:RequestID=\"request-1\" > <mmi:Data> <emma:emma version=\"1.0\"> <emma:interpretation id=\"int1\" emma:no-input=\"true\"/> </emma:emma> </mmi:Data> </mmi:DoneNotification></mmi:mmi>"; - DoneNotification msg = DoneNotification::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "DoneNotification")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.data.size() > 0); - assert(msg.status == StatusResponse::SUCCESS); - - DoneNotification msg2 = DoneNotification::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "DoneNotification")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.data.size() > 0); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.notification.done"); - assert(ev.origin == msg.source); - - } - - { - // --- CancelRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:CancelRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\"/></mmi:mmi>"; - CancelRequest msg = CancelRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "CancelRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - - CancelRequest msg2 = CancelRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "CancelRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.cancel"); - assert(ev.origin == msg.source); - - } - - { - // --- CancelResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:CancelResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\" mmi:Status=\"success\"/></mmi:mmi>"; - CancelResponse msg = CancelResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "CancelResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.status == StatusResponse::SUCCESS); - - CancelResponse msg2 = CancelResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "CancelResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.cancel"); - assert(ev.origin == msg.source); - - } - - { - // --- PauseRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:PauseRequest mmi:Context=\"someURI\" mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:RequestID=\"request-1\"/></mmi:mmi>"; - PauseRequest msg = PauseRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "PauseRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - - PauseRequest msg2 = PauseRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "PauseRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.pause"); - assert(ev.origin == msg.source); - - } - - { - // --- PauseResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:PauseResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\" mmi:Status=\"success\"/></mmi:mmi>"; - PauseResponse msg = PauseResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "PauseResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.status == StatusResponse::SUCCESS); - - PauseResponse msg2 = PauseResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "PauseResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.pause"); - assert(ev.origin == msg.source); - - } - - { - // --- ResumeRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:ResumeRequest mmi:Context=\"someURI\" mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:RequestID=\"request-1\"/></mmi:mmi>"; - ResumeRequest msg = ResumeRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "ResumeRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - - ResumeRequest msg2 = ResumeRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "ResumeRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.resume"); - assert(ev.origin == msg.source); - - } - - { - // --- ResumeResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:ResumeResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\" mmi:Status=\"success\"/></mmi:mmi>"; - ResumeResponse msg = ResumeResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "ResumeResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.status == StatusResponse::SUCCESS); - - ResumeResponse msg2 = ResumeResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "ResumeResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.resume"); - assert(ev.origin == msg.source); - - } - - { - // --- ExtensionNotification - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:ExtensionNotification mmi:Name=\"appEvent\" mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\"> </mmi:ExtensionNotification></mmi:mmi>"; - ExtensionNotification msg = ExtensionNotification::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "ExtensionNotification")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(boost::iequals(msg.name, "appEvent")); - - ExtensionNotification msg2 = ExtensionNotification::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "ExtensionNotification")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(boost::iequals(msg2.name, "appEvent")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "appEvent"); - assert(ev.origin == msg.source); - - } - - { - // --- ExtensionNotification - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:ExtensionNotification mmi:Name=\"appEvent\" mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-1\"> <mmi:Data> { \"foo\": 12 } </mmi:Data> </mmi:ExtensionNotification></mmi:mmi>"; - ExtensionNotification msg = ExtensionNotification::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "ExtensionNotification")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-1")); - assert(boost::iequals(msg.context, "someURI")); - assert(boost::iequals(msg.name, "appEvent")); - - ExtensionNotification msg2 = ExtensionNotification::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "ExtensionNotification")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-1")); - assert(boost::iequals(msg2.context, "someURI")); - assert(boost::iequals(msg2.name, "appEvent")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "appEvent"); - assert(ev.data.compound["foo"] == 12); - assert(ev.origin == msg.source); - - } - - { - // --- ClearContextRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:ClearContextRequest mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-2\"/></mmi:mmi>"; - ClearContextRequest msg = ClearContextRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "ClearContextRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-2")); - assert(boost::iequals(msg.context, "someURI")); - - ClearContextRequest msg2 = ClearContextRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "ClearContextRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-2")); - assert(boost::iequals(msg2.context, "someURI")); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.clearcontext"); - assert(ev.origin == msg.source); - - } - - { - // --- ClearContextResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:ClearContextResponse mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:Context=\"someURI\" mmi:RequestID=\"request-2\" mmi:Status=\"success\"/></mmi:mmi>"; - ClearContextResponse msg = ClearContextResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "ClearContextResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-2")); - assert(boost::iequals(msg.context, "someURI")); - assert(msg.status == StatusResponse::SUCCESS); - - ClearContextResponse msg2 = ClearContextResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "ClearContextResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-2")); - assert(boost::iequals(msg2.context, "someURI")); - assert(msg2.status == StatusResponse::SUCCESS); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.clearcontext"); - assert(ev.origin == msg.source); - - } - - { - // --- StatusRequest - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:StatusRequest mmi:RequestAutomaticUpdate=\"true\" mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:RequestID=\"request-3\" mmi:Context=\"aToken\"/></mmi:mmi>"; - StatusRequest msg = StatusRequest::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "StatusRequest")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-3")); - assert(boost::iequals(msg.context, "aToken")); - assert(msg.automaticUpdate); - - StatusRequest msg2 = StatusRequest::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "StatusRequest")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-3")); - assert(boost::iequals(msg2.context, "aToken")); - assert(msg2.automaticUpdate); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.request.status"); - assert(ev.origin == msg.source); - - } - - { - // --- StatusResponse - std::stringstream ss; - ss << "<mmi:mmi xmlns:mmi=\"http://www.w3.org/2008/04/mmi-arch\" version=\"1.0\"> <mmi:StatusResponse mmi:AutomaticUpdate=\"true\" mmi:Status=\"alive\" mmi:Source=\"someURI\" mmi:Target=\"someOtherURI\" mmi:RequestID=\"request-3\" mmi:Context=\"aToken\"/> </mmi:mmi>"; - StatusResponse msg = StatusResponse::fromXML(xmlToDoc(ss.str())); - assert(boost::iequals(msg.tagName, "StatusResponse")); - assert(boost::iequals(msg.source, "someURI")); - assert(boost::iequals(msg.target, "someOtherURI")); - assert(boost::iequals(msg.requestId, "request-3")); - assert(boost::iequals(msg.context, "aToken")); - assert(msg.status == StatusResponse::ALIVE); - - StatusResponse msg2 = StatusResponse::fromXML(msg.toXML()); - assert(boost::iequals(msg2.tagName, "StatusResponse")); - assert(boost::iequals(msg2.source, "someURI")); - assert(boost::iequals(msg2.target, "someOtherURI")); - assert(boost::iequals(msg2.requestId, "request-3")); - assert(boost::iequals(msg2.context, "aToken")); - assert(msg2.status == StatusResponse::ALIVE); - - std::stringstream xml1SS; - std::stringstream xml2SS; - xml1SS << msg.toXML(); - xml2SS << msg2.toXML(); - assert(xml1SS.str() == xml2SS.str()); - - Event ev = msg; - assert(ev.name == "mmi.response.status"); - assert(ev.origin == msg.source); - - } - -}
\ No newline at end of file diff --git a/test/src/test-predicates.cpp b/test/src/test-predicates.cpp deleted file mode 100644 index 0aff104..0000000 --- a/test/src/test-predicates.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#define protected public -#include "uscxml/Interpreter.h" -#include "uscxml/util/String.h" -#undef protected -#include <iostream> - -int main(int argc, char** argv) { - try { - using namespace uscxml; - using namespace Arabica::DOM; - using namespace Arabica::XPath; - - const char* xml = - "<scxml>" - " <state id=\"atomic\" />" - " <state id=\"compound\">" - " <state id=\"compoundChild1\" />" - " <state id=\"compoundChild2\" />" - " </state>" - " <parallel id=\"parallel\">" - " </parallel>" - "</scxml>"; - - Interpreter interpreter = Interpreter::fromXML(xml, ""); - assert(interpreter); - interpreter.getImpl()->init(); - - Element<std::string> atomicState = interpreter.getImpl()->getState("atomic"); - assert(InterpreterImpl::isAtomic(atomicState)); - assert(!InterpreterImpl::isParallel(atomicState)); - assert(!InterpreterImpl::isCompound(atomicState)); - - Element<std::string> compoundState = interpreter.getImpl()->getState("compound"); - assert(!InterpreterImpl::isAtomic(compoundState)); - assert(!InterpreterImpl::isParallel(compoundState)); - assert(InterpreterImpl::isCompound(compoundState)); - - Element<std::string> parallelState = interpreter.getImpl()->getState("parallel"); - assert(!InterpreterImpl::isAtomic(parallelState)); - assert(InterpreterImpl::isParallel(parallelState)); - assert(!InterpreterImpl::isCompound(parallelState)); // parallel states are not compound! - - NodeSet<std::string> initialState = interpreter.getImpl()->getInitialStates(); - assert(initialState[0] == atomicState); - - NodeSet<std::string> childs = interpreter.getImpl()->getChildStates(compoundState); - Node<std::string> compoundChild1 = interpreter.getImpl()->getState("compoundChild1"); - Node<std::string> compoundChild2 = interpreter.getImpl()->getState("compoundChild2"); - assert(childs.size() > 0); - assert(InterpreterImpl::isMember(compoundChild1, childs)); - assert(InterpreterImpl::isMember(compoundChild2, childs)); - assert(!InterpreterImpl::isMember(compoundState, childs)); - - assert(InterpreterImpl::isDescendant(compoundChild1, compoundState)); - - { - std::string idrefs("id1"); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 1); - assert(tokenizedIdrefs.front().compare("id1") == 0); - } - - { - std::string idrefs(" id1"); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 1); - assert(tokenizedIdrefs.front().compare("id1") == 0); - } - - { - std::string idrefs(" id1 "); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 1); - assert(tokenizedIdrefs.front().compare("id1") == 0); - } - - { - std::string idrefs(" \tid1\n "); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 1); - assert(tokenizedIdrefs.front().compare("id1") == 0); - } - - { - std::string idrefs("id1 id2 id3"); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 3); - assert(tokenizedIdrefs.front().compare("id1") == 0); - tokenizedIdrefs.pop_front(); - assert(tokenizedIdrefs.front().compare("id2") == 0); - tokenizedIdrefs.pop_front(); - assert(tokenizedIdrefs.front().compare("id3") == 0); - } - - { - std::string idrefs("\t id1 \nid2\n\n id3\t"); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 3); - assert(tokenizedIdrefs.front().compare("id1") == 0); - tokenizedIdrefs.pop_front(); - assert(tokenizedIdrefs.front().compare("id2") == 0); - tokenizedIdrefs.pop_front(); - assert(tokenizedIdrefs.front().compare("id3") == 0); - } - - { - std::string idrefs("id1 \nid2 \tid3"); - std::list<std::string> tokenizedIdrefs = tokenize(idrefs); - assert(tokenizedIdrefs.size() == 3); - assert(tokenizedIdrefs.front().compare("id1") == 0); - tokenizedIdrefs.pop_front(); - assert(tokenizedIdrefs.front().compare("id2") == 0); - tokenizedIdrefs.pop_front(); - assert(tokenizedIdrefs.front().compare("id3") == 0); - } - - std::string transEvents; - transEvents = "error"; - assert(nameMatch(transEvents, "error")); - assert(!nameMatch(transEvents, "foo")); - - transEvents = " error foo"; - assert(nameMatch(transEvents, "error")); - assert(nameMatch(transEvents, "error.send")); - assert(nameMatch(transEvents, "error.send.failed")); - assert(nameMatch(transEvents, "foo")); - assert(nameMatch(transEvents, "foo.bar")); - assert(!nameMatch(transEvents, "errors.my.custom")); - assert(!nameMatch(transEvents, "errorhandler.mistake")); - // is the event name case sensitive? - // assert(!nameMatch(transEvents, "errOr.send")); - assert(!nameMatch(transEvents, "foobar")); - } catch(std::exception e) { - std::cout << e.what(); - return false; - } catch(uscxml::Event e) { - std::cout << e; - return false; - } -}
\ No newline at end of file diff --git a/test/src/test-promela-parser.cpp b/test/src/test-promela-parser.cpp deleted file mode 100644 index f3ac4cc..0000000 --- a/test/src/test-promela-parser.cpp +++ /dev/null @@ -1,316 +0,0 @@ -#define protected public -#include "uscxml/URL.h" -#include "uscxml/Message.h" -#include "uscxml/Interpreter.h" -#include "uscxml/plugins/datamodel/promela/PromelaDataModel.h" -#include "uscxml/plugins/datamodel/promela/PromelaParser.h" -#include "uscxml/transform/ChartToPromela.h" - -#include <assert.h> -#include <boost/algorithm/string.hpp> -#include <iostream> -#include <DOM/SAX2DOM/SAX2DOM.hpp> -#include <DOM/Document.hpp> - -using namespace uscxml; -using namespace boost; -using namespace Arabica::DOM; - -extern int promela_debug; - -void testInlinePromela() { - - DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation(); - Document<std::string> document = domFactory.createDocument("", "", 0); - - { - std::string test = "\ - promela-code This is foo!\ - "; - - Comment<std::string> comment = document.createComment(test); - PromelaInline inl(comment); - assert(inl.type == PromelaInline::PROMELA_CODE); - assert(inl.content == "This is foo!"); - } - - { - std::string test = "\ - promela-code\n \ - This is foo!\ - "; - - Comment<std::string> comment = document.createComment(test); - PromelaInline inl(comment); - assert(inl.type == PromelaInline::PROMELA_CODE); - assert(inl.content == "This is foo!"); - } - - { - std::string test = "\ - promela-event\n \ - [{\"name\": \"e1\", \"data\": { \"foo\": \"some string\" }}, \ - {\"name\": \"e1\", \"data\": { \"bar\": 12 }}]"; - - Comment<std::string> comment = document.createComment(test); - PromelaInline inl(comment); - assert(inl.type == PromelaInline::PROMELA_EVENT_ONLY); - - PromelaEventSource es(inl); - assert(es.events.array.size() == 2); - - } - - { - Interpreter interpreter = Interpreter::fromURL("/Users/sradomski/Documents/TK/Code/uscxml/test/uscxml/promela/test-event-source-auto.scxml"); - assert(interpreter); - PromelaInlines inls(interpreter.getDocument().getDocumentElement()); - - assert(inls.getAllOfType(PromelaInline::PROMELA_EVENT_ONLY).size() == 1); - assert(inls.getAllOfType(PromelaInline::PROMELA_EVENT_ALL_BUT).size() == 1); - interpreter.getImpl()->getState("s0"); - } - -#if 0 - { - std::string test = "\ - #promela-inline:\n \ - This is foo!\ - "; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 1 && - prmInls.nrEventSources == 0 && - prmInls.nrEndLabels == 0 && - prmInls.nrAcceptLabels == 0 && - prmInls.nrProgressLabels == 0); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_CODE); - assert(boost::trim_copy(prmInls.code.front().content) == "This is foo!"); - } - - { - std::string test = "#promela-progress"; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 0 && - prmInls.nrEndLabels == 0 && - prmInls.nrProgressLabels == 1); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_PROGRESS_LABEL); - } - - { - std::string test = "#promela-accept and then some"; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 1 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 0 && - prmInls.nrEndLabels == 0 && - prmInls.nrProgressLabels == 0); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_ACCEPT_LABEL); - } - - { - std::string test = "#promela-end and then some"; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 0 && - prmInls.nrEndLabels == 1 && - prmInls.nrProgressLabels == 0); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_END_LABEL); - } - - { - std::string test = "\ - #promela-event-source:\n \ - This is foo!\ - "; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 1 && - prmInls.nrEndLabels == 0 && - prmInls.nrProgressLabels == 0); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_EVENT_SOURCE); - - PromelaEventSource pmlES(prmInls.code.front()); - assert(pmlES.sequences.size() == 1); - std::list<std::list<std::string> >::iterator seqsIter = pmlES.sequences.begin(); - std::list<std::string>::iterator seqIter = seqsIter->begin(); - assert(*seqIter++ == "This"); - assert(*seqIter++ == "is"); - assert(*seqIter++ == "foo!"); - assert(seqIter == seqsIter->end()); - seqsIter++; - assert(seqsIter == pmlES.sequences.end()); - } - - { - std::string test = "\ - #promela-event-source:\n \ - This is foo!\n \ - This is bar!\n \ - "; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 1 && - prmInls.nrEndLabels == 0 && - prmInls.nrProgressLabels == 0); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_EVENT_SOURCE); - - PromelaEventSource pmlES(prmInls.code.front()); - - assert(pmlES.sequences.size() == 2); - std::list<std::list<std::string> >::iterator seqsIter = pmlES.sequences.begin(); - std::list<std::string>::iterator seqIter = seqsIter->begin(); - assert(*seqIter++ == "This"); - assert(*seqIter++ == "is"); - assert(*seqIter++ == "foo!"); - assert(seqIter == seqsIter->end()); - seqsIter++; - seqIter = seqsIter->begin(); - assert(*seqIter++ == "This"); - assert(*seqIter++ == "is"); - assert(*seqIter++ == "bar!"); - assert(seqIter == seqsIter->end()); - seqsIter++; - assert(seqsIter == pmlES.sequences.end()); - } - - { - std::string test = "\ - #promela-event-source-custom:\n \ - This is foo!\ - "; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 1 && - prmInls.nrEndLabels == 0 && - prmInls.nrProgressLabels == 0); - assert(prmInls.code.size() == 1); - assert(prmInls.code.front().type == PromelaInline::PROMELA_EVENT_SOURCE_CUSTOM); - - PromelaEventSource pmlES(prmInls.code.front()); - - assert(pmlES.sequences.size() == 0); - assert(boost::trim_copy(pmlES.source.content) == "This is foo!"); - } - - { - std::string test = "\ - #promela-event-source-custom:\n \ - This is foo! \n\ - #promela-progress\ - "; - PromelaInlines prmInls = PromelaInlines::fromString(test); - assert(prmInls.nrAcceptLabels == 0 && - prmInls.nrCodes == 0 && - prmInls.nrEventSources == 1 && - prmInls.nrEndLabels == 0 && - prmInls.nrProgressLabels == 1); - assert(prmInls.code.size() == 2); - assert(prmInls.code.front().type == PromelaInline::PROMELA_EVENT_SOURCE_CUSTOM); - - PromelaEventSource pmlES(prmInls.code.front()); - - assert(pmlES.sequences.size() == 0); - assert(boost::trim_copy(pmlES.source.content) == "This is foo!"); - } -#endif -} - -void checkTokenLocations(const std::string& expr, PromelaParserNode* ast) { - if (ast->loc != NULL) { - assert(expr.substr(ast->loc->firstCol, ast->loc->lastCol - ast->loc->firstCol) == ast->value); - } - for (std::list<PromelaParserNode*>::iterator opIter = ast->operands.begin(); opIter != ast->operands.end(); opIter++) { - checkTokenLocations(expr, *opIter); - } -} - -void testPromelaParser() { - - promela_debug = 0; -#if 1 - std::list<std::string> expressions; - /* declarations */ - expressions.push_back("bool b1"); - expressions.push_back("bool b1;"); - expressions.push_back("bool b1, b2, b3"); - expressions.push_back("bool b1, b2, b3;"); - expressions.push_back("bool b1, b2 = 3 + 4, b3, b4, b5;"); - expressions.push_back("bool b1; bool b2; bool b3; bool b4;"); - expressions.push_back("bool b1; bool b2; bool b3, b4, b5;"); - expressions.push_back("bit b = 1;"); - expressions.push_back("byte state = 1;"); - expressions.push_back("bool b1, b2 = 1, b3;"); - expressions.push_back("bool busy[3];"); - expressions.push_back("bool busy[3], us[4];"); - expressions.push_back("mtype = {\nred, white, blue,\nabort, accept, ack, sync_ack, close, connect,\ncreate, data, eof, open, reject, sync, transfer,\nFATAL, NON_FATAL, COMPLETE\n}"); - expressions.push_back("typedef D { short f; byte g }; "); - expressions.push_back("x = 1"); - expressions.push_back("x = foo.bar[2].baz; "); - expressions.push_back("_event.data[1].aParam.key1.key2[1].key3.key4"); - expressions.push_back("_event.data.aParam"); - expressions.push_back("_event.data"); - expressions.push_back("_event"); - expressions.push_back("states"); - expressions.push_back("states[1]"); - expressions.push_back("_x.states[1]"); - expressions.push_back("_x.states[1].foo"); - expressions.push_back("_event.data[1].aParam.key1.key2[1].key3.key4"); - expressions.push_back("\n\n\n\n int foo = 3;\n\nint bar = 5;"); - - - /* expressions */ - expressions.push_back("i+1"); - expressions.push_back("(x == false || t == Bturn);"); - expressions.push_back("a + (1 << b)"); - expressions.push_back("(a + 1) << b"); - expressions.push_back("(b < N)"); - expressions.push_back("(mt+1)%MAX;"); - expressions.push_back("state[0] = state[3] + 5 * state[3*2/n]"); - - /* statements */ - expressions.push_back("t = Bturn;"); - expressions.push_back("c++"); - expressions.push_back("state = state - 1"); - expressions.push_back("printf(\"hello world\\n\")"); - expressions.push_back("printf(\"result %d: %d\\n\", id, res, foo, bar)"); - expressions.push_back("printf(\"x = %d\\n\", x)"); - expressions.push_back("(n <= 1)"); - expressions.push_back("res = (a*a+b)/2*a;"); - expressions.push_back("assert(0) /* a forced stop, (Chapter 6) */"); - expressions.push_back("assert(count == 0 || count == 1)"); - expressions.push_back("busy[4 - 3] = 1;"); - - for (std::list<std::string>::iterator exprIter = expressions.begin(); - exprIter != expressions.end(); - exprIter++) { - try { - std::cout << std::endl << "'" << *exprIter << "':" << std::endl; - PromelaParser ast(*exprIter); - ast.dump(); - if (!boost::contains(*exprIter, "\n")) - checkTokenLocations(*exprIter, ast.ast); - } catch (Event e) { - std::cerr << e << std::endl; - } - } -#endif - -} - -int main(int argc, char** argv) { - testInlinePromela(); - testPromelaParser(); -}
\ No newline at end of file diff --git a/test/src/test-sockets.cpp b/test/src/test-sockets.cpp deleted file mode 100644 index 89e6885..0000000 --- a/test/src/test-sockets.cpp +++ /dev/null @@ -1,164 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/Convenience.h" -#include "uscxml/server/Socket.h" -#include <iostream> -#include <stdexcept> - -#include <event2/event.h> -#include "event2/thread.h" - -#ifdef HAS_SIGNAL_H -#include <signal.h> -#endif - -#include "uscxml/concurrency/tinythread.h" - -using namespace uscxml; - -class TestServer : public ServerSocket { -public: - TestServer(int domain, int type, int protocol) : ServerSocket(domain, type, protocol) {} - virtual void readCallback(const char* data, size_t size, Connection& conn) { - std::string content(data, size); -// std::cout << "Server got: " << content << std::endl; - std::string urghs("hi!"); - conn.reply(urghs.data(), urghs.size()); - }; -}; - -int packetSeq = 0; - -class LogServer : public ServerSocket { -public: - LogServer(int domain, int type, int protocol) : ServerSocket(domain, type, protocol) {} - virtual void readCallback(const char* data, size_t size, Connection& conn) { - std::string content(data, size); - std::cout << "Server got: " << content << std::endl; - }; -}; - -class CountingPacketServer : public PacketServerSocket { -public: - CountingPacketServer(int domain, int type, int protocol, const std::string& sep) : PacketServerSocket(domain, type, protocol, sep) {} - virtual void readCallback(const std::string& packet, Connection& conn) { -// std::cout << "-- " << packet << std::endl; - size_t seq = strTo<size_t>(packet); - assert(seq == packetSeq); - packetSeq++; - }; -}; - -class TestClient : public ClientSocket { -public: - TestClient(int domain, int type, int protocol) : ClientSocket(domain, type, protocol) {} - virtual void readCallback(const char* data, size_t size) { - std::string content(data, size); - }; -}; - -int main(int argc, char** argv) { - -#if defined(HAS_SIGNAL_H) && !defined(WIN32) - signal(SIGPIPE, SIG_IGN); -#endif - -#ifndef _WIN32 - evthread_use_pthreads(); -#else - evthread_use_windows_threads(); -#endif - - if (1) { - packetSeq = 0; - CountingPacketServer server(PF_INET, SOCK_STREAM, 0, std::string("tadaa!")); -// LogServer server(PF_INET, SOCK_STREAM, 0); - server.listen("*", 1235); - server.setBlockSizeRead(1); - - TestClient client(PF_INET, SOCK_STREAM, 0); - client.connect("127.0.0.1", 1235); - - int iterations = 1000; - std::stringstream contentSS; - for (size_t i = 0; i < iterations; i++) { - contentSS << toStr(i); - contentSS << "tadaa!"; - } - client.write(contentSS.str()); - - while(packetSeq != iterations) - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(20)); - } - - if (1) { - packetSeq = 0; - CountingPacketServer server(PF_INET, SOCK_STREAM, 0, std::string("\0", 1)); - server.listen("*", 1235); - - TestClient client(PF_INET, SOCK_STREAM, 0); - client.connect("127.0.0.1", 1235); - - int iterations = 1000; - for (size_t i = 0; i < iterations; i++) { - client.write(toStr(i)); - client.write("\0", 1); - } - - while(packetSeq != iterations) - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(20)); - } - - exit(0); - - if (1) { - // start server socket and connect - int iterations = 100; - - TestServer server(PF_INET, SOCK_STREAM, 0); - try { - server.listen("*", 1234); - - while(iterations--) { - std::cout << iterations << std::endl; - TestClient client(PF_INET, SOCK_STREAM, 0); - client.connect("127.0.0.1", 1234); - - std::string hello("hello"); - client.write(hello.data(), hello.size()); - - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(20)); - } - - } catch (std::runtime_error e) { - std::cout << e.what() << std::endl; - } - } - - { - // connect client to server and kill server - int iterations = 100; - - try { - - while(iterations--) { - std::cout << iterations << std::endl; - TestServer* server = new TestServer(PF_INET, SOCK_STREAM, 0); - server->listen("*", 1236 + iterations); - - TestClient client(PF_INET, SOCK_STREAM, 0); - client.connect("127.0.0.1", 1236 + iterations); - - std::string hello("hello"); - client.write(hello.data(), hello.size()); - - delete server; - - tthread::this_thread::sleep_for(tthread::chrono::milliseconds(20)); - } - - } catch (std::runtime_error e) { - std::cout << e.what() << std::endl; - } - - } -}
\ No newline at end of file diff --git a/test/src/test-state-pass.cpp b/test/src/test-state-pass.cpp new file mode 100644 index 0000000..943b3dc --- /dev/null +++ b/test/src/test-state-pass.cpp @@ -0,0 +1,89 @@ +#include <xercesc/parsers/XercesDOMParser.hpp> +#include <xercesc/dom/DOM.hpp> +#include <xercesc/dom/DOMLSSerializer.hpp> +#include <xercesc/dom/DOMImplementationLS.hpp> +#include <xercesc/sax/HandlerBase.hpp> +#include <xercesc/util/XMLString.hpp> +#include <xercesc/util/PlatformUtils.hpp> + +#include "uscxml/Interpreter.h" +#include "uscxml/util/DOM.h" +#include "uscxml/util/String.h" +#include "uscxml/util/UUID.h" +#include "uscxml/util/Predicates.h" +#include "uscxml/util/Convenience.h" // iequals + +#include "easylogging++.h" + +#include "uscxml/messages/Event.h" +#include "uscxml/server/HTTPServer.h" + +#include <iostream> +#include <queue> +#include <condition_variable> + +#include <event2/util.h> // for evutil_socket_t +#include <event2/event.h> +#include <event2/thread.h> + +#ifdef _WIN32 +#include "XGetopt.h" +#include "XGetopt.cpp" +#else +#include <getopt.h> +#endif + +using namespace std; +using namespace xercesc; +using namespace uscxml; + + +int main(int argc, char** argv) { + size_t iterations = 1; + + std::string documentURI; + el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, "%datetime %level %fbase:%line: %msg"); + + if (argc < 2) { + exit(EXIT_FAILURE); + } + + int option; + while ((option = getopt(argc, argv, "n:")) != -1) { + switch(option) { + case 'n': + iterations = strTo<size_t>(optarg); + break; + default: + break; + } + } + + documentURI = argv[optind]; + + HTTPServer::getInstance(7080, 7443); + + while(iterations--) { + try { + Interpreter interpreter = Interpreter::fromURL(documentURI); + + ActionLanguage al; + al.execContent = std::shared_ptr<ContentExecutorImpl>(new BasicContentExecutorImpl(interpreter.getImpl().get())); + interpreter.setActionLanguage(al); + + StateTransitionMonitor mon(interpreter); + interpreter.setMonitor(&mon); + + InterpreterState state = InterpreterState::USCXML_UNDEF; + while(state != USCXML_FINISHED) { + state = interpreter.step(true); + } + assert(interpreter.isInState("pass")); + } catch (Event e) { + std::cerr << "Thrown Event out of Interpreter: " << e; + return EXIT_FAILURE; + } + } + + return 0; +}
\ No newline at end of file diff --git a/test/src/test-stress.cpp b/test/src/test-stress.cpp deleted file mode 100644 index 0099f9b..0000000 --- a/test/src/test-stress.cpp +++ /dev/null @@ -1,196 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/Interpreter.h" -#include "uscxml/Factory.h" -#include "uscxml/server/HTTPServer.h" - -#include <glog/logging.h> - -#include "uscxml/plugins/invoker/filesystem/dirmon/DirMonInvoker.h" -#include <boost/algorithm/string.hpp> - -#ifdef _WIN32 -#include "XGetopt.h" -#endif - -int startedAt; -int lastTransitionAt; - -#ifdef HAS_SIGNAL_H -#include <signal.h> -#endif - -#ifdef HAS_EXECINFO_H -#include <execinfo.h> -#endif - -#ifdef HAS_DLFCN_H -#include <dlfcn.h> -#endif - -#ifdef HAS_EXECINFO_H -void printBacktrace(void** array, int size) { - char** messages = backtrace_symbols(array, size); - for (size_t i = 0; i < size && messages != NULL; ++i) { - std::cerr << "\t" << messages[i] << std::endl; - } - std::cerr << std::endl; - free(messages); -} - -#ifdef HAS_DLFCN_H -// see https://gist.github.com/nkuln/2020860 -typedef void (*cxa_throw_type)(void *, void *, void (*) (void *)); -cxa_throw_type orig_cxa_throw = 0; - -void load_orig_throw_code() { - orig_cxa_throw = (cxa_throw_type) dlsym(RTLD_NEXT, "__cxa_throw"); -} - -extern "C" -CXA_THROW_SIGNATURE { - std::cerr << __FUNCTION__ << " will throw exception from " << std::endl; - if (orig_cxa_throw == 0) - load_orig_throw_code(); - - void *array[50]; - size_t size = backtrace(array, 50); - printBacktrace(array, size); - orig_cxa_throw(thrown_exception, pvtinfo, dest); -} -#endif -#endif - - -// see http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c -void customTerminate() { - static bool tried_throw = false; - try { - // try once to re-throw currently active exception - if (!tried_throw) { - tried_throw = true; - throw; - } else { - tried_throw = false; - } - } catch (const std::exception &e) { - std::cerr << __FUNCTION__ << " caught unhandled exception. what(): " - << e.what() << std::endl; - } catch (const uscxml::Event &e) { - std::cerr << __FUNCTION__ << " caught unhandled exception. Event: " - << e << std::endl; - } catch (...) { - std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." - << std::endl; - } - -#ifdef HAS_EXECINFO_H - void * array[50]; - int size = backtrace(array, 50); - - printBacktrace(array, size); -#endif - abort(); -} - -void printUsageAndExit() { - printf("test-stress version " USCXML_VERSION " (" CMAKE_BUILD_TYPE " build - " CMAKE_COMPILER_STRING ")\n"); - printf("Usage\n"); - printf("\ttest-stress"); -#ifdef BUILD_AS_PLUGINS - printf(" [-p pluginPath]"); -#endif - printf(" <PATH>\n"); - printf("\n"); - exit(1); -} - -class StatusMonitor : public uscxml::InterpreterMonitor { - void beforeTakingTransitions(uscxml::Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& transitions) { - lastTransitionAt = time(NULL); - } - -}; - -int main(int argc, char** argv) { - using namespace uscxml; - - std::set_terminate(customTerminate); - -#if defined(HAS_SIGNAL_H) && !defined(WIN32) - signal(SIGPIPE, SIG_IGN); -#endif - - if (argc < 2) { - printUsageAndExit(); - } - - google::InitGoogleLogging(argv[0]); - google::LogToStderr(); - - HTTPServer::getInstance(8088, 8089); -#ifndef _WIN32 - opterr = 0; -#endif - int option; - while ((option = getopt(argc, argv, "vl:p:")) != -1) { - switch(option) { - case 'l': - google::InitGoogleLogging(optarg); - break; - case 'p': - uscxml::Factory::setDefaultPluginPath(optarg); - break; - case '?': - break; - default: - printUsageAndExit(); - break; - } - } - -#if 0 - while(true) { - Interpreter interpreter = Interpreter::fromURI("/Users/sradomski/Documents/TK/Code/uscxml/test/w3c/ecma/test235.scxml"); - interpreter.interpret(); - } -#else - - DirectoryWatch* watcher = new DirectoryWatch(argv[optind], true); - watcher->updateEntries(true); - std::map<std::string, struct stat> entries = watcher->getAllEntries(); - - StatusMonitor vm; - - std::map<std::string, struct stat>::iterator entryIter = entries.begin(); - while(entryIter != entries.end()) { - if (!boost::ends_with(entryIter->first, ".scxml")) { - entryIter++; - continue; - } - - startedAt = time(NULL); - lastTransitionAt = time(NULL); - - LOG(INFO) << "Processing " << entryIter->first; - Interpreter interpreter = Interpreter::fromURL(std::string(argv[optind]) + PATH_SEPERATOR + entryIter->first); - if (interpreter) { -// interpreter.setCmdLineOptions(argc, argv); - - interpreter.addMonitor(&vm); - - interpreter.start(); - int now = time(NULL); - while(now - startedAt < 20 && now - lastTransitionAt < 2) { - // let the interpreter run for a bit - tthread::this_thread::sleep_for(tthread::chrono::seconds(1)); - now = time(NULL); - } - - } - entryIter++; - } - - delete watcher; -#endif - return EXIT_SUCCESS; -}
\ No newline at end of file diff --git a/test/src/test-trie.cpp b/test/src/test-trie.cpp deleted file mode 100644 index 8c7ab15..0000000 --- a/test/src/test-trie.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "uscxml/util/Trie.h" -#include <iostream> -#include <assert.h> - -using namespace uscxml; - -int main(int argc, char** argv) { - { - Trie trie; - int nrTokens = 0; - size_t offset = 0; - std::string word = "this is to be tokenized"; - std::string token; - while((offset = trie.getNextToken(word, offset, token)) != std::string::npos) { - std::cout << "\"" << token << "\" "; - nrTokens++; - } - std::cout << std::endl; - assert(nrTokens == word.length()); - } - - { - Trie trie(" "); - int nrTokens = 0; - size_t offset = 0; - std::string word = "this is to be tokenized"; - std::string token; - while(offset = trie.getNextToken(word, offset, token), token.length() > 0) { - std::cout << "\"" << token << "\" "; - nrTokens++; - } - std::cout << std::endl; - assert(nrTokens == 5); - } - - { - Trie trie("#"); - int nrTokens = 0; - size_t offset = 0; - std::string word = "#bb#bbbb#b#bbb#bb#b#"; - std::string token; - while(offset = trie.getNextToken(word, offset, token), token.length() > 0) { - std::cout << "\"" << token << "\" "; - nrTokens++; - } - std::cout << std::endl; - assert(nrTokens == 6); - } - - { - Trie trie(" "); - int nrTokens = 0; - size_t offset = 0; - std::string word = " this is to be tokenized"; - std::string token; - while(offset = trie.getNextToken(word, offset, token), token.length() > 0) { - std::cout << "\"" << token << "\" "; - nrTokens++; - } - std::cout << std::endl; - assert(nrTokens == 3); - } - - { - Trie trie(""); - trie.addWord("a"); - trie.addWord("b"); - - trie.dump(); - } - - { - Trie trie("."); - trie.addWord("foo.bar"); - trie.addWord("foo.foo"); - trie.addWord("foo.foo.baz"); - trie.addWord("foz.foo.baz"); - trie.addWord("foz.foo"); - - trie.dump(); - - std::list<TrieNode*> childs; - - childs = trie.getChildsWithWords(trie.root); - assert(childs.size() == 5); - - assert(trie.getNodeWithPrefix("") == trie.root); - - childs = trie.getWordsWithPrefix(""); - assert(childs.size() == 5); - } -}
\ No newline at end of file diff --git a/test/src/test-url.cpp b/test/src/test-url.cpp index d4aa0c0..d713c67 100644 --- a/test/src/test-url.cpp +++ b/test/src/test-url.cpp @@ -1,24 +1,22 @@ -#include "uscxml/URL.h"
-#include "uscxml/Message.h"
+#include "uscxml/util/URL.h"
#include "uscxml/Interpreter.h"
#include "uscxml/server/HTTPServer.h"
#include "uscxml/config.h"
-#include <SAX/helpers/InputSourceResolver.hpp>
-
+#include <xercesc/parsers/XercesDOMParser.hpp>
+#include <easylogging++.h>
#include <assert.h>
-#include <boost/algorithm/string.hpp>
#include <iostream>
using namespace uscxml;
-using namespace boost;
+using namespace xercesc;
class TestServlet : public HTTPServlet {
public:
TestServlet(bool adaptPath) : _canAdaptPath(adaptPath) {}
- bool httpRecvRequest(const HTTPServer::Request& request) {
+ bool requestFromHTTP(const HTTPServer::Request& request) {
return true;
};
bool canAdaptPath() {
@@ -33,13 +31,17 @@ public: };
bool canResolve(const std::string& url) {
- Arabica::SAX::InputSource<std::string> is(url);
- Arabica::SAX::InputSourceResolver res1(is, Arabica::default_string_adaptor<std::string>());
- if(res1.resolve()) {
- std::cout << "good: " << url << std::endl;
+ URL absUrl(url);
+ if (absUrl.scheme() == "") {
+ absUrl = URL("file://" + url);
+ }
+
+ try {
+ XercesDOMParser* parser = new XercesDOMParser();
+ std::string tmp = absUrl;
+ parser->parse(tmp.c_str());
return true;
- } else {
- std::cout << "bad: " << url << std::endl;
+ } catch(...) {
return false;
}
}
@@ -60,7 +62,7 @@ void testFileURLs() { absURLs.push_back(URL("file:/fileURLs/text.txt"));
// usual filesystem paths
- absURLs.push_back(URL("C:\\Windows\\sradomski\\Desktop\\foo.txt"));
+// absURLs.push_back(URL("C:\\Windows\\sradomski\\Desktop\\foo.txt"));
// absURLs.push_back(URL("C:\\Windows\\Some Spaces\\index.txt"));
// absURLs.push_back(URL("C:/Windows/Some Spaces/index.txt"));
// absURLs.push_back(URL("/Users/sradomski/Desktop/"));
@@ -86,7 +88,7 @@ void testFileURLs() { {
relURLs.push_back(URL("file"));
relURLs.push_back(URL("file:"));
- relURLs.push_back(URL("file://"));
+// relURLs.push_back(URL("file://"));
// platform specific
relURLs.push_back(URL("file:Macintosh%20HD/fileURLs/text.txt"));
@@ -102,21 +104,22 @@ void testFileURLs() { }
for (std::list<URL>::iterator absIter = absURLs.begin(); absIter != absURLs.end(); absIter++) {
- absIter->dump();
+ std::cout << std::string(*absIter) << std::endl;
assert(absIter->isAbsolute());
assert(absIter->scheme() == "file");
assert(absIter->host() == "");
}
for (std::list<URL>::iterator relIter = relURLs.begin(); relIter != relURLs.end(); relIter++) {
+ std::cout << std::string(*relIter) << std::endl;
assert(!relIter->isAbsolute());
}
for (std::list<URL>::iterator absIter = absURLs.begin(); absIter != absURLs.end(); absIter++) {
for (std::list<URL>::iterator relIter = relURLs.begin(); relIter != relURLs.end(); relIter++) {
- URL relURL(*relIter);
- relURL.toAbsolute(*absIter);
- assert(relURL.isAbsolute());
+ URL tmp = URL::resolve(*relIter, *absIter);
+ std::cout << std::string(tmp) << std::endl;
+ assert(tmp.isAbsolute());
}
}
@@ -130,12 +133,21 @@ int main(int argc, char** argv) { // some URLs from http://www-archive.mozilla.org/quality/networking/testing/filetests.html
+// URL foo("file:/");
+// assert(foo.isAbsolute());
+
+
HTTPServer::getInstance(8099, 8100);
std::string exeName = argv[0];
exeName = exeName.substr(exeName.find_last_of("\\/") + 1);
- testFileURLs();
+ try {
+ testFileURLs();
+ } catch (Event e) {
+ LOG(ERROR) << e;
+ exit(EXIT_FAILURE);
+ }
{
try {
@@ -167,10 +179,12 @@ int main(int argc, char** argv) { }
#endif
+#if 0
{
try {
URL url(argv[0]);
+ assert(url.isAbsolute());
assert(canResolve(argv[0]));
assert(canResolve(url.asString()));
@@ -186,6 +200,7 @@ int main(int argc, char** argv) { std::cout << e << std::endl;
}
}
+#endif
{
TestServlet* testServlet1 = new TestServlet(false);
@@ -203,6 +218,7 @@ int main(int argc, char** argv) { HTTPServer::unregisterServlet(testServlet2);
}
+#if 0
{
TestServlet* testServlet1 = new TestServlet(true);
TestServlet* testServlet2 = new TestServlet(true);
@@ -219,7 +235,7 @@ int main(int argc, char** argv) { HTTPServer::unregisterServlet(testServlet2);
HTTPServer::unregisterServlet(testServlet3);
}
-
+#endif
{
Data data = Data::fromJSON("{\"shiftKey\":false,\"toElement\":{\"id\":\"\",\"localName\":\"body\"},\"clientY\":38,\"y\":38,\"x\":66,\"ctrlKey\":false,\"relatedTarget\":{\"id\":\"\",\"localName\":\"body\"},\"clientX\":66,\"screenY\":288,\"metaKey\":false,\"offsetX\":58,\"altKey\":false,\"offsetY\":30,\"fromElement\":{\"id\":\"foo\",\"localName\":\"div\"},\"screenX\":-1691,\"dataTransfer\":null,\"button\":0,\"pageY\":38,\"layerY\":38,\"pageX\":66,\"charCode\":0,\"which\":0,\"keyCode\":0,\"detail\":0,\"layerX\":66,\"returnValue\":true,\"timeStamp\":1371223991895,\"eventPhase\":2,\"target\":{\"id\":\"foo\",\"localName\":\"div\"},\"defaultPrevented\":false,\"srcElement\":{\"id\":\"foo\",\"localName\":\"div\"},\"type\":\"mouseout\",\"cancelable\":true,\"currentTarget\":{\"id\":\"foo\",\"localName\":\"div\"},\"bubbles\":true,\"cancelBubble\":false}");
std::cout << data << std::endl;
@@ -243,35 +259,33 @@ int main(int argc, char** argv) { }
{
- URL url("http://www.heise.de/index.html");
- std::cout << url.asString() << std::endl;
+ URL url("http://www.heise.de/de/index.html");
+ std::cout << std::string(url) << std::endl;
assert(url.isAbsolute());
+ assert(iequals(std::string(url), "http://www.heise.de/de/index.html"));
assert(iequals(url.scheme(), "http"));
assert(iequals(url.host(), "www.heise.de"));
- assert(iequals(url.port(), "80"));
- assert(iequals(url.path(), "/index.html"));
- assert(iequals(url.asString(), "http://www.heise.de/index.html"));
- std::stringstream content;
- content << url;
+ assert(iequals(url.path(), "/de/index.html"));
+ url.download();
}
#ifndef _WIN32
{
URL url("https://raw.github.com/tklab-tud/uscxml/master/test/samples/uscxml/test-ecmascript.scxml");
- std::cout << url.asString() << std::endl;
+ std::cout << std::string(url) << std::endl;
assert(url.isAbsolute());
assert(iequals(url.scheme(), "https"));
- std::stringstream content;
- content << url;
+ url.download();
}
#endif
+#if 0
{
URL url("test/index.html");
assert(iequals(url.scheme(), ""));
url.toAbsoluteCwd();
assert(iequals(url.scheme(), "file"));
- std::cout << url.asString() << std::endl;
+ std::cout << std::string(url) << std::endl;
}
{
@@ -280,5 +294,5 @@ int main(int argc, char** argv) { assert(url.isAbsolute());
assert(iequals(url.scheme(), "file"));
}
-
+#endif
}
\ No newline at end of file diff --git a/test/src/test-issue-reporting.cpp b/test/src/test-validating.cpp index 84cc096..a7a89df 100644 --- a/test/src/test-issue-reporting.cpp +++ b/test/src/test-validating.cpp @@ -1,6 +1,7 @@ #include "uscxml/config.h" #include "uscxml/Interpreter.h" -#include <glog/logging.h> +#include <easylogging++.h> +#include <xercesc/util/PlatformUtils.hpp> using namespace uscxml; @@ -8,8 +9,8 @@ std::set<std::string> issueLocationsForXML(const std::string xml) { Interpreter interpreter = Interpreter::fromXML(xml, ""); // common xmlns and version requirement on scxml attribute - interpreter.getDocument().getDocumentElement().setAttribute("xmlns", "http://www.w3.org/2005/07/scxml"); - interpreter.getDocument().getDocumentElement().setAttribute("version", "1.0"); + interpreter.getImpl()->getDocument()->getDocumentElement()->setAttribute(X("xmlns"), X("http://www.w3.org/2005/07/scxml")); + interpreter.getImpl()->getDocument()->getDocumentElement()->setAttribute(X("version"), X("1.0")); std::list<InterpreterIssue> issues = interpreter.validate(); @@ -28,15 +29,14 @@ public: IssueMonitor() { runtimeIssues = 0; } - void reportIssue(Interpreter interpreter, const InterpreterIssue& issue) { + void reportIssue(const InterpreterIssue& issue) { runtimeIssues++; } }; int main(int argc, char** argv) { - google::InitGoogleLogging(argv[0]); - google::LogToStderr(); + using namespace xercesc; int iterations = 1; @@ -58,11 +58,12 @@ int main(int argc, char** argv) { IssueMonitor monitor; Interpreter interpreter = Interpreter::fromXML(xml, ""); - interpreter.addMonitor(&monitor); - interpreter.interpret(); + interpreter.setMonitor(&monitor); - // first reiteration is not counted as it might be valid when raising internal errors - assert(runtimeIssues == 3); + while(interpreter.step() > 0) {} + + // four identical configurations between macrosteps + assert(runtimeIssues == 4); } if (1) { @@ -385,24 +386,22 @@ int main(int argc, char** argv) { } - if (1) { // Transition can never be optimally enabled (conditionless, eventless) const char* xml = "<scxml datamodel=\"ecmascript\">" - " <state id=\"start\">" - " <transition target=\"done\" />" - " <transition target=\"done\" />" - " </state>" - " <final id=\"done\" />" + " <state id=\"start\">" + " <transition target=\"done\" />" + " <transition target=\"done\" />" + " </state>" + " <final id=\"done\" />" "</scxml>"; std::set<std::string> issueLocations = issueLocationsForXML(xml); assert(issueLocations.find("//state[@id=\"start\"]/transition[2]") != issueLocations.end()); assert(issueLocations.size() == 1); } - if (1) { // Transition can never be optimally enabled (conditionless, more events) @@ -448,7 +447,6 @@ int main(int argc, char** argv) { assert(issueLocations.find("//state[@id=\"start\"]") != issueLocations.end()); assert(issueLocations.size() == 1); } - if (1) { // Initial transition with target outside of children @@ -465,9 +463,8 @@ int main(int argc, char** argv) { std::set<std::string> issueLocations = issueLocationsForXML(xml); assert(issueLocations.find("//state[@id=\"start\"]/initial[1]/transition[1]") != issueLocations.end()); - assert(issueLocations.size() == 1); + assert(issueLocations.size() == 1); // there are actually two issues with the transition } - if (1) { // Initial history transition with target outside of children @@ -489,7 +486,6 @@ int main(int argc, char** argv) { assert(issueLocations.find("//history[@id=\"bar\"]/transition[1]") != issueLocations.end()); assert(issueLocations.size() == 1); } - if (1) { // Initial transition with target outside of children @@ -580,8 +576,9 @@ int main(int argc, char** argv) { "</scxml>"; std::set<std::string> issueLocations = issueLocationsForXML(xml); + assert(issueLocations.find("//state[@id=\"foo\"]") != issueLocations.end()); // unreachable assert(issueLocations.find("//state[@id=\"start\"]/initial[1]") != issueLocations.end()); - assert(issueLocations.size() == 1); + assert(issueLocations.size() == 2); } if (1) { @@ -813,7 +810,6 @@ int main(int argc, char** argv) { assert(issueLocations.size() == 1); } - } return EXIT_SUCCESS; diff --git a/test/src/test-vxml-mmi-http.cpp b/test/src/test-vxml-mmi-http.cpp deleted file mode 100644 index 35dc5d6..0000000 --- a/test/src/test-vxml-mmi-http.cpp +++ /dev/null @@ -1,179 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/UUID.h" -#include <iostream> -#include <stdexcept> - -#include <boost/algorithm/string.hpp> - -#include <event2/event.h> -#include "event2/thread.h" - -#ifdef HAS_SIGNAL_H -#include <signal.h> -#endif - -#include "uscxml/server/HTTPServer.h" -#include "uscxml/URL.h" -#include "uscxml/concurrency/tinythread.h" -#include "uscxml/messages/MMIMessages.h" -#include <DOM/io/Stream.hpp> - -#ifdef _WIN32 -#include "XGetopt.h" -#endif - -#define ISSUE_REQUEST(name, block) {\ - Arabica::DOM::Document<std::string> name##XML = name.toXML(true);\ - name##XML.getDocumentElement().setPrefix("mmi");\ - std::stringstream name##XMLSS;\ - name##XMLSS << name##XML;\ - URL name##URL(target);\ - std::cout << "SEND:" << std::endl << name##XMLSS.str() << std::flush;\ - name##URL.setOutContent(name##XMLSS.str());\ - name##URL.addOutHeader("Content-type", "application/xml");\ - name##URL.download(block);\ - std::cout << "OK" << std::endl << std::flush;\ -} - -using namespace uscxml; - -std::map<std::string, MMIEvent*> Requests; -std::map<std::string, MMIEvent*> Replies; - -tthread::condition_variable Cond; -tthread::mutex Mutex; - -std::string context; - -class MMIServlet : public HTTPServlet { -public: - bool httpRecvRequest(const HTTPServer::Request& request) { - std::cout << "RCVD:" << std::endl << request << std::flush; - tthread::lock_guard<tthread::mutex> lock(Mutex); - - const Arabica::DOM::Document<std::string>& doc = request.data.at("content").node.getOwnerDocument(); -// NameSpacingParser parser = NameSpacingParser::fromXML(request.content); - switch(MMIEvent::getType(doc.getDocumentElement())) { - case MMIEvent::NEWCONTEXTRESPONSE: { - NewContextResponse* resp = new NewContextResponse(NewContextResponse::fromXML(doc.getDocumentElement())); - context = resp->context; - Replies[resp->requestId] = resp; - break; - } - case MMIEvent::STARTRESPONSE: { - StartResponse* resp = new StartResponse(StartResponse::fromXML(doc.getDocumentElement())); - Replies[resp->requestId] = resp; - } - default: - ; - } - - Cond.notify_all(); - - HTTPServer::Reply reply(request); - HTTPServer::reply(reply); - - return true; - } - void setURL(const std::string& url) { - this->url = url; - } - std::string url; -}; - -void printUsageAndExit(const char* progName) { - // remove path from program name - std::string progStr(progName); - if (progStr.find_last_of(PATH_SEPERATOR) != std::string::npos) { - progStr = progStr.substr(progStr.find_last_of(PATH_SEPERATOR) + 1, progStr.length() - (progStr.find_last_of(PATH_SEPERATOR) + 1)); - } - - printf("%s version " USCXML_VERSION " (" CMAKE_BUILD_TYPE " build - " CMAKE_COMPILER_STRING ")\n", progStr.c_str()); - printf("Usage\n"); - printf("\t%s", progStr.c_str()); - printf(" [-tURL] URL"); - printf("\n"); - printf("Options\n"); - printf("\t-tURL : URL of VoiceXML HTTP server\n"); - printf("\tURL : URL of a VoiceXML document\n"); - printf("\n"); - exit(1); -} - -int main(int argc, char** argv) { - try { - tthread::lock_guard<tthread::mutex> lock(Mutex); - - std::string target; - std::string document; - - if (argc < 2) - printUsageAndExit(argv[0]); - - int option; - while ((option = getopt(argc, argv, "t:")) != -1) { - switch(option) { - case 't': - target = optarg; - break; - default: - printUsageAndExit(argv[0]); - } - } - - if (argc < optind) - printUsageAndExit(argv[0]); - - document = argv[optind]; - - if (!boost::starts_with(document, "http")) - document = "http://" + document; - - if (!boost::starts_with(target, "http")) - document = "http://" + target; - - // target = "http://130.83.163.167:9090/mmi"; - // target = "http://localhost:9090/mmi"; - - - MMIServlet servlet; - HTTPServer::getInstance(4344, 0); - HTTPServer::getInstance()->registerServlet("/mmi", &servlet); - - std::string source = servlet.url; - - NewContextRequest newCtxReq; - newCtxReq.source = source; - newCtxReq.target = target; - newCtxReq.requestId = uscxml::UUID::getUUID(); - - Requests[newCtxReq.requestId] = &newCtxReq; - - ISSUE_REQUEST(newCtxReq, false); - - while(Replies.find(newCtxReq.requestId) == Replies.end()) - Cond.wait(Mutex); - - StartRequest startReq; - startReq.context = context; - startReq.source = source; - startReq.target = target; - startReq.requestId = uscxml::UUID::getUUID(); - startReq.contentURL.href = document; - //"https://raw.githubusercontent.com/Roland-Taizun-Azhar/TaskAssistance-Project/master/WebContent/hello.vxml"; - - Requests[startReq.requestId] = &startReq; - ISSUE_REQUEST(startReq, false); - - while(Replies.find(startReq.requestId) == Replies.end()) - Cond.wait(Mutex); - - tthread::this_thread::sleep_for(tthread::chrono::seconds(5)); - } catch (Event e) { - std::cout << e << std::endl; - } catch (std::exception e) { - std::cout << e.what() << std::endl; - } - - -}
\ No newline at end of file diff --git a/test/src/test-vxml-mmi-socket.cpp b/test/src/test-vxml-mmi-socket.cpp deleted file mode 100644 index b89a65a..0000000 --- a/test/src/test-vxml-mmi-socket.cpp +++ /dev/null @@ -1,164 +0,0 @@ -#include "uscxml/config.h" -#include "uscxml/server/Socket.h" -#include "uscxml/UUID.h" -#include <iostream> -#include <stdexcept> - -#include <event2/event.h> -#include "event2/thread.h" - -#ifdef HAS_SIGNAL_H -#include <signal.h> -#endif - -#include "uscxml/concurrency/tinythread.h" -#include "uscxml/messages/MMIMessages.h" -#include <DOM/io/Stream.hpp> - - - -using namespace uscxml; - -bool testAddressParsing() { - std::string protocol; - std::string hostName; - uint16_t port; - - { - Socket::parseAddress("4343", protocol, hostName, port); - assert(protocol == "tcp"); - assert(hostName == "127.0.0.1"); - assert(port == 4343); - - Socket::parseAddress("localhost:4343", protocol, hostName, port); - assert(protocol == "tcp"); - assert(hostName == "localhost"); - assert(port == 4343); - - Socket::parseAddress("tcp://localhost:4343", protocol, hostName, port); - assert(protocol == "tcp"); - assert(hostName == "localhost"); - assert(port == 4343); - } - return true; -} - -bool testMMIEvents() { - { - NewContextRequest newCtxReq; - newCtxReq.source = "localhost:3434"; - newCtxReq.target = "localhost:1212"; - newCtxReq.requestId = "requestId"; - - Arabica::DOM::Document<std::string> newCtxReqXML1 = newCtxReq.toXML(); - Arabica::DOM::Document<std::string> newCtxReqXML2 = newCtxReq.toXML(true); - -// std::cout << newCtxReqXML1 << std::endl; -// std::cout << newCtxReqXML2 << std::endl; - - NewContextRequest newCtxReq1 = NewContextRequest::fromXML(newCtxReqXML1.getDocumentElement()); - NewContextRequest newCtxReq2 = NewContextRequest::fromXML(newCtxReqXML2.getDocumentElement()); - - assert(MMIEvent::getType(newCtxReqXML1.getDocumentElement()) == MMIEvent::NEWCONTEXTREQUEST); - assert(MMIEvent::getType(newCtxReqXML2.getDocumentElement()) == MMIEvent::NEWCONTEXTREQUEST); - - assert(newCtxReq1.source == "localhost:3434"); - assert(newCtxReq2.source == "localhost:3434"); - assert(newCtxReq1.target == "localhost:1212"); - assert(newCtxReq2.target == "localhost:1212"); - assert(newCtxReq1.requestId == "requestId"); - assert(newCtxReq2.requestId == "requestId"); - - } - return true; -} - -class TestServer : public PacketServerSocket { -public: - TestServer(int domain, int type, int protocol) : PacketServerSocket(domain, type, protocol, std::string("\0", 1)) {} - virtual void readCallback(const std::string& packet, Connection& conn) { - std::cout << "Server got: " << packet << std::endl; - std::string urghs("hi!"); - conn.reply(urghs.data(), urghs.size()); - }; - - std::stringstream fragment; -}; - -class TestClient : public ClientSocket { -public: - TestClient(int domain, int type, int protocol) : ClientSocket(domain, type, protocol) {} - virtual void readCallback(const char* data, size_t size) { - std::string content(data, size); - }; -}; - -std::map<std::string, MMIEvent*> _requests; -std::map<std::string, MMIEvent*> _replies; - -int main(int argc, char** argv) { - -#if defined(HAS_SIGNAL_H) && !defined(WIN32) - signal(SIGPIPE, SIG_IGN); -#endif - -#ifndef _WIN32 - evthread_use_pthreads(); -#else - evthread_use_windows_threads(); -#endif - testAddressParsing(); - testMMIEvents(); - -// TestClient client(PF_INET, SOCK_STREAM, 0); -// client.connect("epikur.local", 4343); - std::string target = "localhost:4343"; - std::string source = "localhost:4344"; - - TestServer server(PF_INET, SOCK_STREAM, 0); - server.listen(source); - -// while(true) -// sleep(1000); - - TestClient client(PF_INET, SOCK_STREAM, 0); - client.connect(source); - - NewContextRequest newCtxReq; - newCtxReq.source = source; - newCtxReq.target = target; - newCtxReq.requestId = UUID::getUUID(); - - _requests[newCtxReq.requestId] = &newCtxReq; - - Arabica::DOM::Document<std::string> newCtxReqXML = newCtxReq.toXML(true); - std::stringstream newCtxReqXMLSS; - newCtxReqXMLSS << newCtxReqXML; - - for (size_t i = 0; i < 100000; i++) { - std::string index = toStr(i); - client.write(index.c_str(), index.size() + 1); -// client.write(newCtxReqXMLSS.str().data(), newCtxReqXMLSS.str().size()); -// client.write("\0", 1); - } - - while(true) - sleep(1000); - -// StartRequest startReq; -// startReq.source = "localhost:4344"; -// startReq.target = "localhost:4343"; -// startReq.requestId = "131234141234"; -// startReq.data = -// "<vxml xmlns=\"http://www.w3.org/2001/vxml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"2.1\" xml:lang=\"en\"" -// "xsi:schematicLocation=\"http://www.w3.org/2001/vxml http://www.w3.org/TR/voicexml20/vxml.xsd\">" -// " <prompt>Goodbye!</prompt>" -// "</vxml>"; -// -// Arabica::DOM::Document<std::string> reqXML = startReq.toXML(); -// std::stringstream xmlSS; -// xmlSS << reqXML; -// std::cout << reqXML; - -// client.write(xmlSS.str().data(), xmlSS.str().size()); -}
\ No newline at end of file diff --git a/test/src/test-w3c.cpp b/test/src/test-w3c.cpp deleted file mode 100644 index baa963b..0000000 --- a/test/src/test-w3c.cpp +++ /dev/null @@ -1,272 +0,0 @@ -// I feel dirty, but we need to access the datamodel timer -// #define protected public - -#include "uscxml/config.h" - -#ifdef APPLE -#include <mach/mach.h> -#include <mach/mach_time.h> -#include <pthread.h> -#endif - -#include "uscxml/Common.h" -#include "uscxml/Convenience.h" - -#ifdef BUILD_PROFILING -// get access to the datamodel - this causes strange issues with MSVC depending on include order -// may be better to ifndef all protected: and private: stanzas for profiling? -#define protected public -#include "uscxml/Interpreter.h" -#undef protected -# endif - - -#include "uscxml/dom/DOMUtils.h" -#include "uscxml/concurrency/Timer.h" - -#include "uscxml/Factory.h" -#include "uscxml/server/HTTPServer.h" - -#include "uscxml/transform/ChartToFlatSCXML.h" -#include <glog/logging.h> -#include <boost/algorithm/string.hpp> - -#ifdef HAS_SIGNAL_H -#include <signal.h> -#endif - -#ifdef BUILD_PROFILING -# include "uscxml/plugins/DataModel.h" -# endif - -#ifdef _WIN32 -#include "XGetopt.h" -#include "XGetopt.cpp" -#endif - -static bool withFlattening = false; -static double delayFactor = 1; -static size_t benchmarkRuns = 1; -static std::string documentURI; - -int retCode = EXIT_FAILURE; -uscxml::Interpreter interpreter; - -void printUsageAndExit(const char* progName) { - // remove path from program name - std::string progStr(progName); - if (progStr.find_last_of(PATH_SEPERATOR) != std::string::npos) { - progStr = progStr.substr(progStr.find_last_of(PATH_SEPERATOR) + 1, progStr.length() - (progStr.find_last_of(PATH_SEPERATOR) + 1)); - } - - printf("%s version " USCXML_VERSION " (" CMAKE_BUILD_TYPE " build - " CMAKE_COMPILER_STRING ")\n", progStr.c_str()); - printf("Usage\n"); - printf("\t%s", progStr.c_str()); - printf(" [-f] [-dN] [-bN]"); -#ifdef BUILD_AS_PLUGINS - printf(" [-p pluginPath]"); -#endif - printf(" URL"); - printf("\n"); - printf("Options\n"); - printf("\t-f : flatten to SCXML state-machine\n"); - printf("\t-d FACTOR : delay factor\n"); - printf("\t-b ITERATIONS : benchmark with number of runs\n"); - printf("\n"); - exit(1); -} - -class W3CStatusMonitor : public uscxml::InterpreterMonitor { - - void beforeCompletion(uscxml::Interpreter tmp) { - if (interpreter.getConfiguration().size() == 1 && interpreter.isInState("pass")) { -#ifndef BUILD_PROFILING - std::cout << "TEST SUCCEEDED" << std::endl; -#endif - retCode = EXIT_SUCCESS; - return; - } -#ifndef BUILD_PROFILING - std::cout << "TEST FAILED" << std::endl; -#endif - retCode = EXIT_FAILURE; - } -}; - -int main(int argc, char** argv) { - using namespace uscxml; - -#ifdef APPLE - mach_timebase_info_data_t timebase_info; - mach_timebase_info(&timebase_info); - - const uint64_t NANOS_PER_MSEC = 1000000ULL; - double clock2abs = ((double)timebase_info.denom / (double)timebase_info.numer) * NANOS_PER_MSEC; - - thread_time_constraint_policy_data_t policy; - policy.period = 0; - policy.computation = (uint32_t)(5 * clock2abs); // 5 ms of work - policy.constraint = (uint32_t)(10 * clock2abs); - policy.preemptible = FALSE; - - int kr = thread_policy_set(pthread_mach_thread_np(pthread_self()), - THREAD_TIME_CONSTRAINT_POLICY, - (thread_policy_t)&policy, - THREAD_TIME_CONSTRAINT_POLICY_COUNT); - if (kr != KERN_SUCCESS) { - mach_error("thread_policy_set:", kr); - exit(1); - } -#endif - - try { - -#if defined(HAS_SIGNAL_H) && !defined(WIN32) - signal(SIGPIPE, SIG_IGN); -#endif - - if (argc < 2) { - exit(EXIT_FAILURE); - } - - google::InitGoogleLogging(argv[0]); - - HTTPServer::getInstance(32954, 32955, NULL); // bind to some random tcp sockets for ioprocessor tests - - char* dfEnv = getenv("USCXML_DELAY_FACTOR"); - if (dfEnv) { - delayFactor = strTo<double>(dfEnv); - } - - const char* envBenchmarkRuns = getenv("USCXML_BENCHMARK_ITERATIONS"); - if (envBenchmarkRuns != NULL) { - benchmarkRuns = strTo<size_t>(envBenchmarkRuns); - google::SetStderrLogging(3); - } else { - google::LogToStderr(); - } - - int option; - while ((option = getopt(argc, argv, "fd:b:")) != -1) { - switch(option) { - case 'f': - withFlattening = true; - break; - case 'd': - delayFactor = strTo<double>(optarg); - break; - case 'b': - benchmarkRuns = strTo<size_t>(optarg); - break; - default: - break; - } - } - - documentURI = argv[optind]; - - LOG(INFO) << "Processing " << documentURI << (withFlattening ? " FSM converted" : "") << (delayFactor ? "" : " with delays *= " + toStr(delayFactor)) << (benchmarkRuns > 0 ? " for " + toStr(benchmarkRuns) + " benchmarks" : ""); - if (withFlattening) { - interpreter = Interpreter::fromURL(documentURI); - Transformer flattener = ChartToFlatSCXML::transform(interpreter); - interpreter = flattener; -// std::cout << interpreter.getDocument() << std::endl; - } else { - interpreter = Interpreter::fromURL(documentURI); - } - - if (delayFactor != 1) { - Arabica::DOM::Document<std::string> document = interpreter.getDocument(); - Arabica::DOM::Element<std::string> root = document.getDocumentElement(); - Arabica::XPath::NodeSet<std::string> sends = DOMUtils::filterChildElements(interpreter.getNameSpaceInfo().xmlNSPrefix + "send", root, true); - - for (size_t i = 0; i < sends.size(); i++) { - Arabica::DOM::Element<std::string> send = Arabica::DOM::Element<std::string>(sends[i]); - if (HAS_ATTR(send, "delay")) { - NumAttr delay(ATTR(send, "delay")); - int value = strTo<int>(delay.value); - if (delay.unit == "s") - value *= 1000; - value *= delayFactor; - send.setAttribute("delay", toStr(value) + "ms"); - std::cout << ATTR(send, "delay") << std::endl; - } else if (HAS_ATTR(send, "delayexpr")) { - std::string delayExpr = ATTR(send, "delayexpr"); - send.setAttribute("delayexpr", - "(" + delayExpr + ".indexOf('ms', " + delayExpr + ".length - 2) !== -1 ? " - "(" + delayExpr + ".slice(0,-2) * " + toStr(delayFactor) + ") + \"ms\" : " - "(" + delayExpr + ".slice(0,-1) * 1000 * " + toStr(delayFactor) + ") + \"ms\")"); - std::cout << ATTR(send, "delayexpr") << std::endl; - } - } - std::list<InterpreterIssue> issues = interpreter.validate(); - for (std::list<InterpreterIssue>::iterator issueIter = issues.begin(); issueIter != issues.end(); issueIter++) { - std::cout << *issueIter << std::endl; - } - } - - if (interpreter) { - W3CStatusMonitor* vm = new W3CStatusMonitor(); - interpreter.addMonitor(vm); - - LOG(INFO) << "Benchmarking " << documentURI << (withFlattening ? " FSM converted" : "") << (delayFactor ? "" : " with delays *= " + toStr(delayFactor)); - - size_t remainingRuns = benchmarkRuns; - size_t microSteps = 0; - - Timer tTotal; - tTotal.start(); - - double avg = 0; -#ifdef BUILD_PROFILING - double avgDm = 0; - double avgStep = 0; -#endif - - while(remainingRuns-- > 0) { - Timer t; - microSteps = 0; - - InterpreterState state = interpreter.getState(); - - for(;;) { - state = interpreter.step(true); - microSteps++; - if (state == USCXML_INITIALIZED) { - t.start(); - } else if (state == USCXML_FINISHED) { -#ifdef BUILD_PROFILING - avgDm += interpreter._impl->_dataModel.timer.elapsed; - interpreter._impl->_dataModel.timer.reset(); - avgStep += interpreter.timer.elapsed; -#endif - } - if (state < 0) - break; - } - assert(retCode == EXIT_SUCCESS); - t.stop(); - avg += t.elapsed; - interpreter.reset(); - std::cout << "." << std::flush; - } - - tTotal.stop(); - - std::cout << benchmarkRuns << " iterations" << std::endl; - std::cout << tTotal.elapsed * 1000.0 << " ms in total" << std::endl; - std::cout << (avg * 1000.0) / (double)benchmarkRuns << " ms per execution" << std::endl; - std::cout << microSteps << " microsteps per iteration" << std::endl; - std::cout << (avg * 1000.0) / ((double)benchmarkRuns * (double)microSteps) << " ms per microstep" << std::endl; -#ifdef BUILD_PROFILING - std::cout << (avgDm * 1000.0) / (double)benchmarkRuns << " ms in datamodel" << std::endl; - std::cout << ((avg - avgDm) * 1000.0) / ((double)benchmarkRuns * (double)microSteps) << " ms per microstep \\wo datamodel" << std::endl; -#endif - } - } catch(Event e) { - std::cout << e << std::endl; - } catch(std::exception e) { - std::cout << e.what() << std::endl; - } - return retCode; -} |