Reputation: 587
I'm not sure if I'm translating the EBNF to code correctly so if someone can take a look at one of the methods I'm having a hard time doing that'll be great.
Here's the EBNF Grammar:
program ::= P {declare} B {statemt} ;
declare ::= ident {, ident} : V ;
statemt ::= assnmt | ifstmt | doloop | read | output
assnmt ::= ident ~ exprsn ;
ifstmt ::= I comprsn @ {statemt} [% {statemt}] &
doloop ::= D {statemt} U comprsn T
read ::= R ident {, ident } ;
output ::= O ident {, ident } ;
comprsn ::= ( oprnd opratr oprnd )
exprsn ::= factor {+ factor}
factor ::= oprnd {* oprnd}
oprnd ::= integer | ident | ( exprsn )
opratr ::= < | = | > | !
ident ::= letter {char}
char ::= letter | digit
integer ::= digit {digit}
letter ::= X | Y | Z
digit ::= 0 | 1
The tokens are: P B ; , : V ~ I @ % & D U T R O ( ) + * < = > ! X Y Z 0 1
private void statemt(){
if((token() == 'X') || (token() == 'Y') || (token() == 'Z')){
assnmt();
}else if(token() == 'I'){
ifstmt();
}else if(token() == 'D'){
doloop();
}else if(token() == 'R'){
read();
}else if(token() == 'O'){
output();
}
}
Is this if stmt method correct?
private void ifstmt(){
match('I');
comprsn();
match('@');
while((token() == 'X') || (token() == 'Y') || (token() == 'Z')){
statemt();
}
if(token() == '%'){
match('%');
statemt();
}
match('&');
}
Upvotes: 2
Views: 1182
Reputation: 310840
It would be far better to test for the statements that start with keywords first, and then fall into the assignment case if no keywords match. That way you don't need X,Y,Z as keywords:
private void statemt(){
if(token() == 'I'){
ifstmt();
}else if(token() == 'D'){
doloop();
}else if(token() == 'R'){
read();
}else if(token() == 'O'){
output();
} else {
assnmt();
}
}
I don't see any good reason for these abbrevations either in this day and age, and language.
To answer your question about the if
statement:
private void ifstatement() {
match('I');
comprsn();
match('@');
statement();
if (token() == '%') {
statement();
}
if (token() != '&') {
syntax_error("'&' expected");
}
}
To answer the second extension about {
statement ... }
, this is represented in the grammar by
statement ::= '{' statement ... '}'
and this is implemented in statement()
thus:
private void statement(){
if (token == '{') {
do {
statement();
} while (token() != '}');
} else if(token() == 'I'){
ifstmt();
}else if(token() == 'D'){
doloop();
}else if(token() == 'R'){
read();
}else if(token() == 'O'){
output();
} else {
assnmt();
}
}
Note that I'm completely ignoring the issue of when tokens get consumed, as you haven't told us how your token()
and match()
methods work.
Upvotes: 1