4

I have some javascript files and parse it using Rhino's javascript parser.

but I can't get the comments.

How can I get the comments?

here's a part of my code.

run this code, "comment" variable has null. also, while running "astRoot.toSource();", it shows only javascript code. no comment included. it disappeared!

[java code]

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");
}
2
  • What version of rhino are you using? Commented Mar 27, 2013 at 12:29
  • using 1.7R4, but now I solve the problem! thanks! Commented Mar 28, 2013 at 2:28

1 Answer 1

6

Configure your CompilerEnvirons and use 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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, McDowell. it was CompilerEnvirons missing problem! now, work perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.