View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.ecmascript.ast;
5   
6   import java.io.IOException;
7   import java.io.Reader;
8   import java.util.ArrayList;
9   import java.util.List;
10  
11  import net.sourceforge.pmd.lang.ast.ParseException;
12  import net.sourceforge.pmd.lang.ecmascript.EcmascriptParserOptions;
13  
14  import org.mozilla.javascript.CompilerEnvirons;
15  import org.mozilla.javascript.Parser;
16  import org.mozilla.javascript.ast.AstRoot;
17  import org.mozilla.javascript.ast.ErrorCollector;
18  import org.mozilla.javascript.ast.ParseProblem;
19  
20  public class EcmascriptParser {
21      protected final EcmascriptParserOptions parserOptions;
22  
23      public EcmascriptParser(EcmascriptParserOptions parserOptions) {
24  	this.parserOptions = parserOptions;
25      }
26  
27      protected AstRoot parseEcmascript(final Reader reader, final List<ParseProblem> parseProblems) throws ParseException {
28  	final CompilerEnvirons compilerEnvirons = new CompilerEnvirons();
29  	compilerEnvirons.setRecordingComments(parserOptions.isRecordingComments());
30  	compilerEnvirons.setRecordingLocalJsDocComments(parserOptions.isRecordingLocalJsDocComments());
31  	compilerEnvirons.setLanguageVersion(parserOptions.getRhinoLanguageVersion().getVersion());
32  	compilerEnvirons.setIdeMode(true); // Scope's don't appear to get set right without this
33  	compilerEnvirons.setWarnTrailingComma(true);
34  
35  	// TODO We should do something with Rhino errors...
36  	final ErrorCollector errorCollector = new ErrorCollector();
37  	final Parser parser = new Parser(compilerEnvirons, errorCollector);
38  	try {
39  	    // TODO Fix hardcode
40  	    final String sourceURI = "unknown";
41  	    // TODO Fix hardcode
42  	    final int lineno = 0;
43  	    AstRoot astRoot = parser.parse(reader, sourceURI, lineno);
44  	    parseProblems.addAll(errorCollector.getErrors());
45  	    return astRoot;
46  	} catch (final IOException e) {
47  	    throw new ParseException(e);
48  	}
49      }
50  
51      public EcmascriptNode parse(final Reader reader) {
52  	final List<ParseProblem> parseProblems = new ArrayList<ParseProblem>();
53  	final AstRoot astRoot = parseEcmascript(reader, parseProblems);
54  	final EcmascriptTreeBuilder treeBuilder = new EcmascriptTreeBuilder(parseProblems);
55  	return treeBuilder.build(astRoot);
56      }
57  }