open Import let pp ppf (_ : Sast.arith_expr) = Fmt.pf ppf "TODO" let exec_op = function | Sast.Add -> Int.add | Sub -> Int.sub | Mul -> Int.mul | Div -> Int.div | Mod -> ( mod ) | Lt -> fun a b -> if a < b then 1 else 0 | Gt -> fun a b -> if a > b then 1 else 0 | Eq -> fun a b -> if Int.equal a b then 1 else 0 (* Faster way: extract the logic from morbig directly for parsing variables. *) let collect_variables v = let o = object inherit [Sast.variable list] Ast.fold method int _ ctx = ctx method bool _ ctx = ctx method string _ ctx = ctx method char _ ctx = ctx method option f v ctx = Option.fold ~none:ctx ~some:(fun i -> f i ctx) v method nlist__t f v ctx = Nlist.fold_left (fun acc i -> f i acc) ctx v method nslist__t f g v ctx = Nslist.fold_left (fun acc a b -> f a acc |> g b) ctx v method list f v ctx = List.fold_left (fun acc i -> f i acc) ctx v method! variable v ctx = v :: ctx end in o#complete_commands v [] let parse_variable s = let cst = Morbig.parse_string "arith" s in let vars = Ast.of_program cst |> collect_variables in let v = match vars with | [ v ] -> v | vs -> Fmt.failwith "Unexpected number of variables: %i" (List.length vs) in v module Make (S : Types.State) = struct let eval ~expand initial_state expr = let exception Abort of Trace.t * int in let lookup (trace, state) s = let v = match String.get ~label:"arith-eval" s 0 with | '$' -> parse_variable s | (exception _) | _ -> Sast.VariableAtom (s, Sast.NoAttribute) in let r, es = expand state ~param:v in let t = es @ trace in match r with | Some n when Option.is_some (int_of_string_opt n) -> (t, int_of_string n) | None | Some "" -> (t, 0) | Some _ -> raise (Abort (t, 0)) in let update state s i = match S.update state ~param:s [ Ast.Fragment.make (string_of_int i) ] with | Ok s, t -> (s, t) | Error m, _ -> failwith m in let rec calc ((trace, state) : Trace.t * S.t) = function | Sast.Int i -> (trace, state, i) | Var v -> let t, i = lookup (trace, state) v in (t, state, i) | Binop (op, e1, e2) -> let t, state, v1 = calc (trace, state) e1 in let t, state, v2 = calc (t, state) e2 in (t, state, exec_op op v1 v2) | Neg n -> let t, state, v1 = calc (trace, state) n in (t, state, Int.neg v1) | Assign (op, var, e) -> let t, current_v = lookup (trace, state) var in let t, state, v1 = calc (t, state) e in let nv = exec_op op current_v v1 in let v, e = update state var nv in (e :: t, v, nv) | Ternary (e1, e2, e3) -> let t, state, v1 = calc (trace, state) e1 in if Int.equal v1 Int.zero then calc (t, state) e3 else calc (t, state) e2 in try calc (Trace.empty, initial_state) expr with Abort (t, n) -> (t, initial_state, n) end