Parse multiple Reason statements to OCaml (;; issue)


#1

I have a function which takes a string of Reason code and transforms it into a string of OCaml code:

let ocaml_from_reason str =
        let open Ast_404.Parsetree in
        let phrases = Lexing.from_string str |> Reason_toolchain.RE.use_file in
        List.iter (function
            | Ptop_def str ->
            Reason_toolchain.ML.print_implementation_with_comments Format.str_formatter ( str, [] )) phrases;
        Format.flush_str_formatter ()

I am trying to parse multiple Reason statements via RE.use_file and iterate through each statement and print each toplevel_phrase with ML.print_implementation_with_comment … which kinda works, but as a result I get:

/* Reason input */
let a = 1 + 1;
let b = a + 2;

Which results in the (faulty) output:

(* OCaml output *)
let a = 1 + 1let b = a + 2

So it drops the ;; for each toplevel expression… I guess i need to add some functionality to the Reason printer to make this work?


#2

I’m not sure if it would fit your needs in this case, but ocamlformat has a Reason -> OCaml syntax tool. It’s pretty closely tied to ocamlformat’s internals but there may still be pieces there worth using: https://github.com/ocaml-ppx/ocamlformat/blob/master/src/ocamlformat_reason.ml


#3

Hah, I didn’t know ocamlformat also does Reason formatting…
Anyways, I found out that my general idea of having a ocaml_from_reason function was flawed… I took a different approach, which is, generating a parsetree via the appropriate use_file function and execute the parsed toplevel_phrases over the general interface:

let lex = Lexing.from_string str in
  let tpl_phrases = match lang with
    | OCaml -> Parse.use_file lex
    | Reason ->
      List.map Reason_toolchain.To_current.copy_toplevel_phrase (Reason_toolchain.RE.use_file lex)
    in
    ...