-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathPythonOps.cs
More file actions
4400 lines (3630 loc) · 186 KB
/
PythonOps.cs
File metadata and controls
4400 lines (3630 loc) · 186 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.
#nullable enable
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
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.Ast;
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;
using NotNullAttribute = System.Diagnostics.CodeAnalysis.NotNullAttribute;
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
[EditorBrowsable(EditorBrowsableState.Never)]
public static PythonDictionary MakeEmptyDict() {
return new PythonDictionary();
}
/// <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, [NotNullWhen(true)]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) {
return PythonTypeOps.TryGetOperator(context, o, "__call__", out object callFunc) && callFunc != null;
}
public static bool IsTrue(object? o) {
return Converter.ConvertToBoolean(o);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
internal static List<object> GetReprInfinite() {
if (InfiniteRepr == null) {
InfiniteRepr = new List<object>();
}
return InfiniteRepr;
}
[LightThrowing]
internal static object LookupEncodingError(CodeContext/*!*/ context, string name) {
ConcurrentDictionary<string, object> errorHandlers = context.LanguageContext.ErrorHandlers;
if (errorHandlers.TryGetValue(name, out object? handler))
return handler;
else
return LightExceptions.Throw(PythonOps.LookupError("unknown error handler name '{0}'", name));
}
internal static void RegisterEncodingError(CodeContext/*!*/ context, string name, object? handler) {
ConcurrentDictionary<string, object> errorHandlers = context.LanguageContext.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) {
if (res is PythonTuple pt && pt.__len__() == 4) {
return pt;
} else {
throw PythonOps.TypeError("codec search functions must return 4-tuples");
}
}
}
}
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) {
// IronPython uses Int32 objects as "int" for performance reasons (GH #52)
if (obj is int) return "int";
#pragma warning disable IPY04 // Direct call to PythonTypeOps.GetName
return PythonTypeOps.GetName(obj);
#pragma warning restore IPY04
}
internal static string GetPythonTypeNameFromType(Type type) {
// IronPython uses Int32 objects as "int" for performance reasons (GH #52)
if (type == typeof(int)) return "int";
return DynamicHelpers.GetPythonTypeFromType(type).Name;
}
public static string Ascii(CodeContext/*!*/ context, object? o) {
return StringOps.AsciiEncode(Repr(context, o));
}
internal static object GetReprObject(CodeContext/*!*/ context, object? o) {
if (o == null) return "None";
// Fast tracks
if (o is string s) return StringOps.__repr__(s);
if (o is int i32) return Int32Ops.__repr__(i32);
if (o is BigInteger bi) return BigIntegerOps.__repr__(bi);
// 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 if (o is PythonType && o.GetType() != typeof(PythonType)) {
// let is fall through since metaclass may be defining __repr__, resolves the following:
// class MyMetaClass(type):
// def __repr__(self):
// return "qwerty"
//
// class test(metaclass=MyMetaClass): pass
//
// assert repr(test) == "qwerty"
} else {
return f.__repr__(context);
}
}
PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "Repr " + o.GetType().FullName);
object? repr = PythonContext.InvokeUnaryOperator(context, UnaryOperators.Repr, o);
if (repr is string strRepr) return strRepr;
if (repr is Extensible<string> esRepr) return esRepr;
throw PythonOps.TypeError("__repr__ returned non-string (got '{0}' from type '{1}')", PythonOps.GetPythonTypeName(repr), PythonOps.GetPythonTypeName(o));
}
public static string Repr(CodeContext/*!*/ context, object? o)
=> GetReprObject(context, o).ToString() ?? "<unknown>";
public static string Format(CodeContext/*!*/ context, object? argValue, string formatSpec) {
object? res;
// call __format__ with the format spec (__format__ is defined on object, so this always succeeds)
PythonTypeOps.TryInvokeBinaryOperator(
context,
argValue,
formatSpec,
"__format__",
out res);
if (!(res is string strRes)) {
throw PythonOps.TypeError("{0}.__format__ must return a str, not {1}", PythonOps.GetPythonTypeName(argValue), PythonOps.GetPythonTypeName(res));
}
return strRes;
}
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__", PythonOps.GetPythonTypeName(value));
}
ret = es.Value;
}
return ret;
}
public static string FormatString(CodeContext/*!*/ context, string str, object data) {
return StringFormatter.Format(context, str, data);
}
internal static object FsPath(CodeContext context, object? path) {
if (TryToFsPath(context, path, out var res))
return res;
throw PythonOps.TypeError("expected str, bytes or os.PathLike object, not {0}", PythonOps.GetPythonTypeName(path));
}
internal static bool TryToFsPath(CodeContext context, object? path, [NotNullWhen(true)] out object? res) {
res = path;
if (res is string || res is Extensible<string> || res is Bytes) return true;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, path, "__fspath__", out res)) {
if (res is string || res is Extensible<string> || res is Bytes) return true;
throw PythonOps.TypeError("expected {0}.__fspath__() to return str or bytes, not {1}", PythonOps.GetPythonTypeName(path), PythonOps.GetPythonTypeName(res));
}
return false;
}
internal static string FsPathDecoded(CodeContext context, object? path)
=> DecodeFsPath(context, FsPath(context, path));
internal static bool TryToFsPathDecoded(CodeContext context, object? path, [NotNullWhen(true)] out string? res) {
if (PythonOps.TryToFsPath(context, path, out object? obj)) {
res = DecodeFsPath(context, obj);
return true;
}
res = null;
return false;
}
internal static string DecodeFsPath(CodeContext context, object obj) {
return obj switch {
string s => s,
Extensible<string> es => es,
Bytes b => b.decode(context, SysModule.getfilesystemencoding(context), SysModule.getfilesystemencodeerrors()),
_ => throw new InvalidOperationException(),
};
}
public static object Plus(object? o) {
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 object 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);
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__neg__", out object ret) &&
ret != NotImplementedType.Value) {
return ret;
}
throw PythonOps.TypeError("bad operand type for unary -");
}
internal static bool IsSubClass(PythonType/*!*/ c, PythonType/*!*/ typeinfo) {
Assert.NotNull(c, typeinfo);
return typeinfo.__subclasscheck__(c);
}
internal static bool IsSubClass(CodeContext/*!*/ context, PythonType c, [NotNull]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");
PythonContext pyContext = context.LanguageContext;
if (typeinfo is PythonTuple pt) {
// Recursively inspect nested tuple(s)
foreach (object? o in pt) {
try {
FunctionPushFrame(pyContext);
if (IsSubClass(context, c, o)) {
return true;
}
} finally {
FunctionPopFrame();
}
}
return false;
}
if (typeinfo is Type t) {
typeinfo = DynamicHelpers.GetPythonTypeFromType(t);
}
if (!(typeinfo is PythonType dt)) {
if (!PythonOps.TryGetBoundAttr(typeinfo, "__bases__", out object? 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);
}
internal static bool IsInstance(object? o, PythonType typeinfo) {
var objType = DynamicHelpers.GetPythonType(o);
if (objType == typeinfo) {
return true;
}
// PEP 237: int/long unification
// https://github.com/IronLanguages/ironpython3/issues/52
if (typeinfo == TypeCache.BigInteger && o is int) {
return true;
}
if (typeinfo.__instancecheck__(o)) {
return true;
}
return IsInstanceDynamic(o, typeinfo, objType);
}
internal static bool IsInstance(CodeContext/*!*/ context, object? o, PythonTuple typeinfo) {
PythonContext pyContext = context.LanguageContext;
// loop on the underlying data object - https://github.com/IronLanguages/ironpython3/issues/1255
foreach (object? type in typeinfo._data) {
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;
}
// used by Ironclad
public static bool IsInstance(CodeContext/*!*/ context, object? o, [NotNull]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) {
if (PythonOps.TryGetBoundAttr(o, "__class__", out object? cls) &&
(!object.ReferenceEquals(odt, cls))) {
return IsSubclassSlow(cls, typeinfo);
}
}
return false;
}
private static bool IsSubclassSlow([NotNullWhen(true)]object? cls, object typeinfo) {
if (cls == null) return false;
// Same type
if (cls.Equals(typeinfo)) {
return true;
}
// Get bases
if (!PythonOps.TryGetBoundAttr(cls, "__bases__", out object? 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);
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__invert__", out object 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) where T : notnull {
if (isForward) {
if (PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default, count.Value, sequence, "__rmul__", out object 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) {
if (!Converter.TryConvertToIndex(count, out int icount)) {
throw TypeError("can't multiply sequence by non-int of type '{0}'", PythonOps.GetPythonTypeName(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);
internal static object? RichCompare(CodeContext/*!*/ context, object? x, object? y, PythonOperationKind op) {
var res = InternalCompare(context, op, x, y);
if (res is NotImplementedType) {
res = InternalCompare(context, Symbols.OperatorToReverseOperator(op), y, x);
if (res is NotImplementedType) {
throw TypeErrorForBinaryOp(PythonProtocol.GetOperatorDisplay(op), x, y);
}
}
return res;
static object InternalCompare(CodeContext/*!*/ context, PythonOperationKind op, object? self, object? other) {
if (PythonTypeOps.TryInvokeBinaryOperator(context, self, other, Symbols.OperatorToSymbol(op), out object ret))
return ret;
return NotImplementedType.Value;
}
}
public static bool CompareTypesEqual(CodeContext/*!*/ context, object? x, object? y) {
return ReferenceEquals(x, y);
}
public static bool CompareTypesNotEqual(CodeContext/*!*/ context, object? x, object? y) {
return !CompareTypesEqual(context, x, y);
}
internal static bool ArraysEqual(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1) {
if (data0.Length != data1.Length) {
return false;
}
for (int i = 0; i < data0.Length; i++) {
if (!IsOrEqualsRetBool(context, data0[i], data1[i])) {
return false;
}
}
return true;
}
internal static bool ArraysEqual(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1, IEqualityComparer comparer) {
if (data0.Length != data1.Length) {
return false;
}
for (int i = 0; i < data0.Length; i++) {
var d0 = data0[i];
var d1 = data1[i];
if (!ReferenceEquals(d0, d1) && !comparer.Equals(d0, d1)) {
return false;
}
}
return true;
}
private static object CompareLength(int length1, int length2, PythonOperationKind op) {
var res = op switch {
PythonOperationKind.Equal => length1 == length2,
PythonOperationKind.NotEqual => length1 != length2,
PythonOperationKind.LessThan => length1 < length2,
PythonOperationKind.LessThanOrEqual => length1 <= length2,
PythonOperationKind.GreaterThan => length1 > length2,
PythonOperationKind.GreaterThanOrEqual => length1 >= length2,
_ => throw new InvalidOperationException(),
};
return res ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
internal static object? RichCompareSequences(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1, PythonOperationKind op) {
int size = Math.Min(data0.Length, data1.Length);
for (int i = 0; i < size; i++) {
var x = data0[i];
var y = data1[i];
if (IsOrEqualsRetBool(context, x, y)) continue;
if (op == PythonOperationKind.Equal) return ScriptingRuntimeHelpers.False;
if (op == PythonOperationKind.NotEqual) return ScriptingRuntimeHelpers.True;
return RichCompare(context, x, y, op);
}
return CompareLength(data0.Length, data1.Length, op);
}
internal static object? RichCompareSequences(CodeContext context, IList<object?> data0, IList<object?> data1, PythonOperationKind op) {
int size = Math.Min(data0.Count, data1.Count);
for (int i = 0; i < size; i++) {
var x = data0[i];
var y = data1[i];
if (IsOrEqualsRetBool(context, x, y)) continue;
if (op == PythonOperationKind.Equal) return ScriptingRuntimeHelpers.False;
if (op == PythonOperationKind.NotEqual) return ScriptingRuntimeHelpers.True;
return RichCompare(context, x, y, op);
}
return CompareLength(data0.Count, data1.Count, op);
}
internal static object? ArraysGreaterThan(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.GreaterThan);
internal static object? ArraysGreaterThan(CodeContext context, IList<object?> data0, IList<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.GreaterThan);
internal static object? ArraysLessThan(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.LessThan);
internal static object? ArraysLessThan(CodeContext context, IList<object?> data0, IList<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.LessThan);
internal static object? ArraysGreaterThanOrEqual(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.GreaterThanOrEqual);
internal static object? ArraysGreaterThanOrEqual(CodeContext context, IList<object?> data0, IList<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.GreaterThanOrEqual);
internal static object? ArraysLessThanOrEqual(CodeContext context, ReadOnlySpan<object?> data0, ReadOnlySpan<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.LessThanOrEqual);
internal static object? ArraysLessThanOrEqual(CodeContext context, IList<object?> data0, IList<object?> data1)
=> RichCompareSequences(context, data0, data1, PythonOperationKind.LessThanOrEqual);
public static object PowerMod(CodeContext/*!*/ context, object? x, object? y, object? z) {
object? ret;
if (z is null) {
return context.LanguageContext.Operation(PythonOperationKind.Power, x, y);
}
if (x is int ix && y is int iy && z is int iz) {
ret = Int32Ops.Power(ix, iy, iz);
if (ret != NotImplementedType.Value) return ret;
} else if (x is BigInteger bx) {
ret = BigIntegerOps.Power(bx, 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.TypeError("unsupported operand type(s) for pow(): '{0}', '{1}', '{2}'", GetPythonTypeName(x), GetPythonTypeName(y), GetPythonTypeName(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 (TryToIndex(o, out object? index)) return index;
throw TypeErrorForUnIndexableObject(o);
}
internal static bool TryToIndex(object? o, [NotNullWhen(true)] out object? index) {
var context = DefaultContext.Default;
switch (o) {
case int i:
index = o;
return true;
case BigInteger bi:
index = o;
return true;
case Extensible<BigInteger> ebi:
index = ebi.Value;
return true;
default:
break;
}
if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__index__", out index)) {
if (index is int || index is BigInteger)
return true;
if (index is Extensible<BigInteger> ebi) {
Warn(context, PythonExceptions.DeprecationWarning, $"__index__ returned non-int (type {PythonOps.GetPythonTypeName(index)}). The ability to return an instance of a strict subclass of int is deprecated, and may be removed in a future version of Python.");
index = ebi.Value; // this is the behavior of 3.10
return true;
}
if (index is bool b) {
Warn(context, PythonExceptions.DeprecationWarning, $"__index__ returned non-int (type {PythonOps.GetPythonTypeName(index)}). The ability to return an instance of a strict subclass of int is deprecated, and may be removed in a future version of Python.");
index = ScriptingRuntimeHelpers.Int32ToObject(b ? 1 : 0); // this is the behavior of 3.10
return true;
}
throw TypeError("__index__ returned non-int (type {0})", PythonOps.GetPythonTypeName(index));
}
index = default;
return false;
}
internal static bool TryToIndex(object? o, out BigInteger index) {
if (TryToIndex(o, out object? obj)) {
if (obj is int i) {
index = i;
} else {
index = (BigInteger)obj;
}
return true;
}
index = default;
return false;
}
private static bool IndexObjectToInt(object o, out int res, out BigInteger longRes) {
switch (o) {
case int i:
res = i;
break;
case BigInteger bi:
if (!bi.AsInt32(out res)) {
longRes = bi;
return false;
}
break;
default:
throw new InvalidOperationException();
}
longRes = default;
return true;
}
internal static bool Length(object? o, out int res, out BigInteger bigRes) {
if (o is string s) {
res = s.Length;
bigRes = default;
return true;
}
if (o is object[] os) {
res = os.Length;
bigRes = default;
return true;
}
if (!PythonContext.TryInvokeUnaryOperator(DefaultContext.Default, UnaryOperators.Length, o, out object len)) {
throw TypeError("object of type '{0}' has no len()", GetPythonTypeName(o));
}
var indexObj = Index(len);
if (IndexObjectToInt(indexObj, out res, out bigRes)) {
if (res < 0) throw ValueError("__len__() should return >= 0");
return true;
} else {
if (bigRes < 0) throw ValueError("__len__() should return >= 0");
return false;
}
}
public static int Length(object? o) {
if (Length(o, out int res, out _)) {
return res;
}
throw new OverflowException();
}
internal static bool TryInvokeLengthHint(CodeContext context, object? sequence, out int hint) {
if (PythonTypeOps.TryInvokeUnaryOperator(context, sequence, "__len__", out object len_obj)) {
if (!(len_obj is NotImplementedType)) {
hint = Converter.ConvertToInt32(len_obj);
if (hint < 0) throw ValueError("__len__() should return >= 0");
return true;
}
} else if (PythonTypeOps.TryInvokeUnaryOperator(context, sequence, "__length_hint__", out len_obj)) {
if (!(len_obj is NotImplementedType)) {
hint = Converter.ConvertToInt32(len_obj);
if (hint < 0) throw ValueError("__length_hint__() should return >= 0");
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);
}
[Obsolete("Use ObjectOperations 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());
}