CAP/TP02/ariteval/Arit.g4

54 lines
914 B
Plaintext
Raw Permalink Normal View History

2024-09-23 11:04:28 +02:00
grammar Arit;
// MIF08@Lyon1 and CAP@ENSL, arit evaluator
@header {
# header - mettre les déclarations globales
import sys
idTab = {};
class UnknownIdentifier(Exception):
pass
class DivByZero(Exception):
pass
2024-09-30 14:32:21 +02:00
def checkID(s):
if s not in idTab:
raise UnknownIdentifier(s)
def getID(s):
try:
return idTab[s]
except IndexError:
raise UnknownIdentifier(s)
2024-09-23 11:04:28 +02:00
}
2024-09-30 14:32:21 +02:00
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}
;
2024-09-23 11:04:28 +02:00
COMMENT
: '//' ~[\r\n]* -> skip
;
ID : ('a'..'z'|'A'..'Z')+;
INT: '0'..'9'+;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines