org.mozilla.javascript.Parser Java Examples

The following examples show how to use org.mozilla.javascript.Parser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BugGetterSetterTest.java    From rhino-android with Apache License 2.0 7 votes vote down vote up
@Test
public void testNodeReplacementInWhileLoopWithBrackets() throws IOException {
    String script = "var o = {\n" +
            "  _x: 123, \n" +
            "  get x() {\n" +
            "    return this._x;\n" +
            "  }\n" +
            ", \n" +
            "  set x(value) {\n" +
            "    this._x = value;\n" +
            "  }\n" +
            "};\n";

    Parser parser = new Parser(environment);
    AstRoot astRoot = parser.parse(new StringReader(script), null, 1);
    assertEquals(script, astRoot.toSource());
}
 
Example #2
Source File: ScriptDialog.java    From hop with Apache License 2.0 6 votes vote down vote up
public static ScriptNode parseVariables( Context cx, Scriptable scope, String source, String sourceName,
                                         int lineno, Object securityDomain ) {
  // Interpreter compiler = new Interpreter();
  CompilerEnvirons evn = new CompilerEnvirons();
  // evn.setLanguageVersion(Context.VERSION_1_5);
  evn.setOptimizationLevel( -1 );
  evn.setGeneratingSource( true );
  evn.setGenerateDebugInfo( true );
  ErrorReporter errorReporter = new ToolErrorReporter( false );
  Parser p = new Parser( evn, errorReporter );
  ScriptNode tree = p.parse( source, "", 0 ); // IOException
  new NodeTransformer().transform( tree );
  // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
  return tree;
}
 
Example #3
Source File: Bug782363Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
/**
 * Compiles {@code source} and returns the transformed and optimized
 * {@link ScriptNode}
 */
protected ScriptNode compile(CharSequence source) {
    final String mainMethodClassName = "Main";
    final String scriptClassName = "Main";

    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    Parser p = new Parser(compilerEnv);
    AstRoot ast = p.parse(source.toString(), "<eval>", 1);
    IRFactory irf = new IRFactory(compilerEnv);
    ScriptNode tree = irf.transformTree(ast);

    Codegen codegen = new Codegen();
    codegen.setMainMethodClass(mainMethodClassName);
    codegen.compileToClassFile(compilerEnv, scriptClassName, tree, tree.getEncodedSource(),
            false);

    return tree;
}
 
Example #4
Source File: ClassDefScanner.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Scan the given file for class definitions and accumulate dependencies.
 */
private void scan(final File source) throws IOException {
  log.debug("Scanning: " + source);

  ErrorReporter errorReporter = new LogErrorReporter(log);

  CompilerEnvirons env = new CompilerEnvirons();
  env.setErrorReporter(errorReporter);

  Parser parser = new Parser(env, errorReporter);
  Reader reader = new BufferedReader(new FileReader(source));
  try {
    AstRoot root = parser.parse(reader, source.getAbsolutePath(), 0);
    DependencyAccumulator visitor = new DependencyAccumulator(source);
    root.visit(visitor);

    // complain if no def was found in this source
    if (visitor.current == null) {
      log.warn("No class definition was found while processing: " + source);
    }
  }
  finally {
    reader.close();
  }
}
 
Example #5
Source File: ExplanationsTest.java    From SJS with Apache License 2.0 6 votes vote down vote up
private static String explainErrors(JSEnvironment env, String sourceCode) {
    AstRoot root = new Parser().parse(sourceCode, "", 1);
    SatSolver sat = new Sat4J();
    SJSTypeTheory theory = new SJSTypeTheory(env, null, root);
    List<Integer> hard = new ArrayList<>();
    List<Integer> soft = new ArrayList<>();
    List<ITypeConstraint> constraints = theory.getConstraints();
    for (int i = 0; i < constraints.size(); ++i) {
        (theory.hackyGenerator().hasExplanation(constraints.get(i)) ? soft : hard).add(i);
    }
    Pair<TypeAssignment, Collection<Integer>> result =
            TheorySolver.solve(
                theory, new SatFixingSetFinder<>(sat),
                hard, soft);
    ConstraintGenerator g = theory.hackyGenerator();
    StringBuilder buf = new StringBuilder();
    for (int broken : result.getRight()) {
        ITypeConstraint c = theory.hackyConstraintAccess().get(broken);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        g.explainFailure(c, result.getLeft()).prettyprint(new PrintStream(stream));
        buf.append(stream.toString());
    }
    return buf.toString();
}
 
