annotate lab3/parser.mly @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
rev   line source
mike@0 1 /* lab3/parser.mly */
mike@0 2 /* Copyright (c) 2017 J. M. Spivey */
mike@0 3
mike@0 4 %token<string> IDENT
mike@0 5 %token<int> NUMBER
mike@0 6 %token<Keiko.op> MONOP MULOP ADDOP RELOP
mike@0 7 %token MINUS LPAR RPAR COMMA SEMI DOT ASSIGN EOF BADTOK
mike@0 8 %token BEGIN END VAR PRINT IF THEN ELSE WHILE DO PROC RETURN NEWLINE
mike@0 9
mike@0 10 %start program
mike@0 11 %type<Tree.program> program
mike@0 12
mike@0 13 %{
mike@0 14 open Keiko
mike@0 15 open Tree
mike@0 16 %}
mike@0 17
mike@0 18 %%
mike@0 19
mike@0 20 program :
mike@0 21 block DOT { Program $1 } ;
mike@0 22
mike@0 23 block :
mike@0 24 var_decl proc_decls BEGIN stmts END { Block ($1, $2, $4) } ;
mike@0 25
mike@0 26 var_decl :
mike@0 27 /* empty */ { [] }
mike@0 28 | VAR ident_list SEMI { $2 } ;
mike@0 29
mike@0 30 ident_list :
mike@0 31 IDENT { [$1] }
mike@0 32 | IDENT COMMA ident_list { $1::$3 } ;
mike@0 33
mike@0 34 proc_decls :
mike@0 35 /* empty */ { [] }
mike@0 36 | proc_decl proc_decls { $1::$2 } ;
mike@0 37
mike@0 38 proc_decl :
mike@0 39 PROC name formals SEMI block SEMI { Proc ($2, $3, $5) } ;
mike@0 40
mike@0 41 formals :
mike@0 42 LPAR RPAR { [] } ;
mike@0 43 | LPAR ident_list RPAR { $2 } ;
mike@0 44
mike@0 45 stmts :
mike@0 46 stmt_list { seq $1 } ;
mike@0 47
mike@0 48 stmt_list :
mike@0 49 stmt { [$1] }
mike@0 50 | stmt SEMI stmt_list { $1::$3 } ;
mike@0 51
mike@0 52 stmt :
mike@0 53 /* empty */ { Skip }
mike@0 54 | name ASSIGN expr { Assign ($1, $3) }
mike@0 55 | RETURN expr { Return $2 }
mike@0 56 | IF expr THEN stmts END { IfStmt ($2, $4, Skip) }
mike@0 57 | IF expr THEN stmts ELSE stmts END { IfStmt ($2, $4, $6) }
mike@0 58 | WHILE expr DO stmts END { WhileStmt ($2, $4) }
mike@0 59 | PRINT expr { Print $2 }
mike@0 60 | NEWLINE { Newline } ;
mike@0 61
mike@0 62 actuals :
mike@0 63 LPAR RPAR { [] }
mike@0 64 | LPAR expr_list RPAR { $2 } ;
mike@0 65
mike@0 66 expr_list :
mike@0 67 expr { [$1] }
mike@0 68 | expr COMMA expr_list { $1::$3 } ;
mike@0 69
mike@0 70 expr :
mike@0 71 simple { $1 }
mike@0 72 | expr RELOP simple { Binop ($2, $1, $3) } ;
mike@0 73
mike@0 74 simple :
mike@0 75 term { $1 }
mike@0 76 | simple ADDOP term { Binop ($2, $1, $3) }
mike@0 77 | simple MINUS term { Binop (Minus, $1, $3) } ;
mike@0 78
mike@0 79 term :
mike@0 80 factor { $1 }
mike@0 81 | term MULOP factor { Binop ($2, $1, $3) } ;
mike@0 82
mike@0 83 factor :
mike@0 84 NUMBER { Constant $1 }
mike@0 85 | name { Variable $1 }
mike@0 86 | name actuals { Call ($1, $2) }
mike@0 87 | MONOP factor { Monop ($1, $2) }
mike@0 88 | MINUS factor { Monop (Uminus, $2) }
mike@0 89 | LPAR expr RPAR { $2 } ;
mike@0 90
mike@0 91 name :
mike@0 92 IDENT { makeName $1 !Lexer.lineno } ;