forked from amos402/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethodobject.cs
More file actions
751 lines (682 loc) · 24.4 KB
/
methodobject.cs
File metadata and controls
751 lines (682 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
using Python.Runtime.Binder;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Linq;
namespace Python.Runtime
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr PyCFunction(IntPtr self, IntPtr args);
enum METH
{
METH_VARARGS = 0x0001,
METH_KEYWORDS = 0x0002,
METH_NOARGS = 0x0004,
METH_O = 0x0008,
METH_CLASS = 0x0010,
METH_STATIC = 0x0020,
METH_COEXIST = 0x0040,
METH_FASTCALL = 0x0080
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct PyMethodDef
{
public IntPtr ml_name; /* The name of the built-in function/method */
public IntPtr ml_meth; /* The C function that implements it */
public int ml_flags; /* Combination of METH_xxx flags, which mostly
describe the args expected by the C func */
public IntPtr ml_doc; /* The __doc__ attribute, or NULL */
}
/// <summary>
/// Implements a Python type that represents a CLR method. Method objects
/// support a subscript syntax [] to allow explicit overload selection.
/// </summary>
/// <remarks>
/// TODO: ForbidPythonThreadsAttribute per method info
/// </remarks>
internal class MethodObject : ExtensionType
{
internal MethodInfo[] info;
internal string name;
internal MethodBinding unbound;
internal MethodBinder binder;
internal bool is_static = false;
internal IntPtr doc;
internal Type type;
public MethodObject(Type type, string name, MethodInfo[] info)
{
_MethodObject(type, name, info);
}
public MethodObject(Type type, string name, MethodInfo[] info, bool allow_threads)
{
_MethodObject(type, name, info);
binder.allow_threads = allow_threads;
}
private void _MethodObject(Type type, string name, MethodInfo[] info)
{
this.type = type;
this.name = name;
this.info = info;
binder = new MethodBinder();
foreach (MethodInfo item in info)
{
binder.AddMethod(item);
if (item.IsStatic)
{
this.is_static = true;
}
}
}
public virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw)
{
return Invoke(inst, args, kw, null);
}
public virtual IntPtr Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase info)
{
return binder.Invoke(target, args, kw, info, this.info);
}
/// <summary>
/// Helper to get docstrings from reflected method / param info.
/// </summary>
internal IntPtr GetDocString()
{
if (doc != IntPtr.Zero)
{
return doc;
}
var str = "";
Type marker = typeof(DocStringAttribute);
MethodBase[] methods = binder.GetMethods();
foreach (MethodBase method in methods)
{
if (str.Length > 0)
{
str += Environment.NewLine;
}
var attrs = (Attribute[])method.GetCustomAttributes(marker, false);
if (attrs.Length == 0)
{
str += method.ToString();
}
else
{
var attr = (DocStringAttribute)attrs[0];
str += attr.DocString;
}
}
doc = Runtime.PyString_FromString(str);
return doc;
}
/// <summary>
/// This is a little tricky: a class can actually have a static method
/// and instance methods all with the same name. That makes it tough
/// to support calling a method 'unbound' (passing the instance as the
/// first argument), because in this case we can't know whether to call
/// the instance method unbound or call the static method.
/// </summary>
/// <remarks>
/// The rule we is that if there are both instance and static methods
/// with the same name, then we always call the static method. So this
/// method returns true if any of the methods that are represented by
/// the descriptor are static methods (called by MethodBinding).
/// </remarks>
internal bool IsStatic()
{
return is_static;
}
/// <summary>
/// Descriptor __getattribute__ implementation.
/// </summary>
public static IntPtr tp_getattro(IntPtr ob, IntPtr key)
{
var self = (MethodObject)GetManagedObject(ob);
if (!Runtime.PyString_Check(key))
{
return Exceptions.RaiseTypeError("string expected");
}
string name = Runtime.GetManagedString(key);
if (name == "__doc__")
{
IntPtr doc = self.GetDocString();
Runtime.XIncref(doc);
return doc;
}
return Runtime.PyObject_GenericGetAttr(ob, key);
}
/// <summary>
/// Descriptor __get__ implementation. Accessing a CLR method returns
/// a "bound" method similar to a Python bound method.
/// </summary>
public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp)
{
var self = (MethodObject)GetManagedObject(ds);
MethodBinding binding;
// If the method is accessed through its type (rather than via
// an instance) we return an 'unbound' MethodBinding that will
// cached for future accesses through the type.
if (ob == IntPtr.Zero)
{
if (self.unbound == null)
{
self.unbound = new MethodBinding(self, IntPtr.Zero, tp);
}
binding = self.unbound;
Runtime.XIncref(binding.pyHandle);
;
return binding.pyHandle;
}
if (Runtime.PyObject_IsInstance(ob, tp) < 1)
{
return Exceptions.RaiseTypeError("invalid argument");
}
// If the object this descriptor is being called with is a subclass of the type
// this descriptor was defined on then it will be because the base class method
// is being called via super(Derived, self).method(...).
// In which case create a MethodBinding bound to the base class.
var obj = GetManagedObject(ob) as CLRObject;
if (obj != null
&& obj.inst.GetType() != self.type
&& obj.inst is IPythonDerivedType
&& self.type.IsInstanceOfType(obj.inst))
{
ClassBase basecls = ClassManager.GetClass(self.type);
binding = new MethodBinding(self, ob, basecls.pyHandle);
return binding.pyHandle;
}
binding = new MethodBinding(self, ob, tp);
return binding.pyHandle;
}
/// <summary>
/// Descriptor __repr__ implementation.
/// </summary>
public static IntPtr tp_repr(IntPtr ob)
{
var self = (MethodObject)GetManagedObject(ob);
return Runtime.PyString_FromString($"<method '{self.name}'>");
}
/// <summary>
/// Descriptor dealloc implementation.
/// </summary>
public new static void tp_dealloc(IntPtr ob)
{
var self = (MethodObject)GetManagedObject(ob);
Runtime.XDecref(self.doc);
if (self.unbound != null)
{
Runtime.XDecref(self.unbound.pyHandle);
}
ExtensionType.FinalizeObject(self);
}
}
internal static class BoundMethodPool
{
private const int MaxNumFree = 256;
private static DelegateBoundMethodObject[] _cache = new DelegateBoundMethodObject[MaxNumFree];
private static DelegateBoundMethodObject _freeObj = null;
private static int _numFree = 0;
public static DelegateBoundMethodObject NewBoundMethod(IntPtr target, DelegateCallableObject caller)
{
DelegateBoundMethodObject boundMethod;
System.Diagnostics.Debug.Assert(_cache[0] == null);
if (_numFree != 0)
{
boundMethod = _freeObj;
boundMethod.Init(target, caller);
_freeObj = _cache[--_numFree];
return boundMethod;
}
boundMethod = new DelegateBoundMethodObject(target, caller);
return boundMethod;
}
public static bool Recycle(DelegateBoundMethodObject method)
{
System.Diagnostics.Debug.Assert(_cache[0] == null);
method.Release();
if (_numFree >= MaxNumFree)
{
return false;
}
_cache[_numFree++] = _freeObj;
_freeObj = method;
return true;
}
public static void ClearFreeList()
{
ExtensionType.FinalizeObject(_freeObj);
_freeObj = null;
for (int i = 1; i < _numFree; i++)
{
if (_cache[i] != null)
{
ExtensionType.FinalizeObject(_cache[i]);
_cache[i] = null;
}
}
}
}
class DelegateCallableObject
{
public string Name { get; private set; }
protected Dictionary<int, List<Method.IMethodCaller>> _callers;
public DelegateCallableObject(string name)
{
Name = name;
_callers = new Dictionary<int, List<Method.IMethodCaller>>();
}
public bool Empty()
{
return _callers.Count == 0;
}
public Method.IMethodCaller AddMethod(Type boundType, MethodInfo mi)
{
Type[] paramTypes = mi.GetParameters()
.Select(T => T.ParameterType).ToArray();
Type funcType = CreateDelegateType(boundType,
mi.ReturnType, paramTypes);
var caller = (Method.IMethodCaller)Activator.CreateInstance(funcType, mi);
#if AOT
DynamicGenericHelper.RecordDynamicType(funcType);
#endif
List<Method.IMethodCaller> callers;
int paramCount = paramTypes.Length;
if (!_callers.TryGetValue(paramCount, out callers))
{
callers = new List<Method.IMethodCaller>();
_callers[paramCount] = callers;
}
callers.Add(caller);
return caller;
}
public Method.IMethodCaller AddStaticMethod(MethodInfo mi)
{
Type[] paramTypes = mi.GetParameters()
.Select(T => T.ParameterType).ToArray();
Type funcType = CreateStaticDelegateType(mi.ReturnType, paramTypes);
var caller = (Method.IMethodCaller)Activator.CreateInstance(funcType, mi);
#if AOT
DynamicGenericHelper.RecordDynamicType(funcType);
#endif
List<Method.IMethodCaller> callers;
int paramCount = paramTypes.Length;
if (!_callers.TryGetValue(paramCount, out callers))
{
callers = new List<Method.IMethodCaller>();
_callers[paramCount] = callers;
}
callers.Add(caller);
return caller;
}
public virtual IntPtr PyCall(IntPtr self, IntPtr args)
{
int argc = Runtime.PyTuple_Size(args);
// TODO: params array, default params
List<Method.IMethodCaller> callerList;
if (!_callers.TryGetValue(argc, out callerList))
{
return Exceptions.RaiseTypeError("No match found for given type params");
}
if (Exceptions.ErrorOccurred())
{
Runtime.PyErr_Print();
Console.WriteLine();
}
bool needValidate = callerList.Count > 1;
foreach (var caller in callerList)
{
int start = 0;
if (!caller.IsStatic && self == IntPtr.Zero)
{
self = Runtime.PyTuple_GetItem(args, 0);
if (!caller.CheckSelf(self))
{
// Should be invalid for next caller
break;
}
start = 1;
}
if (needValidate && !caller.Check(args, start))
{
continue;
}
try
{
IntPtr res = caller.Call(self, args, start);
#if DEBUG
if (res != IntPtr.Zero && Runtime.PyErr_Occurred() != 0)
{
DebugUtil.debug("");
}
#endif
return res;
}
catch (ConvertException)
{
return IntPtr.Zero;
}
catch (Exception e)
{
Exceptions.SetError(e);
return IntPtr.Zero;
}
}
return Exceptions.RaiseTypeError("No match found for given type params");
}
internal static Type CreateDelegateType(Type type, Type returnType, Type[] paramTypes)
{
Type[] types;
Type func;
if (returnType == typeof(void))
{
types = new Type[paramTypes.Length + 1];
types[0] = type;
paramTypes.CopyTo(types, 1);
func = Method.ActionCallerCreator.CreateDelgates[paramTypes.Length](types);
}
else
{
types = new Type[paramTypes.Length + 2];
types[0] = type;
paramTypes.CopyTo(types, 1);
types[paramTypes.Length + 1] = returnType;
func = Method.FuncCallerCreator.CreateDelgates[paramTypes.Length](types);
}
return func;
}
internal static Type CreateStaticDelegateType(Type returnType, Type[] paramTypes)
{
Type[] types;
Type func;
if (returnType == typeof(void))
{
func = Method.ActionStaticCallerCreator.CreateDelgates[paramTypes.Length](paramTypes);
}
else
{
types = new Type[paramTypes.Length + 1];
paramTypes.CopyTo(types, 0);
types[paramTypes.Length] = returnType;
func = Method.FuncStaticCallerCreator.CreateDelgates[paramTypes.Length](types);
}
return func;
}
}
class DelegateCallableOperatorObject : DelegateCallableObject
{
private IntPtr _args;
public DelegateCallableOperatorObject(string name) : base(name)
{
_args = Runtime.PyTuple_New(2);
}
public override IntPtr PyCall(IntPtr self, IntPtr args)
{
int argc = Runtime.PyTuple_Size(args);
bool useCacheTuple;
if (argc == 1)
{
if (self == IntPtr.Zero)
{
return Exceptions.RaiseTypeError("No match found for given type params");
}
useCacheTuple = true;
IntPtr other = Runtime.PyTuple_GetItem(args, 0);
Runtime.XIncref(self);
Runtime.XIncref(other);
Runtime.PyTuple_SetItem(_args, 0, self);
Runtime.PyTuple_SetItem(_args, 1, other);
args = _args;
}
else if (argc == 2)
{
useCacheTuple = false;
}
else
{
return Exceptions.RaiseTypeError("Operator method only accept one or two arguments");
}
try
{
return InternalCall(self, args);
}
finally
{
if (useCacheTuple)
{
Runtime.PyTuple_SetItem(_args, 0, IntPtr.Zero);
Runtime.PyTuple_SetItem(_args, 1, IntPtr.Zero);
}
}
}
private IntPtr InternalCall(IntPtr self, IntPtr args)
{
List<Method.IMethodCaller> callerList;
if (!_callers.TryGetValue(2, out callerList))
{
return Exceptions.RaiseTypeError("No match found for given type params");
}
foreach (var caller in callerList)
{
if (!caller.Check(args, 0))
{
continue;
}
try
{
IntPtr res = caller.Call(self, args, 0);
return res;
}
catch (ConvertException)
{
return IntPtr.Zero;
}
catch (Exception e)
{
Exceptions.SetError(e);
return IntPtr.Zero;
}
}
return Exceptions.RaiseTypeError("No match found for given type params");
}
}
static class MethodCreator
{
public static ExtensionType CreateDelegateMethod(Type type, string name, MethodInfo[] info)
{
// TODO : If it can support the GeneriType,
// It seems it's unnecessary for Python to using these incompatible methods,
// thus it can just skip the incompatible methods
if (IsIncompatibleType(type)) return null;
for (int i = 0; i < info.Length; i++)
{
if (!CanCreateStaticBinding(info[i]))
{
return null;
}
}
if (OperatorMethod.IsPyOperatorMethod(name))
{
return CreateOperatorBinder(type, name, info);
}
var caller = new DelegateCallableObject(name);
bool hasGeneric = false;
for (int i = 0; i < info.Length; i++)
{
var mi = info[i];
if (mi.ReturnType.IsPointer)
{
continue;
}
if (mi.GetParameters().Any(T => T.ParameterType.IsPointer))
{
continue;
}
if (mi.IsGenericMethod)
{
hasGeneric = true;
continue;
}
if (mi.IsStatic)
{
caller.AddStaticMethod(mi);
}
else
{
caller.AddMethod(type, mi);
}
}
ExtensionType binder;
if (hasGeneric)
{
binder = new DelegateGenericMethodObject(caller, type, info);
}
else
{
binder = new DelegateMethodObject(caller);
}
return binder;
}
private static ExtensionType CreateOperatorBinder(Type type, string name, MethodInfo[] info)
{
var caller = new DelegateCallableOperatorObject(name);
for (int i = 0; i < info.Length; i++)
{
var mi = info[i];
if (mi.ReturnType.IsPointer)
{
continue;
}
var pi = mi.GetParameters();
System.Diagnostics.Debug.Assert(pi.Length == 2);
if (pi.Any(T => T.ParameterType.IsPointer))
{
continue;
}
System.Diagnostics.Debug.Assert(!mi.IsGenericMethod);
System.Diagnostics.Debug.Assert(mi.IsStatic);
caller.AddStaticMethod(mi);
}
return new DelegateMethodObject(caller);
}
private static bool CanCreateStaticBinding(MethodInfo mi)
{
if (IsIncompatibleType(mi.ReturnType))
{
return false;
}
if (mi.GetParameters().Any(T => IsIncompatibleType(T.ParameterType)))
{
return false;
}
return true;
}
private static bool IsIncompatibleType(Type type)
{
if (type.IsPointer) return true;
if (type.IsByRef) return true;
// TODO: make generic compat
if (type.ContainsGenericParameters) return true;
return false;
}
}
// TODO: static method
internal class DelegateMethodObject : ExtensionType
{
private DelegateCallableObject _caller;
public DelegateCallableObject Caller { get { return _caller; } }
public DelegateMethodObject(DelegateCallableObject caller)
{
_caller = caller;
}
public bool IsCallable()
{
return !_caller.Empty();
}
public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp)
{
var self = (DelegateMethodObject)GetManagedObject(ds);
var boundMethod = BoundMethodPool.NewBoundMethod(ob, self._caller);
return boundMethod.pyHandle;
}
public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw)
{
var self = (DelegateMethodObject)GetManagedObject(ob);
return self._caller.PyCall(ob, args);
}
public static IntPtr tp_repr(IntPtr ob)
{
var self = (DelegateMethodObject)GetManagedObject(ob);
return Runtime.PyString_FromString($"<method '{self._caller.Name}'>");
}
}
internal class DelegateBoundMethodObject : ExtensionType
{
public IntPtr Target { get; private set; }
public DelegateCallableObject Caller { get; private set; }
public DelegateBoundMethodObject(IntPtr target, DelegateCallableObject caller)
{
Init(target, caller);
}
public bool IsCallable()
{
return Caller != null && !Caller.Empty();
}
public void Init(IntPtr target, DelegateCallableObject caller)
{
Runtime.XIncref(target);
Target = target;
Caller = caller;
}
public void Release()
{
Runtime.XDecref(Target);
Target = IntPtr.Zero;
Caller = null;
}
public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw)
{
var self = (DelegateBoundMethodObject)GetManagedObject(ob);
return self.Caller.PyCall(self.Target, args);
}
public new static void tp_dealloc(IntPtr ob)
{
var self = (DelegateBoundMethodObject)GetManagedObject(ob);
if (BoundMethodPool.Recycle(self))
{
Runtime.XIncref(self.pyHandle);
return;
}
FinalizeObject(self);
}
public static IntPtr tp_repr(IntPtr ob)
{
var self = (DelegateBoundMethodObject)GetManagedObject(ob);
string type = self.Target == IntPtr.Zero ? "unbound" : "bound";
string name = self.Caller.Name;
return Runtime.PyString_FromString($"<{type} method '{name}'>");
}
}
internal class DelegateGenericMethodObject : DelegateMethodObject
{
private MethodInfo[] _methods;
private Type _boundType;
public DelegateGenericMethodObject(DelegateCallableObject caller,
Type type, MethodInfo[] infos) : base(caller)
{
_boundType = type;
_methods = infos;
}
public new static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp)
{
var self = (DelegateGenericMethodObject)GetManagedObject(ds);
var binding = new DelegateMethodBinding(self._boundType, ob,
self._methods, self.Caller);
return binding.pyHandle;
}
public new static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw)
{
var self = (DelegateGenericMethodObject)GetManagedObject(ob);
return self.Caller.PyCall(ob, args);
}
}
}