forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEngineTest.cs
More file actions
2756 lines (2195 loc) · 109 KB
/
EngineTest.cs
File metadata and controls
2756 lines (2195 loc) · 109 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.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
#if FEATURE_REMOTING
using System.Security.Policy;
#endif
using System.Text;
using System.Threading;
#if FEATURE_WPF
using System.Windows.Markup;
#endif
using Microsoft.Scripting;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Runtime;
using IronPython;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using NUnit.Framework;
#if FEATURE_WPF
using DependencyObject = System.Windows.DependencyObject;
#endif
[assembly: ExtensionType(typeof(IronPythonTest.IFooable), typeof(IronPythonTest.FooableExtensions))]
namespace IronPythonTest {
internal class Common {
public static string RootDirectory;
public static string RuntimeDirectory;
public static string ScriptTestDirectory;
public static string InputTestDirectory;
static Common() {
RuntimeDirectory = Path.GetDirectoryName(typeof(PythonContext).Assembly.Location);
RootDirectory = FindRoot();
ScriptTestDirectory = Path.Combine(RootDirectory, "Tests");
InputTestDirectory = Path.Combine(ScriptTestDirectory, "Inputs");
}
private static string FindRoot() {
// we start at the current directory and look up until we find the "Src" directory
var current = System.Reflection.Assembly.GetExecutingAssembly().Location;
var found = false;
while (!found && !string.IsNullOrEmpty(current)) {
var test = Path.Combine(current, "Src", "StdLib", "Lib");
if (Directory.Exists(test)) {
return current;
}
current = Path.GetDirectoryName(current);
}
return string.Empty;
}
}
public static class TestHelpers {
public static LanguageContext GetContext(CodeContext context) {
return context.LanguageContext;
}
public static int HashObject(object o) {
return o.GetHashCode();
}
}
public delegate int IntIntDelegate(int arg);
public delegate string RefStrDelegate(ref string arg);
public delegate int RefIntDelegate(ref int arg);
public delegate T GenericDelegate<T, U, V>(U arg1, V arg2);
#if FEATURE_WPF
[ContentProperty("Content")]
public class XamlTestObject : DependencyObject {
public event IntIntDelegate Event;
public int Method(int arg) {
if (Event != null)
return Event(arg);
return -1;
}
public object Content {
get;
set;
}
}
[ContentProperty("Content")]
[RuntimeNameProperty("MyName")]
public class InnerXamlTextObject : DependencyObject {
public object Content {
get;
set;
}
public string MyName {
get;
set;
}
}
[ContentProperty("Content")]
[RuntimeNameProperty("Name")]
public class InnerXamlTextObject2 : DependencyObject {
public object Content {
get;
set;
}
public string Name {
get;
set;
}
}
#endif
public class ClsPart {
public int Field;
private int m_property;
public int Property { get { return m_property; } set { m_property = value; } }
public event IntIntDelegate Event;
public int Method(int arg) {
if (Event != null)
return Event(arg);
else
return -1;
}
// Private members
#pragma warning disable 169
// This field is accessed from the test
private int privateField;
private int privateProperty { get { return m_property; } set { m_property = value; } }
private event IntIntDelegate privateEvent;
private int privateMethod(int arg) {
if (privateEvent != null)
return privateEvent(arg);
else
return -1;
}
private static int privateStaticMethod() {
return 100;
}
#pragma warning restore 169
}
internal class InternalClsPart {
#pragma warning disable 649
// This field is accessed from the test
internal int Field;
#pragma warning restore 649
private int m_property;
internal int Property { get { return m_property; } set { m_property = value; } }
internal event IntIntDelegate Event;
internal int Method(int arg) {
if (Event != null)
return Event(arg);
else
return -1;
}
}
public class EngineTest
#if FEATURE_REMOTING
: MarshalByRefObject
#endif
{
private readonly ScriptEngine _pe;
private readonly ScriptRuntime _env;
public EngineTest() {
// Load a script with all the utility functions that are required
// pe.ExecuteFile(InputTestDirectory + "\\EngineTests.py");
_env = Python.CreateRuntime();
_pe = _env.GetEngine("py");
}
// Used to test exception thrown in another domain can be shown correctly.
public void Run(string script) {
ScriptScope scope = _env.CreateScope();
_pe.CreateScriptSourceFromString(script, SourceCodeKind.File).Execute(scope);
}
private static readonly string clspartName = "clsPart";
#if FEATURE_REMOTING
public void ScenarioHostingHelpers() {
AppDomain remote = AppDomain.CreateDomain("foo");
Dictionary<string, object> options = new Dictionary<string,object>();
// DLR ScriptRuntime options
options["Debug"] = true;
options["PrivateBinding"] = true;
// python options
options["StripDocStrings"] = true;
options["Optimize"] = true;
options["RecursionLimit"] = 42;
options["IndentationInconsistencySeverity"] = Severity.Warning;
options["WarningFilters"] = new string[] { "warnonme" };
ScriptEngine engine1 = Python.CreateEngine();
ScriptEngine engine2 = Python.CreateEngine(AppDomain.CurrentDomain);
ScriptEngine engine3 = Python.CreateEngine(remote);
TestEngines(null, new ScriptEngine[] { engine1, engine2, engine3 });
ScriptEngine engine4 = Python.CreateEngine(options);
ScriptEngine engine5 = Python.CreateEngine(AppDomain.CurrentDomain, options);
ScriptEngine engine6 = Python.CreateEngine(remote, options);
TestEngines(options, new ScriptEngine[] { engine4, engine5, engine6 });
ScriptRuntime runtime1 = Python.CreateRuntime();
ScriptRuntime runtime2 = Python.CreateRuntime(AppDomain.CurrentDomain);
ScriptRuntime runtime3 = Python.CreateRuntime(remote);
TestRuntimes(null, new ScriptRuntime[] { runtime1, runtime2, runtime3 });
ScriptRuntime runtime4 = Python.CreateRuntime(options);
ScriptRuntime runtime5 = Python.CreateRuntime(AppDomain.CurrentDomain, options);
ScriptRuntime runtime6 = Python.CreateRuntime(remote, options);
TestRuntimes(options, new ScriptRuntime[] { runtime4, runtime5, runtime6 });
}
private void TestEngines(Dictionary<string, object> options, ScriptEngine[] engines) {
foreach (ScriptEngine engine in engines) {
TestEngine(engine, options);
TestRuntime(engine.Runtime, options);
}
}
private void TestRuntimes(Dictionary<string, object> options, ScriptRuntime[] runtimes) {
foreach (ScriptRuntime runtime in runtimes) {
TestRuntime(runtime, options);
TestEngine(Python.GetEngine(runtime), options);
}
}
private void TestEngine(ScriptEngine scriptEngine, Dictionary<string, object> options) {
// basic smoke tests that the engine is alive and working
Assert.AreEqual((int)(object)scriptEngine.Execute("42"), 42);
if(options != null) {
// TODO:
#pragma warning disable 618 // obsolete API
PythonOptions po = (PythonOptions)Microsoft.Scripting.Hosting.Providers.HostingHelpers.CallEngine<object, LanguageOptions>(
scriptEngine,
(lc, obj) => lc.Options,
null
);
#pragma warning restore 618
Assert.AreEqual(po.StripDocStrings, true);
Assert.AreEqual(po.Optimize, true);
Assert.AreEqual(po.RecursionLimit, 42);
Assert.AreEqual(po.IndentationInconsistencySeverity, Severity.Warning);
Assert.AreEqual(po.WarningFilters[0], "warnonme");
}
Assert.AreEqual(Python.GetSysModule(scriptEngine).GetVariable<string>("platform"), "cli");
Assert.AreEqual(Python.GetBuiltinModule(scriptEngine).GetVariable<bool>("True"), true);
if(System.Environment.OSVersion.Platform == System.PlatformID.Unix) {
Assert.AreEqual(Python.ImportModule(scriptEngine, "posix").GetVariable<int>("F_OK"), 0);
} else {
Assert.AreEqual(Python.ImportModule(scriptEngine, "nt").GetVariable<int>("F_OK"), 0);
}
Assert.Throws<ImportException>(() => {
Python.ImportModule(scriptEngine, "non_existant_module");
});
}
private void TestRuntime(ScriptRuntime runtime, Dictionary<string, object> options) {
// basic smoke tests that the runtime is alive and working
runtime.Globals.SetVariable("hello", 42);
Assert.NotNull(runtime.GetEngine("py"));
if (options != null) {
Assert.AreEqual(runtime.Setup.DebugMode, true);
Assert.AreEqual(runtime.Setup.PrivateBinding, true);
}
Assert.AreEqual(Python.GetSysModule(runtime).GetVariable<string>("platform"), "cli");
Assert.AreEqual(Python.GetBuiltinModule(runtime).GetVariable<bool>("True"), true);
if(System.Environment.OSVersion.Platform == System.PlatformID.Unix) {
Assert.AreEqual(Python.ImportModule(runtime, "posix").GetVariable<int>("F_OK"), 0);
} else {
Assert.AreEqual(Python.ImportModule(runtime, "nt").GetVariable<int>("F_OK"), 0);
}
Assert.Throws<ImportException>(() => {
Python.ImportModule(runtime, "non_existant_module");
});
}
#endif
public class ScopeDynamicObject : DynamicObject {
internal readonly Dictionary<string, object> _members = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result) {
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
_members[binder.Name] = value;
return true;
}
public override bool TryDeleteMember(DeleteMemberBinder binder) {
return _members.Remove(binder.Name);
}
}
public class ScopeDynamicObject2 : ScopeDynamicObject {
public readonly object __doc__ = null;
}
public class ScopeDynamicObject3 : ScopeDynamicObject {
public object __doc__ {
get {
return null;
}
}
}
public class ScopeDynamicObject4 : ScopeDynamicObject {
private object _doc;
public object __doc__ {
get {
return _doc;
}
set {
_doc = value;
}
}
}
public class ScopeDynamicObject5 : ScopeDynamicObject {
public object __doc__;
}
public class ScopeDynamicObject6 : ScopeDynamicObject {
public void __doc__() {
}
}
public class ScopeDynamicObject7 : ScopeDynamicObject {
public class __doc__ {
}
}
public class ScopeDynamicObject8 : ScopeDynamicObject {
#pragma warning disable 67
public event EventHandler __doc__;
#pragma warning restore 67
}
public void ScenarioDynamicObjectAsScope() {
var engine = Python.CreateEngine();
// tests where __doc__ gets assigned into the members dictionary
foreach (var myScope in new ScopeDynamicObject[] { new ScopeDynamicObject(), new ScopeDynamicObject2(), new ScopeDynamicObject3(), new ScopeDynamicObject6(), new ScopeDynamicObject7(), new ScopeDynamicObject8() }) {
var scope = engine.CreateScope(myScope);
engine.Execute(@"
x = 42", scope);
var source = engine.CreateScriptSourceFromString("x = 42", SourceCodeKind.File);
source.Compile().Execute(scope);
Assert.AreEqual(myScope._members.ContainsKey("__doc__"), true);
Assert.AreEqual(myScope._members.ContainsKey("x"), true);
Assert.AreEqual(myScope._members.ContainsKey("__file__"), true);
source = engine.CreateScriptSourceFromString("'hello world'", SourceCodeKind.File);
source.Compile().Execute(scope);
Assert.AreEqual(myScope._members["__doc__"], "hello world");
}
// tests where __doc__ gets assigned into a field/property
{
ScopeDynamicObject myScope = new ScopeDynamicObject4();
var scope = engine.CreateScope(myScope);
var source = engine.CreateScriptSourceFromString("'hello world'\nx=42\n", SourceCodeKind.File);
source.Compile().Execute(scope);
Assert.AreEqual(((ScopeDynamicObject4)myScope).__doc__, "hello world");
myScope = new ScopeDynamicObject5();
scope = engine.CreateScope(myScope);
source.Compile().Execute(scope);
Assert.AreEqual(((ScopeDynamicObject5)myScope).__doc__, "hello world");
}
}
public void ScenarioCodePlex20472() {
try {
string fileName = Path.Combine(Path.Combine(System.IO.Directory.GetCurrentDirectory(), "encoded_files"), "cp20472.py");
_pe.CreateScriptSourceFromFile(fileName, System.Text.Encoding.GetEncoding(1251));
//Disabled. The line above should have thrown a syntax exception or an import error,
//but does not.
//throw new Exception("ScenarioCodePlex20472");
}
catch (IronPython.Runtime.Exceptions.ImportException) { }
}
public void ScenarioInterpreterNestedVariables() {
ParameterExpression arg = Expression.Parameter(typeof(object), "tmp");
var argBody = Expression.Lambda<Func<object, IRuntimeVariables>>(
Expression.RuntimeVariables(
arg
),
arg
);
var vars = CompilerHelpers.LightCompile(argBody)(42);
Assert.AreEqual(vars[0], 42);
ParameterExpression tmp = Expression.Parameter(typeof(object), "tmp");
var body = Expression.Lambda<Func<object>>(
Expression.Block(
Expression.Block(
new[] { tmp },
Expression.Assign(tmp, Expression.Constant(42, typeof(object)))
),
Expression.Block(
new[] { tmp },
tmp
)
)
);
Assert.AreEqual(body.Compile()(), null);
Assert.AreEqual(CompilerHelpers.LightCompile(body)(), null);
body = Expression.Lambda<Func<object>>(
Expression.Block(
Expression.Block(
new[] { tmp },
Expression.Block(
Expression.Assign(tmp, Expression.Constant(42, typeof(object))),
Expression.Block(
new[] { tmp },
tmp
)
)
)
)
);
Assert.AreEqual(CompilerHelpers.LightCompile(body)(), null);
Assert.AreEqual(body.Compile()(), null);
}
public class TestCodePlex23562 {
public bool MethodCalled = false;
public TestCodePlex23562() {
}
public void TestMethod() {
MethodCalled = true;
}
}
public void ScenarioCodePlex23562()
{
string pyCode = @"
test = TestCodePlex23562()
test.TestMethod()
";
var scope = _pe.CreateScope();
scope.SetVariable("TestCodePlex23562", typeof(TestCodePlex23562));
_pe.Execute(pyCode, scope);
TestCodePlex23562 temp = scope.GetVariable<TestCodePlex23562>("test");
Assert.True(temp.MethodCalled);
}
public void ScenarioCodePlex18595() {
string pyCode = @"
str_tuple = ('ab', 'cd')
str_list = ['abc', 'def', 'xyz']
py_func_called = False
def py_func():
global py_func_called
py_func_called = True
";
var scope = _pe.CreateScope();
_pe.Execute(pyCode, scope);
IList<string> str_tuple = scope.GetVariable<IList<string>>("str_tuple");
Assert.AreEqual(str_tuple.Count, 2);
IList<string> str_list = scope.GetVariable<IList<string>>("str_list");
Assert.AreEqual(str_list.Count, 3);
VoidDelegate py_func = scope.GetVariable<VoidDelegate>("py_func");
py_func();
Assert.AreEqual(scope.GetVariable<bool>("py_func_called"), true);
}
public void ScenarioCodePlex24077()
{
string pyCode = @"
class K(object):
def __init__(self, a, b, c):
global A, B, C
A = a
B = b
C = c
";
var scope = _pe.CreateScope();
_pe.Execute(pyCode, scope);
object KKlass = scope.GetVariable("K");
object[] Kparams = new object[] { 1, 3.14, "abc"};
_pe.Operations.CreateInstance(KKlass, Kparams);
Assert.AreEqual(scope.GetVariable<int>("A"), 1);
}
// Execute
public void ScenarioExecute() {
ClsPart clsPart = new ClsPart();
ScriptScope scope = _env.CreateScope();
scope.SetVariable(clspartName, clsPart);
// field: assign and get back
_pe.Execute("clsPart.Field = 100", scope);
_pe.Execute("if 100 != clsPart.Field: raise AssertionError('test failed')", scope);
Assert.AreEqual(100, clsPart.Field);
// property: assign and get back
_pe.Execute("clsPart.Property = clsPart.Field", scope);
_pe.Execute("if 100 != clsPart.Property: raise AssertionError('test failed')", scope);
Assert.AreEqual(100, clsPart.Property);
// method: Event not set yet
_pe.Execute("a = clsPart.Method(2)", scope);
_pe.Execute("if -1 != a: raise AssertionError('test failed')", scope);
// method: add python func as event handler
_pe.Execute("def f(x) : return x * x", scope);
_pe.Execute("clsPart.Event += f", scope);
_pe.Execute("a = clsPart.Method(2)", scope);
_pe.Execute("if 4 != a: raise AssertionError('test failed')", scope);
// ===============================================
// reset the same variable with instance of the same type
scope.SetVariable(clspartName, new ClsPart());
_pe.Execute("if 0 != clsPart.Field: raise AssertionError('test failed')", scope);
// add cls method as event handler
scope.SetVariable("clsMethod", new IntIntDelegate(Negate));
_pe.Execute("clsPart.Event += clsMethod", scope);
_pe.Execute("a = clsPart.Method(2)", scope);
_pe.Execute("if -2 != a: raise AssertionError('test failed')", scope);
// ===============================================
// reset the same variable with integer
scope.SetVariable(clspartName, 1);
_pe.Execute("if 1 != clsPart: raise AssertionError('test failed')", scope);
Assert.AreEqual((int)(object)scope.GetVariable(clspartName), 1);
ScriptSource su = _pe.CreateScriptSourceFromString("");
Assert.Throws<ArgumentNullException>(() => {
su.Execute(null);
});
}
public static void ScenarioTryGetMember() {
var engine = Python.CreateEngine();
var str = ClrModule.GetPythonType(typeof(string));
object result;
Assert.AreEqual(engine.Operations.TryGetMember(str, "Equals", out result), true);
Assert.AreEqual(result.ToString(), "IronPython.Runtime.Types.BuiltinFunction");
}
public static void ScenarioInterfaceExtensions() {
var engine = Python.CreateEngine();
engine.Runtime.LoadAssembly(typeof(Fooable).Assembly);
ScriptSource src = engine.CreateScriptSourceFromString("x.Bar()");
ScriptScope scope = engine.CreateScope();
scope.SetVariable("x", new Fooable());
Assert.AreEqual((object)src.Execute(scope), "Bar Called");
}
private class MyInvokeMemberBinder : InvokeMemberBinder {
public MyInvokeMemberBinder(string name, CallInfo callInfo)
: base(name, false, callInfo) {
}
public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
return errorSuggestion ?? new DynamicMetaObject(
Expression.Constant("FallbackInvokeMember"),
target.Restrictions.Merge(BindingRestrictions.Combine(args)).Merge(target.Restrict(target.LimitType).Restrictions)
);
}
public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Dynamic(new MyInvokeBinder(CallInfo), typeof(object), Microsoft.Scripting.Utils.DynamicUtils.GetExpressions(Microsoft.Scripting.Utils.ArrayUtils.Insert(target, args))),
target.Restrictions.Merge(BindingRestrictions.Combine(args))
);
}
}
private class MyInvokeBinder : InvokeBinder {
public MyInvokeBinder(CallInfo callInfo)
: base(callInfo) {
}
public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Call(
typeof(String).GetMethod("Concat", new Type[] { typeof(object), typeof(object) }),
Expression.Constant("FallbackInvoke"),
target.Expression
),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private class MyGetIndexBinder : GetIndexBinder {
public MyGetIndexBinder(CallInfo args)
: base(args) {
}
public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Call(
typeof(String).GetMethod("Concat", new Type[] { typeof(object), typeof(object) }),
Expression.Constant("FallbackGetIndex"),
indexes[0].Expression
),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private class MySetIndexBinder : SetIndexBinder {
public MySetIndexBinder(CallInfo args)
: base(args) {
}
public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Call(
typeof(String).GetMethod("Concat", new Type[] { typeof(object), typeof(object), typeof(object) }),
Expression.Constant("FallbackSetIndex"),
indexes[0].Expression,
value.Expression
),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private class MyGetMemberBinder : GetMemberBinder {
public MyGetMemberBinder(string name)
: base(name, false) {
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Constant("FallbackGetMember"),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private class MyInvokeBinder2 : InvokeBinder {
public MyInvokeBinder2(CallInfo args)
: base(args) {
}
public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
Expression[] exprs = new Expression[args.Length + 1];
exprs[0] = Expression.Constant("FallbackInvoke");
for (int i = 0; i < args.Length; i++) {
exprs[i + 1] = args[i].Expression;
}
return new DynamicMetaObject(
Expression.Call(
typeof(String).GetMethod("Concat", new Type[] { typeof(object[]) }),
Expression.NewArrayInit(
typeof(object),
exprs
)
),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private class MyConvertBinder : ConvertBinder {
private object _result;
public MyConvertBinder(Type type) : this(type, "Converted") {
}
public MyConvertBinder(Type type, object result)
: base(type, true) {
_result = result;
}
public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Constant(_result),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private class MyUnaryBinder : UnaryOperationBinder {
public MyUnaryBinder(ExpressionType et)
: base(et) {
}
public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
return new DynamicMetaObject(
Expression.Constant("UnaryFallback"),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
);
}
}
private void TestTarget(object sender, EventArgs args) {
}
public void ScenarioDocumentation() {
ScriptScope scope = _pe.CreateScope();
ScriptSource src = _pe.CreateScriptSourceFromString(@"
import System
import clr
def f0(a, b): pass
def f1(a, *b): pass
def f2(a, **b): pass
def f3(a, *b, **c): pass
class C:
m0 = f0
m1 = f1
m2 = f2
m3 = f3
def __init__(self):
self.foo = 42
class SC(C): pass
inst = C()
class NC(object):
m0 = f0
m1 = f1
m2 = f2
m3 = f3
def __init__(self):
self.foo = 42
class SNC(NC): pass
ncinst = C()
class EmptyNC(object): pass
enc = EmptyNC()
m0 = C.m0
m1 = C.m1
m2 = C.m2
m3 = C.m3
z = zip
i = int
", SourceCodeKind.File);
var doc = _pe.GetService<DocumentationOperations>();
src.Execute(scope);
scope.SetVariable("dlg", new EventHandler(TestTarget));
object f0 = scope.GetVariable("f0");
object f1 = scope.GetVariable("f1");
object f2 = scope.GetVariable("f2");
object f3 = scope.GetVariable("f3");
object zip = scope.GetVariable("z");
object dlg = scope.GetVariable("dlg");
object m0 = scope.GetVariable("m0");
object m1 = scope.GetVariable("m1");
object m2 = scope.GetVariable("m2");
object m3 = scope.GetVariable("m3");
var tests = new [] {
new {
Obj=f0,
Result = new [] {
new[] {
new { ParamName="a", ParamAttrs = ParameterFlags.None },
new { ParamName="b", ParamAttrs = ParameterFlags.None }
}
}
},
new {
Obj=f1,
Result = new [] {
new[] {
new { ParamName="a", ParamAttrs = ParameterFlags.None },
new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray }
}
}
},
new {
Obj=f2,
Result = new [] {
new[] {
new { ParamName="a", ParamAttrs = ParameterFlags.None },
new { ParamName="b", ParamAttrs = ParameterFlags.ParamsDict}
}
}
},
new {
Obj=f3,
Result = new [] {
new [] {
new { ParamName="a", ParamAttrs = ParameterFlags.None},
new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray},
new { ParamName="c", ParamAttrs = ParameterFlags.ParamsDict}
}
}
},
new {
Obj = zip,
Result = new [] {
new [] {
new { ParamName="s0", ParamAttrs = ParameterFlags.None },
new { ParamName="s1", ParamAttrs = ParameterFlags.None },
},
new [] {
new { ParamName="seqs", ParamAttrs = ParameterFlags.ParamsArray },
}
}
},
new {
Obj=dlg,
Result = new [] {
new [] {
new { ParamName="sender", ParamAttrs = ParameterFlags.None},
new { ParamName="e", ParamAttrs = ParameterFlags.None},
}
}
},
new {
Obj=m0,
Result = new [] {
new[] {
new { ParamName="a", ParamAttrs = ParameterFlags.None },
new { ParamName="b", ParamAttrs = ParameterFlags.None }
}
}
},
new {
Obj=m1,
Result = new [] {
new[] {
new { ParamName="a", ParamAttrs = ParameterFlags.None },
new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray }
}
}
},
new {
Obj=m2,
Result = new [] {
new[] {
new { ParamName="a", ParamAttrs = ParameterFlags.None },
new { ParamName="b", ParamAttrs = ParameterFlags.ParamsDict}
}
}
},
new {
Obj=m3,
Result = new [] {
new [] {
new { ParamName="a", ParamAttrs = ParameterFlags.None},
new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray},
new { ParamName="c", ParamAttrs = ParameterFlags.ParamsDict}
}
}
},
};
foreach (var test in tests) {
var result = new List<OverloadDoc>(doc.GetOverloads(test.Obj));
Assert.AreEqual(result.Count, test.Result.Length);
for (int i = 0; i < result.Count; i++) {
var received = result[i]; ;
var expected = test.Result[i];
Assert.AreEqual(received.Parameters.Count, expected.Length);
var recvParams = new List<ParameterDoc>(received.Parameters);
for (int j = 0; j < expected.Length; j++) {
var receivedParam = recvParams[j];
var expectedParam = expected[j];
Assert.AreEqual(receivedParam.Flags, expectedParam.ParamAttrs);
Assert.AreEqual(receivedParam.Name, expectedParam.ParamName);
}
}
}
object inst = scope.GetVariable("inst");
object ncinst = scope.GetVariable("ncinst");
object klass = scope.GetVariable("C");
object newklass = scope.GetVariable("NC");
object subklass = scope.GetVariable("SC");
object subnewklass = scope.GetVariable("SNC");
object System = scope.GetVariable("System");
object clr = scope.GetVariable("clr");
foreach (object o in new[] { inst, ncinst }) {
var members = doc.GetMembers(o);
ContainsMemberName(members, "m0", MemberKind.Method);
ContainsMemberName(members, "foo", MemberKind.None);
}
ContainsMemberName(doc.GetMembers(klass), "m0", MemberKind.Method);
ContainsMemberName(doc.GetMembers(newklass), "m0", MemberKind.Method);
ContainsMemberName(doc.GetMembers(subklass), "m0", MemberKind.Method);
ContainsMemberName(doc.GetMembers(subnewklass), "m0", MemberKind.Method);
ContainsMemberName(doc.GetMembers(System), "Collections", MemberKind.Namespace);
ContainsMemberName(doc.GetMembers(clr), "AddReference", MemberKind.Function);
object intType = scope.GetVariable("i");
foreach (object o in new object[] { intType, 42 }) {
var members = doc.GetMembers(o);
ContainsMemberName(members, "__add__", MemberKind.Method);
ContainsMemberName(members, "conjugate", MemberKind.Method);
ContainsMemberName(members, "real", MemberKind.Property);
}
ContainsMemberName(doc.GetMembers(new List<object>()), "Count", MemberKind.Property);
ContainsMemberName(doc.GetMembers(DynamicHelpers.GetPythonTypeFromType(typeof(DateTime))), "MaxValue", MemberKind.Field);
doc.GetMembers(scope.GetVariable("enc"));
}
private void ContainsMemberName(ICollection<MemberDoc> members, string name, MemberKind kind) {
foreach (var member in members) {
if (member.Name == name) {
Assert.AreEqual(member.Kind, kind);
return;
}
}
Assert.Fail("didn't find member " + name);
}
public void ScenarioDlrInterop() {
string actionOfT = typeof(Action<>).FullName.Split('`')[0];
ScriptScope scope = _env.CreateScope();
ScriptSource src = _pe.CreateScriptSourceFromString(@"
import clr
if clr.IsNetCoreApp:
clr.AddReference('System.Collections.NonGeneric')
elif not clr.IsMono:
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Control
import System
from System.Collections import ArrayList