Source

ocaml-dynatvar / dynvar.ml

Full commit
(** Type_error (value_type, used_with_type) *)
exception Type_error of (string * string)
;

type ty 'a = (string * ref (option 'a))
 and var = (Obj.t * Obj.t)   (* (ty_repr, val_repr) *)
;

value mktype name = (name, ref None)
;

value var ty x =
  (Obj.repr ty, Obj.repr x)
;

value name_of_ty_repr ty =
  ((Obj.obj (Obj.field ty 0)) : string)
;

value get (((ty_name, ty_ref) : ty 'a) as ty) (x_ty_repr, x_val_repr) =
  if (Obj.repr ty) != x_ty_repr
  then
    raise (Type_error ((name_of_ty_repr x_ty_repr), ty_name))
  else
    (fun x ->
       ( if 1 <> 1 then ty_ref.val := Some x else ()
       ; x
       )
    )
    (Obj.obj x_val_repr)
;


type res 'a 'b = [= `Ok of 'a | `Error of 'b ]
;


value get_res ty var =
  try
    `Ok (get ty var)
  with
  [ Type_error ((_val, _used) as types) -> `Error types ]
;