I am using the Typedtree type from https://github.com/ocaml/ocaml/blob/trunk/typing/typedtree.mli to access to the OCaml AST generated by the compiler. I would like to inspect the environment (type Env.t), for example search for elements using the Env.find_modtype function. I am getting the AST from compiled .cmt files.
The problem: the environment extracted from the .cmt only contains a summary, thus lookup functions always return “not found”. By applying Envaux.env_of_only_summary I was expecting to retrieve the full environment, but it fails saying that Pervasives (or Stdlib) is not found.
You’ll also need to setup the load path properly before you can use env_of_only_summary.
You can find the compilation load path in the cmt_loadpath field of the cmt.
I confirm that it works, adding Config.load_path := cmt_loadpath; to configure the loading path:
let get_initial_env (file_name : string) : Env.t =
let (_, cmt) = Cmt_format.read file_name in
match cmt with
| Some { Cmt_format.cmt_initial_env = env; cmt_loadpath } ->
Config.load_path := cmt_loadpath;
(* We call [env_of_only_summary] else the environment is empty
(contains only the summary) and cannot be searched.
*)
begin try Envaux.env_of_only_summary env with
| Envaux.Error error ->
Envaux.report_error Format.str_formatter error;
failwith (Format.flush_str_formatter ())
end
| _ -> failwith "Cannot extract cmt data."
;;get_initial_env "example.cmt";
print_endline "success!"