Search code examples
javacompiler-constructionbnfjavacc

BNF for Java Input Statements


I am writing a Java source code(.java) to pseudocode generator in Java using JDK 7. I want to display the pseudo code format of input statements as:

read n

like we see in Pascal.

However the thing is there are myriad ways to take console input in Java. My pseudo code generator is nothing but a parser of Java grammars. However I could not design a grammar to parse input statements.

So can anyone tell me how to write a BNF expression for Java Input Statements. If my approach is wrong please mention the correct approach.


Solution

  • If I understand what you want, you'd like to have Java input like

    int k = new Scanner(System.in).nextInt() ;
    int m = k * 2 ;
    k = k + 1 ;
    

    turn into psuedo code output like

    var k
    read k
    var m := k * 2
    k := k + 1
    

    There are at least three phases where you might recognize the "input statements". One is during parsing. Another is between parsing and generation (i.e. an analysis phase that transforms or marks the tree). A third is during generation.

    Of the three, I'd suggest that the second or third might be best. Parsing is already complex enough. But if you really want to do it during parsing, you can do it with a combination of semantic and syntactic lookahead.

    void DeclOrInput() :
    {}
    {
         LOOKAHEAD( Input() ) Input()
    |
         LocalDeclStatement()
    }
    
    void Input() :
    {  }
    {  <NEW>
       LOOKAHEAD({ token(1).image.equals("Scanner") } )
       <ID> 
       "("
       LOOKAHEAD( { token(1).image.equals("System") } ) 
       <ID> 
       "."
       LOOKAHEAD( { token(1).image.equals("in") } )
       <ID> 
       ")" "."
       LOOKAHEAD( { token(1).image.equals( "nextInt" ) } )
       <ID> 
       "(" ")" ";"
    }