简体   繁体   中英

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.

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 (ie 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> 
   "(" ")" ";"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM