From 58ac684725b4c5c75c94516a2068d8d55e8c348c Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Sun, 30 Nov 2014 23:42:05 +0100 Subject: backup --- CMakeLists.txt | 54 +++++++++++++++++++++++++----------------------------- 1 file changed, 25 insertions(+), 29 deletions(-) (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index f638fd0..da6479b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,7 @@ PROJECT(ousia) CMAKE_MINIMUM_REQUIRED(VERSION 2.8.9) -# Option for enabling testing. Turn on with 'cmake -Dtest=ON'. +# Option for enabling testing. Turn on with 'cmake -DTEST=ON'. # TODO: Automatically activate tests if gtest is available OPTION(TEST "Build all tests." OFF) # Makes boolean 'test' available. @@ -106,28 +106,34 @@ ADD_LIBRARY(ousia_core src/core/Logger src/core/Managed src/core/Node - src/core/Parser src/core/Tokenizer # src/core/Typesystem src/core/Utils - src/core/parser/XmlParser + src/core/parser/Parser src/core/script/Function src/core/script/Object src/core/script/ScriptEngine src/core/script/Variant ) -TARGET_LINK_LIBRARIES(ousia_core +# ousia_xml library + +ADD_LIBRARY(ousia_xml + src/plugins/xml/XmlParser +) + +TARGET_LINK_LIBRARIES(ousia_xml + ousia_core ${EXPAT_LIBRARIES} ) -# ousia_plugin_mozjs library +# ousia_mozjs library -ADD_LIBRARY(ousia_plugin_mozjs +ADD_LIBRARY(ousia_mozjs src/plugins/mozjs/MozJsScriptEngine ) -TARGET_LINK_LIBRARIES(ousia_plugin_mozjs +TARGET_LINK_LIBRARIES(ousia_mozjs ousia_core ${MOZJS_LIBRARIES} ) @@ -135,18 +141,10 @@ TARGET_LINK_LIBRARIES(ousia_plugin_mozjs # If testing is enabled, build the unit tests IF(TEST) - # - # Core Test - # - - # Include the gtest include files and the src directory INCLUDE_DIRECTORIES( ${GTEST_INCLUDE_DIRS} - ${EXPAT_INCLUDE_DIRS} - src/ ) - # Add all unit test files ADD_EXECUTABLE(ousia_test_core test/core/BufferedCharReaderTest test/core/CodeTokenizerTest @@ -158,7 +156,6 @@ IF(TEST) test/core/RangeSetTest test/core/TokenizerTest test/core/UtilsTest - test/core/parser/XmlParserTest test/core/script/FunctionTest test/core/script/ObjectTest test/core/script/VariantTest @@ -169,30 +166,29 @@ IF(TEST) ousia_core ) - # - # Plugin Tests - # + ADD_EXECUTABLE(ousia_test_xml + test/plugins/xml/XmlParserTest + ) - # Include the gtest include files and the src directory - INCLUDE_DIRECTORIES( - ${MOZJS_INCLUDE_DIRS} - ${GTEST_INCLUDE_DIRS} - src/ + TARGET_LINK_LIBRARIES(ousia_test_xml + ${GTEST_LIBRARIES} + ousia_core + ousia_xml ) - # Add all unit test files - ADD_EXECUTABLE(ousia_test_plugin_mozjs + ADD_EXECUTABLE(ousia_test_mozjs test/plugins/mozjs/MozJsScriptEngineTest ) - TARGET_LINK_LIBRARIES(ousia_test_plugin_mozjs + TARGET_LINK_LIBRARIES(ousia_test_mozjs ${GTEST_LIBRARIES} ousia_core - ousia_plugin_mozjs + ousia_mozjs ) # Register the unit tests ADD_TEST(ousia_test_core ousia_test_core) - ADD_TEST(ousia_test_plugin_mozjs ousia_test_plugin_mozjs) + ADD_TEST(ousia_test_xml ousia_test_xml) + ADD_TEST(ousia_test_mozjs ousia_test_mozjs) ENDIF() -- cgit v1.2.3 From 5554f3594d00e267af447a24149f655ceff64d17 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Mon, 1 Dec 2014 21:27:08 +0100 Subject: working version of the ParserStack class plus unit tests --- CMakeLists.txt | 3 + src/core/parser/Parser.hpp | 13 ++ src/core/parser/ParserStack.cpp | 155 +++++++++++++++++ src/core/parser/ParserStack.hpp | 315 +++++++++++++++++++++++++++++++++++ src/core/parser/Scope.hpp | 2 + src/core/parser/XmlStates.cpp | 53 ------ src/core/parser/XmlStates.hpp | 301 --------------------------------- test/core/parser/ParserStackTest.cpp | 165 ++++++++++++++++++ 8 files changed, 653 insertions(+), 354 deletions(-) create mode 100644 src/core/parser/ParserStack.cpp create mode 100644 src/core/parser/ParserStack.hpp delete mode 100644 src/core/parser/XmlStates.cpp delete mode 100644 src/core/parser/XmlStates.hpp create mode 100644 test/core/parser/ParserStackTest.cpp (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index da6479b..327f664 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -110,6 +110,8 @@ ADD_LIBRARY(ousia_core # src/core/Typesystem src/core/Utils src/core/parser/Parser + src/core/parser/ParserStack + src/core/parser/Scope src/core/script/Function src/core/script/Object src/core/script/ScriptEngine @@ -156,6 +158,7 @@ IF(TEST) test/core/RangeSetTest test/core/TokenizerTest test/core/UtilsTest + test/core/parser/ParserStackTest test/core/script/FunctionTest test/core/script/ObjectTest test/core/script/VariantTest diff --git a/src/core/parser/Parser.hpp b/src/core/parser/Parser.hpp index b8faf98..fa5dd49 100644 --- a/src/core/parser/Parser.hpp +++ b/src/core/parser/Parser.hpp @@ -86,6 +86,19 @@ struct ParserContext { : scope(scope), registry(registry), logger(logger){}; }; +struct StandaloneParserContext : public ParserContext { +private: + Logger logger; + Scope scope; + Registry registry; + +public: + StandaloneParserContext() + : ParserContext(scope, registry, logger), + scope(nullptr), + registry(logger){}; +}; + /** * Abstract parser class. This class builds the basic interface that should be * used by any parser which reads data from an input stream and transforms it diff --git a/src/core/parser/ParserStack.cpp b/src/core/parser/ParserStack.cpp new file mode 100644 index 0000000..01fce3f --- /dev/null +++ b/src/core/parser/ParserStack.cpp @@ -0,0 +1,155 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + 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 3 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, see . +*/ + +#include + +#include "ParserStack.hpp" + +#include + +namespace ousia { +namespace parser { + +/* Class HandlerDescriptor */ + +HandlerInstance HandlerDescriptor::create(const ParserContext &ctx, + std::string name, State parentState, + bool isChild, char **attrs) const +{ + Handler *h = ctor(ctx, name, targetState, parentState, isChild); + h->start(attrs); + return HandlerInstance(h, this); +} + +/* Class ParserStack */ + +/** + * Function used internally to turn the elements of a collection into a string + * separated by the given delimiter. + */ +template +static std::string join(T es, const std::string &delim) +{ + std::stringstream res; + bool first = true; + for (auto &e : es) { + if (!first) { + res << delim; + } + res << e; + first = false; + } + return res.str(); +} + +/** + * Returns an Exception that should be thrown when a currently invalid command + * is thrown. + */ +static LoggableException invalidCommand(const std::string &name, + const std::set &expected) +{ + if (expected.empty()) { + return LoggableException{ + std::string{"No nested elements allowed, but got \""} + name + + std::string{"\""}}; + } else { + return LoggableException{ + std::string{"Expected "} + + (expected.size() == 1 ? std::string{"\""} + : std::string{"one of \""}) + + join(expected, "\", \"") + std::string{"\", but got \""} + name + + std::string{"\""}}; + } +} + +std::set ParserStack::expectedCommands(State state) +{ + std::set res; + for (const auto &v : handlers) { + if (v.second.parentStates.count(state)) { + res.insert(v.first); + } + } + return res; +} + +void ParserStack::start(std::string name, char **attrs) +{ + // Fetch the current handler and the current state + const HandlerInstance *h = stack.empty() ? nullptr : &stack.top(); + const State curState = currentState(); + bool isChild = false; + + // Fetch the correct Handler descriptor for this + const HandlerDescriptor *descr = nullptr; + auto range = handlers.equal_range(name); + for (auto it = range.first; it != range.second; it++) { + if (it->second.parentStates.count(curState)) { + descr = &(it->second); + break; + } + } + if (!descr && currentArbitraryChildren()) { + isChild = true; + descr = h->descr; + } + + // No descriptor found, throw an exception. + if (!descr) { + throw invalidCommand(name, expectedCommands(curState)); + } + + // Instantiate the handler and call its start function + stack.emplace(descr->create(ctx, name, curState, isChild, attrs)); +} + +void ParserStack::end() +{ + // Check whether the current command could be ended + if (stack.empty()) { + throw LoggableException{"No command to end."}; + } + + // Remove the current HandlerInstance from the stack + HandlerInstance inst{stack.top()}; + stack.pop(); + + // Call the end function of the last Handler + inst.handler->end(); + + // Call the "child" function of the parent Handler in the stack + // (if one exists). + if (!stack.empty()) { + stack.top().handler->child(inst.handler); + } +} + +void ParserStack::data(const char *data, int len) +{ + // Check whether there is any command the data can be sent to + if (stack.empty()) { + throw LoggableException{"No command to receive data."}; + } + + // Pass the data to the current Handler instance + stack.top().handler->data(data, len); +} +} +} + diff --git a/src/core/parser/ParserStack.hpp b/src/core/parser/ParserStack.hpp new file mode 100644 index 0000000..a777b1e --- /dev/null +++ b/src/core/parser/ParserStack.hpp @@ -0,0 +1,315 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + 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 3 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, see . +*/ + +/** + * @file ParserStack.hpp + * + * Helper classes for document or description parsers. Contains the ParserStack + * class, which is an pushdown automaton responsible for accepting commands in + * the correct order and calling specified handlers. + * + * @author Andreas Stöckel (astoecke@techfak.uni-bielefeld.de) + */ + +#ifndef _OUSIA_PARSER_STACK_HPP_ +#define _OUSIA_PARSER_STACK_HPP_ + +#include + +#include +#include +#include +#include +#include + +#include "Parser.hpp" + +namespace ousia { +namespace parser { + +/** + * The State type alias is used to + */ +using State = int8_t; + +static const State STATE_ALL = -2; +static const State STATE_NONE = -1; + +/** + * The handler class provides a context for handling an XML tag. It has to be + * overridden and registered in the StateStack class to form handlers for + * concrete XML tags. + */ +class Handler { +private: + Rooted node; + +protected: + void setNode(Handle node) { this->node = node; } + +public: + /** + * Reference to the ParserContext instance that should be used to resolve + * references to nodes in the Graph. + */ + const ParserContext &ctx; + + /** + * Contains the name of the tag that is being handled. + */ + const std::string name; + + /** + * Contains the current state of the state machine. + */ + const State state; + + /** + * Contains the state of the state machine when the parent node was handled. + */ + const State parentState; + + /** + * Set to true if the tag that is being handled is not the tag that was + * specified in the state machine but a child tag of that tag. + */ + const bool isChild; + + /** + * Constructor of the Handler class. + * + * @param ctx is the parser context the handler should be executed in. + * @param name is the name of the string. + * @param state is the state this handler was called for. + * @param parentState is the state of the parent command. + * @param isChild specifies whether this handler was called not for the + * command that was specified in the state machine but a child command. + */ + Handler(const ParserContext &ctx, std::string name, State state, + State parentState, bool isChild) + : ctx(ctx), + name(std::move(name)), + state(state), + parentState(parentState), + isChild(isChild){}; + + /** + * Virtual destructor. + */ + virtual ~Handler(){}; + + /** + * Returns the node instance that was created by the handler. + * + * @return the Node instance created by the handler. May be nullptr if no + * Node was created. + */ + Rooted getNode() { return node; } + + /** + * Called when the command that was specified in the constructor is + * instanciated. + * + * @param attrs contains the attributes that were specified for the command. + * TODO: Replace with StructInstance! + */ + virtual void start(char **attrs) = 0; + + /** + * Called whenever the command for which this handler + */ + virtual void end() = 0; + + /** + * Called whenever raw data (int the form of a string) is available for the + * Handler instance. + * + * TODO: Replace with std::string? + * + * @param data is a pointer at the character data that is available for the + * Handler instance. + */ + virtual void data(const char *data, int len){}; + + /** + * Called whenever a direct child element was created and has ended. + * + * @param handler is a reference at the child Handler instance. + */ + virtual void child(std::shared_ptr handler){}; +}; + +/** + * HandlerConstructor is a function pointer type used to create concrete + * instances of the Handler class. + */ +using HandlerConstructor = Handler *(*)(const ParserContext &ctx, + std::string name, State state, + State parentState, bool isChild); + +struct HandlerDescriptor; + +/** + * Used internlly by StateStack to store Handler instances and parameters + * from HandlerDescriptor that are not stored in the Handler instance + * itself. Instances of the HandlerInstance class can be created using the + * HandlerDescriptor "create" method. + */ +struct HandlerInstance { + /** + * Pointer at the actual handler instance. + */ + std::shared_ptr handler; + + const HandlerDescriptor *descr; + + HandlerInstance(Handler *handler, const HandlerDescriptor *descr) + : handler(handler), descr(descr) + { + } +}; + +/** + * Used internally by StateStack to store the pushdown automaton + * description. + */ +struct HandlerDescriptor { + /** + * The valid parent states. + */ + const std::set parentStates; + + /** + * Pointer at a function which creates a new concrete Handler instance. + */ + const HandlerConstructor ctor; + + /** + * The target state for the registered handler. + */ + const State targetState; + + /** + * Set to true if this handler instance allows arbitrary children as + * tags. + */ + const bool arbitraryChildren; + + HandlerDescriptor(std::set parentStates, HandlerConstructor ctor, + State targetState, bool arbitraryChildren = false) + : parentStates(std::move(parentStates)), + ctor(ctor), + targetState(targetState), + arbitraryChildren(arbitraryChildren) + { + } + + /** + * Creates an instance of the concrete Handler class represented by the + * HandlerDescriptor and calls its start function. + */ + HandlerInstance create(const ParserContext &ctx, std::string name, + State parentState, bool isChild, char **attrs) const; +}; + +/** + * The ParserStack class is a pushdown automaton responsible for turning a + * command stream into a tree of Node instances. + */ +class ParserStack { +private: + /** + * Reference at the parser context. + */ + const ParserContext &ctx; + + /** + * Map containing all registered command names and the corresponding + * handler + * descriptor. + */ + const std::multimap &handlers; + + /** + * Internal stack used for managing the currently active Handler instances. + */ + std::stack stack; + + /** + * Used internally to get all expected command names for the given state + * (does not work if the current Handler instance allows arbitrary + * children). This function is used to build error messages. + * + * @param state is the state for which all expected command names should be + * returned. + */ + std::set expectedCommands(State state); + +public: + /** + * Creates a new instance of the ParserStack class. + * + * @param handlers is a map containing the command names and the + * corresponding HandlerDescriptor instances. + */ + ParserStack(const ParserContext &ctx, + const std::multimap &handlers) + : ctx(ctx), handlers(handlers){}; + + /** + * Returns the state the ParserStack instance currently is in. + * + * @return the state of the currently active Handler instance or STATE_NONE + * if no handler is on the stack. + */ + State currentState() { + return stack.empty() ? STATE_NONE : stack.top().handler->state; + } + + /** + * Returns the command name that is currently being handled. + * + * @return the name of the command currently being handled by the active + * Handler instance or an empty string if no handler is currently active. + */ + std::string currentName() { + return stack.empty() ? std::string{} : stack.top().handler->name; + } + + /** + * Returns whether the current command handler allows arbitrary children. + * + * @return true if the handler allows arbitrary children, false otherwise. + */ + bool currentArbitraryChildren() { + return stack.empty() ? false : stack.top().descr->arbitraryChildren; + } + + // TODO: Change signature + void start(std::string name, char **attrs); + + void end(); + + // TODO: Change signature + void data(const char *data, int len); +}; +} +} + +#endif /* _OUSIA_PARSER_STACK_HPP_ */ + diff --git a/src/core/parser/Scope.hpp b/src/core/parser/Scope.hpp index 0c37fbd..9c5504f 100644 --- a/src/core/parser/Scope.hpp +++ b/src/core/parser/Scope.hpp @@ -19,6 +19,8 @@ #ifndef _OUSIA_PARSER_SCOPE_H_ #define _OUSIA_PARSER_SCOPE_H_ +#include + #include /** diff --git a/src/core/parser/XmlStates.cpp b/src/core/parser/XmlStates.cpp deleted file mode 100644 index ec0f002..0000000 --- a/src/core/parser/XmlStates.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - Ousía - Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel - - 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 3 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, see . -*/ - -#include "XmlStates.hpp" - -namespace ousia { -namespace parser { -namespace xml { - -std::set StateStack::expectedCommands(State state) -{ - std::set res; - for (const auto &v: handlers) { - if (v.second.parentStates.count(state)) { - res.insert(v.first); - } - } - return res; -} - -void StateStack::start(std::string tagName, char **attrs) { - // Fetch the current handler and the current state - const Handler *h = stack.empty() ? nullptr : stack.top(); - const State currentState = h ? State::NONE : h->state; - - // Fetch all handlers for the given tagName - auto range = handlers.equal_range(tagName); - if (range->first == handlers.end()) { - // There are no handlers registered for this tag name -- check whether - // the current handler supports arbitrary children - if (h && h->arbitraryChildren) - } -} - -} -} -} - diff --git a/src/core/parser/XmlStates.hpp b/src/core/parser/XmlStates.hpp deleted file mode 100644 index 70e95f4..0000000 --- a/src/core/parser/XmlStates.hpp +++ /dev/null @@ -1,301 +0,0 @@ -/* - Ousía - Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel - - 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 3 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, see . -*/ - -#ifndef _OUSIA_XML_STATES_HPP_ -#define _OUSIA_XML_STATES_HPP_ - -#include - -#include -#include -#include -#include - -namespace ousia { -namespace parser { - -class Scope; -class Registry; -class Logger; - -namespace xml { - -/** - * The State class represents all states the XML parser can be in. These states - * mostly represent single tags. - */ -enum class State : uint8_t { - /* Meta states */ - ALL = -1, - - /* Start state */ - NONE, - - /* Special commands */ - INCLUDE, - INLINE, - - /* Document states */ - DOCUMENT, - HEAD, - BODY, - - /* Domain description states */ - DOMAIN, - - /* Type system states */ - TYPESYSTEM, - TYPE, - TYPE_ELEM -}; - -/** - * The handler class provides a context for handling an XML tag. It has to be - * overridden and registered in the StateStack class to form handlers for - * concrete XML tags. - */ -class Handler { -private: - Rooted node; - -protected: - void setNode(Handle node) { this->node = node; } - -public: - /** - * Reference to the ParserContext instance that should be used to resolve - * references to nodes in the Graph. - */ - const ParserContext &ctx; - - /** - * Contains the name of the tag that is being handled. - */ - const std::string name; - - /** - * Contains the current state of the state machine. - */ - const State state; - - /** - * Contains the state of the state machine when the parent node was handled. - */ - const State parentState; - - /** - * Set to true if the tag that is being handled is not the tag that was - * specified in the state machine but a child tag of that tag. - */ - const bool isChild; - - /** - * Constructor of the Handler class. - * - * @param ctx is the parser context the handler should be executed in. - * @param name is the name of the string. - * @param state is the state this handler was called for. - * @param parentState is the state of the parent command. - * @param isChild specifies whether this handler was called not for the - * command that was specified in the state machine but a child command. - */ - Handler(const ParserContext &ctx, std::string name, State state, - State parentState, bool isChild) - : ctx(ctx), - name(std::move(name)), - state(state), - parentState(parentState), - isChild(isChild){}; - - /** - * Virtual destructor. - */ - virtual ~Handler(); - - /** - * Returns the node instance that was created by the handler. - * - * @return the Node instance created by the handler. May be nullptr if no - * Node was created. - */ - Rooted getNode() { return node; } - - /** - * Called when the command that was specified in the constructor is - * instanciated. - * - * @param attrs contains the attributes that were specified for the command. - * TODO: Replace with StructInstance! - */ - virtual void start(char **attrs) = 0; - - /** - * Called whenever the command for which this handler - */ - virtual void end() = 0; - - /** - * Called whenever raw data (int the form of a string) is available for the - * Handler instance. - * - * TODO: Replace with std::string? - * - * @param data is a pointer at the character data that is available for the - * Handler instance. - */ - virtual void data(char *data, int len){}; - - /** - * Called whenever a direct child element was created and has ended. - * - * @param handler is a reference at the child Handler instance. - */ - virtual void child(Handler *handler){}; -}; - -/** - * HandlerConstructor is a function pointer type used to create concrete - * instances of the Handler class. - */ -using HandlerConstructor = Handler *(*)(const ParserContext &ctx, - std::string name, State state, - State parentState, bool isChild); - -/** - * The StateStack class is a pushdown automaton responsible for turning a - * command stream into a tree of Node instances. - */ -class StateStack { -public: - /** - * Used internlly by StateStack to store Handler instances and parameters - * from HandlerDescriptor that are not stored in the Handler instance - * itself. Instances of the HandlerInstance class can be created using the - * HandlerDescriptor "create" method. - */ - struct HandlerInstance { - /** - * Pointer at the actual handler instance. - */ - std::unique_ptr handler; - - /** - * Value of the arbitraryChildren flag stored in the HandlerDescriptor - * class. - */ - const bool arbitraryChildren; - - HandlerInstance(std::unique_ptr handler, - bool arbitraryChildren) - : handler(handler), arbitraryChildren(arbitraryChildren) - { - } - } - - /** - * Used internally by StateStack to store the pushdown automaton - * description. - */ - struct HandlerDescriptor { - /** - * The valid parent states. - */ - const std::set parentStates; - - /** - * Pointer at a function which creates a new concrete Handler instance. - */ - const HandlerConstructor ctor; - - /** - * The target state for the registered handler. - */ - const State targetState; - - /** - * Set to true if this handler instance allows arbitrary children as - * tags. - */ - const bool arbitraryChildren; - - HandlerDescriptor(std::set parentStates, HandlerConstructor ctor, - State targetState, bool arbitraryChildren = false) - : parentStates(std::move(parentStates)), - ctor(constructor), - targetState(targetState), - arbitraryChildren(arbitraryChildren) - { - } - - HandlerInstance create(const ParserContext &ctx, std::string name, - State parentState, bool isChild) - { - return HandlerInstance{ - ctor(ctx, name, targetState, parentState, isChild), - arbitraryChildren}; - } - }; - -private: - /** - * Map containing all registered command names and the corresponding - * handler - * descriptor. - */ - const std::multimap handlers; - - /** - * Reference at the parser context. - */ - const ParserContext &ctx; - - /** - * Internal stack used for managing the currently active Handler instances. - */ - std::stack stack; - - /** - * Used internally to get all expected command names for the given state - * (does not work if the current Handler instance allows arbitrary - * children). This function is used to build error messages. - * - * @param state is the state for which all expected command names should be - * returned. - */ - std::set expectedCommands(State state); - -public: - /** - * Creates a new instance of the StateStack class. - * - * @param handlers is a map containing the command names and the - * corresponding HandlerDescriptor instances. - */ - StateStack(const ParserContext &ctx, - std::multimap handlers) - : handlers(std::move(handlers)), - ctx(ctx), - currentState(State::NONE), - arbitraryChildren(false); -}; -} -} -} - -#endif /* _OUSIA_XML_STATES_HPP_ */ - diff --git a/test/core/parser/ParserStackTest.cpp b/test/core/parser/ParserStackTest.cpp new file mode 100644 index 0000000..92249ff --- /dev/null +++ b/test/core/parser/ParserStackTest.cpp @@ -0,0 +1,165 @@ +/* + SCAENEA IDL Compiler (scidlc) + Copyright (C) 2014 Andreas Stöckel + + 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 3 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, see . +*/ + +#include + +#include + +#include + +namespace ousia { +namespace parser { + +static const State STATE_DOCUMENT = 0; +static const State STATE_BODY = 1; +static const State STATE_EMPTY = 2; + +static int startCount = 0; +static int endCount = 0; +static int dataCount = 0; +static int childCount = 0; + +class TestHandler : public Handler { + +public: + using Handler::Handler; + + void start(char **attrs) override + { + startCount++; +// std::cout << this->name << ": start (isChild: " << (this->isChild) << ")" << std::endl; + } + + void end() override + { + endCount++; +// std::cout << this->name << ": end " << std::endl; + } + + void data(const char *data, int len) override + { + dataCount++; +// std::cout << this->name << ": data \"" << std::string{data, static_cast(len)} << "\"" << std::endl; + } + + void child(std::shared_ptr handler) override + { + childCount++; +// std::cout << this->name << ": has child \"" << handler->name << "\"" << std::endl; + } + +}; + +static Handler* createTestHandler(const ParserContext &ctx, + std::string name, State state, + State parentState, bool isChild) +{ + return new TestHandler(ctx, name, state, parentState, isChild); +} + +// Two nested elements used for testing +static const std::multimap TEST_HANDLERS{ + {"document", {{STATE_NONE}, createTestHandler, STATE_DOCUMENT}}, + {"body", {{STATE_DOCUMENT}, createTestHandler, STATE_BODY, true}}, + {"empty", {{STATE_DOCUMENT}, createTestHandler, STATE_EMPTY}}, +}; + + +TEST(ParserStack, simpleTest) +{ + StandaloneParserContext ctx; + ParserStack s{ctx, TEST_HANDLERS}; + + startCount = 0; + endCount = 0; + dataCount = 0; + childCount = 0; + + ASSERT_EQ("", s.currentName()); + ASSERT_EQ(STATE_NONE, s.currentState()); + + s.start("document", nullptr); + s.data("test1", 5); + + ASSERT_EQ("document", s.currentName()); + ASSERT_EQ(STATE_DOCUMENT, s.currentState()); + ASSERT_EQ(1, startCount); + ASSERT_EQ(1, dataCount); + + s.start("body", nullptr); + s.data("test2", 5); + ASSERT_EQ("body", s.currentName()); + ASSERT_EQ(STATE_BODY, s.currentState()); + ASSERT_EQ(2, startCount); + ASSERT_EQ(2, dataCount); + + s.start("inner", nullptr); + ASSERT_EQ("inner", s.currentName()); + ASSERT_EQ(STATE_BODY, s.currentState()); + s.end(); + ASSERT_EQ(3, startCount); + ASSERT_EQ(1, childCount); + ASSERT_EQ(1, endCount); + + s.end(); + ASSERT_EQ(2, childCount); + ASSERT_EQ(2, endCount); + + ASSERT_EQ("document", s.currentName()); + ASSERT_EQ(STATE_DOCUMENT, s.currentState()); + + s.start("body", nullptr); + s.data("test3", 5); + ASSERT_EQ("body", s.currentName()); + ASSERT_EQ(STATE_BODY, s.currentState()); + s.end(); + ASSERT_EQ(4, startCount); + ASSERT_EQ(3, dataCount); + ASSERT_EQ(3, childCount); + ASSERT_EQ(3, endCount); + + ASSERT_EQ("document", s.currentName()); + ASSERT_EQ(STATE_DOCUMENT, s.currentState()); + + s.end(); + ASSERT_EQ(4, endCount); + + ASSERT_EQ("", s.currentName()); + ASSERT_EQ(STATE_NONE, s.currentState()); +} + +TEST(ParserStack, errorHandling) +{ + StandaloneParserContext ctx; + ParserStack s{ctx, TEST_HANDLERS}; + + ASSERT_THROW(s.start("body", nullptr), OusiaException); + s.start("document", nullptr); + ASSERT_THROW(s.start("document", nullptr), OusiaException); + s.start("empty", nullptr); + ASSERT_THROW(s.start("body", nullptr), OusiaException); + s.end(); + s.end(); + ASSERT_EQ(STATE_NONE, s.currentState()); + ASSERT_THROW(s.end(), OusiaException); + ASSERT_THROW(s.data("test", 1), OusiaException); +} + +} +} + -- cgit v1.2.3 From 0c26390e71193947a67bdd0536915523da38f00f Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Tue, 2 Dec 2014 14:59:17 +0100 Subject: added revamped variant type --- CMakeLists.txt | 33 +-- src/core/variant/Variant.cpp | 58 ++++ src/core/variant/Variant.hpp | 624 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 699 insertions(+), 16 deletions(-) create mode 100644 src/core/variant/Variant.cpp create mode 100644 src/core/variant/Variant.hpp (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 327f664..3a52b6e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -112,10 +112,11 @@ ADD_LIBRARY(ousia_core src/core/parser/Parser src/core/parser/ParserStack src/core/parser/Scope - src/core/script/Function - src/core/script/Object - src/core/script/ScriptEngine - src/core/script/Variant +# src/core/script/Function +# src/core/script/Object +# src/core/script/ScriptEngine +# src/core/script/Variant + src/core/variant/Variant ) # ousia_xml library @@ -159,9 +160,9 @@ IF(TEST) test/core/TokenizerTest test/core/UtilsTest test/core/parser/ParserStackTest - test/core/script/FunctionTest - test/core/script/ObjectTest - test/core/script/VariantTest +# test/core/script/FunctionTest +# test/core/script/ObjectTest +# test/core/script/VariantTest ) TARGET_LINK_LIBRARIES(ousia_test_core @@ -179,19 +180,19 @@ IF(TEST) ousia_xml ) - ADD_EXECUTABLE(ousia_test_mozjs - test/plugins/mozjs/MozJsScriptEngineTest - ) +# ADD_EXECUTABLE(ousia_test_mozjs +# test/plugins/mozjs/MozJsScriptEngineTest +# ) - TARGET_LINK_LIBRARIES(ousia_test_mozjs - ${GTEST_LIBRARIES} - ousia_core - ousia_mozjs - ) +# TARGET_LINK_LIBRARIES(ousia_test_mozjs +# ${GTEST_LIBRARIES} +# ousia_core +# ousia_mozjs +# ) # Register the unit tests ADD_TEST(ousia_test_core ousia_test_core) ADD_TEST(ousia_test_xml ousia_test_xml) - ADD_TEST(ousia_test_mozjs ousia_test_mozjs) +# ADD_TEST(ousia_test_mozjs ousia_test_mozjs) ENDIF() diff --git a/src/core/variant/Variant.cpp b/src/core/variant/Variant.cpp new file mode 100644 index 0000000..c86905c --- /dev/null +++ b/src/core/variant/Variant.cpp @@ -0,0 +1,58 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + 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 3 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, see . +*/ + +#include "Variant.hpp" + +namespace ousia { + +/* Class Variant */ + +const char *Variant::getTypeName(Type type) +{ + switch (type) { + case Type::NULLPTR: + return "null"; + case Type::BOOL: + return "boolean"; + case Type::INT: + return "integer"; + case Type::DOUBLE: + return "number"; + case Type::STRING: + return "string"; + case Type::ARRAY: + return "array"; + case Type::MAP: + return "map"; + } + return "unknown"; +} + +/* Class VariantTypeException */ + +Variant::TypeException::TypeException(Type actualType, Type requestedType) + : OusiaException(std::string("Variant: Requested \"") + + Variant::getTypeName(actualType) + + std::string("\" but is \"") + + Variant::getTypeName(requestedType) + std::string("\"")), + actualType(actualType), + requestedType(requestedType) +{ +} +} + diff --git a/src/core/variant/Variant.hpp b/src/core/variant/Variant.hpp new file mode 100644 index 0000000..26b053a --- /dev/null +++ b/src/core/variant/Variant.hpp @@ -0,0 +1,624 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + 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 3 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, see . +*/ + +/** + * @file Variant.hpp + * + * The Variant class is used to efficiently represent a variables of varying + * type. Variant instances are used to represent user data and to exchange + * information between the host application and the script clients. + * + * @author Andreas Stöckel (astoecke@techfak.uni-bielefeld.de) + */ + +#ifndef _OUSIA_VARIANT_HPP_ +#define _OUSIA_VARIANT_HPP_ + +#include +#include +#include +#include + +// TODO: Use +// http://nikic.github.io/2012/02/02/Pointer-magic-for-efficient-dynamic-value-representations.html +// later (will allow to use 8 bytes for a variant) + +#include + +namespace ousia { + +/** + * Instances of the Variant class represent any kind of data that is exchanged + * between the host application and the script engine. Variants are immutable. + */ +class Variant { +public: + /** + * Enum containing the possible types a variant may have. + */ + enum class Type : int16_t { + NULLPTR, + BOOL, + INT, + DOUBLE, + STRING, + ARRAY, + MAP + }; + + /** + * Exception thrown whenever a variant is accessed via a getter function + * that + * is not supported for the current variant type. + */ + class TypeException : public OusiaException { + private: + /** + * Internally used string holding the exception message. + */ + const std::string msg; + + public: + /** + * Contains the actual type of the variant. + */ + const Type actualType; + + /** + * Contains the requested type of the variant. + */ + const Type requestedType; + + /** + * Constructor of the TypeException. + * + * @param actualType describes the actual type of the variant. + * @param requestedType describes the type in which the variant was + * requested. + */ + TypeException(Type actualType, Type requestedType); + }; + + using boolType = bool; + using intType = int32_t; + using doubleType = double; + using stringType = std::string; + using arrayType = std::vector; + using mapType = std::map; + +private: + /** + * Used to store the actual type of the variant. + */ + Type type = Type::NULLPTR; + + /** + * Anonymous union containing the possible value of the variant. + */ + union { + /** + * The boolean value. Only valid if type is Type::BOOL. + */ + boolType boolVal; + /** + * The integer value. Only valid if type is Type::INT. + */ + intType intVal; + /** + * The number value. Only valid if type is Type::DOUBLE. + */ + doubleType doubleVal; + /** + * Pointer to the more complex data structures on the free store. Only + * valid if type is one of Type::STRING, Type::ARRAY, + * Type::MAP. + */ + void *ptrVal = nullptr; + }; + + /** + * Internally used to convert the current pointer value to a reference of + * the specified type. + */ + template + T &asObj(Type requestedType) const + { + const Type actualType = getType(); + if (actualType == requestedType) { + return *(static_cast(ptrVal)); + } + throw TypeException{actualType, requestedType}; + } + + /** + * Used internally to assign the value of another Variant instance to this + * instance. + * + * @param v is the Variant instance that should be copied to this instance. + */ + void copy(const Variant &v) + { + type = v.type; + switch (type) { + case Type::NULLPTR: + break; + case Type::BOOL: + boolVal = v.boolVal; + break; + case Type::INT: + intVal = v.intVal; + break; + case Type::DOUBLE: + doubleVal = v.doubleVal; + break; + case Type::STRING: + ptrVal = new stringType{v.asString()}; + break; + case Type::ARRAY: + ptrVal = new arrayType{v.asArray()}; + break; + case Type::MAP: + ptrVal = new mapType{v.asMap()}; + break; + } + } + + /** + * Used internally to move the value of another Variant instance to this + * instance. + * + * @param v is the Variant instance that should be copied to this instance. + */ + void move(Variant &&v) + { + type = v.type; + switch (type) { + case Type::NULLPTR: + break; + case Type::BOOL: + boolVal = v.boolVal; + break; + case Type::INT: + intVal = v.intVal; + break; + case Type::DOUBLE: + doubleVal = v.doubleVal; + break; + case Type::STRING: + case Type::ARRAY: + case Type::MAP: + ptrVal = v.ptrVal; + v.ptrVal = nullptr; + break; + } + v.type = Type::NULLPTR; + } + + /** + * Used internally to destroy any value that was allocated on the heap. + */ + void destroy() + { + if (ptrVal) { + switch (type) { + case Type::STRING: + delete static_cast(ptrVal); + break; + case Type::ARRAY: + delete static_cast(ptrVal); + break; + case Type::MAP: + delete static_cast(ptrVal); + break; + default: + break; + } + } + } + +public: + /** + * Copy constructor of the Variant class. + * + * @param v is the Variant instance that should be cloned. + */ + Variant(const Variant &v) { copy(v); } + + /** + * Move constructor of the Variant class. + * + * @param v is the reference to the Variant instance that should be moved, + * this instance is invalidated afterwards. + */ + Variant(Variant &&v) { move(std::move(v)); } + + /** + * Default constructor. Type is set to Type:null. + */ + Variant() { setNull(); } + + /** + * Default destructor, frees any memory that was allocated on the heap. + */ + ~Variant() { destroy(); } + + /** + * Constructor for boolean values. + * + * @param b boolean value. + */ + Variant(boolType b) { setBool(b); } + + /** + * Constructor for integer values. + * + * @param i integer value. + */ + Variant(intType i) { setInt(i); } + + /** + * Constructor for double values. + * + * @param d double value. + */ + Variant(doubleType d) { setDouble(d); } + + /** + * Constructor for string values. The given string is copied and managed by + * the new Variant instance. + * + * @param s is a reference to a C-Style string used as string value. + */ + Variant(const char *s) { setString(s); } + + /** + * Constructor for array values. The given array is copied and managed by + * the new Variant instance. + * + * @param a is a reference to the array + */ + Variant(std::vector a) { setArray(std::move(a)); } + + /** + * Constructor for map values. The given map is copied and managed by the + * new Variant instance. + * + * @param m is a reference to the map. + */ + Variant(std::map m) { setMap(std::move(m)); } + + /** + * Copy assignment operator. + */ + Variant &operator=(const Variant &v) + { + copy(v); + return *this; + } + + /** + * Move assignment operator. + */ + Variant &operator=(Variant &&v) + { + move(std::move(v)); + return *this; + } + + /** + * Assign nullptr_t operator (allows to write Variant v = nullptr). + * + * @param p is an instance of std::nullptr_t. + */ + Variant &operator=(std::nullptr_t) + { + setNull(); + return *this; + } + + /** + * Assign a boolean value. + * + * @param b is the boolean value to which the variant should be set. + */ + Variant &operator=(boolType b) + { + setBool(b); + return *this; + } + + /** + * Assign an integer value. + * + * @param i is the integer value to which the variant should be set. + */ + Variant &operator=(intType i) + { + setInt(i); + return *this; + } + + /** + * Assign a double value. + * + * @param i is the integer value to which the variant should be set. + */ + Variant &operator=(doubleType d) + { + setInt(d); + return *this; + } + + /** + * Checks whether this Variant instance represents the nullptr. + * + * @return true if the Variant instance represents the nullptr, false + * otherwise. + */ + bool isNull() const { return type == Type::NULLPTR; } + + /** + * Checks whether this Variant instance is a boolean. + * + * @return true if the Variant instance is a boolean, false otherwise. + */ + bool isBool() const { return type == Type::BOOL; } + + /** + * Checks whether this Variant instance is an integer. + * + * @return true if the Variant instance is an integer, false otherwise. + */ + bool isInt() const { return type == Type::INT; } + + /** + * Checks whether this Variant instance is a double. + * + * @return true if the Variant instance is a double, false otherwise. + */ + bool isDouble() const { return type == Type::DOUBLE; } + + /** + * Checks whether this Variant instance is a string. + * + * @return true if the Variant instance is a string, false otherwise. + */ + bool isString() const { return type == Type::STRING; } + + /** + * Checks whether this Variant instance is an array. + * + * @return true if the Variant instance is an array, false otherwise. + */ + bool isArray() const { return type == Type::ARRAY; } + + /** + * Checks whether this Variant instance is a map. + * + * @return true if the Variant instance is a map, false otherwise. + */ + bool isMap() const { return type == Type::MAP; } + + /** + * Returns the Variant boolean value. Performs no type conversion. Throws an + * exception if the underlying type is not a boolean. + * + * @return the boolean value. + */ + boolType asBool() const + { + if (isBool()) { + return boolVal; + } + throw TypeException{getType(), Type::BOOL}; + } + + /** + * Returns the Variant integer value. Performs no type conversion. Throws an + * exception if the underlying type is not an integer. + * + * @return the integer value. + */ + intType asInt() const + { + if (isInt()) { + return intVal; + } + throw TypeException{getType(), Type::INT}; + } + + /** + * Returns the Variant double value. Performs no type conversion. Throws an + * exception if the underlying type is not a double. + * + * @return the double value. + */ + doubleType asDouble() const + { + if (isDouble()) { + return doubleVal; + } + throw TypeException{getType(), Type::DOUBLE}; + } + + /** + * Returns a const reference to the string value. Performs no type + * conversion. Throws an exception if the underlying type is not a string. + * + * @return the string value as const reference. + */ + const stringType &asString() const + { + return asObj(Type::STRING); + } + + /** + * Returns a const reference to the string value. Performs no type + * conversion. Throws an exception if the underlying type is not a string. + * + * @return the string value as reference. + */ + stringType &asString() { return asObj(Type::STRING); } + + /** + * Returns a const reference to the array value. Performs no type + * conversion. Throws an exception if the underlying type is not an array. + * + * @return the array value as const reference. + */ + const arrayType &asArray() const { return asObj(Type::ARRAY); } + + /** + * Returns a const reference to the array value. Performs no type + * conversion. Throws an exception if the underlying type is not an array. + * + * @return the array value as reference. + */ + arrayType &asArray() { return asObj(Type::ARRAY); } + + /** + * Returns a const reference to the map value. Performs no type + * conversion. Throws an exception if the underlying type is not a map. + * + * @return the map value as const reference. + */ + const mapType &asMap() const { return asObj(Type::MAP); } + + /** + * Returns a reference to the map value. Performs no type conversion. + * Throws an exception if the underlying type is not a map. + * + * @return the map value as reference. + */ + mapType &asMap() { return asObj(Type::MAP); } + + /** + * Sets the variant to null. + */ + void setNull() + { + destroy(); + type = Type::NULLPTR; + ptrVal = nullptr; + } + + /** + * Sets the variant to the given boolean value. + * + * @param b is the new boolean value. + */ + void setBool(boolType b) + { + destroy(); + type = Type::BOOL; + boolVal = b; + } + + /** + * Sets the variant to the given integer value. + * + * @param i is the new integer value. + */ + void setInt(intType i) + { + destroy(); + type = Type::INT; + intVal = i; + } + + /** + * Sets the variant to the given double value. + * + * @param d is the new double value. + */ + void setDouble(doubleType d) + { + destroy(); + type = Type::DOUBLE; + doubleVal = d; + } + + /** + * Sets the variant to the given string value. + * + * @param d is the new string value. + */ + void setString(const char *s) + { + if (isString()) { + asString().assign(s); + } else { + destroy(); + type = Type::STRING; + ptrVal = new stringType{s}; + } + } + + /** + * Sets the variant to the given array value. + * + * @param a is the new array value. + */ + void setArray(arrayType a) + { + if (isArray()) { + asArray().swap(a); + } else { + destroy(); + type = Type::ARRAY; + ptrVal = new arrayType{std::move(a)}; + } + } + + /** + * Sets the variant to the given map value. + * + * @param a is the new map value. + */ + void setMap(mapType m) + { + if (isMap()) { + asMap().swap(m); + } else { + destroy(); + type = Type::MAP; + ptrVal = new mapType{std::move(m)}; + } + } + + /** + * Returns the current type of the Variant. + * + * @return the current type of the Variant. + */ + Type getType() const { return type; } + + /** + * Returns the name of the given variant type as C-style string. + */ + static const char *getTypeName(Type type); + + /** + * Returns the name of the type of this variant instance. + */ + const char *getTypeName() { return Variant::getTypeName(getType()); } +}; +} + +#endif /* _OUSIA_VARIANT_HPP_ */ + -- cgit v1.2.3 From 65778eb19e1b4d7d5d145bb2167df0eb01935da7 Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Tue, 2 Dec 2014 15:58:48 +0100 Subject: added new unit test for the Variant class and fixed some bugs --- CMakeLists.txt | 1 + src/core/variant/Variant.hpp | 48 +++++++++++----- test/core/variant/VariantTest.cpp | 118 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 153 insertions(+), 14 deletions(-) create mode 100644 test/core/variant/VariantTest.cpp (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index 3a52b6e..cb4d073 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -163,6 +163,7 @@ IF(TEST) # test/core/script/FunctionTest # test/core/script/ObjectTest # test/core/script/VariantTest + test/core/variant/VariantTest ) TARGET_LINK_LIBRARIES(ousia_test_core diff --git a/src/core/variant/Variant.hpp b/src/core/variant/Variant.hpp index 26b053a..6b5d03f 100644 --- a/src/core/variant/Variant.hpp +++ b/src/core/variant/Variant.hpp @@ -128,7 +128,7 @@ private: * valid if type is one of Type::STRING, Type::ARRAY, * Type::MAP. */ - void *ptrVal = nullptr; + void *ptrVal; }; /** @@ -153,6 +153,7 @@ private: */ void copy(const Variant &v) { + destroy(); type = v.type; switch (type) { case Type::NULLPTR: @@ -186,6 +187,7 @@ private: */ void move(Variant &&v) { + destroy(); type = v.type; switch (type) { case Type::NULLPTR: @@ -237,7 +239,7 @@ public: * * @param v is the Variant instance that should be cloned. */ - Variant(const Variant &v) { copy(v); } + Variant(const Variant &v) : ptrVal(nullptr) { copy(v); } /** * Move constructor of the Variant class. @@ -245,12 +247,12 @@ public: * @param v is the reference to the Variant instance that should be moved, * this instance is invalidated afterwards. */ - Variant(Variant &&v) { move(std::move(v)); } + Variant(Variant &&v) : ptrVal(nullptr) { move(std::move(v)); } /** * Default constructor. Type is set to Type:null. */ - Variant() { setNull(); } + Variant() : ptrVal(nullptr) { setNull(); } /** * Default destructor, frees any memory that was allocated on the heap. @@ -262,21 +264,21 @@ public: * * @param b boolean value. */ - Variant(boolType b) { setBool(b); } + Variant(boolType b) : ptrVal(nullptr) { setBool(b); } /** * Constructor for integer values. * * @param i integer value. */ - Variant(intType i) { setInt(i); } + Variant(intType i) : ptrVal(nullptr) { setInt(i); } /** * Constructor for double values. * * @param d double value. */ - Variant(doubleType d) { setDouble(d); } + Variant(doubleType d) : ptrVal(nullptr) { setDouble(d); } /** * Constructor for string values. The given string is copied and managed by @@ -284,7 +286,7 @@ public: * * @param s is a reference to a C-Style string used as string value. */ - Variant(const char *s) { setString(s); } + Variant(const char *s) : ptrVal(nullptr) { setString(s); } /** * Constructor for array values. The given array is copied and managed by @@ -292,7 +294,10 @@ public: * * @param a is a reference to the array */ - Variant(std::vector a) { setArray(std::move(a)); } + Variant(arrayType a) : ptrVal(nullptr) + { + setArray(std::move(a)); + } /** * Constructor for map values. The given map is copied and managed by the @@ -300,7 +305,10 @@ public: * * @param m is a reference to the map. */ - Variant(std::map m) { setMap(std::move(m)); } + Variant(mapType m) : ptrVal(nullptr) + { + setMap(std::move(m)); + } /** * Copy assignment operator. @@ -356,11 +364,23 @@ public: /** * Assign a double value. * - * @param i is the integer value to which the variant should be set. + * @param d is the double value to which the variant should be set. */ Variant &operator=(doubleType d) { - setInt(d); + setDouble(d); + return *this; + } + + /** + * Assign a zero terminated const char array. + * + * @param s is the zero terminated const char array to which the variant + * should be set. + */ + Variant &operator=(const char *s) + { + setString(s); return *this; } @@ -581,7 +601,7 @@ public: } else { destroy(); type = Type::ARRAY; - ptrVal = new arrayType{std::move(a)}; + ptrVal = new arrayType(std::move(a)); } } @@ -597,7 +617,7 @@ public: } else { destroy(); type = Type::MAP; - ptrVal = new mapType{std::move(m)}; + ptrVal = new mapType(std::move(m)); } } diff --git a/test/core/variant/VariantTest.cpp b/test/core/variant/VariantTest.cpp new file mode 100644 index 0000000..dfa2f1b --- /dev/null +++ b/test/core/variant/VariantTest.cpp @@ -0,0 +1,118 @@ +/* + Ousía + Copyright (C) 2014, 2015 Benjamin Paaßen, Andreas Stöckel + + 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 3 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, see . +*/ + +#include + +#include + +namespace ousia { + +TEST(Variant, nullValue) +{ + Variant v; + ASSERT_TRUE(v.isNull()); + + v = 1; + ASSERT_FALSE(v.isNull()); + + v = nullptr; + ASSERT_TRUE(v.isNull()); +} + +TEST(Variant, booleanValue) +{ + Variant v{true}; + ASSERT_TRUE(v.isBool()); + ASSERT_TRUE(v.asBool()); + + v = false; + ASSERT_TRUE(v.isBool()); + ASSERT_FALSE(v.asBool()); + + v.setBool(true); + ASSERT_TRUE(v.isBool()); + ASSERT_TRUE(v.asBool()); + + v = nullptr; + ASSERT_FALSE(v.isBool()); +} + +TEST(Variant, intValue) +{ + Variant v{42}; + ASSERT_TRUE(v.isInt()); + ASSERT_EQ(42, v.asInt()); + + v = 43; + ASSERT_TRUE(v.isInt()); + ASSERT_EQ(43, v.asInt()); + + v = false; + ASSERT_FALSE(v.isInt()); +} + +TEST(Variant, doubleValue) +{ + Variant v{42.5}; + ASSERT_TRUE(v.isDouble()); + ASSERT_EQ(42.5, v.asDouble()); + + v = 42; + ASSERT_FALSE(v.isDouble()); + + v = 43.5; + ASSERT_TRUE(v.isDouble()); + ASSERT_EQ(43.5, v.asDouble()); +} + +TEST(Variant, stringValue) +{ + Variant v{"Hello World"}; + ASSERT_TRUE(v.isString()); + ASSERT_EQ("Hello World", v.asString()); + + v = "Goodbye World"; + ASSERT_TRUE(v.isString()); + ASSERT_EQ("Goodbye World", v.asString()); + + v = 42; + ASSERT_FALSE(v.isString()); +} + +TEST(Variant, arrayValue) +{ + const Variant v{{"test1", 42}}; + ASSERT_EQ(2, v.asArray().size()); + ASSERT_EQ("test1", v.asArray()[0].asString()); + ASSERT_EQ(42, v.asArray()[1].asInt()); +} + +TEST(Variant, mapValue) +{ + const Variant v{{{"key1", "entry1"}, {"key2", "entry2"}}}; + + auto map = v.asMap(); + ASSERT_EQ(2, map.size()); + + ASSERT_EQ("entry1", map.find("key1")->second.asString()); + ASSERT_EQ("entry2", map.find("key2")->second.asString()); +} + + +} + -- cgit v1.2.3 From 92a31ed239fe41af07bb13d572203a7753091a5b Mon Sep 17 00:00:00 2001 From: Andreas Stöckel Date: Wed, 3 Dec 2014 00:00:02 +0100 Subject: temporarily removed mozjs binding --- CMakeLists.txt | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) (limited to 'CMakeLists.txt') diff --git a/CMakeLists.txt b/CMakeLists.txt index cb4d073..14a50be 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -96,8 +96,6 @@ ADD_DEFINITIONS( ${MOZJS_CFLAGS_OTHER} ) -# ousia_script library (containing the bindings needed for script engines) -# TODO: This is not only the script library. ADD_LIBRARY(ousia_core src/core/BufferedCharReader src/core/CodeTokenizer @@ -119,8 +117,6 @@ ADD_LIBRARY(ousia_core src/core/variant/Variant ) -# ousia_xml library - ADD_LIBRARY(ousia_xml src/plugins/xml/XmlParser ) @@ -130,16 +126,14 @@ TARGET_LINK_LIBRARIES(ousia_xml ${EXPAT_LIBRARIES} ) -# ousia_mozjs library - -ADD_LIBRARY(ousia_mozjs - src/plugins/mozjs/MozJsScriptEngine -) - -TARGET_LINK_LIBRARIES(ousia_mozjs - ousia_core - ${MOZJS_LIBRARIES} -) +#ADD_LIBRARY(ousia_mozjs +# src/plugins/mozjs/MozJsScriptEngine +#) +# +#TARGET_LINK_LIBRARIES(ousia_mozjs +# ousia_core +# ${MOZJS_LIBRARIES} +#) # If testing is enabled, build the unit tests IF(TEST) -- cgit v1.2.3