Make a calculator's grammar that make a binary tree with javacc

北城余情 提交于 2019-12-09 03:51:04

问题


I need to make a simple calculator (with infix operator) parser that handle the operators +,-,*,/ and float and variable. To make this I used javacc, and I have made this grammar with jjtree. It works but it doesn't ensure that the final tree will be a binary tree, which I need. I want something like 5*3+x-y to generate the following tree :

  *
 / \
5   +
   / \
  3   -
     / \
    x   y

What would be a proper grammar to do that, that would not be left-recursive ?


回答1:


Something like the following will give you the tree you asked for.

void sum():
{}
{
    term()
    [    plus() sum()
    |    minus() sum()
    |    times() sum()
    |    divide() sum()
    |    modulo() sum()
    ]
}


void term() :
{}
{
    "(" sum() ")" | Number() | Variable()
}

---Edit:---

To get a tree that reflects precedence and associativity, you can use definite nodes. See the JJTree documentation.

void sum() #void {} :
{
    term()
    (   plus() term() #BinOp(3)
    |   minus() term() #BinOp(3)
    )*
}

void term() #void {} :
{
    factor()
    (   times() factor() #BinOp(3)
    |   divide() factor() #BinOp(3)
    |   modulo() factor() #BinOp(3)
    )*
}

void factor() #void :
{}
{
    "(" sum() ")" | Number() | Variable()
}


来源:https://stackoverflow.com/questions/26846777/make-a-calculators-grammar-that-make-a-binary-tree-with-javacc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!