Skip to content

Instantly share code, notes, and snippets.

@ytomino
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytomino/d3cff860d30d894dca1b to your computer and use it in GitHub Desktop.
Save ytomino/d3cff860d30d894dca1b to your computer and use it in GitHub Desktop.
Use the toplevel pretty-printer from source code
(* ocaml -I `ocamlc -where`/compiler-libs ocamlcommon.cma toplevelpp.ml *)
module L = Longident;;
let print_value long_id value =
let env = !Toploop.toplevel_env in
let value_path, value_desc = Env.lookup_value long_id env in
Toploop.print_value
env
(Obj.repr value)
Format.std_formatter
value_desc.Types.val_type;;
let x = 100;;
Format.pp_print_string Format.std_formatter "x = ";;
print_value (L.Lident "x") x;;
Format.pp_print_newline Format.std_formatter ();;
let y = "abc", "def";;
Format.pp_print_string Format.std_formatter "y = ";;
print_value (L.Lident "y") y;;
Format.pp_print_newline Format.std_formatter ();;
let z = 1234L;;
Format.pp_print_string Format.std_formatter "z = ";;
print_value (L.Lident "z") z;;
Format.pp_print_newline Format.std_formatter ();;
type complex = {re: float; im: float};;
let dummy_for_pp = {re = 0.0; im = 0.0};; (* dummy *)
let outer () =
let local = {re = 3.14; im = 99.9} in
Format.pp_print_string Format.std_formatter "z = ";
(* print_value (L.Lident "local") local; *) (* <- error *)
assert (dummy_for_pp == local || true); (* type checking *)
print_value (L.Lident "dummy_for_pp") local; (* use type_expr of global value *)
Format.pp_print_newline Format.std_formatter ()
in outer ();;
(* expected output:
x = 100
y = ("abc", "def")
z = 1234L
z = {re = 3.14; im = 99.9}
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment