Last active
August 29, 2015 14:16
-
-
Save autotaker/ecbe234fd4e6f84204de to your computer and use it in GitHub Desktop.
Parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
open Parser | |
} | |
rule token = parse | |
[' ' '\t'] { token lexbuf} | |
| ['\n'] { EOL } | |
| ['0'-'9']+ { INT(int_of_string(Lexing.lexeme lexbuf)) } | |
| '+' { PLUS } | |
| '(' { LPAR } | |
| ')' { RPAR } | |
| '=' { EQ } | |
| "let" { LET } | |
| "in" { IN } | |
| ['a'-'z''A'-'Z']+ { ID(Lexing.lexeme lexbuf) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open Syntax | |
let rec string_of_expr = function | |
| Int(x) -> string_of_int x | |
| Id(x) -> x | |
| Let(x,e1,e2) -> "Let(" ^ x ^ ", " | |
^ string_of_expr e1 ^ ", " | |
^ string_of_expr e2 ^ ")" | |
| Plus(e1,e2) -> "Plus(" ^ string_of_expr e1 ^ ", " | |
^ string_of_expr e2 ^ ")" | |
;; | |
let _ = | |
let lexbuf = Lexing.from_channel stdin in | |
while true do | |
let result = Parser.main Lexer.token lexbuf in | |
print_string (string_of_expr result); | |
print_newline(); | |
flush stdout | |
done;; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%{ | |
open Syntax | |
%} | |
%token <int> INT | |
%token <string> ID | |
%token LET | |
%token IN | |
%token LPAR | |
%token RPAR | |
%token PLUS | |
%token EOL | |
%token EQ | |
%start main | |
%type <Syntax.expr> main | |
%% | |
main: | |
expr EOL { $1 } | |
expr: | |
prim { $1 } | |
| term PLUS prim { Plus($1,$3) } | |
; | |
term: | |
atom { $1 } | |
| term PLUS atom { Plus($1,$3) } | |
prim: | |
atom { $1 } | |
| LET ID EQ expr IN expr { Let ($2,$4,$6) } | |
; | |
atom: | |
INT { Int($1) } | |
| ID { Id($1) } | |
| LPAR expr RPAR { $2 } | |
; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type expr = Int of int | |
| Id of string | |
| Let of string * expr * expr | |
| Plus of expr * expr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment