Update TP02

This commit is contained in:
augustin64 2024-09-30 14:32:21 +02:00
parent c527169d0d
commit 10f533808c
3 changed files with 31 additions and 4 deletions

View File

@ -13,9 +13,35 @@ class UnknownIdentifier(Exception):
class DivByZero(Exception): class DivByZero(Exception):
pass 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 COMMENT

View File

@ -4,6 +4,8 @@ lexer grammar Example1;
OP : '+'| '*' | '-' | '/' ; OP : '+'| '*' | '-' | '/' ;
DIGIT : [0-9] ; DIGIT : [0-9] ;
LPAR : '(' ;
RPAR : ')' ;
LETTER : [A-Za-z] ; LETTER : [A-Za-z] ;
ID : LETTER (LETTER | DIGIT)* ; // match idents ID : LETTER (LETTER | DIGIT)* ; // match idents
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

View File

@ -2,7 +2,7 @@
# name: type # name: type
int_variable: int int_variable: int
float_variable: float 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 = 42.0 # OK
float_variable = int_variable # OK float_variable = int_variable # OK
@ -12,5 +12,4 @@ def int_to_string(i: int) -> str:
return str(i) return str(i)
print(int_to_string('Hello')) # Static typing error, but no runtime error print(int_to_string(42)) # Both static and runtime error
print(int_to_string(42) / 5) # Both static and runtime error