Debian Codegraph @

rhino/src/org/mozilla/javascript/NativeJavaMethod.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 package org.mozilla.javascript;
8
9 import java.lang.reflect.*;
10 import java.util.Arrays;
11 import java.util.concurrent.CopyOnWriteArrayList;
12
13 /**
14 * This class reflects Java methods into the JavaScript environment and
15 * handles overloading of methods.
16 *
17 * @author Mike Shaver
18 * @see NativeJavaArray
19 * @see NativeJavaPackage
20 * @see NativeJavaClass
21 */
22
23 public class NativeJavaMethod extends BaseFunction
24 {
25 static final long serialVersionUID = -3440381785576412928L;
26
27 NativeJavaMethod(MemberBox[] methods)
28 {
29 this.functionName = methods[0].getName();
30 this.methods = methods;
31 }
32
33 NativeJavaMethod(MemberBox[] methods, String name)
34 {
35 this.functionName = name;
36 this.methods = methods;
37 }
38
39 NativeJavaMethod(MemberBox method, String name)
40 {
41 this.functionName = name;
42 this.methods = new MemberBox[] { method };
43 }
44
45 public NativeJavaMethod(Method method, String name)
46 {
47 this(new MemberBox(method), name);
48 }
49
50 @Override
51 public String getFunctionName()
52 {
53 return functionName;
54 }
55
56 static String scriptSignature(Object[] values)
57 {
58 StringBuilder sig = new StringBuilder();
59 for (int i = 0; i != values.length; ++i) {
60 Object value = values[i];
61
62 String s;
63 if (value == null) {
64 s = "null";
65 } else if (value instanceof Boolean) {
66 s = "boolean";
67 } else if (value instanceof String) {
68 s = "string";
69 } else if (value instanceof Number) {
70 s = "number";
71 } else if (value instanceof Scriptable) {
72 if (value instanceof Undefined) {
73 s = "undefined";
74 } else if (value instanceof Wrapper) {
75 Object wrapped = ((Wrapper)value).unwrap();
76 s = wrapped.getClass().getName();
77 } else if (value instanceof Function) {
78 s = "function";
79 } else {
80 s = "object";
81 }
82 } else {
83 s = JavaMembers.javaSignature(value.getClass());
84 }
85
86 if (i != 0) {
87 sig.append(',');
88 }
89 sig.append(s);
90 }
91 return sig.toString();
92 }
93
94 @Override
95 String decompile(int indent, int flags)
96 {
97 StringBuilder sb = new StringBuilder();
98 boolean justbody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
99 if (!justbody) {
100 sb.append("function ");
101 sb.append(getFunctionName());
102 sb.append("() {");
103 }
104 sb.append("/*\n");
105 sb.append(toString());
106 sb.append(justbody ? "*/\n" : "*/}\n");
107 return sb.toString();
108 }
109
110 @Override
111 public String toString()
112 {
113 StringBuilder sb = new StringBuilder();
114 for (int i = 0, N = methods.length; i != N; ++i) {
115 // Check member type, we also use this for overloaded constructors
116 if (methods[i].isMethod()) {
117 Method method = methods[i].method();
118 sb.append(JavaMembers.javaSignature(method.getReturnType()));
119 sb.append(' ');
120 sb.append(method.getName());
121 } else {
122 sb.append(methods[i].getName());
123 }
124 sb.append(JavaMembers.liveConnectSignature(methods[i].argTypes));
125 sb.append('\n');
126 }
127 return sb.toString();
128 }
129
130 @Override
131 public Object call(Context cx, Scriptable scope, Scriptable thisObj,
132 Object[] args)
133 {
134 // Find a method that matches the types given.
135 if (methods.length == 0) {
136 throw new RuntimeException("No methods defined for call");
137 }
138
139 int index = findCachedFunction(cx, args);
140 if (index < 0) {
141 Class<?> c = methods[0].method().getDeclaringClass();
142 String sig = c.getName() + '.' + getFunctionName() + '(' +
143 scriptSignature(args) + ')';
144 throw Context.reportRuntimeError1("msg.java.no_such_method", sig);
145 }
146
147 MemberBox meth = methods[index];
148 Class<?>[] argTypes = meth.argTypes;
149
150 if (meth.vararg) {
151 // marshall the explicit parameters
152 Object[] newArgs = new Object[argTypes.length];
153 for (int i = 0; i < argTypes.length-1; i++) {
154 newArgs[i] = Context.jsToJava(args[i], argTypes[i]);
155 }
156
157 Object varArgs;
158
159 // Handle special situation where a single variable parameter
160 // is given and it is a Java or ECMA array or is null.
161 if (args.length == argTypes.length &&
162 (args[args.length-1] == null ||
163 args[args.length-1] instanceof NativeArray ||
164 args[args.length-1] instanceof NativeJavaArray))
165 {
166 // convert the ECMA array into a native array
167 varArgs = Context.jsToJava(args[args.length-1],
168 argTypes[argTypes.length - 1]);
169 } else {
170 // marshall the variable parameters
171 Class<?> componentType = argTypes[argTypes.length - 1].
172 getComponentType();
173 varArgs = Array.newInstance(componentType,
174 args.length - argTypes.length + 1);
175 for (int i = 0; i < Array.getLength(varArgs); i++) {
176 Object value = Context.jsToJava(args[argTypes.length-1 + i],
177 componentType);
178 Array.set(varArgs, i, value);
179 }
180 }
181
182 // add varargs
183 newArgs[argTypes.length-1] = varArgs;
184 // replace the original args with the new one
185 args = newArgs;
186 } else {
187 // First, we marshall the args.
188 Object[] origArgs = args;
189 for (int i = 0; i < args.length; i++) {
190 Object arg = args[i];
191 Object coerced = Context.jsToJava(arg, argTypes[i]);
192 if (coerced != arg) {
193 if (origArgs == args) {
194 args = args.clone();
195 }
196 args[i] = coerced;
197 }
198 }
199 }
200 Object javaObject;
201 if (meth.isStatic()) {
202 javaObject = null; // don't need an object
203 } else {
204 Scriptable o = thisObj;
205 Class<?> c = meth.getDeclaringClass();
206 for (;;) {
207 if (o == null) {
208 throw Context.reportRuntimeError3(
209 "msg.nonjava.method", getFunctionName(),
210 ScriptRuntime.toString(thisObj), c.getName());
211 }
212 if (o instanceof Wrapper) {
213 javaObject = ((Wrapper)o).unwrap();
214 if (c.isInstance(javaObject)) {
215 break;
216 }
217 }
218 o = o.getPrototype();
219 }
220 }
221 if (debug) {
222 printDebug("Calling ", meth, args);
223 }
224
225 Object retval = meth.invoke(javaObject, args);
226 Class<?> staticType = meth.method().getReturnType();
227
228 if (debug) {
229 Class<?> actualType = (retval == null) ? null
230 : retval.getClass();
231 System.err.println(" ----- Returned " + retval +
232 " actual = " + actualType +
233 " expect = " + staticType);
234 }
235
236 Object wrapped = cx.getWrapFactory().wrap(cx, scope,
237 retval, staticType);
238 if (debug) {
239 Class<?> actualType = (wrapped == null) ? null
240 : wrapped.getClass();
241 System.err.println(" ----- Wrapped as " + wrapped +
242 " class = " + actualType);
243 }
244
245 if (wrapped == null && staticType == Void.TYPE) {
246 wrapped = Undefined.instance;
247 }
248 return wrapped;
249 }
250
251 int findCachedFunction(Context cx, Object[] args) {
252 if (methods.length > 1) {
253 if (overloadCache != null) {
254 for (ResolvedOverload ovl : overloadCache) {
255 if (ovl.matches(args)) {
256 return ovl.index;
257 }
258 }
259 } else {
260 overloadCache = new CopyOnWriteArrayList<ResolvedOverload>();
261 }
262 int index = findFunction(cx, methods, args);
263 // As a sanity measure, don't let the lookup cache grow longer
264 // than twice the number of overloaded methods
265 if (overloadCache.size() < methods.length * 2) {
266 synchronized (overloadCache) {
267 ResolvedOverload ovl = new ResolvedOverload(args, index);
268 if (!overloadCache.contains(ovl)) {
269 overloadCache.add(0, ovl);
270 }
271 }
272 }
273 return index;
274 }
275 return findFunction(cx, methods, args);
276 }
277
278 /**
279 * Find the index of the correct function to call given the set of methods
280 * or constructors and the arguments.
281 * If no function can be found to call, return -1.
282 */
283 static int findFunction(Context cx,
284 MemberBox[] methodsOrCtors, Object[] args)
285 {
286 if (methodsOrCtors.length == 0) {
287 return -1;
288 } else if (methodsOrCtors.length == 1) {
289 MemberBox member = methodsOrCtors[0];
290 Class<?>[] argTypes = member.argTypes;
291 int alength = argTypes.length;
292
293 if (member.vararg) {
294 alength--;
295 if ( alength > args.length) {
296 return -1;
297 }
298 } else {
299 if (alength != args.length) {
300 return -1;
301 }
302 }
303 for (int j = 0; j != alength; ++j) {
304 if (!NativeJavaObject.canConvert(args[j], argTypes[j])) {
305 if (debug) printDebug("Rejecting (args can't convert) ",
306 member, args);
307 return -1;
308 }
309 }
310 if (debug) printDebug("Found ", member, args);
311 return 0;
312 }
313
314 int firstBestFit = -1;
315 int[] extraBestFits = null;
316 int extraBestFitsCount = 0;
317
318 search:
319 for (int i = 0; i < methodsOrCtors.length; i++) {
320 MemberBox member = methodsOrCtors[i];
321 Class<?>[] argTypes = member.argTypes;
322 int alength = argTypes.length;
323 if (member.vararg) {
324 alength--;
325 if ( alength > args.length) {
326 continue search;
327 }
328 } else {
329 if (alength != args.length) {
330 continue search;
331 }
332 }
333 for (int j = 0; j < alength; j++) {
334 if (!NativeJavaObject.canConvert(args[j], argTypes[j])) {
335 if (debug) printDebug("Rejecting (args can't convert) ",
336 member, args);
337 continue search;
338 }
339 }
340 if (firstBestFit < 0) {
341 if (debug) printDebug("Found first applicable ", member, args);
342 firstBestFit = i;
343 } else {
344 // Compare with all currently fit methods.
345 // The loop starts from -1 denoting firstBestFit and proceed
346 // until extraBestFitsCount to avoid extraBestFits allocation
347 // in the most common case of no ambiguity
348 int betterCount = 0; // number of times member was prefered over
349 // best fits
350 int worseCount = 0; // number of times best fits were prefered
351 // over member
352 for (int j = -1; j != extraBestFitsCount; ++j) {
353 int bestFitIndex;
354 if (j == -1) {
355 bestFitIndex = firstBestFit;
356 } else {
357 bestFitIndex = extraBestFits[j];
358 }
359 MemberBox bestFit = methodsOrCtors[bestFitIndex];
360 if (cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) &&
361 (bestFit.member().getModifiers() & Modifier.PUBLIC) !=
362 (member.member().getModifiers() & Modifier.PUBLIC))
363 {
364 // When FEATURE_ENHANCED_JAVA_ACCESS gives us access
365 // to non-public members, continue to prefer public
366 // methods in overloading
367 if ((bestFit.member().getModifiers() & Modifier.PUBLIC) == 0)
368 ++betterCount;
369 else
370 ++worseCount;
371 } else {
372 int preference = preferSignature(args, argTypes,
373 member.vararg,
374 bestFit.argTypes,
375 bestFit.vararg );
376 if (preference == PREFERENCE_AMBIGUOUS) {
377 break;
378 } else if (preference == PREFERENCE_FIRST_ARG) {
379 ++betterCount;
380 } else if (preference == PREFERENCE_SECOND_ARG) {
381 ++worseCount;
382 } else {
383 if (preference != PREFERENCE_EQUAL) Kit.codeBug();
384 // This should not happen in theory
385 // but on some JVMs, Class.getMethods will return all
386 // static methods of the class hierarchy, even if
387 // a derived class's parameters match exactly.
388 // We want to call the derived class's method.
389 if (bestFit.isStatic() &&
390 bestFit.getDeclaringClass().isAssignableFrom(
391 member.getDeclaringClass()))
392 {
393 // On some JVMs, Class.getMethods will return all
394 // static methods of the class hierarchy, even if
395 // a derived class's parameters match exactly.
396 // We want to call the derived class's method.
397 if (debug) printDebug(
398 "Substituting (overridden static)",
399 member, args);
400 if (j == -1) {
401 firstBestFit = i;
402 } else {
403 extraBestFits[j] = i;
404 }
405 } else {
406 if (debug) printDebug(
407 "Ignoring same signature member ",
408 member, args);
409 }
410 continue search;
411 }
412 }
413 }
414 if (betterCount == 1 + extraBestFitsCount) {
415 // member was prefered over all best fits
416 if (debug) printDebug(
417 "New first applicable ", member, args);
418 firstBestFit = i;
419 extraBestFitsCount = 0;
420 } else if (worseCount == 1 + extraBestFitsCount) {
421 // all best fits were prefered over member, ignore it
422 if (debug) printDebug(
423 "Rejecting (all current bests better) ", member, args);
424 } else {
425 // some ambiguity was present, add member to best fit set
426 if (debug) printDebug(
427 "Added to best fit set ", member, args);
428 if (extraBestFits == null) {
429 // Allocate maximum possible array
430 extraBestFits = new int[methodsOrCtors.length - 1];
431 }
432 extraBestFits[extraBestFitsCount] = i;
433 ++extraBestFitsCount;
434 }
435 }
436 }
437
438 if (firstBestFit < 0) {
439 // Nothing was found
440 return -1;
441 } else if (extraBestFitsCount == 0) {
442 // single best fit
443 return firstBestFit;
444 }
445
446 // report remaining ambiguity
447 StringBuilder buf = new StringBuilder();
448 for (int j = -1; j != extraBestFitsCount; ++j) {
449 int bestFitIndex;
450 if (j == -1) {
451 bestFitIndex = firstBestFit;
452 } else {
453 bestFitIndex = extraBestFits[j];
454 }
455 buf.append("\n ");
456 buf.append(methodsOrCtors[bestFitIndex].toJavaDeclaration());
457 }
458
459 MemberBox firstFitMember = methodsOrCtors[firstBestFit];
460 String memberName = firstFitMember.getName();
461 String memberClass = firstFitMember.getDeclaringClass().getName();
462
463 if (methodsOrCtors[0].isCtor()) {
464 throw Context.reportRuntimeError3(
465 "msg.constructor.ambiguous",
466 memberName, scriptSignature(args), buf.toString());
467 } else {
468 throw Context.reportRuntimeError4(
469 "msg.method.ambiguous", memberClass,
470 memberName, scriptSignature(args), buf.toString());
471 }
472 }
473
474 /** Types are equal */
475 private static final int PREFERENCE_EQUAL = 0;
476 private static final int PREFERENCE_FIRST_ARG = 1;
477 private static final int PREFERENCE_SECOND_ARG = 2;
478 /** No clear "easy" conversion */
479 private static final int PREFERENCE_AMBIGUOUS = 3;
480
481 /**
482 * Determine which of two signatures is the closer fit.
483 * Returns one of PREFERENCE_EQUAL, PREFERENCE_FIRST_ARG,
484 * PREFERENCE_SECOND_ARG, or PREFERENCE_AMBIGUOUS.
485 */
486 private static int preferSignature(Object[] args,
487 Class<?>[] sig1,
488 boolean vararg1,
489 Class<?>[] sig2,
490 boolean vararg2 )
491 {
492 int totalPreference = 0;
493 for (int j = 0; j < args.length; j++) {
494 Class<?> type1 = vararg1 && j >= sig1.length ? sig1[sig1.length-1] : sig1[j];
495 Class<?> type2 = vararg2 && j >= sig2.length ? sig2[sig2.length-1] : sig2[j];
496 if (type1 == type2) {
497 continue;
498 }
499 Object arg = args[j];
500
501 // Determine which of type1, type2 is easier to convert from arg.
502
503 int rank1 = NativeJavaObject.getConversionWeight(arg, type1);
504 int rank2 = NativeJavaObject.getConversionWeight(arg, type2);
505
506 int preference;
507 if (rank1 < rank2) {
508 preference = PREFERENCE_FIRST_ARG;
509 } else if (rank1 > rank2) {
510 preference = PREFERENCE_SECOND_ARG;
511 } else {
512 // Equal ranks
513 if (rank1 == NativeJavaObject.CONVERSION_NONTRIVIAL) {
514 if (type1.isAssignableFrom(type2)) {
515 preference = PREFERENCE_SECOND_ARG;
516 } else if (type2.isAssignableFrom(type1)) {
517 preference = PREFERENCE_FIRST_ARG;
518 } else {
519 preference = PREFERENCE_AMBIGUOUS;
520 }
521 } else {
522 preference = PREFERENCE_AMBIGUOUS;
523 }
524 }
525
526 totalPreference |= preference;
527
528 if (totalPreference == PREFERENCE_AMBIGUOUS) {
529 break;
530 }
531 }
532 return totalPreference;
533 }
534
535
536 private static final boolean debug = false;
537
538 private static void printDebug(String msg, MemberBox member,
539 Object[] args)
540 {
541 if (debug) {
542 StringBuilder sb = new StringBuilder();
543 sb.append(" ----- ");
544 sb.append(msg);
545 sb.append(member.getDeclaringClass().getName());
546 sb.append('.');
547 if (member.isMethod()) {
548 sb.append(member.getName());
549 }
550 sb.append(JavaMembers.liveConnectSignature(member.argTypes));
551 sb.append(" for arguments (");
552 sb.append(scriptSignature(args));
553 sb.append(')');
554 System.out.println(sb);
555 }
556 }
557
558 MemberBox[] methods;
559 private String functionName;
560 private transient CopyOnWriteArrayList<ResolvedOverload> overloadCache;
561 }
562
563 class ResolvedOverload {
564 final Class<?>[] types;
565 final int index;
566
567 ResolvedOverload(Object[] args, int index) {
568 this.index = index;
569 types = new Class<?>[args.length];
570 for (int i = 0, l = args.length; i < l; i++) {
571 Object arg = args[i];
572 if (arg instanceof Wrapper)
573 arg = ((Wrapper)arg).unwrap();
574 types[i] = arg == null ? null : arg.getClass();
575 }
576 }
577
578 boolean matches(Object[] args) {
579 if (args.length != types.length) {
580 return false;
581 }
582 for (int i = 0, l = args.length; i < l; i++) {
583 Object arg = args[i];
584 if (arg instanceof Wrapper)
585 arg = ((Wrapper)arg).unwrap();
586 if (arg == null) {
587 if (types[i] != null) return false;
588 } else if (arg.getClass() != types[i]) {
589 return false;
590 }
591 }
592 return true;
593 }
594
595 @Override
596 public boolean equals(Object other) {
597 if (!(other instanceof ResolvedOverload)) {
598 return false;
599 }
600 ResolvedOverload ovl = (ResolvedOverload) other;
601 return Arrays.equals(types, ovl.types) && index == ovl.index;
602 }
603
604 @Override
605 public int hashCode() {
606 return Arrays.hashCode(types);
607 }
608 }