com.google.javascript.rhino
Class Context

java.lang.Object
  extended by com.google.javascript.rhino.Context

public class Context
extends Object

This class represents the runtime context of an executing script. Before executing a script, an instance of Context must be created and associated with the thread that will be executing the script. The Context will be used to store information about the executing of the script such as the call stack. Contexts are associated with the current thread using the enter() method.

Different forms of script execution are supported. Scripts may be evaluated from the source directly, or first compiled and then later executed. Interactive execution is also supported.

Some aspects of script execution, such as type conversions and object creation, may be accessed directly through methods of Context.


Field Summary
static Object[] emptyArgs
          Convinient value to use as zero-length array of objects.
static String errorReporterProperty
           
static int FEATURE_DYNAMIC_SCOPE
          Control if dynamic scope should be used for name access.
static int FEATURE_E4X
          Control if support for E4X(ECMAScript for XML) extension is available.
static int FEATURE_LOCATION_INFORMATION_IN_ERROR
          When the feature is on Rhino will add a "fileName" and "lineNumber" properties to Error objects automatically.
static int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
          Control if member expression as function name extension is available.
static int FEATURE_NON_ECMA_GET_YEAR
          Controls behaviour of Date.prototype.getYear().
static int FEATURE_PARENT_PROTO_PROPRTIES
          Control if properties __proto__ and __parent__ are treated specially.
static int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
          Control if reserved keywords are treated as identifiers.
static int FEATURE_STRICT_EVAL
          Control if strict eval mode is enabled.
static int FEATURE_STRICT_MODE
          Controls whether JS 1.5 'strict mode' is enabled.
static int FEATURE_STRICT_VARS
          Control if strict variable mode is enabled.
static int FEATURE_TO_STRING_AS_SOURCE
          Control if toString() should returns the same result as toSource() when applied to objects and arrays.
static int FEATURE_WARNING_AS_ERROR
          Controls whether a warning should be treated as an error.
static String languageVersionProperty
           
static int VERSION_1_0
          JavaScript 1.0
static int VERSION_1_1
          JavaScript 1.1
static int VERSION_1_2
          JavaScript 1.2
static int VERSION_1_3
          JavaScript 1.3
static int VERSION_1_4
          JavaScript 1.4
static int VERSION_1_5
          JavaScript 1.5
static int VERSION_1_6
          JavaScript 1.5
static int VERSION_DEFAULT
          The default version.
static int VERSION_UNKNOWN
          The unknown version.
 
Constructor Summary
Context()
          Create a new Context.
 
Method Summary
 void addActivationName(String name)
          Add a name to the list of names forcing the creation of real activation objects for functions.
 void addPropertyChangeListener(PropertyChangeListener l)
          Register an object to receive notifications when a bound property has changed
static void checkLanguageVersion(int version)
           
static void checkOptimizationLevel(int optimizationLevel)
           
static Context enter()
          Get a context associated with the current thread, creating one if need be.
static Context enter(Context cx)
          Get a Context associated with the current thread, using the given Context if need be.
static void exit()
          Exit a block of code requiring a Context.
static Context getCurrentContext()
          Get the current Context.
 Object getDebuggerContextData()
          Return the debugger context data associated with current context.
 ErrorReporter getErrorReporter()
          Get the current error reporter.
 String getImplementationVersion()
          Get the implementation version.
 int getInstructionObserverThreshold()
          Get/Set threshold of executed instructions counter that triggers call to observeInstructionCount().
 int getLanguageVersion()
          Get the current language version.
 Locale getLocale()
          Get the current locale.
 int getOptimizationLevel()
          Get the current optimization level.
 Object getThreadLocal(Object key)
          Get a value corresponding to a key.
 boolean hasCompileFunctionsWithDynamicScope()
          Deprecated.  
protected  boolean hasFeature(int featureIndex)
          Implementation of hasFeature(int featureIndex).
 boolean isActivationNeeded(String name)
          Check whether the name is in the list of names of objects forcing the creation of activation objects.
 boolean isGeneratingDebug()
          Tell whether debug information is being generated.
 boolean isGeneratingDebugChanged()
           
 boolean isGeneratingSource()
          Tell whether source information is being generated.
 boolean isSealed()
          Checks if this is a sealed Context.
static boolean isValidLanguageVersion(int version)
           
