From 69550462d0fc7e55d6d268f8bdb10b6f18a23bc9 Mon Sep 17 00:00:00 2001 From: romildo Date: Sun, 9 Oct 2016 07:10:44 -0300 Subject: [PATCH] Add semantic actions to the grammar 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. --- src/main/cup/parser.cup | 28 ++++++++++++++-------------- src/main/java/main/Driver.java | 3 ++- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/main/cup/parser.cup b/src/main/cup/parser.cup index bd4ece4..e8d46c9 100644 --- a/src/main/cup/parser.cup +++ b/src/main/cup/parser.cup @@ -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; :} ; diff --git a/src/main/java/main/Driver.java b/src/main/java/main/Driver.java index da1f1f3..d89fd06 100644 --- a/src/main/java/main/Driver.java +++ b/src/main/java/main/Driver.java @@ -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); } }