forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonProtocol.Operations.cs
More file actions
1782 lines (1550 loc) · 84.4 KB
/
PythonProtocol.Operations.cs
File metadata and controls
1782 lines (1550 loc) · 84.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
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 System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime.Binding {
using Ast = Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
internal static partial class PythonProtocol {
public static DynamicMetaObject/*!*/ Operation(BinaryOperationBinder/*!*/ operation, DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Fallback BinaryOperator " + target.LimitType.FullName + " " + operation.Operation + " " + arg.LimitType.FullName);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, operation.Operation.ToString());
DynamicMetaObject[] args = new[] { target, arg };
if (BindingHelpers.NeedsDeferral(args)) {
return operation.Defer(target, arg);
}
ValidationInfo valInfo = BindingHelpers.GetValidationInfo(args);
PythonOperationKind? pyOperator = null;
switch (operation.Operation) {
case ExpressionType.Add: pyOperator = PythonOperationKind.Add; break;
case ExpressionType.And: pyOperator = PythonOperationKind.BitwiseAnd; break;
case ExpressionType.Divide: pyOperator = PythonOperationKind.TrueDivide; break;
case ExpressionType.ExclusiveOr: pyOperator = PythonOperationKind.ExclusiveOr; break;
case ExpressionType.Modulo: pyOperator = PythonOperationKind.Mod; break;
case ExpressionType.Multiply: pyOperator = PythonOperationKind.Multiply; break;
case ExpressionType.Or: pyOperator = PythonOperationKind.BitwiseOr; break;
case ExpressionType.Power: pyOperator = PythonOperationKind.Power; break;
case ExpressionType.RightShift: pyOperator = PythonOperationKind.RightShift; break;
case ExpressionType.LeftShift: pyOperator = PythonOperationKind.LeftShift; break;
case ExpressionType.Subtract: pyOperator = PythonOperationKind.Subtract; break;
case ExpressionType.AddAssign: pyOperator = PythonOperationKind.InPlaceAdd; break;
case ExpressionType.AndAssign: pyOperator = PythonOperationKind.InPlaceBitwiseAnd; break;
case ExpressionType.DivideAssign: pyOperator = PythonOperationKind.InPlaceTrueDivide; break;
case ExpressionType.ExclusiveOrAssign: pyOperator = PythonOperationKind.InPlaceExclusiveOr; break;
case ExpressionType.ModuloAssign: pyOperator = PythonOperationKind.InPlaceMod; break;
case ExpressionType.MultiplyAssign: pyOperator = PythonOperationKind.InPlaceMultiply; break;
case ExpressionType.OrAssign: pyOperator = PythonOperationKind.InPlaceBitwiseOr; break;
case ExpressionType.PowerAssign: pyOperator = PythonOperationKind.InPlacePower; break;
case ExpressionType.RightShiftAssign: pyOperator = PythonOperationKind.InPlaceRightShift; break;
case ExpressionType.LeftShiftAssign: pyOperator = PythonOperationKind.InPlaceLeftShift; break;
case ExpressionType.SubtractAssign: pyOperator = PythonOperationKind.InPlaceSubtract; break;
case ExpressionType.Equal: pyOperator = PythonOperationKind.Equal; break;
case ExpressionType.GreaterThan: pyOperator = PythonOperationKind.GreaterThan; break;
case ExpressionType.GreaterThanOrEqual: pyOperator = PythonOperationKind.GreaterThanOrEqual; break;
case ExpressionType.LessThan: pyOperator = PythonOperationKind.LessThan; break;
case ExpressionType.LessThanOrEqual: pyOperator = PythonOperationKind.LessThanOrEqual; break;
case ExpressionType.NotEqual: pyOperator = PythonOperationKind.NotEqual; break;
}
DynamicMetaObject res = null;
if (pyOperator != null) {
res = MakeBinaryOperation(operation, args, pyOperator.Value, errorSuggestion);
} else {
res = operation.FallbackBinaryOperation(target, arg);
}
return BindingHelpers.AddDynamicTestAndDefer(operation, BindingHelpers.AddPythonBoxing(res), args, valInfo);
}
public static DynamicMetaObject/*!*/ Operation(UnaryOperationBinder/*!*/ operation, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Fallback UnaryOperator " + " " + operation.Operation + " " + arg.LimitType.FullName);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, operation.Operation.ToString());
DynamicMetaObject[] args = new[] { arg };
if (arg.NeedsDeferral()) {
return operation.Defer(arg);
}
ValidationInfo valInfo = BindingHelpers.GetValidationInfo(args);
DynamicMetaObject res = null;
Type retType = typeof(object);
switch (operation.Operation) {
case ExpressionType.UnaryPlus:
res = BindingHelpers.AddPythonBoxing(MakeUnaryOperation(operation, arg, "__pos__", errorSuggestion));
break;
case ExpressionType.Negate:
res = BindingHelpers.AddPythonBoxing(MakeUnaryOperation(operation, arg, "__neg__", errorSuggestion));
break;
case ExpressionType.OnesComplement:
res = BindingHelpers.AddPythonBoxing(MakeUnaryOperation(operation, arg, "__invert__", errorSuggestion));
break;
case ExpressionType.Not:
res = MakeUnaryNotOperation(operation, arg, typeof(object), errorSuggestion);
break;
case ExpressionType.IsFalse:
res = MakeUnaryNotOperation(operation, arg, typeof(bool), errorSuggestion);
retType = typeof(bool);
break;
case ExpressionType.IsTrue:
res = ConvertToBool(operation, arg);
retType = typeof(bool);
break;
default:
res = TypeError(operation, "unknown operation: " + operation.ToString(), args);
break;
}
return BindingHelpers.AddDynamicTestAndDefer(operation, res, args, valInfo, retType);
}
public static DynamicMetaObject/*!*/ Index(DynamicMetaObjectBinder/*!*/ operation, PythonIndexType index, DynamicMetaObject[] args) {
return Index(operation, index, args, null);
}
public static DynamicMetaObject/*!*/ Index(DynamicMetaObjectBinder/*!*/ operation, PythonIndexType index, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
if (args.Length >= 3) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Fallback Index " + " " + index + " " + args[0].LimitType + ", " + args[1].LimitType + ", " + args[2].LimitType + args.Length);
} else {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Fallback Index " + " " + index + " " + args[0].LimitType + ", " + args[1].LimitType + args.Length);
}
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, index.ToString());
if (BindingHelpers.NeedsDeferral(args)) {
return operation.Defer(args);
}
ValidationInfo valInfo = BindingHelpers.GetValidationInfo(args[0]);
DynamicMetaObject res = BindingHelpers.AddPythonBoxing(MakeIndexerOperation(operation, index, args, errorSuggestion));
return BindingHelpers.AddDynamicTestAndDefer(operation, res, args, valInfo);
}
public static DynamicMetaObject/*!*/ Operation(PythonOperationBinder/*!*/ operation, params DynamicMetaObject/*!*/[]/*!*/ args) {
if (args.Length == 1) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Fallback PythonOp " + " " + operation.Operation + " " + args[0].LimitType);
} else {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Fallback PythonOp " + " " + operation.Operation + " " + args[0].LimitType + ", " + args[1].LimitType);
}
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, operation.Operation.ToString());
if (BindingHelpers.NeedsDeferral(args)) {
return operation.Defer(args);
}
return MakeOperationRule(operation, args);
}
private static DynamicMetaObject/*!*/ MakeOperationRule(PythonOperationBinder/*!*/ operation, DynamicMetaObject/*!*/[]/*!*/ args) {
ValidationInfo valInfo = BindingHelpers.GetValidationInfo(args);
DynamicMetaObject res;
Type deferType = typeof(object);
switch (operation.Operation) {
case PythonOperationKind.Documentation:
res = BindingHelpers.AddPythonBoxing(MakeDocumentationOperation(operation, args));
break;
case PythonOperationKind.CallSignatures:
res = BindingHelpers.AddPythonBoxing(MakeCallSignatureOperation(args[0], CompilerHelpers.GetMethodTargets(args[0].Value)));
break;
case PythonOperationKind.IsCallable:
res = MakeIscallableOperation(operation, args);
break;
case PythonOperationKind.Hash:
res = MakeHashOperation(operation, args[0]);
break;
case PythonOperationKind.Contains:
res = MakeContainsOperation(operation, args);
break;
case PythonOperationKind.AbsoluteValue:
res = BindingHelpers.AddPythonBoxing(MakeUnaryOperation(operation, args[0], "__abs__", null));
break;
case PythonOperationKind.GetEnumeratorForIteration:
res = MakeEnumeratorOperation(operation, args[0]);
break;
case PythonOperationKind.AIter:
res = MakeUnaryOperation(operation, args[0], "__aiter__", TypeError(operation, "'async for' requires an object with __aiter__ method, got {0}", args));
break;
case PythonOperationKind.ANext:
res = MakeUnaryOperation(operation, args[0], "__anext__", TypeError(operation, "'async for' received an invalid object from __aiter__: {0}", args));
break;
default:
res = BindingHelpers.AddPythonBoxing(MakeBinaryOperation(operation, args, operation.Operation, null));
break;
}
return BindingHelpers.AddDynamicTestAndDefer(operation, res, args, valInfo, deferType);
}
private static DynamicMetaObject MakeBinaryOperation(DynamicMetaObjectBinder operation, DynamicMetaObject/*!*/[] args, PythonOperationKind opStr, DynamicMetaObject errorSuggestion) {
if (IsComparison(opStr)) {
return MakeComparisonOperation(args, operation, opStr, errorSuggestion);
}
return MakeSimpleOperation(args, operation, opStr, errorSuggestion);
}
#region Unary Operations
/// <summary>
/// Creates a rule for the contains operator. This is exposed via "x in y" in
/// IronPython. It is implemented by calling the __contains__ method on x and
/// passing in y.
///
/// If a type doesn't define __contains__ but does define __getitem__ then __getitem__ is
/// called repeatedly in order to see if the object is there.
///
/// For normal .NET enumerables we'll walk the iterator and see if it's present.
/// </summary>
private static DynamicMetaObject/*!*/ MakeContainsOperation(PythonOperationBinder/*!*/ operation, DynamicMetaObject/*!*/[]/*!*/ types) {
DynamicMetaObject res;
// the paramteres come in backwards from how we look up __contains__, flip them.
Debug.Assert(types.Length == 2);
ArrayUtils.SwapLastTwo(types);
PythonContext state = PythonContext.GetPythonContext(operation);
SlotOrFunction sf = SlotOrFunction.GetSlotOrFunction(state, "__contains__", types);
if (sf.Success) {
// just a call to __contains__
res = sf.Target;
} else {
var types1 = types[1];
RestrictTypes(types);
sf = SlotOrFunction.GetSlotOrFunction(state, "__iter__", types[0]);
if (sf.Success) {
types[1] = types1; // restore types[1] value to prevent reboxing
// iterate using __iter__
res = new DynamicMetaObject(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.ContainsFromEnumerable)),
AstUtils.Constant(state.SharedContext),
sf.Target.Expression,
AstUtils.Convert(types[1].Expression, typeof(object))
),
BindingRestrictions.Combine(types)
);
} else {
ParameterExpression curIndex = Ast.Variable(typeof(int), "count");
sf = SlotOrFunction.GetSlotOrFunction(state, "__getitem__", types[0], new DynamicMetaObject(curIndex, BindingRestrictions.Empty));
if (sf.Success) {
// defines __getitem__, need to loop over the indexes and see if we match
ParameterExpression getItemRes = Ast.Variable(sf.ReturnType, "getItemRes");
ParameterExpression containsRes = Ast.Variable(typeof(bool), "containsRes");
LabelTarget target = Ast.Label();
res = new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { curIndex, getItemRes, containsRes },
Utils.Loop(
null, // test
Ast.Assign(curIndex, Ast.Add(curIndex, AstUtils.Constant(1))), // increment
Ast.Block( // body
// getItemRes = param0.__getitem__(curIndex)
Utils.Try(
Ast.Block(
Ast.Assign(
getItemRes,
sf.Target.Expression
),
Ast.Empty()
)
).Catch(
// end of indexes, return false
typeof(IndexOutOfRangeException),
Ast.Break(target)
),
// if(getItemRes == param1) return true
Utils.If(
DynamicExpression.Dynamic(
state.BinaryOperationRetType(
state.BinaryOperation(ExpressionType.Equal),
state.Convert(typeof(bool), ConversionResultKind.ExplicitCast)
),
typeof(bool),
types[1].Expression,
getItemRes
),
Ast.Assign(containsRes, AstUtils.Constant(true)),
Ast.Break(target)
),
AstUtils.Empty()
),
null, // loop else
target, // break label target
null
),
containsRes
),
BindingRestrictions.Combine(types)
);
} else {
// non-iterable object
res = new DynamicMetaObject(
operation.Throw(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.TypeErrorForNonIterableObject)),
AstUtils.Convert(
types[0].Expression,
typeof(object)
)
),
typeof(bool)
),
BindingRestrictions.Combine(types)
);
}
}
}
if (res.GetLimitType() != typeof(bool) && res.GetLimitType() != typeof(void)) {
res = new DynamicMetaObject(
DynamicExpression.Dynamic(
state.Convert(
typeof(bool),
ConversionResultKind.ExplicitCast
),
typeof(bool),
res.Expression
),
res.Restrictions
);
}
return res;
}
private static void RestrictTypes(DynamicMetaObject/*!*/[] types) {
for (int i = 0; i < types.Length; i++) {
types[i] = types[i].Restrict(types[i].GetLimitType());
}
}
private static DynamicMetaObject/*!*/ MakeHashOperation(PythonOperationBinder/*!*/ operation, DynamicMetaObject/*!*/ self) {
self = self.Restrict(self.GetLimitType());
PythonContext state = PythonContext.GetPythonContext(operation);
SlotOrFunction func = SlotOrFunction.GetSlotOrFunction(state, "__hash__", self);
DynamicMetaObject res = func.Target;
if (func.IsNull) {
// Python 2.6 setting __hash__ = None makes the type unhashable
res = new DynamicMetaObject(
operation.Throw(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.TypeErrorForUnhashableObject)),
self.Expression
),
typeof(int)
),
res.Restrictions
);
} else if (func.ReturnType != typeof(int)) {
if (func.ReturnType == typeof(BigInteger)) {
// Python 2.5 defines the result of returning a long as hashing the long
res = new DynamicMetaObject(
HashBigInt(operation, res.Expression),
res.Restrictions
);
} else if (func.ReturnType == typeof(object)) {
// need to get the integer value here...
ParameterExpression tempVar = Ast.Parameter(typeof(object), "hashTemp");
res = new DynamicMetaObject(
Expression.Block(
new[] { tempVar },
Expression.Assign(tempVar, res.Expression),
Expression.Condition(
Expression.TypeIs(tempVar, typeof(int)),
Expression.Convert(tempVar, typeof(int)),
Expression.Condition(
Expression.TypeIs(tempVar, typeof(BigInteger)),
HashBigInt(operation, tempVar),
HashConvertToInt(state, tempVar)
)
)
),
res.Restrictions
);
} else {
// need to convert unknown value to object
res = new DynamicMetaObject(
HashConvertToInt(state, res.Expression),
res.Restrictions
);
}
}
return res;
}
private static DynamicExpression/*!*/ HashBigInt(PythonOperationBinder/*!*/ operation, Expression/*!*/ expression) {
return DynamicExpression.Dynamic(
operation,
typeof(int),
expression
);
}
private static DynamicExpression/*!*/ HashConvertToInt(PythonContext/*!*/ state, Expression/*!*/ expression) {
return DynamicExpression.Dynamic(
state.Convert(
typeof(int),
ConversionResultKind.ExplicitCast
),
typeof(int),
expression
);
}
private static DynamicMetaObject MakeUnaryOperation(DynamicMetaObjectBinder binder, DynamicMetaObject self, string symbol, DynamicMetaObject errorSuggestion) {
self = self.Restrict(self.GetLimitType());
SlotOrFunction func = SlotOrFunction.GetSlotOrFunction(PythonContext.GetPythonContext(binder), symbol, self);
if (!func.Success) {
// we get the error message w/ {0} so that PythonBinderHelper.TypeError formats it correctly
return errorSuggestion ?? TypeError(binder, MakeUnaryOpErrorMessage(symbol, "{0}"), self);
}
return func.Target;
}
private static DynamicMetaObject MakeEnumeratorOperation(PythonOperationBinder operation, DynamicMetaObject self) {
if (self.GetLimitType() == typeof(string)) {
self = self.Restrict(self.GetLimitType());
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.StringEnumerator)),
self.Expression
),
self.Restrictions
);
} else if (self.GetLimitType() == typeof(Bytes)) {
self = self.Restrict(self.GetLimitType());
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.BytesEnumerator)),
self.Expression
),
self.Restrictions
);
} else if ((self.Value is IEnumerable ||
typeof(IEnumerable).IsAssignableFrom(self.GetLimitType())) && !(self.Value is PythonGenerator)) {
self = self.Restrict(self.GetLimitType());
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.GetEnumeratorFromEnumerable)),
Expression.Convert(
self.Expression,
typeof(IEnumerable)
)
),
self.Restrictions
);
} else if (self.Value is IEnumerator || // check for COM object (and fast check when we have values)
typeof(IEnumerator).IsAssignableFrom(self.GetLimitType())) { // check if we don't have a value
DynamicMetaObject ieres = new DynamicMetaObject(
MakeEnumeratorResult(
Ast.Convert(
self.Expression,
typeof(IEnumerator)
)
),
self.Restrict(self.GetLimitType()).Restrictions
);
#if FEATURE_COM
if (Microsoft.Scripting.ComInterop.ComBinder.IsComObject(self.Value)) {
ieres = new DynamicMetaObject(
MakeEnumeratorResult(
Expression.Convert(
self.Expression,
typeof(IEnumerator)
)
),
ieres.Restrictions.Merge(
BindingRestrictions.GetExpressionRestriction(
Ast.TypeIs(self.Expression, typeof(IEnumerator))
)
)
);
}
#endif
return ieres;
}
ParameterExpression tmp = Ast.Parameter(typeof(IEnumerator), "enum");
PythonConversionBinder convBinder = PythonContext.GetPythonContext(operation).Convert(typeof(IEnumerator), ConversionResultKind.ExplicitTry);
DynamicMetaObject res = self is IPythonConvertible pyConv
? pyConv.BindConvert(convBinder)
: convBinder.Bind(self, Array.Empty<DynamicMetaObject>());
return new DynamicMetaObject(
Expression.Block(
new[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(tmp, res.Expression),
AstUtils.Constant(null)
),
MakeEnumeratorResult(tmp),
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.ThrowTypeErrorForBadIteration)),
PythonContext.GetCodeContext(operation),
self.Expression
)
)
),
res.Restrictions
);
}
private static NewExpression MakeEnumeratorResult(Expression tmp) {
return Expression.New(
typeof(KeyValuePair<IEnumerator, IDisposable>).GetConstructor(new[] { typeof(IEnumerator), typeof(IDisposable) }),
tmp,
Expression.Constant(null, typeof(IDisposable))
);
}
private static DynamicMetaObject/*!*/ MakeUnaryNotOperation(DynamicMetaObjectBinder/*!*/ operation, DynamicMetaObject/*!*/ self, Type retType, DynamicMetaObject errorSuggestion) {
self = self.Restrict(self.GetLimitType());
Expression notExpr;
var res = ConvertToBool(operation, self);
if (res is null) {
// no __len__ or __bool__, for None this is always false, everything else is True. If we have
// an error suggestion though we'll go with that.
if (errorSuggestion == null) {
notExpr = (self.GetLimitType() == typeof(DynamicNull)) ? AstUtils.Constant(true) : AstUtils.Constant(false);
} else {
notExpr = errorSuggestion.Expression;
}
}
else {
Debug.Assert(res.Expression.Type == typeof(bool));
notExpr = Ast.IsFalse(res.Expression);
self = res;
}
if (retType == typeof(object) && notExpr.Type == typeof(bool)) {
notExpr = BindingHelpers.AddPythonBoxing(notExpr);
}
return new DynamicMetaObject(
notExpr,
self.Restrictions
);
}
#endregion
#region Reflective Operations
private static DynamicMetaObject/*!*/ MakeDocumentationOperation(PythonOperationBinder/*!*/ operation, DynamicMetaObject/*!*/[]/*!*/ args) {
PythonContext state = PythonContext.GetPythonContext(operation);
return new DynamicMetaObject(
Binders.Convert(
PythonContext.GetCodeContext(operation),
state,
typeof(string),
ConversionResultKind.ExplicitCast,
Binders.Get(
PythonContext.GetCodeContext(operation),
state,
typeof(object),
"__doc__",
args[0].Expression
)
),
args[0].Restrictions
);
}
internal static DynamicMetaObject/*!*/ MakeCallSignatureOperation(DynamicMetaObject/*!*/ self, IList<MethodBase/*!*/>/*!*/ targets) {
List<string> arrres = new List<string>();
foreach (MethodBase mb in targets) {
StringBuilder res = new StringBuilder();
string comma = "";
Type retType = mb.GetReturnType();
if (retType != typeof(void)) {
res.Append(DynamicHelpers.GetPythonTypeFromType(retType).Name);
res.Append(" ");
}
if (mb is MethodInfo mi) {
string name;
NameConverter.TryGetName(DynamicHelpers.GetPythonTypeFromType(mb.DeclaringType), mi, out name);
res.Append(name);
} else {
res.Append(DynamicHelpers.GetPythonTypeFromType(mb.DeclaringType).Name);
}
res.Append("(");
if (!CompilerHelpers.IsStatic(mb)) {
res.Append("self");
comma = ", ";
}
foreach (ParameterInfo pi in mb.GetParameters()) {
if (pi.ParameterType == typeof(CodeContext)) continue;
res.Append(comma);
res.Append(DynamicHelpers.GetPythonTypeFromType(pi.ParameterType).Name + " " + pi.Name);
comma = ", ";
}
res.Append(")");
arrres.Add(res.ToString());
}
return new DynamicMetaObject(
AstUtils.Constant(arrres.ToArray()),
self.Restrictions.Merge(BindingRestrictions.GetInstanceRestriction(self.Expression, self.Value))
);
}
private static DynamicMetaObject/*!*/ MakeIscallableOperation(PythonOperationBinder/*!*/ operation, DynamicMetaObject/*!*/[]/*!*/ args) {
// Certain non-python types (encountered during interop) are callable, but don't have
// a __call__ attribute. The default base binder also checks these, but since we're overriding
// the base binder, we check them here.
DynamicMetaObject self = args[0];
// only applies when called from a Python site
if (typeof(Delegate).IsAssignableFrom(self.GetLimitType()) ||
typeof(MethodGroup).IsAssignableFrom(self.GetLimitType())) {
return new DynamicMetaObject(
AstUtils.Constant(true),
self.Restrict(self.GetLimitType()).Restrictions
);
}
PythonContext state = PythonContext.GetPythonContext(operation);
Expression isCallable = Ast.NotEqual(
Binders.TryGet(
PythonContext.GetCodeContext(operation),
state,
typeof(object),
"__call__",
self.Expression
),
AstUtils.Constant(OperationFailed.Value)
);
return new DynamicMetaObject(
isCallable,
self.Restrict(self.GetLimitType()).Restrictions
);
}
#endregion
#region Common Binary Operations
private static DynamicMetaObject/*!*/ MakeSimpleOperation(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ binder, PythonOperationKind operation, DynamicMetaObject errorSuggestion) {
RestrictTypes(types);
SlotOrFunction fbinder;
SlotOrFunction rbinder;
PythonTypeSlot fSlot;
PythonTypeSlot rSlot;
GetOperatorMethods(types, operation, PythonContext.GetPythonContext(binder), out fbinder, out rbinder, out fSlot, out rSlot);
return MakeBinaryOperatorResult(types, binder, operation, fbinder, rbinder, fSlot, rSlot, errorSuggestion);
}
private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, PythonOperationKind oper, PythonContext state, out SlotOrFunction fbinder, out SlotOrFunction rbinder, out PythonTypeSlot fSlot, out PythonTypeSlot rSlot) {
oper &= ~PythonOperationKind.InPlace;
string op, rop;
if (!IsReverseOperator(oper)) {
op = Symbols.OperatorToSymbol(oper);
rop = Symbols.OperatorToReversedSymbol(oper);
} else {
// coming back after coercion, just try reverse operator.
rop = Symbols.OperatorToSymbol(oper);
op = Symbols.OperatorToReversedSymbol(oper);
}
fSlot = null;
rSlot = null;
PythonType fParent, rParent;
bool isSequence = IsSequence(types[0]);
if (oper == PythonOperationKind.Multiply &&
isSequence &&
!PythonOps.IsNonExtensibleNumericType(types[1].GetLimitType())) {
// class M:
// def __rmul__(self, other):
// print("CALLED")
// return 1
//
// print [1,2] * M()
//
// in CPython this results in a successful call to __rmul__ on the type ignoring the forward
// multiplication. But calling the __mul__ method directly does NOT return NotImplemented like
// one might expect. Therefore we explicitly convert the MetaObject argument into an Index
// for binding purposes. That allows this to work at multiplication time but not with
// a direct call to __mul__.
DynamicMetaObject[] newTypes = new DynamicMetaObject[2];
newTypes[0] = types[0];
newTypes[1] = new DynamicMetaObject(
Ast.New(
typeof(Index).GetConstructor(new Type[] { typeof(object) }),
AstUtils.Convert(types[1].Expression, typeof(object))
),
BindingRestrictions.Empty
);
types = newTypes;
}
if (!SlotOrFunction.TryGetBinder(state, types, op, null, out fbinder, out fParent)) {
foreach (PythonType pt in MetaPythonObject.GetPythonType(types[0]).ResolutionOrder) {
if (pt.TryLookupSlot(state.SharedContext, op, out fSlot)) {
fParent = pt;
break;
}
}
}
if (!SlotOrFunction.TryGetBinder(state, types, null, rop, out rbinder, out rParent)) {
foreach (PythonType pt in MetaPythonObject.GetPythonType(types[1]).ResolutionOrder) {
if (pt.TryLookupSlot(state.SharedContext, rop, out rSlot)) {
rParent = pt;
break;
}
}
}
// TODO: this is incorrect - if the rslot returns NotImplemented then fslot is never called and a TypeError will be raised (https://github.com/IronLanguages/ironpython3/issues/1479)
if (fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && rParent.IsSubclassOf(fParent)) {
// Python says if x + subx and subx defines __r*__ we should call r*.
fbinder = SlotOrFunction.Empty;
fSlot = null;
}
// TODO: this is incorrect - if the rslot returns NotImplemented then fslot is never called and a TypeError will be raised (https://github.com/IronLanguages/ironpython3/issues/560)
if (oper == PythonOperationKind.Add && fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && isSequence) {
// if the left operand is a sequence and the right operand defines __radd__, we should call __radd__.
fbinder = SlotOrFunction.Empty;
fSlot = null;
}
}
private static bool IsReverseOperator(PythonOperationKind oper) {
return (oper & PythonOperationKind.Reversed) != 0;
}
private static bool IsSequence(DynamicMetaObject/*!*/ metaObject) {
var limitType = metaObject.GetLimitType();
if (typeof(PythonList).IsAssignableFrom(limitType) ||
typeof(PythonTuple).IsAssignableFrom(limitType) ||
typeof(ByteArray).IsAssignableFrom(limitType) ||
typeof(Bytes).IsAssignableFrom(limitType) ||
typeof(string).IsAssignableFrom(limitType)) {
return true;
}
return false;
}
private static DynamicMetaObject/*!*/ MakeBinaryOperatorResult(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ operation, PythonOperationKind op, SlotOrFunction/*!*/ fCand, SlotOrFunction/*!*/ rCand, PythonTypeSlot fSlot, PythonTypeSlot rSlot, DynamicMetaObject errorSuggestion) {
Assert.NotNull(operation, fCand, rCand);
SlotOrFunction fTarget, rTarget;
PythonContext state = PythonContext.GetPythonContext(operation);
ConditionalBuilder bodyBuilder = new ConditionalBuilder(operation);
if ((op & PythonOperationKind.InPlace) != 0) {
// in place operator, see if there's a specific method that handles it.
SlotOrFunction function = SlotOrFunction.GetSlotOrFunction(PythonContext.GetPythonContext(operation), Symbols.OperatorToSymbol(op), types);
// we don't do a coerce for in place operators if the lhs implements __iop__
if (!MakeOneCompareGeneric(function, false, types, MakeCompareReturn, bodyBuilder, typeof(object))) {
// the method handles it and always returns a useful value.
return bodyBuilder.GetMetaObject(types);
}
}
if (!SlotOrFunction.GetCombinedTargets(fCand, rCand, out fTarget, out rTarget) &&
fSlot == null &&
rSlot == null &&
bodyBuilder.NoConditions) {
return MakeRuleForNoMatch(operation, op, errorSuggestion, types);
}
if (MakeOneTarget(PythonContext.GetPythonContext(operation), fTarget, fSlot, bodyBuilder, false, types)) {
if (rSlot != null) {
MakeSlotCall(PythonContext.GetPythonContext(operation), types, bodyBuilder, rSlot, true);
bodyBuilder.FinishCondition(MakeBinaryThrow(operation, op, types).Expression, typeof(object));
} else if (MakeOneTarget(PythonContext.GetPythonContext(operation), rTarget, rSlot, bodyBuilder, false, types)) {
// need to fallback to throwing or coercion
bodyBuilder.FinishCondition(MakeBinaryThrow(operation, op, types).Expression, typeof(object));
}
}
return bodyBuilder.GetMetaObject(types);
}
private static void MakeCompareReturn(ConditionalBuilder/*!*/ bodyBuilder, Expression retCondition, Expression/*!*/ retValue, bool isReverse, Type retType) {
if (retCondition != null) {
bodyBuilder.AddCondition(retCondition, retValue);
} else {
bodyBuilder.FinishCondition(retValue, retType);
}
}
/// <summary>
/// Delegate for finishing the comparison. This takes in a condition and a return value and needs to update the ConditionalBuilder
/// with the appropriate resulting body. The condition may be null.
/// </summary>
private delegate void ComparisonHelper(ConditionalBuilder/*!*/ bodyBuilder, Expression retCondition, Expression/*!*/ retValue, bool isReverse, Type retType);
/// <summary>
/// Helper to handle a comparison operator call. Checks to see if the call can
/// return NotImplemented and allows the caller to modify the expression that
/// is ultimately returned (e.g. to turn __cmp__ into a bool after a comparison)
/// </summary>
private static bool MakeOneCompareGeneric(SlotOrFunction/*!*/ target, bool reverse, DynamicMetaObject/*!*/[]/*!*/ types, ComparisonHelper returner, ConditionalBuilder/*!*/ bodyBuilder, Type retType) {
if (target == SlotOrFunction.Empty || !target.Success) return true;
ParameterExpression tmp;
if (target.ReturnType == typeof(bool)) {
tmp = bodyBuilder.CompareRetBool;
} else {
tmp = Ast.Variable(target.ReturnType, "compareRetValue");
bodyBuilder.AddVariable(tmp);
}
if (target.MaybeNotImplemented) {
Expression call = target.Target.Expression;
Expression assign = Ast.Assign(tmp, call);
returner(
bodyBuilder,
Ast.NotEqual(
assign,
AstUtils.Constant(PythonOps.NotImplemented)
),
tmp,
reverse,
retType);
return true;
} else {
returner(
bodyBuilder,
null,
target.Target.Expression,
reverse,
retType
);
return false;
}
}
private static bool MakeOneTarget(PythonContext/*!*/ state, SlotOrFunction/*!*/ target, PythonTypeSlot slotTarget, ConditionalBuilder/*!*/ bodyBuilder, bool reverse, DynamicMetaObject/*!*/[]/*!*/ types) {
if (target == SlotOrFunction.Empty && slotTarget == null) return true;
if (slotTarget != null) {
MakeSlotCall(state, types, bodyBuilder, slotTarget, reverse);
return true;
} else if (target.MaybeNotImplemented) {
Debug.Assert(target.ReturnType == typeof(object));
ParameterExpression tmp = Ast.Variable(typeof(object), "slot");
bodyBuilder.AddVariable(tmp);
bodyBuilder.AddCondition(
Ast.NotEqual(
Ast.Assign(
tmp,
target.Target.Expression
),
Ast.Property(null, typeof(PythonOps).GetProperty(nameof(PythonOps.NotImplemented)))
),
tmp
);
return true;
} else {
bodyBuilder.FinishCondition(target.Target.Expression, typeof(object));
return false;
}
}
private static void MakeSlotCall(PythonContext/*!*/ state, DynamicMetaObject/*!*/[]/*!*/ types, ConditionalBuilder/*!*/ bodyBuilder, PythonTypeSlot/*!*/ slotTarget, bool reverse) {
Debug.Assert(slotTarget != null);
Expression self, other;
if (reverse) {
self = types[1].Expression;
other = types[0].Expression;
} else {
self = types[0].Expression;
other = types[1].Expression;
}
MakeSlotCallWorker(state, slotTarget, self, bodyBuilder, other);
}
private static void MakeSlotCallWorker(PythonContext/*!*/ state, PythonTypeSlot/*!*/ slotTarget, Expression/*!*/ self, ConditionalBuilder/*!*/ bodyBuilder, params Expression/*!*/[]/*!*/ args) {
// Generate:
//
// SlotTryGetValue(context, slot, selfType, out callable) && (tmp=callable(args)) != NotImplemented) ?
// tmp :
// RestOfOperation
//
ParameterExpression callable = Ast.Variable(typeof(object), "slot");
ParameterExpression tmp = Ast.Variable(typeof(object), "slot");
bodyBuilder.AddCondition(
Ast.AndAlso(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTryGetValue)),
AstUtils.Constant(state.SharedContext),
AstUtils.Convert(Utils.WeakConstant(slotTarget), typeof(PythonTypeSlot)),
AstUtils.Convert(self, typeof(object)),
Ast.Call(
typeof(DynamicHelpers).GetMethod(nameof(DynamicHelpers.GetPythonType)),
AstUtils.Convert(self, typeof(object))
),
callable
),
Ast.NotEqual(
Ast.Assign(
tmp,
DynamicExpression.Dynamic(
state.Invoke(
new CallSignature(args.Length)
),
typeof(object),
ArrayUtils.Insert(AstUtils.Constant(state.SharedContext), (Expression)callable, args)
)
),
Ast.Property(null, typeof(PythonOps).GetProperty(nameof(PythonOps.NotImplemented)))
)
),
tmp
);
bodyBuilder.AddVariable(callable);
bodyBuilder.AddVariable(tmp);
}
#endregion
#region Comparison Operations
private static DynamicMetaObject/*!*/ MakeComparisonOperation(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ operation, PythonOperationKind op, DynamicMetaObject errorSuggestion) {
RestrictTypes(types);
PythonContext state = PythonContext.GetPythonContext(operation);
Debug.Assert(types.Length == 2);
DynamicMetaObject xType = types[0], yType = types[1];
string opSym = Symbols.OperatorToSymbol(op);
string ropSym = Symbols.OperatorToReversedSymbol(op);
// reverse
DynamicMetaObject[] rTypes = new DynamicMetaObject[] { types[1], types[0] };
SlotOrFunction fop = SlotOrFunction.GetSlotOrFunction(state, opSym, types);
SlotOrFunction rop = SlotOrFunction.GetSlotOrFunction(state, ropSym, rTypes);
ConditionalBuilder bodyBuilder = new ConditionalBuilder(operation);
SlotOrFunction.GetCombinedTargets(fop, rop, out fop, out rop);
bool shouldWarn = false;