From 2be0b7f794239c92141842717b76b364914e21d4 Mon Sep 17 00:00:00 2001 From: Hyeonung Baek Date: Fri, 21 Jan 2022 00:17:01 +0900 Subject: [PATCH] Add let --- ast.ml | 5 +++++ eval.ml | 4 ++++ parser.ml | 17 +++++++++++++++++ token.ml | 2 ++ 4 files changed, 28 insertions(+) diff --git a/ast.ml b/ast.ml index 0f19d60..ae18fa3 100644 --- a/ast.ml +++ b/ast.ml @@ -99,6 +99,7 @@ end type t = | Value of Value.t | Var of string + | Let of string * t | Binop of t * Binop.t * t | Set_binop_pre of Binop.t * t | Get_binop_pre of Binop.t @@ -117,6 +118,10 @@ let print ast = let rec aux = function | Value n -> pv n | Var v -> pr "%s" v + | Let (v, e) -> + pr "(let %s " v; + aux e; + pr ")" | Binop (left, op, right) -> begin let op = Binop.to_string op in pr "(%s " op; aux left; pr " "; aux right; pr ")"; diff --git a/eval.ml b/eval.ml index 6f2bd25..51b071b 100644 --- a/eval.ml +++ b/eval.ml @@ -31,6 +31,10 @@ let eval vars ast = | Binop (l, op, r) -> let l = aux l and r = aux r in binop op l r + | Let (var, e) -> + let v = aux e in + Hashtbl.replace vars var v; + v | Set_binop_pre (op, l) -> let l = match aux l with diff --git a/parser.ml b/parser.ml index 40d1246..1492822 100644 --- a/parser.ml +++ b/parser.ml @@ -78,6 +78,14 @@ let token tok seq = if x = tok then x, seq else expected @@ Token.to_string tok +let any_ident seq = + match seq () with + | Seq.Nil -> expected "ident" + | Seq.Cons (x, seq) -> begin match x with + | Token.Ident id -> id, seq + | _ -> unexpected_token x + end + let idents set seq = match seq () with | Seq.Nil -> @@ -122,6 +130,7 @@ let rec expr pre seq = seq |> oneof [ level; assoc; + let_value; value @> binop pre; ] @@ -151,6 +160,14 @@ and assoc seq = else failwith "Parser.assoc" +(* let_value := "let" ident "=" expr *) +and let_value seq = + let _, seq = ident "let" seq in + let id, seq = any_ident seq in + let _, seq = token Token.Equal seq in + let e, seq = expr min_int seq in + Let (id, e), seq + (* value := int | float | ( expr ) *) and value seq = match seq () with diff --git a/token.ml b/token.ml index 1e83fc8..3647f3c 100644 --- a/token.ml +++ b/token.ml @@ -10,6 +10,7 @@ type t = | Percent | LParen | RParen + | Equal let tokens = ref [ "+", Plus; @@ -20,6 +21,7 @@ let tokens = ref [ "%", Percent; "(", LParen; ")", RParen; + "=", Equal; ] let to_string = function