Search code examples
javacc

How can I convert an EBNF grammar to Javacc?


I want to implement an interpreter for a multi notation (prefix, infix, and postfix) arithmetic language. Its grammar description in EBNF is given below. How can I code this in Javacc?

< Process> --> PROCESS  id ; <First Section> <SecondSection>
<First Section> --> VARIABLES [<Variable List>];
<First List> --> <First Def> | <First Def>, <First List>
<First Def> --> <First Name> [ EQUAL integer_literal ]
<First Name> --> id

<Second Section> --> COMMANDS {<Statement>;}
<Statement> --> <Input Statement> | <Output Statement> | <Assignment Statement>

<Input Statement> --> READ 'message ' <First Name>
<Output Statement> --> WRITE 'message ' [ <Expression>]
<Assignment Statement> --> <First Name> <-- <Expression>

<Expression> --> <PrefixExp> | <InfixExp> | <PostfixExp>

<InfixExp> --> <Term> | <InfixExp> (PLUS | MINUS) <Term>
<Term> --> <Factor> | <Term> (MULTIPLICATION | DIVISION) <Factor>
<Factor> --> integer_literal | <First Name> | ( <InfixExp> )

<PrefixExp> --> <Operator> <PrefixExp> <PrefixExp>
<PrefixExp> --> integer_literal | <First Name>

<PostfixExp> --> <PostfixExp> <PostfixExp> <Operator>
<PostfixExp> --> integer_literal | <First Name>

<Operator> --> (ADD | SUBSTRACT | MULTIPLY | DIVIDE)

Solution

  • Don't do it! Your grammar, as it stands, is ambiguous. First rewrite the grammar in EBNF form to an unambiguous and non-left-recursive form. After you have done that, it will be ready to convert to JavaCC.

    For example, consider a command

    write 'hello' 1
    

    is the 1 a prefix expression, a postfix expression, or an infix expression? Your grammar permits all three interpretation.