Example #6
Source File: OlapExpressionCompiler.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 
 * @param expr
 * @param objectName
 * @return
 */
public static String getReferencedScriptObject( String expr,
		String objectName )
{
	if ( expr == null )
		return null;
	try
	{
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr, null, 0 );
		Node root = new IRFactory( ce).transformTree(tree);

		return getScriptObjectName( root, objectName );
	}
	catch( Exception ex )
	{
		return null;
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #7
Source File: CubeQueryUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 
 * @param expr
 * @param objectName
 * @return
 */
private static String getReferencedScriptObject( String expr,
		String objectName )
{
	if ( expr == null )
		return null;
	try
	{
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr, null, 0 );
		IRFactory ir = new IRFactory( ce );
		ScriptNode script = ir.transformTree( tree );
		return getScriptObjectName( script, objectName );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #8
Source File: Bug708801Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
/**
 * Compiles {@code source} and returns the transformed and optimized
 * {@link ScriptNode}
 */
protected ScriptNode compile(CharSequence source) {
    final String mainMethodClassName = "Main";
    final String scriptClassName = "Main";

    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv
            .getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    AstRoot ast = p.parse(source.toString(), "<eval>", 1);
    IRFactory irf = new IRFactory(compilerEnv);
    ScriptNode tree = irf.transformTree(ast);

    Codegen codegen = new Codegen();
    codegen.setMainMethodClass(mainMethodClassName);
    codegen.compileToClassFile(compilerEnv, scriptClassName, tree,
            tree.getEncodedSource(), false);

    return tree;
}
 
Example #9
Source File: Bug689314Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #10
Source File: FileRepository.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
public List<AstRoot> getAsts() throws IOException {
  List<AstRoot> asts = new LinkedList<AstRoot>();
  for (Map.Entry<String, Reader> file : files.entrySet()) {
    Parser parser = new Parser();
    asts.add(parser.parse(file.getValue(), file.getKey(), 1));
  }
  return asts;
}
 
Example #11
Source File: Bug688021Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #12
Source File: Bug491621Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Asserts that the value returned by {@link AstRoot#toSource()} after
 * the given input source was parsed equals the specified expected output source.
 *
 * @param source the JavaScript source to be parsed
 * @param expectedOutput the JavaScript source that is expected to be
 *                       returned by {@link AstRoot#toSource()}
 */
private void assertSource(String source, String expectedOutput)
{
    CompilerEnvirons env = new CompilerEnvirons();
    env.setLanguageVersion(Context.VERSION_1_7);
    Parser parser = new Parser(env);
    AstRoot root = parser.parse(source, null, 0);
    Assert.assertEquals(expectedOutput, root.toSource());
}
 
Example #13
Source File: Bug688018Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #14
Source File: Bug687669Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #15
Source File: Bug689308Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #16
Source File: ParserTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parse(
    String string, final String [] errors, final String [] warnings,
    boolean jsdoc) {
    TestErrorReporter testErrorReporter =
        new TestErrorReporter(errors, warnings) {
      @Override
      public EvaluatorException runtimeError(
           String message, String sourceName, int line, String lineSource,
           int lineOffset) {
         if (errors == null) {
           throw new UnsupportedOperationException();
         }
         return new EvaluatorException(
           message, sourceName, line, lineSource, lineOffset);
       }
    };
    environment.setErrorReporter(testErrorReporter);

    environment.setRecordingComments(true);
    environment.setRecordingLocalJsDocComments(jsdoc);

    Parser p = new Parser(environment, testErrorReporter);
    AstRoot script = null;
    try {
      script = p.parse(string, null, 0);
    } catch (EvaluatorException e) {
      if (errors == null) {
        // EvaluationExceptions should not occur when we aren't expecting
        // errors.
        throw e;
      }
    }

    assertTrue(testErrorReporter.hasEncounteredAllErrors());
    assertTrue(testErrorReporter.hasEncounteredAllWarnings());

    return script;
}
 
Example #17
Source File: ParserTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private AstRoot parseAsReader(String string) throws IOException {
    TestErrorReporter testErrorReporter = new TestErrorReporter(null, null);
    environment.setErrorReporter(testErrorReporter);

    environment.setRecordingComments(true);
    environment.setRecordingLocalJsDocComments(true);

    Parser p = new Parser(environment, testErrorReporter);
    AstRoot script = p.parse(new StringReader(string), null, 0);

    assertTrue(testErrorReporter.hasEncounteredAllErrors());
    assertTrue(testErrorReporter.hasEncounteredAllWarnings());

    return script;
}
 
Example #18
Source File: OlapExpressionCompiler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param expr
 * @param bindings
 * @param onlyFromDirectReferenceExpr
 * @return
 * @throws DataException
 */
private static Set getReferencedDimLevel( IScriptExpression expr,
		List bindings, boolean onlyFromDirectReferenceExpr )
		throws DataException
{
	if ( expr == null || expr.getText( ) == null || expr.getText( ).length( ) == 0 || BaseExpression.constantId.equals( expr.getScriptId( ) ) )
		return new HashSet( );
	try
	{
		Set result = new HashSet( );
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr.getText( ), null, 0 );
		Node root = new IRFactory( ce).transformTree(tree);

		populateDimLevels( null,
				root,
				result,
				bindings,
				onlyFromDirectReferenceExpr );
		return result;
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #19
Source File: AbstractExpressionCompiler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * parse the expression to script tree
 * 
 * @param expression
 * @param cx
 * @return
 * @throws DataException
 */
protected ScriptNode parse( String expression, Context cx )
		throws DataException
{
	if ( expression == null )
		throw new DataException( ResourceConstants.EXPRESSION_CANNOT_BE_NULL_OR_BLANK );

	CompilerEnvirons compilerEnv = getCompilerEnv( cx );
	Parser p = new Parser( compilerEnv, cx.getErrorReporter( ) );
	AstRoot root = p.parse( expression, null, 0 );
	IRFactory ir = new IRFactory(compilerEnv );
	ScriptNode script = ir.transformTree(root);
	return script;
}
 
Example #20
Source File: ScriptValidator.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validates the specified script.
 * 
 * @param script
 *            the script to validate.
 * @throws ParseException
 *             if an syntax error is found.
 */
protected void validateScript( String script ) throws ParseException
{
	if ( script == null )
	{
		return;
	}

	CompilerEnvirons compilerEnv = new CompilerEnvirons( );
	Parser jsParser = new Parser( compilerEnv,
			compilerEnv.getErrorReporter( ) );

	try
	{
		jsParser.parse( script, null, 0 );
	}
	catch ( EvaluatorException e )
	{
		int offset = -1;

		if ( scriptViewer != null )
		{
			String[] lines = script.split( "\n" ); //$NON-NLS-1$

			for ( int i = 0; i < e.lineNumber( ); i++ )
			{
				offset += lines[i].length( ) + 1;
			}
			offset += e.columnNumber( );
		}
		throw new ParseException( e.getLocalizedMessage( ), offset );
	}
}
 
Example #21
Source File: ExpressionParserUtility.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * parse the expression into a script tree
 * 
 * @param expression
 * @param cx
 * @return
 */
private ScriptNode parse( String expression, Context cx )
{
	CompilerEnvirons compilerEnv = new CompilerEnvirons( );
	Parser p = new Parser( compilerEnv, cx.getErrorReporter( ) );
	AstRoot root = p.parse( expression, null, 0 );
	IRFactory ir = new IRFactory(compilerEnv);
	return ir.transformTree(root);
}
 
Example #22
Source File: OlapExpressionCompiler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param expr
 * @param objectName
 * @return
 */
public static Set<String> getReferencedMeasure( String expr )
{
	if ( expr == null )
		return Collections.emptySet( );
	try
	{
		Set<String> result = new LinkedHashSet<String>( );
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr, null, 0 );
		IRFactory ir = new IRFactory( ce );
		ScriptNode script = ir.transformTree( tree );
		getScriptObjectName( script, "measure", result ); //$NON-NLS-1$
		
		return result;
	}
	catch( Exception e )
	{
		return Collections.emptySet( );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #23
Source File: OlapExpressionCompiler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param expr
 * @param bindings
 * @param onlyFromDirectReferenceExpr
 * @return
 * @throws DataException
 */
public static Set<IDimLevel> getReferencedDimLevel( String expr )
		throws CoreException
{
	if ( expr == null  )
		return new HashSet<IDimLevel>( );
	try
	{
		Set<IDimLevel> result = new HashSet<IDimLevel>( );
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr, null, 0 );
		IRFactory ir = new IRFactory( ce );
		ScriptNode script = ir.transformTree( tree );
		populateDimLevels( null, script, result );
		return result;
	}
	catch( Exception e )
	{
		return Collections.emptySet( );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #24
Source File: ScriptDialog.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static ScriptNode parseVariables( Context cx, Scriptable scope, String source, String sourceName,
  int lineno, Object securityDomain ) {
  // Interpreter compiler = new Interpreter();
  CompilerEnvirons evn = new CompilerEnvirons();
  // evn.setLanguageVersion(Context.VERSION_1_5);
  evn.setOptimizationLevel( -1 );
  evn.setGeneratingSource( true );
  evn.setGenerateDebugInfo( true );
  ErrorReporter errorReporter = new ToolErrorReporter( false );
  Parser p = new Parser( evn, errorReporter );
  ScriptNode tree = p.parse( source, "", 0 ); // IOException
  new NodeTransformer().transform( tree );
  // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
  return tree;
}
 
Example #25
Source File: ScriptValuesModDialog.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static ScriptNode parseVariables( Context cx, Scriptable scope, String source, String sourceName,
  int lineno, Object securityDomain ) {
  // Interpreter compiler = new Interpreter();
  CompilerEnvirons evn = new CompilerEnvirons();
  // evn.setLanguageVersion(Context.VERSION_1_5);
  evn.setOptimizationLevel( -1 );
  evn.setGeneratingSource( true );
  evn.setGenerateDebugInfo( true );
  ErrorReporter errorReporter = new ToolErrorReporter( false );
  Parser p = new Parser( evn, errorReporter );
  ScriptNode tree = p.parse( source, "", 0 ); // IOException
  new NodeTransformer().transform( tree );
  // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
  return tree;
}
 
Example #26
Source File: Bug688018Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #27
Source File: ScriptValuesModDialog.java    From hop with Apache License 2.0 5 votes vote down vote up
public static ScriptNode parseVariables( Context cx, Scriptable scope, String source, String sourceName,
                                         int lineno, Object securityDomain ) {
  // Interpreter compiler = new Interpreter();
  CompilerEnvirons evn = new CompilerEnvirons();
  // evn.setLanguageVersion(Context.VERSION_1_5);
  evn.setOptimizationLevel( -1 );
  evn.setGeneratingSource( true );
  evn.setGenerateDebugInfo( true );
  ErrorReporter errorReporter = new ToolErrorReporter( false );
  Parser p = new Parser( evn, errorReporter );
  ScriptNode tree = p.parse( source, "", 0 ); // IOException
  new NodeTransformer().transform( tree );
  // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
  return tree;
}
 
Example #28
Source File: Bug689314Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #29
Source File: Bug688021Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private AstRoot parse(CharSequence cs) {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(cx);
    ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter();
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    return p.parse(cs.toString(), "<eval>", 1);
}
 
Example #30
Source File: Bug491621Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the value returned by {@link AstRoot#toSource()} after
 * the given input source was parsed equals the specified expected output source.
 *
 * @param source the JavaScript source to be parsed
 * @param expectedOutput the JavaScript source that is expected to be
 *                       returned by {@link AstRoot#toSource()}
 */
private void assertSource(String source, String expectedOutput)
{
    CompilerEnvirons env = new CompilerEnvirons();
    env.setLanguageVersion(Context.VERSION_1_7);
    Parser parser = new Parser(env);
    AstRoot root = parser.parse(source, null, 0);
    Assert.assertEquals(expectedOutput, root.toSource());
}