mirror of
https://github.com/allankoechke/cparse.git
synced 2026-12-01 17:15:15 +00:00
Some refactoring and bug fixing (#22)
* Remove redundant calculator::compile(const char*, OppMap_t) * Add support for calculator to work as a slave parser As a slave parser I mean it will parse until a specified delimiter and report back the pointer of where it has stopped. This way another class can the calculator constructor to parse or evaluate a sequence of expressions. * Add static calculator::str() implementation for help debug * Add an arguments validation check at calculator::toRPN() * Minor refactor: Move calculator::scope_empty to Scope::empty * Set Function string argument to `const char*` * Update files to satisfy Travis CI rules * Move Function::default_functions to Scope::default_global The TokenMap_t Function::default_functions was used as base map for all Scope instances, and represented the global scope. It is more coherent to keep it with the name default_global and defined as a static member of Scope class. Now any other class that needs to add something to the global scope can just use Scope::default_global. * Make packToken::str(TokenBase*) accept const argument * Fix memory leak problem on Reference Token management * Prevent bug called "static initialization order fiasco" This bug is better explained here: - https://isocpp.org/wiki/faq/ctors#static-init-order Short version: It is caused when the compiler initializes static objects in a random order. And one of these objects depend on the initialization of another one. In our project the singleton class Function::Startup depends on the TokenMap_t Scope::default_global. It might cause no bug if we are lucky with the init order the compiler chooses. But might cause big problems otherwise. This commit fix this problem so we don't need to depend on lucky. * Optimize calculator::toRPN loop * Update README.md features section * Update quote escaping for string literals Now the user can type \\n and it will be converted to \n. It also works for \\t, but nothing happens with other characters like: \\f or \\o Also add more tests for the string section. * Fix bug on string escaping * Add RAII_TokenQueue_t class to facilitate rpn management Since C++ does not allow a finally block it is hard to be sure something will be dealloc'd even when exceptions are thrown. The function calculator::calculate(char* expr, ...) needed to have a catch for each possible exception type thrown by its internal function calls (where a single finally block would have done the job) The only alternative encouraged by C++ is the RAII idiom so the RAII_TokenQueue_t was built. This new class should be used with care, but it has reduced the number of explicit calls to cleanRPN which is good. * Add valgrind check (make check) to Makefile * Fix () operator so m.a(arg) works * Fix `print()` so that it will call `print(None)` * Add string representations to types FUNC and TUPLE
This commit is contained in:
committed by
Brandon Amos
parent
c2ad59c69d
commit
e4ebe719cd
2
Makefile
2
Makefile
@@ -13,4 +13,6 @@ again: clean all
|
||||
|
||||
test: $(EXE); ./$(EXE)
|
||||
|
||||
check: $(EXE); valgrind --leak-check=full ./$(EXE)
|
||||
|
||||
clean: ; rm -f $(EXE) $(OBJ)
|
||||
|
||||
@@ -59,6 +59,8 @@ int main() {
|
||||
+ Binary operators. +, -, /, *, %, <<, >>, ^
|
||||
+ Boolean operators. <, >, <=, >=, ==, !=, &&, ||
|
||||
+ Map of variable names.
|
||||
+ Functions. sin, cos, tan, abs, print
|
||||
+ Easy to add new operators, functions and even new types.
|
||||
|
||||
# Adding a binary operator.
|
||||
To add a binary operator,
|
||||
|
||||
@@ -2,22 +2,27 @@
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
#include "./shunting-yard.h"
|
||||
|
||||
TokenMap_t Function::default_functions = Function::initialize_functions();
|
||||
#include "./shunting-yard.h"
|
||||
#include "./functions.h"
|
||||
|
||||
/* * * * * Built-in Functions: * * * * */
|
||||
|
||||
std::string text_arg[] = {"text"};
|
||||
const char* text_arg[] = {"text"};
|
||||
packToken default_print(const Scope* scope) {
|
||||
// Get a single argument:
|
||||
std::string text = scope->find("text")->asString();
|
||||
printf("%s\n", text.c_str());
|
||||
packToken* p = scope->find("text");
|
||||
if ((*p)->type == STR) {
|
||||
std::string text = p->asString();
|
||||
printf("%s\n", text.c_str());
|
||||
} else {
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
return packToken::None;
|
||||
}
|
||||
|
||||
std::string num_arg[] = {"number"};
|
||||
const char* num_arg[] = {"number"};
|
||||
packToken default_sqrt(const Scope* scope) {
|
||||
// Get a single argument:
|
||||
double number = scope->find("number")->asDouble();
|
||||
@@ -50,7 +55,7 @@ packToken default_abs(const Scope* scope) {
|
||||
}
|
||||
|
||||
|
||||
std::string pow_args[] = {"number", "exp"};
|
||||
const char* pow_args[] = {"number", "exp"};
|
||||
packToken default_pow(const Scope* scope) {
|
||||
// Get two arguments:
|
||||
double number = scope->find("number")->asDouble();
|
||||
@@ -59,20 +64,21 @@ packToken default_pow(const Scope* scope) {
|
||||
return pow(number, exp);
|
||||
}
|
||||
|
||||
/* * * * * Initializer Function: * * * * */
|
||||
/* * * * * Function Initializer Constructor: * * * * */
|
||||
|
||||
TokenMap_t Function::initialize_functions() {
|
||||
TokenMap_t funcs;
|
||||
struct Function::Startup {
|
||||
Startup() {
|
||||
TokenMap_t& global = Scope::default_global();
|
||||
|
||||
funcs["print"] = Function(&default_print, 1, text_arg);
|
||||
funcs["sqrt"] = Function(&default_sqrt, 1, num_arg);
|
||||
funcs["sin"] = Function(&default_sin, 1, num_arg);
|
||||
funcs["cos"] = Function(&default_cos, 1, num_arg);
|
||||
funcs["tan"] = Function(&default_tan, 1, num_arg);
|
||||
funcs["abs"] = Function(&default_abs, 1, num_arg);
|
||||
funcs["pow"] = Function(&default_pow, 2, pow_args);
|
||||
return funcs;
|
||||
}
|
||||
global["print"] = Function(&default_print, 1, text_arg);
|
||||
global["sqrt"] = Function(&default_sqrt, 1, num_arg);
|
||||
global["sin"] = Function(&default_sin, 1, num_arg);
|
||||
global["cos"] = Function(&default_cos, 1, num_arg);
|
||||
global["tan"] = Function(&default_tan, 1, num_arg);
|
||||
global["abs"] = Function(&default_abs, 1, num_arg);
|
||||
global["pow"] = Function(&default_pow, 2, pow_args);
|
||||
}
|
||||
} startup;
|
||||
|
||||
/* * * * * Tuple Functions: * * * * */
|
||||
|
||||
|
||||
10
functions.h
10
functions.h
@@ -8,15 +8,17 @@
|
||||
class Function : public TokenBase {
|
||||
static TokenMap_t initialize_functions();
|
||||
|
||||
public:
|
||||
static TokenMap_t default_functions;
|
||||
private:
|
||||
// Used only to initialize
|
||||
// default functions on program startup.
|
||||
struct Startup;
|
||||
|
||||
public:
|
||||
packToken (*func)(const Scope*);
|
||||
unsigned nargs;
|
||||
std::string* arg_names;
|
||||
const char** arg_names;
|
||||
|
||||
Function(packToken (*func)(const Scope*), unsigned nargs, std::string* arg_names)
|
||||
Function(packToken (*func)(const Scope*), unsigned nargs, const char** arg_names)
|
||||
: func(func), nargs(nargs), arg_names(arg_names) { this->type = FUNC; }
|
||||
|
||||
virtual TokenBase* clone() const {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
#include "./shunting-yard.h"
|
||||
#include "./packToken.h"
|
||||
#include "./shunting-yard-exceptions.h"
|
||||
|
||||
const packToken packToken::None = packToken(TokenNone());
|
||||
@@ -139,31 +141,50 @@ TokenMap_t* packToken::asMap() const {
|
||||
std::string packToken::str() const {
|
||||
return packToken::str(base);
|
||||
}
|
||||
std::string packToken::str(TokenBase* base) {
|
||||
std::string packToken::str(const TokenBase* base) {
|
||||
std::stringstream ss;
|
||||
TokenMap_t* tmap;
|
||||
TokenMap_t::iterator it;
|
||||
bool first;
|
||||
std::string name;
|
||||
|
||||
if (!base) return "undefined";
|
||||
|
||||
if (base->type & REF) {
|
||||
base = static_cast<Token<RefValue_t>*>(base)->val.value;
|
||||
base = static_cast<const RefToken*>(base)->value;
|
||||
name = static_cast<const RefToken*>(base)->name;
|
||||
}
|
||||
|
||||
switch (base->type) {
|
||||
case NONE:
|
||||
return "None";
|
||||
case OP:
|
||||
return static_cast<Token<std::string>*>(base)->val;
|
||||
return static_cast<const Token<std::string>*>(base)->val;
|
||||
case VAR:
|
||||
return static_cast<Token<std::string>*>(base)->val;
|
||||
return static_cast<const Token<std::string>*>(base)->val;
|
||||
case NUM:
|
||||
ss << static_cast<Token<double>*>(base)->val;
|
||||
ss << static_cast<const Token<double>*>(base)->val;
|
||||
return ss.str();
|
||||
case STR:
|
||||
return "\"" + static_cast<Token<std::string>*>(base)->val + "\"";
|
||||
return "\"" + static_cast<const Token<std::string>*>(base)->val + "\"";
|
||||
case FUNC:
|
||||
if (name.size()) return "[Function: " + name + "]";
|
||||
return "[Function]";
|
||||
case TUPLE:
|
||||
ss << "(";
|
||||
first = true;
|
||||
for (const TokenBase* token : static_cast<const Tuple*>(base)->tuple) {
|
||||
if (!first) {
|
||||
ss << ", ";
|
||||
} else {
|
||||
first = false;
|
||||
}
|
||||
ss << str(token);
|
||||
}
|
||||
ss << ")";
|
||||
return ss.str();
|
||||
case MAP:
|
||||
tmap = static_cast<Token<TokenMap_t*>*>(base)->val;
|
||||
tmap = static_cast<const Token<TokenMap_t*>*>(base)->val;
|
||||
if (tmap->size() == 0) return "{}";
|
||||
ss << "{";
|
||||
for (it = tmap->begin(); it != tmap->end(); ++it) {
|
||||
|
||||
@@ -46,7 +46,7 @@ class packToken {
|
||||
TokenMap_t* asMap() const;
|
||||
|
||||
std::string str() const;
|
||||
static std::string str(TokenBase* t);
|
||||
static std::string str(const TokenBase* t);
|
||||
|
||||
private:
|
||||
// Note:
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include <string>
|
||||
#include <stack>
|
||||
#include <utility> // For std::pair
|
||||
#include <cstring> // For strchr()
|
||||
|
||||
OppMap_t calculator::buildOpPrecedence() {
|
||||
OppMap_t opp;
|
||||
@@ -35,15 +36,25 @@ OppMap_t calculator::buildOpPrecedence() {
|
||||
}
|
||||
// Builds the opPrecedence map only once:
|
||||
OppMap_t calculator::_opPrecedence = calculator::buildOpPrecedence();
|
||||
Scope calculator::empty_scope = Scope();
|
||||
|
||||
// Using the "Construct On First Use Idiom"
|
||||
// to avoid the "static initialization order fiasco",
|
||||
// for more information read:
|
||||
//
|
||||
// - https://isocpp.org/wiki/faq/ctors#static-init-order
|
||||
//
|
||||
const Scope Scope::empty = Scope();
|
||||
TokenMap_t& Scope::default_global() {
|
||||
static TokenMap_t global_map;
|
||||
return global_map;
|
||||
}
|
||||
|
||||
packToken trueToken = packToken(1);
|
||||
packToken falseToken = packToken(0);
|
||||
|
||||
// Check for unary operators and "convert" them to binary:
|
||||
bool calculator::handle_unary(const std::string& op,
|
||||
TokenQueue_t* rpnQueue, bool lastTokenWasOp,
|
||||
OppMap_t opPrecedence) {
|
||||
TokenQueue_t* rpnQueue, bool lastTokenWasOp) {
|
||||
if (lastTokenWasOp) {
|
||||
// Convert unary operators to binary in the RPN.
|
||||
if (!op.compare("-") || !op.compare("+")) {
|
||||
@@ -87,39 +98,72 @@ void calculator::handle_op(const std::string& op,
|
||||
operatorStack->push(op);
|
||||
}
|
||||
|
||||
// Use this function to discard a reference to an object
|
||||
// And obtain the original TokenBase*.
|
||||
// Please note that it only deletes memory if the token
|
||||
// is of type REF.
|
||||
TokenBase* pop_reference(TokenBase* b) {
|
||||
if (b->type & REF) {
|
||||
TokenBase* ref = static_cast<RefToken*>(b)->value;
|
||||
delete b;
|
||||
return ref;
|
||||
} else {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
|
||||
/* * * * * RAII_TokenQueue_t struct * * * * */
|
||||
|
||||
// Used to make sure an rpn is dealloc'd correctly
|
||||
// even when an exception is thrown.
|
||||
//
|
||||
// Note: This is needed because C++ does not
|
||||
// allow a try-finally block.
|
||||
struct calculator::RAII_TokenQueue_t : TokenQueue_t {
|
||||
RAII_TokenQueue_t() {}
|
||||
RAII_TokenQueue_t(const TokenQueue_t& rpn) : TokenQueue_t(rpn) {}
|
||||
~RAII_TokenQueue_t() { cleanRPN(this); }
|
||||
|
||||
RAII_TokenQueue_t(const RAII_TokenQueue_t& rpn) {
|
||||
throw std::runtime_error("You should not copy this class!");
|
||||
}
|
||||
RAII_TokenQueue_t& operator=(const RAII_TokenQueue_t& rpn) {
|
||||
throw std::runtime_error("You should not copy this class!");
|
||||
}
|
||||
};
|
||||
|
||||
/* * * * * calculator class * * * * */
|
||||
|
||||
#define isvariablechar(c) (isalpha(c) || c == '_')
|
||||
TokenQueue_t calculator::toRPN(const char* expr,
|
||||
const Scope* vars, OppMap_t opPrecedence) {
|
||||
const Scope* vars, const char* delim,
|
||||
const char** rest, OppMap_t opPrecedence) {
|
||||
TokenQueue_t rpnQueue; std::stack<std::string> operatorStack;
|
||||
bool lastTokenWasOp = true;
|
||||
uint8_t lastTokenWasOp = true;
|
||||
bool lastTokenWasUnary = false;
|
||||
char* nextChar;
|
||||
|
||||
static char c = '\0';
|
||||
if (!delim) delim = &c;
|
||||
|
||||
while (*expr && isblank(*expr)) ++expr;
|
||||
|
||||
if (*expr == '\0' || strchr(delim, *expr)) {
|
||||
throw std::invalid_argument("Cannot build a calculator from an empty expression!");
|
||||
}
|
||||
|
||||
// In one pass, ignore whitespace and parse the expression into RPN
|
||||
// using Dijkstra's Shunting-yard algorithm.
|
||||
while (*expr && isspace(*expr)) ++expr;
|
||||
while (*expr) {
|
||||
while (*expr && !strchr(delim, *expr)) {
|
||||
if (isdigit(*expr)) {
|
||||
// If the token is a number, add it to the output queue.
|
||||
char* nextChar = 0;
|
||||
double digit = strtod(expr , &nextChar);
|
||||
double digit = strtod(expr, &nextChar);
|
||||
rpnQueue.push(new Token<double>(digit, NUM));
|
||||
expr = nextChar;
|
||||
lastTokenWasOp = false;
|
||||
lastTokenWasUnary = false;
|
||||
} else if (isvariablechar(*expr) && lastTokenWasOp
|
||||
&& operatorStack.size() > 0 && !operatorStack.top().compare(".")) {
|
||||
// If it is a member access key (e.g. `map.name`)
|
||||
// parse it and add to the output queue.
|
||||
std::stringstream ss;
|
||||
while (isvariablechar(*expr) || isdigit(*expr)) {
|
||||
ss << *expr;
|
||||
++expr;
|
||||
}
|
||||
|
||||
rpnQueue.push(new Token<std::string>(ss.str(), STR));
|
||||
lastTokenWasOp = false;
|
||||
} else if (isvariablechar(*expr)) {
|
||||
// If the function is a variable, resolve it and
|
||||
// If the token is a variable, resolve it and
|
||||
// add the parsed number to the output queue.
|
||||
std::stringstream ss;
|
||||
ss << *expr;
|
||||
@@ -129,25 +173,28 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
++expr;
|
||||
}
|
||||
|
||||
packToken* value = NULL;
|
||||
|
||||
std::string key = ss.str();
|
||||
|
||||
if (key == "true") {
|
||||
value = &trueToken;
|
||||
} else if (key == "false") {
|
||||
value = &falseToken;
|
||||
if (lastTokenWasOp == '.') {
|
||||
rpnQueue.push(new Token<std::string>(ss.str(), STR));
|
||||
} else {
|
||||
if (vars) value = vars->find(key);
|
||||
}
|
||||
packToken* value = NULL;
|
||||
std::string key = ss.str();
|
||||
|
||||
if (value) {
|
||||
// Save a reference token:
|
||||
TokenBase* copy = (*value)->clone();
|
||||
rpnQueue.push(new Token<RefValue_t>({key, copy}, copy->type | REF));
|
||||
} else {
|
||||
// Save the variable name:
|
||||
rpnQueue.push(new Token<std::string>(key, VAR));
|
||||
if (key == "true") {
|
||||
value = &trueToken;
|
||||
} else if (key == "false") {
|
||||
value = &falseToken;
|
||||
} else {
|
||||
if (vars) value = vars->find(key);
|
||||
}
|
||||
|
||||
if (value) {
|
||||
// Save a reference token:
|
||||
TokenBase* copy = (*value)->clone();
|
||||
rpnQueue.push(new RefToken(key, copy, copy->type | REF));
|
||||
} else {
|
||||
// Save the variable name:
|
||||
rpnQueue.push(new Token<std::string>(key, VAR));
|
||||
}
|
||||
}
|
||||
|
||||
lastTokenWasOp = false;
|
||||
@@ -160,9 +207,25 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
++expr;
|
||||
std::stringstream ss;
|
||||
while (*expr && *expr != quote && *expr != '\n') {
|
||||
if (*expr == '\\') ++expr;
|
||||
ss << *expr;
|
||||
++expr;
|
||||
if (*expr == '\\') {
|
||||
switch (expr[1]) {
|
||||
case 'n':
|
||||
expr+=2;
|
||||
ss << '\n';
|
||||
break;
|
||||
case 't':
|
||||
expr+=2;
|
||||
ss << '\t';
|
||||
break;
|
||||
default:
|
||||
if (strchr("\"'\n", expr[1])) ++expr;
|
||||
ss << *expr;
|
||||
++expr;
|
||||
}
|
||||
} else {
|
||||
ss << *expr;
|
||||
++expr;
|
||||
}
|
||||
}
|
||||
|
||||
if (*expr != quote) {
|
||||
@@ -177,6 +240,7 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
} else {
|
||||
// Otherwise, the variable is an operator or paranthesis.
|
||||
uint8_t lastType;
|
||||
char lastOp;
|
||||
|
||||
// Check for syntax errors (excess of operators i.e. 10 + + -1):
|
||||
if (lastTokenWasUnary) {
|
||||
@@ -191,28 +255,30 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
case '(':
|
||||
// If it is a function call:
|
||||
lastType = rpnQueue.size() ? rpnQueue.front()->type : NONE;
|
||||
if (lastType == VAR || lastType == (FUNC | REF)) {
|
||||
lastOp = operatorStack.size() ? operatorStack.top()[0] : '\0';
|
||||
if (lastType == VAR || lastType == (FUNC | REF) || lastOp == '.') {
|
||||
// This counts as a bracket and as an operator:
|
||||
lastTokenWasUnary = handle_unary("()", &rpnQueue,
|
||||
lastTokenWasOp, opPrecedence);
|
||||
lastTokenWasUnary = handle_unary("()", &rpnQueue, lastTokenWasOp);
|
||||
handle_op("()", &rpnQueue, &operatorStack, opPrecedence);
|
||||
// Add it as a bracket to the op stack:
|
||||
}
|
||||
operatorStack.push("(");
|
||||
lastTokenWasOp = '(';
|
||||
++expr;
|
||||
lastTokenWasOp = true;
|
||||
break;
|
||||
case '[':
|
||||
// This counts as a bracket and as an operator:
|
||||
lastTokenWasUnary = handle_unary("[]", &rpnQueue,
|
||||
lastTokenWasOp, opPrecedence);
|
||||
lastTokenWasUnary = handle_unary("[]", &rpnQueue, lastTokenWasOp);
|
||||
handle_op("[]", &rpnQueue, &operatorStack, opPrecedence);
|
||||
// Add it as a bracket to the op stack:
|
||||
operatorStack.push("[");
|
||||
++expr;
|
||||
lastTokenWasOp = true;
|
||||
++expr;
|
||||
break;
|
||||
case ')':
|
||||
if (lastTokenWasOp == '(') {
|
||||
rpnQueue.push(new TokenNone());
|
||||
}
|
||||
while (operatorStack.top().compare("(")) {
|
||||
rpnQueue.push(new Token<std::string>(operatorStack.top(), OP));
|
||||
operatorStack.pop();
|
||||
@@ -234,8 +300,7 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
std::stringstream ss;
|
||||
ss << *expr;
|
||||
++expr;
|
||||
while (*expr && !isspace(*expr) && !isdigit(*expr)
|
||||
&& !isvariablechar(*expr) && *expr != '(' && *expr != ')') {
|
||||
while (*expr && ispunct(*expr) && !strchr("()_", *expr)) {
|
||||
ss << *expr;
|
||||
++expr;
|
||||
}
|
||||
@@ -244,16 +309,15 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
|
||||
ss >> op;
|
||||
|
||||
lastTokenWasUnary = handle_unary(op, &rpnQueue,
|
||||
lastTokenWasOp, opPrecedence);
|
||||
lastTokenWasUnary = handle_unary(op, &rpnQueue, lastTokenWasOp);
|
||||
|
||||
handle_op(op, &rpnQueue, &operatorStack, opPrecedence);
|
||||
|
||||
lastTokenWasOp = true;
|
||||
lastTokenWasOp = op[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
while (*expr && isspace(*expr)) ++expr;
|
||||
while (*expr && isblank(*expr)) ++expr;
|
||||
}
|
||||
|
||||
// Check for syntax errors (excess of operators i.e. 10 + + -1):
|
||||
@@ -266,25 +330,19 @@ TokenQueue_t calculator::toRPN(const char* expr,
|
||||
rpnQueue.push(new Token<std::string>(operatorStack.top(), OP));
|
||||
operatorStack.pop();
|
||||
}
|
||||
|
||||
if (rest) *rest = expr;
|
||||
return rpnQueue;
|
||||
}
|
||||
|
||||
packToken calculator::calculate(const char* expr, const Scope& vars) {
|
||||
packToken calculator::calculate(const char* expr, const Scope& vars,
|
||||
const char* delim, const char** rest) {
|
||||
// Convert to RPN with Dijkstra's Shunting-yard algorithm.
|
||||
TokenQueue_t rpn = calculator::toRPN(expr, &vars);
|
||||
RAII_TokenQueue_t rpn = calculator::toRPN(expr, &vars, delim, rest);
|
||||
packToken ret;
|
||||
|
||||
try {
|
||||
ret = calculator::calculate(rpn, &vars);
|
||||
} catch (undefined_operation e) {
|
||||
cleanRPN(&rpn);
|
||||
throw e;
|
||||
} catch (std::domain_error e) {
|
||||
cleanRPN(&rpn);
|
||||
throw e;
|
||||
}
|
||||
ret = calculator::calculate(rpn, &vars);
|
||||
|
||||
cleanRPN(&rpn);
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -297,7 +355,7 @@ void cleanStack(std::stack<TokenBase*> st) {
|
||||
|
||||
packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
const Scope* vars) {
|
||||
TokenQueue_t rpn;
|
||||
RAII_TokenQueue_t rpn;
|
||||
|
||||
// Deep copy the token list, so everything can be
|
||||
// safely deallocated:
|
||||
@@ -319,34 +377,30 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
delete base;
|
||||
|
||||
if (evaluation.size() < 2) {
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw std::domain_error("Invalid equation.");
|
||||
}
|
||||
TokenBase* b_right = evaluation.top(); evaluation.pop();
|
||||
TokenBase* b_left = evaluation.top(); evaluation.pop();
|
||||
|
||||
if (b_right->type & REF) {
|
||||
RefValue_t rvalue = static_cast<Token<RefValue_t>*>(b_right)->val;
|
||||
delete b_right;
|
||||
b_right = rvalue.value->clone();
|
||||
} else if (b_right->type == VAR) {
|
||||
if (b_right->type == VAR) {
|
||||
std::string var_name = static_cast<Token<std::string>*>(b_right)->val;
|
||||
delete b_right;
|
||||
delete b_left;
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw std::domain_error("Unable to find the variable '" + var_name + "'.");
|
||||
} else {
|
||||
b_right = pop_reference(b_right);
|
||||
}
|
||||
|
||||
std::string r_left;
|
||||
TokenMap_t* m_left = NULL;
|
||||
if (b_left->type & REF) {
|
||||
RefValue_t rvalue = static_cast<Token<RefValue_t>*>(b_left)->val;
|
||||
delete b_left;
|
||||
r_left = rvalue.name;
|
||||
b_left = rvalue.value->clone();
|
||||
m_left = rvalue.source_map;
|
||||
RefToken* left = static_cast<RefToken*>(b_left);
|
||||
r_left = left->name;
|
||||
m_left = left->source_map;
|
||||
b_left = left->value;
|
||||
delete left;
|
||||
} else if (b_left->type == VAR) {
|
||||
r_left = static_cast<Token<std::string>*>(b_left)->val;
|
||||
}
|
||||
@@ -367,6 +421,7 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
} else if (!op.compare("=")) {
|
||||
delete b_left;
|
||||
|
||||
// If the left operand has a variable name:
|
||||
if (r_left.size() > 0) {
|
||||
if (vars) {
|
||||
if (m_left && b_right->type != NONE) {
|
||||
@@ -377,7 +432,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
evaluation.push(b_right);
|
||||
} else {
|
||||
delete b_right;
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw std::domain_error("No Scope available for assignment of variable `" + r_left + "`.");
|
||||
}
|
||||
@@ -385,7 +439,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
packToken p_right(b_right->clone());
|
||||
delete b_right;
|
||||
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, r_left, p_right);
|
||||
}
|
||||
@@ -431,7 +484,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
} else if (!op.compare("||")) {
|
||||
evaluation.push(new Token<double>(left_i || right_i, NUM));
|
||||
} else {
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, left, right);
|
||||
}
|
||||
@@ -448,7 +500,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
} else if (!op.compare("!=")) {
|
||||
evaluation.push(new Token<double>(left.compare(right) != 0, NUM));
|
||||
} else {
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, left, right);
|
||||
}
|
||||
@@ -463,7 +514,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
ss << left << right;
|
||||
evaluation.push(new Token<std::string>(ss.str(), STR));
|
||||
} else {
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, left, right);
|
||||
}
|
||||
@@ -478,7 +528,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
ss << left << right;
|
||||
evaluation.push(new Token<std::string>(ss.str(), STR));
|
||||
} else {
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, left, right);
|
||||
}
|
||||
@@ -501,9 +550,8 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
type = value->type | REF;
|
||||
}
|
||||
|
||||
evaluation.push(new Token<RefValue_t>({right, value, left}, type));
|
||||
evaluation.push(new RefToken(right, value, left, type));
|
||||
} else {
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, left, right);
|
||||
}
|
||||
@@ -546,7 +594,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
packToken p_right(b_right->clone());
|
||||
delete b_right;
|
||||
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, left, p_right);
|
||||
}
|
||||
@@ -556,7 +603,6 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
delete b_left;
|
||||
delete b_right;
|
||||
|
||||
cleanRPN(&rpn);
|
||||
cleanStack(evaluation);
|
||||
throw undefined_operation(op, p_left, p_right);
|
||||
}
|
||||
@@ -568,7 +614,7 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
|
||||
if (value) {
|
||||
TokenBase* copy = (*value)->clone();
|
||||
evaluation.push(new Token<RefValue_t>({key, copy}, copy->type | REF));
|
||||
evaluation.push(new RefToken(key, copy, copy->type | REF));
|
||||
delete base;
|
||||
} else {
|
||||
evaluation.push(base);
|
||||
@@ -578,18 +624,12 @@ packToken calculator::calculate(TokenQueue_t _rpn,
|
||||
}
|
||||
}
|
||||
|
||||
TokenBase* result = evaluation.top();
|
||||
if (result->type & REF) {
|
||||
RefValue_t rvalue = static_cast<Token<RefValue_t>*>(result)->val;
|
||||
delete result;
|
||||
result = rvalue.value;
|
||||
}
|
||||
return packToken(result);
|
||||
return packToken(pop_reference(evaluation.top()));
|
||||
}
|
||||
|
||||
void calculator::cleanRPN(TokenQueue_t* rpn) {
|
||||
while (rpn->size()) {
|
||||
delete rpn->front();
|
||||
delete pop_reference(rpn->front());
|
||||
rpn->pop();
|
||||
}
|
||||
}
|
||||
@@ -612,24 +652,21 @@ calculator::calculator(const calculator& calc) {
|
||||
}
|
||||
}
|
||||
|
||||
calculator::calculator(const char* expr,
|
||||
const Scope& vars, OppMap_t opPrecedence) {
|
||||
compile(expr, vars, opPrecedence);
|
||||
}
|
||||
|
||||
void calculator::compile(const char* expr, OppMap_t opPrecedence) {
|
||||
// Make sure it is empty:
|
||||
cleanRPN(&this->RPN);
|
||||
|
||||
this->RPN = calculator::toRPN(expr, NULL, opPrecedence);
|
||||
// Work as a sub-parser:
|
||||
// - Stops at delim or '\0'
|
||||
// - Returns the rest of the string as char* rest
|
||||
calculator::calculator(const char* expr, const Scope& vars,
|
||||
const char* delim, const char** rest, OppMap_t opPrecedence) {
|
||||
compile(expr, vars, delim, rest, opPrecedence);
|
||||
}
|
||||
|
||||
void calculator::compile(const char* expr,
|
||||
const Scope& vars, OppMap_t opPrecedence) {
|
||||
const Scope& vars, const char* delim,
|
||||
const char** rest, OppMap_t opPrecedence) {
|
||||
// Make sure it is empty:
|
||||
cleanRPN(&this->RPN);
|
||||
|
||||
this->RPN = calculator::toRPN(expr, &vars, opPrecedence);
|
||||
this->RPN = calculator::toRPN(expr, &vars, delim, rest, opPrecedence);
|
||||
}
|
||||
|
||||
packToken calculator::eval(const Scope& vars) {
|
||||
@@ -653,9 +690,12 @@ calculator& calculator::operator=(const calculator& calc) {
|
||||
|
||||
/* * * * * For Debug Only * * * * */
|
||||
|
||||
std::string calculator::str() {
|
||||
std::string calculator::str() const {
|
||||
return str(this->RPN);
|
||||
}
|
||||
|
||||
std::string calculator::str(TokenQueue_t rpn) {
|
||||
std::stringstream ss;
|
||||
TokenQueue_t rpn = this->RPN;
|
||||
|
||||
ss << "calculator { RPN: [ ";
|
||||
while (rpn.size()) {
|
||||
@@ -672,7 +712,7 @@ std::string calculator::str() {
|
||||
|
||||
Scope::Scope(TokenMap_t* vars) {
|
||||
// Add default functions to the global namespace:
|
||||
scope.push_front(&Function::default_functions);
|
||||
scope.push_front(&default_global());
|
||||
|
||||
if (vars) scope.push_front(vars);
|
||||
}
|
||||
|
||||
@@ -38,14 +38,20 @@ typedef std::map<std::string, packToken> TokenMap_t;
|
||||
typedef std::map<std::string, int> OppMap_t;
|
||||
typedef std::list<TokenBase*> Tuple_t;
|
||||
|
||||
struct RefValue_t {
|
||||
struct RefToken : public TokenBase {
|
||||
std::string name;
|
||||
TokenBase* value;
|
||||
TokenMap_t* source_map;
|
||||
RefValue_t(std::string n, TokenBase* v, TokenMap_t* m) :
|
||||
name(n), value(v), source_map(m) {}
|
||||
RefValue_t(std::string n, TokenBase* v) :
|
||||
name(n), value(v), source_map(0) {}
|
||||
RefToken(std::string n, TokenBase* v, TokenMap_t* m, uint8_t type) :
|
||||
name(n), value(v), source_map(m) { this->type = type; }
|
||||
RefToken(std::string n, TokenBase* v, uint8_t type) :
|
||||
name(n), value(v), source_map(0) { this->type = type; }
|
||||
|
||||
virtual TokenBase* clone() const {
|
||||
RefToken* copy = new RefToken(static_cast<const RefToken&>(*this));
|
||||
copy->value = value->clone();
|
||||
return copy;
|
||||
}
|
||||
};
|
||||
|
||||
#include "./packToken.h"
|
||||
@@ -55,6 +61,10 @@ struct RefValue_t {
|
||||
#include "./functions.h"
|
||||
|
||||
class Scope {
|
||||
public:
|
||||
static const Scope empty;
|
||||
static TokenMap_t& default_global();
|
||||
|
||||
public:
|
||||
typedef std::list<TokenMap_t*> Scope_t;
|
||||
mutable Scope_t scope;
|
||||
@@ -78,27 +88,29 @@ class calculator {
|
||||
private:
|
||||
static OppMap_t _opPrecedence;
|
||||
static OppMap_t buildOpPrecedence();
|
||||
static Scope empty_scope;
|
||||
|
||||
public:
|
||||
static packToken calculate(const char* expr, const Scope& vars = empty_scope);
|
||||
static packToken calculate(const char* expr, const Scope& vars = Scope::empty,
|
||||
const char* delim = 0, const char** rest = 0);
|
||||
|
||||
private:
|
||||
static packToken calculate(TokenQueue_t RPN,
|
||||
const Scope* vars);
|
||||
static void cleanRPN(TokenQueue_t* rpn);
|
||||
static TokenQueue_t toRPN(const char* expr,
|
||||
const Scope* vars,
|
||||
const Scope* vars, const char* delim = 0, const char** rest = 0,
|
||||
OppMap_t opPrecedence = _opPrecedence);
|
||||
|
||||
static bool handle_unary(const std::string& op,
|
||||
TokenQueue_t* rpnQueue, bool lastTokenWasOp,
|
||||
OppMap_t opPrecedence);
|
||||
TokenQueue_t* rpnQueue, bool lastTokenWasOp);
|
||||
static void handle_op(const std::string& op,
|
||||
TokenQueue_t* rpnQueue,
|
||||
std::stack<std::string>* operatorStack,
|
||||
OppMap_t opPrecedence);
|
||||
|
||||
// Used to dealloc a TokenQueue_t safely.
|
||||
struct RAII_TokenQueue_t;
|
||||
|
||||
private:
|
||||
TokenQueue_t RPN;
|
||||
|
||||
@@ -106,17 +118,17 @@ class calculator {
|
||||
~calculator();
|
||||
calculator() {}
|
||||
calculator(const calculator& calc);
|
||||
calculator(const char* expr, const Scope& vars = empty_scope,
|
||||
calculator(const char* expr, const Scope& vars = Scope::empty,
|
||||
const char* delim = 0, const char** rest = 0,
|
||||
OppMap_t opPrecedence = _opPrecedence);
|
||||
void compile(const char* expr,
|
||||
OppMap_t opPrecedence = _opPrecedence);
|
||||
void compile(const char* expr,
|
||||
const Scope& vars = empty_scope,
|
||||
OppMap_t opPrecedence = _opPrecedence);
|
||||
packToken eval(const Scope& vars = empty_scope);
|
||||
const Scope& vars = Scope::empty, const char* delim = 0,
|
||||
const char** rest = 0, OppMap_t opPrecedence = _opPrecedence);
|
||||
packToken eval(const Scope& vars = Scope::empty);
|
||||
|
||||
// Serialization:
|
||||
std::string str();
|
||||
std::string str() const;
|
||||
static std::string str(TokenQueue_t rpn);
|
||||
|
||||
// Operators:
|
||||
calculator& operator = (const calculator& calc);
|
||||
|
||||
@@ -9,6 +9,7 @@ void PREPARE_ENVIRONMENT() {
|
||||
vars["pi"] = 3.14;
|
||||
vars["b1"] = 0.0;
|
||||
vars["b2"] = 0.86;
|
||||
vars["_b"] = 0;
|
||||
vars["str1"] = "foo";
|
||||
vars["str2"] = "bar";
|
||||
vars["str3"] = "foobar";
|
||||
@@ -33,6 +34,7 @@ TEST_CASE("Static calculate::calculate()") {
|
||||
REQUIRE(calculator::calculate("(20+10)*3/2-3", &vars).asDouble() == Approx(42.0));
|
||||
REQUIRE(calculator::calculate("1 << 4", &vars).asDouble() == Approx(16.0));
|
||||
REQUIRE(calculator::calculate("1+(-2*3)", &vars).asDouble() == Approx(-5));
|
||||
REQUIRE(calculator::calculate("1+_b+(-2*3)", &vars).asDouble() == Approx(-5));
|
||||
}
|
||||
|
||||
TEST_CASE("calculate::compile() and calculate::eval()") {
|
||||
@@ -70,7 +72,21 @@ TEST_CASE("String expressions") {
|
||||
|
||||
REQUIRE(calculator::calculate("'foo' + \"bar\" == str3", &vars).asBool());
|
||||
REQUIRE(calculator::calculate("'foo' + \"bar\" != 'foobar\"'", &vars).asBool());
|
||||
REQUIRE(calculator::calculate("'foo' + \"bar\\\"\" == 'foobar\"'", &vars).asBool());
|
||||
|
||||
// Test escaping characters:
|
||||
REQUIRE(calculator::calculate("'foo\\'bar'").asString() == "foo'bar");
|
||||
REQUIRE(calculator::calculate("\"foo\\\"bar\"").asString() == "foo\"bar");
|
||||
|
||||
// Special meaning escaped characters:
|
||||
REQUIRE(calculator::calculate("'foo\\bar'").asString() == "foo\\bar");
|
||||
REQUIRE(calculator::calculate("'foo\\nar'").asString() == "foo\nar");
|
||||
REQUIRE(calculator::calculate("'foo\\tar'").asString() == "foo\tar");
|
||||
REQUIRE_NOTHROW(calculator::calculate("'foo\\t'"));
|
||||
REQUIRE(calculator::calculate("'foo\\t'").asString() == "foo\t");
|
||||
|
||||
// Scaping linefeed:
|
||||
REQUIRE_THROWS(calculator::calculate("'foo\nar'"));
|
||||
REQUIRE(calculator::calculate("'foo\\\nar'").asString() == "foo\nar");
|
||||
}
|
||||
|
||||
TEST_CASE("Map access expressions") {
|
||||
@@ -110,8 +126,10 @@ TEST_CASE("Function usage expressions") {
|
||||
REQUIRE_THROWS(calculator::calculate("foo(10),"));
|
||||
REQUIRE_THROWS(calculator::calculate("foo,(10)"));
|
||||
|
||||
// The test bellow will fail, TODO fix it:
|
||||
// REQUIRE_NOTHROW(calculator::calculate("print()"));
|
||||
REQUIRE_NOTHROW(calculator::calculate("print()"));
|
||||
|
||||
REQUIRE(Scope::default_global()["abs"].str() == "[Function]");
|
||||
REQUIRE(calculator::calculate("1,2,3,4,5").str() == "(1, 2, 3, 4, 5)");
|
||||
}
|
||||
|
||||
TEST_CASE("Assignment expressions") {
|
||||
@@ -192,6 +210,35 @@ TEST_CASE("Scope management") {
|
||||
scope.clean();
|
||||
}
|
||||
|
||||
// Working as a slave parser implies it will return
|
||||
// a pointer to the place it has stopped parsing
|
||||
// and accept a list of delimiters that should make it stop.
|
||||
TEST_CASE("Parsing as slave parser") {
|
||||
const char* original_code = "a=1; b=2\n c=a+b }";
|
||||
const char* code = original_code;
|
||||
TokenMap_t vars;
|
||||
calculator c1, c2, c3;
|
||||
|
||||
// With static function:
|
||||
REQUIRE_NOTHROW(calculator::calculate(code, &vars, ";}\n", &code));
|
||||
REQUIRE(code == &(original_code[3]));
|
||||
REQUIRE(vars["a"].asDouble() == 1);
|
||||
|
||||
// With constructor:
|
||||
REQUIRE_NOTHROW((c2 = calculator(++code, &vars, ";}\n", &code)));
|
||||
REQUIRE(code == &(original_code[8]));
|
||||
|
||||
// With compile method:
|
||||
REQUIRE_NOTHROW(c3.compile(++code, &vars, ";}\n", &code));
|
||||
REQUIRE(code == &(original_code[16]));
|
||||
|
||||
REQUIRE_NOTHROW(c2.eval(&vars));
|
||||
REQUIRE(vars["b"] == 2);
|
||||
|
||||
REQUIRE_NOTHROW(c3.eval(&vars));
|
||||
REQUIRE(vars["c"] == 3);
|
||||
}
|
||||
|
||||
TEST_CASE("Resource management") {
|
||||
calculator C1, C2("1 + 1");
|
||||
|
||||
@@ -209,6 +256,9 @@ TEST_CASE("Exception management") {
|
||||
ecalc.compile("a+b+del", &emap);
|
||||
emap["del"] = 30;
|
||||
|
||||
REQUIRE_THROWS(calculator(""));
|
||||
REQUIRE_THROWS(calculator(" "));
|
||||
|
||||
REQUIRE_THROWS(ecalc.eval());
|
||||
REQUIRE_NOTHROW(ecalc.eval(&emap));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user