static boolean isValidOptimizationLevel(int optimizationLevel)
           
 void putThreadLocal(Object key, Object value)
          Put a value that can later be retrieved using a given key.
 void removeActivationName(String name)
          Remove a name from the list of names forcing the creation of real activation objects for functions.
 void removePropertyChangeListener(PropertyChangeListener l)
          Remove an object from the list of objects registered to receive notification of changes to a bounded property
 void removeThreadLocal(Object key)
          Remove values from thread-local storage.
static void reportError(String message)
          Report an error using the error reporter for the current thread.
static void reportError(String message, String sourceName, int lineno, String lineSource, int lineOffset)
          Report an error using the error reporter for the current thread.
static EvaluatorException reportRuntimeError(String message)
          Report a runtime error using the error reporter for the current thread.
static EvaluatorException reportRuntimeError(String message, String sourceName, int lineno, String lineSource, int lineOffset)
          Report a runtime error using the error reporter for the current thread.
static void reportWarning(String message)
          Report a warning using the error reporter for the current thread.
static void reportWarning(String message, String sourceName, int lineno, String lineSource, int lineOffset)
          Report a warning using the error reporter for the current thread.
 void seal(Object sealKey)
          Seal this Context object so any attempt to modify any of its properties including calling enter() and exit() methods will throw an exception.
 void setCompileFunctionsWithDynamicScope(boolean flag)
          Deprecated.  
 ErrorReporter setErrorReporter(ErrorReporter reporter)
          Change the current error reporter.
 void setGeneratingSource(boolean generatingSource)
          Specify whether or not source information should be generated.
 void setInstructionObserverThreshold(int threshold)
           
 void setLanguageVersion(int version)
          Set the language version.
 Locale setLocale(Locale loc)
          Set the current locale.
 void unseal(Object sealKey)
          Unseal previously sealed Context object.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

VERSION_UNKNOWN

public static final int VERSION_UNKNOWN
The unknown version.

See Also:
Constant Field Values

VERSION_DEFAULT

public static final int VERSION_DEFAULT
The default version.

See Also:
Constant Field Values

VERSION_1_0

public static final int VERSION_1_0
JavaScript 1.0

See Also:
Constant Field Values

VERSION_1_1

public static final int VERSION_1_1
JavaScript 1.1

See Also:
Constant Field Values

VERSION_1_2

public static final int VERSION_1_2
JavaScript 1.2

See Also:
Constant Field Values

VERSION_1_3

public static final int VERSION_1_3
JavaScript 1.3

See Also:
Constant Field Values

VERSION_1_4

public static final int VERSION_1_4
JavaScript 1.4

See Also:
Constant Field Values

VERSION_1_5

public static final int VERSION_1_5
JavaScript 1.5

See Also:
Constant Field Values

VERSION_1_6

public static final int VERSION_1_6
JavaScript 1.5

See Also:
Constant Field Values

FEATURE_NON_ECMA_GET_YEAR

public static final int FEATURE_NON_ECMA_GET_YEAR
Controls behaviour of Date.prototype.getYear(). If hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true, Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000. The default behavior of hasFeature(int) is always to subtruct 1900 as rquired by ECMAScript B.2.4.

See Also:
Constant Field Values

FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME

public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
Control if member expression as function name extension is available. If hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true, allow function memberExpression(args) { body } to be syntax sugar for memberExpression = function(args) { body }, when memberExpression is not a simple identifier. See ECMAScript-262, section 11.2 for definition of memberExpression. By default hasFeature(int) returns false.

See Also:
Constant Field Values

FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER

public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
Control if reserved keywords are treated as identifiers. If hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER) returns true, treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary identifiers but warn about this usage. By default hasFeature(int) returns false.

See Also:
Constant Field Values

FEATURE_TO_STRING_AS_SOURCE

public static final int FEATURE_TO_STRING_AS_SOURCE
Control if toString() should returns the same result as toSource() when applied to objects and arrays. If hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true, calling toString() on JS objects gives the same result as calling toSource(). That is it returns JS source with code to create an object with all enumeratable fields of the original object.

By default hasFeature(int) returns true only if the current JS version is set to VERSION_1_2.

See Also:
Constant Field Values

FEATURE_PARENT_PROTO_PROPRTIES

public static final int FEATURE_PARENT_PROTO_PROPRTIES
Control if properties __proto__ and __parent__ are treated specially. If hasFeature(FEATURE_PARENT_PROTO_PROPRTIES) returns true, treat __parent__ and __proto__ as special properties.

