Debian Codegraph @

src/main/c/jpy_jmethod.c

raw symbols SCIP
1 /*
2 * Copyright 2015 Brockmann Consult GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * This file was modified by Deephaven Data Labs.
17 */
18
19 #include "jpy_module.h"
20 #include "jpy_diag.h"
21 #include "jpy_jtype.h"
22 #include "jpy_jobj.h"
23 #include "jpy_jmethod.h"
24 #include "jpy_conv.h"
25 #include "jpy_compat.h"
26
27
28 JPy_JMethod* JMethod_New(JPy_JType* declaringClass,
29 PyObject* name,
30 int paramCount,
31 JPy_ParamDescriptor* paramDescriptors,
32 JPy_ReturnDescriptor* returnDescriptor,
33 jboolean isStatic,
34 jboolean isVarArgs,
35 jmethodID mid)
36 {
37 PyTypeObject* type = &JMethod_Type;
38 JPy_JMethod* method;
39
40 method = (JPy_JMethod*) type->tp_alloc(type, 0);
41 method->declaringClass = declaringClass;
42 method->name = name;
43 method->paramCount = paramCount;
44 method->paramDescriptors = paramDescriptors;
45 method->returnDescriptor = returnDescriptor;
46 method->isStatic = isStatic;
47 method->isVarArgs = isVarArgs;
48 method->mid = mid;
49
50 JPy_INCREF(declaringClass);
51 JPy_INCREF(method->name);
52
53 return method;
54 }
55
56
57 /**
58 * The JMethod type's tp_dealloc slot.
59 */
60 void JMethod_dealloc(JPy_JMethod* self)
61 {
62 JNIEnv* jenv;
63
64 JPy_DECREF(self->declaringClass);
65 JPy_DECREF(self->name);
66
67 jenv = JPy_GetJNIEnv();
68 if (jenv != NULL) {
69 int i;
70 for (i = 0; i < self->paramCount; i++) {
71 JPy_DECREF((self->paramDescriptors + i)->type);
72 }
73 JPy_DECREF((self->returnDescriptor + i)->type);
74 }
75
76 PyMem_Del(self->paramDescriptors);
77 PyMem_Del(self->returnDescriptor);
78
79 Py_TYPE(self)->tp_free((PyObject*) self);
80 }
81
82 void JMethod_Del(JPy_JMethod* method)
83 {
84 JMethod_dealloc(method);
85 }
86
87 /**
88 * Matches the give Python argument tuple against the Java method's formal parameters.
89 * Returns the sum of the i-th argument against the i-th Java parameter.
90 * The maximum match value returned is 100 * method->paramCount.
91 *
92 * The isVarArgsArray pointer is set to 1 if this is a varargs match for an object array
93 * argument.
94 */
95 int JMethod_MatchPyArgs(JNIEnv* jenv, JPy_JType* declaringClass, JPy_JMethod* method, int argCount, PyObject* pyArgs, int *isVarArgArray)
96 {
97 JPy_ParamDescriptor* paramDescriptor;
98 PyObject* pyArg;
99 int matchValueSum;
100 int matchValue;
101 int i;
102 int i0;
103 int iLast;
104 *isVarArgArray = 0;
105
106 if (method->isStatic) {
107 if (method->isVarArgs) {
108 if(argCount < method->paramCount - 1) {
109 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: var args argument count mismatch java=%d, python=%d (matchValue=0)\n", method->paramCount, argCount);
110 // argument count mismatch
111 return 0;
112 }
113 iLast = method->paramCount - 1;
114 } else {
115 if (method->paramCount != argCount) {
116 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: argument count mismatch (matchValue=0)\n");
117 // argument count mismatch
118 return 0;
119 }
120 if (method->paramCount == 0) {
121 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: no-argument static method (matchValue=100)\n");
122 // There can't be any other static method overloads with no parameters
123 return 100;
124 }
125
126 iLast = argCount;
127 }
128 matchValueSum = 0;
129 i0 = 0;
130 } else {
131 PyObject* self;
132 //printf("Non-Static! method->paramCount=%d, argCount=%d, isVarArg=%d\n", method->paramCount, argCount, method->isVarArgs);
133
134 if (method->isVarArgs) {
135 if (argCount < method->paramCount) {
136 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: var args argument count mismatch java=%d, python=%d (matchValue=0)\n", method->paramCount, argCount);
137 // argument count mismatch
138 return 0;
139 }
140 iLast = method->paramCount;
141 }
142 else if (method->paramCount != argCount - 1) {
143 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: argument count mismatch (matchValue=0)\n");
144 // argument count mismatch
145 return 0;
146 } else {
147 iLast = method->paramCount + 1;
148 }
149
150 self = PyTuple_GetItem(pyArgs, 0);
151 if (self == Py_None) {
152 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: self argument is None (matchValue=0)\n");
153 return 0;
154 }
155 if (!JObj_Check(self)) {
156 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: self argument is not a Java object (matchValue=0)\n");
157 return 0;
158 }
159
160 i0 = 1;
161 matchValueSum = JType_MatchPyArgAsJObject(jenv, declaringClass, self);
162 if (matchValueSum == 0) {
163 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: self argument does not match required Java class (matchValue=0)\n");
164 return 0;
165 }
166 if (method->paramCount == 0) {
167 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: no-argument non-static method (matchValue=%d)\n", matchValueSum);
168 // There can't be any other method overloads with no parameters
169 return matchValueSum;
170 }
171 }
172
173 paramDescriptor = method->paramDescriptors;
174 for (i = i0; i < iLast; i++) {
175 pyArg = PyTuple_GetItem(pyArgs, i);
176 matchValue = paramDescriptor->MatchPyArg(jenv, paramDescriptor, pyArg);
177
178 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: pyArgs[%d]: paramDescriptor->type->javaName='%s', matchValue=%d\n", i, paramDescriptor->type->javaName, matchValue);
179
180 if (matchValue == 0) {
181 //printf("JMethod_MatchPyArgs 6\n");
182 // current pyArg does not match parameter type at all
183 return 0;
184 }
185
186 matchValueSum += matchValue;
187 paramDescriptor++;
188 }
189 if (method->isVarArgs) {
190 int singleMatchValue = 0;
191
192 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: isVarArgs, argCount = %d, i=%d\n", argCount, i);
193
194 if (argCount - i == 0) {
195 matchValueSum += 10;
196 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: isVarArgs, argCount = %d, paramCount = %d, matchValueSum=%d\n", argCount, method->paramCount, matchValueSum);
197 } else if (argCount - i == 1) {
198 // if we have exactly one argument, which matches our array type, then we can use that as an array
199 pyArg = PyTuple_GetItem(pyArgs, i);
200 singleMatchValue = paramDescriptor->MatchPyArg(jenv, paramDescriptor, pyArg);
201 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: isVarArgs, argCount = %d, paramCount = %d, starting singleMatchValue=%d\n", argCount, method->paramCount, singleMatchValue);
202 }
203
204 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: isVarArgs, argCount = %d, paramCount = %d, starting matchValue=%d\n", argCount, method->paramCount, matchValueSum);
205 matchValue = paramDescriptor->MatchVarArgPyArg(jenv, paramDescriptor, pyArgs, i);
206 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JMethod_MatchPyArgs: isVarArgs, paramDescriptor->type->javaName='%s', matchValue=%d\n", paramDescriptor->type->javaName, matchValue);
207 if (matchValue == 0 && singleMatchValue == 0) {
208 return 0;
209 }
210 if (matchValue > singleMatchValue) {
211 matchValueSum += matchValue;
212 } else {
213 matchValueSum += singleMatchValue;
214 *isVarArgArray = 1;
215 }
216 }
217
218 //printf("JMethod_MatchPyArgs 7\n");
219 return matchValueSum;
220 }
221
222 #define JPy_SUPPORT_RETURN_PARAMETER 1
223
224 PyObject* JMethod_FromJObject(JNIEnv* jenv, JPy_JMethod* method, PyObject* pyArgs, jvalue* jArgs, int argOffset, JPy_JType* returnType, jobject jReturnValue)
225 {
226 #ifdef JPy_SUPPORT_RETURN_PARAMETER
227 if (method->returnDescriptor->paramIndex >= 0) {
228 jint paramIndex = method->returnDescriptor->paramIndex;
229 PyObject* pyReturnArg = PyTuple_GetItem(pyArgs, paramIndex + argOffset);
230 jobject jArg = jArgs[paramIndex].l;
231 //printf("JMethod_FromJObject: paramIndex=%d, jArg=%p, isNone=%d\n", paramIndex, jArg, pyReturnArg == Py_None);
232 if ((JObj_Check(pyReturnArg) || PyObject_CheckBuffer(pyReturnArg))
233 && (*jenv)->IsSameObject(jenv, jReturnValue, jArg)) {
234 JPy_INCREF(pyReturnArg);
235 return pyReturnArg;
236 }
237 }
238 #endif
239 return JPy_FromJObjectWithType(jenv, jReturnValue, returnType);
240 }
241
242 /**
243 * Invoke a method. We have already ensured that the Python arguments and expected Java parameters match.
244 */
245 PyObject* JMethod_InvokeMethod(JNIEnv* jenv, JPy_JMethod* method, PyObject* pyArgs, int isVarArgsArray)
246 {
247 jvalue* jArgs;
248 JPy_ArgDisposer* argDisposers;
249 PyObject* returnValue;
250 JPy_JType* declaringClass;
251 JPy_JType* returnType;
252 jclass classRef;
253
254 //printf("JMethod_InvokeMethod 1: typeCode=%c\n", typeCode);
255 if (JMethod_CreateJArgs(jenv, method, pyArgs, &jArgs, &argDisposers, isVarArgsArray) < 0) {
256 return NULL;
257 }
258
259 //printf("JMethod_InvokeMethod 2: typeCode=%c\n", typeCode);
260
261 returnType = method->returnDescriptor->type;
262 returnValue = NULL;
263 declaringClass = method->declaringClass;
264 classRef = declaringClass->classRef;
265
266 if (method->isStatic) {
267
268 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "JMethod_InvokeMethod: calling static Java method %s#%s\n", declaringClass->javaName, JPy_AS_UTF8(method->name));
269
270 if (returnType == JPy_JVoid) {
271 Py_BEGIN_ALLOW_THREADS;
272 (*jenv)->CallStaticVoidMethodA(jenv, classRef, method->mid, jArgs);
273 Py_END_ALLOW_THREADS
274 JPy_ON_JAVA_EXCEPTION_GOTO(error);
275 returnValue = JPy_FROM_JVOID();
276 } else if (returnType == JPy_JBoolean) {
277 jboolean v;
278 Py_BEGIN_ALLOW_THREADS;
279 v = (*jenv)->CallStaticBooleanMethodA(jenv, classRef, method->mid, jArgs);
280 Py_END_ALLOW_THREADS;
281 JPy_ON_JAVA_EXCEPTION_GOTO(error);
282 returnValue = JPy_FROM_JBOOLEAN(v);
283 } else if (returnType == JPy_JChar) {
284 jchar v;
285 Py_BEGIN_ALLOW_THREADS;
286 v = (*jenv)->CallStaticCharMethodA(jenv, classRef, method->mid, jArgs);
287 Py_END_ALLOW_THREADS;
288 JPy_ON_JAVA_EXCEPTION_GOTO(error);
289 returnValue = JPy_FROM_JCHAR(v);
290 } else if (returnType == JPy_JByte) {
291 jbyte v;
292 Py_BEGIN_ALLOW_THREADS;
293 v = (*jenv)->CallStaticByteMethodA(jenv, classRef, method->mid, jArgs);
294 Py_END_ALLOW_THREADS;
295 JPy_ON_JAVA_EXCEPTION_GOTO(error);
296 returnValue = JPy_FROM_JBYTE(v);
297 } else if (returnType == JPy_JShort) {
298 jshort v;
299 Py_BEGIN_ALLOW_THREADS;
300 v = (*jenv)->CallStaticShortMethodA(jenv, classRef, method->mid, jArgs);
301 Py_END_ALLOW_THREADS;
302 JPy_ON_JAVA_EXCEPTION_GOTO(error);
303 returnValue = JPy_FROM_JSHORT(v);
304 } else if (returnType == JPy_JInt) {
305 jint v;
306 Py_BEGIN_ALLOW_THREADS;
307 v = (*jenv)->CallStaticIntMethodA(jenv, classRef, method->mid, jArgs);
308 Py_END_ALLOW_THREADS;
309 JPy_ON_JAVA_EXCEPTION_GOTO(error);
310 returnValue = JPy_FROM_JINT(v);
311 } else if (returnType == JPy_JLong) {
312 jlong v;
313 Py_BEGIN_ALLOW_THREADS;
314 v = (*jenv)->CallStaticLongMethodA(jenv, classRef, method->mid, jArgs);
315 Py_END_ALLOW_THREADS;
316 JPy_ON_JAVA_EXCEPTION_GOTO(error);
317 returnValue = JPy_FROM_JLONG(v);
318 } else if (returnType == JPy_JFloat) {
319 jfloat v;
320 Py_BEGIN_ALLOW_THREADS;
321 v = (*jenv)->CallStaticFloatMethodA(jenv, classRef, method->mid, jArgs);
322 Py_END_ALLOW_THREADS;
323 JPy_ON_JAVA_EXCEPTION_GOTO(error);
324 returnValue = JPy_FROM_JFLOAT(v);
325 } else if (returnType == JPy_JDouble) {
326 jdouble v;
327 Py_BEGIN_ALLOW_THREADS;
328 v = (*jenv)->CallStaticDoubleMethodA(jenv, classRef, method->mid, jArgs);
329 Py_END_ALLOW_THREADS;
330 JPy_ON_JAVA_EXCEPTION_GOTO(error);
331 returnValue = JPy_FROM_JDOUBLE(v);
332 } else if (returnType == JPy_JString) {
333 jstring v;
334 Py_BEGIN_ALLOW_THREADS;
335 v = (*jenv)->CallStaticObjectMethodA(jenv, classRef, method->mid, jArgs);
336 Py_END_ALLOW_THREADS;
337 JPy_ON_JAVA_EXCEPTION_GOTO(error);
338 returnValue = JPy_FromJString(jenv, v);
339 JPy_DELETE_LOCAL_REF(v);
340 } else {
341 jobject v;
342 Py_BEGIN_ALLOW_THREADS;
343 v = (*jenv)->CallStaticObjectMethodA(jenv, classRef, method->mid, jArgs);
344 Py_END_ALLOW_THREADS;
345 JPy_ON_JAVA_EXCEPTION_GOTO(error);
346 returnValue = JMethod_FromJObject(jenv, method, pyArgs, jArgs, 0, returnType, v);
347 JPy_DELETE_LOCAL_REF(v);
348 }
349
350 } else {
351 jobject objectRef;
352 PyObject* self;
353
354 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "JMethod_InvokeMethod: calling Java method %s#%s\n", declaringClass->javaName, JPy_AS_UTF8(method->name));
355
356 self = PyTuple_GetItem(pyArgs, 0);
357 // Note it is already ensured that self is a JPy_JObj*
358 objectRef = ((JPy_JObj*) self)->objectRef;
359
360 if (returnType == JPy_JVoid) {
361 Py_BEGIN_ALLOW_THREADS;
362 (*jenv)->CallVoidMethodA(jenv, objectRef, method->mid, jArgs);
363 Py_END_ALLOW_THREADS;
364 JPy_ON_JAVA_EXCEPTION_GOTO(error);
365 returnValue = JPy_FROM_JVOID();
366 } else if (returnType == JPy_JBoolean) {
367 jboolean v;
368 Py_BEGIN_ALLOW_THREADS;
369 v = (*jenv)->CallBooleanMethodA(jenv, objectRef, method->mid, jArgs);
370 Py_END_ALLOW_THREADS;
371 JPy_ON_JAVA_EXCEPTION_GOTO(error);
372 returnValue = JPy_FROM_JBOOLEAN(v);
373 } else if (returnType == JPy_JChar) {
374 jchar v;
375 Py_BEGIN_ALLOW_THREADS;
376 v = (*jenv)->CallCharMethodA(jenv, objectRef, method->mid, jArgs);
377 Py_END_ALLOW_THREADS;
378 JPy_ON_JAVA_EXCEPTION_GOTO(error);
379 returnValue = JPy_FROM_JCHAR(v);
380 } else if (returnType == JPy_JByte) {
381 jbyte v;
382 Py_BEGIN_ALLOW_THREADS;
383 v = (*jenv)->CallByteMethodA(jenv, objectRef, method->mid, jArgs);
384 Py_END_ALLOW_THREADS;
385 JPy_ON_JAVA_EXCEPTION_GOTO(error);
386 returnValue = JPy_FROM_JBYTE(v);
387 } else if (returnType == JPy_JShort) {
388 jshort v;
389 Py_BEGIN_ALLOW_THREADS;
390 v = (*jenv)->CallShortMethodA(jenv, objectRef, method->mid, jArgs);
391 Py_END_ALLOW_THREADS;
392 JPy_ON_JAVA_EXCEPTION_GOTO(error);
393 returnValue = JPy_FROM_JSHORT(v);
394 } else if (returnType == JPy_JInt) {
395 jint v;
396 Py_BEGIN_ALLOW_THREADS;
397 v = (*jenv)->CallIntMethodA(jenv, objectRef, method->mid, jArgs);
398 Py_END_ALLOW_THREADS;
399 JPy_ON_JAVA_EXCEPTION_GOTO(error);
400 returnValue = JPy_FROM_JINT(v);
401 } else if (returnType == JPy_JLong) {
402 jlong v;
403 Py_BEGIN_ALLOW_THREADS;
404 v = (*jenv)->CallLongMethodA(jenv, objectRef, method->mid, jArgs);
405 Py_END_ALLOW_THREADS;
406 JPy_ON_JAVA_EXCEPTION_GOTO(error);
407 returnValue = JPy_FROM_JLONG(v);
408 } else if (returnType == JPy_JFloat) {
409 jfloat v;
410 Py_BEGIN_ALLOW_THREADS;
411 v = (*jenv)->CallFloatMethodA(jenv, objectRef, method->mid, jArgs);
412 Py_END_ALLOW_THREADS;
413 JPy_ON_JAVA_EXCEPTION_GOTO(error);
414 returnValue = JPy_FROM_JFLOAT(v);
415 } else if (returnType == JPy_JDouble) {
416 jdouble v;
417 Py_BEGIN_ALLOW_THREADS;
418 v = (*jenv)->CallDoubleMethodA(jenv, objectRef, method->mid, jArgs);
419 Py_END_ALLOW_THREADS;
420 JPy_ON_JAVA_EXCEPTION_GOTO(error);
421 returnValue = JPy_FROM_JDOUBLE(v);
422 } else if (returnType == JPy_JString) {
423 jstring v;
424 Py_BEGIN_ALLOW_THREADS;
425 v = (*jenv)->CallObjectMethodA(jenv, objectRef, method->mid, jArgs);
426 Py_END_ALLOW_THREADS;
427 JPy_ON_JAVA_EXCEPTION_GOTO(error);
428 returnValue = JPy_FromJString(jenv, v);
429 JPy_DELETE_LOCAL_REF(v);
430 } else {
431 jobject v;
432 Py_BEGIN_ALLOW_THREADS;
433 v = (*jenv)->CallObjectMethodA(jenv, objectRef, method->mid, jArgs);
434 Py_END_ALLOW_THREADS;
435 JPy_ON_JAVA_EXCEPTION_GOTO(error);
436 returnValue = JMethod_FromJObject(jenv, method, pyArgs, jArgs, 1, returnType, v);
437 JPy_DELETE_LOCAL_REF(v);
438 }
439 }
440
441 error:
442 if (jArgs != NULL) {
443 JMethod_DisposeJArgs(jenv, method->paramCount, jArgs, argDisposers);
444 }
445
446 return returnValue;
447 }
448
449 int JMethod_CreateJArgs(JNIEnv* jenv, JPy_JMethod* method, PyObject* pyArgs, jvalue** argValuesRet, JPy_ArgDisposer** argDisposersRet, int isVarArgsArray)
450 {
451 JPy_ParamDescriptor* paramDescriptor;
452 Py_ssize_t i, i0, iLast;
453 Py_ssize_t argCount;
454 PyObject* pyArg;
455 jvalue* jValue;
456 jvalue* jValues;
457 JPy_ArgDisposer* argDisposer;
458 JPy_ArgDisposer* argDisposers;
459
460 if (method->paramCount == 0) {
461 *argValuesRet = NULL;
462 *argDisposersRet = NULL;
463 return 0;
464 }
465
466 argCount = PyTuple_Size(pyArgs);
467
468 if (method->isVarArgs) {
469 // need to know if we expect a self parameter
470 i0 = method->isStatic ? 0 : 1;
471 iLast = method->isStatic ? method->paramCount - 1 : method->paramCount;
472 } else {
473 i0 = argCount - method->paramCount;
474 if (!(i0 == 0 || i0 == 1)) {
475 PyErr_SetString(PyExc_RuntimeError, "internal error");
476 return -1;
477 }
478 iLast = argCount;
479 }
480
481 jValues = PyMem_New(jvalue, method->paramCount);
482 if (jValues == NULL) {
483 PyErr_NoMemory();
484 return -1;
485 }
486
487 argDisposers = PyMem_New(JPy_ArgDisposer, method->paramCount);
488 if (argDisposers == NULL) {
489 PyMem_Del(jValues);
490 PyErr_NoMemory();
491 return -1;
492 }
493
494 paramDescriptor = method->paramDescriptors;
495 jValue = jValues;
496 argDisposer = argDisposers;
497 for (i = i0; i < iLast; i++) {
498 pyArg = PyTuple_GetItem(pyArgs, i);
499 jValue->l = 0;
500 argDisposer->data = NULL;
501 argDisposer->DisposeArg = NULL;
502 if (paramDescriptor->ConvertPyArg(jenv, paramDescriptor, pyArg, jValue, argDisposer) < 0) {
503 PyMem_Del(jValues);
504 PyMem_Del(argDisposers);
505 return -1;
506 }
507 paramDescriptor++;
508 jValue++;
509 argDisposer++;
510 }
511 if (method->isVarArgs) {
512 if (isVarArgsArray) {
513 pyArg = PyTuple_GetItem(pyArgs, i);
514 jValue->l = 0;
515 argDisposer->data = NULL;
516 argDisposer->DisposeArg = NULL;
517 if (paramDescriptor->ConvertPyArg(jenv, paramDescriptor, pyArg, jValue, argDisposer) < 0) {
518 PyMem_Del(jValues);
519 PyMem_Del(argDisposers);
520 return -1;
521 }
522 } else {
523 jValue->l = 0;
524 argDisposer->data = NULL;
525 argDisposer->DisposeArg = NULL;
526 if (paramDescriptor->ConvertVarArgPyArg(jenv, paramDescriptor, pyArgs, i, jValue, argDisposer) < 0) {
527 PyMem_Del(jValues);
528 PyMem_Del(argDisposers);
529 return -1;
530 }
531 }
532 }
533
534 *argValuesRet = jValues;
535 *argDisposersRet = argDisposers;
536 return 0;
537 }
538
539 void JMethod_DisposeJArgs(JNIEnv* jenv, int paramCount, jvalue* jArgs, JPy_ArgDisposer* argDisposers)
540 {
541 jvalue* jArg;
542 JPy_ArgDisposer* argDisposer;
543 int index;
544
545 jArg = jArgs;
546 argDisposer = argDisposers;
547
548 for (index = 0; index < paramCount; index++) {
549 if (argDisposer->DisposeArg != NULL) {
550 argDisposer->DisposeArg(jenv, jArg, argDisposer->data);
551 }
552 jArg++;
553 argDisposer++;
554 }
555
556 PyMem_Del(jArgs);
557 PyMem_Del(argDisposers);
558 }
559
560
561 PyObject* JMethod_repr(JPy_JMethod* self)
562 {
563 const char* name = JPy_AS_UTF8(self->name);
564 return JPy_FROM_FORMAT("%s(name='%s', param_count=%d, is_static=%d, mid=%p)",
565 ((PyObject*)self)->ob_type->tp_name,
566 name,
567 self->paramCount,
568 self->isStatic,
569 self->mid);
570 }
571
572 PyObject* JMethod_str(JPy_JMethod* self)
573 {
574 JPy_INCREF(self->name);
575 return self->name;
576 }
577
578
579 static PyMemberDef JMethod_members[] =
580 {
581 {"name", T_OBJECT_EX, offsetof(JPy_JMethod, name), READONLY, "Method name"},
582 {"param_count", T_INT, offsetof(JPy_JMethod, paramCount), READONLY, "Number of method parameters"},
583 {"is_static", T_BOOL, offsetof(JPy_JMethod, isStatic), READONLY, "Tests if this is a static method"},
584 {NULL} /* Sentinel */
585 };
586
587 #define JMethod_CHECK_PARAMETER_INDEX(self, index) \
588 if (index < 0 || index >= self->paramCount) { \
589 PyErr_SetString(PyExc_IndexError, "invalid parameter index"); \
590 return NULL; \
591 }
592
593
594 PyObject* JMethod_get_param_type(JPy_JMethod* self, PyObject* args)
595 {
596 PyObject* type;
597 int index;
598 if (!PyArg_ParseTuple(args, "i:get_param_type", &index)) {
599 return NULL;
600 }
601 JMethod_CHECK_PARAMETER_INDEX(self, index);
602 type = (PyObject*) self->paramDescriptors[index].type;
603 JPy_INCREF(type);
604 return type;
605 }
606
607 PyObject* JMethod_is_param_mutable(JPy_JMethod* self, PyObject* args)
608 {
609 int index;
610 int value;
611 if (!PyArg_ParseTuple(args, "i:is_param_mutable", &index)) {
612 return NULL;
613 }
614 JMethod_CHECK_PARAMETER_INDEX(self, index);
615 value = self->paramDescriptors[index].isMutable;
616 return PyBool_FromLong(value);
617 }
618
619 PyObject* JMethod_set_param_mutable(JPy_JMethod* self, PyObject* args)
620 {
621 int index;
622 int value;
623 if (!PyArg_ParseTuple(args, "ip:set_param_mutable", &index, &value)) {
624 return NULL;
625 }
626 JMethod_CHECK_PARAMETER_INDEX(self, index);
627 self->paramDescriptors[index].isMutable = value;
628 Py_RETURN_NONE;
629 }
630
631 PyObject* JMethod_is_param_output(JPy_JMethod* self, PyObject* args)
632 {
633 int index = 0;
634 int value = 0;
635 if (!PyArg_ParseTuple(args, "i:is_param_output", &index)) {
636 return NULL;
637 }
638 JMethod_CHECK_PARAMETER_INDEX(self, index);
639 value = self->paramDescriptors[index].isOutput;
640 return PyBool_FromLong(value);
641 }
642
643 PyObject* JMethod_set_param_output(JPy_JMethod* self, PyObject* args)
644 {
645 int index = 0;
646 int value = 0;
647 if (!PyArg_ParseTuple(args, "ip:set_param_output", &index, &value)) {
648 return NULL;
649 }
650 JMethod_CHECK_PARAMETER_INDEX(self, index);
651 self->paramDescriptors[index].isOutput = value;
652 Py_RETURN_NONE;
653 }
654
655 PyObject* JMethod_is_param_return(JPy_JMethod* self, PyObject* args)
656 {
657 int index = 0;
658 int value = 0;
659 if (!PyArg_ParseTuple(args, "i:is_param_return", &index)) {
660 return NULL;
661 }
662 JMethod_CHECK_PARAMETER_INDEX(self, index);
663 value = self->paramDescriptors[index].isReturn;
664 return PyBool_FromLong(value);
665 }
666
667 PyObject* JMethod_set_param_return(JPy_JMethod* self, PyObject* args)
668 {
669 int index = 0;
670 int value = 0;
671 if (!PyArg_ParseTuple(args, "ip:set_param_return", &index, &value)) {
672 return NULL;
673 }
674 JMethod_CHECK_PARAMETER_INDEX(self, index);
675 self->paramDescriptors[index].isReturn = value;
676 if (value) {
677 self->returnDescriptor->paramIndex = index;
678 }
679 Py_RETURN_NONE;
680 }
681
682
683 static PyMethodDef JMethod_methods[] =
684 {
685 {"get_param_type", (PyCFunction) JMethod_get_param_type, METH_VARARGS, "Gets the type of the parameter given by index"},
686 {"is_param_mutable", (PyCFunction) JMethod_is_param_mutable, METH_VARARGS, "Tests if the method parameter given by index is mutable"},
687 {"is_param_output", (PyCFunction) JMethod_is_param_output, METH_VARARGS, "Tests if the method parameter given by index is a mere output value (and not read from)"},
688 {"is_param_return", (PyCFunction) JMethod_is_param_return, METH_VARARGS, "Tests if the method parameter given by index is the return value"},
689 {"set_param_mutable", (PyCFunction) JMethod_set_param_mutable, METH_VARARGS, "Sets whether the method parameter given by index is mutable"},
690 {"set_param_output", (PyCFunction) JMethod_set_param_output, METH_VARARGS, "Sets whether the method parameter given by index is a mere output value (and not read from)"},
691 {"set_param_return", (PyCFunction) JMethod_set_param_return, METH_VARARGS, "Sets whether the method parameter given by index is the return value"},
692 {NULL} /* Sentinel */
693 };
694
695 /**
696 * Implements the BeamPy_JObjectType class singleton.
697 */
698 PyTypeObject JMethod_Type = {
699 PyVarObject_HEAD_INIT(NULL, 0)
700 "jpy.JMethod", /* tp_name */
701 sizeof (JPy_JMethod), /* tp_basicsize */
702 0, /* tp_itemsize */
703 (destructor)JMethod_dealloc, /* tp_dealloc */
704 0, /* tp_print */
705 NULL, /* tp_getattr */
706 NULL, /* tp_setattr */
707 NULL, /* tp_reserved */
708 (reprfunc)JMethod_repr, /* tp_repr */
709 NULL, /* tp_as_number */
710 NULL, /* tp_as_sequence */
711 NULL, /* tp_as_mapping */
712 NULL, /* tp_hash */
713 NULL, /* tp_call */
714 (reprfunc)JMethod_str, /* tp_str */
715 NULL, /* tp_getattro */
716 NULL, /* tp_setattro */
717 NULL, /* tp_as_buffer */
718 Py_TPFLAGS_DEFAULT, /* tp_flags */
719 "Java Method Wrapper", /* tp_doc */
720 NULL, /* tp_traverse */
721 NULL, /* tp_clear */
722 NULL, /* tp_richcompare */
723 0, /* tp_weaklistoffset */
724 NULL, /* tp_iter */
725 NULL, /* tp_iternext */
726 JMethod_methods, /* tp_methods */
727 JMethod_members, /* tp_members */
728 NULL, /* tp_getset */
729 NULL, /* tp_base */
730 NULL, /* tp_dict */
731 NULL, /* tp_descr_get */
732 NULL, /* tp_descr_set */
733 0, /* tp_dictoffset */
734 NULL, /* tp_init */
735 NULL, /* tp_alloc */
736 NULL, /* tp_new */
737 };
738
739 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
740 // JOverloadedMethod
741
742 typedef struct JPy_MethodFindResult
743 {
744 JPy_JMethod* method;
745 int matchValue;
746 int matchCount;
747 int isVarArgsArray;
748 }
749 JPy_MethodFindResult;
750
751 JPy_JMethod* JOverloadedMethod_FindMethod0(JNIEnv* jenv, JPy_JOverloadedMethod* overloadedMethod, PyObject* pyArgs, JPy_MethodFindResult* result)
752 {
753 Py_ssize_t overloadCount;
754 Py_ssize_t argCount;
755 int matchCount;
756 int matchValue;
757 int matchValueMax;
758 JPy_JMethod* currMethod;
759 JPy_JMethod* bestMethod;
760 int i;
761 int currentIsVarArgsArray;
762 int bestIsVarArgsArray;
763
764 result->method = NULL;
765 result->matchValue = 0;
766 result->matchCount = 0;
767
768 overloadCount = PyList_Size(overloadedMethod->methodList);
769 if (overloadCount <= 0) {
770 PyErr_SetString(PyExc_RuntimeError, "internal error: invalid overloadedMethod->methodList");
771 return NULL;
772 }
773
774 argCount = PyTuple_Size(pyArgs);
775 matchCount = 0;
776 matchValueMax = -1;
777 bestMethod = NULL;
778 bestIsVarArgsArray = 0;
779
780 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JOverloadedMethod_FindMethod0: method '%s#%s': overloadCount=%d, argCount=%d\n",
781 overloadedMethod->declaringClass->javaName, JPy_AS_UTF8(overloadedMethod->name), overloadCount, argCount);
782
783 for (i = 0; i < overloadCount; i++) {
784 // borrowed ref, no need to replace with PyList_GetItemRef() because the list won't be changed concurrently
785 currMethod = (JPy_JMethod*) PyList_GetItem(overloadedMethod->methodList, i);
786
787 if (currMethod->isVarArgs && matchValueMax > 0 && !bestMethod->isVarArgs) {
788 // we should not process varargs if we have already found a suitable fixed arity method
789 break;
790 }
791
792 matchValue = JMethod_MatchPyArgs(jenv, overloadedMethod->declaringClass, currMethod, argCount, pyArgs, &currentIsVarArgsArray);
793
794 JPy_DIAG_PRINT(JPy_DIAG_F_METH, "JOverloadedMethod_FindMethod0: methodList[%d]: paramCount=%d, matchValue=%d, isVarArgs=%d\n", i,
795 currMethod->paramCount, matchValue, currMethod->isVarArgs);
796
797 if (matchValue > 0) {
798 if (matchValue > matchValueMax) {
799 matchValueMax = matchValue;
800 bestMethod = currMethod;
801 matchCount = 1;
802 bestIsVarArgsArray = currentIsVarArgsArray;
803 } else if (matchValue == matchValueMax) {
804 matchCount++;
805 }
806 if (!currMethod->isVarArgs && (matchValue >= 100 * argCount)) {
807 // we can't get any better (if so, we have an internal problem)
808 break;
809 }
810 }
811 }
812
813 if (bestMethod == NULL) {
814 matchValueMax = 0;
815 matchCount = 0;
816 bestIsVarArgsArray = 0;
817 }
818
819 result->method = bestMethod;
820 result->matchValue = matchValueMax;
821 result->matchCount = matchCount;
822 result->isVarArgsArray = bestIsVarArgsArray;
823
824 return bestMethod;
825 }
826
827 JPy_JMethod* JOverloadedMethod_FindMethod(JNIEnv* jenv, JPy_JOverloadedMethod* overloadedMethod, PyObject* pyArgs, jboolean visitSuperClass, int *isVarArgsArray)
828 {
829 JPy_JOverloadedMethod* currentOM;
830 JPy_MethodFindResult result;
831 JPy_MethodFindResult bestResult;
832 JPy_JType* superClass;
833 PyObject* superOM;
834 int argCount;
835
836 argCount = PyTuple_Size(pyArgs);
837
838 if ((JPy_DiagFlags & JPy_DIAG_F_METH) != 0) {
839 int i;
840 printf("JOverloadedMethod_FindMethod: argCount=%d, visitSuperClass=%d\n", argCount, visitSuperClass);
841 for (i = 0; i < argCount; i++) {
842 PyObject* pyArg = PyTuple_GetItem(pyArgs, i);
843 printf("\tPy_TYPE(pyArgs[%d])->tp_name = %s\n", i, Py_TYPE(pyArg)->tp_name);
844 }
845 }
846
847 bestResult.method = NULL;
848 bestResult.matchValue = 0;
849 bestResult.matchCount = 0;
850 bestResult.isVarArgsArray = 0;
851
852 currentOM = overloadedMethod;
853 while (1) {
854 if (JOverloadedMethod_FindMethod0(jenv, currentOM, pyArgs, &result) < 0) {
855 // oops, error
856 return NULL;
857 }
858 if (result.method != NULL) {
859 // in the case where we have a match count that is perfect, but more than one match; the super class might
860 // have a better match count, because varargs can have fewer arguments than actual parameters.
861 if (result.matchValue >= 100 * argCount && result.matchCount == 1) {
862 // We can't get any better.
863 *isVarArgsArray = result.isVarArgsArray;
864 return result.method;
865 } else if (result.matchValue > 0 && result.matchValue > bestResult.matchValue) {
866 // We may have better matching methods overloads in the super class (if any)
867 bestResult = result;
868 }
869 }
870
871 if (visitSuperClass) {
872 superClass = currentOM->declaringClass->superType;
873 if (superClass != NULL) {
874 superOM = JType_GetOverloadedMethod(jenv, superClass, currentOM->name, JNI_TRUE);
875 } else {
876 superOM = Py_None;
877 }
878 } else {
879 superOM = Py_None;
880 }
881
882 if (superOM == NULL) {
883 // oops, error
884 return NULL;
885 } else if (superOM == Py_None) {
886 // no overloaded methods found in super class, so return best result found so far
887 if (bestResult.method == NULL) {
888 PyErr_SetString(PyExc_RuntimeError, "no matching Java method overloads found");
889 return NULL;
890 } else if (bestResult.matchCount > 1) {
891 PyErr_SetString(PyExc_RuntimeError, "ambiguous Java method call, too many matching method overloads found");
892 return NULL;
893 } else {
894 *isVarArgsArray = bestResult.isVarArgsArray;
895 return bestResult.method;
896 }
897 } else {
898 // Continue trying with overloads from super type
899 currentOM = (JPy_JOverloadedMethod*) superOM;
900 }
901 }
902
903 // Should never come here
904 PyErr_SetString(PyExc_RuntimeError, "internal error");
905 return NULL;
906 }
907
908 JPy_JOverloadedMethod* JOverloadedMethod_New(JPy_JType* declaringClass, PyObject* name, JPy_JMethod* method)
909 {
910 PyTypeObject* methodType = &JOverloadedMethod_Type;
911 JPy_JOverloadedMethod* overloadedMethod;
912
913 overloadedMethod = (JPy_JOverloadedMethod*) methodType->tp_alloc(methodType, 0);
914 overloadedMethod->declaringClass = declaringClass;
915 overloadedMethod->name = name;
916 overloadedMethod->methodList = PyList_New(0);
917
918 JPy_INCREF((PyObject*) overloadedMethod->declaringClass);
919 JPy_INCREF((PyObject*) overloadedMethod->name);
920 JPy_INCREF((PyObject*) overloadedMethod);
921
922 JOverloadedMethod_AddMethod(overloadedMethod, method);
923
924 return overloadedMethod;
925 }
926
927 int JOverloadedMethod_AddMethod(JPy_JOverloadedMethod* overloadedMethod, JPy_JMethod* method)
928 {
929 Py_ssize_t destinationIndex = -1;
930
931 if (!method->isVarArgs) {
932 Py_ssize_t ii;
933 // we need to insert this before the first varargs method
934 Py_ssize_t size = PyList_Size(overloadedMethod->methodList);
935 for (ii = 0; ii < size; ii++) {
936 // borrowed ref, no need to replace with PyList_GetItemRef() because the list won't be changed concurrently
937 PyObject *check = PyList_GetItem(overloadedMethod->methodList, ii);
938 if (((JPy_JMethod *) check)->isVarArgs) {
939 // this is the first varargs method, so we should go before it
940 destinationIndex = ii;
941 break;
942 }
943 }
944 }
945
946 if (destinationIndex >= 0) {
947 return PyList_Insert(overloadedMethod->methodList, destinationIndex, (PyObject *) method);
948 } else {
949 return PyList_Append(overloadedMethod->methodList, (PyObject *) method);
950 }
951 }
952
953 /**
954 * The 'JOverloadedMethod' type's tp_dealloc slot.
955 */
956 void JOverloadedMethod_dealloc(JPy_JOverloadedMethod* self)
957 {
958 JPy_DECREF((PyObject*) self->declaringClass);
959 JPy_DECREF((PyObject*) self->name);
960 JPy_DECREF((PyObject*) self->methodList);
961 Py_TYPE(self)->tp_free((PyObject*) self);
962 }
963
964 PyObject* JOverloadedMethod_call_internal(JNIEnv* jenv, JPy_JOverloadedMethod* self, PyObject *args, PyObject *kw)
965 {
966 JPy_JMethod* method;
967 int isVarArgsArray;
968
969 method = JOverloadedMethod_FindMethod(jenv, self, args, JNI_TRUE, &isVarArgsArray);
970 if (method == NULL) {
971 return NULL;
972 }
973
974 return JMethod_InvokeMethod(jenv, method, args, isVarArgsArray);
975 }
976
977 /**
978 * The 'JOverloadedMethod' type's tp_call slot. Makes instances of the 'JOverloadedMethod' type callable.
979 */
980 PyObject* JOverloadedMethod_call(JPy_JOverloadedMethod* self, PyObject *args, PyObject *kw)
981 {
982 JPy_FRAME(PyObject*, NULL, JOverloadedMethod_call_internal(jenv, self, args, kw), 16)
983 }
984
985 /**
986 * The 'JOverloadedMethod' type's tp_repr slot.
987 */
988 PyObject* JOverloadedMethod_repr(JPy_JOverloadedMethod* self)
989 {
990 const char* className = self->declaringClass->javaName;
991 const char* name = JPy_AS_UTF8(self->name);
992 int methodCount = PyList_Size(self->methodList);
993 return JPy_FROM_FORMAT("%s(class='%s', name='%s', methodCount=%d)",
994 ((PyObject*)self)->ob_type->tp_name,
995 className,
996 name,
997 methodCount);
998 }
999
1000 static PyMemberDef JOverloadedMethod_members[] =
1001 {
1002 {"decl_class", T_OBJECT_EX, offsetof(JPy_JOverloadedMethod, declaringClass), READONLY, "Declaring Java class"},
1003 {"name", T_OBJECT_EX, offsetof(JPy_JOverloadedMethod, name), READONLY, "Overloaded method name"},
1004 {"methods", T_OBJECT_EX, offsetof(JPy_JOverloadedMethod, methodList), READONLY, "List of methods"},
1005 {NULL} /* Sentinel */
1006 };
1007
1008 /**
1009 * The 'JOverloadedMethod' type's tp_str slot.
1010 */
1011 PyObject* JOverloadedMethod_str(JPy_JOverloadedMethod* self)
1012 {
1013 JPy_INCREF(self->name);
1014 return self->name;
1015 }
1016
1017 PyTypeObject JOverloadedMethod_Type = {
1018 PyVarObject_HEAD_INIT(NULL, 0)
1019 "jpy.JOverloadedMethod", /* tp_name */
1020 sizeof (JPy_JOverloadedMethod), /* tp_basicsize */
1021 0, /* tp_itemsize */
1022 (destructor)JOverloadedMethod_dealloc, /* tp_dealloc */
1023 0, /* tp_print */
1024 NULL, /* tp_getattr */
1025 NULL, /* tp_setattr */
1026 NULL, /* tp_reserved */
1027 (reprfunc)JOverloadedMethod_repr, /* tp_repr */
1028 NULL, /* tp_as_number */
1029 NULL, /* tp_as_sequence */
1030 NULL, /* tp_as_mapping */
1031 NULL, /* tp_hash */
1032 (ternaryfunc)JOverloadedMethod_call, /* tp_call */
1033 (reprfunc)JOverloadedMethod_str, /* tp_str */
1034 NULL, /* tp_getattro */
1035 NULL, /* tp_setattro */
1036 NULL, /* tp_as_buffer */
1037 Py_TPFLAGS_DEFAULT, /* tp_flags */
1038 "Java Overloaded Method", /* tp_doc */
1039 NULL, /* tp_traverse */
1040 NULL, /* tp_clear */
1041 NULL, /* tp_richcompare */
1042 0, /* tp_weaklistoffset */
1043 NULL, /* tp_iter */
1044 NULL, /* tp_iternext */
1045 NULL, /* tp_methods */
1046 JOverloadedMethod_members, /* tp_members */
1047 NULL, /* tp_getset */
1048 NULL, /* tp_base */
1049 NULL, /* tp_dict */
1050 NULL, /* tp_descr_get */
1051 NULL, /* tp_descr_set */
1052 0, /* tp_dictoffset */
1053 NULL, /* tp_init */
1054 NULL, /* tp_alloc */
1055 NULL, /* tp_new */
1056 };