diff --git a/TP02/ariteval/Arit.g4 b/TP02/ariteval/Arit.g4 index 53e1d98..775eb97 100644 --- a/TP02/ariteval/Arit.g4 +++ b/TP02/ariteval/Arit.g4 @@ -13,9 +13,35 @@ class UnknownIdentifier(Exception): class DivByZero(Exception): pass +def checkID(s): + if s not in idTab: + raise UnknownIdentifier(s) + +def getID(s): + try: + return idTab[s] + except IndexError: + raise UnknownIdentifier(s) + } -prog: ID {print("prog = "+str($ID.text));} ; +prog: e0=expr EOF {print($e0.text, "=>", $e0.val)}; + +expr returns [int val]: + | e=expr '+' t=term {$val = $e.val + $t.val} + | t=term {$val = $t.val} + ; + +term returns [int val]: + | t=term '*' f=fxpr {$val = $t.val * $f.val} + | f=fxpr {$val = $f.val} + ; + +fxpr returns [int val]: + | ID {$val = getID($ID.text)} + | INT {$val = int($INT.text)} + | '(' e=expr ')' {$val = $e.val} + ; COMMENT diff --git a/TP02/demo_files/ex1/Example1.g4 b/TP02/demo_files/ex1/Example1.g4 index 0f526a4..05a6dd5 100644 --- a/TP02/demo_files/ex1/Example1.g4 +++ b/TP02/demo_files/ex1/Example1.g4 @@ -4,6 +4,8 @@ lexer grammar Example1; OP : '+'| '*' | '-' | '/' ; DIGIT : [0-9] ; +LPAR : '(' ; +RPAR : ')' ; LETTER : [A-Za-z] ; ID : LETTER (LETTER | DIGIT)* ; // match idents WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines diff --git a/TP02/python/typecheck.py b/TP02/python/typecheck.py index 58f8288..2761421 100644 --- a/TP02/python/typecheck.py +++ b/TP02/python/typecheck.py @@ -2,7 +2,7 @@ # name: type int_variable: int float_variable: float -int_variable = 4.2 # Static typing error, but no runtime error +int_variable = 4 # Static typing error, but no runtime error float_variable = 42.0 # OK float_variable = int_variable # OK @@ -12,5 +12,4 @@ def int_to_string(i: int) -> str: return str(i) -print(int_to_string('Hello')) # Static typing error, but no runtime error -print(int_to_string(42) / 5) # Both static and runtime error +print(int_to_string(42)) # Both static and runtime error