The properties allow to query and set scope and prototype chains for the objects. The special meaning of the properties is available only when they are used as the right hand side of the dot operator. For example, while x.__proto__ = y changes the prototype chain of the object x to point to y, x["__proto__"] = y simply assigns a new value to the property __proto__ in x even when the feature is on. By default hasFeature(int) returns true.

See Also:
Constant Field Values

FEATURE_E4X

public static final int FEATURE_E4X
Control if support for E4X(ECMAScript for XML) extension is available. If hasFeature(FEATURE_E4X) returns true, the XML syntax is available.

By default hasFeature(int) returns true if the current JS version is set to VERSION_DEFAULT or is greater then VERSION_1_6.

Since:
1.6 Release 1
See Also:
Constant Field Values

FEATURE_DYNAMIC_SCOPE

public static final int FEATURE_DYNAMIC_SCOPE
Control if dynamic scope should be used for name access. If hasFeature(FEATURE_DYNAMIC_SCOPE) returns true, then the name lookup during name resolution will use the top scope of the script or function which is at the top of JS execution stack instead of the top scope of the script or function from the current stack frame if the top scope of the top stack frame contains the top scope of the current stack frame on its prototype chain.

This is useful to define shared scope containing functions that can be called from scripts and functions using private scopes.

By default hasFeature(int) returns false.

Since:
1.6 Release 1
See Also:
Constant Field Values

FEATURE_STRICT_VARS

public static final int FEATURE_STRICT_VARS
Control if strict variable mode is enabled. When the feature is on Rhino reports runtime errors if assignment to a global variable that does not exist is executed. When the feature is off such assignments creates new variable in the global scope as required by ECMA 262.

By default hasFeature(int) returns false.

Since:
1.6 Release 1
See Also:
Constant Field Values

FEATURE_STRICT_EVAL

public static final int FEATURE_STRICT_EVAL
Control if strict eval mode is enabled. When the feature is on Rhino reports runtime errors if non-string argument is passed to the eval function. When the feature is off eval simply return non-string argument as is without performing any evaluation as required by ECMA 262.

By default hasFeature(int) returns false.

Since:
1.6 Release 1
See Also:
Constant Field Values

FEATURE_LOCATION_INFORMATION_IN_ERROR

