mirror of
https://github.com/allankoechke/cparse.git
synced 2026-11-30 17:11:31 +00:00
e4ebe719cd706088caa02c0e96087d2c2647e2bd
* 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
C++ Expression Parser • [ ![Build Status] travis-image ] travis [
license-image ] license
This project provides a C++ library to parse a character sequence as an expression using Dijkstra's Shunting-yard algorithm, which modifies Jesse Brown's original code.
This project was created by Brandon Amos and contains substantial modifications from Vinícius Garcia.
Modifications and Uses of This Code
- In Andrew Steiner's
o2scl:
- Adds simple unary functions like sin, cos, and exp.
- shunting_yard.cpp
- shunting_yard.h
- shunting_yard_ts.cpp
Minimal example.
#include <iostream>
#include "shunting-yard.h"
int main() {
TokenMap_t vars;
vars["pi"] = 3.14;
std::cout << calculator::calculate("-pi+1", &vars) << std::endl;
// Or if you want to evaluate an expression
// several times efficiently:
calculator c1("pi-b");
vars["b"] = 0.14;
std::cout << c1.eval(&vars) << std::endl; // 3
vars["b"] = 2.14;
std::cout << c1.eval(&vars) << std::endl; // 1
return 0;
}
More examples.
- See
test-shunting-yard.cpp.
Features.
- Unary operators. +, -
- 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,
- Update the operator precedence map in
calculator::buildOpPrecedence. - Add the computation to
calculator::calculate.
Implementation Details
The main steps of the calculation process are:
- Create the operator precedence map.
- Convert to RPN with Dijkstra's Shunting-yard algorithm.
- Evaluate the expression in RPN form.
Converting to RPN.
Most of the Shunting-yard algorithm resides here. The idea is to do everything in one pass for elegance. Please see the source code for implementation-specific details, and refer to the pruned code below for a summary.
TokenQueue_t calculator::toRPN(const char* expr,
std::map<std::string, double>* vars,
std::map<std::string, int> opPrecedence) {
TokenQueue_t rpnQueue; std::stack<std::string> operatorStack;
while (*expr ) {
if (isdigit(*expr )) {
// If the token is a number, add it to the output queue.
} else if (isvariablechar(*expr )) {
// If the function is a variable, resolve it and
// add the parsed number to the output queue.
} else {
// Otherwise, the variable is an operator or parenthesis.
switch (*expr) {
case '(':
operatorStack.push("(");
++expr;
break;
case ')':
while (operatorStack.top().compare("(")) {
rpnQueue.push(new Token<std::string>(operatorStack.top()));
operatorStack.pop();
}
operatorStack.pop();
++expr;
break;
default:
{
// The token is an operator.
//
// Let p(o) denote the precedence of an operator o.
//
// If the token is an operator, o1, then
// While there is an operator token, o2, at the top
// and p(o1) <= p(o2), then
// pop o2 off the stack onto the output queue.
// Push o1 on the stack.
}
}
}
}
while (!operatorStack.empty()) {
rpnQueue.push(new Token<std::string>(operatorStack.top()));
operatorStack.pop();
}
return rpnQueue;
}
Evaluating RPN form.
The RPN is represented as tokens in a stack. To evaluate this, pop all of the elements off and handle operations when encountered.
std::stack<double> evaluation;
while (!rpn.empty()) {
TokenBase* base = rpn.front();
rpn.pop();
if (base->type == OP) {
Token<std::string>* strTok = static_cast<Token<std::string>*>(base);
std::string str = strTok->val;
if (evaluation.size() < 2) {
throw std::domain_error("Invalid equation.");
}
double right = evaluation.top(); evaluation.pop();
double left = evaluation.top(); evaluation.pop();
if (!str.compare("+")) {
evaluation.push(left + right);
} else if (!str.compare("*")) {
evaluation.push(left * right);
} else if (!str.compare("-")) {
evaluation.push(left - right);
} else if (!str.compare("/")) {
evaluation.push(left / right);
} else if (!str.compare("<<")) {
evaluation.push((int) left << (int) right);
} else if (!str.compare(">>")) {
evaluation.push((int) left >> (int) right);
} else {
throw std::domain_error("Unknown operator: '" + str + "'.");
}
} else if (base->type == NUM) {
Token<double>* doubleTok = static_cast<Token<double>*>(base);
evaluation.push(doubleTok->val);
} else {
throw std::domain_error("Invalid token.");
}
delete base;
}
The evaluated value resides in evaluation.top of type double.
Description
A C++ configurable Expression Parser. Useful as a Calculator or for helping you write your own Programming Language
Languages
C++
99.8%
Makefile
0.2%