Getting parse tree from source code string in Poly/ML

309 views Asked by At

I am trying to compile a string of source code and print the parse tree using Poly/ML. The following code compiles, but the parse tree is empty:

fun main () =
    let
        val stream = TextIO.openString "let val a = \"abc\"; val b = \"def\"; val c = a ^ b in print c end";
        val _ = PolyML.compiler (fn () => TextIO.input1 stream, []);
        val (_, parseTree) = !PolyML.IDEInterface.parseTree
    in
        PolyML.print (parseTree);
        PolyML.print (List.length parseTree);
        List.map PolyML.print (parseTree);
        ()
    end

Running this:

$ ./a.out
[...]
0
$

What do I need to do to get the parse tree from the compiler? I also tried a variation using the CPCompilerResultFun compiler parameter. But this did not work either:

fun main () =
    let
        fun useTree (NONE, _) () =
            (PolyML.print "not parsed"; ())
          | useTree (SOME parseTree, _) () =
            (PolyML.print "parsed"; PolyML.print parseTree; ());

        val stream = TextIO.openString "let val a = \"abc\"; val b = \"def\"; val c = a ^ b in print c end";
        val _ = PolyML.compiler (fn () => TextIO.input1 stream, [PolyML.Compiler.CPCompilerResultFun useTree]);
    in
        ()
    end

Running this does not produce any output.

1

There are 1 answers

3
IonuČ› G. Stan On

I was able to obtain it by providing the PolyML.Compiler.CPCompilerResultFun compiler option. It allows you to access and save the parse tree. However, I can't say too much about how the parse tree is actually represented. There's some documentation here (the website is down for me), but I couldn't make too much sense of it yet.

val resultTrees : PolyML.parseTree list ref = ref [];

fun compilerResultFun (parsetree, codeOpt) =
  let
    val _ =
      case parsetree of
        SOME pt => resultTrees := !resultTrees @ [pt]
      | NONE => ()
  in
    fn () => raise Fail "not implemented"
  end;

val stream = TextIO.openString "val a = 1";

val _ = PolyML.compiler (fn () => TextIO.input1 stream, [
  PolyML.Compiler.CPCompilerResultFun compilerResultFun
]);

val [(a, [PolyML.PTfirstChild b])] = !resultTrees;
val (_, [PolyML.PTfirstChild c, PolyML.PTparent d, PolyML.PTprint e]) = b ();