Skip to content

Commit

Permalink
Add semantic actions to the grammar
Browse files Browse the repository at this point in the history
The terminal symbol for literal number and the non terminal symbols receives a semantic value of type Double, corresponding to their value when evaluated. The semantic actions evaluate the operations indicated in each production rule, calculating the semantic value of the symbol in its left hand side. At the end the start symbol semantic value is the value of the whole expression.
  • Loading branch information
romildo committed Oct 9, 2016
1 parent a5321a6 commit 6955046
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
28 changes: 14 additions & 14 deletions src/main/cup/parser.cup
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,29 @@ parser code {:
}
:};

terminal LITNUM;
terminal PLUS, MINUS, TIMES, DIV;
terminal LPAREN, RPAREN;
terminal Double LITNUM;
terminal PLUS, MINUS, TIMES, DIV;
terminal LPAREN, RPAREN;

non terminal exp;
non terminal term;
non terminal factor;
non terminal Double exp;
non terminal Double term;
non terminal Double factor;

start with exp;

exp ::=
exp PLUS term
| exp MINUS term
| term
exp:x PLUS term:y {: RESULT = x + y; :}
| exp:x MINUS term:y {: RESULT = x - y; :}
| term:x {: RESULT = x; :}
;

term ::=
| term TIMES factor
| term DIV factor
| factor
| term:x TIMES factor:y {: RESULT = x * y; :}
| term:x DIV factor:y {: RESULT = x / y; :}
| factor:x {: RESULT = x; :}
;

factor ::=
LITNUM
| LPAREN exp RPAREN
LITNUM:x {: RESULT = x; :}
| LPAREN exp:x RPAREN {: RESULT = x; :}
;
3 changes: 2 additions & 1 deletion src/main/java/main/Driver.java
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ public static void lexicalAnalysis(Reader input) throws IOException {
public static void syntaxAnalysis(Reader input) throws Exception {
Lexer lexer = new Lexer(input);
parser parser = new parser(lexer);
parser.parse();
Symbol result = parser.parse();
System.out.println(result.value);
}

}

0 comments on commit 6955046

Please sign in to comment.