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

半腔热情 提交于 2019-12-02 10:23:05

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