简体   繁体   中英

Evaluating Logical expression in string format with operators as predefined variables in Embedded C++

  • In my C++ embedded program, I have certain predefined variables such as int Var_A, Var_B, Var_C, Var_D....
  • I have to define logical expression in external text file (As logical expressions are configurable in external text file called config file), later this file is read in micro controller's File System.
  • The variables in config file are same as variables in embedded program.
  • The file contains logical expression in following predefined format,

(Operand 1) (Operator) (Operator 2)

Example: Var_A AND Var_B

  • The variables do change (in embedded program) during runtime.
  • Later the result of this logical expression is used to execute certain subroutine program.
  • We can not use interrupts for same operation as we have 100s of such variables.

I thought to use interpreter to resolve this problem, but that too I'm not much familiar with interpreter and just heard interpreter can be used in this case.

Please suggest logical solution for same.

Your solution is going to be to write a scanner and parser to build up a tree.

The best solution to get ideas with it is to do some testing usingFlex and Yacc . These tools allow you to do scanning (Flex) and transform the scanned strings into tokens which the parser(Yacc) can convert using a Context Free Grammer (CFG) into a tree of nodes which encode the equation. (This is very similar as to how compilers are done)

This allow you to do the following, if your input is this:

var1 + var2

You scan this string for tokens, these being: var1<variable> +<operator> var2<variable>

You convert these tokens into nodes of a tree:

    node #1
    op: +
    operatorType: enumvalue for +
       |               |
      |                 |
     |                   |
    \/                   \/
node #2                node# #3
name: var1             name: var2
type: var              type: var

You can now travers the tree and use the members of the objects in the tree to determine what it is and how to use it.

Now the tricky part is how are you going to implement this in a restricted embedded device. If your device has enough RAM to contain a large enough buffer of data for this tree structure than it can be done. My solution would be to allocate a buffer for my tree object nodes and a buffer for the names of the variables, which would allow a static amount of memory to be used without fragmentation.

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