annotate lab2/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 /* lab2/parser.mly */
mike@0 2 /* Copyright (c) 2017 J. M. Spivey */
mike@0 3
mike@0 4 %{
mike@0 5 open Keiko
mike@0 6 open Dict
mike@0 7 open Tree
mike@0 8 %}
mike@0 9
mike@0 10 %token <Dict.ident> IDENT
mike@0 11 %token <Keiko.op> MULOP ADDOP RELOP MONOP
mike@0 12 %token <int> NUMBER BOOLCONST
mike@0 13
mike@0 14 /* punctuation */
mike@0 15 %token SEMI DOT COLON LPAR RPAR COMMA
mike@0 16 %token EQUAL MINUS ASSIGN EOF BADTOK
mike@0 17 %token SUB BUS
mike@0 18
mike@0 19 /* keywords */
mike@0 20 %token BEGIN DO ELSE END IF
mike@0 21 %token THEN VAR WHILE PRINT NEWLINE
mike@0 22 %token ARRAY OF
mike@0 23 %token INTEGER BOOLEAN
mike@0 24
mike@0 25 %type <Tree.program> program
mike@0 26
mike@0 27 %start program
mike@0 28
mike@0 29 %%
mike@0 30
mike@0 31 program :
mike@0 32 decls BEGIN stmts END DOT { Program ($1, $3) } ;
mike@0 33
mike@0 34 decls :
mike@0 35 /* empty */ { [] }
mike@0 36 | decl decls { $1 :: $2 }
mike@0 37
mike@0 38 decl :
mike@0 39 VAR name_list COLON typexp SEMI { Decl ($2, $4) } ;
mike@0 40
mike@0 41 name_list :
mike@0 42 name { [$1] }
mike@0 43 | name COMMA name_list { $1 :: $3 } ;
mike@0 44
mike@0 45 typexp :
mike@0 46 INTEGER { Integer }
mike@0 47 | BOOLEAN { Boolean }
mike@0 48 | ARRAY NUMBER OF typexp { Array ($2, $4) } ;
mike@0 49
mike@0 50 stmts :
mike@0 51 stmt_list { seq $1 } ;
mike@0 52
mike@0 53 stmt_list :
mike@0 54 stmt { [$1] }
mike@0 55 | stmt SEMI stmt_list { $1 :: $3 } ;
mike@0 56
mike@0 57 stmt :
mike@0 58 /* empty */ { Skip }
mike@0 59 | variable ASSIGN expr { Assign ($1, $3) }
mike@0 60 | PRINT expr { Print $2 }
mike@0 61 | NEWLINE { Newline }
mike@0 62 | IF expr THEN stmts END { IfStmt ($2, $4, Skip) }
mike@0 63 | IF expr THEN stmts ELSE stmts END { IfStmt ($2, $4, $6) }
mike@0 64 | WHILE expr DO stmts END { WhileStmt ($2, $4) } ;
mike@0 65
mike@0 66 expr :
mike@0 67 simple { $1 }
mike@0 68 | expr RELOP simple { makeExpr (Binop ($2, $1, $3)) }
mike@0 69 | expr EQUAL simple { makeExpr (Binop (Eq, $1, $3)) } ;
mike@0 70
mike@0 71 simple :
mike@0 72 term { $1 }
mike@0 73 | simple ADDOP term { makeExpr (Binop ($2, $1, $3)) }
mike@0 74 | simple MINUS term { makeExpr (Binop (Minus, $1, $3)) } ;
mike@0 75
mike@0 76 term :
mike@0 77 factor { $1 }
mike@0 78 | term MULOP factor { makeExpr (Binop ($2, $1, $3)) }
mike@0 79
mike@0 80 factor :
mike@0 81 variable { $1 }
mike@0 82 | NUMBER { makeExpr (Constant ($1, Integer)) }
mike@0 83 | BOOLCONST { makeExpr (Constant ($1, Boolean)) }
mike@0 84 | MONOP factor { makeExpr (Monop ($1, $2)) }
mike@0 85 | MINUS factor { makeExpr (Monop (Uminus, $2)) }
mike@0 86 | LPAR expr RPAR { $2 } ;
mike@0 87
mike@0 88 variable :
mike@0 89 name { makeExpr (Variable $1) }
mike@0 90 | variable SUB expr BUS { makeExpr (Sub ($1, $3)) } ;
mike@0 91
mike@0 92 name :
mike@0 93 IDENT { makeName $1 !Lexer.lineno } ;