Debian Codegraph @

rhino/src/org/mozilla/javascript/Context.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // API class
8
9 package org.mozilla.javascript;
10
11 import java.beans.PropertyChangeEvent;
12 import java.beans.PropertyChangeListener;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.io.PrintWriter;
16 import java.io.Reader;
17 import java.io.StringWriter;
18 import java.io.Writer;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.net.URL;
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.jar.Attributes;
29 import java.util.jar.Manifest;
30
31 import org.mozilla.javascript.ast.AstRoot;
32 import org.mozilla.javascript.ast.ScriptNode;
33 import org.mozilla.javascript.debug.DebuggableScript;
34 import org.mozilla.javascript.debug.Debugger;
35 import org.mozilla.javascript.xml.XMLLib;
36
37 /**
38 * This class represents the runtime context of an executing script.
39 *
40 * Before executing a script, an instance of Context must be created
41 * and associated with the thread that will be executing the script.
42 * The Context will be used to store information about the executing
43 * of the script such as the call stack. Contexts are associated with
44 * the current thread using the {@link #call(ContextAction)}
45 * or {@link #enter()} methods.<p>
46 *
47 * Different forms of script execution are supported. Scripts may be
48 * evaluated from the source directly, or first compiled and then later
49 * executed. Interactive execution is also supported.<p>
50 *
51 * Some aspects of script execution, such as type conversions and
52 * object creation, may be accessed directly through methods of
53 * Context.
54 *
55 * @see Scriptable
56 * @author Norris Boyd
57 * @author Brendan Eich
58 */
59
60 public class Context
61 {
62 /**
63 * Language versions.
64 *
65 * All integral values are reserved for future version numbers.
66 */
67
68 /**
69 * The unknown version.
70 */
71 public static final int VERSION_UNKNOWN = -1;
72
73 /**
74 * The default version.
75 */
76 public static final int VERSION_DEFAULT = 0;
77
78 /**
79 * JavaScript 1.0
80 */
81 public static final int VERSION_1_0 = 100;
82
83 /**
84 * JavaScript 1.1
85 */
86 public static final int VERSION_1_1 = 110;
87
88 /**
89 * JavaScript 1.2
90 */
91 public static final int VERSION_1_2 = 120;
92
93 /**
94 * JavaScript 1.3
95 */
96 public static final int VERSION_1_3 = 130;
97
98 /**
99 * JavaScript 1.4
100 */
101 public static final int VERSION_1_4 = 140;
102
103 /**
104 * JavaScript 1.5
105 */
106 public static final int VERSION_1_5 = 150;
107
108 /**
109 * JavaScript 1.6
110 */
111 public static final int VERSION_1_6 = 160;
112
113 /**
114 * JavaScript 1.7
115 */
116 public static final int VERSION_1_7 = 170;
117
118 /**
119 * JavaScript 1.8
120 */
121 public static final int VERSION_1_8 = 180;
122
123 /**
124 * ECMAScript 6.
125 */
126 public static final int VERSION_ES6 = 200;
127
128 /**
129 * Controls behaviour of <tt>Date.prototype.getYear()</tt>.
130 * If <tt>hasFeature(FEATURE_NON_ECMA_GET_YEAR)</tt> returns true,
131 * Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000.
132 * The default behavior of {@link #hasFeature(int)} is always to subtruct
133 * 1900 as rquired by ECMAScript B.2.4.
134 */
135 public static final int FEATURE_NON_ECMA_GET_YEAR = 1;
136
137 /**
138 * Control if member expression as function name extension is available.
139 * If <tt>hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME)</tt> returns
140 * true, allow <tt>function memberExpression(args) { body }</tt> to be
141 * syntax sugar for <tt>memberExpression = function(args) { body }</tt>,
142 * when memberExpression is not a simple identifier.
143 * See ECMAScript-262, section 11.2 for definition of memberExpression.
144 * By default {@link #hasFeature(int)} returns false.
145 */
146 public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2;
147
148 /**
149 * Control if reserved keywords are treated as identifiers.
150 * If <tt>hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER)</tt> returns true,
151 * treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary
152 * identifiers but warn about this usage.
153 *
154 * By default {@link #hasFeature(int)} returns false.
155 */
156 public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3;
157
158 /**
159 * Control if <tt>toString()</tt> should returns the same result
160 * as <tt>toSource()</tt> when applied to objects and arrays.
161 * If <tt>hasFeature(FEATURE_TO_STRING_AS_SOURCE)</tt> returns true,
162 * calling <tt>toString()</tt> on JS objects gives the same result as
163 * calling <tt>toSource()</tt>. That is it returns JS source with code
164 * to create an object with all enumeratable fields of the original object
165 * instead of printing <tt>[object <i>result of
166 * {@link Scriptable#getClassName()}</i>]</tt>.
167 * <p>
168 * By default {@link #hasFeature(int)} returns true only if
169 * the current JS version is set to {@link #VERSION_1_2}.
170 */
171 public static final int FEATURE_TO_STRING_AS_SOURCE = 4;
172
173 /**
174 * Control if properties <tt>__proto__</tt> and <tt>__parent__</tt>
175 * are treated specially.
176 * If <tt>hasFeature(FEATURE_PARENT_PROTO_PROPERTIES)</tt> returns true,
177 * treat <tt>__parent__</tt> and <tt>__proto__</tt> as special properties.
178 * <p>
179 * The properties allow to query and set scope and prototype chains for the
180 * objects. The special meaning of the properties is available
181 * only when they are used as the right hand side of the dot operator.
182 * For example, while <tt>x.__proto__ = y</tt> changes the prototype
183 * chain of the object <tt>x</tt> to point to <tt>y</tt>,
184 * <tt>x["__proto__"] = y</tt> simply assigns a new value to the property
185 * <tt>__proto__</tt> in <tt>x</tt> even when the feature is on.
186 *
187 * By default {@link #hasFeature(int)} returns true.
188 */
189 public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5;
190
191 /**
192 * @deprecated In previous releases, this name was given to
193 * FEATURE_PARENT_PROTO_PROPERTIES.
194 */
195 @Deprecated
196 public static final int FEATURE_PARENT_PROTO_PROPRTIES = 5;
197
198 /**
199 * Control if support for E4X(ECMAScript for XML) extension is available.
200 * If hasFeature(FEATURE_E4X) returns true, the XML syntax is available.
201 * <p>
202 * By default {@link #hasFeature(int)} returns true if
203 * the current JS version is set to {@link #VERSION_DEFAULT}
204 * or is at least {@link #VERSION_1_6}.
205 * @since 1.6 Release 1
206 */
207 public static final int FEATURE_E4X = 6;
208
209 /**
210 * Control if dynamic scope should be used for name access.
211 * If hasFeature(FEATURE_DYNAMIC_SCOPE) returns true, then the name lookup
212 * during name resolution will use the top scope of the script or function
213 * which is at the top of JS execution stack instead of the top scope of the
214 * script or function from the current stack frame if the top scope of
215 * the top stack frame contains the top scope of the current stack frame
216 * on its prototype chain.
217 * <p>
218 * This is useful to define shared scope containing functions that can
219 * be called from scripts and functions using private scopes.
220 * <p>
221 * By default {@link #hasFeature(int)} returns false.
222 * @since 1.6 Release 1
223 */
224 public static final int FEATURE_DYNAMIC_SCOPE = 7;
225
226 /**
227 * Control if strict variable mode is enabled.
228 * When the feature is on Rhino reports runtime errors if assignment
229 * to a global variable that does not exist is executed. When the feature
230 * is off such assignments create a new variable in the global scope as
231 * required by ECMA 262.
232 * <p>
233 * By default {@link #hasFeature(int)} returns false.
234 * @since 1.6 Release 1
235 */
236 public static final int FEATURE_STRICT_VARS = 8;
237
238 /**
239 * Control if strict eval mode is enabled.
240 * When the feature is on Rhino reports runtime errors if non-string
241 * argument is passed to the eval function. When the feature is off
242 * eval simply return non-string argument as is without performing any
243 * evaluation as required by ECMA 262.
244 * <p>
245 * By default {@link #hasFeature(int)} returns false.
246 * @since 1.6 Release 1
247 */
248 public static final int FEATURE_STRICT_EVAL = 9;
249
250 /**
251 * When the feature is on Rhino will add a "fileName" and "lineNumber"
252 * properties to Error objects automatically. When the feature is off, you
253 * have to explicitly pass them as the second and third argument to the
254 * Error constructor. Note that neither behavior is fully ECMA 262
255 * compliant (as 262 doesn't specify a three-arg constructor), but keeping
256 * the feature off results in Error objects that don't have
257 * additional non-ECMA properties when constructed using the ECMA-defined
258 * single-arg constructor and is thus desirable if a stricter ECMA
259 * compliance is desired, specifically adherence to the point 15.11.5. of
260 * the standard.
261 * <p>
262 * By default {@link #hasFeature(int)} returns false.
263 * @since 1.6 Release 6
264 */
265 public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10;
266
267 /**
268 * Controls whether JS 1.5 'strict mode' is enabled.
269 * When the feature is on, Rhino reports more than a dozen different
270 * warnings. When the feature is off, these warnings are not generated.
271 * FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL.
272 * <p>
273 * By default {@link #hasFeature(int)} returns false.
274 * @since 1.6 Release 6
275 */
276 public static final int FEATURE_STRICT_MODE = 11;
277
278 /**
279 * Controls whether a warning should be treated as an error.
280 * @since 1.6 Release 6
281 */
282 public static final int FEATURE_WARNING_AS_ERROR = 12;
283
284 /**
285 * Enables enhanced access to Java.
286 * Specifically, controls whether private and protected members can be
287 * accessed, and whether scripts can catch all Java exceptions.
288 * <p>
289 * Note that this feature should only be enabled for trusted scripts.
290 * <p>
291 * By default {@link #hasFeature(int)} returns false.
292 * @since 1.7 Release 1
293 */
294 public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13;
295
296 /**
297 * Enables access to JavaScript features from ECMAscript 6 that are present in
298 * JavaScript engines that do not yet support version 6, such as V8.
299 * This includes support for typed arrays. Default is true.
300 * @since 1.7 Release 3
301 */
302 public static final int FEATURE_V8_EXTENSIONS = 14;
303
304 /**
305 * Defines how an undefined "this" parameter is handled in certain calls. Previously Rhino
306 * would convert an undefined "this" to null, whereas recent specs call for it to be treated
307 * differently. Default is to be set if language version <= 1.7.
308 * @since 1.7.7
309 */
310 public static final int FEATURE_OLD_UNDEF_NULL_THIS = 15;
311
312 /**
313 * If set, then the order of property key enumeration will be first numeric keys in numeric order,
314 * followed by string keys in order of creation, and finally Symbol keys, as specified in ES6.
315 * Default is true for language version >= "ES6" and false otherwise.
316 * @since 1.7.8
317 */
318 public static final int FEATURE_ENUMERATE_IDS_FIRST = 16;
319
320 public static final String languageVersionProperty = "language version";
321 public static final String errorReporterProperty = "error reporter";
322
323 /**
324 * Convenient value to use as zero-length array of objects.
325 */
326 public static final Object[] emptyArgs = ScriptRuntime.emptyArgs;
327
328 /**
329 * Creates a new Context. The context will be associated with the {@link
330 * ContextFactory#getGlobal() global context factory}.
331 *
332 * Note that the Context must be associated with a thread before
333 * it can be used to execute a script.
334 * @deprecated this constructor is deprecated because it creates a
335 * dependency on a static singleton context factory. Use
336 * {@link ContextFactory#enter()} or
337 * {@link ContextFactory#call(ContextAction)} instead. If you subclass
338 * this class, consider using {@link #Context(ContextFactory)} constructor
339 * instead in the subclasses' constructors.
340 */
341 @Deprecated
342 public Context()
343 {
344 this(ContextFactory.getGlobal());
345 }
346
347 /**
348 * Creates a new context. Provided as a preferred super constructor for
349 * subclasses in place of the deprecated default public constructor.
350 * @param factory the context factory associated with this context (most
351 * likely, the one that created the context). Can not be null. The context
352 * features are inherited from the factory, and the context will also
353 * otherwise use its factory's services.
354 * @throws IllegalArgumentException if factory parameter is null.
355 */
356 protected Context(ContextFactory factory)
357 {
358 if(factory == null) {
359 throw new IllegalArgumentException("factory == null");
360 }
361 this.factory = factory;
362 version = VERSION_DEFAULT;
363 optimizationLevel = codegenClass != null ? 0 : -1;
364 maximumInterpreterStackDepth = Integer.MAX_VALUE;
365 }
366
367 /**
368 * Get the current Context.
369 *
370 * The current Context is per-thread; this method looks up
371 * the Context associated with the current thread. <p>
372 *
373 * @return the Context associated with the current thread, or
374 * null if no context is associated with the current
375 * thread.
376 * @see ContextFactory#enterContext()
377 * @see ContextFactory#call(ContextAction)
378 */
379 public static Context getCurrentContext()
380 {
381 Object helper = VMBridge.instance.getThreadContextHelper();
382 return VMBridge.instance.getContext(helper);
383 }
384
385 /**
386 * Same as calling {@link ContextFactory#enterContext()} on the global
387 * ContextFactory instance.
388 * @return a Context associated with the current thread
389 * @see #getCurrentContext()
390 * @see #exit()
391 * @see #call(ContextAction)
392 */
393 public static Context enter()
394 {
395 return enter(null);
396 }
397
398 /**
399 * Get a Context associated with the current thread, using
400 * the given Context if need be.
401 * <p>
402 * The same as <code>enter()</code> except that <code>cx</code>
403 * is associated with the current thread and returned if
404 * the current thread has no associated context and <code>cx</code>
405 * is not associated with any other thread.
406 * @param cx a Context to associate with the thread if possible
407 * @return a Context associated with the current thread
408 * @deprecated use {@link ContextFactory#enterContext(Context)} instead as
409 * this method relies on usage of a static singleton "global" ContextFactory.
410 * @see ContextFactory#enterContext(Context)
411 * @see ContextFactory#call(ContextAction)
412 */
413 @Deprecated
414 public static Context enter(Context cx)
415 {
416 return enter(cx, ContextFactory.getGlobal());
417 }
418
419 static final Context enter(Context cx, ContextFactory factory)
420 {
421 Object helper = VMBridge.instance.getThreadContextHelper();
422 Context old = VMBridge.instance.getContext(helper);
423 if (old != null) {
424 cx = old;
425 } else {
426 if (cx == null) {
427 cx = factory.makeContext();
428 if (cx.enterCount != 0) {
429 throw new IllegalStateException("factory.makeContext() returned Context instance already associated with some thread");
430 }
431 factory.onContextCreated(cx);
432 if (factory.isSealed() && !cx.isSealed()) {
433 cx.seal(null);
434 }
435 } else {
436 if (cx.enterCount != 0) {
437 throw new IllegalStateException("can not use Context instance already associated with some thread");
438 }
439 }
440 VMBridge.instance.setContext(helper, cx);
441 }
442 ++cx.enterCount;
443 return cx;
444 }
445
446 /**
447 * Exit a block of code requiring a Context.
448 *
449 * Calling <code>exit()</code> will remove the association between
450 * the current thread and a Context if the prior call to
451 * {@link ContextFactory#enterContext()} on this thread newly associated a
452 * Context with this thread. Once the current thread no longer has an
453 * associated Context, it cannot be used to execute JavaScript until it is
454 * again associated with a Context.
455 * @see ContextFactory#enterContext()
456 */
457 public static void exit()
458 {
459 Object helper = VMBridge.instance.getThreadContextHelper();
460 Context cx = VMBridge.instance.getContext(helper);
461 if (cx == null) {
462 throw new IllegalStateException(
463 "Calling Context.exit without previous Context.enter");
464 }
465 if (cx.enterCount < 1) Kit.codeBug();
466 if (--cx.enterCount == 0) {
467 VMBridge.instance.setContext(helper, null);
468 cx.factory.onContextReleased(cx);
469 }
470 }
471
472 /**
473 * Call {@link ContextAction#run(Context cx)}
474 * using the Context instance associated with the current thread.
475 * If no Context is associated with the thread, then
476 * <tt>ContextFactory.getGlobal().makeContext()</tt> will be called to
477 * construct new Context instance. The instance will be temporary
478 * associated with the thread during call to
479 * {@link ContextAction#run(Context)}.
480 * @deprecated use {@link ContextFactory#call(ContextAction)} instead as
481 * this method relies on usage of a static singleton "global"
482 * ContextFactory.
483 * @return The result of {@link ContextAction#run(Context)}.
484 */
485 @Deprecated
486 public static Object call(ContextAction action)
487 {
488 return call(ContextFactory.getGlobal(), action);
489 }
490
491 /**
492 * Call {@link
493 * Callable#call(Context cx, Scriptable scope, Scriptable thisObj,
494 * Object[] args)}
495 * using the Context instance associated with the current thread.
496 * If no Context is associated with the thread, then
497 * {@link ContextFactory#makeContext()} will be called to construct
498 * new Context instance. The instance will be temporary associated
499 * with the thread during call to {@link ContextAction#run(Context)}.
500 * <p>
501 * It is allowed but not advisable to use null for <tt>factory</tt>
502 * argument in which case the global static singleton ContextFactory
503 * instance will be used to create new context instances.
504 * @see ContextFactory#call(ContextAction)
505 */
506 public static Object call(ContextFactory factory, final Callable callable,
507 final Scriptable scope, final Scriptable thisObj,
508 final Object[] args)
509 {
510 if(factory == null) {
511 factory = ContextFactory.getGlobal();
512 }
513 return call(factory, new ContextAction() {
514 public Object run(Context cx) {
515 return callable.call(cx, scope, thisObj, args);
516 }
517 });
518 }
519
520 /**
521 * The method implements {@link ContextFactory#call(ContextAction)} logic.
522 */
523 static Object call(ContextFactory factory, ContextAction action) {
524 Context cx = enter(null, factory);
525 try {
526 return action.run(cx);
527 }
528 finally {
529 exit();
530 }
531 }
532
533 /**
534 * @deprecated
535 * @see ContextFactory#addListener(org.mozilla.javascript.ContextFactory.Listener)
536 * @see ContextFactory#getGlobal()
537 */
538 @Deprecated
539 public static void addContextListener(ContextListener listener)
540 {
541 // Special workaround for the debugger
542 String DBG = "org.mozilla.javascript.tools.debugger.Main";
543 if (DBG.equals(listener.getClass().getName())) {
544 Class<?> cl = listener.getClass();
545 Class<?> factoryClass = Kit.classOrNull(
546 "org.mozilla.javascript.ContextFactory");
547 Class<?>[] sig = { factoryClass };
548 Object[] args = { ContextFactory.getGlobal() };
549 try {
550 Method m = cl.getMethod("attachTo", sig);
551 m.invoke(listener, args);
552 } catch (Exception ex) {
553 RuntimeException rex = new RuntimeException();
554 Kit.initCause(rex, ex);
555 throw rex;
556 }
557 return;
558 }
559
560 ContextFactory.getGlobal().addListener(listener);
561 }
562
563 /**
564 * @deprecated
565 * @see ContextFactory#removeListener(org.mozilla.javascript.ContextFactory.Listener)
566 * @see ContextFactory#getGlobal()
567 */
568 @Deprecated
569 public static void removeContextListener(ContextListener listener)
570 {
571 ContextFactory.getGlobal().addListener(listener);
572 }
573
574 /**
575 * Return {@link ContextFactory} instance used to create this Context.
576 */
577 public final ContextFactory getFactory()
578 {
579 return factory;
580 }
581
582 /**
583 * Checks if this is a sealed Context. A sealed Context instance does not
584 * allow to modify any of its properties and will throw an exception
585 * on any such attempt.
586 * @see #seal(Object sealKey)
587 */
588 public final boolean isSealed()
589 {
590 return sealed;
591 }
592
593 /**
594 * Seal this Context object so any attempt to modify any of its properties
595 * including calling {@link #enter()} and {@link #exit()} methods will
596 * throw an exception.
597 * <p>
598 * If <tt>sealKey</tt> is not null, calling
599 * {@link #unseal(Object sealKey)} with the same key unseals
600 * the object. If <tt>sealKey</tt> is null, unsealing is no longer possible.
601 *
602 * @see #isSealed()
603 * @see #unseal(Object)
604 */
605 public final void seal(Object sealKey)
606 {
607 if (sealed) onSealedMutation();
608 sealed = true;
609 this.sealKey = sealKey;
610 }
611
612 /**
613 * Unseal previously sealed Context object.
614 * The <tt>sealKey</tt> argument should not be null and should match
615 * <tt>sealKey</tt> suplied with the last call to
616 * {@link #seal(Object)} or an exception will be thrown.
617 *
618 * @see #isSealed()
619 * @see #seal(Object sealKey)
620 */
621 public final void unseal(Object sealKey)
622 {
623 if (sealKey == null) throw new IllegalArgumentException();
624 if (this.sealKey != sealKey) throw new IllegalArgumentException();
625 if (!sealed) throw new IllegalStateException();
626 sealed = false;
627 this.sealKey = null;
628 }
629
630 static void onSealedMutation()
631 {
632 throw new IllegalStateException();
633 }
634
635 /**
636 * Get the current language version.
637 * <p>
638 * The language version number affects JavaScript semantics as detailed
639 * in the overview documentation.
640 *
641 * @return an integer that is one of VERSION_1_0, VERSION_1_1, etc.
642 */
643 public final int getLanguageVersion()
644 {
645 return version;
646 }
647
648 /**
649 * Set the language version.
650 *
651 * <p>
652 * Setting the language version will affect functions and scripts compiled
653 * subsequently. See the overview documentation for version-specific
654 * behavior.
655 *
656 * @param version the version as specified by VERSION_1_0, VERSION_1_1, etc.
657 */
658 public void setLanguageVersion(int version)
659 {
660 if (sealed) onSealedMutation();
661 checkLanguageVersion(version);
662 Object listeners = propertyListeners;
663 if (listeners != null && version != this.version) {
664 firePropertyChangeImpl(listeners, languageVersionProperty,
665 Integer.valueOf(this.version),
666 Integer.valueOf(version));
667 }
668 this.version = version;
669 }
670
671 public static boolean isValidLanguageVersion(int version)
672 {
673 switch (version) {
674 case VERSION_DEFAULT:
675 case VERSION_1_0:
676 case VERSION_1_1:
677 case VERSION_1_2:
678 case VERSION_1_3:
679 case VERSION_1_4:
680 case VERSION_1_5:
681 case VERSION_1_6:
682 case VERSION_1_7:
683 case VERSION_1_8:
684 case VERSION_ES6:
685 return true;
686 }
687 return false;
688 }
689
690 public static void checkLanguageVersion(int version)
691 {
692 if (isValidLanguageVersion(version)) {
693 return;
694 }
695 throw new IllegalArgumentException("Bad language version: "+version);
696 }
697
698 /**
699 * Get the implementation version.
700 *
701 * <p>
702 * The implementation version is of the form
703 * <pre>
704 * "<i>name langVer</i> <code>release</code> <i>relNum date</i>"
705 * </pre>
706 * where <i>name</i> is the name of the product, <i>langVer</i> is
707 * the language version, <i>relNum</i> is the release number, and
708 * <i>date</i> is the release date for that specific
709 * release in the form "yyyy mm dd".
710 *
711 * @return a string that encodes the product, language version, release
712 * number, and date.
713 */
714 public final String getImplementationVersion()
715 {
716 if (implementationVersion == null) {
717 Enumeration<URL> urls;
718 try {
719 urls = Context.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
720 } catch (IOException ioe) {
721 return null;
722 }
723
724 // There will be many manifests in the world -- enumerate all of them until we find the right one.
725 while (urls.hasMoreElements()) {
726 URL metaUrl = urls.nextElement();
727 InputStream is = null;
728 try {
729 is = metaUrl.openStream();
730 Manifest mf = new Manifest(is);
731 Attributes attrs = mf.getMainAttributes();
732 if ("Mozilla Rhino".equals(attrs.getValue("Implementation-Title"))) {
733 implementationVersion =
734 "Rhino " + attrs.getValue("Implementation-Version") + " " + attrs.getValue("Built-Date").replaceAll("-", " ");
735 return implementationVersion;
736 }
737 } catch (IOException e) {
738 // Ignore this unlikely event
739 } finally {
740 try {
741 if (is != null) is.close();
742 } catch (IOException e) {
743 // Ignore this even unlikelier event
744 }
745 }
746 }
747 }
748
749 return implementationVersion;
750 }
751
752 /**
753 * Get the current error reporter.
754 *
755 * @see org.mozilla.javascript.ErrorReporter
756 */
757 public final ErrorReporter getErrorReporter()
758 {
759 if (errorReporter == null) {
760 return DefaultErrorReporter.instance;
761 }
762 return errorReporter;
763 }
764
765 /**
766 * Change the current error reporter.
767 *
768 * @return the previous error reporter
769 * @see org.mozilla.javascript.ErrorReporter
770 */
771 public final ErrorReporter setErrorReporter(ErrorReporter reporter)
772 {
773 if (sealed) onSealedMutation();
774 if (reporter == null) throw new IllegalArgumentException();
775 ErrorReporter old = getErrorReporter();
776 if (reporter == old) {
777 return old;
778 }
779 Object listeners = propertyListeners;
780 if (listeners != null) {
781 firePropertyChangeImpl(listeners, errorReporterProperty,
782 old, reporter);
783 }
784 this.errorReporter = reporter;
785 return old;
786 }
787
788 /**
789 * Get the current locale. Returns the default locale if none has
790 * been set.
791 *
792 * @see java.util.Locale
793 */
794
795 public final Locale getLocale()
796 {
797 if (locale == null)
798 locale = Locale.getDefault();
799 return locale;
800 }
801
802 /**
803 * Set the current locale.
804 *
805 * @see java.util.Locale
806 */
807 public final Locale setLocale(Locale loc)
808 {
809 if (sealed) onSealedMutation();
810 Locale result = locale;
811 locale = loc;
812 return result;
813 }
814
815 /**
816 * Register an object to receive notifications when a bound property
817 * has changed
818 * @see java.beans.PropertyChangeEvent
819 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
820 * @param l the listener
821 */
822 public final void addPropertyChangeListener(PropertyChangeListener l)
823 {
824 if (sealed) onSealedMutation();
825 propertyListeners = Kit.addListener(propertyListeners, l);
826 }
827
828 /**
829 * Remove an object from the list of objects registered to receive
830 * notification of changes to a bounded property
831 * @see java.beans.PropertyChangeEvent
832 * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
833 * @param l the listener
834 */
835 public final void removePropertyChangeListener(PropertyChangeListener l)
836 {
837 if (sealed) onSealedMutation();
838 propertyListeners = Kit.removeListener(propertyListeners, l);
839 }
840
841 /**
842 * Notify any registered listeners that a bounded property has changed
843 * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
844 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
845 * @see java.beans.PropertyChangeListener
846 * @see java.beans.PropertyChangeEvent
847 * @param property the bound property
848 * @param oldValue the old value
849 * @param newValue the new value
850 */
851 final void firePropertyChange(String property, Object oldValue,
852 Object newValue)
853 {
854 Object listeners = propertyListeners;
855 if (listeners != null) {
856 firePropertyChangeImpl(listeners, property, oldValue, newValue);
857 }
858 }
859
860 private void firePropertyChangeImpl(Object listeners, String property,
861 Object oldValue, Object newValue)
862 {
863 for (int i = 0; ; ++i) {
864 Object l = Kit.getListener(listeners, i);
865 if (l == null)
866 break;
867 if (l instanceof PropertyChangeListener) {
868 PropertyChangeListener pcl = (PropertyChangeListener)l;
869 pcl.propertyChange(new PropertyChangeEvent(
870 this, property, oldValue, newValue));
871 }
872 }
873 }
874
875 /**
876 * Report a warning using the error reporter for the current thread.
877 *
878 * @param message the warning message to report
879 * @param sourceName a string describing the source, such as a filename
880 * @param lineno the starting line number
881 * @param lineSource the text of the line (may be null)
882 * @param lineOffset the offset into lineSource where problem was detected
883 * @see org.mozilla.javascript.ErrorReporter
884 */
885 public static void reportWarning(String message, String sourceName,
886 int lineno, String lineSource,
887 int lineOffset)
888 {
889 Context cx = Context.getContext();
890 if (cx.hasFeature(FEATURE_WARNING_AS_ERROR))
891 reportError(message, sourceName, lineno, lineSource, lineOffset);
892 else
893 cx.getErrorReporter().warning(message, sourceName, lineno,
894 lineSource, lineOffset);
895 }
896
897 /**
898 * Report a warning using the error reporter for the current thread.
899 *
900 * @param message the warning message to report
901 * @see org.mozilla.javascript.ErrorReporter
902 */
903 public static void reportWarning(String message)
904 {
905 int[] linep = { 0 };
906 String filename = getSourcePositionFromStack(linep);
907 Context.reportWarning(message, filename, linep[0], null, 0);
908 }
909
910 public static void reportWarning(String message, Throwable t)
911 {
912 int[] linep = { 0 };
913 String filename = getSourcePositionFromStack(linep);
914 Writer sw = new StringWriter();
915 PrintWriter pw = new PrintWriter(sw);
916 pw.println(message);
917 t.printStackTrace(pw);
918 pw.flush();
919 Context.reportWarning(sw.toString(), filename, linep[0], null, 0);
920 }
921
922 /**
923 * Report an error using the error reporter for the current thread.
924 *
925 * @param message the error message to report
926 * @param sourceName a string describing the source, such as a filename
927 * @param lineno the starting line number
928 * @param lineSource the text of the line (may be null)
929 * @param lineOffset the offset into lineSource where problem was detected
930 * @see org.mozilla.javascript.ErrorReporter
931 */
932 public static void reportError(String message, String sourceName,
933 int lineno, String lineSource,
934 int lineOffset)
935 {
936 Context cx = getCurrentContext();
937 if (cx != null) {
938 cx.getErrorReporter().error(message, sourceName, lineno,
939 lineSource, lineOffset);
940 } else {
941 throw new EvaluatorException(message, sourceName, lineno,
942 lineSource, lineOffset);
943 }
944 }
945
946 /**
947 * Report an error using the error reporter for the current thread.
948 *
949 * @param message the error message to report
950 * @see org.mozilla.javascript.ErrorReporter
951 */
952 public static void reportError(String message)
953 {
954 int[] linep = { 0 };
955 String filename = getSourcePositionFromStack(linep);
956 Context.reportError(message, filename, linep[0], null, 0);
957 }
958
959 /**
960 * Report a runtime error using the error reporter for the current thread.
961 *
962 * @param message the error message to report
963 * @param sourceName a string describing the source, such as a filename
964 * @param lineno the starting line number
965 * @param lineSource the text of the line (may be null)
966 * @param lineOffset the offset into lineSource where problem was detected
967 * @return a runtime exception that will be thrown to terminate the
968 * execution of the script
969 * @see org.mozilla.javascript.ErrorReporter
970 */
971 public static EvaluatorException reportRuntimeError(String message,
972 String sourceName,
973 int lineno,
974 String lineSource,
975 int lineOffset)
976 {
977 Context cx = getCurrentContext();
978 if (cx != null) {
979 return cx.getErrorReporter().
980 runtimeError(message, sourceName, lineno,
981 lineSource, lineOffset);
982 } else {
983 throw new EvaluatorException(message, sourceName, lineno,
984 lineSource, lineOffset);
985 }
986 }
987
988 static EvaluatorException reportRuntimeError0(String messageId)
989 {
990 String msg = ScriptRuntime.getMessage0(messageId);
991 return reportRuntimeError(msg);
992 }
993
994 static EvaluatorException reportRuntimeError1(String messageId,
995 Object arg1)
996 {
997 String msg = ScriptRuntime.getMessage1(messageId, arg1);
998 return reportRuntimeError(msg);
999 }
1000
1001 static EvaluatorException reportRuntimeError2(String messageId,
1002 Object arg1, Object arg2)
1003 {
1004 String msg = ScriptRuntime.getMessage2(messageId, arg1, arg2);
1005 return reportRuntimeError(msg);
1006 }
1007
1008 static EvaluatorException reportRuntimeError3(String messageId,
1009 Object arg1, Object arg2,
1010 Object arg3)
1011 {
1012 String msg = ScriptRuntime.getMessage3(messageId, arg1, arg2, arg3);
1013 return reportRuntimeError(msg);
1014 }
1015
1016 static EvaluatorException reportRuntimeError4(String messageId,
1017 Object arg1, Object arg2,
1018 Object arg3, Object arg4)
1019 {
1020 String msg
1021 = ScriptRuntime.getMessage4(messageId, arg1, arg2, arg3, arg4);
1022 return reportRuntimeError(msg);
1023 }
1024
1025 /**
1026 * Report a runtime error using the error reporter for the current thread.
1027 *
1028 * @param message the error message to report
1029 * @see org.mozilla.javascript.ErrorReporter
1030 */
1031 public static EvaluatorException reportRuntimeError(String message)
1032 {
1033 int[] linep = { 0 };
1034 String filename = getSourcePositionFromStack(linep);
1035 return Context.reportRuntimeError(message, filename, linep[0], null, 0);
1036 }
1037
1038 /**
1039 * Initialize the standard objects.
1040 *
1041 * Creates instances of the standard objects and their constructors
1042 * (Object, String, Number, Date, etc.), setting up 'scope' to act
1043 * as a global object as in ECMA 15.1.<p>
1044 *
1045 * This method must be called to initialize a scope before scripts
1046 * can be evaluated in that scope.<p>
1047 *
1048 * This method does not affect the Context it is called upon.
1049 *
1050 * @return the initialized scope
1051 */
1052 public final ScriptableObject initStandardObjects()
1053 {
1054 return initStandardObjects(null, false);
1055 }
1056
1057 /**
1058 * Initialize the standard objects, leaving out those that offer access directly
1059 * to Java classes. This sets up "scope" to have access to all the standard
1060 * JavaScript classes, but does not create global objects for any top-level
1061 * Java packages. In addition, the "Packages," "JavaAdapter," and
1062 * "JavaImporter" classes, and the "getClass" function, are not
1063 * initialized.
1064 *
1065 * The result of this function is a scope that may be safely used in a "sandbox"
1066 * environment where it is not desirable to give access to Java code from JavaScript.
1067 *
1068 * Creates instances of the standard objects and their constructors
1069 * (Object, String, Number, Date, etc.), setting up 'scope' to act
1070 * as a global object as in ECMA 15.1.<p>
1071 *
1072 * This method must be called to initialize a scope before scripts
1073 * can be evaluated in that scope.<p>
1074 *
1075 * This method does not affect the Context it is called upon.
1076 *
1077 * @return the initialized scope
1078 */
1079 public final ScriptableObject initSafeStandardObjects()
1080 {
1081 return initSafeStandardObjects(null, false);
1082 }
1083
1084 /**
1085 * Initialize the standard objects.
1086 *
1087 * Creates instances of the standard objects and their constructors
1088 * (Object, String, Number, Date, etc.), setting up 'scope' to act
1089 * as a global object as in ECMA 15.1.<p>
1090 *
1091 * This method must be called to initialize a scope before scripts
1092 * can be evaluated in that scope.<p>
1093 *
1094 * This method does not affect the Context it is called upon.
1095 *
1096 * @param scope the scope to initialize, or null, in which case a new
1097 * object will be created to serve as the scope
1098 * @return the initialized scope. The method returns the value of the scope
1099 * argument if it is not null or newly allocated scope object which
1100 * is an instance {@link ScriptableObject}.
1101 */
1102 public final Scriptable initStandardObjects(ScriptableObject scope)
1103 {
1104 return initStandardObjects(scope, false);
1105 }
1106
1107 /**
1108 * Initialize the standard objects, leaving out those that offer access directly
1109 * to Java classes. This sets up "scope" to have access to all the standard
1110 * JavaScript classes, but does not create global objects for any top-level
1111 * Java packages. In addition, the "Packages," "JavaAdapter," and
1112 * "JavaImporter" classes, and the "getClass" function, are not
1113 * initialized.
1114 *
1115 * The result of this function is a scope that may be safely used in a "sandbox"
1116 * environment where it is not desirable to give access to Java code from JavaScript.
1117 *
1118 * Creates instances of the standard objects and their constructors
1119 * (Object, String, Number, Date, etc.), setting up 'scope' to act
1120 * as a global object as in ECMA 15.1.<p>
1121 *
1122 * This method must be called to initialize a scope before scripts
1123 * can be evaluated in that scope.<p>
1124 *
1125 * This method does not affect the Context it is called upon.
1126 *
1127 * @param scope the scope to initialize, or null, in which case a new
1128 * object will be created to serve as the scope
1129 * @return the initialized scope. The method returns the value of the scope
1130 * argument if it is not null or newly allocated scope object which
1131 * is an instance {@link ScriptableObject}.
1132 */
1133 public final Scriptable initSafeStandardObjects(ScriptableObject scope)
1134 {
1135 return initSafeStandardObjects(scope, false);
1136 }
1137
1138 /**
1139 * Initialize the standard objects.
1140 *
1141 * Creates instances of the standard objects and their constructors
1142 * (Object, String, Number, Date, etc.), setting up 'scope' to act
1143 * as a global object as in ECMA 15.1.<p>
1144 *
1145 * This method must be called to initialize a scope before scripts
1146 * can be evaluated in that scope.<p>
1147 *
1148 * This method does not affect the Context it is called upon.<p>
1149 *
1150 * This form of the method also allows for creating "sealed" standard
1151 * objects. An object that is sealed cannot have properties added, changed,
1152 * or removed. This is useful to create a "superglobal" that can be shared
1153 * among several top-level objects. Note that sealing is not allowed in
1154 * the current ECMA/ISO language specification, but is likely for
1155 * the next version.
1156 *
1157 * @param scope the scope to initialize, or null, in which case a new
1158 * object will be created to serve as the scope
1159 * @param sealed whether or not to create sealed standard objects that
1160 * cannot be modified.
1161 * @return the initialized scope. The method returns the value of the scope
1162 * argument if it is not null or newly allocated scope object.
1163 * @since 1.4R3
1164 */
1165 public ScriptableObject initStandardObjects(ScriptableObject scope,
1166 boolean sealed)
1167 {
1168 return ScriptRuntime.initStandardObjects(this, scope, sealed);
1169 }
1170
1171 /**
1172 * Initialize the standard objects, leaving out those that offer access directly
1173 * to Java classes. This sets up "scope" to have access to all the standard
1174 * JavaScript classes, but does not create global objects for any top-level
1175 * Java packages. In addition, the "Packages," "JavaAdapter," and
1176 * "JavaImporter" classes, and the "getClass" function, are not
1177 * initialized.
1178 *
1179 * The result of this function is a scope that may be safely used in a "sandbox"
1180 * environment where it is not desirable to give access to Java code from JavaScript.
1181 *
1182 * Creates instances of the standard objects and their constructors
1183 * (Object, String, Number, Date, etc.), setting up 'scope' to act
1184 * as a global object as in ECMA 15.1.<p>
1185 *
1186 * This method must be called to initialize a scope before scripts
1187 * can be evaluated in that scope.<p>
1188 *
1189 * This method does not affect the Context it is called upon.<p>
1190 *
1191 * This form of the method also allows for creating "sealed" standard
1192 * objects. An object that is sealed cannot have properties added, changed,
1193 * or removed. This is useful to create a "superglobal" that can be shared
1194 * among several top-level objects. Note that sealing is not allowed in
1195 * the current ECMA/ISO language specification, but is likely for
1196 * the next version.
1197 *
1198 * @param scope the scope to initialize, or null, in which case a new
1199 * object will be created to serve as the scope
1200 * @param sealed whether or not to create sealed standard objects that
1201 * cannot be modified.
1202 * @return the initialized scope. The method returns the value of the scope
1203 * argument if it is not null or newly allocated scope object.
1204 * @since 1.7.6
1205 */
1206 public ScriptableObject initSafeStandardObjects(ScriptableObject scope,
1207 boolean sealed)
1208 {
1209 return ScriptRuntime.initSafeStandardObjects(this, scope, sealed);
1210 }
1211
1212 /**
1213 * Get the singleton object that represents the JavaScript Undefined value.
1214 */
1215 public static Object getUndefinedValue()
1216 {
1217 return Undefined.instance;
1218 }
1219
1220 /**
1221 * Evaluate a JavaScript source string.
1222 *
1223 * The provided source name and line number are used for error messages
1224 * and for producing debug information.
1225 *
1226 * @param scope the scope to execute in
1227 * @param source the JavaScript source
1228 * @param sourceName a string describing the source, such as a filename
1229 * @param lineno the starting line number
1230 * @param securityDomain an arbitrary object that specifies security
1231 * information about the origin or owner of the script. For
1232 * implementations that don't care about security, this value
1233 * may be null.
1234 * @return the result of evaluating the string
1235 * @see org.mozilla.javascript.SecurityController
1236 */
1237 public final Object evaluateString(Scriptable scope, String source,
1238 String sourceName, int lineno,
1239 Object securityDomain)
1240 {
1241 Script script = compileString(source, sourceName, lineno,
1242 securityDomain);
1243 if (script != null) {
1244 return script.exec(this, scope);
1245 } else {
1246 return null;
1247 }
1248 }
1249
1250 /**
1251 * Evaluate a reader as JavaScript source.
1252 *
1253 * All characters of the reader are consumed.
1254 *
1255 * @param scope the scope to execute in
1256 * @param in the Reader to get JavaScript source from
1257 * @param sourceName a string describing the source, such as a filename
1258 * @param lineno the starting line number
1259 * @param securityDomain an arbitrary object that specifies security
1260 * information about the origin or owner of the script. For
1261 * implementations that don't care about security, this value
1262 * may be null.
1263 * @return the result of evaluating the source
1264 *
1265 * @exception IOException if an IOException was generated by the Reader
1266 */
1267 public final Object evaluateReader(Scriptable scope, Reader in,
1268 String sourceName, int lineno,
1269 Object securityDomain)
1270 throws IOException
1271 {
1272 Script script = compileReader(scope, in, sourceName, lineno,
1273 securityDomain);
1274 if (script != null) {
1275 return script.exec(this, scope);
1276 } else {
1277 return null;
1278 }
1279 }
1280
1281 /**
1282 * Execute script that may pause execution by capturing a continuation.
1283 * Caller must be prepared to catch a ContinuationPending exception
1284 * and resume execution by calling
1285 * {@link #resumeContinuation(Object, Scriptable, Object)}.
1286 * @param script The script to execute. Script must have been compiled
1287 * with interpreted mode (optimization level -1)
1288 * @param scope The scope to execute the script against
1289 * @throws ContinuationPending if the script calls a function that results
1290 * in a call to {@link #captureContinuation()}
1291 * @since 1.7 Release 2
1292 */
1293 public Object executeScriptWithContinuations(Script script,
1294 Scriptable scope)
1295 throws ContinuationPending
1296 {
1297 if (!(script instanceof InterpretedFunction) ||
1298 !((InterpretedFunction)script).isScript())
1299 {
1300 // Can only be applied to scripts
1301 throw new IllegalArgumentException("Script argument was not" +
1302 " a script or was not created by interpreted mode ");
1303 }
1304 return callFunctionWithContinuations((InterpretedFunction) script,
1305 scope, ScriptRuntime.emptyArgs);
1306 }
1307
1308 /**
1309 * Call function that may pause execution by capturing a continuation.
1310 * Caller must be prepared to catch a ContinuationPending exception
1311 * and resume execution by calling
1312 * {@link #resumeContinuation(Object, Scriptable, Object)}.
1313 * @param function The function to call. The function must have been
1314 * compiled with interpreted mode (optimization level -1)
1315 * @param scope The scope to execute the script against
1316 * @param args The arguments for the function
1317 * @throws ContinuationPending if the script calls a function that results
1318 * in a call to {@link #captureContinuation()}
1319 * @since 1.7 Release 2
1320 */
1321 public Object callFunctionWithContinuations(Callable function,
1322 Scriptable scope, Object[] args)
1323 throws ContinuationPending
1324 {
1325 if (!(function instanceof InterpretedFunction)) {
1326 // Can only be applied to scripts
1327 throw new IllegalArgumentException("Function argument was not" +
1328 " created by interpreted mode ");
1329 }
1330 if (ScriptRuntime.hasTopCall(this)) {
1331 throw new IllegalStateException("Cannot have any pending top " +
1332 "calls when executing a script with continuations");
1333 }
1334 // Annotate so we can check later to ensure no java code in
1335 // intervening frames
1336 isContinuationsTopCall = true;
1337 return ScriptRuntime.doTopCall(function, this, scope, scope, args, isTopLevelStrict);
1338 }
1339
1340 /**
1341 * Capture a continuation from the current execution. The execution must
1342 * have been started via a call to
1343 * {@link #executeScriptWithContinuations(Script, Scriptable)} or
1344 * {@link #callFunctionWithContinuations(Callable, Scriptable, Object[])}.
1345 * This implies that the code calling
1346 * this method must have been called as a function from the
1347 * JavaScript script. Also, there cannot be any non-JavaScript code
1348 * between the JavaScript frames (e.g., a call to eval()). The
1349 * ContinuationPending exception returned must be thrown.
1350 * @return A ContinuationPending exception that must be thrown
1351 * @since 1.7 Release 2
1352 */
1353 public ContinuationPending captureContinuation() {
1354 return new ContinuationPending(
1355 Interpreter.captureContinuation(this));
1356 }
1357
1358 /**
1359 * Restarts execution of the JavaScript suspended at the call
1360 * to {@link #captureContinuation()}. Execution of the code will resume
1361 * with the functionResult as the result of the call that captured the
1362 * continuation.
1363 * Execution of the script will either conclude normally and the
1364 * result returned, another continuation will be captured and
1365 * thrown, or the script will terminate abnormally and throw an exception.
1366 * @param continuation The value returned by
1367 * {@link ContinuationPending#getContinuation()}
1368 * @param functionResult This value will appear to the code being resumed
1369 * as the result of the function that captured the continuation
1370 * @throws ContinuationPending if another continuation is captured before
1371 * the code terminates
1372 * @since 1.7 Release 2
1373 */
1374 public Object resumeContinuation(Object continuation,
1375 Scriptable scope, Object functionResult)
1376 throws ContinuationPending
1377 {
1378 Object[] args = { functionResult };
1379 return Interpreter.restartContinuation(
1380 (org.mozilla.javascript.NativeContinuation) continuation,
1381 this, scope, args);
1382 }
1383
1384 /**
1385 * Check whether a string is ready to be compiled.
1386 * <p>
1387 * stringIsCompilableUnit is intended to support interactive compilation of
1388 * JavaScript. If compiling the string would result in an error
1389 * that might be fixed by appending more source, this method
1390 * returns false. In every other case, it returns true.
1391 * <p>
1392 * Interactive shells may accumulate source lines, using this
1393 * method after each new line is appended to check whether the
1394 * statement being entered is complete.
1395 *
1396 * @param source the source buffer to check
1397 * @return whether the source is ready for compilation
1398 * @since 1.4 Release 2
1399 */
1400 public final boolean stringIsCompilableUnit(String source) {
1401 boolean errorseen = false;
1402 CompilerEnvirons compilerEnv = new CompilerEnvirons();
1403 compilerEnv.initFromContext(this);
1404 // no source name or source text manager, because we're just
1405 // going to throw away the result.
1406 compilerEnv.setGeneratingSource(false);
1407 Parser p = new Parser(compilerEnv, DefaultErrorReporter.instance);
1408 try {
1409 p.parse(source, null, 1);
1410 } catch (EvaluatorException ee) {
1411 errorseen = true;
1412 }
1413 // Return false only if an error occurred as a result of reading past
1414 // the end of the file, i.e. if the source could be fixed by
1415 // appending more source.
1416 return !(errorseen && p.eof());
1417 }
1418
1419 /**
1420 * @deprecated
1421 * @see #compileReader(Reader in, String sourceName, int lineno,
1422 * Object securityDomain)
1423 */
1424 @Deprecated
1425 public final Script compileReader(Scriptable scope, Reader in,
1426 String sourceName, int lineno,
1427 Object securityDomain)
1428 throws IOException
1429 {
1430 return compileReader(in, sourceName, lineno, securityDomain);
1431 }
1432
1433 /**
1434 * Compiles the source in the given reader.
1435 * <p>
1436 * Returns a script that may later be executed.
1437 * Will consume all the source in the reader.
1438 *
1439 * @param in the input reader
1440 * @param sourceName a string describing the source, such as a filename
1441 * @param lineno the starting line number for reporting errors
1442 * @param securityDomain an arbitrary object that specifies security
1443 * information about the origin or owner of the script. For
1444 * implementations that don't care about security, this value
1445 * may be null.
1446 * @return a script that may later be executed
1447 * @exception IOException if an IOException was generated by the Reader
1448 * @see org.mozilla.javascript.Script
1449 */
1450 public final Script compileReader(Reader in, String sourceName,
1451 int lineno, Object securityDomain)
1452 throws IOException
1453 {
1454 if (lineno < 0) {
1455 // For compatibility IllegalArgumentException can not be thrown here
1456 lineno = 0;
1457 }
1458 return (Script) compileImpl(null, in, null, sourceName, lineno,
1459 securityDomain, false, null, null);
1460 }
1461
1462 /**
1463 * Compiles the source in the given string.
1464 * <p>
1465 * Returns a script that may later be executed.
1466 *
1467 * @param source the source string
1468 * @param sourceName a string describing the source, such as a filename
1469 * @param lineno the starting line number for reporting errors. Use
1470 * 0 if the line number is unknown.
1471 * @param securityDomain an arbitrary object that specifies security
1472 * information about the origin or owner of the script. For
1473 * implementations that don't care about security, this value
1474 * may be null.
1475 * @return a script that may later be executed
1476 * @see org.mozilla.javascript.Script
1477 */
1478 public final Script compileString(String source,
1479 String sourceName, int lineno,
1480 Object securityDomain)
1481 {
1482 if (lineno < 0) {
1483 // For compatibility IllegalArgumentException can not be thrown here
1484 lineno = 0;
1485 }
1486 return compileString(source, null, null, sourceName, lineno,
1487 securityDomain);
1488 }
1489
1490 final Script compileString(String source,
1491 Evaluator compiler,
1492 ErrorReporter compilationErrorReporter,
1493 String sourceName, int lineno,
1494 Object securityDomain)
1495 {
1496 try {
1497 return (Script) compileImpl(null, null, source, sourceName, lineno,
1498 securityDomain, false,
1499 compiler, compilationErrorReporter);
1500 } catch (IOException ex) {
1501 // Should not happen when dealing with source as string
1502 throw new RuntimeException();
1503 }
1504 }
1505
1506 /**
1507 * Compile a JavaScript function.
1508 * <p>
1509 * The function source must be a function definition as defined by
1510 * ECMA (e.g., "function f(a) { return a; }").
1511 *
1512 * @param scope the scope to compile relative to
1513 * @param source the function definition source
1514 * @param sourceName a string describing the source, such as a filename
1515 * @param lineno the starting line number
1516 * @param securityDomain an arbitrary object that specifies security
1517 * information about the origin or owner of the script. For
1518 * implementations that don't care about security, this value
1519 * may be null.
1520 * @return a Function that may later be called
1521 * @see org.mozilla.javascript.Function
1522 */
1523 public final Function compileFunction(Scriptable scope, String source,
1524 String sourceName, int lineno,
1525 Object securityDomain)
1526 {
1527 return compileFunction(scope, source, null, null, sourceName, lineno,
1528 securityDomain);
1529 }
1530
1531 final Function compileFunction(Scriptable scope, String source,
1532 Evaluator compiler,
1533 ErrorReporter compilationErrorReporter,
1534 String sourceName, int lineno,
1535 Object securityDomain)
1536 {
1537 try {
1538 return (Function) compileImpl(scope, null, source, sourceName,
1539 lineno, securityDomain, true,
1540 compiler, compilationErrorReporter);
1541 }
1542 catch (IOException ioe) {
1543 // Should never happen because we just made the reader
1544 // from a String
1545 throw new RuntimeException();
1546 }
1547 }
1548
1549 /**
1550 * Decompile the script.
1551 * <p>
1552 * The canonical source of the script is returned.
1553 *
1554 * @param script the script to decompile
1555 * @param indent the number of spaces to indent the result
1556 * @return a string representing the script source
1557 */
1558 public final String decompileScript(Script script, int indent)
1559 {
1560 NativeFunction scriptImpl = (NativeFunction) script;
1561 return scriptImpl.decompile(indent, 0);
1562 }
1563
1564 /**
1565 * Decompile a JavaScript Function.
1566 * <p>
1567 * Decompiles a previously compiled JavaScript function object to
1568 * canonical source.
1569 * <p>
1570 * Returns function body of '[native code]' if no decompilation
1571 * information is available.
1572 *
1573 * @param fun the JavaScript function to decompile
1574 * @param indent the number of spaces to indent the result
1575 * @return a string representing the function source
1576 */
1577 public final String decompileFunction(Function fun, int indent)
1578 {
1579 if (fun instanceof BaseFunction)
1580 return ((BaseFunction)fun).decompile(indent, 0);
1581 else
1582 return "function " + fun.getClassName() +
1583 "() {\n\t[native code]\n}\n";
1584 }
1585
1586 /**
1587 * Decompile the body of a JavaScript Function.
1588 * <p>
1589 * Decompiles the body a previously compiled JavaScript Function
1590 * object to canonical source, omitting the function header and
1591 * trailing brace.
1592 *
1593 * Returns '[native code]' if no decompilation information is available.
1594 *
1595 * @param fun the JavaScript function to decompile
1596 * @param indent the number of spaces to indent the result
1597 * @return a string representing the function body source.
1598 */
1599 public final String decompileFunctionBody(Function fun, int indent)
1600 {
1601 if (fun instanceof BaseFunction) {
1602 BaseFunction bf = (BaseFunction)fun;
1603 return bf.decompile(indent, Decompiler.ONLY_BODY_FLAG);
1604 }
1605 // ALERT: not sure what the right response here is.
1606 return "[native code]\n";
1607 }
1608
1609 /**
1610 * Create a new JavaScript object.
1611 *
1612 * Equivalent to evaluating "new Object()".
1613 * @param scope the scope to search for the constructor and to evaluate
1614 * against
1615 * @return the new object
1616 */
1617 public Scriptable newObject(Scriptable scope)
1618 {
1619 NativeObject result = new NativeObject();
1620 ScriptRuntime.setBuiltinProtoAndParent(result, scope,
1621 TopLevel.Builtins.Object);
1622 return result;
1623 }
1624
1625 /**
1626 * Create a new JavaScript object by executing the named constructor.
1627 *
1628 * The call <code>newObject(scope, "Foo")</code> is equivalent to
1629 * evaluating "new Foo()".
1630 *
1631 * @param scope the scope to search for the constructor and to evaluate against
1632 * @param constructorName the name of the constructor to call
1633 * @return the new object
1634 */
1635 public Scriptable newObject(Scriptable scope, String constructorName)
1636 {
1637 return newObject(scope, constructorName, ScriptRuntime.emptyArgs);
1638 }
1639
1640 /**
1641 * Creates a new JavaScript object by executing the named constructor.
1642 *
1643 * Searches <code>scope</code> for the named constructor, calls it with
1644 * the given arguments, and returns the result.<p>
1645 *
1646 * The code
1647 * <pre>
1648 * Object[] args = { "a", "b" };
1649 * newObject(scope, "Foo", args)</pre>
1650 * is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo
1651 * constructor has been defined in <code>scope</code>.
1652 *
1653 * @param scope The scope to search for the constructor and to evaluate
1654 * against
1655 * @param constructorName the name of the constructor to call
1656 * @param args the array of arguments for the constructor
1657 * @return the new object
1658 */
1659 public Scriptable newObject(Scriptable scope, String constructorName,
1660 Object[] args)
1661 {
1662 return ScriptRuntime.newObject(this, scope, constructorName, args);
1663 }
1664
1665 /**
1666 * Create an array with a specified initial length.
1667 * <p>
1668 * @param scope the scope to create the object in
1669 * @param length the initial length (JavaScript arrays may have
1670 * additional properties added dynamically).
1671 * @return the new array object
1672 */
1673 public Scriptable newArray(Scriptable scope, int length)
1674 {
1675 NativeArray result = new NativeArray(length);
1676 ScriptRuntime.setBuiltinProtoAndParent(result, scope,
1677 TopLevel.Builtins.Array);
1678 return result;
1679 }
1680
1681 /**
1682 * Create an array with a set of initial elements.
1683 *
1684 * @param scope the scope to create the object in.
1685 * @param elements the initial elements. Each object in this array
1686 * must be an acceptable JavaScript type and type
1687 * of array should be exactly Object[], not
1688 * SomeObjectSubclass[].
1689 * @return the new array object.
1690 */
1691 public Scriptable newArray(Scriptable scope, Object[] elements)
1692 {
1693 if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass)
1694 throw new IllegalArgumentException();
1695 NativeArray result = new NativeArray(elements);
1696 ScriptRuntime.setBuiltinProtoAndParent(result, scope,
1697 TopLevel.Builtins.Array);
1698 return result;
1699 }
1700
1701 /**
1702 * Get the elements of a JavaScript array.
1703 * <p>
1704 * If the object defines a length property convertible to double number,
1705 * then the number is converted Uint32 value as defined in Ecma 9.6
1706 * and Java array of that size is allocated.
1707 * The array is initialized with the values obtained by
1708 * calling get() on object for each value of i in [0,length-1]. If
1709 * there is not a defined value for a property the Undefined value
1710 * is used to initialize the corresponding element in the array. The
1711 * Java array is then returned.
1712 * If the object doesn't define a length property or it is not a number,
1713 * empty array is returned.
1714 * @param object the JavaScript array or array-like object
1715 * @return a Java array of objects
1716 * @since 1.4 release 2
1717 */
1718 public final Object[] getElements(Scriptable object)
1719 {
1720 return ScriptRuntime.getArrayElements(object);
1721 }
1722
1723 /**
1724 * Convert the value to a JavaScript boolean value.
1725 * <p>
1726 * See ECMA 9.2.
1727 *
1728 * @param value a JavaScript value
1729 * @return the corresponding boolean value converted using
1730 * the ECMA rules
1731 */
1732 public static boolean toBoolean(Object value)
1733 {
1734 return ScriptRuntime.toBoolean(value);
1735 }
1736
1737 /**
1738 * Convert the value to a JavaScript Number value.
1739 * <p>
1740 * Returns a Java double for the JavaScript Number.
1741 * <p>
1742 * See ECMA 9.3.
1743 *
1744 * @param value a JavaScript value
1745 * @return the corresponding double value converted using
1746 * the ECMA rules
1747 */
1748 public static double toNumber(Object value)
1749 {
1750 return ScriptRuntime.toNumber(value);
1751 }
1752
1753 /**
1754 * Convert the value to a JavaScript String value.
1755 * <p>
1756 * See ECMA 9.8.
1757 * <p>
1758 * @param value a JavaScript value
1759 * @return the corresponding String value converted using
1760 * the ECMA rules
1761 */
1762 public static String toString(Object value)
1763 {
1764 return ScriptRuntime.toString(value);
1765 }
1766
1767 /**
1768 * Convert the value to an JavaScript object value.
1769 * <p>
1770 * Note that a scope must be provided to look up the constructors
1771 * for Number, Boolean, and String.
1772 * <p>
1773 * See ECMA 9.9.
1774 * <p>
1775 * Additionally, arbitrary Java objects and classes will be
1776 * wrapped in a Scriptable object with its Java fields and methods
1777 * reflected as JavaScript properties of the object.
1778 *
1779 * @param value any Java object
1780 * @param scope global scope containing constructors for Number,
1781 * Boolean, and String
1782 * @return new JavaScript object
1783 */
1784 public static Scriptable toObject(Object value, Scriptable scope)
1785 {
1786 return ScriptRuntime.toObject(scope, value);
1787 }
1788
1789 /**
1790 * @deprecated
1791 * @see #toObject(Object, Scriptable)
1792 */
1793 @Deprecated
1794 public static Scriptable toObject(Object value, Scriptable scope,
1795 Class<?> staticType)
1796 {
1797 return ScriptRuntime.toObject(scope, value);
1798 }
1799
1800 /**
1801 * Convenient method to convert java value to its closest representation
1802 * in JavaScript.
1803 * <p>
1804 * If value is an instance of String, Number, Boolean, Function or
1805 * Scriptable, it is returned as it and will be treated as the corresponding
1806 * JavaScript type of string, number, boolean, function and object.
1807 * <p>
1808 * Note that for Number instances during any arithmetic operation in
1809 * JavaScript the engine will always use the result of
1810 * <tt>Number.doubleValue()</tt> resulting in a precision loss if
1811 * the number can not fit into double.
1812 * <p>
1813 * If value is an instance of Character, it will be converted to string of
1814 * length 1 and its JavaScript type will be string.
1815 * <p>
1816 * The rest of values will be wrapped as LiveConnect objects
1817 * by calling {@link WrapFactory#wrap(Context cx, Scriptable scope,
1818 * Object obj, Class staticType)} as in:
1819 * <pre>
1820 * Context cx = Context.getCurrentContext();
1821 * return cx.getWrapFactory().wrap(cx, scope, value, null);
1822 * </pre>
1823 *
1824 * @param value any Java object
1825 * @param scope top scope object
1826 * @return value suitable to pass to any API that takes JavaScript values.
1827 */
1828 public static Object javaToJS(Object value, Scriptable scope)
1829 {
1830 if (value instanceof String || value instanceof Number
1831 || value instanceof Boolean || value instanceof Scriptable)
1832 {
1833 return value;
1834 } else if (value instanceof Character) {
1835 return String.valueOf(((Character)value).charValue());
1836 } else {
1837 Context cx = Context.getContext();
1838 return cx.getWrapFactory().wrap(cx, scope, value, null);
1839 }
1840 }
1841
1842 /**
1843 * Convert a JavaScript value into the desired type.
1844 * Uses the semantics defined with LiveConnect3 and throws an
1845 * Illegal argument exception if the conversion cannot be performed.
1846 * @param value the JavaScript value to convert
1847 * @param desiredType the Java type to convert to. Primitive Java
1848 * types are represented using the TYPE fields in the corresponding
1849 * wrapper class in java.lang.
1850 * @return the converted value
1851 * @throws EvaluatorException if the conversion cannot be performed
1852 */
1853 public static Object jsToJava(Object value, Class<?> desiredType)
1854 throws EvaluatorException
1855 {
1856 return NativeJavaObject.coerceTypeImpl(desiredType, value);
1857 }
1858
1859 /**
1860 * @deprecated
1861 * @see #jsToJava(Object, Class)
1862 * @throws IllegalArgumentException if the conversion cannot be performed.
1863 * Note that {@link #jsToJava(Object, Class)} throws
1864 * {@link EvaluatorException} instead.
1865 */
1866 @Deprecated
1867 public static Object toType(Object value, Class<?> desiredType)
1868 throws IllegalArgumentException
1869 {
1870 try {
1871 return jsToJava(value, desiredType);
1872 } catch (EvaluatorException ex) {
1873 IllegalArgumentException
1874 ex2 = new IllegalArgumentException(ex.getMessage());
1875 Kit.initCause(ex2, ex);
1876 throw ex2;
1877 }
1878 }
1879
1880 /**
1881 * Rethrow the exception wrapping it as the script runtime exception.
1882 * Unless the exception is instance of {@link EcmaError} or
1883 * {@link EvaluatorException} it will be wrapped as
1884 * {@link WrappedException}, a subclass of {@link EvaluatorException}.
1885 * The resulting exception object always contains
1886 * source name and line number of script that triggered exception.
1887 * <p>
1888 * This method always throws an exception, its return value is provided
1889 * only for convenience to allow a usage like:
1890 * <pre>
1891 * throw Context.throwAsScriptRuntimeEx(ex);
1892 * </pre>
1893 * to indicate that code after the method is unreachable.
1894 * @throws EvaluatorException
1895 * @throws EcmaError
1896 */
1897 public static RuntimeException throwAsScriptRuntimeEx(Throwable e)
1898 {
1899 while ((e instanceof InvocationTargetException)) {
1900 e = ((InvocationTargetException) e).getTargetException();
1901 }
1902 // special handling of Error so scripts would not catch them
1903 if (e instanceof Error) {
1904 Context cx = getContext();
1905 if (cx == null ||
1906 !cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS))
1907 {
1908 throw (Error)e;
1909 }
1910 }
1911 if (e instanceof RhinoException) {
1912 throw (RhinoException)e;
1913 }
1914 throw new WrappedException(e);
1915 }
1916
1917 /**
1918 * Tell whether debug information is being generated.
1919 * @since 1.3
1920 */
1921 public final boolean isGeneratingDebug()
1922 {
1923 return generatingDebug;
1924 }
1925
1926 /**
1927 * Specify whether or not debug information should be generated.
1928 * <p>
1929 * Setting the generation of debug information on will set the
1930 * optimization level to zero.
1931 * @since 1.3
1932 */
1933 public final void setGeneratingDebug(boolean generatingDebug)
1934 {
1935 if (sealed) onSealedMutation();
1936 generatingDebugChanged = true;
1937 if (generatingDebug && getOptimizationLevel() > 0)
1938 setOptimizationLevel(0);
1939 this.generatingDebug = generatingDebug;
1940 }
1941
1942 /**
1943 * Tell whether source information is being generated.
1944 * @since 1.3
1945 */
1946 public final boolean isGeneratingSource()
1947 {
1948 return generatingSource;
1949 }
1950
1951 /**
1952 * Specify whether or not source information should be generated.
1953 * <p>
1954 * Without source information, evaluating the "toString" method
1955 * on JavaScript functions produces only "[native code]" for
1956 * the body of the function.
1957 * Note that code generated without source is not fully ECMA
1958 * conformant.
1959 * @since 1.3
1960 */
1961 public final void setGeneratingSource(boolean generatingSource)
1962 {
1963 if (sealed) onSealedMutation();
1964 this.generatingSource = generatingSource;
1965 }
1966
1967 /**
1968 * Get the current optimization level.
1969 * <p>
1970 * The optimization level is expressed as an integer between -1 and
1971 * 9.
1972 * @since 1.3
1973 *
1974 */
1975 public final int getOptimizationLevel()
1976 {
1977 return optimizationLevel;
1978 }
1979
1980 /**
1981 * Set the current optimization level.
1982 * <p>
1983 * The optimization level is expected to be an integer between -1 and
1984 * 9. Any negative values will be interpreted as -1, and any values
1985 * greater than 9 will be interpreted as 9.
1986 * An optimization level of -1 indicates that interpretive mode will
1987 * always be used. Levels 0 through 9 indicate that class files may
1988 * be generated. Higher optimization levels trade off compile time
1989 * performance for runtime performance.
1990 * The optimizer level can't be set greater than -1 if the optimizer
1991 * package doesn't exist at run time.
1992 * @param optimizationLevel an integer indicating the level of
1993 * optimization to perform
1994 * @since 1.3
1995 *
1996 */
1997 public final void setOptimizationLevel(int optimizationLevel)
1998 {
1999 if (sealed) onSealedMutation();
2000 if (optimizationLevel == -2) {
2001 // To be compatible with Cocoon fork
2002 optimizationLevel = -1;
2003 }
2004 checkOptimizationLevel(optimizationLevel);
2005 if (codegenClass == null)
2006 optimizationLevel = -1;
2007 this.optimizationLevel = optimizationLevel;
2008 }
2009
2010 public static boolean isValidOptimizationLevel(int optimizationLevel)
2011 {
2012 return -1 <= optimizationLevel && optimizationLevel <= 9;
2013 }
2014
2015 public static void checkOptimizationLevel(int optimizationLevel)
2016 {
2017 if (isValidOptimizationLevel(optimizationLevel)) {
2018 return;
2019 }
2020 throw new IllegalArgumentException(
2021 "Optimization level outside [-1..9]: "+optimizationLevel);
2022 }
2023
2024 /**
2025 * Returns the maximum stack depth (in terms of number of call frames)
2026 * allowed in a single invocation of interpreter. If the set depth would be
2027 * exceeded, the interpreter will throw an EvaluatorException in the script.
2028 * Defaults to Integer.MAX_VALUE. The setting only has effect for
2029 * interpreted functions (those compiled with optimization level set to -1).
2030 * As the interpreter doesn't use the Java stack but rather manages its own
2031 * stack in the heap memory, a runaway recursion in interpreted code would
2032 * eventually consume all available memory and cause OutOfMemoryError
2033 * instead of a StackOverflowError limited to only a single thread. This
2034 * setting helps prevent such situations.
2035 *
2036 * @return The current maximum interpreter stack depth.
2037 */
2038 public final int getMaximumInterpreterStackDepth()
2039 {
2040 return maximumInterpreterStackDepth;
2041 }
2042
2043 /**
2044 * Sets the maximum stack depth (in terms of number of call frames)
2045 * allowed in a single invocation of interpreter. If the set depth would be
2046 * exceeded, the interpreter will throw an EvaluatorException in the script.
2047 * Defaults to Integer.MAX_VALUE. The setting only has effect for
2048 * interpreted functions (those compiled with optimization level set to -1).
2049 * As the interpreter doesn't use the Java stack but rather manages its own
2050 * stack in the heap memory, a runaway recursion in interpreted code would
2051 * eventually consume all available memory and cause OutOfMemoryError
2052 * instead of a StackOverflowError limited to only a single thread. This
2053 * setting helps prevent such situations.
2054 *
2055 * @param max the new maximum interpreter stack depth
2056 * @throws IllegalStateException if this context's optimization level is not
2057 * -1
2058 * @throws IllegalArgumentException if the new depth is not at least 1
2059 */
2060 public final void setMaximumInterpreterStackDepth(int max)
2061 {
2062 if(sealed) onSealedMutation();
2063 if(optimizationLevel != -1) {
2064 throw new IllegalStateException("Cannot set maximumInterpreterStackDepth when optimizationLevel != -1");
2065 }
2066 if(max < 1) {
2067 throw new IllegalArgumentException("Cannot set maximumInterpreterStackDepth to less than 1");
2068 }
2069 maximumInterpreterStackDepth = max;
2070 }
2071
2072 /**
2073 * Set the security controller for this context.
2074 * <p> SecurityController may only be set if it is currently null
2075 * and {@link SecurityController#hasGlobal()} is <tt>false</tt>.
2076 * Otherwise a SecurityException is thrown.
2077 * @param controller a SecurityController object
2078 * @throws SecurityException if there is already a SecurityController
2079 * object for this Context or globally installed.
2080 * @see SecurityController#initGlobal(SecurityController controller)
2081 * @see SecurityController#hasGlobal()
2082 */
2083 public final void setSecurityController(SecurityController controller)
2084 {
2085 if (sealed) onSealedMutation();
2086 if (controller == null) throw new IllegalArgumentException();
2087 if (securityController != null) {
2088 throw new SecurityException("Can not overwrite existing SecurityController object");
2089 }
2090 if (SecurityController.hasGlobal()) {
2091 throw new SecurityException("Can not overwrite existing global SecurityController object");
2092 }
2093 securityController = controller;
2094 }
2095
2096 /**
2097 * Set the LiveConnect access filter for this context.
2098 * <p> {@link ClassShutter} may only be set if it is currently null.
2099 * Otherwise a SecurityException is thrown.
2100 * @param shutter a ClassShutter object
2101 * @throws SecurityException if there is already a ClassShutter
2102 * object for this Context
2103 */
2104 public synchronized final void setClassShutter(ClassShutter shutter)
2105 {
2106 if (sealed) onSealedMutation();
2107 if (shutter == null) throw new IllegalArgumentException();
2108 if (hasClassShutter) {
2109 throw new SecurityException("Cannot overwrite existing " +
2110 "ClassShutter object");
2111 }
2112 classShutter = shutter;
2113 hasClassShutter = true;
2114 }
2115
2116 final synchronized ClassShutter getClassShutter()
2117 {
2118 return classShutter;
2119 }
2120
2121 public interface ClassShutterSetter {
2122 public void setClassShutter(ClassShutter shutter);
2123 public ClassShutter getClassShutter();
2124 }
2125
2126 public final synchronized ClassShutterSetter getClassShutterSetter() {
2127 if (hasClassShutter)
2128 return null;
2129 hasClassShutter = true;
2130 return new ClassShutterSetter() {
2131 public void setClassShutter(ClassShutter shutter) {
2132 classShutter = shutter;
2133 }
2134 public ClassShutter getClassShutter() {
2135 return classShutter;
2136 }
2137 };
2138 }
2139
2140 /**
2141 * Get a value corresponding to a key.
2142 * <p>
2143 * Since the Context is associated with a thread it can be
2144 * used to maintain values that can be later retrieved using
2145 * the current thread.
2146 * <p>
2147 * Note that the values are maintained with the Context, so
2148 * if the Context is disassociated from the thread the values
2149 * cannot be retrieved. Also, if private data is to be maintained
2150 * in this manner the key should be a java.lang.Object
2151 * whose reference is not divulged to untrusted code.
2152 * @param key the key used to lookup the value
2153 * @return a value previously stored using putThreadLocal.
2154 */
2155 public final Object getThreadLocal(Object key)
2156 {
2157 if (threadLocalMap == null)
2158 return null;
2159 return threadLocalMap.get(key);
2160 }
2161
2162 /**
2163 * Put a value that can later be retrieved using a given key.
2164 * <p>
2165 * @param key the key used to index the value
2166 * @param value the value to save
2167 */
2168 public synchronized final void putThreadLocal(Object key, Object value)
2169 {
2170 if (sealed) onSealedMutation();
2171 if (threadLocalMap == null)
2172 threadLocalMap = new HashMap<Object,Object>();
2173 threadLocalMap.put(key, value);
2174 }
2175
2176 /**
2177 * Remove values from thread-local storage.
2178 * @param key the key for the entry to remove.
2179 * @since 1.5 release 2
2180 */
2181 public final void removeThreadLocal(Object key)
2182 {
2183 if (sealed) onSealedMutation();
2184 if (threadLocalMap == null)
2185 return;
2186 threadLocalMap.remove(key);
2187 }
2188
2189 /**
2190 * @deprecated
2191 * @see ClassCache#get(Scriptable)
2192 * @see ClassCache#setCachingEnabled(boolean)
2193 */
2194 @Deprecated
2195 public static void setCachingEnabled(boolean cachingEnabled)
2196 {
2197 }
2198
2199 /**
2200 * Set a WrapFactory for this Context.
2201 * <p>
2202 * The WrapFactory allows custom object wrapping behavior for
2203 * Java object manipulated with JavaScript.
2204 * @see WrapFactory
2205 * @since 1.5 Release 4
2206 */
2207 public final void setWrapFactory(WrapFactory wrapFactory)
2208 {
2209 if (sealed) onSealedMutation();
2210 if (wrapFactory == null) throw new IllegalArgumentException();
2211 this.wrapFactory = wrapFactory;
2212 }
2213
2214 /**
2215 * Return the current WrapFactory, or null if none is defined.
2216 * @see WrapFactory
2217 * @since 1.5 Release 4
2218 */
2219 public final WrapFactory getWrapFactory()
2220 {
2221 if (wrapFactory == null) {
2222 wrapFactory = new WrapFactory();
2223 }
2224 return wrapFactory;
2225 }
2226
2227 /**
2228 * Return the current debugger.
2229 * @return the debugger, or null if none is attached.
2230 */
2231 public final Debugger getDebugger()
2232 {
2233 return debugger;
2234 }
2235
2236 /**
2237 * Return the debugger context data associated with current context.
2238 * @return the debugger data, or null if debugger is not attached
2239 */
2240 public final Object getDebuggerContextData()
2241 {
2242 return debuggerData;
2243 }
2244
2245 /**
2246 * Set the associated debugger.
2247 * @param debugger the debugger to be used on callbacks from
2248 * the engine.
2249 * @param contextData arbitrary object that debugger can use to store
2250 * per Context data.
2251 */
2252 public final void setDebugger(Debugger debugger, Object contextData)
2253 {
2254 if (sealed) onSealedMutation();
2255 this.debugger = debugger;
2256 debuggerData = contextData;
2257 }
2258
2259 /**
2260 * Return DebuggableScript instance if any associated with the script.
2261 * If callable supports DebuggableScript implementation, the method
2262 * returns it. Otherwise null is returned.
2263 */
2264 public static DebuggableScript getDebuggableView(Script script)
2265 {
2266 if (script instanceof NativeFunction) {
2267 return ((NativeFunction)script).getDebuggableView();
2268 }
2269 return null;
2270 }
2271
2272 /**
2273 * Controls certain aspects of script semantics.
2274 * Should be overwritten to alter default behavior.
2275 * <p>
2276 * The default implementation calls
2277 * {@link ContextFactory#hasFeature(Context cx, int featureIndex)}
2278 * that allows to customize Context behavior without introducing
2279 * Context subclasses. {@link ContextFactory} documentation gives
2280 * an example of hasFeature implementation.
2281 *
2282 * @param featureIndex feature index to check
2283 * @return true if the <code>featureIndex</code> feature is turned on
2284 * @see #FEATURE_NON_ECMA_GET_YEAR
2285 * @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
2286 * @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
2287 * @see #FEATURE_TO_STRING_AS_SOURCE
2288 * @see #FEATURE_PARENT_PROTO_PROPRTIES
2289 * @see #FEATURE_E4X
2290 * @see #FEATURE_DYNAMIC_SCOPE
2291 * @see #FEATURE_STRICT_VARS
2292 * @see #FEATURE_STRICT_EVAL
2293 * @see #FEATURE_LOCATION_INFORMATION_IN_ERROR
2294 * @see #FEATURE_STRICT_MODE
2295 * @see #FEATURE_WARNING_AS_ERROR
2296 * @see #FEATURE_ENHANCED_JAVA_ACCESS
2297 */
2298 public boolean hasFeature(int featureIndex)
2299 {
2300 ContextFactory f = getFactory();
2301 return f.hasFeature(this, featureIndex);
2302 }
2303
2304 /**
2305 * Returns an object which specifies an E4X implementation to use within
2306 * this <code>Context</code>. Note that the XMLLib.Factory interface should
2307 * be considered experimental.
2308 *
2309 * The default implementation uses the implementation provided by this
2310 * <code>Context</code>'s {@link ContextFactory}.
2311 *
2312 * @return An XMLLib.Factory. Should not return <code>null</code> if
2313 * {@link #FEATURE_E4X} is enabled. See {@link #hasFeature}.
2314 */
2315 public XMLLib.Factory getE4xImplementationFactory() {
2316 return getFactory().getE4xImplementationFactory();
2317 }
2318
2319 /**
2320 * Get threshold of executed instructions counter that triggers call to
2321 * <code>observeInstructionCount()</code>.
2322 * When the threshold is zero, instruction counting is disabled,
2323 * otherwise each time the run-time executes at least the threshold value
2324 * of script instructions, <code>observeInstructionCount()</code> will
2325 * be called.
2326 */
2327 public final int getInstructionObserverThreshold()
2328 {
2329 return instructionThreshold;
2330 }
2331
2332 /**
2333 * Set threshold of executed instructions counter that triggers call to
2334 * <code>observeInstructionCount()</code>.
2335 * When the threshold is zero, instruction counting is disabled,
2336 * otherwise each time the run-time executes at least the threshold value
2337 * of script instructions, <code>observeInstructionCount()</code> will
2338 * be called.<p/>
2339 * Note that the meaning of "instruction" is not guaranteed to be
2340 * consistent between compiled and interpretive modes: executing a given
2341 * script or function in the different modes will result in different
2342 * instruction counts against the threshold.
2343 * {@link #setGenerateObserverCount} is called with true if
2344 * <code>threshold</code> is greater than zero, false otherwise.
2345 * @param threshold The instruction threshold
2346 */
2347 public final void setInstructionObserverThreshold(int threshold)
2348 {
2349 if (sealed) onSealedMutation();
2350 if (threshold < 0) throw new IllegalArgumentException();
2351 instructionThreshold = threshold;
2352 setGenerateObserverCount(threshold > 0);
2353 }
2354
2355 /**
2356 * Turn on or off generation of code with callbacks to
2357 * track the count of executed instructions.
2358 * Currently only affects JVM byte code generation: this slows down the
2359 * generated code, but code generated without the callbacks will not
2360 * be counted toward instruction thresholds. Rhino's interpretive
2361 * mode does instruction counting without inserting callbacks, so
2362 * there is no requirement to compile code differently.
2363 * @param generateObserverCount if true, generated code will contain
2364 * calls to accumulate an estimate of the instructions executed.
2365 */
2366 public void setGenerateObserverCount(boolean generateObserverCount) {
2367 this.generateObserverCount = generateObserverCount;
2368 }
2369
2370 /**
2371 * Allow application to monitor counter of executed script instructions
2372 * in Context subclasses.
2373 * Run-time calls this when instruction counting is enabled and the counter
2374 * reaches limit set by <code>setInstructionObserverThreshold()</code>.
2375 * The method is useful to observe long running scripts and if necessary
2376 * to terminate them.
2377 * <p>
2378 * The default implementation calls
2379 * {@link ContextFactory#observeInstructionCount(Context cx,
2380 * int instructionCount)}
2381 * that allows to customize Context behavior without introducing
2382 * Context subclasses.
2383 *
2384 * @param instructionCount amount of script instruction executed since
2385 * last call to <code>observeInstructionCount</code>
2386 * @throws Error to terminate the script
2387 * @see #setOptimizationLevel(int)
2388 */
2389 protected void observeInstructionCount(int instructionCount)
2390 {
2391 ContextFactory f = getFactory();
2392 f.observeInstructionCount(this, instructionCount);
2393 }
2394
2395 /**
2396 * Create class loader for generated classes.
2397 * The method calls {@link ContextFactory#createClassLoader(ClassLoader)}
2398 * using the result of {@link #getFactory()}.
2399 */
2400 public GeneratedClassLoader createClassLoader(ClassLoader parent)
2401 {
2402 ContextFactory f = getFactory();
2403 return f.createClassLoader(parent);
2404 }
2405
2406 public final ClassLoader getApplicationClassLoader()
2407 {
2408 if (applicationClassLoader == null) {
2409 ContextFactory f = getFactory();
2410 ClassLoader loader = f.getApplicationClassLoader();
2411 if (loader == null) {
2412 ClassLoader threadLoader
2413 = VMBridge.instance.getCurrentThreadClassLoader();
2414 if (threadLoader != null
2415 && Kit.testIfCanLoadRhinoClasses(threadLoader))
2416 {
2417 // Thread.getContextClassLoader is not cached since
2418 // its caching prevents it from GC which may lead to
2419 // a memory leak and hides updates to
2420 // Thread.getContextClassLoader
2421 return threadLoader;
2422 }
2423 // Thread.getContextClassLoader can not load Rhino classes,
2424 // try to use the loader of ContextFactory or Context
2425 // subclasses.
2426 Class<?> fClass = f.getClass();
2427 if (fClass != ScriptRuntime.ContextFactoryClass) {
2428 loader = fClass.getClassLoader();
2429 } else {
2430 loader = getClass().getClassLoader();
2431 }
2432 }
2433 applicationClassLoader = loader;
2434 }
2435 return applicationClassLoader;
2436 }
2437
2438 public final void setApplicationClassLoader(ClassLoader loader)
2439 {
2440 if (sealed) onSealedMutation();
2441 if (loader == null) {
2442 // restore default behaviour
2443 applicationClassLoader = null;
2444 return;
2445 }
2446 if (!Kit.testIfCanLoadRhinoClasses(loader)) {
2447 throw new IllegalArgumentException(
2448 "Loader can not resolve Rhino classes");
2449 }
2450 applicationClassLoader = loader;
2451 }
2452
2453 /********** end of API **********/
2454
2455 /**
2456 * Internal method that reports an error for missing calls to
2457 * enter().
2458 */
2459 static Context getContext()
2460 {
2461 Context cx = getCurrentContext();
2462 if (cx == null) {
2463 throw new RuntimeException(
2464 "No Context associated with current Thread");
2465 }
2466 return cx;
2467 }
2468
2469 private Object compileImpl(Scriptable scope,
2470 Reader sourceReader, String sourceString,
2471 String sourceName, int lineno,
2472 Object securityDomain, boolean returnFunction,
2473 Evaluator compiler,
2474 ErrorReporter compilationErrorReporter)
2475 throws IOException
2476 {
2477 if(sourceName == null) {
2478 sourceName = "unnamed script";
2479 }
2480 if (securityDomain != null && getSecurityController() == null) {
2481 throw new IllegalArgumentException(
2482 "securityDomain should be null if setSecurityController() was never called");
2483 }
2484
2485 // One of sourceReader or sourceString has to be null
2486 if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug();
2487 // scope should be given if and only if compiling function
2488 if (!(scope == null ^ returnFunction)) Kit.codeBug();
2489
2490 CompilerEnvirons compilerEnv = new CompilerEnvirons();
2491 compilerEnv.initFromContext(this);
2492 if (compilationErrorReporter == null) {
2493 compilationErrorReporter = compilerEnv.getErrorReporter();
2494 }
2495
2496 if (debugger != null) {
2497 if (sourceReader != null) {
2498 sourceString = Kit.readReader(sourceReader);
2499 sourceReader = null;
2500 }
2501 }
2502
2503 Parser p = new Parser(compilerEnv, compilationErrorReporter);
2504 if (returnFunction) {
2505 p.calledByCompileFunction = true;
2506 }
2507 if (isStrictMode()) {
2508 p.setDefaultUseStrictDirective(true);
2509 }
2510 AstRoot ast;
2511 if (sourceString != null) {
2512 ast = p.parse(sourceString, sourceName, lineno);
2513 } else {
2514 ast = p.parse(sourceReader, sourceName, lineno);
2515 }
2516 if (returnFunction) {
2517 // parser no longer adds function to script node
2518 if (!(ast.getFirstChild() != null
2519 && ast.getFirstChild().getType() == Token.FUNCTION))
2520 {
2521 // XXX: the check just looks for the first child
2522 // and allows for more nodes after it for compatibility
2523 // with sources like function() {};;;
2524 throw new IllegalArgumentException(
2525 "compileFunction only accepts source with single JS function: "+sourceString);
2526 }
2527 }
2528
2529 IRFactory irf = new IRFactory(compilerEnv, compilationErrorReporter);
2530 ScriptNode tree = irf.transformTree(ast);
2531
2532 // discard everything but the IR tree
2533 p = null;
2534 ast = null;
2535 irf = null;
2536
2537 if (compiler == null) {
2538 compiler = createCompiler();
2539 }
2540
2541 Object bytecode = compiler.compile(compilerEnv,
2542 tree, tree.getEncodedSource(),
2543 returnFunction);
2544 if (debugger != null) {
2545 if (sourceString == null) Kit.codeBug();
2546 if (bytecode instanceof DebuggableScript) {
2547 DebuggableScript dscript = (DebuggableScript)bytecode;
2548 notifyDebugger_r(this, dscript, sourceString);
2549 } else {
2550 throw new RuntimeException("NOT SUPPORTED");
2551 }
2552 }
2553
2554 Object result;
2555 if (returnFunction) {
2556 result = compiler.createFunctionObject(this, scope, bytecode, securityDomain);
2557 } else {
2558 result = compiler.createScriptObject(bytecode, securityDomain);
2559 }
2560
2561 return result;
2562 }
2563
2564 private static void notifyDebugger_r(Context cx, DebuggableScript dscript,
2565 String debugSource)
2566 {
2567 cx.debugger.handleCompilationDone(cx, dscript, debugSource);
2568 for (int i = 0; i != dscript.getFunctionCount(); ++i) {
2569 notifyDebugger_r(cx, dscript.getFunction(i), debugSource);
2570 }
2571 }
2572
2573 private static Class<?> codegenClass = Kit.classOrNull(
2574 "org.mozilla.javascript.optimizer.Codegen");
2575 private static Class<?> interpreterClass = Kit.classOrNull(
2576 "org.mozilla.javascript.Interpreter");
2577
2578 private Evaluator createCompiler()
2579 {
2580 Evaluator result = null;
2581 if (optimizationLevel >= 0 && codegenClass != null) {
2582 result = (Evaluator)Kit.newInstanceOrNull(codegenClass);
2583 }
2584 if (result == null) {
2585 result = createInterpreter();
2586 }
2587 return result;
2588 }
2589
2590 static Evaluator createInterpreter()
2591 {
2592 return (Evaluator)Kit.newInstanceOrNull(interpreterClass);
2593 }
2594
2595 static String getSourcePositionFromStack(int[] linep)
2596 {
2597 Context cx = getCurrentContext();
2598 if (cx == null)
2599 return null;
2600 if (cx.lastInterpreterFrame != null) {
2601 Evaluator evaluator = createInterpreter();
2602 if (evaluator != null)
2603 return evaluator.getSourcePositionFromStack(cx, linep);
2604 }
2605 /**
2606 * A bit of a hack, but the only way to get filename and line
2607 * number from an enclosing frame.
2608 */
2609 StackTraceElement[] stackTrace = new Throwable().getStackTrace();
2610 for (StackTraceElement st : stackTrace) {
2611 String file = st.getFileName();
2612 if (!(file == null || file.endsWith(".java"))) {
2613 int line = st.getLineNumber();
2614 if (line >= 0) {
2615 linep[0] = line;
2616 return file;
2617 }
2618 }
2619 }
2620
2621 return null;
2622 }
2623
2624 RegExpProxy getRegExpProxy()
2625 {
2626 if (regExpProxy == null) {
2627 Class<?> cl = Kit.classOrNull(
2628 "org.mozilla.javascript.regexp.RegExpImpl");
2629 if (cl != null) {
2630 regExpProxy = (RegExpProxy)Kit.newInstanceOrNull(cl);
2631 }
2632 }
2633 return regExpProxy;
2634 }
2635
2636 final boolean isVersionECMA1()
2637 {
2638 return version == VERSION_DEFAULT || version >= VERSION_1_3;
2639 }
2640
2641 // The method must NOT be public or protected
2642 SecurityController getSecurityController()
2643 {
2644 SecurityController global = SecurityController.global();
2645 if (global != null) {
2646 return global;
2647 }
2648 return securityController;
2649 }
2650
2651 public final boolean isGeneratingDebugChanged()
2652 {
2653 return generatingDebugChanged;
2654 }
2655
2656 /**
2657 * Add a name to the list of names forcing the creation of real
2658 * activation objects for functions.
2659 *
2660 * @param name the name of the object to add to the list
2661 */
2662 public void addActivationName(String name)
2663 {
2664 if (sealed) onSealedMutation();
2665 if (activationNames == null)
2666 activationNames = new HashSet<String>();
2667 activationNames.add(name);
2668 }
2669
2670 /**
2671 * Check whether the name is in the list of names of objects
2672 * forcing the creation of activation objects.
2673 *
2674 * @param name the name of the object to test
2675 *
2676 * @return true if an function activation object is needed.
2677 */
2678 public final boolean isActivationNeeded(String name)
2679 {
2680 return activationNames != null && activationNames.contains(name);
2681 }
2682
2683 /**
2684 * Remove a name from the list of names forcing the creation of real
2685 * activation objects for functions.
2686 *
2687 * @param name the name of the object to remove from the list
2688 */
2689 public void removeActivationName(String name)
2690 {
2691 if (sealed) onSealedMutation();
2692 if (activationNames != null)
2693 activationNames.remove(name);
2694 }
2695
2696 public final boolean isStrictMode() {
2697 return isTopLevelStrict || (currentActivationCall != null && currentActivationCall.isStrict);
2698 }
2699
2700 private static String implementationVersion;
2701
2702 private final ContextFactory factory;
2703 private boolean sealed;
2704 private Object sealKey;
2705
2706 Scriptable topCallScope;
2707 boolean isContinuationsTopCall;
2708 NativeCall currentActivationCall;
2709 XMLLib cachedXMLLib;
2710 BaseFunction typeErrorThrower;
2711
2712 // for Objects, Arrays to tag themselves as being printed out,
2713 // so they don't print themselves out recursively.
2714 // Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility
2715 ObjToIntMap iterating;
2716
2717 Object interpreterSecurityDomain;
2718
2719 int version;
2720
2721 private SecurityController securityController;
2722 private boolean hasClassShutter;
2723 private ClassShutter classShutter;
2724 private ErrorReporter errorReporter;
2725 RegExpProxy regExpProxy;
2726 private Locale locale;
2727 private boolean generatingDebug;
2728 private boolean generatingDebugChanged;
2729 private boolean generatingSource=true;
2730 boolean useDynamicScope;
2731 private int optimizationLevel;
2732 private int maximumInterpreterStackDepth;
2733 private WrapFactory wrapFactory;
2734 Debugger debugger;
2735 private Object debuggerData;
2736 private int enterCount;
2737 private Object propertyListeners;
2738 private Map<Object,Object> threadLocalMap;
2739 private ClassLoader applicationClassLoader;
2740
2741 /**
2742 * This is the list of names of objects forcing the creation of
2743 * function activation records.
2744 */
2745 Set<String> activationNames;
2746
2747 // For the interpreter to store the last frame for error reports etc.
2748 Object lastInterpreterFrame;
2749
2750 // For the interpreter to store information about previous invocations
2751 // interpreter invocations
2752 ObjArray previousInterpreterInvocations;
2753
2754 // For instruction counting (interpreter only)
2755 int instructionCount;
2756 int instructionThreshold;
2757
2758 // It can be used to return the second index-like result from function
2759 int scratchIndex;
2760
2761 // It can be used to return the second uint32 result from function
2762 long scratchUint32;
2763
2764 // It can be used to return the second Scriptable result from function
2765 Scriptable scratchScriptable;
2766
2767 // Generate an observer count on compiled code
2768 public boolean generateObserverCount = false;
2769
2770 boolean isTopLevelStrict;
2771 }