From 9bdba2aa4cfd04b28d18c6af4dca21c32d101132 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Tue, 4 Oct 2016 14:37:35 -0300 Subject: [PATCH] Decouple operations (#30) * Replace all `scope->find(name)` calls for `scope[name]` These calls were on the built-in functions declarations, and were used to recover the function arguments. This change was made because the find() function was not the correct tool for the job; The find() function looks on the entire prototype chain of the scope for the variable, and this is not needed on this case since the function arguments will always be on the most local scope of the function. This refactor makes the code more readable and sightly more efficient. * Rename `argsList` to `args_t` * Convert Function::name from a literal string to a getter function * Simplify CppFunction constructor This commit adds a new constructor to CppFunction that expects a `const args_t` as argument. This way it is possible to define a new function without having to explicitly give how many arguments it receives, i.e.: CppFunction(&my_func, {"arg1", "arg2", "arg3"}, "my_func"); instead of: CppFunction(&my_func, 3, {"arg1", "arg2", "arg3"}, "my_func"); * Add new constructor to undefined_operation * Major refactor: decouple operations from calculator class Before this commit every new operation would be hard coded inside the static calculator::calculate() function. Now it is not required anymore. To add a new operation do as follow: ```C++ struct my_operation : public Operation { // This describes the operands expected by this operation: const opID_t getMask() { return build_mask(INT, REAL); } // This describes the operation behavior: TokenBase* exec(TokenBase* left, std::string op, TokenBase* right) { if (/* not satisfy condition */) { // Ignore this operation and keep looking for a match: return 0; } if (/* erro condition*/) { throw my_error("..."); } // if its all ok: TokenBase* result = some_code(left, right); // Consume both Tokens: delete left; delete right; // Return: return result; } // Don't forget to declare and static instance: } my_operation; struct my_Startup { my_Startup() { // Register the operation on the default opMap: opMap_t& opMap = calculator::default_opMap(); opMap[","].push_back(&my_operation); opMap[ANY_OP].push_back(&my_other_operation); } } my_Startup; ``` The default operations are on the operations.cpp file. To declare your own default operations, just make sure to not link your code to `operations.o`, and add your own description of your operations wherever you want. In future work: * Make an optional Operation function that works with packTokens, so the final user will not need to worry about memory management. * Make it possible to overwrite the default_opMap by extending the calculator class, creating any number of different calculators as required. * Add `release` recipe to Makefile The `make release` will output 2 `.o` files: - core-shunting-yard.o - operations.o The `core` bin contain an working calculator with no defined operations except for asignment and function call, that are still hard-coded on the system. The `operations` bin contain all the other default operations. If a user wants to define adhoc operations, include only the `core` binary. * Add tests for declaring adhoc operations * Simplify Operation definition Now there are 2 Operation classes: `BaseOperation` which is the old class with a new name and the `Operation` that inherits from the former. The `exec()` pure virtual function from BaseOperation has the following signature: TokenBase* exec(TokenBase*, std::string, TokenBase*); The `exec()` pure virtual function from Operation has the following signature: packToken exec(packToken, std::string, packToken); This makes the usage of the Operation class easier since hiding from the user the required memory management. Advanced users can declare new operations using the `BaseOperation` class. Working with TokenBase* is more efficient since it does not require to call the packToken constructor and destructor several times. * Make possible to define adhoc opPrecedence. Now it is possible to define your own operator precedence map the same way it is done for operations. The definition of the operator precedence was now moved to the file `operations.h` and is initialized just before the operations. If the user want to define its own operations and precedence map, he just need to compile his code without the file `operations.o`. After that he can define his own adhoc behavior in a file on his project. It is also possible to overwrite opPrecedence on a child calculator class. The user just need to overwrite the function "opPrecedence()". * Update README with new features. --- Makefile | 17 +- README.md | 39 ++-- functions.cpp | 117 +++++----- functions.h | 26 +-- objects.cpp | 12 +- operations.cpp | 449 ++++++++++++++++++++++++++++++++++++ packToken.cpp | 2 +- shunting-yard-exceptions.h | 2 + shunting-yard.cpp | 452 +++++++------------------------------ shunting-yard.h | 103 +++++++-- test-shunting-yard.cpp | 73 +++++- 11 files changed, 805 insertions(+), 487 deletions(-) create mode 100644 operations.cpp diff --git a/Makefile b/Makefile index f9c658b..42e3de2 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,20 @@ EXE = test-shunting-yard -SRC = $(EXE).cpp shunting-yard.cpp packToken.cpp functions.cpp objects.cpp catch.cpp +CORE_SRC = shunting-yard.cpp packToken.cpp functions.cpp objects.cpp +SRC = $(EXE).cpp $(CORE_SRC) operations.cpp catch.cpp OBJ = $(SRC:.cpp=.o) +LD ?= ld CXX ?= g++ -CFLAGS = -std=c++11 -g -Wall -pedantic #-DDEBUG +CFLAGS = -std=c++11 -Wall -pedantic +DEBUG = -g #-DDEBUG all: $(EXE) -$(EXE): $(OBJ); $(CXX) $(CFLAGS) $(OBJ) -o $(EXE) -%.o: %.cpp *.h; $(CXX) $(CFLAGS) -c $< -o $@ $(DEBUG) +$(EXE): $(OBJ); $(CXX) $(CFLAGS) $(DEBUG) $(OBJ) -o $(EXE) +%.o: %.cpp *.h; $(CXX) $(CFLAGS) $(DEBUG) -c $< -o $@ $(DEBUG) + +release: $(CORE_SRC) operations.cpp; + $(CXX) -c -O3 $(CFLAGS) $(CORE_SRC) operations.cpp + $(LD) -r -O1 $(CORE_SRC:.cpp=.o) -o core-shunting-yard.o again: clean all @@ -15,4 +22,4 @@ test: $(EXE); ./$(EXE) $(args) check: $(EXE); valgrind --leak-check=full ./$(EXE) $(args) -clean: ; rm -f $(EXE) $(OBJ) +clean: ; rm -f $(EXE) $(OBJ) core-shunting-yard.o full-shunting-yard.o diff --git a/README.md b/README.md index a31089d..e02b58e 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,7 @@ as an expression using Dijkstra's which modifies [Jesse Brown's original code](http://www.daniweb.com/software-development/cpp/code/427500/calculator-using-shunting-yard-algorithm). -*This project was created by [Brandon Amos](http://bamos.github.io) and -contains substantial modifications from Vinícius Garcia.* +*This project was developed by [Brandon Amos](http://bamos.github.io) and Vinícius Garcia.* --- @@ -111,7 +110,7 @@ int main() { Please note that a calculator can compile an expression so that it can efficiently be executed several times at a later moment. -## Using built-in containers. +## Using built-in List and Map. ```C++ int main() { @@ -145,13 +144,13 @@ int main() { We describe two functions: `foo` and `bar`. - `foo` works as a print() function. -- `bar` has no required arguments, but accept arguments anyway and print them. +- `bar` has no required arguments, but accept arguments anyway and prints them. ```C++ #include #include "shunting-yard.h" -const char* args[] = {"str"}; +const args_t args = {"str"}; packToken func_foo(TokenMap scope) { // Just print `str` std::string str = scope["str"].asString(); @@ -166,14 +165,14 @@ packToken func_bar(TokenMap scope) { return packToken::None; } -// This initializer is instantiated before main() is executed: +// This initializer is a trick to run code before main() is executed: struct FuncInitializer { FuncInitializer() { TokenMap& global_scope = TokenMap::default_global(); // Register the functions on the default global scope: - global_scope["bar"] = CppFunction(&func_bar, /*optional: */ "bar"); - global_scope["foo"] = CppFunction(&func_foo, 1, args, "foo"); + global_scope["bar"] = CppFunction(&func_bar, /*optional name:*/ "bar"); + global_scope["foo"] = CppFunction(&func_foo, args, "foo"); } } my_initializer; @@ -183,9 +182,12 @@ int main() { // Executing function bar with several arguments: calculator::calculate("bar('positional', 'args', 'key':'-', 'word':'args')"); - // output: - // arg-list: [ 'positional', 'args' ] - // key-word: { 'key': '-', 'word': 'args' } + + /* + * Output: + * arg-list: [ 'positional', 'args' ] + * key-word: { 'key': '-', 'word': 'args' } + */ return 0; } @@ -200,17 +202,18 @@ int main() { + Unary operators. +, - + Binary operators. +, -, /, *, %, <<, >>, ^ + Boolean operators. <, >, <=, >=, ==, !=, &&, || - + Support for local variables + Functions. sin, cos, tan, abs, print - + Easy to add new operators, functions and even new types + + Support for an hierarchy of scopes with local scope, global scope etc. + + Easy to add new operators, operations, functions and even new types + Easy to implement object-to-object inheritance (with the prototype concept) - + Built-in garbage collector (does not handle cyclic references yet). + + Built-in garbage collector (does not handle cyclic references yet) -# Adding a binary operator. -To add a binary operator, +# Writing your own operations. +To write your own operations: - 1. Update the operator precedence map in `calculator::buildOpPrecedence`. - 2. Add the computation to `calculator::calculate`. + 1. Copy the `operations.cpp` file. + 2. Edit it as you please; it is very easy to understand what to do. + 3. Compile your code and make sure to include your copied file instead of the original `.o`. # Implementation Details The main steps of the calculation process are: diff --git a/functions.cpp b/functions.cpp index 635f7fb..282b243 100644 --- a/functions.cpp +++ b/functions.cpp @@ -18,10 +18,10 @@ packToken Function::call(packToken _this, Function* func, TokenMap kwargs; TokenMap local = scope.getChild(); - argsList arg_names = func->args(); + args_t arg_names = func->args(); TokenList_t::iterator args_it = args->list().begin(); - argsList::const_iterator names_it = arg_names.begin(); + args_t::const_iterator names_it = arg_names.begin(); /* * * * * Parse named arguments: * * * * */ @@ -89,11 +89,13 @@ packToken Function::call(packToken _this, Function* func, return func->exec(local); } +namespace builtin_functions { + /* * * * * Built-in Functions: * * * * */ packToken default_print(TokenMap scope) { // Get the argument list: - TokenList list = scope.find("args")->asList(); + TokenList list = scope["args"].asList(); bool first = true; for (packToken item : list.list()) { @@ -117,7 +119,7 @@ packToken default_print(TokenMap scope) { packToken default_sum(TokenMap scope) { // Get the arguments: - TokenList list = scope.find("args")->asList(); + TokenList list = scope["args"].asList(); if (list.list().size() == 1 && list.list().front()->type == LIST) { list = list.list().front().asList(); @@ -131,20 +133,20 @@ packToken default_sum(TokenMap scope) { return sum; } -const char* value_arg[] = {"value"}; +const args_t value_arg = {"value"}; packToken default_eval(TokenMap scope) { - std::string code = scope.find("value")->asString(); + std::string code = scope["value"].asString(); // Evaluate it as a calculator expression: return calculator::calculate(code.c_str(), scope); } packToken default_float(TokenMap scope) { - packToken* tok = scope.find("value"); - if ((*tok)->type & NUM) return tok->asDouble(); + packToken tok = scope["value"]; + if (tok->type & NUM) return tok.asDouble(); // Convert it to double: char* rest; - const std::string& str = tok->asString(); + const std::string& str = tok.asString(); errno = 0; double ret = strtod(str.c_str(), &rest); @@ -157,12 +159,12 @@ packToken default_float(TokenMap scope) { } packToken default_int(TokenMap scope) { - packToken* tok = scope.find("value"); - if ((*tok)->type & NUM) return tok->asInt(); + packToken tok = scope["value"]; + if (tok->type & NUM) return tok.asInt(); // Convert it to double: char* rest; - const std::string& str = tok->asString(); + const std::string& str = tok.asString(); errno = 0; int64_t ret = strtol(str.c_str(), &rest, 10); @@ -176,14 +178,14 @@ packToken default_int(TokenMap scope) { packToken default_str(TokenMap scope) { // Return its string representation: - packToken* tok = scope.find("value"); - if ((*tok)->type == STR) return *tok; - return tok->str(); + packToken tok = scope["value"]; + if (tok->type == STR) return tok; + return tok.str(); } packToken default_type(TokenMap scope) { - packToken* tok = scope.find("value"); - switch ((*tok)->type) { + packToken tok = scope["value"]; + switch (tok->type) { case NONE: return "none"; case VAR: return "variable"; case REAL: return "float"; @@ -200,18 +202,18 @@ packToken default_type(TokenMap scope) { } packToken default_extend(TokenMap scope) { - packToken* tok = scope.find("value"); + packToken tok = scope["value"]; - if ((*tok)->type == MAP) { - return tok->asMap().getChild(); + if (tok->type == MAP) { + return tok.asMap().getChild(); } else { - throw std::runtime_error(tok->str() + " is not extensible!"); + throw std::runtime_error(tok.str() + " is not extensible!"); } } packToken default_instanceof(TokenMap scope) { - TokenMap _super = scope.find("value")->asMap(); - TokenMap* _this = scope.find("this")->asMap().parent(); + TokenMap _super = scope["value"].asMap(); + TokenMap* _this = scope["this"].asMap().parent(); TokenMap* parent = _this; while (parent) { @@ -225,43 +227,43 @@ packToken default_instanceof(TokenMap scope) { return false; } -const char* num_arg[] = {"number"}; +const args_t num_arg = {"number"}; packToken default_sqrt(TokenMap scope) { // Get a single argument: - double number = scope.find("number")->asDouble(); + double number = scope["number"].asDouble(); return sqrt(number); } packToken default_sin(TokenMap scope) { // Get a single argument: - double number = scope.find("number")->asDouble(); + double number = scope["number"].asDouble(); return sin(number); } packToken default_cos(TokenMap scope) { // Get a single argument: - double number = scope.find("number")->asDouble(); + double number = scope["number"].asDouble(); return cos(number); } packToken default_tan(TokenMap scope) { // Get a single argument: - double number = scope.find("number")->asDouble(); + double number = scope["number"].asDouble(); return tan(number); } packToken default_abs(TokenMap scope) { // Get a single argument: - double number = scope.find("number")->asDouble(); + double number = scope["number"].asDouble(); return std::abs(number); } -const char* pow_args[] = {"number", "exp"}; +const args_t pow_args = {"number", "exp"}; packToken default_pow(TokenMap scope) { // Get two arguments: - double number = scope.find("number")->asDouble(); - double exp = scope.find("exp")->asDouble(); + double number = scope["number"].asDouble(); + double exp = scope["exp"].asDouble(); return pow(number, exp); } @@ -269,12 +271,12 @@ packToken default_pow(TokenMap scope) { /* * * * * Type-specific default functions * * * * */ packToken string_len(TokenMap scope) { - std::string str = scope.find("this")->asString(); + std::string str = scope["this"].asString(); return static_cast(str.size()); } packToken string_lower(TokenMap scope) { - std::string str = scope.find("this")->asString(); + std::string str = scope["this"].asString(); std::string out; for (char c : str) { out.push_back(tolower(c)); @@ -283,7 +285,7 @@ packToken string_lower(TokenMap scope) { } packToken string_upper(TokenMap scope) { - std::string str = scope.find("this")->asString(); + std::string str = scope["this"].asString(); std::string out; for (char c : str) { out.push_back(toupper(c)); @@ -295,7 +297,7 @@ packToken string_upper(TokenMap scope) { packToken default_list(TokenMap scope) { // Get the arguments: - TokenList list = scope.find("args")->asList(); + TokenList list = scope["args"].asList(); // If the only argument is iterable: if (list.list().size() == 1 && list.list()[0]->type & IT) { @@ -319,12 +321,20 @@ packToken default_map(TokenMap scope) { return scope["kwargs"]; } +} // namespace builtin_functions + /* * * * * class CppFunction * * * * */ +CppFunction::CppFunction(packToken (*func)(TokenMap), const args_t args, + std::string name) + : func(func), _args(args) { + this->_name = name; +} + CppFunction::CppFunction(packToken (*func)(TokenMap), unsigned int nargs, const char** args, std::string name) : func(func) { - this->name = name; + this->_name = name; // Add all strings to args list: for (uint32_t i = 0; i < nargs; ++i) { this->_args.push_back(args[i]); @@ -334,35 +344,37 @@ CppFunction::CppFunction(packToken (*func)(TokenMap), unsigned int nargs, // Build a function with no named args: CppFunction::CppFunction(packToken (*func)(TokenMap), std::string name) : func(func) { - this->name = name; + this->_name = name; } /* * * * * CppFunction Initializer Constructor: * * * * */ -struct CppFunction::Startup { +namespace builtin_functions { + +struct Startup { Startup() { TokenMap& global = TokenMap::default_global(); global["print"] = CppFunction(&default_print, "print"); global["sum"] = CppFunction(&default_sum, "sum"); - global["sqrt"] = CppFunction(&default_sqrt, 1, num_arg, "sqrt"); - global["sin"] = CppFunction(&default_sin, 1, num_arg, "sin"); - global["cos"] = CppFunction(&default_cos, 1, num_arg, "cos"); - global["tan"] = CppFunction(&default_tan, 1, num_arg, "tan"); - global["abs"] = CppFunction(&default_abs, 1, num_arg, "abs"); - global["pow"] = CppFunction(&default_pow, 2, pow_args, "pow"); - global["float"] = CppFunction(&default_float, 1, value_arg, "float"); - global["str"] = CppFunction(&default_str, 1, value_arg, "str"); - global["eval"] = CppFunction(&default_eval, 1, value_arg, "eval"); - global["type"] = CppFunction(&default_type, 1, value_arg, "type"); - global["extend"] = CppFunction(&default_extend, 1, value_arg, "extend"); + global["sqrt"] = CppFunction(&default_sqrt, num_arg, "sqrt"); + global["sin"] = CppFunction(&default_sin, num_arg, "sin"); + global["cos"] = CppFunction(&default_cos, num_arg, "cos"); + global["tan"] = CppFunction(&default_tan, num_arg, "tan"); + global["abs"] = CppFunction(&default_abs, num_arg, "abs"); + global["pow"] = CppFunction(&default_pow, pow_args, "pow"); + global["float"] = CppFunction(&default_float, value_arg, "float"); + global["str"] = CppFunction(&default_str, value_arg, "str"); + global["eval"] = CppFunction(&default_eval, value_arg, "eval"); + global["type"] = CppFunction(&default_type, value_arg, "type"); + global["extend"] = CppFunction(&default_extend, value_arg, "extend"); // Default constructors: global["list"] = CppFunction(&default_list, "list"); global["map"] = CppFunction(&default_map, "map"); TokenMap& base_map = TokenMap::base_map(); - base_map["instanceof"] = CppFunction(&default_instanceof, 1, + base_map["instanceof"] = CppFunction(&default_instanceof, value_arg, "instanceof"); typeMap_t& type_map = calculator::type_attribute_map(); @@ -370,5 +382,6 @@ struct CppFunction::Startup { type_map[STR]["lower"] = CppFunction(&string_lower, "lower"); type_map[STR]["upper"] = CppFunction(&string_upper, "upper"); } -} CppFunction_startup; +} base_functions_startup; +} // namespace builtin_functions diff --git a/functions.h b/functions.h index 2bbea19..c41c164 100644 --- a/functions.h +++ b/functions.h @@ -4,41 +4,37 @@ #include #include +typedef std::list args_t; + class Function : public TokenBase { public: static packToken call(packToken _this, Function* func, TokenList* args, TokenMap scope); - public: - typedef std::list argsList; - - // Used only to initialize - // default functions on program startup. - std::string name; - Function() { this->type = FUNC; } virtual ~Function() {} - virtual const argsList args() const = 0; + public: + virtual const std::string name() const = 0; + virtual const args_t args() const = 0; virtual packToken exec(TokenMap scope) const = 0; virtual TokenBase* clone() const = 0; }; class CppFunction : public Function { - private: - // Used only to initialize - // builtin functions at startup. - struct Startup; - public: packToken (*func)(TokenMap); - argsList _args; + args_t _args; + std::string _name; + CppFunction(packToken (*func)(TokenMap), const args_t args, + std::string name = ""); CppFunction(packToken (*func)(TokenMap), unsigned int nargs, const char** args, std::string name = ""); CppFunction(packToken (*func)(TokenMap), std::string name = ""); - virtual const argsList args() const { return _args; } + virtual const std::string name() const { return _name; } + virtual const args_t args() const { return _args; } virtual packToken exec(TokenMap scope) const { return func(scope); } virtual TokenBase* clone() const { diff --git a/objects.cpp b/objects.cpp index f80b9a1..6e3cbf8 100644 --- a/objects.cpp +++ b/objects.cpp @@ -25,7 +25,7 @@ TokenMap TokenMap::empty = TokenMap(&default_global()); /* * * * * TokenMap built-in functions * * * * */ -const char* map_pop_args[] = {"key", "default"}; +const args_t map_pop_args = {"key", "default"}; packToken map_pop(TokenMap scope) { TokenMap map = scope["this"].asMap(); std::string key = scope["key"].asString(); @@ -53,7 +53,7 @@ packToken map_len(TokenMap scope) { /* * * * * TokenList built-in functions * * * * */ -const char* push_args[] = {"item"}; +const args_t push_args = {"item"}; packToken list_push(TokenMap scope) { packToken* list = scope.find("this"); packToken* token = scope.find("item"); @@ -64,7 +64,7 @@ packToken list_push(TokenMap scope) { return *list; } -const char* list_pop_args[] = {"pos"}; +const args_t list_pop_args = {"pos"}; packToken list_pop(TokenMap scope) { TokenList list = scope.find("this")->asList(); packToken* token = scope.find("pos"); @@ -99,12 +99,12 @@ packToken list_len(TokenMap scope) { struct TokenList::Startup { Startup() { TokenMap& base_list = calculator::type_attribute_map()[LIST]; - base_list["push"] = CppFunction(list_push, 1, push_args, "push"); - base_list["pop"] = CppFunction(list_pop, 1, list_pop_args, "pop"); + base_list["push"] = CppFunction(list_push, push_args, "push"); + base_list["pop"] = CppFunction(list_pop, list_pop_args, "pop"); base_list["len"] = CppFunction(list_len, "len"); TokenMap& base_map = TokenMap::base_map(); - base_map["pop"] = CppFunction(map_pop, 2, map_pop_args, "pop"); + base_map["pop"] = CppFunction(map_pop, map_pop_args, "pop"); base_map["len"] = CppFunction(map_len, "len"); } } list_startup; diff --git a/operations.cpp b/operations.cpp new file mode 100644 index 0000000..85652c1 --- /dev/null +++ b/operations.cpp @@ -0,0 +1,449 @@ + +#ifndef OPERATIONS_H_ +#define OPERATIONS_H_ + +#include +#include + +#include "./shunting-yard.h" +#include "./shunting-yard-exceptions.h" + +namespace builtin_operations { + +struct Comma : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(ANY_TYPE, ANY_TYPE); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + TokenBase* result; + if (b_left->type == TUPLE) { + Tuple* tuple = static_cast(b_left); + tuple->list().push_back(packToken(b_right)); + result = tuple; + } else { + result = new Tuple(b_left, b_right); + delete b_left; + delete b_right; + } + return result; + } +} Comma; + +struct Colon : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(ANY_TYPE, ANY_TYPE); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + TokenBase* result; + if (b_left->type == STUPLE) { + STuple* tuple = static_cast(b_left); + tuple->list().push_back(packToken(b_right)); + result = tuple; + } else { + result = new STuple(b_left, b_right); + delete b_left; + delete b_right; + } + return result; + } +} Colon; + + // If it is an assignment operation: +struct Equal : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(ANY_TYPE, ANY_TYPE); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + if (b_left->type == VAR || b_right->type == VAR) { + throw undefined_operation(op, b_left, b_right); + } + + packToken left(b_left); + packToken right(b_right); + + return new Token(left == right, INT); + } +} Equal; + +struct Different : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(ANY_TYPE, ANY_TYPE); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + if (b_left->type == VAR || b_right->type == VAR) { + throw undefined_operation(op, b_left, b_right); + } + + packToken left(b_left); + packToken right(b_right); + + return new Token(left != right, INT); + } +} Different; + +struct MapIndex : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(MAP, STR); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + TokenMap left = *static_cast(b_left); + std::string right = static_cast*>(b_right)->val; + + if (!op.compare("[]") || !op.compare(".")) { + packToken* p_value = left.find(right); + TokenBase* value; + + if (p_value) { + value = (*p_value)->clone(); + } else { + value = new TokenNone(); + } + + delete b_left; + delete b_right; + return new RefToken(right, value, left); + } else { + throw undefined_operation(op, b_left, b_right); + } + } +} MapIndex; + +// Resolve build-in operations for non-map types, e.g.: 'str'.len() +struct TypeSpecificFunction : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(ANY_TYPE, STR); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + if (b_left->type == MAP) return 0; + + TokenMap& left = calculator::type_attribute_map()[b_left->type]; + std::string right = static_cast*>(b_right)->val; + + packToken* attr = left.find(right); + if (attr) { + TokenBase* value = (*attr)->clone(); + packToken source = packToken(b_left); + delete b_right; + + // Note: If attr is a function, it will receive have + // scope["this"] == source, so it can make changes on this object. + // Or just read some information for example: its length. + return new RefToken(right, value, source); + } else { + throw undefined_operation(op, b_left, b_right); + } + } +} TypeSpecificFunction; + +struct NumeralOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(NUM, NUM); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + double left, right; + int64_t left_i, right_i; + TokenBase* result; + + // Extract integer and real values of the operators: + if (b_left->type == REAL) { + left = static_cast*>(b_left)->val; + left_i = static_cast(left); + } else { + left_i = static_cast*>(b_left)->val; + left = static_cast(left_i); + } + + if (b_right->type == REAL) { + right = static_cast*>(b_right)->val; + right_i = static_cast(right); + } else { + right_i = static_cast*>(b_right)->val; + right = static_cast(right_i); + } + + if (!op.compare("+")) { + result = new Token(left + right, REAL); + } else if (!op.compare("*")) { + result = new Token(left * right, REAL); + } else if (!op.compare("-")) { + result = new Token(left - right, REAL); + } else if (!op.compare("/")) { + result = new Token(left / right, REAL); + } else if (!op.compare("<<")) { + result = new Token(left_i << right_i, REAL); + } else if (!op.compare("**")) { + result = new Token(pow(left, right), REAL); + } else if (!op.compare(">>")) { + result = new Token(left_i >> right_i, REAL); + } else if (!op.compare("%")) { + result = new Token(left_i % right_i, REAL); + } else if (!op.compare("<")) { + result = new Token(left < right, REAL); + } else if (!op.compare(">")) { + result = new Token(left > right, REAL); + } else if (!op.compare("<=")) { + result = new Token(left <= right, REAL); + } else if (!op.compare(">=")) { + result = new Token(left >= right, REAL); + } else if (!op.compare("&&")) { + result = new Token(left_i && right_i, REAL); + } else if (!op.compare("||")) { + result = new Token(left_i || right_i, REAL); + } else { + throw undefined_operation(op, b_left, b_right); + } + + delete b_left; + delete b_right; + return result; + } +} NumeralOperation; + +struct FormatOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(STR, ANY_TYPE); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + std::string s_left = static_cast*>(b_left)->val; + const char* left = s_left.c_str(); + + Tuple right; + + if (b_right->type == TUPLE) { + right = *static_cast(b_right); + } else { + right = Tuple(b_right); + } + + std::string output; + for (const TokenBase* token : right.list()) { + // Find the next occurrence of "%s" + while (*left && (*left != '%' || left[1] != 's')) { + if (*left == '\\' && left[1] == '%') ++left; + output.push_back(*left); + ++left; + } + + if (*left == '\0') { + throw type_error("Not all arguments converted during string formatting"); + } else { + left += 2; + } + + // Replace it by the token string representation: + if (token->type == STR) { + // Avoid using packToken::str for strings + // or it will enclose it quotes `"str"` + output += static_cast*>(token)->val; + } else { + output += packToken::str(token); + } + } + + // Find the next occurrence of "%s" + while (*left && (*left != '%' || left[1] != 's')) { + if (*left == '\\' && left[1] == '%') ++left; + output.push_back(*left); + ++left; + } + + if (*left != '\0') { + throw type_error("Not enough arguments for format string"); + } else { + delete b_left; + delete b_right; + return new Token(output, STR); + } + } +} FormatOperation; + +struct StringOnStringOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(STR, STR); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + std::string left = static_cast*>(b_left)->val; + std::string right = static_cast*>(b_right)->val; + TokenBase* result; + + if (!op.compare("+")) { + result = new Token(left + right, STR); + } else if (!op.compare("==")) { + result = new Token(left.compare(right) == 0, INT); + } else if (!op.compare("!=")) { + result = new Token(left.compare(right) != 0, INT); + } else { + throw undefined_operation(op, b_left, b_right); + } + + delete b_left; + delete b_right; + return result; + } +} StringOnStringOperation; + +struct StringOnNumberOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(STR, NUM); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + std::string left = static_cast*>(b_left)->val; + double right; + TokenBase* result; + + if (b_right->type == REAL) { + right = static_cast*>(b_right)->val; + } else { + right = static_cast*>(b_right)->val; + } + + std::stringstream ss; + if (!op.compare("+")) { + ss << left << right; + result = new Token(ss.str(), STR); + } else if (!op.compare("[]")) { + int64_t index = right; + + if (index < 0) { + // Reverse index, i.e. list[-1] = list[list.size()-1] + index += left.size(); + } + + if (index < 0 || static_cast(index) >= left.size()) { + delete b_left; + throw std::domain_error("String index out of range!"); + } + + std::string value; + value.push_back(left[index]); + + result = new Token(value, STR); + } else { + throw undefined_operation(op, left, right); + } + + delete b_left; + delete b_right; + return result; + } +} StringOnNumberOperation; + +struct NumberOnStringOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(NUM, STR); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + double left; + std::string right = static_cast*>(b_right)->val; + + if (b_left->type == REAL) { + left = static_cast*>(b_left)->val; + } else { + left = static_cast*>(b_left)->val; + } + + std::stringstream ss; + if (!op.compare("+")) { + ss << left << right; + + delete b_left; + delete b_right; + return new Token(ss.str(), STR); + } else { + throw undefined_operation(op, left, right); + } + } +} NumberOnStringOperation; + +struct ListOnNumberOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(LIST, NUM); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + TokenList left = *static_cast(b_left); + int64_t right = static_cast*>(b_right)->val; + + if (b_right->type == REAL) { + right = static_cast*>(b_right)->val; + } else { + right = static_cast*>(b_right)->val; + } + + if (!op.compare("[]")) { + int64_t index = right; + + if (index < 0) { + // Reverse index, i.e. list[-1] = list[list.size()-1] + index += left.list().size(); + } + + if (index < 0 || static_cast(index) >= left.list().size()) { + throw std::domain_error("List index out of range!"); + } + + TokenBase* value = left.list()[index]->clone(); + + delete b_right; + return new RefToken(index, value, packToken(b_left)); + } else { + throw undefined_operation(op, b_left, b_right); + } + } +} ListOnNumberOperation; + +struct ListOnListOperation : public BaseOperation { + const opID_t getMask() { return Operation::build_mask(LIST, LIST); } + + TokenBase* exec(TokenBase* b_left, const std::string& op, TokenBase* b_right) { + TokenList left = *static_cast(b_left); + TokenList right = *static_cast(b_right); + + if (!op.compare("+")) { + // Deep copy the first list: + TokenList result; + result.list() = left.list(); + + // Insert items from the right list into the left: + for (packToken& p : right.list()) { + result.list().push_back(p); + } + + delete b_left; + delete b_right; + return new TokenList(result); + } else { + throw undefined_operation(op, left, right); + } + } +} ListOnListOperation; + +struct Startup { + Startup() { + // Create the operator precedence map based on C++ default + // precedence order as described on cppreference website: + // http://en.cppreference.com/w/cpp/language/operator_precedence + OppMap_t& opp = calculator::default_opPrecedence(); + opp["[]"] = 2; opp["()"] = 2; opp["."] = 2; + opp["**"] = 3; + opp["*"] = 5; opp["/"] = 5; opp["%"] = 5; + opp["+"] = 6; opp["-"] = 6; + opp["<<"] = 7; opp[">>"] = 7; + opp["<"] = 8; opp["<="] = 8; opp[">="] = 8; opp[">"] = 8; + opp["=="] = 9; opp["!="] = 9; + opp["&&"] = 13; + opp["||"] = 14; + opp["="] = 15; opp[":"] = 15; + opp[","] = 16; + + // Link operations to respective operators: + opMap_t& opMap = calculator::default_opMap(); + opMap[","].push_back(&Comma); + opMap[":"].push_back(&Colon); + opMap["=="].push_back(&Equal); + opMap["!="].push_back(&Different); + opMap["[]"].push_back(&MapIndex); + opMap["."].push_back(&TypeSpecificFunction); + opMap["."].push_back(&MapIndex); + opMap["%"].push_back(&FormatOperation); + + // Note: The order is important: + opMap[ANY_OP].push_back(&NumeralOperation); + opMap[ANY_OP].push_back(&StringOnStringOperation); + opMap[ANY_OP].push_back(&StringOnNumberOperation); + opMap[ANY_OP].push_back(&NumberOnStringOperation); + opMap[ANY_OP].push_back(&ListOnNumberOperation); + opMap[ANY_OP].push_back(&ListOnListOperation); + } +} StartUp; + +} // namespace builtin_operations + +#endif // OPERATIONS_H_ diff --git a/packToken.cpp b/packToken.cpp index 0f91901..42bd3e8 100644 --- a/packToken.cpp +++ b/packToken.cpp @@ -187,7 +187,7 @@ std::string packToken::str(const TokenBase* base) { return "\"" + static_cast*>(base)->val + "\""; case FUNC: func = static_cast(base); - if (func->name.size()) return "[Function: " + func->name + "]"; + if (func->name().size()) return "[Function: " + func->name() + "]"; if (name.size()) return "[Function: " + name + "]"; return "[Function]"; case TUPLE: diff --git a/shunting-yard-exceptions.h b/shunting-yard-exceptions.h index bb040cb..7bdca88 100644 --- a/shunting-yard-exceptions.h +++ b/shunting-yard-exceptions.h @@ -31,6 +31,8 @@ struct type_error : public msg_exception { }; struct undefined_operation : public msg_exception { + undefined_operation(const std::string& op, const TokenBase* left, const TokenBase* right) + : undefined_operation(op, packToken(left->clone()), packToken(right->clone())) {} undefined_operation(const std::string& op, const packToken& left, const packToken& right) : msg_exception("Unexpected operation with operator '" + op + "' and operands: " + left.str() + " and " + right.str() + ".") {} }; diff --git a/shunting-yard.cpp b/shunting-yard.cpp index 75cece3..f1b2ab3 100644 --- a/shunting-yard.cpp +++ b/shunting-yard.cpp @@ -1,8 +1,6 @@ #include "./shunting-yard.h" #include "./shunting-yard-exceptions.h" -#include - #include #include #include @@ -13,40 +11,65 @@ #include // For std::pair #include // For strchr() -OppMap_t calculator::buildOpPrecedence() { - OppMap_t opp; +/* * * * * BaseOperation class: * * * * */ - // Create the operator precedence map based on C++ default - // precedence order as described on cppreference website: - // http://en.cppreference.com/w/cpp/language/operator_precedence - opp["[]"] = 2; opp["()"] = 2; opp["."] = 2; - opp["**"] = 3; - opp["*"] = 5; opp["/"] = 5; opp["%"] = 5; - opp["+"] = 6; opp["-"] = 6; - opp["<<"] = 7; opp[">>"] = 7; - opp["<"] = 8; opp["<="] = 8; opp[">="] = 8; opp[">"] = 8; - opp["=="] = 9; opp["!="] = 9; - opp["&&"] = 13; - opp["||"] = 14; - opp["="] = 15; opp[":"] = 15; - opp[","] = 16; - opp["("] = 17; opp["["] = 17; +// Convert a type into an unique mask for bit wise operations: +const uint32_t BaseOperation::mask(tokType_t type) { + if (type == ANY_TYPE) { + return 0xFFFF; + } else { + return ((type & 0xE0) << 24) | (1 << (type & 0x1F)); + } +} +// Build a mask for each pair of operands +const opID_t BaseOperation::build_mask(tokType_t left, tokType_t right) { + opID_t result = mask(left); + return (result << 32) | mask(right); +} + +/* * * * * Operation Utilities: * * * * */ + +bool match_op_id(opID_t id, opID_t mask) { + uint64_t result = id & mask; + uint32_t* val = reinterpret_cast(&result); + if (val[0] && val[1]) return true; + return false; +} + +#define EXEC_OPERATION(result, opID, opMap, OP_MASK)\ + for (BaseOperation* operation : opMap[OP_MASK]) {\ + if (match_op_id(opID, operation->getMask())) {\ + result = operation->exec(b_left, op, b_right);\ + if (result) break;\ + }\ + }\ + +/* * * * * Static containers: * * * * */ + +// Builds the opPrecedence map only once: +OppMap_t& calculator::default_opPrecedence() { + static OppMap_t opp; return opp; } -// Builds the opPrecedence map only once: -OppMap_t calculator::_opPrecedence = calculator::buildOpPrecedence(); typeMap_t& calculator::type_attribute_map() { static typeMap_t type_map; return type_map; } +opMap_t& calculator::default_opMap() { + static opMap_t opMap; + return opMap; +} + // Literal Tokens: True, False and None: packToken trueToken = packToken(1); packToken falseToken = packToken(0); packToken noneToken = TokenNone(); +/* * * * * Calculator Class: * * * * */ + // Check for unary operators and "convert" them to binary: bool calculator::handle_unary(const std::string& op, TokenQueue_t* rpnQueue, bool lastTokenWasOp) { @@ -72,7 +95,7 @@ void calculator::handle_op(const std::string& op, // Check if operator exists: if (opPrecedence.find(op) == opPrecedence.end()) { cleanRPN(rpnQueue); - throw std::domain_error("Unknown operator: `" + op + "`!"); + throw std::domain_error("Undefined operator: `" + op + "`!"); } float cur_opp = opPrecedence[op]; @@ -266,7 +289,7 @@ TokenQueue_t calculator::toRPN(const char* expr, lastTokenWasOp = false; } else { // Otherwise, the variable is an operator or paranthesis. - uint8_t lastType; + tokType_t lastType; char lastOp; // Check for syntax errors (excess of operators i.e. 10 + + -1): @@ -385,9 +408,8 @@ packToken calculator::calculate(const char* expr, TokenMap vars, const char* delim, const char** rest) { // Convert to RPN with Dijkstra's Shunting-yard algorithm. RAII_TokenQueue_t rpn = calculator::toRPN(expr, vars, delim, rest); - TokenBase* ret; - ret = calculator::calculate(rpn, vars); + TokenBase* ret = calculator::calculate(rpn, vars); return packToken(resolve_reference(ret)); } @@ -399,7 +421,8 @@ void cleanStack(std::stack st) { } } -TokenBase* calculator::calculate(TokenQueue_t _rpn, TokenMap vars) { +TokenBase* calculator::calculate(TokenQueue_t _rpn, TokenMap vars, + opMap_t opMap) { RAII_TokenQueue_t rpn; // Deep copy the token list, so everything can be @@ -421,6 +444,8 @@ TokenBase* calculator::calculate(TokenQueue_t _rpn, TokenMap vars) { std::string op = static_cast*>(base)->val; delete base; + /* * * * * Resolve operands Values and References: * * * * */ + if (evaluation.size() < 2) { cleanStack(evaluation); throw std::domain_error("Invalid equation."); @@ -449,29 +474,9 @@ TokenBase* calculator::calculate(TokenQueue_t _rpn, TokenMap vars) { r_left = static_cast*>(b_left)->val; } - // If it is a tuple operator: - if (!op.compare(",")) { - if (b_left->type == TUPLE) { - Tuple* tuple = static_cast(b_left); - tuple->list().push_back(packToken(b_right)); - evaluation.push(tuple); - } else { - evaluation.push(new Tuple(b_left, b_right)); - delete b_left; - delete b_right; - } - } else if (!op.compare(":")) { - if (b_left->type == STUPLE) { - STuple* tuple = static_cast(b_left); - tuple->list().push_back(packToken(b_right)); - evaluation.push(tuple); - } else { - evaluation.push(new STuple(b_left, b_right)); - delete b_left; - delete b_right; - } - // If it is an assignment operation: - } else if (!op.compare("=")) { + /* * * * * Resolve Asign Operation * * * * */ + + if (!op.compare("=")) { delete b_left; // If the left operand has a variable name: @@ -517,308 +522,6 @@ TokenBase* calculator::calculate(TokenQueue_t _rpn, TokenMap vars) { cleanStack(evaluation); throw undefined_operation(op, r_left, p_right); } - } else if (!op.compare("==")) { - packToken left(b_left); - packToken right(b_right); - - if (left->type == VAR || right->type == VAR) { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - - evaluation.push(new Token(left == right, INT)); - } else if (!op.compare("!=")) { - packToken left(b_left); - packToken right(b_right); - - if (left->type == VAR || right->type == VAR) { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - - evaluation.push(new Token(left != right, INT)); - } else if (b_left->type == MAP && b_right->type == STR) { - TokenMap left = *static_cast(b_left); - std::string right = static_cast*>(b_right)->val; - delete b_left; - delete b_right; - - if (!op.compare("[]") || !op.compare(".")) { - packToken* p_value = left.find(right); - TokenBase* value; - - if (p_value) { - value = (*p_value)->clone(); - } else { - value = new TokenNone(); - } - - evaluation.push(new RefToken(right, value, left)); - } else { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - // Resolve build-in operations for non-map types, e.g.: 'str'.len() - } else if (!op.compare(".") && b_right->type == STR) { - TokenMap& left = calculator::type_attribute_map()[b_left->type]; - std::string right = static_cast*>(b_right)->val; - delete b_right; - - packToken* attr = left.find(right); - if (attr) { - TokenBase* value = (*attr)->clone(); - packToken source = packToken(b_left); - - // Note: If attr is a function, it will receive have - // scope["this"] == source, so it can make changes on this object. - // Or just read some information for example: its length. - evaluation.push(new RefToken(right, value, source)); - } else { - packToken p_left = packToken(b_left->clone()); - delete b_left; - cleanStack(evaluation); - throw undefined_operation(op, p_left, right); - } - } else if (b_left->type & NUM && b_right->type & NUM) { - double left, right; - int64_t left_i, right_i; - - // Extract integer and real values of the operators: - if (b_left->type == NUM) { - left = static_cast*>(b_left)->val; - left_i = static_cast(left); - } else { - left_i = static_cast*>(b_left)->val; - left = static_cast(left_i); - } - - if (b_right->type == NUM) { - right = static_cast*>(b_right)->val; - right_i = static_cast(right); - } else { - right_i = static_cast*>(b_right)->val; - right = static_cast(right_i); - } - - delete b_left; - delete b_right; - - if (!op.compare("+")) { - evaluation.push(new Token(left + right, NUM)); - } else if (!op.compare("*")) { - evaluation.push(new Token(left * right, NUM)); - } else if (!op.compare("-")) { - evaluation.push(new Token(left - right, NUM)); - } else if (!op.compare("/")) { - evaluation.push(new Token(left / right, NUM)); - } else if (!op.compare("<<")) { - evaluation.push(new Token(left_i << right_i, NUM)); - } else if (!op.compare("**")) { - evaluation.push(new Token(pow(left, right), NUM)); - } else if (!op.compare(">>")) { - evaluation.push(new Token(left_i >> right_i, NUM)); - } else if (!op.compare("%")) { - evaluation.push(new Token(left_i % right_i, NUM)); - } else if (!op.compare("<")) { - evaluation.push(new Token(left < right, NUM)); - } else if (!op.compare(">")) { - evaluation.push(new Token(left > right, NUM)); - } else if (!op.compare("<=")) { - evaluation.push(new Token(left <= right, NUM)); - } else if (!op.compare(">=")) { - evaluation.push(new Token(left >= right, NUM)); - } else if (!op.compare("&&")) { - evaluation.push(new Token(left_i && right_i, NUM)); - } else if (!op.compare("||")) { - evaluation.push(new Token(left_i || right_i, NUM)); - } else { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - } else if (b_left->type == STR && !op.compare("%")) { - std::string s_left = static_cast*>(b_left)->val; - const char* left = s_left.c_str(); - delete b_left; - - Tuple right; - - if (b_right->type == TUPLE) { - right = *static_cast(b_right); - } else { - right = Tuple(b_right); - } - delete b_right; - - std::string output; - for (const TokenBase* token : right.list()) { - // Find the next occurrence of "%s" - while (*left && (*left != '%' || left[1] != 's')) { - if (*left == '\\' && left[1] == '%') ++left; - output.push_back(*left); - ++left; - } - - if (*left == '\0') { - cleanStack(evaluation); - throw type_error("Not all arguments converted during string formatting"); - } else { - left += 2; - } - - // Replace it by the token string representation: - if (token->type == STR) { - // Avoid using packToken::str for strings - // or it will enclose it quotes `"str"` - output += static_cast*>(token)->val; - } else { - output += packToken::str(token); - } - } - - // Find the next occurrence of "%s" - while (*left && (*left != '%' || left[1] != 's')) { - if (*left == '\\' && left[1] == '%') ++left; - output.push_back(*left); - ++left; - } - - if (*left != '\0') { - cleanStack(evaluation); - throw type_error("Not enough arguments for format string"); - } else { - evaluation.push(new Token(output, STR)); - } - } else if (b_left->type == STR && b_right->type == STR) { - std::string left = static_cast*>(b_left)->val; - std::string right = static_cast*>(b_right)->val; - delete b_left; - delete b_right; - - if (!op.compare("+")) { - evaluation.push(new Token(left + right, STR)); - } else if (!op.compare("==")) { - evaluation.push(new Token(left.compare(right) == 0, INT)); - } else if (!op.compare("!=")) { - evaluation.push(new Token(left.compare(right) != 0, INT)); - } else { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - } else if (b_left->type == STR && b_right->type & NUM) { - std::string left = static_cast*>(b_left)->val; - double right; - - if (b_right->type == REAL) { - right = static_cast*>(b_right)->val; - } else { - right = static_cast*>(b_right)->val; - } - - delete b_left; - delete b_right; - - std::stringstream ss; - if (!op.compare("+")) { - ss << left << right; - evaluation.push(new Token(ss.str(), STR)); - } else if (!op.compare("[]")) { - int64_t index = right; - - if (index < 0) { - // Reverse index, i.e. list[-1] = list[list.size()-1] - index += left.size(); - } - - if (index < 0 || static_cast(index) >= left.size()) { - delete b_left; - cleanStack(evaluation); - throw std::domain_error("String index out of range!"); - } - - std::string value; - value.push_back(left[index]); - - evaluation.push(new Token(value, STR)); - } else { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - } else if (b_left->type & NUM && b_right->type == STR) { - double left; - std::string right = static_cast*>(b_right)->val; - - if (b_left->type == REAL) { - left = static_cast*>(b_left)->val; - } else { - left = static_cast*>(b_left)->val; - } - - delete b_left; - delete b_right; - - std::stringstream ss; - if (!op.compare("+")) { - ss << left << right; - evaluation.push(new Token(ss.str(), STR)); - } else { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - } else if (b_left->type == LIST && b_right->type & NUM) { - TokenList left = *static_cast(b_left); - int64_t right = static_cast*>(b_right)->val; - - if (b_right->type == REAL) { - right = static_cast*>(b_right)->val; - } else { - right = static_cast*>(b_right)->val; - } - - delete b_right; - - if (!op.compare("[]")) { - int64_t index = right; - - if (index < 0) { - // Reverse index, i.e. list[-1] = list[list.size()-1] - index += left.list().size(); - } - - if (index < 0 || static_cast(index) >= left.list().size()) { - delete b_left; - cleanStack(evaluation); - throw std::domain_error("List index out of range!"); - } - - TokenBase* value = left.list()[index]->clone(); - - evaluation.push(new RefToken(index, value, packToken(b_left))); - } else { - delete b_left; - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } - } else if (b_left->type == LIST && b_right->type == LIST) { - TokenList left = *static_cast(b_left); - TokenList right = *static_cast(b_right); - delete b_left; - delete b_right; - - if (!op.compare("+")) { - // Deep copy the first list: - TokenList result; - result.list() = left.list(); - - // Insert items from the right list into the left: - for (packToken& p : right.list()) { - result.list().push_back(p); - } - - evaluation.push(new TokenList(result)); - } else { - cleanStack(evaluation); - throw undefined_operation(op, left, right); - } } else if (b_left->type == FUNC) { Function* f_left = static_cast(b_left); @@ -861,13 +564,33 @@ TokenBase* calculator::calculate(TokenQueue_t _rpn, TokenMap vars) { throw undefined_operation(op, p_left, p_right); } } else { - packToken p_left(b_left->clone()); - packToken p_right(b_right->clone()); - delete b_left; - delete b_right; + opID_t opID = BaseOperation::build_mask(b_left->type, b_right->type); + TokenBase* result = 0; - cleanStack(evaluation); - throw undefined_operation(op, p_left, p_right); + try { + // Resolve the operation: + EXEC_OPERATION(result, opID, opMap, op); + if (!result) { + EXEC_OPERATION(result, opID, opMap, ANY_OP); + } + } catch (...) { + delete b_left; + delete b_right; + cleanStack(evaluation); + throw; + } + + if (result) { + evaluation.push(result); + } else { + packToken p_left(b_left->clone()); + packToken p_right(b_right->clone()); + delete b_left; + delete b_right; + + cleanStack(evaluation); + throw undefined_operation(op, p_left, p_right); + } } } else if (base->type == VAR) { // Variable packToken* value = NULL; @@ -918,22 +641,21 @@ calculator::calculator(const calculator& calc) { // Work as a sub-parser: // - Stops at delim or '\0' // - Returns the rest of the string as char* rest -calculator::calculator(const char* expr, TokenMap vars, - const char* delim, const char** rest, OppMap_t opPrecedence) { - compile(expr, vars, delim, rest, opPrecedence); +calculator::calculator(const char* expr, TokenMap vars, const char* delim, + const char** rest, const OppMap_t& opp) { + this->RPN = calculator::toRPN(expr, vars, delim, rest, opp); } -void calculator::compile(const char* expr, - TokenMap vars, const char* delim, - const char** rest, OppMap_t opPrecedence) { +void calculator::compile(const char* expr, TokenMap vars, const char* delim, + const char** rest) { // Make sure it is empty: cleanRPN(&this->RPN); - this->RPN = calculator::toRPN(expr, vars, delim, rest, opPrecedence); + this->RPN = calculator::toRPN(expr, vars, delim, rest, opPrecedence()); } packToken calculator::eval(TokenMap vars, bool keep_refs) const { - TokenBase* value = calculate(this->RPN, vars); + TokenBase* value = calculate(this->RPN, vars, opMap()); packToken p = packToken(value->clone()); if (keep_refs) { return packToken(value); diff --git a/shunting-yard.h b/shunting-yard.h index f2e015a..d26f211 100644 --- a/shunting-yard.h +++ b/shunting-yard.h @@ -6,30 +6,43 @@ #include #include #include +#include +/* + * About tokType enum: + * + * The 3 left most bits (0x80, 0x40 and 0x20) of the Token Type + * are reserved for denoting Numerals, Iterators and References. + * If you want to define your own type please mind this bits. + */ +typedef uint8_t tokType_t; +typedef uint64_t opID_t; enum tokType { // Base types: + // Note: The mask system accepts at most 29 (32-3) different base types. NONE, OP, VAR, STR, FUNC, // Numerals: - NUM = 0x8, // Everything with the bit 0x8 set is a number. - REAL = 0x8, // == 0x8 => Real numbers. - INT = 0x9, // == 0x8 + 0x1 => Integers are numbers. + NUM = 0x20, // Everything with the bit 0x20 set is a number. + REAL = 0x21, // == 0x20 => Real numbers. + INT = 0x22, // == 0x20 + 0x1 => Integers are numbers. // Complex types: - IT = 0x20, // Everything with the bit 0x20 set is an iterator. - LIST = 0x21, // == 0x20 + 0x01 => Lists are iterators. - TUPLE = 0x22, // == 0x20 + 0x01 => Tuples are iterators. - STUPLE = 0x23, // == 0x20 + 0x02 => ArgTuples are iterators. - MAP = 0x60, // == 0x20 + 0x40 => Maps are Iterators - // Everything with the bit 0x40 set is a MAP. - REF = 0x80 + IT = 0x40, // Everything with the bit 0x20 set is an iterator. + LIST = 0x41, // == 0x20 + 0x01 => Lists are iterators. + TUPLE = 0x42, // == 0x20 + 0x02 => Tuples are iterators. + STUPLE = 0x43, // == 0x20 + 0x03 => ArgTuples are iterators. + MAP = 0x44, // == 0x20 + 0x04 => Maps are Iterators + + REF = 0x80, + + ANY_TYPE = 0xFF }; -typedef unsigned char uint8_t; +#define ANY_OP "" struct TokenBase { - uint8_t type; + tokType_t type; virtual ~TokenBase() {} virtual TokenBase* clone() const = 0; }; @@ -37,7 +50,7 @@ struct TokenBase { template class Token : public TokenBase { public: T val; - Token(T t, uint8_t type) : val(t) { this->type = type; } + Token(T t, tokType_t type) : val(t) { this->type = type; } virtual TokenBase* clone() const { return new Token(static_cast(*this)); } @@ -52,7 +65,14 @@ struct TokenNone : public TokenBase { class packToken; typedef std::queue TokenQueue_t; -typedef std::map OppMap_t; +struct OppMap_t : public std::map { + OppMap_t() { + // These operations are hard-coded on the system, + // thus they should always be defined. + (*this)["[]"] = -1; (*this)["()"] = -1; + (*this)["["] = 0xFFFFFF; (*this)["("] = 0xFFFFFF; + } +}; class TokenMap; class TokenList; @@ -82,12 +102,43 @@ struct RefToken : public TokenBase { } }; -typedef std::map typeMap_t; +struct BaseOperation { + static inline const uint32_t mask(tokType_t type); + static const opID_t build_mask(tokType_t left, tokType_t right); + virtual const opID_t getMask() = 0; + + // This exec is designed for use of advanced users: + virtual TokenBase* exec(TokenBase* left, const std::string& op, + TokenBase* right) = 0; +}; + +struct Operation : public BaseOperation { + virtual TokenBase* exec(TokenBase* left, const std::string& op, + TokenBase* right) { + packToken result = exec(packToken(left->clone()), + op, packToken(right->clone())); + + if (result) { + delete left; + delete right; + return result->clone(); + } else { + return 0; + } + } + + // This exec is designed for use of non advanced users: + virtual packToken exec(packToken left, std::string op, packToken right) = 0; +}; + +typedef std::map typeMap_t; +typedef std::vector opList_t; +typedef std::map opMap_t; class calculator { - private: - static OppMap_t _opPrecedence; - static OppMap_t buildOpPrecedence(); + public: + static OppMap_t& default_opPrecedence(); + static opMap_t& default_opMap(); public: static typeMap_t& type_attribute_map(); @@ -97,11 +148,12 @@ class calculator { const char* delim = 0, const char** rest = 0); private: - static TokenBase* calculate(TokenQueue_t RPN, TokenMap vars); + static TokenBase* calculate(TokenQueue_t RPN, TokenMap vars, + opMap_t opMap = default_opMap()); static void cleanRPN(TokenQueue_t* rpn); static TokenQueue_t toRPN(const char* expr, TokenMap vars, const char* delim = 0, const char** rest = 0, - OppMap_t opPrecedence = _opPrecedence); + OppMap_t opPrecedence = default_opPrecedence()); static bool handle_unary(const std::string& op, TokenQueue_t* rpnQueue, bool lastTokenWasOp); @@ -113,19 +165,22 @@ class calculator { // Used to dealloc a TokenQueue_t safely. struct RAII_TokenQueue_t; + protected: + virtual const opMap_t opMap() const { return default_opMap(); } + virtual const OppMap_t opPrecedence() const { return default_opPrecedence(); } + private: TokenQueue_t RPN; public: - ~calculator(); + virtual ~calculator(); calculator() { this->RPN.push(new TokenNone()); } calculator(const calculator& calc); calculator(const char* expr, TokenMap vars = &TokenMap::empty, const char* delim = 0, const char** rest = 0, - OppMap_t opPrecedence = _opPrecedence); + const OppMap_t& opPrecedence = default_opPrecedence()); void compile(const char* expr, TokenMap vars = &TokenMap::empty, - const char* delim = 0, const char** rest = 0, - OppMap_t opPrecedence = _opPrecedence); + const char* delim = 0, const char** rest = 0); packToken eval(TokenMap vars = &TokenMap::empty, bool keep_refs = false) const; // Serialization: diff --git a/test-shunting-yard.cpp b/test-shunting-yard.cpp index 6710a16..8c3eaf6 100644 --- a/test-shunting-yard.cpp +++ b/test-shunting-yard.cpp @@ -28,7 +28,7 @@ void PREPARE_ENVIRONMENT() { emap["b"] = 20; } -TEST_CASE("Static calculate::calculate()") { +TEST_CASE("Static calculate::calculate()", "[calculate]") { REQUIRE(calculator::calculate("-pi + 1", vars).asDouble() == Approx(-2.14)); REQUIRE(calculator::calculate("-pi + 1 * b1", vars).asDouble() == Approx(-3.14)); REQUIRE(calculator::calculate("(20+10)*3/2-3", vars).asDouble() == Approx(42.0)); @@ -551,6 +551,77 @@ TEST_CASE("Parsing as slave parser") { REQUIRE_THROWS(calculator::calculate(error_test, vars, "\n;", &code)); } +TEST_CASE("operation_id() function", "[op_id]") { + #define opID(t1, t2) Operation::build_mask(t1, t2) + REQUIRE((opID(NONE, NONE)) == 0x0000000100000001); + REQUIRE((opID(FUNC, FUNC)) == 0x0000001000000010); + REQUIRE((opID(FUNC, ANY_TYPE)) == 0x000000100000FFFF); + REQUIRE((opID(FUNC, ANY_TYPE)) == 0x000000100000FFFF); +} + +/* * * * * Declaring adhoc operations * * * * */ + +struct myCalc : public calculator { + static opMap_t& my_opMap() { + static opMap_t opMap; + return opMap; + } + + static OppMap_t& my_OppMap() { + static OppMap_t opp; + return opp; + } + + const opMap_t opMap() const { return my_opMap(); } + const OppMap_t opPrecedence() const { return my_OppMap(); } + + using calculator::calculator; +}; + +struct op1 : public BaseOperation { + const opID_t getMask() { return build_mask(STR, TUPLE); } + TokenBase* exec(TokenBase* left, const std::string& op, + TokenBase* right) { + return calculator::default_opMap()["%"][0]->exec(left, op, right); + } +} op1; + +struct op2 : public Operation { + const opID_t getMask() { return build_mask(ANY_TYPE, ANY_TYPE); } + packToken exec(packToken left, std::string op, packToken right) { + return packToken(calculator::default_opMap()[","][0]->exec(left->clone(), op, right->clone())); + } +} op2; + +struct myCalcStartup { + myCalcStartup() { + OppMap_t& opp = myCalc::my_OppMap(); + opp["."] = 1; + opp["+"] = 2; + + opMap_t& opMap = myCalc::my_opMap(); + opMap["+"].push_back(&op1); + opMap["."].push_back(&op2); + } +} myCalcStartup; + +/* * * * * Testing adhoc operations * * * * */ + +TEST_CASE("Adhoc operations", "[operation]") { + myCalc c1, c2; + const char* exp = "'Lets create %s operators%s' + ('adhoc' . '!' )"; + REQUIRE_NOTHROW(c1.compile(exp)); + REQUIRE_NOTHROW(c2 = myCalc(exp, vars, 0, 0, myCalc::my_OppMap())); + + REQUIRE(c1.eval() == "Lets create adhoc operators!"); + REQUIRE(c2.eval() == "Lets create adhoc operators!"); + + // Testing opPrecedence: + exp = "'Lets create %s operators%s' + 'adhoc' . '!'"; + REQUIRE_NOTHROW(c1.compile(exp)); + REQUIRE(c1.eval() == "Lets create adhoc operators!"); +} + TEST_CASE("Resource management") { calculator C1, C2("1 + 1");