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.apache.commons.io.IOUtils;
    15  import org.mozilla.javascript.CompilerEnvirons;
    16  import org.mozilla.javascript.Parser;
    17  import org.mozilla.javascript.ast.AstRoot;
    18  import org.mozilla.javascript.ast.ErrorCollector;
    19  import org.mozilla.javascript.ast.ParseProblem;
    20
    21  public class EcmascriptParser {
    22      protected final EcmascriptParserOptions parserOptions;
    23
    24      public EcmascriptParser(EcmascriptParserOptions parserOptions) {
    25  	this.parserOptions = parserOptions;
    26      }
    27
    28      protected AstRoot parseEcmascript(final String sourceCode, final List<ParseProblem> parseProblems) throws ParseException {
    29  	final CompilerEnvirons compilerEnvirons = new CompilerEnvirons();
    30  	compilerEnvirons.setRecordingComments(parserOptions.isRecordingComments());
    31  	compilerEnvirons.setRecordingLocalJsDocComments(parserOptions.isRecordingLocalJsDocComments());
    32  	compilerEnvirons.setLanguageVersion(parserOptions.getRhinoLanguageVersion().getVersion());
    33  	compilerEnvirons.setIdeMode(true); // Scope's don't appear to get set right without this
    34  	compilerEnvirons.setWarnTrailingComma(true);
    35
    36  	// TODO We should do something with Rhino errors...
    37  	final ErrorCollector errorCollector = new ErrorCollector();
    38  	final Parser parser = new Parser(compilerEnvirons, errorCollector);
    39  	// TODO Fix hardcode
    40  	final String sourceURI = "unknown";
    41  	final int beginLineno = 1;
    42  	AstRoot astRoot = parser.parse(sourceCode, sourceURI, beginLineno);
    43  	parseProblems.addAll(errorCollector.getErrors());
    44  	return astRoot;
    45      }
    46
    47      public EcmascriptNode<AstRoot> parse(final Reader reader) {
    48  	try {
    49  	    final List<ParseProblem> parseProblems = new ArrayList<ParseProblem>();
    50  	    final String sourceCode = IOUtils.toString(reader);
    51  	    final AstRoot astRoot = parseEcmascript(sourceCode, parseProblems);
    52  	    final EcmascriptTreeBuilder treeBuilder = new EcmascriptTreeBuilder(sourceCode, parseProblems);
    53  	    return treeBuilder.build(astRoot);
    54  	} catch (IOException e) {
    55  	    throw new ParseException(e);
    56  	}
    57      }
    58  }