public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR
When the feature is on Rhino will add a "fileName" and "lineNumber" properties to Error objects automatically. When the feature is off, you have to explicitly pass them as the second and third argument to the Error constructor. Note that neither behaviour is fully ECMA 262 compliant (as 262 doesn't specify a three-arg constructor), but keeping the feature off results in Error objects that don't have additional non-ECMA properties when constructed using the ECMA-defined single-arg constructor and is thus desirable if a stricter ECMA compliance is desired, specifically adherence to the point 15.11.5. of the standard.

By default hasFeature(int) returns false.

Since:
1.6 Release 6
See Also:
Constant Field Values

FEATURE_STRICT_MODE

public static final int FEATURE_STRICT_MODE
Controls whether JS 1.5 'strict mode' is enabled. When the feature is on, Rhino reports more than a dozen different warnings. When the feature is off, these warnings are not generated. FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL.

By default hasFeature(int) returns false.

Since:
1.6 Release 6
See Also:
Constant Field Values

FEATURE_WARNING_AS_ERROR

public static final int FEATURE_WARNING_AS_ERROR
Controls whether a warning should be treated as an error.

Since:
1.6 Release 6
See Also:
Constant Field Values

languageVersionProperty

public static final String languageVersionProperty
See Also:
Constant Field Values

errorReporterProperty

public static final String errorReporterProperty
See Also:
Constant Field Values

emptyArgs

public static final Object[] emptyArgs
Convinient value to use as zero-length array of objects.

Constructor Detail

Context

public Context()
Create a new Context. Note that the Context must be associated with a thread before it can be used to execute a script.

See Also:
enter()
Method Detail

enter

public static Context enter()
Get a context associated with the current thread, creating one if need be. The Context stores the execution state of the JavaScript engine, so it is required that the context be entered before execution may begin. Once a thread has entered a Context, then getCurrentContext() may be called to find the context that is associated with the current thread.

Calling enter() will return either the Context currently associated with the thread, or will create a new context and associate it with the current thread. Each call to enter() must have a matching call to exit(). For example,

      Context cx = Context.enter();
      try {
          ...
          cx.evaluateString(...);
      }
      finally { Context.exit(); }
 

Returns:
a Context associated with the current thread
See Also:
getCurrentContext(), exit()

enter

public static Context enter(Context cx)
Get a Context associated with the current thread, using the given Context if need be.

The same as enter() except that cx is associated with the current thread and returned if the current thread has no associated context and cx is not associated with any other thread.

Parameters:
cx - a Context to associate with the thread if possible
Returns:
a Context associated with the current thread

exit

public static void exit()
Exit a block of code requiring a Context. Calling exit() will remove the association between the current thread and a Context if the prior call to enter() on this thread newly associated a Context with this thread. Once the current thread no longer has an associated Context, it cannot be used to execute JavaScript until it is again associated with a Context.

See Also:
enter()

getCurrentContext

public static Context getCurrentContext()
Get the current Context. The current Context is per-thread; this method looks up the Context associated with the current thread.

Returns:
the Context associated with the current thread, or null if no context is associated with the current thread.

isSealed

public final boolean isSealed()
Checks if this is a sealed Context. A sealed Context instance does not allow to modify any of its properties and will throw an exception on any such attempt.

See Also:
seal(Object sealKey)

seal

public final void seal(Object sealKey)
Seal this Context object so any attempt to modify any of its properties including calling enter() and exit() methods will throw an exception.

If sealKey is not null, calling unseal(Object sealKey) with the same key unseals the object. If sealKey is null, unsealing is no longer possible.

See Also:
isSealed(), unseal(Object)

unseal

public final void unseal(Object sealKey)
Unseal previously sealed Context object. The sealKey argument should not be null and should match sealKey suplied with the last call to seal(Object) or an exception will be thrown.

See Also:
isSealed(), seal(Object sealKey)

getLanguageVersion

public final int getLanguageVersion()
Get the current language version.

The language version number affects JavaScript semantics as detailed in the overview documentation.

Returns:
an integer that is one of VERSION_1_0, VERSION_1_1, etc.

setLanguageVersion

public void setLanguageVersion(int version)
Set the language version.

Setting the language version will affect functions and scripts compiled subsequently. See the overview documentation for version-specific behavior.

Parameters:
version - the version as specified by VERSION_1_0, VERSION_1_1, etc.

isValidLanguageVersion

public static boolean isValidLanguageVersion(int version)

checkLanguageVersion

public static void checkLanguageVersion(int version)

getImplementationVersion

public final String getImplementationVersion()
Get the implementation version.

The implementation version is of the form

    "name langVer release relNum date"
 
where name is the name of the product, langVer is the language version, relNum is the release number, and date is the release date for that specific release in the form "yyyy mm dd".

Returns:
a string that encodes the product, language version, release number, and date.

getErrorReporter

public final ErrorReporter getErrorReporter()
Get the current error reporter.

See Also:
ErrorReporter

setErrorReporter

public final ErrorReporter setErrorReporter(ErrorReporter reporter)
Change the current error reporter.

Returns:
the previous error reporter
See Also:
ErrorReporter

getLocale

public final Locale getLocale()
Get the current locale. Returns the default locale if none has been set.

See Also:
Locale

setLocale

public final Locale setLocale(Locale loc)
Set the current locale.

See Also:
Locale

addPropertyChangeListener

public final void addPropertyChangeListener(PropertyChangeListener l)
Register an object to receive notifications when a bound property has changed

Parameters:
l - the listener
See Also:
PropertyChangeEvent, removePropertyChangeListener(java.beans.PropertyChangeListener)

removePropertyChangeListener

public final void removePropertyChangeListener(PropertyChangeListener l)
Remove an object from the list of objects registered to receive notification of changes to a bounded property

Parameters:
l - the listener
See Also:
PropertyChangeEvent, addPropertyChangeListener(java.beans.PropertyChangeListener)

reportWarning

public static void reportWarning(String message,
                                 String sourceName,
                                 int lineno,
                                 String lineSource,
                                 int lineOffset)
Report a warning using the error reporter for the current thread.

Parameters:
message - the warning message to report
sourceName - a string describing the source, such as a filename
lineno - the starting line number
lineSource - the text of the line (may be null)
lineOffset - the offset into lineSource where problem was detected
See Also:
ErrorReporter

reportWarning

public static void reportWarning(String message)
Report a warning using the error reporter for the current thread.

Parameters:
message - the warning message to report
See Also:
ErrorReporter

reportError

public static void reportError(String message,
                               String sourceName,
                               int lineno,
                               String lineSource,
                               int lineOffset)
Report an error using the error reporter for the current thread.

Parameters:
message - the error message to report
sourceName - a string describing the source, such as a filename
lineno - the starting line number
lineSource - the text of the line (may be null)
lineOffset - the offset into lineSource where problem was detected
See Also:
ErrorReporter

reportError

public static void reportError(String message)
Report an error using the error reporter for the current thread.

Parameters:
message - the error message to report
See Also:
ErrorReporter

reportRuntimeError

public static EvaluatorException reportRuntimeError(String message,
                                                    String sourceName,
                                                    int lineno,
                                                    String lineSource,
                                                    int lineOffset)
Report a runtime error using the error reporter for the current thread.

Parameters:
message - the error message to report
sourceName - a string describing the source, such as a filename
lineno - the starting line number
lineSource - the text of the line (may be null)
lineOffset - the offset into lineSource where problem was detected
Returns:
a runtime exception that will be thrown to terminate the execution of the script
See Also:
ErrorReporter

reportRuntimeError

public static EvaluatorException reportRuntimeError(String message)
Report a runtime error using the error reporter for the current thread.

Parameters:
message - the error message to report
See Also:
ErrorReporter

isGeneratingDebug

public final boolean isGeneratingDebug()
Tell whether debug information is being generated.

Since:
1.3

isGeneratingSource

public final boolean isGeneratingSource()
Tell whether source information is being generated.

Since:
1.3

setGeneratingSource

public final void setGeneratingSource(boolean generatingSource)
Specify whether or not source information should be generated.

Without source information, evaluating the "toString" method on JavaScript functions produces only "[native code]" for the body of the function. Note that code generated without source is not fully ECMA conformant.

Since:
1.3

getOptimizationLevel

public final int getOptimizationLevel()
Get the current optimization level.

The optimization level is expressed as an integer between -1 and 9.

Since:
1.3

isValidOptimizationLevel

public static boolean isValidOptimizationLevel(int optimizationLevel)

checkOptimizationLevel

public static void checkOptimizationLevel(int optimizationLevel)

getThreadLocal

public final Object getThreadLocal(Object key)
Get a value corresponding to a key.

Since the Context is associated with a thread it can be used to maintain values that can be later retrieved using the current thread.

Note that the values are maintained with the Context, so if the Context is disassociated from the thread the values cannot be retreived. Also, if private data is to be maintained in this manner the key should be a java.lang.Object whose reference is not divulged to untrusted code.

Parameters:
key - the key used to lookup the value
Returns:
a value previously stored using putThreadLocal.

putThreadLocal

public final void putThreadLocal(Object key,
                                 Object value)
Put a value that can later be retrieved using a given key.

Parameters:
key - the key used to index the value
value - the value to save

removeThreadLocal

public final void removeThreadLocal(Object key)
Remove values from thread-local storage.

Parameters:
key - the key for the entry to remove.
Since:
1.5 release 2

hasCompileFunctionsWithDynamicScope

@Deprecated
public final boolean hasCompileFunctionsWithDynamicScope()
Deprecated. 

See Also:
FEATURE_DYNAMIC_SCOPE, hasFeature(int)

setCompileFunctionsWithDynamicScope

@Deprecated
public final void setCompileFunctionsWithDynamicScope(boolean flag)
Deprecated. 

See Also:
FEATURE_DYNAMIC_SCOPE, hasFeature(int)

getDebuggerContextData

public final Object getDebuggerContextData()
Return the debugger context data associated with current context.

Returns:
the debugger data, or null if debugger is not attached

hasFeature

protected boolean hasFeature(int featureIndex)
Implementation of hasFeature(int featureIndex). This can be used to customize Context without introducing additional subclasses.


getInstructionObserverThreshold

public final int getInstructionObserverThreshold()
Get/Set threshold of executed instructions counter that triggers call to observeInstructionCount(). When the threshold is zero, instruction counting is disabled, otherwise each time the run-time executes at least the threshold value of script instructions, observeInstructionCount() will be called.


setInstructionObserverThreshold

public final void setInstructionObserverThreshold(int threshold)

isGeneratingDebugChanged

public final boolean isGeneratingDebugChanged()

addActivationName

public void addActivationName(String name)
Add a name to the list of names forcing the creation of real activation objects for functions.

Parameters:
name - the name of the object to add to the list

isActivationNeeded

public final boolean isActivationNeeded(String name)
Check whether the name is in the list of names of objects forcing the creation of activation objects.

Parameters:
name - the name of the object to test
Returns:
true if an function activation object is needed.

removeActivationName

public void removeActivationName(String name)
Remove a name from the list of names forcing the creation of real activation objects for functions.

Parameters:
name - the name of the object to remove from the list