Getting syntax tree from source line in Poly / ML

I am trying to compile a line of source code and print a 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 

Launch:

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

What do I need to do to get the syntax tree from the compiler? I also tried the option using the compiler CPCompilerResultFun parameter. But that didn't 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 produces no output.

+5
source share
1 answer

I was able to get it by providing the PolyML.Compiler.CPCompilerResultFun compiler option. This allows access and preservation of the parsing tree . However, I cannot say too much about how the parsing tree is actually represented. There is documentation here (the site does not work for me), but I could not understand it too much.

 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 (); 
+3
source

Source: https://habr.com/ru/post/1243691/


All Articles