54 lines
914 B
ANTLR
54 lines
914 B
ANTLR
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
|
|
|
|
def checkID(s):
|
|
if s not in idTab:
|
|
raise UnknownIdentifier(s)
|
|
|
|
def getID(s):
|
|
try:
|
|
return idTab[s]
|
|
except IndexError:
|
|
raise UnknownIdentifier(s)
|
|
|
|
}
|
|
|
|
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
|
|
: '//' ~[\r\n]* -> skip
|
|
;
|
|
|
|
ID : ('a'..'z'|'A'..'Z')+;
|
|
INT: '0'..'9'+;
|
|
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
|