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

后端 未结 1 880
旧巷少年郎
旧巷少年郎 2021-01-27 05:52

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 gramma

相关标签:
1条回答
  • 2021-01-27 06:42

    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()
    }
    
    0 讨论(0)
提交回复
热议问题