forked from pythonnet/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathClassBase.cs
More file actions
926 lines (811 loc) · 35.1 KB
/
Copy pathClassBase.cs
File metadata and controls
926 lines (811 loc) · 35.1 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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Python.Runtime.Slots;
namespace Python.Runtime
{
/// <summary>
/// Base class for Python types that reflect managed types / classes.
/// Concrete subclasses include ClassObject and DelegateObject. This
/// class provides common attributes and common machinery for doing
/// class initialization (initialization of the class __dict__). The
/// concrete subclasses provide slot implementations appropriate for
/// each variety of reflected type.
/// </summary>
[Serializable]
internal class ClassBase : ManagedType, IDeserializationCallback
{
[NonSerialized]
internal List<string> dotNetMembers = new();
internal Indexer? indexer;
internal readonly Dictionary<int, MethodObject> richcompare = new();
internal MaybeType type;
// How a member is used from Python, so a missing-attribute hint only suggests members
// usable the same way as the one the user most likely meant. Nested types count as
// callable: `Foo.Bar()` may be an attempted constructor call. A single exposed name can
// carry both flags when e.g. a method and a property collapse to the same snake_case name.
[Flags]
private enum SuggestionKind
{
Callable = 1,
Data = 2,
}
// Reflecting over a managed type's full member set (with FlattenHierarchy) plus the
// snake_case conversion is expensive, and the result never changes for a given type.
// Compute it once per type.
private static readonly ConcurrentDictionary<Type, Dictionary<string, SuggestionKind>> _candidateNameCache = new();
// A miss-heavy workload probes the same missing names over and over (e.g. a per-bar
// getattr(self, "_optional", None) on a .NET-derived object, or a mistyped enum value).
// Memoize the fully-built " Did you mean: ...?" hint (empty when there is nothing to
// suggest) per (type, missing-name) so repeats are a dictionary lookup instead of an
// O(members) reflection + similarity scan on every miss.
private static readonly ConcurrentDictionary<(Type Type, string Name), string> _suggestionCache = new();
internal ClassBase(Type tp)
{
if (tp is null) throw new ArgumentNullException(nameof(type));
indexer = null;
type = tp;
}
internal virtual bool CanSubclass()
{
return !type.Value.IsEnum;
}
public readonly static Dictionary<string, int> CilToPyOpMap = new Dictionary<string, int>
{
["op_Equality"] = Runtime.Py_EQ,
["op_Inequality"] = Runtime.Py_NE,
["op_LessThanOrEqual"] = Runtime.Py_LE,
["op_GreaterThanOrEqual"] = Runtime.Py_GE,
["op_LessThan"] = Runtime.Py_LT,
["op_GreaterThan"] = Runtime.Py_GT,
};
/// <summary>
/// Default implementation of [] semantics for reflected types.
/// </summary>
public virtual NewReference type_subscript(BorrowedReference idx)
{
Type[]? types = Runtime.PythonArgsToTypeArray(idx);
if (types == null)
{
return Exceptions.RaiseTypeError("type(s) expected");
}
if (!type.Valid)
{
return Exceptions.RaiseTypeError(type.DeletedMessage);
}
Type? target = GenericUtil.GenericForType(type.Value, types.Length);
if (target != null)
{
Type t;
try
{
// MakeGenericType can throw ArgumentException
t = target.MakeGenericType(types);
}
catch (ArgumentException e)
{
return Exceptions.RaiseTypeError(e.Message);
}
var c = ClassManager.GetClass(t);
return new NewReference(c);
}
return Exceptions.RaiseTypeError($"{type.Value.Namespace}.{type.Name} does not accept {types.Length} generic parameters");
}
/// <summary>
/// Standard comparison implementation for instances of reflected types.
/// </summary>
public static NewReference tp_richcompare(BorrowedReference ob, BorrowedReference other, int op)
{
CLRObject co1;
object co2Inst;
BorrowedReference tp = Runtime.PyObject_TYPE(ob);
var cls = (ClassBase)GetManagedObject(tp)!;
// C# operator methods take precedence over IComparable.
// We first check if there's a comparison operator by looking up the richcompare table,
// otherwise fallback to checking if an IComparable interface is handled.
if (cls.richcompare.TryGetValue(op, out var methodObject))
{
// Wrap the `other` argument of a binary comparison operator in a PyTuple.
using var args = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(args.Borrow(), 0, other);
return methodObject.Invoke(ob, args.Borrow(), null);
}
switch (op)
{
case Runtime.Py_EQ:
case Runtime.Py_NE:
BorrowedReference pytrue = Runtime.PyTrue;
BorrowedReference pyfalse = Runtime.PyFalse;
// swap true and false for NE
if (op != Runtime.Py_EQ)
{
pytrue = Runtime.PyFalse;
pyfalse = Runtime.PyTrue;
}
if (ob == other)
{
return new NewReference(pytrue);
}
if (!TryGetSecondCompareOperandInstance(ob, other, out co1, out co2Inst))
{
return new NewReference(pyfalse);
}
if (Equals(co1.inst, co2Inst))
{
return new NewReference(pytrue);
}
return new NewReference(pyfalse);
case Runtime.Py_LT:
case Runtime.Py_LE:
case Runtime.Py_GT:
case Runtime.Py_GE:
if (!TryGetSecondCompareOperandInstance(ob, other, out co1, out co2Inst))
{
return Exceptions.RaiseTypeError("Cannot get managed object");
}
var co1Comp = co1.inst as IComparable;
if (co1Comp == null)
{
Type co1Type = co1.GetType();
return Exceptions.RaiseTypeError($"Cannot convert object of type {co1Type} to IComparable");
}
try
{
int cmp = co1Comp.CompareTo(co2Inst);
return new NewReference(GetComparisonResult(op, cmp));
}
catch (ArgumentException e)
{
return Exceptions.RaiseTypeError(e.Message);
}
default:
return new NewReference(Runtime.PyNotImplemented);
}
}
/// <summary>
/// Get the result of a comparison operation based on the operator and the comparison result.
/// </summary>
/// <remarks>
/// This method is used to determine the result of a comparison operation, excluding equality and inequality.
/// </remarks>
protected static BorrowedReference GetComparisonResult(int op, int comparisonResult)
{
BorrowedReference pyCmp;
if (comparisonResult < 0)
{
if (op == Runtime.Py_LT || op == Runtime.Py_LE)
{
pyCmp = Runtime.PyTrue;
}
else
{
pyCmp = Runtime.PyFalse;
}
}
else if (comparisonResult == 0)
{
if (op == Runtime.Py_LE || op == Runtime.Py_GE)
{
pyCmp = Runtime.PyTrue;
}
else
{
pyCmp = Runtime.PyFalse;
}
}
else
{
if (op == Runtime.Py_GE || op == Runtime.Py_GT)
{
pyCmp = Runtime.PyTrue;
}
else
{
pyCmp = Runtime.PyFalse;
}
}
return pyCmp;
}
protected static bool TryGetSecondCompareOperandInstance(BorrowedReference left, BorrowedReference right, out CLRObject co1, out object co2Inst)
{
co2Inst = null;
co1 = (CLRObject)GetManagedObject(left)!;
if (co1 == null)
{
return false;
}
var co2 = GetManagedObject(right) as CLRObject;
// The object comparing against is not a managed object. It could still be a Python object
// that can be compared against (e.g. comparing against a Python string)
if (co2 == null)
{
if (right != null)
{
using var pyCo2 = new PyObject(right);
if (Converter.ToManagedValue(pyCo2, typeof(object), out var result, false))
{
co2Inst = result;
return true;
}
}
return false;
}
co2Inst = co2.inst;
return true;
}
/// <summary>
/// Standard iteration support for instances of reflected types. This
/// allows natural iteration over objects that either are IEnumerable
/// or themselves support IEnumerator directly.
/// </summary>
static NewReference tp_iter_impl(BorrowedReference ob)
{
var co = GetManagedObject(ob) as CLRObject;
if (co == null)
{
return Exceptions.RaiseTypeError("invalid object");
}
var e = co.inst as IEnumerable;
IEnumerator? o;
if (e != null)
{
o = e.GetEnumerator();
}
else
{
o = co.inst as IEnumerator;
if (o == null)
{
return Exceptions.RaiseTypeError("iteration over non-sequence");
}
}
var elemType = typeof(object);
var iterType = co.inst.GetType();
foreach(var ifc in iterType.GetInterfaces())
{
if (ifc.IsGenericType)
{
var genTypeDef = ifc.GetGenericTypeDefinition();
if (genTypeDef == typeof(IEnumerable<>) || genTypeDef == typeof(IEnumerator<>))
{
elemType = ifc.GetGenericArguments()[0];
break;
}
}
}
return new Iterator(o, elemType).Alloc();
}
/// <summary>
/// Standard __hash__ implementation for instances of reflected types.
/// </summary>
public static nint tp_hash(BorrowedReference ob)
{
var co = GetManagedObject(ob) as CLRObject;
if (co == null)
{
Exceptions.RaiseTypeError("unhashable type");
return 0;
}
return co.inst.GetHashCode();
}
/// <summary>
/// Standard __str__ implementation for instances of reflected types.
/// </summary>
public static NewReference tp_str(BorrowedReference ob)
{
var co = GetManagedObject(ob) as CLRObject;
if (co == null)
{
return Exceptions.RaiseTypeError("invalid object");
}
try
{
return Runtime.PyString_FromString(co.inst.ToString());
}
catch (Exception e)
{
if (e.InnerException != null)
{
e = e.InnerException;
}
Exceptions.SetError(e);
return default;
}
}
public static NewReference tp_repr(BorrowedReference ob)
{
var co = GetManagedObject(ob) as CLRObject;
if (co == null)
{
return Exceptions.RaiseTypeError("invalid object");
}
try
{
//if __repr__ is defined, use it
var instType = co.inst.GetType();
System.Reflection.MethodInfo methodInfo = instType.GetMethod("__repr__");
if (methodInfo != null && methodInfo.IsPublic)
{
var reprString = methodInfo.Invoke(co.inst, null) as string;
return reprString is null ? new NewReference(Runtime.PyNone) : Runtime.PyString_FromString(reprString);
}
//otherwise use the standard object.__repr__(inst)
using var args = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(args.Borrow(), 0, ob);
using var reprFunc = Runtime.PyObject_GetAttr(Runtime.PyBaseObjectType, PyIdentifier.__repr__);
return Runtime.PyObject_Call(reprFunc.Borrow(), args.Borrow(), null);
}
catch (Exception e)
{
if (e.InnerException != null)
{
e = e.InnerException;
}
Exceptions.SetError(e);
return default;
}
}
/// <summary>
/// Standard dealloc implementation for instances of reflected types.
/// </summary>
public static void tp_dealloc(NewReference lastRef)
{
Runtime.PyObject_GC_UnTrack(lastRef.Borrow());
CallClear(lastRef.Borrow());
DecrefTypeAndFree(lastRef.Steal());
}
public static int tp_clear(BorrowedReference ob)
{
var weakrefs = Runtime.PyObject_GetWeakRefList(ob);
if (weakrefs != null)
{
Runtime.PyObject_ClearWeakRefs(ob);
}
TryFreeGCHandle(ob);
int baseClearResult = BaseUnmanagedClear(ob);
if (baseClearResult != 0)
{
return baseClearResult;
}
ClearObjectDict(ob);
return 0;
}
static readonly HashSet<IntPtr> ClearVisited = new();
internal static unsafe int BaseUnmanagedClear(BorrowedReference ob)
{
var type = Runtime.PyObject_TYPE(ob);
var unmanagedBase = GetUnmanagedBaseType(type);
var clearPtr = Util.ReadIntPtr(unmanagedBase, TypeOffset.tp_clear);
if (clearPtr == IntPtr.Zero)
{
return 0;
}
var clear = (delegate* unmanaged[Cdecl]<BorrowedReference, int>)clearPtr;
if (clearPtr == TypeManager.subtype_clear)
{
var addr = ob.DangerousGetAddress();
if (!ClearVisited.Add(addr))
return 0;
int res = clear(ob);
ClearVisited.Remove(addr);
return res;
}
else
{
return clear(ob);
}
}
protected override Dictionary<string, object?> OnSave(BorrowedReference ob)
{
var context = base.OnSave(ob) ?? new();
context["impl"] = this;
return context;
}
protected override void OnLoad(BorrowedReference ob, Dictionary<string, object?>? context)
{
base.OnLoad(ob, context);
var gcHandle = GCHandle.Alloc(this);
SetGCHandle(ob, gcHandle);
}
/// <summary>
/// Implements __getitem__ for reflected classes and value types.
/// </summary>
static NewReference mp_subscript_impl(BorrowedReference ob, BorrowedReference idx)
{
BorrowedReference tp = Runtime.PyObject_TYPE(ob);
var cls = (ClassBase)GetManagedObject(tp)!;
if (cls.indexer == null || !cls.indexer.CanGet)
{
Exceptions.SetError(Exceptions.TypeError, "unindexable object");
return default;
}
// Arg may be a tuple in the case of an indexer with multiple
// parameters. If so, use it directly, else make a new tuple
// with the index arg (method binders expect arg tuples).
if (!Runtime.PyTuple_Check(idx))
{
using var argTuple = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(argTuple.Borrow(), 0, idx);
return cls.indexer.GetItem(ob, argTuple.Borrow());
}
else
{
return cls.indexer.GetItem(ob, idx);
}
}
/// <summary>
/// Implements __setitem__ for reflected classes and value types.
/// </summary>
static int mp_ass_subscript_impl(BorrowedReference ob, BorrowedReference idx, BorrowedReference v)
{
BorrowedReference tp = Runtime.PyObject_TYPE(ob);
var cls = (ClassBase)GetManagedObject(tp)!;
if (cls.indexer == null || !cls.indexer.CanSet)
{
Exceptions.SetError(Exceptions.TypeError, "object doesn't support item assignment");
return -1;
}
// Arg may be a tuple in the case of an indexer with multiple
// parameters. If so, use it directly, else make a new tuple
// with the index arg (method binders expect arg tuples).
NewReference argsTuple = default;
if (!Runtime.PyTuple_Check(idx))
{
argsTuple = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(argsTuple.Borrow(), 0, idx);
idx = argsTuple.Borrow();
}
// Get the args passed in.
var i = Runtime.PyTuple_Size(idx);
using var defaultArgs = cls.indexer.GetDefaultArgs(idx);
var numOfDefaultArgs = Runtime.PyTuple_Size(defaultArgs.Borrow());
var temp = i + numOfDefaultArgs;
using var real = Runtime.PyTuple_New(temp + 1);
for (var n = 0; n < i; n++)
{
BorrowedReference item = Runtime.PyTuple_GetItem(idx, n);
Runtime.PyTuple_SetItem(real.Borrow(), n, item);
}
argsTuple.Dispose();
// Add Default Args if needed
for (var n = 0; n < numOfDefaultArgs; n++)
{
BorrowedReference item = Runtime.PyTuple_GetItem(defaultArgs.Borrow(), n);
Runtime.PyTuple_SetItem(real.Borrow(), n + i, item);
}
i = temp;
// Add value to argument list
Runtime.PyTuple_SetItem(real.Borrow(), i, v);
cls.indexer.SetItem(ob, real.Borrow());
if (Exceptions.ErrorOccurred())
{
return -1;
}
return 0;
}
static NewReference tp_call_impl(BorrowedReference ob, BorrowedReference args, BorrowedReference kw)
{
BorrowedReference tp = Runtime.PyObject_TYPE(ob);
var self = (ClassBase)GetManagedObject(tp)!;
if (!self.type.Valid)
{
return Exceptions.RaiseTypeError(self.type.DeletedMessage);
}
Type type = self.type.Value;
var calls = GetCallImplementations(type).ToList();
Debug.Assert(calls.Count > 0);
var callBinder = new MethodBinder();
foreach (MethodInfo call in calls)
{
callBinder.AddMethod(call, true);
}
return callBinder.Invoke(ob, args, kw);
}
static IEnumerable<MethodInfo> GetCallImplementations(Type type)
=> type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.Name == "__call__");
public virtual void InitializeSlots(BorrowedReference pyType, SlotsHolder slotsHolder)
{
if (!this.type.Valid) return;
if (GetCallImplementations(this.type.Value).Any())
{
TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.tp_call, new Interop.BBB_N(tp_call_impl), slotsHolder);
}
if (indexer is not null)
{
if (indexer.CanGet)
{
TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.mp_subscript, new Interop.BB_N(mp_subscript_impl), slotsHolder);
}
if (indexer.CanSet)
{
TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.mp_ass_subscript, new Interop.BBB_I32(mp_ass_subscript_impl), slotsHolder);
}
}
if (typeof(IEnumerable).IsAssignableFrom(type.Value)
|| typeof(IEnumerator).IsAssignableFrom(type.Value))
{
TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.tp_iter, new Interop.B_N(tp_iter_impl), slotsHolder);
}
if (MpLengthSlot.CanAssign(type.Value))
{
TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.mp_length, new Interop.B_P(MpLengthSlot.impl), slotsHolder);
}
}
public virtual bool HasCustomNew() => this.GetType().GetMethod("tp_new") is not null;
public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
{
if (this.HasCustomNew())
// initialization must be done in tp_new
return true;
return base.Init(obj, args, kw);
}
protected virtual void OnDeserialization(object sender)
{
this.dotNetMembers = new List<string>();
}
void IDeserializationCallback.OnDeserialization(object sender) => this.OnDeserialization(sender);
/// <summary>
/// If an <c>AttributeError</c> is currently set as the result of a missing
/// attribute lookup on a .NET object, rewrites its message to append a list
/// of similarly-named members of the managed type (a "Did you mean ...?" hint).
/// This is a no-op when there is no AttributeError set, when the object is not
/// a CLR object, or when no similarly-named members exist. It only runs on the
/// exceptional (miss) path, so the reflection cost is not on the hot path.
/// </summary>
internal static void AppendAttributeErrorSuggestions(BorrowedReference ob, BorrowedReference key)
{
if (!Exceptions.ExceptionMatches(Exceptions.AttributeError))
{
return;
}
var name = Runtime.GetManagedString(key);
if (string.IsNullOrEmpty(name))
{
return;
}
var hint = GetSuggestionHint(ob, name);
if (hint.Length == 0)
{
return;
}
// Keep the original AttributeError message and append our hint to it.
Runtime.PyErr_Fetch(out var errType, out var errValue, out var errTraceback);
try
{
var baseMessage = GetErrorMessage(errValue.BorrowNullable(), name);
Exceptions.SetError(Exceptions.AttributeError, baseMessage + hint);
}
finally
{
errType.Dispose();
errValue.Dispose();
errTraceback.Dispose();
}
}
/// <summary>
/// Builds the full message for an <c>AttributeError</c> raised for a missing
/// attribute on a .NET object, including any "Did you mean ...?" hint. Used by
/// the miss-only <c>__getattr__</c> hook installed on reflected types (see
/// <see cref="AttributeErrorHint"/>), where the original error has already been
/// cleared, so the base message is reconstructed here.
/// </summary>
internal static string BuildMissingAttributeMessage(PyObject self, string name)
{
try
{
if (TryGetSuggestionTarget(self.Reference, out var type, out var staticScope))
{
// Match CPython's wording: instances say "'T' object ...", whereas an access
// on the type object itself (a missing static member or enum value) says
// "type object 'T' ...".
var baseMessage = staticScope
? $"type object '{type!.Name}' has no attribute '{name}'"
: $"'{PythonTypeName(self)}' object has no attribute '{name}'";
return baseMessage + GetSuggestionHint(type!, name);
}
}
catch
{
// never let message building turn into a different exception
}
return $"'{PythonTypeName(self)}' object has no attribute '{name}'";
}
private static string PythonTypeName(PyObject self)
{
try
{
using var pyType = self.GetPythonType();
return pyType.Name;
}
catch
{
return "object";
}
}
/// <summary>
/// Resolves the managed <see cref="Type"/> whose members should be searched for a
/// missing-attribute suggestion, and whether the access was on the type object itself
/// (<paramref name="staticScope"/> = true, for static members and enum values) rather
/// than on an instance. Returns false for objects that are not reflected .NET types.
/// </summary>
private static bool TryGetSuggestionTarget(BorrowedReference ob, out Type? type, out bool staticScope)
{
type = null;
staticScope = false;
switch (GetManagedObject(ob))
{
case CLRObject clrObj when clrObj.inst is not null:
type = clrObj.inst.GetType();
return true;
case ClassBase classBase when classBase.type.Valid:
type = classBase.type.Value;
staticScope = true;
return true;
default:
return false;
}
}
/// <summary>
/// Returns " Did you mean: 'x', 'y'?" listing similarly-named members of the
/// managed object, or an empty string when there is nothing to suggest. Dunder
/// names are skipped: they are probed internally by CPython (e.g. __iter__,
/// __len__) and are never user-facing typos worth helping with.
/// </summary>
private static string GetSuggestionHint(BorrowedReference ob, string name)
{
if (!TryGetSuggestionTarget(ob, out var type, out _))
{
return string.Empty;
}
return GetSuggestionHint(type!, name);
}
private static string GetSuggestionHint(Type type, string name)
{
if (string.IsNullOrEmpty(name) || name.StartsWith("__", StringComparison.Ordinal))
{
return string.Empty;
}
// The hint is built and cached once per (type, name); on a repeated miss this is just
// a dictionary lookup. An empty string means there was nothing to suggest. The
// suggested names use the same convention Python exposes members under (see
// GetCandidateMemberNames), so they are independent of whether the access was on
// an instance or the type object.
return _suggestionCache.GetOrAdd((type, name),
static key => ComputeSimilarMemberNames(key.Type, key.Name));
}
private static string GetErrorMessage(BorrowedReference value, string fallbackName)
{
if (value != null)
{
using var str = Runtime.PyObject_Str(value);
if (!str.IsNull())
{
var managed = Runtime.GetManagedString(str.Borrow());
if (!string.IsNullOrEmpty(managed))
{
return managed;
}
}
// PyObject_Str may itself have failed; do not let that error leak out.
Exceptions.Clear();
}
return $"object has no attribute '{fallbackName}'";
}
// The candidate member names of a type, cached so the reflection and name conversion
// happen at most once per type rather than on every attribute miss. Instance and static
// members are both included, and each is converted with ToSnakeCaseMemberName so the
// suggestion matches the name Python exposes it under: methods become lower_snake, enum
// values, consts and static-readonly members become UPPER_SNAKE (e.g. DayOfWeek.SUNDAY,
// Math.PI, String.EMPTY), and nested types keep their original name. Each name is tagged
// with how it is used from Python so suggestions can be filtered by usage.
private static Dictionary<string, SuggestionKind> GetCandidateMemberNames(Type type)
{
return _candidateNameCache.GetOrAdd(type, static t =>
{
var names = new Dictionary<string, SuggestionKind>(StringComparer.Ordinal);
var members = t.GetMembers(BindingFlags.Public | BindingFlags.Instance
| BindingFlags.Static | BindingFlags.FlattenHierarchy);
foreach (var member in members)
{
// Skip property/event accessors, operators and other special-name methods,
// as well as compiler-generated members; none are accessible by name.
if (member is MethodBase { IsSpecialName: true })
{
continue;
}
if (member.Name.Length == 0 || member.Name[0] == '<')
{
continue;
}
var (name, kind) = ToSnakeCaseMemberName(member);
names[name] = names.TryGetValue(name, out var existing) ? existing | kind : kind;
}
return names;
});
}
// Builds the " Did you mean: 'x', 'y'?" hint for a missing attribute, or an empty
// string when no member is similar enough to suggest. The result is cached in
// _suggestionCache, so this runs at most once per (type, missing-name).
//
// Jaro-Winkler (prefix-favoring) keeps suffix-extended targets that an edit-distance
// cutoff rejects (InteractiveBrokers -> INTERACTIVE_BROKERS_BROKERAGE); gated
// containment covers fragment lookups outside its match window ('cash' -> 'set_cash').
private static string ComputeSimilarMemberNames(Type type, string name)
{
const int MaxSuggestions = 5;
// In evaluation over real member sets, intended targets scored >= 0.90 and noise <= 0.85.
const double SimilarityThreshold = 0.87;
var scored = new List<(string Name, double Score, SuggestionKind Kind)>();
foreach (var candidate in GetCandidateMemberNames(type))
{
var score = Util.JaroWinklerSimilarity(name, candidate.Key);
if (score < SimilarityThreshold)
{
// Coverage scoring ranks containment matches below any similarity match.
score = IsMeaningfulContainment(name, candidate.Key)
? (double)Math.Min(name.Length, candidate.Key.Length) / Math.Max(name.Length, candidate.Key.Length)
: 0;
}
if (score > 0)
{
scored.Add((candidate.Key, score, candidate.Value));
}
}
if (scored.Count == 0)
{
return string.Empty;
}
var ordered = scored
.OrderByDescending(t => t.Score)
.ThenBy(t => t.Name, StringComparer.OrdinalIgnoreCase)
.ToList();
// Only suggest members used the same way as the closest match, the member the user
// most likely meant: a miss that best matches a method or nested type gets callable
// suggestions only, one that best matches a field/property gets data suggestions
// only. Mixing the two would suggest names the caller cannot use the same way.
var kind = ordered[0].Kind;
var suggestions = ordered
.Where(t => (t.Kind & kind) != 0)
.Take(MaxSuggestions)
.Select(t => $"'{t.Name}'");
return " Did you mean: " + string.Join(", ", suggestions) + "?";
}
// Converts a member to the name Python exposes it under, tagged with how it is used.
// The field/property overloads of ToSnakeCase are used so const and static-readonly
// members are converted to UPPER_CASE. Nested types keep their original name verbatim:
// ClassManager registers no snake_case alias for them, and they count as callable since
// accessing one may be an attempted constructor call.
private static (string Name, SuggestionKind Kind) ToSnakeCaseMemberName(MemberInfo member)
{
return member switch
{
Type => (member.Name, SuggestionKind.Callable),
MethodBase => (member.Name.ToSnakeCase(), SuggestionKind.Callable),
FieldInfo fieldInfo => (fieldInfo.ToSnakeCase(), SuggestionKind.Data),
PropertyInfo propertyInfo => (propertyInfo.ToSnakeCase(), SuggestionKind.Data),
_ => (member.Name.ToSnakeCase(), SuggestionKind.Data),
};
}
// Without the length gates every 1-2 letter member is a substring of any long
// missed name and floods the suggestion list.
private static bool IsMeaningfulContainment(string name, string candidate)
{
const int MinFragmentLength = 3;
if (name.Length >= MinFragmentLength
&& candidate.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
return candidate.Length >= MinFragmentLength
&& 2 * candidate.Length >= name.Length
&& name.IndexOf(candidate, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}