Java Code Examples for jdk.nashorn.internal.runtime.Context
The following examples show how to use
jdk.nashorn.internal.runtime.Context. These examples are extracted from open source projects.
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 Project: openjdk-jdk8u-backup Source File: Compiler.java License: GNU General Public License v2.0 | 6 votes |
/** * Creates a compiler for an on-demand compilation job. * * @param installer code installer * @param source source to compile * @param isStrict is this a strict compilation * @param compiledFunction compiled function, if any * @param types parameter and return value type information, if any is known * @param invalidatedProgramPoints invalidated program points for recompilation * @param typeInformationFile descriptor of the location where type information is persisted * @param continuationEntryPoints continuation entry points for restof method * @param runtimeScope runtime scope for recompilation type lookup in {@code TypeEvaluator} * @return a new compiler */ public static Compiler forOnDemandCompilation( final CodeInstaller installer, final Source source, final boolean isStrict, final RecompilableScriptFunctionData compiledFunction, final TypeMap types, final Map<Integer, Type> invalidatedProgramPoints, final Object typeInformationFile, final int[] continuationEntryPoints, final ScriptObject runtimeScope) { final Context context = installer.getContext(); return new Compiler(context, installer, source, context.getErrorManager(), isStrict, true, compiledFunction, types, invalidatedProgramPoints, typeInformationFile, continuationEntryPoints, runtimeScope); }
Example 2
Source Project: jdk8u_nashorn Source File: NativeJavaImporter.java License: GNU General Public License v2.0 | 6 votes |
private Object createProperty(final String name) { final int len = args.length; for (int i = len - 1; i > -1; i--) { final Object obj = args[i]; if (obj instanceof StaticClass) { if (((StaticClass)obj).getRepresentedClass().getSimpleName().equals(name)) { return obj; } } else if (obj instanceof NativeJavaPackage) { final String pkgName = ((NativeJavaPackage)obj).getName(); final String fullName = pkgName.isEmpty() ? name : (pkgName + "." + name); final Context context = Global.instance().getContext(); try { return StaticClass.forClass(context.findClass(fullName)); } catch (final ClassNotFoundException e) { // IGNORE } } } return null; }
Example 3
Source Project: nashorn Source File: Shell.java License: GNU General Public License v2.0 | 6 votes |
/** * Run method logic. * * @param in input stream for Shell * @param out output stream for Shell * @param err error stream for Shell * @param args arguments to Shell * * @return exit code * * @throws IOException if there's a problem setting up the streams */ protected final int run(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException { final Context context = makeContext(in, out, err, args); if (context == null) { return COMMANDLINE_ERROR; } final ScriptObject global = context.createGlobal(); final ScriptEnvironment env = context.getEnv(); final List<String> files = env.getFiles(); if (files.isEmpty()) { return readEvalPrint(context, global); } if (env._compile_only) { return compileScripts(context, global, files); } if (env._fx) { return runFXScripts(context, global, files); } return runScripts(context, global, files); }
Example 4
Source Project: hottub Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 6 votes |
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException { final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != newGlobal); try { if (globalChanged) { Context.setGlobal(newGlobal); } return nashornContext.compileScript(source, newGlobal); } catch (final Exception e) { throwAsScriptException(e, newGlobal); throw new AssertionError("should not reach here"); } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
Example 5
Source Project: TencentKona-8 Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 6 votes |
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException { final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != newGlobal); try { if (globalChanged) { Context.setGlobal(newGlobal); } return nashornContext.compileScript(source, newGlobal); } catch (final Exception e) { throwAsScriptException(e, newGlobal); throw new AssertionError("should not reach here"); } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
Example 6
Source Project: openjdk-jdk8u Source File: NativeDebug.java License: GNU General Public License v2.0 | 6 votes |
/** * Dump all Nashorn debug mode counters. Calling this may be better if * you want to print all counters. This way you can avoid too many callsites * due to counter access itself!! * @param self self reference * @return undefined */ @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) public static Object dumpCounters(final Object self) { final PrintWriter out = Context.getCurrentErr(); out.println("ScriptObject count " + ScriptObject.getCount()); out.println("Scope count " + Scope.getScopeCount()); out.println("ScriptObject listeners added " + PropertyListeners.getListenersAdded()); out.println("ScriptObject listeners removed " + PropertyListeners.getListenersRemoved()); out.println("ScriptFunction constructor calls " + ScriptFunction.getConstructorCount()); out.println("ScriptFunction invokes " + ScriptFunction.getInvokes()); out.println("ScriptFunction allocations " + ScriptFunction.getAllocations()); out.println("PropertyMap count " + PropertyMap.getCount()); out.println("PropertyMap cloned " + PropertyMap.getClonedCount()); out.println("PropertyMap history hit " + PropertyMap.getHistoryHit()); out.println("PropertyMap proto invalidations " + PropertyMap.getProtoInvalidations()); out.println("PropertyMap proto history hit " + PropertyMap.getProtoHistoryHit()); out.println("PropertyMap setProtoNewMapCount " + PropertyMap.getSetProtoNewMapCount()); out.println("Callsite count " + LinkerCallSite.getCount()); out.println("Callsite misses " + LinkerCallSite.getMissCount()); out.println("Callsite misses by site at " + LinkerCallSite.getMissSamplingPercentage() + "%"); LinkerCallSite.getMissCounts(out); return UNDEFINED; }
Example 7
Source Project: jdk8u60 Source File: ScriptObjectMirror.java License: GNU General Public License v2.0 | 6 votes |
@Override public void putAll(final Map<? extends String, ? extends Object> map) { Objects.requireNonNull(map); final ScriptObject oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != global); inGlobal(new Callable<Object>() { @Override public Object call() { for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) { final Object value = entry.getValue(); final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value; final String key = entry.getKey(); checkKey(key); sobj.set(key, unwrap(modValue, global), getCallSiteFlags()); } return null; } }); }
Example 8
Source Project: TencentKona-8 Source File: NativeArray.java License: GNU General Public License v2.0 | 6 votes |
/** * ECMA 15.4.4.7 Array.prototype.push (args...) * * @param self self reference * @param args arguments to push * @return array length after pushes */ @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) public static Object push(final Object self, final Object... args) { try { final ScriptObject sobj = (ScriptObject)self; if (bulkable(sobj) && sobj.getArray().length() + args.length <= JSType.MAX_UINT) { final ArrayData newData = sobj.getArray().push(true, args); sobj.setArray(newData); return JSType.toNarrowestNumber(newData.length()); } long len = JSType.toUint32(sobj.getLength()); for (final Object element : args) { sobj.set(len++, element, CALLSITE_STRICT); } sobj.set("length", len, CALLSITE_STRICT); return JSType.toNarrowestNumber(len); } catch (final ClassCastException | NullPointerException e) { throw typeError(Context.getGlobal(), e, "not.an.object", ScriptRuntime.safeToString(self)); } }
Example 9
Source Project: jdk8u60 Source File: NashornBeansLinker.java License: GNU General Public License v2.0 | 6 votes |
private static Method findFunctionalInterfaceMethod(final Class<?> clazz) { if (clazz == null) { return null; } for (final Class<?> iface : clazz.getInterfaces()) { // check accessiblity up-front if (! Context.isAccessibleClass(iface)) { continue; } // check for @FunctionalInterface if (iface.isAnnotationPresent(FunctionalInterface.class)) { // return the first abstract method for (final Method m : iface.getMethods()) { if (Modifier.isAbstract(m.getModifiers())) { return m; } } } } // did not find here, try super class return findFunctionalInterfaceMethod(clazz.getSuperclass()); }
Example 10
Source Project: openjdk-jdk8u Source File: ContextTest.java License: GNU General Public License v2.0 | 6 votes |
@Test public void evalTest() { final Options options = new Options(""); final ErrorManager errors = new ErrorManager(); final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader()); final Global oldGlobal = Context.getGlobal(); Context.setGlobal(cx.createGlobal()); try { String code = "22 + 10"; assertTrue(32.0 == ((Number)(eval(cx, "<evalTest>", code))).doubleValue()); code = "obj = { js: 'nashorn' }; obj.js"; assertEquals(eval(cx, "<evalTest2>", code), "nashorn"); } finally { Context.setGlobal(oldGlobal); } }
Example 11
Source Project: openjdk-jdk8u-backup Source File: NativeDebug.java License: GNU General Public License v2.0 | 6 votes |
/** * Dump all Nashorn debug mode counters. Calling this may be better if * you want to print all counters. This way you can avoid too many callsites * due to counter access itself!! * @param self self reference * @return undefined */ @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) public static Object dumpCounters(final Object self) { final PrintWriter out = Context.getCurrentErr(); out.println("ScriptObject count " + ScriptObject.getCount()); out.println("Scope count " + Scope.getScopeCount()); out.println("ScriptObject listeners added " + PropertyListeners.getListenersAdded()); out.println("ScriptObject listeners removed " + PropertyListeners.getListenersRemoved()); out.println("ScriptFunction constructor calls " + ScriptFunction.getConstructorCount()); out.println("ScriptFunction invokes " + ScriptFunction.getInvokes()); out.println("ScriptFunction allocations " + ScriptFunction.getAllocations()); out.println("PropertyMap count " + PropertyMap.getCount()); out.println("PropertyMap cloned " + PropertyMap.getClonedCount()); out.println("PropertyMap history hit " + PropertyMap.getHistoryHit()); out.println("PropertyMap proto invalidations " + PropertyMap.getProtoInvalidations()); out.println("PropertyMap proto history hit " + PropertyMap.getProtoHistoryHit()); out.println("PropertyMap setProtoNewMapCount " + PropertyMap.getSetProtoNewMapCount()); out.println("Callsite count " + LinkerCallSite.getCount()); out.println("Callsite misses " + LinkerCallSite.getMissCount()); out.println("Callsite misses by site at " + LinkerCallSite.getMissSamplingPercentage() + "%"); LinkerCallSite.getMissCounts(out); return UNDEFINED; }
Example 12
Source Project: openjdk-jdk8u Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 6 votes |
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException { final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != newGlobal); try { if (globalChanged) { Context.setGlobal(newGlobal); } return nashornContext.compileScript(source, newGlobal); } catch (final Exception e) { throwAsScriptException(e, newGlobal); throw new AssertionError("should not reach here"); } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
Example 13
Source Project: openjdk-jdk9 Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 6 votes |
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException { final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != newGlobal); try { if (globalChanged) { Context.setGlobal(newGlobal); } return nashornContext.compileScript(source, newGlobal); } catch (final Exception e) { throwAsScriptException(e, newGlobal); throw new AssertionError("should not reach here"); } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
Example 14
Source Project: TencentKona-8 Source File: Shell.java License: GNU General Public License v2.0 | 6 votes |
/** * Run method logic. * * @param in input stream for Shell * @param out output stream for Shell * @param err error stream for Shell * @param args arguments to Shell * * @return exit code * * @throws IOException if there's a problem setting up the streams */ protected final int run(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException { final Context context = makeContext(in, out, err, args); if (context == null) { return COMMANDLINE_ERROR; } final Global global = context.createGlobal(); final ScriptEnvironment env = context.getEnv(); final List<String> files = env.getFiles(); if (files.isEmpty()) { return readEvalPrint(context, global); } if (env._compile_only) { return compileScripts(context, global, files); } if (env._fx) { return runFXScripts(context, global, files); } return runScripts(context, global, files); }
Example 15
Source Project: openjdk-jdk8u Source File: JSONWriter.java License: GNU General Public License v2.0 | 5 votes |
/** * Returns AST as JSON compatible string. * * @param context context * @param code code to be parsed * @param name name of the code source (used for location) * @param includeLoc tells whether to include location information for nodes or not * @return JSON string representation of AST of the supplied code */ public static String parse(final Context context, final String code, final String name, final boolean includeLoc) { final Parser parser = new Parser(context.getEnv(), sourceFor(name, code), new Context.ThrowErrorManager(), context.getEnv()._strict, context.getLogger(Parser.class)); final JSONWriter jsonWriter = new JSONWriter(includeLoc); try { final FunctionNode functionNode = parser.parse(); //symbol name is ":program", default functionNode.accept(jsonWriter); return jsonWriter.getString(); } catch (final ParserException e) { e.throwAsEcmaException(); return null; } }
Example 16
Source Project: openjdk-8 Source File: ScriptObjectMirror.java License: GNU General Public License v2.0 | 5 votes |
@Override public void putAll(final Map<? extends String, ? extends Object> map) { final ScriptObject oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != global); inGlobal(new Callable<Object>() { @Override public Object call() { for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) { final Object value = entry.getValue(); final Object modValue = globalChanged? wrap(value, oldGlobal) : value; sobj.set(entry.getKey(), unwrap(modValue, global), strict); } return null; } }); }
Example 17
Source Project: jdk8u_nashorn Source File: NashornScriptEngineFactory.java License: GNU General Public License v2.0 | 5 votes |
private ScriptEngine newEngine(final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) { checkConfigPermission(); try { return new NashornScriptEngine(this, args, appLoader, classFilter); } catch (final RuntimeException e) { if (Context.DEBUG) { e.printStackTrace(); } throw e; } }
Example 18
Source Project: nashorn Source File: NashornPrimitiveLinker.java License: GNU General Public License v2.0 | 5 votes |
@Override public GuardedInvocation getGuardedInvocation(final LinkRequest origRequest, final LinkerServices linkerServices) throws Exception { final LinkRequest request = origRequest.withoutRuntimeContext(); // Nashorn has no runtime context final Object self = request.getReceiver(); final GlobalObject global = (GlobalObject) Context.getGlobal(); final NashornCallSiteDescriptor desc = (NashornCallSiteDescriptor) request.getCallSiteDescriptor(); return Bootstrap.asType(global.primitiveLookup(request, self), linkerServices, desc); }
Example 19
Source Project: TencentKona-8 Source File: ScriptObjectMirror.java License: GNU General Public License v2.0 | 5 votes |
@Override public Object put(final String key, final Object value) { checkKey(key); final ScriptObject oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != global); return inGlobal(new Callable<Object>() { @Override public Object call() { final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value; return translateUndefined(wrapLikeMe(sobj.put(key, unwrap(modValue, global), strict))); } }); }
Example 20
Source Project: TencentKona-8 Source File: ScriptUtils.java License: GNU General Public License v2.0 | 5 votes |
/** * Unwrap a script object mirror if needed. * * @param obj object to be unwrapped * @return unwrapped object */ public static Object unwrap(final Object obj) { if (obj instanceof ScriptObjectMirror) { return ScriptObjectMirror.unwrap(obj, Context.getGlobal()); } return obj; }
Example 21
Source Project: hottub Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 5 votes |
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException { if (script == null) { return null; } final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != ctxtGlobal); try { if (globalChanged) { Context.setGlobal(ctxtGlobal); } final ScriptContext oldCtxt = ctxtGlobal.getScriptContext(); ctxtGlobal.setScriptContext(ctxt); try { return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal)); } finally { ctxtGlobal.setScriptContext(oldCtxt); } } catch (final Exception e) { throwAsScriptException(e, ctxtGlobal); throw new AssertionError("should not reach here"); } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
Example 22
Source Project: TencentKona-8 Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 5 votes |
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException { if (script == null) { return null; } final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != ctxtGlobal); try { if (globalChanged) { Context.setGlobal(ctxtGlobal); } final ScriptContext oldCtxt = ctxtGlobal.getScriptContext(); ctxtGlobal.setScriptContext(ctxt); try { return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal)); } finally { ctxtGlobal.setScriptContext(oldCtxt); } } catch (final Exception e) { throwAsScriptException(e, ctxtGlobal); throw new AssertionError("should not reach here"); } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
Example 23
Source Project: TencentKona-8 Source File: ParserTest.java License: GNU General Public License v2.0 | 5 votes |
@BeforeClass public void setupTest() { final Options options = new Options("nashorn"); options.set("anon.functions", true); options.set("parse.only", true); options.set("scripting", true); options.set("const.as.var", true); final ErrorManager errors = new ErrorManager(); this.context = new Context(options, errors, Thread.currentThread().getContextClassLoader()); }
Example 24
Source Project: hottub Source File: Shell.java License: GNU General Public License v2.0 | 5 votes |
/** * Runs launches "fx:bootstrap.js" with the given JavaScript files provided * as arguments. * * @param context the nashorn context * @param global the global scope * @param files the list of script files to provide * * @return error code * @throws IOException when any script file read results in I/O error */ private static int runFXScripts(final Context context, final Global global, final List<String> files) throws IOException { final Global oldGlobal = Context.getGlobal(); final boolean globalChanged = (oldGlobal != global); try { if (globalChanged) { Context.setGlobal(global); } global.addOwnProperty("$GLOBAL", Property.NOT_ENUMERABLE, global); global.addOwnProperty("$SCRIPTS", Property.NOT_ENUMERABLE, files); context.load(global, "fx:bootstrap.js"); } catch (final NashornException e) { context.getErrorManager().error(e.toString()); if (context.getEnv()._dump_on_error) { e.printStackTrace(context.getErr()); } return RUNTIME_ERROR; } finally { context.getOut().flush(); context.getErr().flush(); if (globalChanged) { Context.setGlobal(oldGlobal); } } return SUCCESS; }
Example 25
Source Project: openjdk-jdk9 Source File: NashornCompleter.java License: GNU General Public License v2.0 | 5 votes |
NashornCompleter(final Context context, final Global global, final PartialParser partialParser, final PropertiesHelper propsHelper) { this.context = context; this.global = global; this.env = context.getEnv(); this.partialParser = partialParser; this.propsHelper = propsHelper; this.parser = createParser(env); }
Example 26
Source Project: openjdk-jdk9 Source File: NativeDebug.java License: GNU General Public License v2.0 | 5 votes |
/** * Nashorn extension: get context, context utility * * @param self self reference * @return context */ @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) public static Object getContext(final Object self) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission(Context.NASHORN_GET_CONTEXT)); } return Global.getThisContext(); }
Example 27
Source Project: openjdk-8 Source File: ScriptUtils.java License: GNU General Public License v2.0 | 5 votes |
/** * Unwrap an array of script object mirrors if needed. * * @param args array to be unwrapped * @return unwrapped array */ public static Object[] unwrapArray(final Object[] args) { if (args == null || args.length == 0) { return args; } return ScriptObjectMirror.unwrapArray(args, Context.getGlobal()); }
Example 28
Source Project: nashorn Source File: NashornScriptEngine.java License: GNU General Public License v2.0 | 5 votes |
private ScriptObject createNashornGlobal(final ScriptContext ctxt) { final ScriptObject newGlobal = AccessController.doPrivileged(new PrivilegedAction<ScriptObject>() { @Override public ScriptObject run() { try { return nashornContext.newGlobal(); } catch (final RuntimeException e) { if (Context.DEBUG) { e.printStackTrace(); } throw e; } } }, CREATE_GLOBAL_ACC_CTXT); nashornContext.initGlobal(newGlobal); final int NON_ENUMERABLE_CONSTANT = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE; // current ScriptContext exposed as "context" // "context" is non-writable from script - but script engine still // needs to set it and so save the context Property object contextProperty = newGlobal.addOwnProperty("context", NON_ENUMERABLE_CONSTANT, ctxt); // current ScriptEngine instance exposed as "engine". We added @SuppressWarnings("LeakingThisInConstructor") as // NetBeans identifies this assignment as such a leak - this is a false positive as we're setting this property // in the Global of a Context we just created - both the Context and the Global were just created and can not be // seen from another thread outside of this constructor. newGlobal.addOwnProperty("engine", NON_ENUMERABLE_CONSTANT, this); // global script arguments with undefined value newGlobal.addOwnProperty("arguments", Property.NOT_ENUMERABLE, UNDEFINED); // file name default is null newGlobal.addOwnProperty(ScriptEngine.FILENAME, Property.NOT_ENUMERABLE, null); // evaluate engine.js initialization script this new global object try { evalImpl(compileImpl(ENGINE_SCRIPT_SRC, newGlobal), ctxt, newGlobal); } catch (final ScriptException exp) { throw new RuntimeException(exp); } return newGlobal; }
Example 29
Source Project: openjdk-8 Source File: Global.java License: GNU General Public License v2.0 | 5 votes |
/** * Constructor * * @param context the context */ public Global(final Context context) { super(checkAndGetMap(context)); this.context = context; this.setIsScope(); final int cacheSize = context.getEnv()._class_cache_size; if (cacheSize > 0) { classCache = new ClassCache(cacheSize); } }
Example 30
Source Project: hottub Source File: Global.java License: GNU General Public License v2.0 | 5 votes |
private static PropertyMap checkAndGetMap(final Context context) { // security check first final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission(Context.NASHORN_CREATE_GLOBAL)); } Objects.requireNonNull(context); return $nasgenmap$; }