mlox/lib/value.ml

49 lines
1.4 KiB
OCaml
Raw Normal View History

2024-08-28 17:17:17 +02:00
type lox_function = {
name : string;
2024-08-28 23:58:55 +02:00
env : environment;
2024-08-28 17:17:17 +02:00
arity : int;
arg_names : string list;
2024-08-29 02:57:58 +02:00
body : Stmt.stmt_node;
2024-08-28 17:17:17 +02:00
}
2024-08-28 23:58:55 +02:00
and native_function = {
2024-08-28 17:17:17 +02:00
name : string;
arity : int;
fn : lox_value list -> (lox_value, string) result;
}
and lox_value =
| Function of lox_function
| NativeFunction of native_function
| String of string
| Number of float
| Bool of bool
| Nil
2024-08-28 23:58:55 +02:00
and env_table = (string, lox_value) Hashtbl.t
and environment = { globals : env_table ref; locals : env_table list }
let string_of_lox_value lox_value =
match lox_value with
| Function { name; arity; _ } -> Printf.sprintf "<fn %s/%d>" name arity
| NativeFunction { name; arity; _ } -> Printf.sprintf "<native fn %s/%d>" name arity
| String s -> s
| Number x -> if Float.is_integer x then string_of_int (Int.of_float x) else string_of_float x
| Bool b -> string_of_bool b
| Nil -> "nil"
let type_string_of_lox_value lox_value =
match lox_value with
| Function _ -> "Function"
| NativeFunction _ -> "NativeFunction"
| String _ -> "String"
| Number _ -> "Number"
| Bool _ -> "Bool"
| Nil -> "Nil"
2024-08-26 17:26:59 +02:00
2024-08-28 17:17:17 +02:00
let lox_value_to_bool lox_value = match lox_value with Bool b -> b | Nil -> false | _ -> true
2024-08-28 23:58:55 +02:00
let make_lox_function (name : string) (env : environment) (arg_names : string list)
(body : Stmt.stmt_node) : lox_value =
2024-08-28 17:17:17 +02:00
let arity = List.length arg_names in
2024-08-28 23:58:55 +02:00
Function { name; env; arity; arg_names; body }