简体   繁体   中英

Boolean expression parser in C++

I need a simple boolean expression parser for a little C++ templating engine I'm working on, and I was looking for some library that could do it for me. Unfortunately, I didn't really find anything easy to integrate. I found this spirit based solution , which seems like a good starting point, but it doesn't quite have all the features I need. I am aware of the spirit mini-c example, but it seems way too complex and it would probably take me forever to somehow strip what I need. Basically, what I need is the following:

  • Variables with variable types: integer, double, string, array
  • Operators "and", "or", "xor", "not" and the correct/expected precedence
  • Comparison operators "==", "!=", "<", "<=", ">", ">="
  • Arithmetic operators such as "+", "-", "/", "*" and their expected precedence
  • Optional: C-style function calls that return a value, eg somefunc(12, "abc") that I can somehow map to a c++ function during evaluation

I need to be able to supply the parser with all variables and their values, including arrays. The idea is to be able to evaluate expressions such as:

var == 2 + 3
var != 2.32
var == "foo"
somearr[var][2] == "bar"
(var == 2) or (var > 100)

Optionally for functions I'd be nice to be able to do something like this:

var.length() == 3
"bla".length() == 3

or alternatively

length(var) == 3
length("bla") == 3

I am somewhat flexible on the syntax details, so does anyone know of an open source library that can do this and is easy to integrate? Or how I can maybe extend some spirit based example?

For example, in this boolean expression example I don't quite understand how I would set the variables to some values before parsing them. But even if i did, it wouldn't quite support enough of what I need.

Any help/pointers are appreciated! I spent quite some time trying to understand spirit, but I guess I still don't understand it well enough to accomplish anything beyond very simple parsing.

Probably the best way to learn about that is by reading chapter 6 of Stroustrup's "The C++ Programming Language", which discusses at some length source code for a desk calculator (available here: http://www.stroustrup.com/3rd_code.html ).

It's basic (since it's a teaching tool) but easy to modify to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM