A PL/0 Interpreter implemented in Python
The grammar is based on wikipedia's PL/0 page.
program = block "." ;
block = [ "const" ident "=" number {"," ident "=" number} ";"]
[ "var" ident {"," ident} ";"]
{ "procedure" ident ";" block ";" } statement ;
statement = [ ident ":=" expression | "call" ident
| "?" ident | "!" expression
| "begin" statement {";" statement } "end"
| "if" condition "then" statement
| "while" condition "do" statement ];
condition = "odd" expression |
expression ("="|"#"|"<"|"<="|">"|">=") expression ;
expression = [ "+"|"-"] term { ("+"|"-") term};
term = factor {("*"|"/") factor};
factor = ident | number | "(" expression ")";
Note: Keywords are case-insensitive in this implementation.
const
: declares constantsvar
: declares variablesprocedure
: declares a procedurecall
: calls a procedurebegin
: composite statementsend
: composite statements endsif
: conditional statement conditionthen
: conditional statement bodywhile
: loop statement conditiondo
: loop statement bodyodd
: condition operator, returns true if the expression is odd
+
,-
: unary operators+
,-
,*
,/
: arithmetic operators=
,#
,<
,<=
,>
,>=
: comparison operators:=
: assignment operator?
: input operator!
: output operator;
: statement separator,
: variable separator(
,)
: parenthesis.
: program end
- Lexer: converts source code into tokens
- Parser: converts tokens into an AST
- ASTInterpreter: interprets the AST
- IR Generator: generates an IR from the AST
- IR Interpreter: interprets the IR
TODO
To test a certain program, either use pytest to run the test file (not covering a lot) or run the following command:
python3.11 <path-to-program> <path-to-input>
and the output will be printed to the console.