Getting the environment from the AST in .cmt


I am using the Typedtree type from 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.

I made a minimal example:
Do you have an idea of how to get an Env.t from a .cmt? Is this possible? Thanks!

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.

1 Like

OK thanks for the quick answer, trying it!

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) = 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 ())
  | _ -> failwith "Cannot extract cmt data."

;;get_initial_env "example.cmt";
print_endline "success!"

Thanks a lot!