forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonOps.cs
More file actions
4135 lines (3390 loc) · 168 KB
/
PythonOps.cs
File metadata and controls
4135 lines (3390 loc) · 168 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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using System.Numerics;
using Microsoft.Scripting.Ast;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Hosting.Providers;
using Microsoft.Scripting.Hosting.Shell;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler;
using IronPython.Hosting;
using IronPython.Modules;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Types;
namespace IronPython.Runtime.Operations {
internal class ExceptionState {
public Exception Exception { get; set; }
public ExceptionState PrevException { get; set; }
}
/// <summary>
/// Contains functions that are called directly from
/// generated code to perform low-level runtime functionality.
/// </summary>
public static partial class PythonOps {
#region Shared static data
[ThreadStatic]
private static List<object> InfiniteRepr;
// The "current" exception on this thread that will be returned via sys.exc_info()
[ThreadStatic]
internal static ExceptionState CurrentExceptionState;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonTuple EmptyTuple = PythonTuple.EMPTY;
private static readonly Type[] _DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) };
#endregion
public static BigInteger MakeIntegerFromHex(string s) {
return LiteralParser.ParseBigInteger(s, 16);
}
public static PythonDictionary MakeDict(int size) {
return new PythonDictionary(size);
}
public static PythonDictionary MakeEmptyDict() {
return new PythonDictionary(EmptyDictionaryStorage.Instance);
}
/// <summary>
/// Creates a new dictionary extracting the keys and values from the
/// provided data array. Keys/values are adjacent in the array with
/// the value coming first.
/// </summary>
public static PythonDictionary MakeDictFromItems(params object[] data) {
return new PythonDictionary(new CommonDictionaryStorage(data, false));
}
public static PythonDictionary MakeConstantDict(object items) {
return new PythonDictionary((ConstantDictionaryStorage)items);
}
public static object MakeConstantDictStorage(params object[] data) {
return new ConstantDictionaryStorage(new CommonDictionaryStorage(data, false));
}
public static SetCollection MakeSet(params object[] items) {
return new SetCollection(items);
}
public static SetCollection MakeEmptySet() {
return new SetCollection();
}
/// <summary>
/// Creates a new dictionary extracting the keys and values from the
/// provided data array. Keys/values are adjacent in the array with
/// the value coming first.
/// </summary>
public static PythonDictionary MakeHomogeneousDictFromItems(object[] data) {
return new PythonDictionary(new CommonDictionaryStorage(data, true));
}
public static bool IsCallable(CodeContext/*!*/ context, object o) {
// This tells if an object can be called, but does not make a claim about the parameter list.
// In 1.x, we could check for certain interfaces like ICallable*, but those interfaces were deprecated
// in favor of dynamic sites.
// This is difficult to infer because we'd need to simulate the entire callbinder, which can include
// looking for [SpecialName] call methods and checking for a rule from IDynamicMetaObjectProvider. But even that wouldn't
// be complete since sites require the argument list of the call, and we only have the instance here.
// Thus check a dedicated IsCallable operator. This lets each object describe if it's callable.
// Invoke Operator.IsCallable on the object.
return context.LanguageContext.IsCallable(o);
}
public static bool UserObjectIsCallable(CodeContext/*!*/ context, object o) {
object callFunc;
return TryGetBoundAttr(context, o, "__call__", out callFunc) && callFunc != null;
}
public static bool IsTrue(object o) {
return Converter.ConvertToBoolean(o);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
public static List<object> GetReprInfinite() {
if (InfiniteRepr == null) {
InfiniteRepr = new List<object>();
}
return InfiniteRepr;
}
[LightThrowing]
internal static object LookupEncodingError(CodeContext/*!*/ context, string name) {
Dictionary<string, object> errorHandlers = context.LanguageContext.ErrorHandlers;
lock (errorHandlers) {
if (errorHandlers.ContainsKey(name))
return errorHandlers[name];
else
return LightExceptions.Throw(PythonOps.LookupError("unknown error handler name '{0}'", name));
}
}
internal static void RegisterEncodingError(CodeContext/*!*/ context, string name, object handler) {
Dictionary<string, object> errorHandlers = context.LanguageContext.ErrorHandlers;
lock (errorHandlers) {
if (!PythonOps.IsCallable(context, handler))
throw PythonOps.TypeError("handler must be callable");
errorHandlers[name] = handler;
}
}
internal static PythonTuple LookupEncoding(CodeContext/*!*/ context, string encoding) {
if (encoding.IndexOf('\0') != -1) {
throw PythonOps.TypeError("lookup string cannot contain null character");
}
//compute encoding.ToLower().Replace(' ', '-') but ToLower only on ASCII letters
var sb = new StringBuilder(encoding.Length);
foreach (var c in encoding) {
if (c == ' ') sb.Append('-');
else if (c < 0x80) sb.Append(char.ToLowerInvariant(c));
else sb.Append(c);
}
string normalized = sb.ToString();
context.LanguageContext.EnsureEncodings();
List<object> searchFunctions = context.LanguageContext.SearchFunctions;
lock (searchFunctions) {
for (int i = 0; i < searchFunctions.Count; i++) {
object res = PythonCalls.Call(context, searchFunctions[i], normalized);
if (res != null) return (PythonTuple)res;
}
}
throw PythonOps.LookupError("unknown encoding: {0}", encoding);
}
internal static PythonTuple LookupTextEncoding(CodeContext/*!*/ context, string encoding, string alternateCommand) {
var tuple = LookupEncoding(context, encoding);
if (TryGetBoundAttr(tuple, "_is_text_encoding", out object isTextEncodingObj)
&& isTextEncodingObj is bool isTextEncoding && !isTextEncoding) {
throw LookupError("'{0}' is not a text encoding; use {1} to handle arbitrary codecs", encoding, alternateCommand);
}
return tuple;
}
internal static void RegisterEncoding(CodeContext/*!*/ context, object search_function) {
if (!PythonOps.IsCallable(context, search_function))
throw PythonOps.TypeError("search_function must be callable");
List<object> searchFunctions = context.LanguageContext.SearchFunctions;
lock (searchFunctions) {
searchFunctions.Add(search_function);
}
}
internal static string GetPythonTypeName(object obj) {
return PythonTypeOps.GetName(obj);
}
public static string Ascii(CodeContext/*!*/ context, object o) {
return StringOps.AsciiEncode(Repr(context, o));
}
public static string Repr(CodeContext/*!*/ context, object o) {
if (o == null) return "None";
if (o is string s) return StringOps.__repr__(s);
if (o is int) return Int32Ops.__repr__((int)o);
if (o is long) return ((long)o).ToString();
// could be a container object, we need to detect recursion, but only
// for our own built-in types that we're aware of. The user can setup
// infinite recursion in their own class if they want.
if (o is ICodeFormattable f) {
if (o is PythonExceptions.BaseException) {
Debug.Assert(typeof(PythonExceptions.BaseException).IsDefined(typeof(DynamicBaseTypeAttribute), false));
// let it fall through to InvokeUnaryOperator, resolves the following:
// class MyException(Exception):
// def __repr__(self): return "qwerty"
//
// assert repr(MyException) == "qwerty"
} else {
return f.__repr__(context);
}
}
PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "Repr " + o.GetType().FullName);
return PythonContext.InvokeUnaryOperator(context, UnaryOperators.Repr, o) as string;
}
public static List<object> GetAndCheckInfinite(object o) {
List<object> infinite = GetReprInfinite();
foreach (object o2 in infinite) {
if (o == o2) {
return null;
}
}
return infinite;
}
public static string ToString(object o) {
return ToString(DefaultContext.Default, o);
}
public static string ToString(CodeContext/*!*/ context, object o) {
if (o is string x) return x;
if (o is null) return "None";
if (o is double) return DoubleOps.__str__(context, (double)o);
if (o is PythonType dt) return dt.__repr__(DefaultContext.Default);
if (o.GetType() == typeof(object).Assembly.GetType("System.__ComObject")) return ComOps.__repr__(o);
object value = PythonContext.InvokeUnaryOperator(context, UnaryOperators.String, o);
if (!(value is string ret)) {
if (!(value is Extensible<string> es)) {
throw PythonOps.TypeError("expected str, got {0} from __str__", PythonTypeOps.GetName(value));
}
ret = es.Value;
}
return ret;
}
public static string FormatString(CodeContext/*!*/ context, string str, object data) {
return new StringFormatter(context, str, data).Format();
}
public static object Plus(object o) {
object ret;
if (o is int) return o;
else if (o is double) return o;
else if (o is BigInteger) return o;
else if (o is Complex) return o;
else if (o is long) return o;
else if (o is float) return o;
else if (o is bool) return ScriptingRuntimeHelpers.Int32ToObject((bool)o ? 1 : 0);
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__pos__", out ret) &&
ret != NotImplementedType.Value) {
return ret;
}
throw PythonOps.TypeError("bad operand type for unary +");
}
public static object Negate(object o) {
if (o is int) return Int32Ops.Negate((int)o);
else if (o is double) return DoubleOps.Negate((double)o);
else if (o is long) return Int64Ops.Negate((long)o);
else if (o is BigInteger) return BigIntegerOps.Negate((BigInteger)o);
else if (o is Complex) return -(Complex)o;
else if (o is float) return DoubleOps.Negate((float)o);
else if (o is bool) return ScriptingRuntimeHelpers.Int32ToObject((bool)o ? -1 : 0);
object ret;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__neg__", out ret) &&
ret != NotImplementedType.Value) {
return ret;
}
throw PythonOps.TypeError("bad operand type for unary -");
}
public static bool IsSubClass(PythonType/*!*/ c, PythonType/*!*/ typeinfo) {
Assert.NotNull(c, typeinfo);
return typeinfo.__subclasscheck__(c);
}
public static bool IsSubClass(CodeContext/*!*/ context, PythonType c, object typeinfo) {
if (c == null) throw PythonOps.TypeError("issubclass: arg 1 must be a class");
if (typeinfo == null) throw PythonOps.TypeError("issubclass: arg 2 must be a class");
PythonTuple pt = typeinfo as PythonTuple;
PythonContext pyContext = context.LanguageContext;
if (pt != null) {
// Recursively inspect nested tuple(s)
foreach (object o in pt) {
try {
FunctionPushFrame(pyContext);
if (IsSubClass(context, c, o)) {
return true;
}
} finally {
FunctionPopFrame();
}
}
return false;
}
Type t = typeinfo as Type;
if (t != null) {
typeinfo = DynamicHelpers.GetPythonTypeFromType(t);
}
object bases;
if (!(typeinfo is PythonType dt)) {
if (!PythonOps.TryGetBoundAttr(typeinfo, "__bases__", out bases)) {
//!!! deal with classes w/ just __bases__ defined.
throw PythonOps.TypeErrorForBadInstance("issubclass(): {0} is not a class nor a tuple of classes", typeinfo);
}
IEnumerator ie = PythonOps.GetEnumerator(bases);
while (ie.MoveNext()) {
if (!(ie.Current is PythonType baseType)) continue;
if (c.IsSubclassOf(baseType)) return true;
}
return false;
}
return IsSubClass(c, dt);
}
public static bool IsInstance(object o, PythonType typeinfo) {
if (typeinfo.__instancecheck__(o)) {
return true;
}
return IsInstanceDynamic(o, typeinfo, DynamicHelpers.GetPythonType(o));
}
public static bool IsInstance(CodeContext/*!*/ context, object o, PythonTuple typeinfo) {
PythonContext pyContext = context.LanguageContext;
foreach (object type in typeinfo) {
try {
PythonOps.FunctionPushFrame(pyContext);
if (type is PythonType) {
if (IsInstance(o, (PythonType)type)) {
return true;
}
} else if (type is PythonTuple) {
if (IsInstance(context, o, (PythonTuple)type)) {
return true;
}
} else if (IsInstance(context, o, type)) {
return true;
}
} finally {
PythonOps.FunctionPopFrame();
}
}
return false;
}
public static bool IsInstance(CodeContext/*!*/ context, object o, object typeinfo) {
if (typeinfo == null) throw PythonOps.TypeError("isinstance: arg 2 must be a class, type, or tuple of classes and types");
if (typeinfo is PythonTuple tt) {
return IsInstance(context, o, tt);
}
PythonType odt = DynamicHelpers.GetPythonType(o);
if (IsSubClass(context, odt, typeinfo)) {
return true;
}
return IsInstanceDynamic(o, typeinfo);
}
private static bool IsInstanceDynamic(object o, object typeinfo) {
return IsInstanceDynamic(o, typeinfo, DynamicHelpers.GetPythonType(o));
}
private static bool IsInstanceDynamic(object o, object typeinfo, PythonType odt) {
if (o is IPythonObject) {
object cls;
if (PythonOps.TryGetBoundAttr(o, "__class__", out cls) &&
(!object.ReferenceEquals(odt, cls))) {
return IsSubclassSlow(cls, typeinfo);
}
}
return false;
}
private static bool IsSubclassSlow(object cls, object typeinfo) {
Debug.Assert(typeinfo != null);
if (cls == null) return false;
// Same type
if (cls.Equals(typeinfo)) {
return true;
}
// Get bases
object bases;
if (!PythonOps.TryGetBoundAttr(cls, "__bases__", out bases)) {
return false; // no bases, cannot be subclass
}
if (!(bases is PythonTuple tbases)) {
return false; // not a tuple, cannot be subclass
}
foreach (object baseclass in tbases) {
if (IsSubclassSlow(baseclass, typeinfo)) return true;
}
return false;
}
public static object OnesComplement(object o) {
if (o is int) return ~(int)o;
if (o is long) return ~(long)o;
if (o is BigInteger) return ~((BigInteger)o);
if (o is bool) return ScriptingRuntimeHelpers.Int32ToObject((bool)o ? -2 : -1);
object ret;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__invert__", out ret) &&
ret != NotImplementedType.Value)
return ret;
throw PythonOps.TypeError("bad operand type for unary ~");
}
public static bool Not(object o) {
return !IsTrue(o);
}
public static object Is(object x, object y) {
return IsRetBool(x, y) ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public static bool IsRetBool(object x, object y) {
if (x == y)
return true;
// Special case "is True"/"is False" checks. They are somewhat common in
// Python (particularly in tests), but non-Python code may not stick to the
// convention of only using the two singleton instances at ScriptingRuntimeHelpers.
// (https://github.com/IronLanguages/main/issues/1299)
if (x is bool xb)
return xb == (y as bool?);
return false;
}
public static object IsNot(object x, object y) {
return IsRetBool(x, y) ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True;
}
internal delegate T MultiplySequenceWorker<T>(T self, int count);
/// <summary>
/// Wraps up all the semantics of multiplying sequences so that all of our sequences
/// don't duplicate the same logic. When multiplying sequences we need to deal with
/// only multiplying by valid sequence types (ints, not floats), support coercion
/// to integers if the type supports it, not multiplying by None, and getting the
/// right semantics for multiplying by negative numbers and 1 (w/ and w/o subclasses).
///
/// This function assumes that it is only called for case where count is not implicitly
/// coercible to int so that check is skipped.
/// </summary>
internal static object MultiplySequence<T>(MultiplySequenceWorker<T> multiplier, T sequence, Index count, bool isForward) {
if (isForward && count != null) {
object ret;
if (PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default, count.Value, sequence, "__rmul__", out ret)) {
if (ret != NotImplementedType.Value) return ret;
}
}
int icount = GetSequenceMultiplier(sequence, count.Value);
if (icount < 0) icount = 0;
return multiplier(sequence, icount);
}
internal static int GetSequenceMultiplier(object sequence, object count) {
int icount;
if (!Converter.TryConvertToIndex(count, out icount)) {
throw TypeError("can't multiply sequence by non-int of type '{0}'", PythonTypeOps.GetName(count));
}
return icount;
}
public static object Equal(CodeContext/*!*/ context, object x, object y) {
PythonContext pc = context.LanguageContext;
return pc.EqualSite.Target(pc.EqualSite, x, y);
}
public static bool EqualRetBool(object x, object y) {
//TODO just can't seem to shake these fast paths
if (x is int && y is int) { return ((int)x) == ((int)y); }
if (x is string && y is string) { return ((string)x).Equals((string)y); }
return DynamicHelpers.GetPythonType(x).EqualRetBool(x, y);
}
public static bool EqualRetBool(CodeContext/*!*/ context, object x, object y) {
// TODO: use context
//TODO just can't seem to shake these fast paths
if (x is int && y is int) { return ((int)x) == ((int)y); }
if (x is string && y is string) { return ((string)x).Equals((string)y); }
return DynamicHelpers.GetPythonType(x).EqualRetBool(x, y);
}
internal static bool IsOrEqualsRetBool(object x, object y) => ReferenceEquals(x, y) || EqualRetBool(x, y);
internal static bool IsOrEqualsRetBool(CodeContext/*!*/ context, object x, object y) => ReferenceEquals(x, y) || EqualRetBool(context, x, y);
public static int Compare(object x, object y) {
return Compare(DefaultContext.Default, x, y);
}
public static int Compare(CodeContext/*!*/ context, object x, object y) {
if (x == y) return 0;
return DynamicHelpers.GetPythonType(x).Compare(x, y);
}
public static object CompareEqual(int res) {
return res == 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public static object CompareNotEqual(int res) {
return res == 0 ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True;
}
public static object CompareGreaterThan(int res) {
return res > 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public static object CompareGreaterThanOrEqual(int res) {
return res >= 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public static object CompareLessThan(int res) {
return res < 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public static object CompareLessThanOrEqual(int res) {
return res <= 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public static bool CompareTypesEqual(CodeContext/*!*/ context, object x, object y) {
if (x == null && y == null) return true;
if (x == null) return false;
if (y == null) return false;
if (DynamicHelpers.GetPythonType(x) == DynamicHelpers.GetPythonType(y)) {
// avoid going to the ID dispenser if we have the same types...
return x == y;
}
return PythonOps.CompareTypesWorker(context, false, x, y) == 0;
}
public static bool CompareTypesNotEqual(CodeContext/*!*/ context, object x, object y) {
return PythonOps.CompareTypesWorker(context, false, x, y) != 0;
}
public static int CompareTypesWorker(CodeContext/*!*/ context, bool shouldWarn, object x, object y) {
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
int diff;
if (DynamicHelpers.GetPythonType(x) != DynamicHelpers.GetPythonType(y)) {
string name1 = PythonTypeOps.GetName(x);
string name2 = PythonTypeOps.GetName(y);
diff = string.CompareOrdinal(name1, name2);
if (diff == 0) {
// if the types are different but have the same name compare based upon their types.
diff = (int)(IdDispenser.GetId(DynamicHelpers.GetPythonType(x)) - IdDispenser.GetId(DynamicHelpers.GetPythonType(y)));
}
} else {
diff = (int)(IdDispenser.GetId(x) - IdDispenser.GetId(y));
}
if (diff < 0) return -1;
if (diff == 0) return 0;
return 1;
}
public static int CompareTypes(CodeContext/*!*/ context, object x, object y) {
return CompareTypesWorker(context, true, x, y);
}
public static object GreaterThanHelper(CodeContext/*!*/ context, object self, object other) {
return InternalCompare(context, PythonOperationKind.GreaterThan, self, other);
}
public static object LessThanHelper(CodeContext/*!*/ context, object self, object other) {
return InternalCompare(context, PythonOperationKind.LessThan, self, other);
}
public static object GreaterThanOrEqualHelper(CodeContext/*!*/ context, object self, object other) {
return InternalCompare(context, PythonOperationKind.GreaterThanOrEqual, self, other);
}
public static object LessThanOrEqualHelper(CodeContext/*!*/ context, object self, object other) {
return InternalCompare(context, PythonOperationKind.LessThanOrEqual, self, other);
}
internal static object InternalCompare(CodeContext/*!*/ context, PythonOperationKind op, object self, object other) {
object ret;
if (PythonTypeOps.TryInvokeBinaryOperator(context, self, other, Symbols.OperatorToSymbol(op), out ret))
return ret;
return NotImplementedType.Value;
}
public static int CompareToZero(object value) {
double val;
if (Converter.TryConvertToDouble(value, out val)) {
if (val > 0) return 1;
if (val < 0) return -1;
return 0;
}
throw PythonOps.TypeErrorForBadInstance("an integer is required (got {0})", value);
}
public static int CompareArrays(object[] data0, int size0, object[] data1, int size1) {
int size = Math.Min(size0, size1);
for (int i = 0; i < size; i++) {
int c = PythonOps.Compare(data0[i], data1[i]);
if (c != 0) return c;
}
if (size0 == size1) return 0;
return size0 > size1 ? +1 : -1;
}
public static int CompareArrays(object[] data0, int size0, object[] data1, int size1, IComparer comparer) {
int size = Math.Min(size0, size1);
for (int i = 0; i < size; i++) {
int c = comparer.Compare(data0[i], data1[i]);
if (c != 0) return c;
}
if (size0 == size1) return 0;
return size0 > size1 ? +1 : -1;
}
public static bool ArraysEqual(object[] data0, int size0, object[] data1, int size1) {
if (size0 != size1) {
return false;
}
for (int i = 0; i < size0; i++) {
if (!IsOrEqualsRetBool(data0[i], data1[i])) {
return false;
}
}
return true;
}
public static bool ArraysEqual(object[] data0, int size0, object[] data1, int size1, IEqualityComparer comparer) {
if (size0 != size1) {
return false;
}
for (int i = 0; i < size0; i++) {
var d0 = data0[i];
var d1 = data1[i];
if (!ReferenceEquals(d0, d1) && !comparer.Equals(d0, d1)) {
return false;
}
}
return true;
}
public static object PowerMod(CodeContext/*!*/ context, object x, object y, object z) {
object ret;
if (z == null) {
return context.LanguageContext.Operation(PythonOperationKind.Power, x, y);
}
if (x is int && y is int && z is int) {
ret = Int32Ops.Power((int)x, (int)y, (int)z);
if (ret != NotImplementedType.Value) return ret;
} else if (x is BigInteger) {
ret = BigIntegerOps.Power((BigInteger)x, y, z);
if (ret != NotImplementedType.Value) return ret;
}
if (x is Complex || y is Complex || z is Complex) {
throw PythonOps.ValueError("complex modulo");
}
if (PythonTypeOps.TryInvokeTernaryOperator(context, x, y, z, "__pow__", out ret)) {
if (ret != NotImplementedType.Value) {
return ret;
} else if (!IsNumericObject(y) || !IsNumericObject(z)) {
// special error message in this case...
throw TypeError("pow() 3rd argument not allowed unless all arguments are integers");
}
}
throw PythonOps.TypeErrorForBinaryOp("power with modulus", x, y);
}
public static long Id(object o) {
return IdDispenser.GetId(o);
}
public static string HexId(object o) {
return string.Format("0x{0:X16}", Id(o));
}
// For hash operators, it's essential that:
// Cmp(x,y)==0 implies hash(x) == hash(y)
//
// Equality is a language semantic determined by the Python's numerical Compare() ops
// in IronPython.Runtime.Operations namespaces.
// For example, the CLR compares float(1.0) and int32(1) as different, but Python
// compares them as equal. So Hash(1.0f) and Hash(1) must be equal.
//
// Python allows an equality relationship between int, double, BigInteger, and complex.
// So each of these hash functions must be aware of their possible equality relationships
// and hash appropriately.
//
// Types which differ in hashing from .NET have __hash__ functions defined in their
// ops classes which do the appropriate hashing.
public static int Hash(CodeContext/*!*/ context, object o) {
return PythonContext.Hash(o);
}
public static object Index(object o) {
if (o is int) {
return Int32Ops.__index__((int)o);
} else if (o is uint) {
return UInt32Ops.__index__((uint)o);
} else if (o is ushort) {
return UInt16Ops.__index__((ushort)o);
} else if (o is short) {
return Int16Ops.__index__((short)o);
} else if (o is byte) {
return ByteOps.__index__((byte)o);
} else if (o is sbyte) {
return SByteOps.__index__((sbyte)o);
} else if (o is long) {
return Int64Ops.__index__((long)o);
} else if(o is ulong) {
return UInt64Ops.__index__((ulong)o);
} else if (o is BigInteger) {
return BigIntegerOps.__index__((BigInteger)o);
}
object index;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default,
o,
"__index__",
out index)) {
if (!(index is int) && !(index is BigInteger))
throw PythonOps.TypeError("__index__ returned non-int (type {0})", PythonTypeOps.GetName(index));
return index;
}
throw TypeError("'{0}' object cannot be interpreted as an integer", PythonTypeOps.GetName(o));
}
public static int Length(object o) {
if (o is string s) {
return s.Length;
}
if (o is object[] os) {
return os.Length;
}
object len = PythonContext.InvokeUnaryOperator(DefaultContext.Default, UnaryOperators.Length, o,
string.Format("object of type '{0}' has no len()", PythonOps.GetPythonTypeName(o)));
int res;
if (len is int) {
res = (int)len;
} else {
res = Converter.ConvertToInt32(len);
}
if (res < 0) {
throw PythonOps.ValueError("__len__() should return >= 0");
}
return res;
}
internal static bool TryInvokeLengthHint(CodeContext context, object sequence, out int hint) {
object len_obj;
if (PythonTypeOps.TryInvokeUnaryOperator(context, sequence, "__len__", out len_obj) ||
PythonTypeOps.TryInvokeUnaryOperator(context, sequence, "__length_hint__", out len_obj)) {
if (!(len_obj is NotImplementedType)) {
hint = Converter.ConvertToInt32(len_obj);
return true;
}
}
hint = 0;
return false;
}
public static object CallWithContext(CodeContext/*!*/ context, object func, params object[] args) {
return PythonCalls.Call(context, func, args);
}
/// <summary>
/// Supports calling of functions that require an explicit 'this'
/// Currently, we check if the function object implements the interface
/// that supports calling with 'this'. If not, the 'this' object is dropped
/// and a normal call is made.
/// </summary>
public static object CallWithContextAndThis(CodeContext/*!*/ context, object func, object instance, params object[] args) {
// drop the 'this' and make the call
return CallWithContext(context, func, args);
}
public static object ToPythonType(PythonType dt) {
return ((object)dt);
}
public static object CallWithArgsTupleAndContext(CodeContext/*!*/ context, object func, object[] args, object argsTuple) {
if (argsTuple is PythonTuple tp) {
object[] nargs = new object[args.Length + tp.__len__()];
for (int i = 0; i < args.Length; i++) nargs[i] = args[i];
for (int i = 0; i < tp.__len__(); i++) nargs[i + args.Length] = tp[i];
return CallWithContext(context, func, nargs);
}
PythonList allArgs = PythonOps.MakeEmptyList(args.Length + 10);
allArgs.AddRange(args);
IEnumerator e = PythonOps.GetEnumerator(argsTuple);
while (e.MoveNext()) allArgs.AddNoLock(e.Current);
return CallWithContext(context, func, allArgs.GetObjectArray());
}
[Obsolete("Use ObjectOpertaions instead")]
public static object CallWithArgsTupleAndKeywordDictAndContext(CodeContext/*!*/ context, object func, object[] args, string[] names, object argsTuple, object kwDict) {
IDictionary kws = kwDict as IDictionary;
if (kws == null && kwDict != null) throw PythonOps.TypeError("argument after ** must be a dictionary");
if ((kws == null || kws.Count == 0) && names.Length == 0) {
List<object> largs = new List<object>(args);
if (argsTuple != null) {
foreach (object arg in PythonOps.GetCollection(argsTuple))
largs.Add(arg);
}
return CallWithContext(context, func, largs.ToArray());
} else {
List<object> largs;
if (argsTuple != null && args.Length == names.Length) {
if (!(argsTuple is PythonTuple tuple)) tuple = new PythonTuple(argsTuple);
largs = new List<object>(tuple);
largs.AddRange(args);
} else {
largs = new List<object>(args);
if (argsTuple != null) {
largs.InsertRange(args.Length - names.Length, PythonTuple.Make(argsTuple));
}
}
List<string> lnames = new List<string>(names);
if (kws != null) {
IDictionaryEnumerator ide = kws.GetEnumerator();
while (ide.MoveNext()) {
lnames.Add((string)ide.Key);
largs.Add(ide.Value);
}
}
return PythonCalls.CallWithKeywordArgs(context, func, largs.ToArray(), lnames.ToArray());
}
}
public static object CallWithKeywordArgs(CodeContext/*!*/ context, object func, object[] args, string[] names) {
return PythonCalls.CallWithKeywordArgs(context, func, args, names);
}
public static object CallWithArgsTuple(object func, object[] args, object argsTuple) {
if (argsTuple is PythonTuple tp) {
object[] nargs = new object[args.Length + tp.__len__()];
for (int i = 0; i < args.Length; i++) nargs[i] = args[i];
for (int i = 0; i < tp.__len__(); i++) nargs[i + args.Length] = tp[i];
return PythonCalls.Call(func, nargs);
}
PythonList allArgs = PythonOps.MakeEmptyList(args.Length + 10);
allArgs.AddRange(args);
IEnumerator e = PythonOps.GetEnumerator(argsTuple);
while (e.MoveNext()) allArgs.AddNoLock(e.Current);
return PythonCalls.Call(func, allArgs.GetObjectArray());
}
public static object GetIndex(CodeContext/*!*/ context, object o, object index) {
PythonContext pc = context.LanguageContext;
return pc.GetIndexSite.Target(pc.GetIndexSite, o, index);
}
public static bool TryGetBoundAttr(object o, string name, out object ret) {
return TryGetBoundAttr(DefaultContext.Default, o, name, out ret);
}
public static void SetAttr(CodeContext/*!*/ context, object o, string name, object value) {
context.LanguageContext.SetAttr(context, o, name, value);
}
public static bool TryGetBoundAttr(CodeContext/*!*/ context, object o, string name, out object ret) {
return DynamicHelpers.GetPythonType(o).TryGetBoundAttr(context, o, name, out ret);
}
public static void DeleteAttr(CodeContext/*!*/ context, object o, string name) {
context.LanguageContext.DeleteAttr(context, o, name);
}
public static bool HasAttr(CodeContext/*!*/ context, object o, string name) {
object dummy;
return TryGetBoundAttr(context, o, name, out dummy);
}
public static object GetBoundAttr(CodeContext/*!*/ context, object o, string name) {
object ret;
if (!DynamicHelpers.GetPythonType(o).TryGetBoundAttr(context, o, name, out ret)) {
throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonTypeOps.GetName(o), name);
}
return ret;
}
public static void ObjectSetAttribute(CodeContext/*!*/ context, object o, string name, object value) {
if (!DynamicHelpers.GetPythonType(o).TrySetNonCustomMember(context, o, name, value))
throw AttributeErrorForMissingOrReadonly(context, DynamicHelpers.GetPythonType(o), name);
}
public static void ObjectDeleteAttribute(CodeContext/*!*/ context, object o, string name) {
if (!DynamicHelpers.GetPythonType(o).TryDeleteNonCustomMember(context, o, name)) {
throw AttributeErrorForMissingOrReadonly(context, DynamicHelpers.GetPythonType(o), name);
}
}
public static object ObjectGetAttribute(CodeContext/*!*/ context, object o, string name) {
object value;
if (DynamicHelpers.GetPythonType(o).TryGetNonCustomMember(context, o, name, out value)) {
return value;
}
throw PythonOps.AttributeErrorForObjectMissingAttribute(o, name);
}
internal static IList<string> GetStringMemberList(IPythonMembersList pyMemList) {
List<string> res = new List<string>();
foreach (object o in pyMemList.GetMemberNames(DefaultContext.Default)) {
if (o is string) {