private AstRoot parse(String string, boolean jsdoc) { CompilerEnvirons environment = new CompilerEnvirons(); TestErrorReporter testErrorReporter = new TestErrorReporter(null, null); environment.setErrorReporter(testErrorReporter); environment.setRecordingComments(true); environment.setRecordingLocalJsDocComments(jsdoc); Parser p = new Parser(environment, testErrorReporter); AstRoot script = p.parse(string, null, 0); assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; }
private AstRoot parseAsReader(String string) throws IOException { CompilerEnvirons environment = new CompilerEnvirons(); 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; }
/** * 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; }
/** * 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; }
/** * @return a tree representation of the parsed JavaScript file * @throws IOException */ public ScriptOrFnNode parse() throws IOException { if (nodeTree == null) { Reader reader = new FileReader(jsFile); CompilerEnvirons compilerEnv = new CompilerEnvirons(); ErrorReporter errorReporter = compilerEnv.getErrorReporter(); Parser parser = new Parser(compilerEnv, errorReporter); String sourceURI; try { sourceURI = jsFile.getCanonicalPath(); } catch (IOException e) { sourceURI = jsFile.toString(); } nodeTree = parser.parse(reader, sourceURI, 1); } return nodeTree; }
/** * 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(); } }
/** * Constructor. * * @throws LanguageAdapterException * In case of an initialization error */ public RhinoAdapter() throws LanguageAdapterException { super( "Rhino", getImplementationVersion(), "JavaScript", getLanguageVersion(), Arrays.asList( "js", "javascript", "rhino" ), "js", Arrays.asList( "javascript", "js", "rhino" ), "rhino" ); CompilerEnvirons compilerEnvirons = new CompilerEnvirons(); compilerEnvirons.setOptimizationLevel( getOptimizationLevel() ); classCompiler = new ClassCompiler( compilerEnvirons ); Context context = enterContext(); try { generatedClassLoader = context.createClassLoader( RhinoAdapter.class.getClassLoader() ); } finally { Context.exit(); } }
/** * * @param fileName * @param staticMethods * @param staticFields * @return * @throws FileNotFoundException * @throws IOException */ Collection<JsFile> parseFile(final String fileName, final List<JsMethod> staticMethods, final Map<String, JsElement> staticFields) throws FileNotFoundException, IOException { try (final Reader reader = new FileReader(fileName)) { final CompilerEnvirons env = new CompilerEnvirons(); env.setRecordingLocalJsDocComments(true); env.setAllowSharpComments(true); env.setRecordingComments(true); final AstRoot node = new Parser(env).parse(reader, fileName, 1); final JavaScriptFileParser parser = new JavaScriptFileParser(fileName); node.visitAll(parser); staticMethods.addAll(parser.getStaticMethods()); staticFields.putAll(parser.getConsts()); return parser.getFiles(); } }
/** * * @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( ); } }
/** * * @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( ); } }
public void parseScript(String scriptText, TypeDeclarationOptions options) { if(scriptText != null && scriptText.length() > 0) { CompilerEnvirons env = JavaScriptParser.createCompilerEnvironment(new JavaScriptParser.JSErrorReporter(), provider.getLanguageSupport()); Parser parser = new Parser(env); StringReader r = new StringReader(scriptText); try { AstRoot root = parser.parse(r, null, 0); CodeBlock block = provider.iterateAstRoot(root, preProcessingCompletions, "", Integer.MAX_VALUE, options); provider.recursivelyAddLocalVars(preProcessingCompletions, block, 0, null, false, true); } catch(IOException io) { //ignore this } } }
/** * Compiles Text and resolves the type. * e.g * "Hello World".length; //resolve as a Number * * @param text to compile and resolve */ @Override public JavaScriptType compileText(String text) throws IOException { CompilerEnvirons env = JavaScriptParser.createCompilerEnvironment(new JavaScriptParser.JSErrorReporter(), provider.getLanguageSupport()); String parseText = JavaScriptHelper.removeLastDotFromText(text); int charIndex = JavaScriptHelper.findIndexOfFirstOpeningBracket(parseText); env.setRecoverFromErrors(true); Parser parser = new Parser(env); StringReader r = new StringReader(parseText); AstRoot root = parser.parse(r, null, 0); CompilerNodeVisitor visitor = new CompilerNodeVisitor(charIndex == 0); root.visitAll(visitor); return lastJavaScriptType; }
/** * Resolve node type to TypeDeclaration. Called instead of #compileText(String text) when document is already parsed * @param node AstNode to resolve * @return TypeDeclaration for node or null if not found. */ @Override public TypeDeclaration resolveParamNode(String text) throws IOException { if(text != null) { CompilerEnvirons env = JavaScriptParser.createCompilerEnvironment(new JavaScriptParser.JSErrorReporter(), provider.getLanguageSupport()); int charIndex = JavaScriptHelper.findIndexOfFirstOpeningBracket(text); env.setRecoverFromErrors(true); Parser parser = new Parser(env); StringReader r = new StringReader(text); AstRoot root = parser.parse(r, null, 0); CompilerNodeVisitor visitor = new CompilerNodeVisitor(charIndex == 0); root.visitAll(visitor); } return lastJavaScriptType != null ? lastJavaScriptType.getType() : provider.getTypesFactory().getDefaultTypeDeclaration(); }
/** * Creates options for Rhino based off of the user's preferences. * * @param errorHandler The container for errors found while parsing. * @return The properties for the JS compiler to use. */ public static CompilerEnvirons createCompilerEnvironment(ErrorReporter errorHandler, JavaScriptLanguageSupport langSupport) { CompilerEnvirons env = new CompilerEnvirons(); env.setErrorReporter(errorHandler); env.setIdeMode(true); env.setRecordingComments(true); env.setRecordingLocalJsDocComments(true); env.setRecoverFromErrors(true); if(langSupport != null) { env.setXmlAvailable(langSupport.isXmlAvailable()); env.setStrictMode(langSupport.isStrictMode()); int version = langSupport.getLanguageVersion(); if (version > 0) { Logger.log("[JavaScriptParser]: JS language version set to: " + version); env.setLanguageVersion(version); } } return env; }
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); }
/** * 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()); }
private void assertSource(String source, String expectedOutput) { CompilerEnvirons env = new CompilerEnvirons(); env.setLanguageVersion(Context.VERSION_ES6); Parser parser = new Parser(env); AstRoot root = parser.parse(source, null, 0); Assert.assertEquals(expectedOutput, root.toSource()); }
protected void compileScripts(JRCompilationUnit unit, CompilerEnvirons compilerEnv, CompileSources compileSources, JavaScriptCompiledData compiledData) { List<String> scripts = compileSources.getScripts(); int scriptIndex = 0; for (String scriptSource : scripts) { String scriptClassName = unit.getName() + "_" + scriptIndex; if (log.isTraceEnabled()) { log.trace("compiling script with name " + scriptClassName + "\n" + scriptSource); } ClassCompiler compiler = new ClassCompiler(compilerEnv); // this should not fail since we've already separately compiled the default expression Object[] compilationResult = compiler.compileToClassFiles(scriptSource, unit.getName(), 0, scriptClassName); if (compilationResult.length != 2) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_UNEXPECTED_CLASSES_LENGTH, new Object[]{compilationResult.length}); } if (!scriptClassName.equals(compilationResult[0])) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_UNEXPECTED_CLASS_NAME, new Object[]{compilationResult[0], scriptClassName}); } byte[] compiledClass = (byte[]) compilationResult[1]; compiledData.addClass(scriptClassName, compiledClass); ++scriptIndex; } }
protected static AstRoot parseIntoTree(String formula) { Context cx = Context.enter(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(cx); ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter(); Parser parser = new Parser(compilerEnv, compilationErrorReporter); AstRoot tree = parser.parse(formula, "(formula being checked by unit-checker)", 0); Context.exit(); return tree; }
protected AstRoot parseScript(String script){ CompilerEnvirons ce = new CompilerEnvirons(); ce.setRecordingComments(false); ce.setStrictMode(true); ce.setXmlAvailable(false); final AstRoot root; try { root = new Parser(ce).parse(script,"S1RestrictedScript",1); } catch (Throwable e) { String message = ""; int line = 0; int column = 0; String m = null; if(e instanceof EvaluatorException){ EvaluatorException ex = (EvaluatorException)e; message = "Syntax error: "+ex.getMessage(); line = ex.getLineNumber()-1; column = ex.getColumnNumber(); String arr [] = script.split("\n",-1); m = (arr.length>line?(arr[line]):""); }else{ message = e.getMessage(); } throw new SyntaxException(m,line,column,message,e); } if(LOG.isDebugEnabled()){ LOG.debug(root.debugPrint()); } return root; }