You are on page 1of 5

NAME: Alok Patel

REG.NO: 21BPS1349
COURSE Code: BCSE307P
COURSE Title: Compiler Design
LAB SLOT: L13+L14
DATE: 19-03-2024

LAB-07
Parser generator
Installation and Successful compilation of CUP and parser.cup
Modified and Compiled Parser Generator
After edits:
Modified Parser CUP Source Code:
What is different: a new rule that allows for expressions to be negated using an
exclamationmark, which we will arbitrarily define as a logical negation
operation
1. Add a new terminal for the exclamation mark (logical NOT operator).

2. Define new production rules that use this operator.

3. Update the parser actions to compute the result of the


negated expression.

4. /* Simple +/-/*// expression language with bitwise NOT operation; parser


evaluates constant expressions on the fly */
5. package cupexample;
6. import java_cup.runtime.*; 7.
8. parser code {:
9. // Connect this parser to a scanner!
10. Lexer lexer;
11. Parser(Lexer lexer){ this.lexer=lexer; } 12.:}
13.
14. /* Define how to connect to the scanner! */
15. init with {: lexer.init(); :};
16. scan with {: return lexer.nextToken(); :}; 17.
18. /* Terminals (tokens returned by the scanner). */
19. terminal SEMI, PLUS, MINUS, TIMES, DIVIDE, UMINUS, LPAREN, RPAREN, BNOT;
20. terminal Integer NUMBER; // our scanner provides numbers as
integers 21.
22. /* Non terminals */
23. non terminal expr_list;
24. non terminal Integer expr; // used to store evaluated
subexpressions 25.
26. /* Precedences */
27. precedence left PLUS, MINUS;
28. precedence left TIMES, DIVIDE;
29. precedence left UMINUS;
30. precedence left BNOT; 31.
32. /* The grammar rules */
33. expr_list ::= expr_list expr:e SEMI {: System.out.println("Result: " + e); :}
34. | expr:e SEMI {: System.out.println("Result: " + e); :}
35.;
36. expr ::= expr:e1 PLUS expr:e2 {: RESULT = e1 + e2; :}
37. | expr:e1 MINUS expr:e2 {: RESULT = e1 - e2; :}
38. | expr:e1 TIMES expr:e2 {: RESULT = e1 * e2; :}
39. | expr:e1 DIVIDE expr:e2 {: RESULT = e2 != 0 ? e1 / e2
: 0; :}
40. | MINUS expr:e {: RESULT = -e; :}
41. %prec UMINUS
42. | BNOT expr:e {: RESULT = ~e;:} // Bitwise NOT operation on expression
43. %prec BNOT
44. | LPAREN expr:e RPAREN {: RESULT = e; :}
45. | NUMBER:n {: RESULT = n; :}
46. ;

You might also like