使用Rhino的Javascript解析器,如何获取注释?

4
我有一些 JavaScript 文件,使用 Rhino 的 JavaScript 解析器进行解析。
但是我无法获取注释。
如何获得注释?
下面是我的代码的一部分。
运行此代码,“comment”变量为 null。 同时,在运行“astRoot.toSource()”时,它只显示 JavaScript 代码。没有注释。 它消失了!
[java 代码]
public void parser() {
    AstRoot astRoot = new Parser().parse(this.jsString, this.uri, 1);

    List<AstNode> statList = astRoot.getStatements();
    for(Iterator<AstNode> iter = statList.iterator(); iter.hasNext();) {
        FunctionNode fNode = (FunctionNode)iter.next();

        System.out.println("*** function Name : " + fNode.getName() + ", paramCount : " + fNode.getParamCount() + ", depth : " + fNode.depth());

        AstNode bNode = fNode.getBody();
        Block block = (Block)bNode;
        visitBody(block);
    }

    System.out.println(astRoot.toSource());
    SortedSet<Comment> comment = astRoot.getComments();
    if(comment == null)
        System.out.println("comment is null");
}

你正在使用哪个版本的Rhino? - gshank
使用1.7R4版本,但现在我解决了这个问题!谢谢! - igc_Cog
1个回答

6

配置您的编译环境并使用AstRoot.visitAll(NodeVisitor)

import java.io.*;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ast.*;

public class PrintNodes {
  public static void main(String[] args) throws IOException {
    class Printer implements NodeVisitor {
      @Override public boolean visit(AstNode node) {
        String indent = "%1$Xs".replace("X", String.valueOf(node.depth() + 1));
        System.out.format(indent, "").println(node.getClass());
        return true;
      }
    }
    String file = "foo.js";
    Reader reader = new FileReader(file);
    try {
      CompilerEnvirons env = new CompilerEnvirons();
      env.setRecordingLocalJsDocComments(true);
      env.setAllowSharpComments(true);
      env.setRecordingComments(true);
      AstRoot node = new Parser(env).parse(reader, file, 1);
      node.visitAll(new Printer());
    } finally {
      reader.close();
    }
  }
}

Java 6;Rhino 1.7R4


谢谢,麦克道尔。是编译器环境问题导致的!现在,完美运行了! - igc_Cog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接