TigerインタプリタでUnitを扱いたい
#OCaml
from タイガーブック
Unit () を返せるようにした。
code:diff
diff --git a/bin/main.ml b/bin/main.ml
index d54652e..c2ad7d7 100644
--- a/bin/main.ml
+++ b/bin/main.ml
@@ -14,8 +14,7 @@ let () =
match args with
| Tiger.Eval.StringVal(s) ->
print_string s;
- (* NOTE: 本当は unit を返したいけどまだ未実装なので 0 を返してる *)
- Tiger.Eval.IntVal(0)
+ Tiger.Eval.UnitVal
| _ -> failwith "invalid arguments"
))
] in
diff --git a/lib/eval.ml b/lib/eval.ml
index d759c21..e1d7083 100644
--- a/lib/eval.ml
+++ b/lib/eval.ml
@@ -3,6 +3,7 @@ and table = (id * val_t) list
and val_t =
IntVal of int
| StringVal of string
+ | UnitVal
| FunctionDec of id list * Syntax.t
| BuiltInFunction of (val_t list -> table -> val_t)
@@ -10,6 +11,7 @@ let rec f expr env: val_t * table =
match expr with
| Syntax.IntExp n -> (IntVal n, env)
| Syntax.StringExp s -> (StringVal s, env)
+ | Syntax.UnitExp -> (UnitVal, env)
| Syntax.VarExp s -> (List.assoc s env, env)
| Syntax.LetExp { decs; body } ->
let new_env = List.fold_left
@@ -24,7 +26,7 @@ let rec f expr env: val_t * table =
| IntVal 0 ->
(match else' with
| Some else' -> f else' env
- | None -> (IntVal 0, env))
+ | None -> (UnitVal, env))
| _ -> failwith "type error")
| Syntax.CallExp { id; args } ->
(let func = List.assoc id env in
@@ -103,6 +105,7 @@ and string_of_val v =
match v with
IntVal n -> string_of_int n
| StringVal s -> s
+ | UnitVal -> "()"
| FunctionDec _ -> "<fun>"
| BuiltInFunction _ -> "<builtin>"
diff --git a/lib/parser.mly b/lib/parser.mly
index 4040da7..32f4a41 100644
--- a/lib/parser.mly
+++ b/lib/parser.mly
@@ -40,6 +40,7 @@ program: exp EOF { $1 }
exp:
INT { Syntax.IntExp($1) }
| STRING { Syntax.StringExp($1) }
+| LPAREN RPAREN { Syntax.UnitExp }
| ID { Syntax.VarExp($1) }
| LPAREN exp RPAREN { $2 }
| exp PLUS exp { Syntax.OpExp { left = $1; op = Syntax.PlusOp; right = $3} }
diff --git a/lib/syntax.ml b/lib/syntax.ml
index fdbabc8..4ce1f99 100644
--- a/lib/syntax.ml
+++ b/lib/syntax.ml
@@ -15,6 +15,7 @@ and op_t =
and t =
| IntExp of int (* 整数 *)
| StringExp of string (* 文字列 *)
+ | UnitExp (* ユニット *)
| LetExp of { decs: dec_t list; body: t }
| VarExp of string
| CallExp of { id: string; args: t list } (* 関数呼び出し *)
diff --git a/test/tiger_test.ml b/test/tiger_test.ml
index ea6f020..2a32255 100644
--- a/test/tiger_test.ml
+++ b/test/tiger_test.ml
@@ -12,8 +12,7 @@ let eval src =
match args with
| Tiger.Eval.StringVal(s) ->
print_string s;
- (* NOTE: 本当は unit を返したいけどまだ未実装なので 0 を返してる *)
- Tiger.Eval.IntVal(0)
+ Tiger.Eval.UnitVal
| _ -> failwith "invalid arguments"
))
]