gpt4 book ai didi

sml - 从 Poly/ML 中的源代码字符串获取解析树

转载 作者:行者123 更新时间:2023-12-02 01:46:24 26 4
gpt4 key购买 nike

我正在尝试编译一串源代码并使用 Poly/ML 打印解析树。以下代码可以编译,但解析树为空:

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

运行这个:

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

我需要做什么才能从编译器获取解析树?我还尝试了使用 CPCompilerResultFun 编译器参数的变体。但这也不起作用:

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

运行此命令不会产生任何输出。

最佳答案

我可以通过提供PolyML.Compiler.CPCompilerResultFun编译器选项来获取它。它允许您access and save the parse tree 。但是,我不能过多谈论解析树的实际表示方式。有一些文档here (该网站对我来说已经关闭了),但我还不太明白它的意义。

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 ();

关于sml - 从 Poly/ML 中的源代码字符串获取解析树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com