1 /*
   2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.api.scripting;
  27 
  28 import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
  29 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
  30 
  31 import java.io.IOException;
  32 import java.io.InputStream;
  33 import java.io.InputStreamReader;
  34 import java.io.Reader;
  35 import java.lang.reflect.Method;
  36 import java.lang.reflect.Modifier;
  37 import java.net.URL;
  38 import java.nio.charset.Charset;
  39 import java.security.AccessControlContext;
  40 import java.security.AccessController;
  41 import java.security.Permissions;
  42 import java.security.PrivilegedAction;
  43 import java.security.PrivilegedActionException;
  44 import java.security.PrivilegedExceptionAction;
  45 import java.security.ProtectionDomain;
  46 import java.text.MessageFormat;
  47 import java.util.Locale;
  48 import java.util.ResourceBundle;
  49 import javax.script.AbstractScriptEngine;
  50 import javax.script.Bindings;
  51 import javax.script.Compilable;
  52 import javax.script.CompiledScript;
  53 import javax.script.Invocable;
  54 import javax.script.ScriptContext;
  55 import javax.script.ScriptEngine;
  56 import javax.script.ScriptEngineFactory;
  57 import javax.script.ScriptException;
  58 import javax.script.SimpleBindings;
  59 import jdk.nashorn.internal.runtime.Context;
  60 import jdk.nashorn.internal.runtime.ErrorManager;
  61 import jdk.nashorn.internal.runtime.GlobalObject;
  62 import jdk.nashorn.internal.runtime.Property;
  63 import jdk.nashorn.internal.runtime.ScriptFunction;
  64 import jdk.nashorn.internal.runtime.ScriptObject;
  65 import jdk.nashorn.internal.runtime.ScriptRuntime;
  66 import jdk.nashorn.internal.runtime.Source;
  67 import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
  68 import jdk.nashorn.internal.runtime.options.Options;
  69 
  70 /**
  71  * JSR-223 compliant script engine for Nashorn. Instances are not created directly, but rather returned through
  72  * {@link NashornScriptEngineFactory#getScriptEngine()}. Note that this engine implements the {@link Compilable} and
  73  * {@link Invocable} interfaces, allowing for efficient precompilation and repeated execution of scripts.
  74  * @see NashornScriptEngineFactory
  75  */
  76 
  77 public final class NashornScriptEngine extends AbstractScriptEngine implements Compilable, Invocable {
  78     /**
  79      * Key used to associate Nashorn global object mirror with arbitrary Bindings instance.
  80      */
  81     public static final String NASHORN_GLOBAL = "nashorn.global";
  82 
  83     // commonly used access control context objects
  84     private static AccessControlContext createPermAccCtxt(final String permName) {
  85         final Permissions perms = new Permissions();
  86         perms.add(new RuntimePermission(permName));
  87         return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
  88     }
  89 
  90     private static final AccessControlContext CREATE_CONTEXT_ACC_CTXT = createPermAccCtxt(Context.NASHORN_CREATE_CONTEXT);
  91     private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT  = createPermAccCtxt(Context.NASHORN_CREATE_GLOBAL);
  92 
  93     // the factory that created this engine
  94     private final ScriptEngineFactory factory;
  95     // underlying nashorn Context - 1:1 with engine instance
  96     private final Context             nashornContext;
  97     // do we want to share single Nashorn global instance across ENGINE_SCOPEs?
  98     private final boolean             _global_per_engine;
  99     // This is the initial default Nashorn global object.
 100     // This is used as "shared" global if above option is true.
 101     private final ScriptObject        global;
 102     // initialized bit late to be made 'final'.
 103     // Property object for "context" property of global object.
 104     private volatile Property         contextProperty;
 105 
 106     // default options passed to Nashorn Options object
 107     private static final String[] DEFAULT_OPTIONS = new String[] { "-scripting", "-doe" };
 108 
 109     // Nashorn script engine error message management
 110     private static final String MESSAGES_RESOURCE = "jdk.nashorn.api.scripting.resources.Messages";
 111 
 112     private static final ResourceBundle MESSAGES_BUNDLE;
 113     static {
 114         MESSAGES_BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, Locale.getDefault());
 115     }
 116 
 117     // helper to get Nashorn script engine error message
 118     private static String getMessage(final String msgId, final String... args) {
 119         try {
 120             return new MessageFormat(MESSAGES_BUNDLE.getString(msgId)).format(args);
 121         } catch (final java.util.MissingResourceException e) {
 122             throw new RuntimeException("no message resource found for message id: "+ msgId);
 123         }
 124     }
 125 
 126     // load engine.js and return content as a char[]
 127     private static char[] loadEngineJSSource() {
 128         final String script = "resources/engine.js";
 129         try {
 130             final InputStream is = AccessController.doPrivileged(
 131                     new PrivilegedExceptionAction<InputStream>() {
 132                         @Override
 133                         public InputStream run() throws Exception {
 134                             final URL url = NashornScriptEngine.class.getResource(script);
 135                             return url.openStream();
 136                         }
 137                     });
 138             return Source.readFully(new InputStreamReader(is));
 139         } catch (final PrivilegedActionException | IOException e) {
 140             if (Context.DEBUG) {
 141                 e.printStackTrace();
 142             }
 143             throw new RuntimeException(e);
 144         }
 145     }
 146 
 147     // Source object for engine.js
 148     private static final Source ENGINE_SCRIPT_SRC = new Source(NashornException.ENGINE_SCRIPT_SOURCE_NAME, loadEngineJSSource());
 149 
 150     NashornScriptEngine(final NashornScriptEngineFactory factory, final ClassLoader appLoader) {
 151         this(factory, DEFAULT_OPTIONS, appLoader);
 152     }
 153 
 154     NashornScriptEngine(final NashornScriptEngineFactory factory, final String[] args, final ClassLoader appLoader) {
 155         this.factory = factory;
 156         final Options options = new Options("nashorn");
 157         options.process(args);
 158 
 159         // throw ParseException on first error from script
 160         final ErrorManager errMgr = new Context.ThrowErrorManager();
 161         // create new Nashorn Context
 162         this.nashornContext = AccessController.doPrivileged(new PrivilegedAction<Context>() {
 163             @Override
 164             public Context run() {
 165                 try {
 166                     return new Context(options, errMgr, appLoader);
 167                 } catch (final RuntimeException e) {
 168                     if (Context.DEBUG) {
 169                         e.printStackTrace();
 170                     }
 171                     throw e;
 172                 }
 173             }
 174         }, CREATE_CONTEXT_ACC_CTXT);
 175 
 176         // cache this option that is used often
 177         this._global_per_engine = nashornContext.getEnv()._global_per_engine;
 178 
 179         // create new global object
 180         this.global = createNashornGlobal(context);
 181         // set the default ENGINE_SCOPE object for the default context
 182         context.setBindings(new ScriptObjectMirror(global, global), ScriptContext.ENGINE_SCOPE);
 183     }
 184 
 185     @Override
 186     public Object eval(final Reader reader, final ScriptContext ctxt) throws ScriptException {
 187         try {
 188             if (reader instanceof URLReader) {
 189                 final URL url = ((URLReader)reader).getURL();
 190                 final Charset cs = ((URLReader)reader).getCharset();
 191                 return evalImpl(compileImpl(new Source(url.toString(), url, cs), ctxt), ctxt);
 192             }
 193             return evalImpl(Source.readFully(reader), ctxt);
 194         } catch (final IOException e) {
 195             throw new ScriptException(e);
 196         }
 197     }
 198 
 199     @Override
 200     public Object eval(final String script, final ScriptContext ctxt) throws ScriptException {
 201         return evalImpl(script.toCharArray(), ctxt);
 202     }
 203 
 204     @Override
 205     public ScriptEngineFactory getFactory() {
 206         return factory;
 207     }
 208 
 209     @Override
 210     public Bindings createBindings() {
 211         if (_global_per_engine) {
 212             // just create normal SimpleBindings.
 213             // We use same 'global' for all Bindings.
 214             return new SimpleBindings();
 215         } else {
 216             return createGlobalMirror(null);
 217         }
 218     }
 219 
 220     // Compilable methods
 221 
 222     @Override
 223     public CompiledScript compile(final Reader reader) throws ScriptException {
 224         try {
 225             return asCompiledScript(compileImpl(Source.readFully(reader), context));
 226         } catch (final IOException e) {
 227             throw new ScriptException(e);
 228         }
 229     }
 230 
 231     @Override
 232     public CompiledScript compile(final String str) throws ScriptException {
 233         return asCompiledScript(compileImpl(str.toCharArray(), context));
 234     }
 235 
 236     // Invocable methods
 237 
 238     @Override
 239     public Object invokeFunction(final String name, final Object... args)
 240             throws ScriptException, NoSuchMethodException {
 241         return invokeImpl(null, name, args);
 242     }
 243 
 244     @Override
 245     public Object invokeMethod(final Object thiz, final String name, final Object... args)
 246             throws ScriptException, NoSuchMethodException {
 247         if (thiz == null) {
 248             throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
 249         }
 250         return invokeImpl(thiz, name, args);
 251     }
 252 
 253     @Override
 254     public <T> T getInterface(final Class<T> clazz) {
 255         return getInterfaceInner(null, clazz);
 256     }
 257 
 258     @Override
 259     public <T> T getInterface(final Object thiz, final Class<T> clazz) {
 260         if (thiz == null) {
 261             throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
 262         }
 263         return getInterfaceInner(thiz, clazz);
 264     }
 265 
 266     // These are called from the "engine.js" script
 267 
 268     /**
 269      * This hook is used to search js global variables exposed from Java code.
 270      *
 271      * @param self 'this' passed from the script
 272      * @param ctxt current ScriptContext in which name is searched
 273      * @param name name of the variable searched
 274      * @return the value of the named variable
 275      */
 276     public Object __noSuchProperty__(final Object self, final ScriptContext ctxt, final String name) {
 277         if (ctxt != null) {
 278             final int scope = ctxt.getAttributesScope(name);
 279             final ScriptObject ctxtGlobal = getNashornGlobalFrom(ctxt);
 280             if (scope != -1) {
 281                 return ScriptObjectMirror.unwrap(ctxt.getAttribute(name, scope), ctxtGlobal);
 282             }
 283 
 284             if (self == UNDEFINED) {
 285                 // scope access and so throw ReferenceError
 286                 throw referenceError(ctxtGlobal, "not.defined", name);
 287             }
 288         }
 289 
 290         return UNDEFINED;
 291     }
 292 
 293     // Implementation only below this point
 294 
 295     private <T> T getInterfaceInner(final Object thiz, final Class<T> clazz) {
 296         if (clazz == null || !clazz.isInterface()) {
 297             throw new IllegalArgumentException(getMessage("interface.class.expected"));
 298         }
 299 
 300         // perform security access check as early as possible
 301         final SecurityManager sm = System.getSecurityManager();
 302         if (sm != null) {
 303             if (! Modifier.isPublic(clazz.getModifiers())) {
 304                 throw new SecurityException(getMessage("implementing.non.public.interface", clazz.getName()));
 305             }
 306             Context.checkPackageAccess(clazz.getName());
 307         }
 308 
 309         ScriptObject realSelf = null;
 310         ScriptObject realGlobal = null;
 311         if(thiz == null) {
 312             // making interface out of global functions
 313             realSelf = realGlobal = getNashornGlobalFrom(context);
 314         } else if (thiz instanceof ScriptObjectMirror) {
 315             final ScriptObjectMirror mirror = (ScriptObjectMirror)thiz;
 316             realSelf = mirror.getScriptObject();
 317             realGlobal = mirror.getHomeGlobal();
 318             if (! realGlobal.isOfContext(nashornContext)) {
 319                 throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
 320             }
 321         } else if (thiz instanceof ScriptObject) {
 322             // called from script code.
 323             realSelf = (ScriptObject)thiz;
 324             realGlobal = Context.getGlobal();
 325             if (realGlobal == null) {
 326                 throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
 327             }
 328 
 329             if (! realGlobal.isOfContext(nashornContext)) {
 330                 throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
 331             }
 332         }
 333 
 334         if (realSelf == null) {
 335             throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
 336         }
 337 
 338         try {
 339             final ScriptObject oldGlobal = Context.getGlobal();
 340             final boolean globalChanged = (oldGlobal != realGlobal);
 341             try {
 342                 if (globalChanged) {
 343                     Context.setGlobal(realGlobal);
 344                 }
 345 
 346                 if (! isInterfaceImplemented(clazz, realSelf)) {
 347                     return null;
 348                 }
 349                 return clazz.cast(JavaAdapterFactory.getConstructor(realSelf.getClass(), clazz).invoke(realSelf));
 350             } finally {
 351                 if (globalChanged) {
 352                     Context.setGlobal(oldGlobal);
 353                 }
 354             }
 355         } catch(final RuntimeException|Error e) {
 356             throw e;
 357         } catch(final Throwable t) {
 358             throw new RuntimeException(t);
 359         }
 360     }
 361 
 362     // Retrieve nashorn Global object for a given ScriptContext object
 363     private ScriptObject getNashornGlobalFrom(final ScriptContext ctxt) {
 364         if (_global_per_engine) {
 365             // shared single global object for all ENGINE_SCOPE Bindings
 366             return global;
 367         }
 368 
 369         final Bindings bindings = ctxt.getBindings(ScriptContext.ENGINE_SCOPE);
 370         // is this Nashorn's own Bindings implementation?
 371         if (bindings instanceof ScriptObjectMirror) {
 372             final ScriptObject sobj = globalFromMirror((ScriptObjectMirror)bindings);
 373             if (sobj != null) {
 374                 return sobj;
 375             }
 376         }
 377 
 378         // Arbitrary user Bindings implementation. Look for NASHORN_GLOBAL in it!
 379         Object scope = bindings.get(NASHORN_GLOBAL);
 380         if (scope instanceof ScriptObjectMirror) {
 381             final ScriptObject sobj = globalFromMirror((ScriptObjectMirror)scope);
 382             if (sobj != null) {
 383                 return sobj;
 384             }
 385         }
 386 
 387         // We didn't find associated nashorn global mirror in the Bindings given!
 388         // Create new global instance mirror and associate with the Bindings.
 389         final ScriptObjectMirror mirror = createGlobalMirror(ctxt);
 390         bindings.put(NASHORN_GLOBAL, mirror);
 391         return mirror.getScriptObject();
 392     }
 393 
 394     // Retrieve nashorn Global object from a given ScriptObjectMirror
 395     private ScriptObject globalFromMirror(final ScriptObjectMirror mirror) {
 396         ScriptObject sobj = mirror.getScriptObject();
 397         if (sobj instanceof GlobalObject && sobj.isOfContext(nashornContext)) {
 398             return sobj;
 399         }
 400 
 401         return null;
 402     }
 403 
 404     // Create a new ScriptObjectMirro wrapping a newly created Nashorn Global object
 405     private ScriptObjectMirror createGlobalMirror(final ScriptContext ctxt) {
 406         final ScriptObject newGlobal = createNashornGlobal(ctxt);
 407         return new ScriptObjectMirror(newGlobal, newGlobal);
 408     }
 409 
 410     // Create a new Nashorn Global object
 411     private ScriptObject createNashornGlobal(final ScriptContext ctxt) {
 412         final ScriptObject newGlobal = AccessController.doPrivileged(new PrivilegedAction<ScriptObject>() {
 413             @Override
 414             public ScriptObject run() {
 415                 try {
 416                     return nashornContext.newGlobal();
 417                 } catch (final RuntimeException e) {
 418                     if (Context.DEBUG) {
 419                         e.printStackTrace();
 420                     }
 421                     throw e;
 422                 }
 423             }
 424         }, CREATE_GLOBAL_ACC_CTXT);
 425 
 426         nashornContext.initGlobal(newGlobal);
 427 
 428         final int NON_ENUMERABLE_CONSTANT = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE;
 429         // current ScriptContext exposed as "context"
 430         // "context" is non-writable from script - but script engine still
 431         // needs to set it and so save the context Property object
 432         contextProperty = newGlobal.addOwnProperty("context", NON_ENUMERABLE_CONSTANT, null);
 433         // current ScriptEngine instance exposed as "engine". We added @SuppressWarnings("LeakingThisInConstructor") as
 434         // NetBeans identifies this assignment as such a leak - this is a false positive as we're setting this property
 435         // in the Global of a Context we just created - both the Context and the Global were just created and can not be
 436         // seen from another thread outside of this constructor.
 437         newGlobal.addOwnProperty("engine", NON_ENUMERABLE_CONSTANT, this);
 438         // global script arguments with undefined value
 439         newGlobal.addOwnProperty("arguments", Property.NOT_ENUMERABLE, UNDEFINED);
 440         // file name default is null
 441         newGlobal.addOwnProperty(ScriptEngine.FILENAME, Property.NOT_ENUMERABLE, null);
 442         // evaluate engine.js initialization script this new global object
 443         try {
 444             evalImpl(compileImpl(ENGINE_SCRIPT_SRC, newGlobal), ctxt, newGlobal);
 445         } catch (final ScriptException exp) {
 446             throw new RuntimeException(exp);
 447         }
 448         return newGlobal;
 449     }
 450 
 451     // scripts should see "context" and "engine" as variables in the given global object
 452     private void setContextVariables(final ScriptObject ctxtGlobal, final ScriptContext ctxt) {
 453         // set "context" global variable via contextProperty - because this
 454         // property is non-writable
 455         contextProperty.setObjectValue(ctxtGlobal, ctxtGlobal, ctxt, false);
 456         Object args = ScriptObjectMirror.unwrap(ctxt.getAttribute("arguments"), ctxtGlobal);
 457         if (args == null || args == UNDEFINED) {
 458             args = ScriptRuntime.EMPTY_ARRAY;
 459         }
 460         // if no arguments passed, expose it
 461         if (! (args instanceof ScriptObject)) {
 462             args = ((GlobalObject)ctxtGlobal).wrapAsObject(args);
 463             ctxtGlobal.set("arguments", args, false);
 464         }
 465     }
 466 
 467     private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
 468         name.getClass(); // null check
 469 
 470         ScriptObjectMirror selfMirror = null;
 471         if (selfObject instanceof ScriptObjectMirror) {
 472             selfMirror = (ScriptObjectMirror)selfObject;
 473             if (! selfMirror.getHomeGlobal().isOfContext(nashornContext)) {
 474                 throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
 475             }
 476         } else if (selfObject instanceof ScriptObject) {
 477             // invokeMethod called from script code - in which case we may get 'naked' ScriptObject
 478             // Wrap it with oldGlobal to make a ScriptObjectMirror for the same.
 479             final ScriptObject oldGlobal = Context.getGlobal();
 480             if (oldGlobal == null) {
 481                 throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
 482             }
 483 
 484             if (! oldGlobal.isOfContext(nashornContext)) {
 485                 throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
 486             }
 487 
 488             selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(selfObject, oldGlobal);
 489         } else if (selfObject == null) {
 490             // selfObject is null => global function call
 491             final ScriptObject ctxtGlobal = getNashornGlobalFrom(context);
 492             selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(ctxtGlobal, ctxtGlobal);
 493         }
 494 
 495         if (selfMirror != null) {
 496             try {
 497                 return ScriptObjectMirror.translateUndefined(selfMirror.call(name, args));
 498             } catch (final Exception e) {
 499                 final Throwable cause = e.getCause();
 500                 if (cause instanceof NoSuchMethodException) {
 501                     throw (NoSuchMethodException)cause;
 502                 }
 503                 throwAsScriptException(e);
 504                 throw new AssertionError("should not reach here");
 505             }
 506         }
 507 
 508         // Non-script object passed as selfObject
 509         throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
 510     }
 511 
 512     private Object evalImpl(final char[] buf, final ScriptContext ctxt) throws ScriptException {
 513         return evalImpl(compileImpl(buf, ctxt), ctxt);
 514     }
 515 
 516     private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt) throws ScriptException {
 517         return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
 518     }
 519 
 520     private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
 521         if (script == null) {
 522             return null;
 523         }
 524         final ScriptObject oldGlobal = Context.getGlobal();
 525         final boolean globalChanged = (oldGlobal != ctxtGlobal);
 526         try {
 527             if (globalChanged) {
 528                 Context.setGlobal(ctxtGlobal);
 529             }
 530 
 531             // set ScriptContext variables if ctxt is non-null
 532             if (ctxt != null) {
 533                 setContextVariables(ctxtGlobal, ctxt);
 534             }
 535             return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
 536         } catch (final Exception e) {
 537             throwAsScriptException(e);
 538             throw new AssertionError("should not reach here");
 539         } finally {
 540             if (globalChanged) {
 541                 Context.setGlobal(oldGlobal);
 542             }
 543         }
 544     }
 545 
 546     private static void throwAsScriptException(final Exception e) throws ScriptException {
 547         if (e instanceof ScriptException) {
 548             throw (ScriptException)e;
 549         } else if (e instanceof NashornException) {
 550             final NashornException ne = (NashornException)e;
 551             final ScriptException se = new ScriptException(
 552                 ne.getMessage(), ne.getFileName(),
 553                 ne.getLineNumber(), ne.getColumnNumber());
 554             se.initCause(e);
 555             throw se;
 556         } else if (e instanceof RuntimeException) {
 557             throw (RuntimeException)e;
 558         } else {
 559             // wrap any other exception as ScriptException
 560             throw new ScriptException(e);
 561         }
 562     }
 563 
 564     private CompiledScript asCompiledScript(final ScriptFunction script) {
 565         return new CompiledScript() {
 566             @Override
 567             public Object eval(final ScriptContext ctxt) throws ScriptException {
 568                 return evalImpl(script, ctxt);
 569             }
 570             @Override
 571             public ScriptEngine getEngine() {
 572                 return NashornScriptEngine.this;
 573             }
 574         };
 575     }
 576 
 577     private ScriptFunction compileImpl(final char[] buf, final ScriptContext ctxt) throws ScriptException {
 578         final Object val = ctxt.getAttribute(ScriptEngine.FILENAME);
 579         final String fileName = (val != null) ? val.toString() : "<eval>";
 580         return compileImpl(new Source(fileName, buf), ctxt);
 581     }
 582 
 583     private ScriptFunction compileImpl(final Source source, final ScriptContext ctxt) throws ScriptException {
 584         return compileImpl(source, getNashornGlobalFrom(ctxt));
 585     }
 586 
 587     private ScriptFunction compileImpl(final Source source, final ScriptObject newGlobal) throws ScriptException {
 588         final ScriptObject oldGlobal = Context.getGlobal();
 589         final boolean globalChanged = (oldGlobal != newGlobal);
 590         try {
 591             if (globalChanged) {
 592                 Context.setGlobal(newGlobal);
 593             }
 594 
 595             return nashornContext.compileScript(source, newGlobal);
 596         } catch (final Exception e) {
 597             throwAsScriptException(e);
 598             throw new AssertionError("should not reach here");
 599         } finally {
 600             if (globalChanged) {
 601                 Context.setGlobal(oldGlobal);
 602             }
 603         }
 604     }
 605 
 606     private static boolean isInterfaceImplemented(final Class<?> iface, final ScriptObject sobj) {
 607         for (final Method method : iface.getMethods()) {
 608             // ignore methods of java.lang.Object class
 609             if (method.getDeclaringClass() == Object.class) {
 610                 continue;
 611             }
 612 
 613             Object obj = sobj.get(method.getName());
 614             if (! (obj instanceof ScriptFunction)) {
 615                 return false;
 616             }
 617         }
 618         return true;
 619     }
 620 }