Debian Codegraph @

rhino/src/org/mozilla/javascript/FunctionObject.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.lang.reflect.*;
12 import java.io.*;
13
14 public class FunctionObject extends BaseFunction
15 {
16 static final long serialVersionUID = -5332312783643935019L;
17
18 /**
19 * Create a JavaScript function object from a Java method.
20 *
21 * <p>The <code>member</code> argument must be either a java.lang.reflect.Method
22 * or a java.lang.reflect.Constructor and must match one of two forms.<p>
23 *
24 * The first form is a member with zero or more parameters
25 * of the following types: Object, String, boolean, Scriptable,
26 * int, or double. The Long type is not supported
27 * because the double representation of a long (which is the
28 * EMCA-mandated storage type for Numbers) may lose precision.
29 * If the member is a Method, the return value must be void or one
30 * of the types allowed for parameters.<p>
31 *
32 * The runtime will perform appropriate conversions based
33 * upon the type of the parameter. A parameter type of
34 * Object specifies that no conversions are to be done. A parameter
35 * of type String will use Context.toString to convert arguments.
36 * Similarly, parameters of type double, boolean, and Scriptable
37 * will cause Context.toNumber, Context.toBoolean, and
38 * Context.toObject, respectively, to be called.<p>
39 *
40 * If the method is not static, the Java 'this' value will
41 * correspond to the JavaScript 'this' value. Any attempt
42 * to call the function with a 'this' value that is not
43 * of the right Java type will result in an error.<p>
44 *
45 * The second form is the variable arguments (or "varargs")
46 * form. If the FunctionObject will be used as a constructor,
47 * the member must have the following parameters
48 * <pre>
49 * (Context cx, Object[] args, Function ctorObj,
50 * boolean inNewExpr)</pre>
51 * and if it is a Method, be static and return an Object result.<p>
52 *
53 * Otherwise, if the FunctionObject will <i>not</i> be used to define a
54 * constructor, the member must be a static Method with parameters
55 * <pre>
56 * (Context cx, Scriptable thisObj, Object[] args,
57 * Function funObj) </pre>
58 * and an Object result.<p>
59 *
60 * When the function varargs form is called as part of a function call,
61 * the <code>args</code> parameter contains the
62 * arguments, with <code>thisObj</code>
63 * set to the JavaScript 'this' value. <code>funObj</code>
64 * is the function object for the invoked function.<p>
65 *
66 * When the constructor varargs form is called or invoked while evaluating
67 * a <code>new</code> expression, <code>args</code> contains the
68 * arguments, <code>ctorObj</code> refers to this FunctionObject, and
69 * <code>inNewExpr</code> is true if and only if a <code>new</code>
70 * expression caused the call. This supports defining a function that
71 * has different behavior when called as a constructor than when
72 * invoked as a normal function call. (For example, the Boolean
73 * constructor, when called as a function,
74 * will convert to boolean rather than creating a new object.)<p>
75 *
76 * @param name the name of the function
77 * @param methodOrConstructor a java.lang.reflect.Method or a java.lang.reflect.Constructor
78 * that defines the object
79 * @param scope enclosing scope of function
80 * @see org.mozilla.javascript.Scriptable
81 */
82 public FunctionObject(String name, Member methodOrConstructor,
83 Scriptable scope)
84 {
85 if (methodOrConstructor instanceof Constructor) {
86 member = new MemberBox((Constructor<?>) methodOrConstructor);
87 isStatic = true; // well, doesn't take a 'this'
88 } else {
89 member = new MemberBox((Method) methodOrConstructor);
90 isStatic = member.isStatic();
91 }
92 String methodName = member.getName();
93 this.functionName = name;
94 Class<?>[] types = member.argTypes;
95 int arity = types.length;
96 if (arity == 4 && (types[1].isArray() || types[2].isArray())) {
97 // Either variable args or an error.
98 if (types[1].isArray()) {
99 if (!isStatic ||
100 types[0] != ScriptRuntime.ContextClass ||
101 types[1].getComponentType() != ScriptRuntime.ObjectClass ||
102 types[2] != ScriptRuntime.FunctionClass ||
103 types[3] != Boolean.TYPE)
104 {
105 throw Context.reportRuntimeError1(
106 "msg.varargs.ctor", methodName);
107 }
108 parmsLength = VARARGS_CTOR;
109 } else {
110 if (!isStatic ||
111 types[0] != ScriptRuntime.ContextClass ||
112 types[1] != ScriptRuntime.ScriptableClass ||
113 types[2].getComponentType() != ScriptRuntime.ObjectClass ||
114 types[3] != ScriptRuntime.FunctionClass)
115 {
116 throw Context.reportRuntimeError1(
117 "msg.varargs.fun", methodName);
118 }
119 parmsLength = VARARGS_METHOD;
120 }
121 } else {
122 parmsLength = arity;
123 if (arity > 0) {
124 typeTags = new byte[arity];
125 for (int i = 0; i != arity; ++i) {
126 int tag = getTypeTag(types[i]);
127 if (tag == JAVA_UNSUPPORTED_TYPE) {
128 throw Context.reportRuntimeError2(
129 "msg.bad.parms", types[i].getName(), methodName);
130 }
131 typeTags[i] = (byte)tag;
132 }
133 }
134 }
135
136 if (member.isMethod()) {
137 Method method = member.method();
138 Class<?> returnType = method.getReturnType();
139 if (returnType == Void.TYPE) {
140 hasVoidReturn = true;
141 } else {
142 returnTypeTag = getTypeTag(returnType);
143 }
144 } else {
145 Class<?> ctorType = member.getDeclaringClass();
146 if (!ScriptRuntime.ScriptableClass.isAssignableFrom(ctorType)) {
147 throw Context.reportRuntimeError1(
148 "msg.bad.ctor.return", ctorType.getName());
149 }
150 }
151
152 ScriptRuntime.setFunctionProtoAndParent(this, scope);
153 }
154
155 /**
156 * @return One of <tt>JAVA_*_TYPE</tt> constants to indicate desired type
157 * or {@link #JAVA_UNSUPPORTED_TYPE} if the convertion is not
158 * possible
159 */
160 public static int getTypeTag(Class<?> type)
161 {
162 if (type == ScriptRuntime.StringClass)
163 return JAVA_STRING_TYPE;
164 if (type == ScriptRuntime.IntegerClass || type == Integer.TYPE)
165 return JAVA_INT_TYPE;
166 if (type == ScriptRuntime.BooleanClass || type == Boolean.TYPE)
167 return JAVA_BOOLEAN_TYPE;
168 if (type == ScriptRuntime.DoubleClass || type == Double.TYPE)
169 return JAVA_DOUBLE_TYPE;
170 if (ScriptRuntime.ScriptableClass.isAssignableFrom(type))
171 return JAVA_SCRIPTABLE_TYPE;
172 if (type == ScriptRuntime.ObjectClass)
173 return JAVA_OBJECT_TYPE;
174
175 // Note that the long type is not supported; see the javadoc for
176 // the constructor for this class
177
178 return JAVA_UNSUPPORTED_TYPE;
179 }
180
181 public static Object convertArg(Context cx, Scriptable scope,
182 Object arg, int typeTag)
183 {
184 switch (typeTag) {
185 case JAVA_STRING_TYPE:
186 if (arg instanceof String)
187 return arg;
188 return ScriptRuntime.toString(arg);
189 case JAVA_INT_TYPE:
190 if (arg instanceof Integer)
191 return arg;
192 return Integer.valueOf(ScriptRuntime.toInt32(arg));
193 case JAVA_BOOLEAN_TYPE:
194 if (arg instanceof Boolean)
195 return arg;
196 return ScriptRuntime.toBoolean(arg) ? Boolean.TRUE
197 : Boolean.FALSE;
198 case JAVA_DOUBLE_TYPE:
199 if (arg instanceof Double)
200 return arg;
201 return new Double(ScriptRuntime.toNumber(arg));
202 case JAVA_SCRIPTABLE_TYPE:
203 return ScriptRuntime.toObjectOrNull(cx, arg, scope);
204 case JAVA_OBJECT_TYPE:
205 return arg;
206 default:
207 throw new IllegalArgumentException();
208 }
209 }
210
211 /**
212 * Return the value defined by the method used to construct the object
213 * (number of parameters of the method, or 1 if the method is a "varargs"
214 * form).
215 */
216 @Override
217 public int getArity() {
218 return parmsLength < 0 ? 1 : parmsLength;
219 }
220
221 /**
222 * Return the same value as {@link #getArity()}.
223 */
224 @Override
225 public int getLength() {
226 return getArity();
227 }
228
229 @Override
230 public String getFunctionName()
231 {
232 return (functionName == null) ? "" : functionName;
233 }
234
235 /**
236 * Get Java method or constructor this function represent.
237 */
238 public Member getMethodOrConstructor()
239 {
240 if (member.isMethod()) {
241 return member.method();
242 } else {
243 return member.ctor();
244 }
245 }
246
247 static Method findSingleMethod(Method[] methods, String name)
248 {
249 Method found = null;
250 for (int i = 0, N = methods.length; i != N; ++i) {
251 Method method = methods[i];
252 if (method != null && name.equals(method.getName())) {
253 if (found != null) {
254 throw Context.reportRuntimeError2(
255 "msg.no.overload", name,
256 method.getDeclaringClass().getName());
257 }
258 found = method;
259 }
260 }
261 return found;
262 }
263
264 /**
265 * Returns all public methods declared by the specified class. This excludes
266 * inherited methods.
267 *
268 * @param clazz the class from which to pull public declared methods
269 * @return the public methods declared in the specified class
270 * @see Class#getDeclaredMethods()
271 */
272 static Method[] getMethodList(Class<?> clazz) {
273 Method[] methods = null;
274 try {
275 // getDeclaredMethods may be rejected by the security manager
276 // but getMethods is more expensive
277 if (!sawSecurityException)
278 methods = clazz.getDeclaredMethods();
279 } catch (SecurityException e) {
280 // If we get an exception once, give up on getDeclaredMethods
281 sawSecurityException = true;
282 }
283 if (methods == null) {
284 methods = clazz.getMethods();
285 }
286 int count = 0;
287 for (int i=0; i < methods.length; i++) {
288 if (sawSecurityException
289 ? methods[i].getDeclaringClass() != clazz
290 : !Modifier.isPublic(methods[i].getModifiers()))
291 {
292 methods[i] = null;
293 } else {
294 count++;
295 }
296 }
297 Method[] result = new Method[count];
298 int j=0;
299 for (int i=0; i < methods.length; i++) {
300 if (methods[i] != null)
301 result[j++] = methods[i];
302 }
303 return result;
304 }
305
306 /**
307 * Define this function as a JavaScript constructor.
308 * <p>
309 * Sets up the "prototype" and "constructor" properties. Also
310 * calls setParent and setPrototype with appropriate values.
311 * Then adds the function object as a property of the given scope, using
312 * <code>prototype.getClassName()</code>
313 * as the name of the property.
314 *
315 * @param scope the scope in which to define the constructor (typically
316 * the global object)
317 * @param prototype the prototype object
318 * @see org.mozilla.javascript.Scriptable#setParentScope
319 * @see org.mozilla.javascript.Scriptable#setPrototype
320 * @see org.mozilla.javascript.Scriptable#getClassName
321 */
322 public void addAsConstructor(Scriptable scope, Scriptable prototype)
323 {
324 initAsConstructor(scope, prototype);
325 defineProperty(scope, prototype.getClassName(),
326 this, ScriptableObject.DONTENUM);
327 }
328
329 void initAsConstructor(Scriptable scope, Scriptable prototype)
330 {
331 ScriptRuntime.setFunctionProtoAndParent(this, scope);
332 setImmunePrototypeProperty(prototype);
333
334 prototype.setParentScope(this);
335
336 defineProperty(prototype, "constructor", this,
337 ScriptableObject.DONTENUM |
338 ScriptableObject.PERMANENT |
339 ScriptableObject.READONLY);
340 setParentScope(scope);
341 }
342
343 /**
344 * @deprecated Use {@link #getTypeTag(Class)}
345 * and {@link #convertArg(Context, Scriptable, Object, int)}
346 * for type conversion.
347 */
348 @Deprecated
349 public static Object convertArg(Context cx, Scriptable scope,
350 Object arg, Class<?> desired)
351 {
352 int tag = getTypeTag(desired);
353 if (tag == JAVA_UNSUPPORTED_TYPE) {
354 throw Context.reportRuntimeError1
355 ("msg.cant.convert", desired.getName());
356 }
357 return convertArg(cx, scope, arg, tag);
358 }
359
360 /**
361 * Performs conversions on argument types if needed and
362 * invokes the underlying Java method or constructor.
363 * <p>
364 * Implements Function.call.
365 *
366 * @see org.mozilla.javascript.Function#call(
367 * Context, Scriptable, Scriptable, Object[])
368 */
369 @Override
370 public Object call(Context cx, Scriptable scope, Scriptable thisObj,
371 Object[] args)
372 {
373 Object result;
374 boolean checkMethodResult = false;
375 int argsLength = args.length;
376
377 for (int i = 0; i < argsLength; i++) {
378 // flatten cons-strings before passing them as arguments
379 if (args[i] instanceof ConsString) {
380 args[i] = args[i].toString();
381 }
382 }
383
384 if (parmsLength < 0) {
385 if (parmsLength == VARARGS_METHOD) {
386 Object[] invokeArgs = { cx, thisObj, args, this };
387 result = member.invoke(null, invokeArgs);
388 checkMethodResult = true;
389 } else {
390 boolean inNewExpr = (thisObj == null);
391 Boolean b = inNewExpr ? Boolean.TRUE : Boolean.FALSE;
392 Object[] invokeArgs = { cx, args, this, b };
393 result = (member.isCtor())
394 ? member.newInstance(invokeArgs)
395 : member.invoke(null, invokeArgs);
396 }
397
398 } else {
399 if (!isStatic) {
400 Class<?> clazz = member.getDeclaringClass();
401 if (!clazz.isInstance(thisObj)) {
402 boolean compatible = false;
403 if (thisObj == scope) {
404 Scriptable parentScope = getParentScope();
405 if (scope != parentScope) {
406 // Call with dynamic scope for standalone function,
407 // use parentScope as thisObj
408 compatible = clazz.isInstance(parentScope);
409 if (compatible) {
410 thisObj = parentScope;
411 }
412 }
413 }
414 if (!compatible) {
415 // Couldn't find an object to call this on.
416 throw ScriptRuntime.typeError1("msg.incompat.call",
417 functionName);
418 }
419 }
420 }
421
422 Object[] invokeArgs;
423 if (parmsLength == argsLength) {
424 // Do not allocate new argument array if java arguments are
425 // the same as the original js ones.
426 invokeArgs = args;
427 for (int i = 0; i != parmsLength; ++i) {
428 Object arg = args[i];
429 Object converted = convertArg(cx, scope, arg, typeTags[i]);
430 if (arg != converted) {
431 if (invokeArgs == args) {
432 invokeArgs = args.clone();
433 }
434 invokeArgs[i] = converted;
435 }
436 }
437 } else if (parmsLength == 0) {
438 invokeArgs = ScriptRuntime.emptyArgs;
439 } else {
440 invokeArgs = new Object[parmsLength];
441 for (int i = 0; i != parmsLength; ++i) {
442 Object arg = (i < argsLength)
443 ? args[i]
444 : Undefined.instance;
445 invokeArgs[i] = convertArg(cx, scope, arg, typeTags[i]);
446 }
447 }
448
449 if (member.isMethod()) {
450 result = member.invoke(thisObj, invokeArgs);
451 checkMethodResult = true;
452 } else {
453 result = member.newInstance(invokeArgs);
454 }
455
456 }
457
458 if (checkMethodResult) {
459 if (hasVoidReturn) {
460 result = Undefined.instance;
461 } else if (returnTypeTag == JAVA_UNSUPPORTED_TYPE) {
462 result = cx.getWrapFactory().wrap(cx, scope, result, null);
463 }
464 // XXX: the code assumes that if returnTypeTag == JAVA_OBJECT_TYPE
465 // then the Java method did a proper job of converting the
466 // result to JS primitive or Scriptable to avoid
467 // potentially costly Context.javaToJS call.
468 }
469
470 return result;
471 }
472
473 /**
474 * Return new {@link Scriptable} instance using the default
475 * constructor for the class of the underlying Java method.
476 * Return null to indicate that the call method should be used to create
477 * new objects.
478 */
479 @Override
480 public Scriptable createObject(Context cx, Scriptable scope) {
481 if (member.isCtor() || parmsLength == VARARGS_CTOR) {
482 return null;
483 }
484 Scriptable result;
485 try {
486 result = (Scriptable) member.getDeclaringClass().newInstance();
487 } catch (Exception ex) {
488 throw Context.throwAsScriptRuntimeEx(ex);
489 }
490
491 result.setPrototype(getClassPrototype());
492 result.setParentScope(getParentScope());
493 return result;
494 }
495
496 boolean isVarArgsMethod() {
497 return parmsLength == VARARGS_METHOD;
498 }
499
500 boolean isVarArgsConstructor() {
501 return parmsLength == VARARGS_CTOR;
502 }
503
504 private void readObject(ObjectInputStream in)
505 throws IOException, ClassNotFoundException
506 {
507 in.defaultReadObject();
508 if (parmsLength > 0) {
509 Class<?>[] types = member.argTypes;
510 typeTags = new byte[parmsLength];
511 for (int i = 0; i != parmsLength; ++i) {
512 typeTags[i] = (byte)getTypeTag(types[i]);
513 }
514 }
515 if (member.isMethod()) {
516 Method method = member.method();
517 Class<?> returnType = method.getReturnType();
518 if (returnType == Void.TYPE) {
519 hasVoidReturn = true;
520 } else {
521 returnTypeTag = getTypeTag(returnType);
522 }
523 }
524 }
525
526 private static final short VARARGS_METHOD = -1;
527 private static final short VARARGS_CTOR = -2;
528
529 private static boolean sawSecurityException;
530
531 public static final int JAVA_UNSUPPORTED_TYPE = 0;
532 public static final int JAVA_STRING_TYPE = 1;
533 public static final int JAVA_INT_TYPE = 2;
534 public static final int JAVA_BOOLEAN_TYPE = 3;
535 public static final int JAVA_DOUBLE_TYPE = 4;
536 public static final int JAVA_SCRIPTABLE_TYPE = 5;
537 public static final int JAVA_OBJECT_TYPE = 6;
538
539 MemberBox member;
540 private String functionName;
541 private transient byte[] typeTags;
542 private int parmsLength;
543 private transient boolean hasVoidReturn;
544 private transient int returnTypeTag;
545 private boolean isStatic;
546 }