Skip to content

Instantly share code, notes, and snippets.

@autotaker
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save autotaker/ecbe234fd4e6f84204de to your computer and use it in GitHub Desktop.
Save autotaker/ecbe234fd4e6f84204de to your computer and use it in GitHub Desktop.
Parsing
{
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) }
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;;
%{
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 }
;
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