compiler and vm: implemented add
This commit is contained in:
@@ -202,3 +202,4 @@ let compile (exprs : expression list) (tbl : (int * expression) SymbolTable.t) =
|
|||||||
let compile_src src =
|
let compile_src src =
|
||||||
let* (exprs, tbl) = Scope_analysis.of_src src in
|
let* (exprs, tbl) = Scope_analysis.of_src src in
|
||||||
compile exprs tbl
|
compile exprs tbl
|
||||||
|
|
||||||
|
|||||||
@@ -57,8 +57,8 @@ type expression =
|
|||||||
*)
|
*)
|
||||||
let default_global_table =
|
let default_global_table =
|
||||||
SymbolTable.of_list [
|
SymbolTable.of_list [
|
||||||
("print", (0, Native 0));
|
("PRINT", (0, Native 0));
|
||||||
("add", (1, Native 1))
|
("ADD", (1, Native 1))
|
||||||
]
|
]
|
||||||
|
|
||||||
(* extract all defined global symbols, given the top-level expressions
|
(* extract all defined global symbols, given the top-level expressions
|
||||||
|
|||||||
+27
-1
@@ -5,12 +5,38 @@
|
|||||||
*)
|
*)
|
||||||
open Types
|
open Types
|
||||||
|
|
||||||
|
type numeric_val =
|
||||||
|
| NInt of int
|
||||||
|
| NDouble of float
|
||||||
|
|
||||||
|
let to_numeric = function
|
||||||
|
| Int x -> NInt x
|
||||||
|
| Double x -> NDouble x
|
||||||
|
| v -> failwith ((print_value v) ^ " is not a numeric value")
|
||||||
|
let of_numeric = function
|
||||||
|
| NInt x -> Int x
|
||||||
|
| NDouble x -> Double x
|
||||||
|
let numeric_add = function
|
||||||
|
| NInt x -> (function
|
||||||
|
| NInt y -> NInt (x+y)
|
||||||
|
| NDouble y -> NDouble ((float_of_int x) +. y))
|
||||||
|
| NDouble x -> (function
|
||||||
|
| NInt y -> NDouble (x+.(float_of_int y))
|
||||||
|
| NDouble y -> NDouble (x+.y))
|
||||||
|
|
||||||
|
|
||||||
let builtin_print (v : Types.value ref list) =
|
let builtin_print (v : Types.value ref list) =
|
||||||
List.iter (fun r -> print_endline (print_value !r)) v;
|
List.iter (fun r -> print_endline (print_value !r)) v;
|
||||||
Types.Nil
|
Types.Nil
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
let builtin_add (vs : Types.value ref list) =
|
||||||
|
of_numeric (List.fold_left numeric_add (NInt 0) (List.map (fun r -> to_numeric !r) vs))
|
||||||
|
|
||||||
let table = [|
|
let table = [|
|
||||||
builtin_print
|
builtin_print;
|
||||||
|
builtin_add
|
||||||
|]
|
|]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -52,7 +52,7 @@ let rec do_apply state arg_count =
|
|||||||
| _ -> failwith "Cannot apply non-closure object"
|
| _ -> failwith "Cannot apply non-closure object"
|
||||||
|
|
||||||
and interpret state =
|
and interpret state =
|
||||||
(*trace state; (* For debug use *)*)
|
(*trace state; (*For debug use only*)*)
|
||||||
let i = state.i in
|
let i = state.i in
|
||||||
state.i <- i + 1;
|
state.i <- i + 1;
|
||||||
(match state.instrs.(i) with
|
(match state.instrs.(i) with
|
||||||
|
|||||||
Reference in New Issue
Block a user