Method and apparatus for interfacing a javascript interpreter with library of host objects implemented in java6823504Abstract A JavaScript interpreter may be interfaced with a JavaScript library of host objects implemented in Java. A JavaScript program may be accessed and parsed, an intermediate representation of the program may be generated, and the intermediate representation may be executed by interfacing with the library of host objects. In one embodiment, the JavaScript program is embedded in HTML documents in a Web browser. The browser is programmed to intercept the JavaScript code and pass execution control to an interpreter engine implemented in Java. The interpreter engine may access the program's library of host objects through an interface to the library and execute the intermediate representation to produce the desired results as programmed in the original JavaScript source program. The implementation of the interface enables the implementation of the interpreter engine to be independent from the implementation of the library of host objects and independent from the implementation of the browser. Claims What is claimed is: Description BACKGROUND OF THE INVENTION
PARSER_BEGIN(JvScParser)
class JvScParser
{
static JvScCodeGenerator codeGen; . . .
boolean parseScript (int lineOffset) throws ParseException
{
lineNumber = lineOffset;
if(Script ( ) )
{
if (codeGen.lastPut ( ) == JvScOperator.OP_STMTEND)
codeGen.unput ( );
codeGen.put (JvscOperator.OP_EOF);
return true;
}
return false;
} . . .
} . . .
.vertline. < #LETTER: [ "A"-"Z", "a"-"z", "$" ] >
.vertline. < #DIGIT: [ "0"-"9" ] >
.vertline. < IDENTIFIER: <LETTER> (<LETTER> .vertline.
<DIGIT>) * > . . .
boolean Script ( ) : { }
{
( <SEMICOLON> ) * Statement ( ) ( <SEMICOLON> ) *
( Statement ( ) ( <SEMICOLON> ) * ) * <EOF>
{ return true; }
.vertline. <EOF>
{ return false; }
}
/*
This is a handler for the JavaScript statement.
It delegates code-generating duties to other handlers depending on the
current statement type.
*/
void Statement ( ) : { boolean nonEmpty; }
{
nonEmpty = StatementBody ( )
{ if (nonEmpty)
codeGen.put (JvScOperator.OP_STMTEND);
}
.vertline. Block (null, false)
.vertline. SwitchStatement ( )
.vertline. WhileStatement ( )
.vertline. ForStatement ( )
.vertline. DoStatement ( )
.vertline. IfStatement ( )
.vertline. FunctionDefinition ( )
{ codeGen.put (JvScOperator.OP_STMTEND); }
.vertline. GlobalVarDef ( )
} . . .
/*
When a string of characters satisfying the pattern determined by
<DENTIFIER> (see above) has been encountered, it is used to create
the
JavaScript engine internal representation of identifiers, JvScName.
`token.image` is where the string is stored by the parser.
*/
JvScName Name ( ) : { }
{
<IDENTIFIER>
{ return new JvScName (token.image); }
}
Once the parser 320 has parsed the input stream of the JavaScript program 310, the parsed JavaScript code 330 may be translated into an intermediate representation Java code 350 by the representation generator component 340. The intermediate format of the preferred embodiment may be an arbitrary scheme that is similar to Java byte code. As one skilled in the art will appreciate, the intermediate format may be any scheme that adequately represents the input JavaScript code 310 for execution by a JavaScript interpreter. The representation or intermediate format 350 of the preferred embodiment is particularly suitable for execution by a stack-machine implemented interpreter written in Java. However, as one skilled in the art will readily appreciate, it is not required that the intermediate format 350 be designed such that it may be executed by stack-machine implemented interpreter. Depending on the representation scheme used, alternatively designed interpreters may be used without departing from the present invention. As stated above, the representation of the input JavaScript program 310 may be accomplished using many different schemes. The preferred embodiment of the present invention demonstrates one representation scheme using Java classes and objects. Referring now to FIG. 4, a representation scheme example according to a preferred embodiment is illustrated. The input JavaScript source code sample 410 is "Echo("2+3:"+(2+));." The JavaScript code 410 performs the simple function of adding two numbers and displaying the result. Box 420 shows a representation of the JavaScript code 410 as it is accomplished in the preferred embodiment. More particularly, box 430 lists logical commands representing the JavaScript code 410, and box 440 lists Java objects and classes which correspond to the logical representations 430. Box 450 illustrates the foregoing with Java program code. The representation generator 340 may use a stack data structure to store the intermediate representation 350 as Java objects. For example, the JavaScript function "Echo" is represented with two pushes on the stack data structure. First, the logical command "call" is pushed on the stack to indicate the presence of a function or method. Second, the name of the function "echo" is pushed on the stack. The Java object "call" is an instance of the Java class JvScFunctionalCall. Similarly, the Java object "echo" is an instance of the Java class JvScName, used for storing host objects. The names of host objects may be names of methods or functions which are called to perform specific functions. And similarly, Java classes, such as JvScOperator, JvScString and JvScNumber may be created to hold Java objects, such as the operator "add," the string "2+3" and the integer "2" respectively. The parameters and commands in the intermediate representation may be Java objects. Referring now to FIG. 5, box 510 illustrates a hierarchy of the JavaScript runtime objects and its relationship to a hierarchy of library objects 580. The class JvScAtom 520 may generally consist of a JvScOperator class 530 and the JvScDatum class 540. The JvScOperator class 530 may contain objects such as "MUL," "ADD," "CALL," "GETFIELD" and "RETURN." The JvScDatum class 540 includes JvScName 550 (e.g., name of a method or function), JvScNumber 560 (e.g., the integer "2" used in an ADD operation) and JvScObject 570 (which is inserted in the stack data structure discussed above). As stated above, the representation generator 340 may use a stack data structure to store the intermediate representation 350 as Java objects. The stack used in the representation scheme of the preferred embodiment may be an array of Java objects. Each element of this array (stack) may be either a command or a parameter. Each element may derive from an abstract Java class with very generic functionality and may contain data pertaining to the operator or data type it represents, sufficient for a stack machine interpreter to perform actions equivalent to those specified in the original JavaScript program 310. The Java class to which an object in the array (stack) belongs, may determine whether the particular object is a command or a parameter. As one of ordinary skill in the art will appreciate, there are numerous methods of representing in memory the operators and the operands of a compiled program. In the preferred embodiment of the present invention, the logical representation 430 uses the well-known Polish notation scheme. The intermediate representation 350 may have several advantages, such as a small memory footprint. Furthermore, the representation scheme of the preferred embodiment may enable faster execution of the JavaScript code 310 by the interpreter component 360. The following illustrates the representation generator component 340 of the preferred embodiment and an associated representation scheme suitable for execution by a stack-machine implemented interpreter:
void ForStatement ( ) : { }
{ <FOR> <LPAREN>ForRemainder ( ) }
void ForRemainder ( ) :
{ JvScScope scope = new JvScScope ( ) ;
JvScName n = null; }
{
LOOKAHEAD ( Name ( ) <IN> ) n = Name( ) <IN> {
scope.addLocal (n.name); }
ForInRemainder (scope, n)
.vertline. LOOKAHEAD ( <VAR> Name ( ) <IN> ) <VAR> n =
Name ( ) <IN>
{ scope.addLocal (n.name) ; } ForInRemainder (scope, n)
.vertline. [ForInitList(scope)] <SEMICOLON>
TraditionalForRemainder(scope)
}
void ForInitList (JvScScope scope) : { }
{
{ /*codeGen.put (scope); */ scope = insideFunction; }
( Expression( ) { codeGen.put(JvScOperator.OP_STMTEND); }
(LOOKAHEAD(2) <COMMA> Expression( )
{ codeGen.put (JvScOperator.OP STMTEND); }
)*
( <COMMA> LocalVarStatement (scope) )?
.vertline. LocalVarStatement(scope)
)
}
. . .
JvScAtom Literal( ) : { JvScArray a = null; }
{
<INTEGER>
{
long num = 0;
boolean tryDec = false;
if (token.image.charAt(0) == `0` && token.image.length( ) > 1)
{
if(Character.toUpperCase (
token.image.charAt (1)) == `X`)
num = Long.parseLong (
token.image.substring(2), 16);
else if(qualifyOctal (token.image)) {
num = Long.parseLong (
token.image.substring (1), 8;)
}
else {
tryDec = true;
token.image = token.image.substring(1);
}
}
else
tryDec = true;
if (tryDec)
{
try {
num = Long.parseLong (token.image);
}
catch (NumberFormatException e) {
// Most probably the number was too long
return new JvScBigNumber(token.image);
}
}
return new CacheNumber (num);
}
.vertline. <FLOAT>
{ return new
CacheNumber ( (Double.valueOf (token.image)).
DoubleValue ( ) );
}
.vertline. <STRING>
{ return new CacheString (
token.image.substring (1, token.image.length ( ) -1)); }
.vertline. <TRUE>
{ return JvScAtom.JvScTrue; }
.vertline. <FALSE>
{ return JvScAtom.JvScFalse; }
.vertline. <NULL>
{ return JvScAtom.JvScNull; }
.vertline. <UNDEFINED>
{ return JvScAtom.JvScuUdefined; }
}
. . .
JvScOperator AssignOperator ( ) : { }
{
<ASSIGN> {return JvScOperator.OP_SET; }
.vertline. <PLUS_ASSIGN> {return JvScOperator.OP_ADD_SET; }
.vertline. <MINUS_ASSIGN> {return JvScOperator.OP_SUB_SET; }
.vertline. <MUL_ASSIGN> {return JvScOperator.OP_MUL_SET; }
.vertline. <DIV_ASSIGN> {return JvScOperator.OP_DIV_SET; }
.vertline. <AND_ASSIGN> {return JvScOperator.OP_AND_SET; }
.vertline. <OR_ASSIGN> {return JvScOperator.OP_OR_SET; }
.vertline. <XOR_ASSIGN> {return JvScOperator.OP_XOR_SET; }
.vertline. <MOD_ASSIGN> {return JvScOperator.OP_MOD_SET; }
.vertline. <LSHIFT_ASSIGN> {return JvScOperator.OP_LSH_SET; }
.vertline. <RSHIFT_ASSIGN> {return JvScOperator.OP_RSH_SET; }
.vertline. <RUSHIFT_ASSIGN> {return JvScOperator.OP_USH_SET; }
}
. . .
public class JvScAtom implements Cloneable
{
/* ECMAScript compatibility constants to be used by the typeof operator.
*/
static final String typeofUndefined = "undefined";
static final String typeofObject = "object";
static final String typeofNull = typeofObject;
static final String typeofBoolean = "boolean";
static final String typeofFunction = "function";
static final String typeofNumber = "number";
static public final JvScAtom JvScTrue = new JvScObject( );
static public final JvScAtom JvScFalse = new JvScObject( );
static public final JvScAtom JvScUndefined = new JvScObject( );
static public final JvScAtom JvScNull = new JvScObject( );
static public final JvScNumber JvScNaN = new JvScNumber(DOuble.NaN);
static public final JvScAtom JvScLineNumber = new JvScAtom( );
public String typeOf( )
{
if (this == JvScNull)
return typeofNull;
else if (this == JvScUndefined)
return typeofUndefined;
else if (this == JvScTrue .parallel. this == JvScFalse)
return typeofBoolean;
else if (this == JvScObject.NaN .parallel. this ==
JvScobject.Infinity)
return typeofNumber;
return typeofObject;
}
. . .
public class JvScNumber extends JvScAtom
{
static final String NAN_STRING ="NaN";
static final int MAX_RADIX = 36;
static final String TYPEOF_NUMBER = "number";
static final String MAX_VALUE_STRING = "1.7976931348623157e308";
static final JvScNumber RADIX_10 = new JvScNumber(10);
static final JvScNumber JvScZero = new JvScNumber(0);
static final JvScNumber JvScOne = new JvScNumber(1);
boolean integer;
double value;
public JvScNumber(int value)
{ this.value = value; integer = true;
public JvScNumber(long value)
{ this.value = value; integer = true;
public JvScNumber(float value)
{ this.value = value; integer = Math.floor(value) == value; }
public JvScNumber(double value)
{ this.value = value; integer = Math.floor(value) == value; }
public JvScNumber(double value, boolean integer)
{ this.value = value; this.integer = integer; }
public JvScNumber(Number value)
{ this(value.doubleValue( )); }
final public boolean isInteger( ) { return integer; }
final public void set(int value) { this.value = value; integer = true;
}
finaJ public void set(long value) { this.value = value; integer = true;
}
final public void set(float value) { this.value = value; integer =
false; }
final public double get( ) { return value; }
final public int intValue( ) { return (int)value; }
final public long longValue( ) { return (long)value; }
final public float floatValue( ) { return (float)value;
public double doubleValue( ) { return value; }
public JvScAtom toNumber( ) { return this; }
public JvScAtom toBoolean( )
{
return value == 0.0 .parallel. Double.isNaN(value)?
JvScFalse : JvScTrue;
}
public JvScAtom isFinite( )
{ return isFiniteboolean( )? JvScTrue : JvScFalse; }
public JvScAtom isNaN( )
{ return Double.isNaN(value)? JvScTrue: JvScFalse; }
boolean isNaNboolean( )
{ return Double.isNaN(value); }
boolean isFiniteboolean( )
{
return !Double.isNaN(value)
&& value < Float.MAX_VALUE
&& value > -Float.MAX_VALUE;
}
static String trimSpaces(String str)
{
inti = 0;
for ( ; i < str.length( )
&& (Character.isWhitespace(str.charAt(i))
.parallel. str.charAt(i) == `.backslash.u000b`);
1++);
return i > 0?
(i >= str.length( )? "" : str.substring(i)) :
str;
}
static long parseInt(String inStr, int radix)
{
int i = 0;
String numstr = trimSpaces(inStr);
if(numstr.charAt (i) == `-`
.parallel. numstr.charAt (i) == `+`
.parallel.Character.digit(numstr.charAt(i), radix) >= 0)
{
for ( ++i;
i < numstr.length( )
&& Character.digit(numstr.charAt(i), radix) >= 0;
i++);
}
return i < numstr.length( )?
Long.parseLong(numstr.substring(0,i), radix) :
Long.parseLong(numstr, radix);
}
static double parseFloat(String numstr)
{
int i = 0;
boolean dot = false;
if(numstr.charAt(i) == `-`
.parallel. numstr.charAt(i) == `+`
.parallel. Character.digit(numstr.charAt(i), 10) >= 0)
{
for(++i;
i < numstr.length( )
&& (Character.digit(numstr.charAt(i), 10) >= 0
.parallel. numstr.charAt(i) == `.` && (dot = !dot));
i++);
}
return Double.valueOf(
i < numstr.length( )? numstr.substring(O,i) : numstr).
doubleValue( );
}
public Object toJavaType( )
{
if (integer)
return new Long((long)value);
else
return new Double(value);
}
public final String toString(JvScAtcm radix) throws
JavaScriptRuntimeException
{
double r = radix.doubleValue( );
if(Double.isNaN(value) .parallel. this == JvScNaN)
return NAN_STRING;
if ((int)r != 10)
{
if(Double.isNaN(r) .parallel. r <= 0 .parallel. r >
MAX_RADIX)
throw new JavaScriptRuntimeException (
"IllegaI radix: " + radix);
return Long.toString(longvalue( ), (int)r);
}
return value >= Float.MAX_VALUE?
MAX_VALUE_STRING : (integer? ""+longvalue( ): ""+(float)value);
}
public String toString( )
{
try {
return toString(RADIX_10);
}
catch(JavaScriptRuntimeException e) {
}
return NAN_STRING;
}
public String typeOf( ) { return TYPEOF_NUMBER; }
}
. . .
public class JvScObject extends JvScAtom
{
static final String CLS_ARRAY = "Array";
static final String CLS_OBJECT = "Object";
static final String CLS_NUMBER = "Number";
static final String CLS_STRING = "String";
static final String CLS_FUNCTION = "Function";
static final String FLD_PROTOTYPE = "prototype";
static final String FLD_CONSTRUCTOR = "constructor";
static final String FLD_PROTO_= "_proto_";
static final String FLD_LENGTH = "length";
static final String FLD_TOSTRING = "toString";
static final Class[ ] voidClsList = new Class[0];
public static JvScAtom proto.sub.-- = new JvScObject( );
public static JvScAtom NaN = JvScAtom.JvScNaN;
public static JvScAtom Infinity = new JvScObject( );
private static Class STRING_CLASS = "".getClass( );
Once the representation generator 340 has translated the parsed JavaScript code 330 to produce the intermediate representation 350, the interpreter component 360 may use the library interface 370 to communicate with the JavaScript host objects library 380 to execute the intermediate representation 350 and produce the desired results 390, as programmed in the original JavaScript source program 310. The interpreter 360 may pop elements off the stack, executes them and places the result back on the stack. The interpreter may execute streams of Java objects (e.g., "push" and "2+3") in the stack containing commands and parameters belonging to various Java classes (e.g., JvScOperator or JvScString). The interpreter may pop one or more elements off the stack depending on what instruction is being executed. For example, if an "ADD" operator is encountered, then the interpreter knows that it must pop two more elements which will form the operands for the "ADD" operation. The following illustrates the execution of the intermediate representation Java code 350 by the interpreter 360, according to one embodiment:
public class StackMachine
{
. . .
private JvScAtom executeScript (JvScAtom[ ] word,
int start, JvScBrowseContext bc)
throws JavaScriptRuntimeException
{
if (bc != null)
initContext(browseContext = bc);
. . .
for ( pc = start; ; pc++)
{
if ( (w=word[pc] ) instanceof JvScOperator)
{
. . .
case JvScOperator.ARITHM : arithmetic(w, n, n2) ; break;
. . .
}
else
stack [++sp] = w;
}
}
private JvScAtom arithmetic (JvScAtom w, JvScNumber n, JvScNumber n2)
throws JavaScriptRuntimeException
{
if (w == JvScOperator.OP_ADD .parallel. w ==
JvScOperator.OP_ADD_SET)
shadowNumber [sp - 1]. value = n.value + n2.value;
if (w == JvScOperator.OP_SUB .parallel. w ==
JvScOperator.OP_SUB_SET)
shadowNumber [sp - 1]. value = n.value - n2.value;
// etc., . . .
return stack [sp - 1] = shadowNumber [sp - 1];
}
Referring to FIG. 3, the interpreter component 360 may use the library interface 370 to communicate with the JavaScript host objects library 380 to execute the intermediate representation 350. In a JavaScript program execution environment, there may be several functionally independent components. The JavaScript interpreter and the JavaScript library are two of the most important components. In a preferred embodiment, the JavaScript program execution environment may be implemented using the Java programming language. The preferred embodiment may provide a mechanism whereby host objects in a JavaScript library are accessible to the interpreter in an execution environment designed in Java. The method and system of the preferred embodiment may provide an interface 370 between the JavaScript interpreter 360 and the JavaScript library objects 380, where both the interpreter 360 and the library objects 380 are written in Java. The interface 370 enables the implementation of the interpreter 360 to be independent of the implementation of the library objects 380. Furthermore, the implementation of the interpreter 360 may be independent of the HTML browser 220 in which it runs. The foregoing relationship between the interpreter, the library objects and the browser may make it possible to easily incorporate the interpreter in any Java-enabled browser with an arbitrary library objects implementation. Still referring to FIG. 3, the library objects 380 may be derived from abstract Java classes. The interpreter 360 may use the JDK Reflection API for at least two purposes. First, the Reflection API may enable the interpreter 360 to access specific information (such as properties) about known objects and classes in the library 380. Such information may include, for example, the availability of particular fields and methods within objects. Second, the Reflection API may enable the interpreter 360 to execute methods if they are not privately protected. The interface 370 may also enable manipulation of field values and call methods of an object. Additionally, fields and methods may be dynamically added or deleted in a class or object. The techniques of hash tables and the JDK Reflection API may be utilized to facilitate the foregoing processing. One JavaScript standards specification requires five basic host objects that must be present in the local library of a JavaScript interpreter. All other objects that are called by a JavaScript program must be available in other libraries accessible to the JavaScript interpreter. The programmer of the JavaScript source code must know what objects, other than the five basic host objects, are accessible to the interpreter which will execute the JavaScript source code. The Web browser in which the JavaScript program runs may provide additional non-required host objects in its libraries. As one of ordinary skill in the art will appreciate, new fields and methods may be added or deleted to any object during run time. As defined by a JavaScript standards specification, an object in JavaScript does not necessarily only bear traces of the class to which it belongs. The JavaScript object may have characteristics that are different from other objects belonging to the same class. Thus, objects in JavaScript may act as independent entities with methods and fields which may be different from the methods and fields in other objects belonging to the same class. However, objects in the same class may have certain basic methods and fields in common. Still referring to FIG. 3, during the processing of the JavaScript source code 310 in the preferred embodiment, the interpreter encounters fields and methods in the JavaScript program. The interpreter may create Java objects in a library containing the fields and the methods. However, as the input stream of JavaScript source code is processed, the interpreter may learn more information about fields and methods which it has previously encountered. The library interface 370 may provide the interpreter 360 the dynamic capability to update Java objects and their related properties or attributes. In an embodiment, the library interface 370 may have three primary Java methods through which any interaction with an object 380 is carried out. The three primary Java methods may be "get field," "set field" and "invoke method." These methods may be used in conjunction with JavaScript objects and classes whose methods and fields are known to the JavaScript library 380, but not known to the interpreter 360. The Reflection API may be used to access the JavaScript library 380 and thus inform the interpreter 360 about methods and fields contained in any particular object. The JavaScript library 380 may contain a static set of predefined objects containing methods and fields. In one embodiment, all objects within the input stream of JavaScript source code 310 must exist in the JavaScript library 380. However, certain objects within the JavaScript source code 310 may contain methods and fields which are not known to the JavaScript library 380. When this occurs, the JavaScript library 380 may be dynamically updated with the new methods and fields. Similarly, the interpreter 360 may need to be aware of the new methods and fields. The dynamic update of the library 380 may be accomplished with the use of hash tables. In a preferred embodiment, the JavaScript library 380 may include a hash table for each object. Initially, the hash table for each object may be empty. When the input JavaScript program 310 introduces a new method or field, an entry may be created in the hash table corresponding to the new method or field. The name of the new method or field may be used as the key to the hash table entry. The key serves as the means by which the new method or field may be accessed to acquire information about the method or field. For methods, the information to be accessed may be the code section associated with the new method, and for fields, the information to be accessed may be the data holder or the field value. The interpreter 360 may access the hash tables to get values of the new fields and to execute the code associated with the new methods. The newly added fields and methods in the hash tables may remain available to all JavaScript program and interpreter invocations so long as the current session of the HTML browser 220 is running. Once the HTML browser 220 is closed, the newly updated methods and fields in the hash tables may be lost and therefore, the methods and fields may not be available to future JavaScript program and interpreter invocations in a subsequent session of the HTML browser. The clearing of the new methods and fields in the hash tables at the end of an HTML browser session may be done pursuant to a JavaScript standards specification. In the preferred embodiment the source code associated with the newly added methods is not compiled when a reference to it is stored in the hash table. Instead, an intermediate representation is stored within the engine. This technique may solve certain problems encountered by the prior art. Some prior art methods compile the source code associated with the newly added methods and store the new source code in object code format for future use. The prior art technique is not efficient because it uses large amounts of memory to store the compiled object code and uses valuable processing time to convert the source code to object code. In the present invention, these problems may be overcome by storing an intermediate representation of the original JavaScript syntax. The present invention does not require that the library host objects 380 (and their associated methods) be written in Java. The objects and methods may be native code but the entry point is written in Java, in a preferred embodiment, because in the preferred embodiment the interpreter 360 may require methods to have a Java entry point so that the interpreter 360 can call on such routines. One desirable attribute of the present invention may be the independence and interchangeability of the JavaScript library 380. The preferred embodiment may include one implementation of the JavaScript library 380. This implementation may be written in Java based on a JavaScript standards specification. The JavaScript library 380 may be independent of the interpreter 360. Therefore, any other implementation of the JavaScript library 380 may be easily substituted for the library used in the preferred embodiment. As mentioned previously, both the interpreter and the JavaScript library may also be independent of the HTML browser. The independence and interchangeability of the JavaScript library may permit customization of the library to different environments, such as through the addition of objects, and their corresponding methods and fields, that may be better suited to certain HTML browsers. The following illustrates how the interpreter component 360 may use the library interface 370 to communicate with the JavaScript host objects library 380 to execute the intermediate representation 350, according to one embodiment:
public abstract class LibObject extends JvScObject
{
private static JvScBrowseContext context = null;
public static void setContext(JvScBrowseContext contxt) {context = contxt;}
public static JvScBrowserContext getContext( ) {return context:}
protected JvScAtom getField(java.lang.String name) throws
JavaScriptRuntimeException
{
java.lang.String s = "get_" + name;
try {m = getClass( ),getMethod(s, null);}
catch(Exception e) {m = null;}
if (m != null)
{
try {return (JaScAtom) (m.invoke(this, null) );}
catch (Exception e) { // fall back}
}
return super.getField(name);
}
protected JvScAtom setField(java.lang.String name, JvScAtom value)
throws JavaScriptRuntimeException
{
java.lang.String s = "set_" + name;
JvScAtom[ ] args = new JvScAtom[1];
args [0] = value;
try {
// this uses the Reflection API to find the field whose
name is specified by
// `name`. The value of s specifies what method should be
called to set the
// field.
return invokeMethod(s, args, 0, 1);
}
catch(Exception e) { // just fall back }
return super.setField(name, value);
}
}
class JvScObject extends JvScAtom
{
protected JvScAtom getField(String name) throws
JavaScriptRuntimeException
{
JvScAtom val = properties == null? null :
(JvScAtom)properties.get(name);
If(val == null)
{
// Reflection is being used:
try {
return (JvScAtom) this.
getClass( ).getField(name).get(this);
}
catch(NoSuchFiledException e) {
. . .
}
}
}
/* How methods of JavaScript (host) objects are invoked: */
protected JvScAtom invokeMethod(String name, JvScAtom mem[ ], int p1, int
n)
throws JavaScriptRuntimeException
{
/* An attempt to access a user-defined method */
if (properties != null)
try {
JvScFunction f =
/* Try to cast it to JvScFunction. If we are not caught
into an
* exception, it's really a function. */
(JvScFunction)properties.get(name);
if(f != null)
{
if(! (f instanceof JvScMethod))
properties.put(name, f=new JvScMethod (this, f) );
return (JvScAtom) f;
}
}
catchException e) {
System.out.println (name + " is a field, not method : "
+ properties.get (name) );
}
int i;
JvScAtom[ ] param;
Method method[ ] = null;
If ( (method = (Method[ ])methods.get (this.getCalss( ) ) ) == null)
methods.put(this.getClass( )
for ( i = 0; i < method.length
&& (method[i].getName( ) compareTo (name) != 0
.parallel. method[i].getParameterTypes ( ).length != n
.parallel. (n > 0 && method[i].getParameterTypes ( ) [0] ==
varParam[0] ) );
i++);
if (i >= method.length)
{
Method m;
/* Try to find method (JvScAtom[ ] varp) */
try {
m = this.getClass ( ) getMethod (name, varParam);
}
catch (Exception e) (
throw new JavaScriptRuntimeException(
"There is no method `" +
className (this.getClass ( ) ) + "." +
name + "( ).backslash. accepting " + n +
" parameter(s). ",
JavaScriptRuntimeException.NO_SUCH_METHOD
);
return invokeMethod(m, mem, p1, n)
}
try {
if(n > 0)
{
param = new JvScAtom[n];
System.arraycopy (mem, p1, param, 0, n);
}
return (JvScAtom)method[i].invoke(this, param);
}
catch (Exception e) {
if (e instanceof InvocationTargetException)
{
if ( ( (InvocationTargetException)e).getTargetException ( )
instanceof JavaScriptRuntimeException)
throw (JavaSCriptRuntimeException)
((InvocationTargetException)e).
getTargetException( );
}
throw new JavaScriptRuntimeException (
"EXCEPTION caught while trying to invoke method`" +
name +"`; " +
(e instanceof InvocationTargetException?
((InvocationTargetException)e).
getTargetException( ).toString( ) : e.toString( ) )
);
}
{
protected JvScAtom invokeMethod (Method method, JvScAtom mem[ ], int p1,
int n)
throws JavaScriptRuntimeException
{
Object[ ] p = new Object[1];
JvScAtom[ ] param = new JvScAtom[n];
System.arraycopy(mem, p1, 0, n);
P[0] = param;
try {
Return (JvScAtom)method.invoke(this, p);
}
catchException e) {
throw new JavaScriptRuntimeException (
"Exception in method " + method + ": " +
(e instance of InvocationTargetException?
((InvocationTargetException)e).
getTargetException( ).toString( ) : e.toString( ) )
);
}
}
. . .
}
static final void initFieldsFromPrototype(JvScObject o, JvScPrototype
proto) throws
JavaScriptRuntimeException
{
Object key;
for(Enumeration e = proto.properties.keys( ); e.hasMoreElements( ); )
{
key = e.nextElement( );
o.setField(key.toString( ),
(JvScAtom)proto.properties.get(key));
}
}
public JvScAtom eval(JvScAtom code)
{
return null;
}
public void setproperty(String name, JvScAtom value)
{
if (properties == null)
properties = new Hashtable( );
properties.put(name, value);
}
protected JvScAtom setField(String name, JvScAtom val)
throws JavaScriptRuntimeException
{
if(name.compareTo(FLD PROTOTYPE) == 0)
return val;
if(properties == null .parallel. properties.get(name) == null)
{
/*
* If there is no user defined field under
* this name, maybe there is the real field.
*/
try {
this.getClass( ).getField(name).set(this, val);
return val;
}
catch(IllegalAccessException ie) {
/* that means the field is final or non-public.
* In any case ignore this assignment.
*/
return val;
}
catch(Exception e) {
if(!(e instanceof NoSuchFieldException))
throw new JavaScriptRuntimeException(
"Access error: " + this.getClass( ) +
"cannot set `"` name + ".backslash.`:" + e
);
}
}
/*
* Access the user-defined properties table
*/
setProperty(name, val);
return val;
}
public JvScAtom getProperty(String name)
{ return properties == null? null : (JvScAtom)properties.get(name);}
private Exception savedException;
protected JvScAtom getField(String name) throws JavaScriptRuntimeException
{
JvScAtom val = properties == null? null :
(JvScAtom)properties.get(name);
if(val == null)
{
try {
return (JvScAtom)this.
getClass ( ).getField(name).get(this);
}
catch(NoSuchFieldException e) {
try {
return new JvScNativeFunction(
this.getClass( ).getName( ),
this.getClass( ).getMethod(name,
null)
}
catch(Exception ex) { savedException = ex; }
}
catch(Exception ex2) { saveClException = ex2; }
throw new JavaScriptRuntimeException("Access error:" +
"cannot get field `" +
className(this.getClass( )) +
"." + name + ".backslash.`:" + saveException );
}
return val;
}
boolean hasMethod(String name)
{
if (properties != null)
if(properties.get(name) != null)
return true;
Method method[ ] = (Method[ ])methods.get(this.getClass( ));
if (method != null)
for( int i=0; i <method.length; i++)
if (method [i].getName( ).compareTo(name) == 0)
return true;
return false;
}
protected JvScAtom invokeMethod(String name, JvScAtom mem[ ], int p1, int
n)
throws JavaScriptRuntimeException
Although the forgoing description has focused on Java implementations, other similar programming languages may be used as well. Any of the foregoing embodiments may be implemented by programming a suitable general-purpose machine having appropriate hardware. The machine may comprise a single computer or computing device. Alternatively, the machine may comprise a plurality of computers or computing devices connected by a communications link. Various embodiments may further include receiving, sending or storing instructions and/or data implemented in accordance with the foregoing description upon a carrier medium. Generally speaking, a carrier medium may include storage media or memory media such as magnetic or optical media, e.g., disk or CD-ROM, volatile or non-volatile media such as RAM (e.g. SDRAM, DDR SDRAM, RDRAM, SRAM, etc.), ROM, etc. as well as transmission media or signals such as electrical, electromagnetic, or digital signals, conveyed via a communication medium such as network and/or a wireless link. It will be appreciated by those of ordinary skill having the benefit of this disclosure that the illustrative embodiments described above are capable of numerous variations without departing from the scope and spirit of the invention. Various modifications and changes may be made as would be obvious to a person skilled in the art having the benefit of this disclosure. It is intended that the following claims be interpreted to embrace all such modifications and changes and, accordingly, the specifications and drawings are to be regarded in an illustrative rather than a restrictive sense.
|
Same subclass Same class Consider this |
||||||||||
