首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Poly/ML中从源代码字符串中获取解析树

在Poly/ML中从源代码字符串中获取解析树
EN

Stack Overflow用户
提问于 2016-02-24 00:26:52
回答 1查看 257关注 0票数 5

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

代码语言:javascript
复制
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

运行以下命令:

代码语言:javascript
复制
$ ./a.out
[...]
0
$

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

代码语言:javascript
复制
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

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

EN

回答 1

Stack Overflow用户

发布于 2016-02-24 17:30:46

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

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35582815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档