PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/Languages/IronPython/IronPythonTest/EngineTest.cs

http://github.com/IronLanguages/main
C# | 2853 lines | 2268 code | 459 blank | 126 comment | 71 complexity | 114284ad390082b02472e0d5a624e52f MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Apache License, Version 2.0, please send an email to
  8. * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Apache License, Version 2.0.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. #if FEATURE_CORE_DLR
  16. using System.Linq.Expressions;
  17. using System.Numerics;
  18. #else
  19. using Microsoft.Scripting.Ast;
  20. using Microsoft.Scripting.Math;
  21. using Complex = Microsoft.Scripting.Math.Complex64;
  22. #endif
  23. using System;
  24. using System.Collections;
  25. using System.Collections.Generic;
  26. using System.Diagnostics;
  27. using System.Dynamic;
  28. using System.IO;
  29. using System.Reflection;
  30. using System.Runtime.CompilerServices;
  31. using System.Security;
  32. #if FEATURE_REMOTING
  33. using System.Security.Policy;
  34. #endif
  35. using System.Text;
  36. using System.Threading;
  37. #if FEATURE_WPF
  38. using System.Windows.Markup;
  39. #endif
  40. using Microsoft.Scripting;
  41. using Microsoft.Scripting.Generation;
  42. using Microsoft.Scripting.Hosting;
  43. using Microsoft.Scripting.Runtime;
  44. using Microsoft.Scripting.Utils;
  45. using IronPython;
  46. using IronPython.Hosting;
  47. using IronPython.Runtime;
  48. using IronPython.Runtime.Exceptions;
  49. using IronPython.Runtime.Operations;
  50. using IronPython.Runtime.Types;
  51. #if FEATURE_WPF
  52. using DependencyObject = System.Windows.DependencyObject;
  53. #endif
  54. [assembly: ExtensionType(typeof(IronPythonTest.IFooable), typeof(IronPythonTest.FooableExtensions))]
  55. namespace IronPythonTest {
  56. #if !SILVERLIGHT
  57. class Common {
  58. public static string RootDirectory;
  59. public static string RuntimeDirectory;
  60. public static string ScriptTestDirectory;
  61. public static string InputTestDirectory;
  62. static Common() {
  63. RuntimeDirectory = Path.GetDirectoryName(typeof(PythonContext).GetTypeInfo().Assembly.Location);
  64. RootDirectory = Environment.GetEnvironmentVariable("DLR_ROOT");
  65. if (RootDirectory != null) {
  66. ScriptTestDirectory = Path.Combine(Path.Combine(Path.Combine(RootDirectory, "Languages"), "IronPython"), "Tests");
  67. } else {
  68. RootDirectory = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Directory.FullName;
  69. ScriptTestDirectory = Path.Combine(Path.Combine(RootDirectory, "Src"), "Tests");
  70. }
  71. InputTestDirectory = Path.Combine(ScriptTestDirectory, "Inputs");
  72. }
  73. }
  74. #endif
  75. public static class TestHelpers {
  76. public static LanguageContext GetContext(CodeContext context) {
  77. return context.LanguageContext;
  78. }
  79. public static int HashObject(object o) {
  80. return o.GetHashCode();
  81. }
  82. }
  83. public delegate int IntIntDelegate(int arg);
  84. public delegate string RefStrDelegate(ref string arg);
  85. public delegate int RefIntDelegate(ref int arg);
  86. public delegate T GenericDelegate<T, U, V>(U arg1, V arg2);
  87. #if FEATURE_WPF
  88. [ContentProperty("Content")]
  89. public class XamlTestObject : DependencyObject {
  90. public event IntIntDelegate Event;
  91. public int Method(int arg) {
  92. if (Event != null)
  93. return Event(arg);
  94. else
  95. return -1;
  96. }
  97. public object Content {
  98. get;
  99. set;
  100. }
  101. }
  102. [ContentProperty("Content")]
  103. [RuntimeNameProperty("MyName")]
  104. public class InnerXamlTextObject : DependencyObject {
  105. public object Content {
  106. get;
  107. set;
  108. }
  109. public string MyName {
  110. get;
  111. set;
  112. }
  113. }
  114. [ContentProperty("Content")]
  115. [RuntimeNameProperty("Name")]
  116. public class InnerXamlTextObject2 : DependencyObject {
  117. public object Content {
  118. get;
  119. set;
  120. }
  121. public string Name {
  122. get;
  123. set;
  124. }
  125. }
  126. #endif
  127. public class ClsPart {
  128. public int Field;
  129. int m_property;
  130. public int Property { get { return m_property; } set { m_property = value; } }
  131. public event IntIntDelegate Event;
  132. public int Method(int arg) {
  133. if (Event != null)
  134. return Event(arg);
  135. else
  136. return -1;
  137. }
  138. // Private members
  139. #pragma warning disable 169
  140. // This field is accessed from the test
  141. private int privateField;
  142. private int privateProperty { get { return m_property; } set { m_property = value; } }
  143. private event IntIntDelegate privateEvent;
  144. private int privateMethod(int arg) {
  145. if (privateEvent != null)
  146. return privateEvent(arg);
  147. else
  148. return -1;
  149. }
  150. private static int privateStaticMethod() {
  151. return 100;
  152. }
  153. #pragma warning restore 169
  154. }
  155. internal class InternalClsPart {
  156. #pragma warning disable 649
  157. // This field is accessed from the test
  158. internal int Field;
  159. #pragma warning restore 649
  160. int m_property;
  161. internal int Property { get { return m_property; } set { m_property = value; } }
  162. internal event IntIntDelegate Event;
  163. internal int Method(int arg) {
  164. if (Event != null)
  165. return Event(arg);
  166. else
  167. return -1;
  168. }
  169. }
  170. public class EngineTest
  171. #if FEATURE_REMOTING
  172. : MarshalByRefObject
  173. #endif
  174. {
  175. private readonly ScriptEngine _pe;
  176. private readonly ScriptRuntime _env;
  177. public EngineTest() {
  178. // Load a script with all the utility functions that are required
  179. // pe.ExecuteFile(InputTestDirectory + "\\EngineTests.py");
  180. _env = Python.CreateRuntime();
  181. _pe = _env.GetEngine("py");
  182. }
  183. // Used to test exception thrown in another domain can be shown correctly.
  184. public void Run(string script) {
  185. ScriptScope scope = _env.CreateScope();
  186. _pe.CreateScriptSourceFromString(script, SourceCodeKind.File).Execute(scope);
  187. }
  188. static readonly string clspartName = "clsPart";
  189. /// <summary>
  190. /// Asserts an condition it true
  191. /// </summary>
  192. private static void Assert(bool condition, string msg) {
  193. if (!condition) throw new Exception(String.Format("Assertion failed: {0}", msg));
  194. }
  195. private static void Assert(bool condition) {
  196. if (!condition) throw new Exception("Assertion failed");
  197. }
  198. private static T AssertExceptionThrown<T>(Action f) where T : Exception {
  199. try {
  200. f();
  201. } catch (T ex) {
  202. return ex;
  203. }
  204. Assert(false, "Expecting exception '" + typeof(T) + "'.");
  205. return null;
  206. }
  207. #if FEATURE_REMOTING
  208. public void ScenarioHostingHelpers() {
  209. AppDomain remote = AppDomain.CreateDomain("foo");
  210. Dictionary<string, object> options = new Dictionary<string,object>();
  211. // DLR ScriptRuntime options
  212. options["Debug"] = true;
  213. options["PrivateBinding"] = true;
  214. // python options
  215. options["StripDocStrings"] = true;
  216. options["Optimize"] = true;
  217. options["DivisionOptions"] = PythonDivisionOptions.New;
  218. options["RecursionLimit"] = 42;
  219. options["IndentationInconsistencySeverity"] = Severity.Warning;
  220. options["WarningFilters"] = new string[] { "warnonme" };
  221. ScriptEngine engine1 = Python.CreateEngine();
  222. ScriptEngine engine2 = Python.CreateEngine(AppDomain.CurrentDomain);
  223. ScriptEngine engine3 = Python.CreateEngine(remote);
  224. TestEngines(null, new ScriptEngine[] { engine1, engine2, engine3 });
  225. ScriptEngine engine4 = Python.CreateEngine(options);
  226. ScriptEngine engine5 = Python.CreateEngine(AppDomain.CurrentDomain, options);
  227. ScriptEngine engine6 = Python.CreateEngine(remote, options);
  228. TestEngines(options, new ScriptEngine[] { engine4, engine5, engine6 });
  229. ScriptRuntime runtime1 = Python.CreateRuntime();
  230. ScriptRuntime runtime2 = Python.CreateRuntime(AppDomain.CurrentDomain);
  231. ScriptRuntime runtime3 = Python.CreateRuntime(remote);
  232. TestRuntimes(null, new ScriptRuntime[] { runtime1, runtime2, runtime3 });
  233. ScriptRuntime runtime4 = Python.CreateRuntime(options);
  234. ScriptRuntime runtime5 = Python.CreateRuntime(AppDomain.CurrentDomain, options);
  235. ScriptRuntime runtime6 = Python.CreateRuntime(remote, options);
  236. TestRuntimes(options, new ScriptRuntime[] { runtime4, runtime5, runtime6 });
  237. }
  238. private void TestEngines(Dictionary<string, object> options, ScriptEngine[] engines) {
  239. foreach (ScriptEngine engine in engines) {
  240. TestEngine(engine, options);
  241. TestRuntime(engine.Runtime, options);
  242. }
  243. }
  244. private void TestRuntimes(Dictionary<string, object> options, ScriptRuntime[] runtimes) {
  245. foreach (ScriptRuntime runtime in runtimes) {
  246. TestRuntime(runtime, options);
  247. TestEngine(Python.GetEngine(runtime), options);
  248. }
  249. }
  250. private void TestEngine(ScriptEngine scriptEngine, Dictionary<string, object> options) {
  251. // basic smoke tests that the engine is alive and working
  252. AreEqual((int)(object)scriptEngine.Execute("42"), 42);
  253. if(options != null) {
  254. // TODO:
  255. #pragma warning disable 618 // obsolete API
  256. PythonOptions po = (PythonOptions)Microsoft.Scripting.Hosting.Providers.HostingHelpers.CallEngine<object, LanguageOptions>(
  257. scriptEngine,
  258. (lc, obj) => lc.Options,
  259. null
  260. );
  261. #pragma warning restore 618
  262. AreEqual(po.StripDocStrings, true);
  263. AreEqual(po.Optimize, true);
  264. AreEqual(po.DivisionOptions, PythonDivisionOptions.New);
  265. AreEqual(po.RecursionLimit, 42);
  266. AreEqual(po.IndentationInconsistencySeverity, Severity.Warning);
  267. AreEqual(po.WarningFilters[0], "warnonme");
  268. }
  269. AreEqual(Python.GetSysModule(scriptEngine).GetVariable<string>("platform"), "cli");
  270. AreEqual(Python.GetBuiltinModule(scriptEngine).GetVariable<bool>("True"), true);
  271. if(System.Environment.OSVersion.Platform == System.PlatformID.Unix) {
  272. AreEqual(Python.ImportModule(scriptEngine, "posix").GetVariable<int>("F_OK"), 0);
  273. } else {
  274. AreEqual(Python.ImportModule(scriptEngine, "nt").GetVariable<int>("F_OK"), 0);
  275. }
  276. try {
  277. Python.ImportModule(scriptEngine, "non_existant_module");
  278. Assert(false);
  279. } catch (ImportException) {
  280. }
  281. }
  282. private void TestRuntime(ScriptRuntime runtime, Dictionary<string, object> options) {
  283. // basic smoke tests that the runtime is alive and working
  284. runtime.Globals.SetVariable("hello", 42);
  285. Assert(runtime.GetEngine("py") != null);
  286. if (options != null) {
  287. AreEqual(runtime.Setup.DebugMode, true);
  288. AreEqual(runtime.Setup.PrivateBinding, true);
  289. }
  290. AreEqual(Python.GetSysModule(runtime).GetVariable<string>("platform"), "cli");
  291. AreEqual(Python.GetBuiltinModule(runtime).GetVariable<bool>("True"), true);
  292. if(System.Environment.OSVersion.Platform == System.PlatformID.Unix) {
  293. AreEqual(Python.ImportModule(runtime, "posix").GetVariable<int>("F_OK"), 0);
  294. } else {
  295. AreEqual(Python.ImportModule(runtime, "nt").GetVariable<int>("F_OK"), 0);
  296. }
  297. try {
  298. Python.ImportModule(runtime, "non_existant_module");
  299. Assert(false);
  300. } catch (ImportException) {
  301. }
  302. }
  303. #endif
  304. public class ScopeDynamicObject : DynamicObject {
  305. internal readonly Dictionary<string, object> _members = new Dictionary<string, object>();
  306. public override bool TryGetMember(GetMemberBinder binder, out object result) {
  307. return _members.TryGetValue(binder.Name, out result);
  308. }
  309. public override bool TrySetMember(SetMemberBinder binder, object value) {
  310. _members[binder.Name] = value;
  311. return true;
  312. }
  313. public override bool TryDeleteMember(DeleteMemberBinder binder) {
  314. return _members.Remove(binder.Name);
  315. }
  316. }
  317. public class ScopeDynamicObject2 : ScopeDynamicObject {
  318. public readonly object __doc__ = null;
  319. }
  320. public class ScopeDynamicObject3 : ScopeDynamicObject {
  321. public object __doc__ {
  322. get {
  323. return null;
  324. }
  325. }
  326. }
  327. public class ScopeDynamicObject4 : ScopeDynamicObject {
  328. private object _doc;
  329. public object __doc__ {
  330. get {
  331. return _doc;
  332. }
  333. set {
  334. _doc = value;
  335. }
  336. }
  337. }
  338. public class ScopeDynamicObject5 : ScopeDynamicObject {
  339. public object __doc__;
  340. }
  341. public class ScopeDynamicObject6 : ScopeDynamicObject {
  342. public void __doc__() {
  343. }
  344. }
  345. public class ScopeDynamicObject7 : ScopeDynamicObject {
  346. public class __doc__ {
  347. }
  348. }
  349. public class ScopeDynamicObject8 : ScopeDynamicObject {
  350. #pragma warning disable 67
  351. public event EventHandler __doc__;
  352. #pragma warning restore 67
  353. }
  354. public void ScenarioDynamicObjectAsScope() {
  355. var engine = Python.CreateEngine();
  356. // tests where __doc__ gets assigned into the members dictionary
  357. foreach (var myScope in new ScopeDynamicObject[] { new ScopeDynamicObject(), new ScopeDynamicObject2(), new ScopeDynamicObject3(), new ScopeDynamicObject6(), new ScopeDynamicObject7(), new ScopeDynamicObject8() }) {
  358. var scope = engine.CreateScope(myScope);
  359. engine.Execute(@"
  360. x = 42", scope);
  361. var source = engine.CreateScriptSourceFromString("x = 42", SourceCodeKind.File);
  362. source.Compile().Execute(scope);
  363. AreEqual(myScope._members.ContainsKey("__doc__"), true);
  364. AreEqual(myScope._members.ContainsKey("x"), true);
  365. AreEqual(myScope._members.ContainsKey("__file__"), true);
  366. source = engine.CreateScriptSourceFromString("'hello world'", SourceCodeKind.File);
  367. source.Compile().Execute(scope);
  368. AreEqual(myScope._members["__doc__"], "hello world");
  369. }
  370. // tests where __doc__ gets assigned into a field/property
  371. {
  372. ScopeDynamicObject myScope = new ScopeDynamicObject4();
  373. var scope = engine.CreateScope(myScope);
  374. var source = engine.CreateScriptSourceFromString("'hello world'\nx=42\n", SourceCodeKind.File);
  375. source.Compile().Execute(scope);
  376. AreEqual(((ScopeDynamicObject4)myScope).__doc__, "hello world");
  377. myScope = new ScopeDynamicObject5();
  378. scope = engine.CreateScope(myScope);
  379. source.Compile().Execute(scope);
  380. AreEqual(((ScopeDynamicObject5)myScope).__doc__, "hello world");
  381. }
  382. }
  383. #if !SILVERLIGHT
  384. public void ScenarioCodePlex20472() {
  385. try {
  386. string fileName = Path.Combine(Path.Combine(System.IO.Directory.GetCurrentDirectory(), "encoded_files"), "cp20472.py");
  387. _pe.CreateScriptSourceFromFile(fileName, System.Text.Encoding.GetEncoding(1251));
  388. //Disabled. The line above should have thrown a syntax exception or an import error,
  389. //but does not.
  390. //throw new Exception("ScenarioCodePlex20472");
  391. }
  392. catch (IronPython.Runtime.Exceptions.ImportException) { }
  393. }
  394. #endif
  395. public void ScenarioInterpreterNestedVariables() {
  396. #if !NETSTANDARD
  397. ParameterExpression arg = Expression.Parameter(typeof(object), "tmp");
  398. var argBody = Expression.Lambda<Func<object, IRuntimeVariables>>(
  399. Expression.RuntimeVariables(
  400. arg
  401. ),
  402. arg
  403. );
  404. var vars = CompilerHelpers.LightCompile(argBody)(42);
  405. AreEqual(vars[0], 42);
  406. #endif
  407. ParameterExpression tmp = Expression.Parameter(typeof(object), "tmp");
  408. var body = Expression.Lambda<Func<object>>(
  409. Expression.Block(
  410. Expression.Block(
  411. new[] { tmp },
  412. Expression.Assign(tmp, Expression.Constant(42, typeof(object)))
  413. ),
  414. Expression.Block(
  415. new[] { tmp },
  416. tmp
  417. )
  418. )
  419. );
  420. AreEqual(body.Compile()(), null);
  421. AreEqual(CompilerHelpers.LightCompile(body)(), null);
  422. body = Expression.Lambda<Func<object>>(
  423. Expression.Block(
  424. Expression.Block(
  425. new[] { tmp },
  426. Expression.Block(
  427. Expression.Assign(tmp, Expression.Constant(42, typeof(object))),
  428. Expression.Block(
  429. new[] { tmp },
  430. tmp
  431. )
  432. )
  433. )
  434. )
  435. );
  436. AreEqual(CompilerHelpers.LightCompile(body)(), null);
  437. AreEqual(body.Compile()(), null);
  438. }
  439. public void ScenarioLightExceptions() {
  440. LightExceptionTests.RunTests();
  441. }
  442. public class TestCodePlex23562 {
  443. public bool MethodCalled = false;
  444. public TestCodePlex23562() {
  445. }
  446. public void TestMethod() {
  447. MethodCalled = true;
  448. }
  449. }
  450. public void ScenarioCodePlex23562()
  451. {
  452. string pyCode = @"
  453. test = TestCodePlex23562()
  454. test.TestMethod()
  455. ";
  456. var scope = _pe.CreateScope();
  457. scope.SetVariable("TestCodePlex23562", typeof(TestCodePlex23562));
  458. _pe.Execute(pyCode, scope);
  459. TestCodePlex23562 temp = scope.GetVariable<TestCodePlex23562>("test");
  460. Assert(temp.MethodCalled);
  461. }
  462. public void ScenarioCodePlex18595() {
  463. string pyCode = @"
  464. str_tuple = ('ab', 'cd')
  465. str_list = ['abc', 'def', 'xyz']
  466. py_func_called = False
  467. def py_func():
  468. global py_func_called
  469. py_func_called = True
  470. ";
  471. var scope = _pe.CreateScope();
  472. _pe.Execute(pyCode, scope);
  473. IList<string> str_tuple = scope.GetVariable<IList<string>>("str_tuple");
  474. AreEqual<int>(str_tuple.Count, 2);
  475. IList<string> str_list = scope.GetVariable<IList<string>>("str_list");
  476. AreEqual<int>(str_list.Count, 3);
  477. VoidDelegate py_func = scope.GetVariable<VoidDelegate>("py_func");
  478. py_func();
  479. AreEqual<bool>(scope.GetVariable<bool>("py_func_called"), true);
  480. }
  481. public void ScenarioCodePlex24077()
  482. {
  483. string pyCode = @"
  484. class K(object):
  485. def __init__(self, a, b, c):
  486. global A, B, C
  487. A = a
  488. B = b
  489. C = c
  490. ";
  491. var scope = _pe.CreateScope();
  492. _pe.Execute(pyCode, scope);
  493. object KKlass = scope.GetVariable("K");
  494. object[] Kparams = new object[] { 1, 3.14, "abc"};
  495. _pe.Operations.CreateInstance(KKlass, Kparams);
  496. AreEqual<int>(scope.GetVariable<int>("A"), 1);
  497. }
  498. // Execute
  499. public void ScenarioExecute() {
  500. ClsPart clsPart = new ClsPart();
  501. ScriptScope scope = _env.CreateScope();
  502. scope.SetVariable(clspartName, clsPart);
  503. // field: assign and get back
  504. _pe.Execute("clsPart.Field = 100", scope);
  505. _pe.Execute("if 100 != clsPart.Field: raise AssertionError('test failed')", scope);
  506. AreEqual(100, clsPart.Field);
  507. // property: assign and get back
  508. _pe.Execute("clsPart.Property = clsPart.Field", scope);
  509. _pe.Execute("if 100 != clsPart.Property: raise AssertionError('test failed')", scope);
  510. AreEqual(100, clsPart.Property);
  511. // method: Event not set yet
  512. _pe.Execute("a = clsPart.Method(2)", scope);
  513. _pe.Execute("if -1 != a: raise AssertionError('test failed')", scope);
  514. // method: add python func as event handler
  515. _pe.Execute("def f(x) : return x * x", scope);
  516. _pe.Execute("clsPart.Event += f", scope);
  517. _pe.Execute("a = clsPart.Method(2)", scope);
  518. _pe.Execute("if 4 != a: raise AssertionError('test failed')", scope);
  519. // ===============================================
  520. // reset the same variable with instance of the same type
  521. scope.SetVariable(clspartName, new ClsPart());
  522. _pe.Execute("if 0 != clsPart.Field: raise AssertionError('test failed')", scope);
  523. // add cls method as event handler
  524. scope.SetVariable("clsMethod", new IntIntDelegate(Negate));
  525. _pe.Execute("clsPart.Event += clsMethod", scope);
  526. _pe.Execute("a = clsPart.Method(2)", scope);
  527. _pe.Execute("if -2 != a: raise AssertionError('test failed')", scope);
  528. // ===============================================
  529. // reset the same variable with integer
  530. scope.SetVariable(clspartName, 1);
  531. _pe.Execute("if 1 != clsPart: raise AssertionError('test failed')", scope);
  532. AreEqual((int)(object)scope.GetVariable(clspartName), 1);
  533. ScriptSource su = _pe.CreateScriptSourceFromString("");
  534. AssertExceptionThrown<ArgumentNullException>(delegate() {
  535. su.Execute(null);
  536. });
  537. }
  538. public static void ScenarioTryGetMember() {
  539. var engine = Python.CreateEngine();
  540. var str = ClrModule.GetPythonType(typeof(string));
  541. object result;
  542. AreEqual(engine.Operations.TryGetMember(str, "Equals", out result), true);
  543. AreEqual(result.ToString(), "IronPython.Runtime.Types.BuiltinFunction");
  544. }
  545. public static void ScenarioInterfaceExtensions() {
  546. var engine = Python.CreateEngine();
  547. engine.Runtime.LoadAssembly(typeof(Fooable).GetTypeInfo().Assembly);
  548. ScriptSource src = engine.CreateScriptSourceFromString("x.Bar()");
  549. ScriptScope scope = engine.CreateScope();
  550. scope.SetVariable("x", new Fooable());
  551. AreEqual((object)src.Execute(scope), "Bar Called");
  552. }
  553. class MyInvokeMemberBinder : InvokeMemberBinder {
  554. public MyInvokeMemberBinder(string name, CallInfo callInfo)
  555. : base(name, false, callInfo) {
  556. }
  557. public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
  558. return errorSuggestion ?? new DynamicMetaObject(
  559. Expression.Constant("FallbackInvokeMember"),
  560. target.Restrictions.Merge(BindingRestrictions.Combine(args)).Merge(target.Restrict(target.LimitType).Restrictions)
  561. );
  562. }
  563. public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
  564. return new DynamicMetaObject(
  565. DynamicExpression.Dynamic(new MyInvokeBinder(CallInfo), typeof(object), DynamicUtils.GetExpressions(ArrayUtils.Insert(target, args))),
  566. target.Restrictions.Merge(BindingRestrictions.Combine(args))
  567. );
  568. }
  569. }
  570. class MyInvokeBinder : InvokeBinder {
  571. public MyInvokeBinder(CallInfo callInfo)
  572. : base(callInfo) {
  573. }
  574. public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
  575. return new DynamicMetaObject(
  576. Expression.Call(
  577. typeof(String).GetMethod("Concat", new Type[] { typeof(object), typeof(object) }),
  578. Expression.Constant("FallbackInvoke"),
  579. target.Expression
  580. ),
  581. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  582. );
  583. }
  584. }
  585. class MyGetIndexBinder : GetIndexBinder {
  586. public MyGetIndexBinder(CallInfo args)
  587. : base(args) {
  588. }
  589. public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) {
  590. return new DynamicMetaObject(
  591. Expression.Call(
  592. typeof(String).GetMethod("Concat", new Type[] { typeof(object), typeof(object) }),
  593. Expression.Constant("FallbackGetIndex"),
  594. indexes[0].Expression
  595. ),
  596. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  597. );
  598. }
  599. }
  600. class MySetIndexBinder : SetIndexBinder {
  601. public MySetIndexBinder(CallInfo args)
  602. : base(args) {
  603. }
  604. public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion) {
  605. return new DynamicMetaObject(
  606. Expression.Call(
  607. typeof(String).GetMethod("Concat", new Type[] { typeof(object), typeof(object), typeof(object) }),
  608. Expression.Constant("FallbackSetIndex"),
  609. indexes[0].Expression,
  610. value.Expression
  611. ),
  612. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  613. );
  614. }
  615. }
  616. class MyGetMemberBinder : GetMemberBinder {
  617. public MyGetMemberBinder(string name)
  618. : base(name, false) {
  619. }
  620. public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
  621. return new DynamicMetaObject(
  622. Expression.Constant("FallbackGetMember"),
  623. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  624. );
  625. }
  626. }
  627. class MyInvokeBinder2 : InvokeBinder {
  628. public MyInvokeBinder2(CallInfo args)
  629. : base(args) {
  630. }
  631. public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
  632. Expression[] exprs = new Expression[args.Length + 1];
  633. exprs[0] = Expression.Constant("FallbackInvoke");
  634. for (int i = 0; i < args.Length; i++) {
  635. exprs[i + 1] = args[i].Expression;
  636. }
  637. return new DynamicMetaObject(
  638. Expression.Call(
  639. typeof(String).GetMethod("Concat", new Type[] { typeof(object[]) }),
  640. Expression.NewArrayInit(
  641. typeof(object),
  642. exprs
  643. )
  644. ),
  645. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  646. );
  647. }
  648. }
  649. class MyConvertBinder : ConvertBinder {
  650. private object _result;
  651. public MyConvertBinder(Type type) : this(type, "Converted") {
  652. }
  653. public MyConvertBinder(Type type, object result)
  654. : base(type, true) {
  655. _result = result;
  656. }
  657. public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
  658. return new DynamicMetaObject(
  659. Expression.Constant(_result),
  660. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  661. );
  662. }
  663. }
  664. class MyUnaryBinder : UnaryOperationBinder {
  665. public MyUnaryBinder(ExpressionType et)
  666. : base(et) {
  667. }
  668. public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
  669. return new DynamicMetaObject(
  670. Expression.Constant("UnaryFallback"),
  671. BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
  672. );
  673. }
  674. }
  675. private void TestTarget(object sender, EventArgs args) {
  676. }
  677. #if !SILVERLIGHT
  678. public void ScenarioDocumentation() {
  679. ScriptScope scope = _pe.CreateScope();
  680. ScriptSource src = _pe.CreateScriptSourceFromString(@"
  681. import System
  682. import clr
  683. def f0(a, b): pass
  684. def f1(a, *b): pass
  685. def f2(a, **b): pass
  686. def f3(a, *b, **c): pass
  687. class C:
  688. m0 = f0
  689. m1 = f1
  690. m2 = f2
  691. m3 = f3
  692. def __init__(self):
  693. self.foo = 42
  694. class SC(C): pass
  695. inst = C()
  696. class NC(object):
  697. m0 = f0
  698. m1 = f1
  699. m2 = f2
  700. m3 = f3
  701. def __init__(self):
  702. self.foo = 42
  703. class SNC(NC): pass
  704. ncinst = C()
  705. class EmptyNC(object): pass
  706. enc = EmptyNC()
  707. m0 = C.m0
  708. m1 = C.m1
  709. m2 = C.m2
  710. m3 = C.m3
  711. z = zip
  712. i = int
  713. ", SourceCodeKind.File);
  714. var doc = _pe.GetService<DocumentationOperations>();
  715. src.Execute(scope);
  716. scope.SetVariable("dlg", new EventHandler(TestTarget));
  717. object f0 = scope.GetVariable("f0");
  718. object f1 = scope.GetVariable("f1");
  719. object f2 = scope.GetVariable("f2");
  720. object f3 = scope.GetVariable("f3");
  721. object zip = scope.GetVariable("z");
  722. object dlg = scope.GetVariable("dlg");
  723. object m0 = scope.GetVariable("m0");
  724. object m1 = scope.GetVariable("m1");
  725. object m2 = scope.GetVariable("m2");
  726. object m3 = scope.GetVariable("m3");
  727. var tests = new [] {
  728. new {
  729. Obj=f0,
  730. Result = new [] {
  731. new[] {
  732. new { ParamName="a", ParamAttrs = ParameterFlags.None },
  733. new { ParamName="b", ParamAttrs = ParameterFlags.None }
  734. }
  735. }
  736. },
  737. new {
  738. Obj=f1,
  739. Result = new [] {
  740. new[] {
  741. new { ParamName="a", ParamAttrs = ParameterFlags.None },
  742. new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray }
  743. }
  744. }
  745. },
  746. new {
  747. Obj=f2,
  748. Result = new [] {
  749. new[] {
  750. new { ParamName="a", ParamAttrs = ParameterFlags.None },
  751. new { ParamName="b", ParamAttrs = ParameterFlags.ParamsDict}
  752. }
  753. }
  754. },
  755. new {
  756. Obj=f3,
  757. Result = new [] {
  758. new [] {
  759. new { ParamName="a", ParamAttrs = ParameterFlags.None},
  760. new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray},
  761. new { ParamName="c", ParamAttrs = ParameterFlags.ParamsDict}
  762. }
  763. }
  764. },
  765. new {
  766. Obj = zip,
  767. Result = new [] {
  768. new [] {
  769. new { ParamName="s0", ParamAttrs = ParameterFlags.None },
  770. new { ParamName="s1", ParamAttrs = ParameterFlags.None },
  771. },
  772. new [] {
  773. new { ParamName="seqs", ParamAttrs = ParameterFlags.ParamsArray },
  774. }
  775. }
  776. },
  777. new {
  778. Obj=dlg,
  779. Result = new [] {
  780. new [] {
  781. new { ParamName="sender", ParamAttrs = ParameterFlags.None},
  782. new { ParamName="e", ParamAttrs = ParameterFlags.None},
  783. }
  784. }
  785. },
  786. new {
  787. Obj=m0,
  788. Result = new [] {
  789. new[] {
  790. new { ParamName="a", ParamAttrs = ParameterFlags.None },
  791. new { ParamName="b", ParamAttrs = ParameterFlags.None }
  792. }
  793. }
  794. },
  795. new {
  796. Obj=m1,
  797. Result = new [] {
  798. new[] {
  799. new { ParamName="a", ParamAttrs = ParameterFlags.None },
  800. new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray }
  801. }
  802. }
  803. },
  804. new {
  805. Obj=m2,
  806. Result = new [] {
  807. new[] {
  808. new { ParamName="a", ParamAttrs = ParameterFlags.None },
  809. new { ParamName="b", ParamAttrs = ParameterFlags.ParamsDict}
  810. }
  811. }
  812. },
  813. new {
  814. Obj=m3,
  815. Result = new [] {
  816. new [] {
  817. new { ParamName="a", ParamAttrs = ParameterFlags.None},
  818. new { ParamName="b", ParamAttrs = ParameterFlags.ParamsArray},
  819. new { ParamName="c", ParamAttrs = ParameterFlags.ParamsDict}
  820. }
  821. }
  822. },
  823. };
  824. foreach (var test in tests) {
  825. var result = new List<OverloadDoc>(doc.GetOverloads(test.Obj));
  826. AreEqual(result.Count, test.Result.Length);
  827. for (int i = 0; i < result.Count; i++) {
  828. var received = result[i]; ;
  829. var expected = test.Result[i];
  830. AreEqual(received.Parameters.Count, expected.Length);
  831. var recvParams = new List<ParameterDoc>(received.Parameters);
  832. for (int j = 0; j < expected.Length; j++) {
  833. var receivedParam = recvParams[j];
  834. var expectedParam = expected[j];
  835. AreEqual(receivedParam.Flags, expectedParam.ParamAttrs);
  836. AreEqual(receivedParam.Name, expectedParam.ParamName);
  837. }
  838. }
  839. }
  840. object inst = scope.GetVariable("inst");
  841. object ncinst = scope.GetVariable("ncinst");
  842. object klass = scope.GetVariable("C");
  843. object newklass = scope.GetVariable("NC");
  844. object subklass = scope.GetVariable("SC");
  845. object subnewklass = scope.GetVariable("SNC");
  846. object System = scope.GetVariable("System");
  847. object clr = scope.GetVariable("clr");
  848. foreach (object o in new[] { inst, ncinst }) {
  849. var members = doc.GetMembers(o);
  850. ContainsMemberName(members, "m0", MemberKind.Method);
  851. ContainsMemberName(members, "foo", MemberKind.None);
  852. }
  853. ContainsMemberName(doc.GetMembers(klass), "m0", MemberKind.Method);
  854. ContainsMemberName(doc.GetMembers(newklass), "m0", MemberKind.Method);
  855. ContainsMemberName(doc.GetMembers(subklass), "m0", MemberKind.Method);
  856. ContainsMemberName(doc.GetMembers(subnewklass), "m0", MemberKind.Method);
  857. ContainsMemberName(doc.GetMembers(System), "Collections", MemberKind.Namespace);
  858. ContainsMemberName(doc.GetMembers(clr), "AddReference", MemberKind.Function);
  859. object intType = scope.GetVariable("i");
  860. foreach (object o in new object[] { intType, 42 }) {
  861. var members = doc.GetMembers(o);
  862. ContainsMemberName(members, "__add__", MemberKind.Method);
  863. ContainsMemberName(members, "conjugate", MemberKind.Method);
  864. ContainsMemberName(members, "real", MemberKind.Property);
  865. }
  866. ContainsMemberName(doc.GetMembers(new List<object>()), "Count", MemberKind.Property);
  867. ContainsMemberName(doc.GetMembers(DynamicHelpers.GetPythonTypeFromType(typeof(DateTime))), "MaxValue", MemberKind.Field);
  868. doc.GetMembers(scope.GetVariable("enc"));
  869. }
  870. #endif
  871. private void ContainsMemberName(ICollection<MemberDoc> members, string name, MemberKind kind) {
  872. foreach (var member in members) {
  873. if (member.Name == name) {
  874. AreEqual(member.Kind, kind);
  875. return;
  876. }
  877. }
  878. Assert(false, "didn't find member " + name);
  879. }
  880. public void ScenarioDlrInterop() {
  881. string actionOfT = typeof(Action<>).FullName.Split('`')[0];
  882. ScriptScope scope = _env.CreateScope();
  883. ScriptSource src = _pe.CreateScriptSourceFromString(@"
  884. import clr
  885. if clr.IsNetStandard:
  886. clr.AddReference('System.Collections.NonGeneric')
  887. elif not clr.IsMono:
  888. clr.AddReference('System.Windows.Forms')
  889. from System.Windows.Forms import Control
  890. import System
  891. from System.Collections import ArrayList
  892. somecallable = " + actionOfT + @"[object](lambda : 'Delegate')
  893. if not clr.IsNetStandard and not clr.IsMono:
  894. class control(Control):
  895. pass
  896. class control_setattr(Control):
  897. def __init__(self):
  898. object.__setattr__(self, 'lastset', None)
  899. def __setattr__(self, name, value):
  900. object.__setattr__(self, 'lastset', (name, value))
  901. class control_override_prop(Control):
  902. def __setattr__(self, name, value):
  903. pass
  904. def get_AllowDrop(self):
  905. return 'abc'
  906. def set_AllowDrop(self, value):
  907. super(control_setattr, self).AllowDrop.SetValue(value)
  908. class ns(object):
  909. ClassVal = 'ClassVal'
  910. def __init__(self):
  911. self.InstVal = 'InstVal'
  912. self.InstCallable = somecallable
  913. self.LastSetItem = None
  914. def __add__(self, other):
  915. return 'add' + str(other)
  916. def TestFunc(self):
  917. return 'TestFunc'
  918. def ToString(self):
  919. return 'MyToString'
  920. def NsMethod(self, *args, **kwargs):
  921. return args, kwargs
  922. @staticmethod
  923. def StaticMethod():
  924. return 'Static'
  925. @classmethod
  926. def StaticMethod(cls):
  927. return cls
  928. def __call__(self, *args, **kwargs):
  929. return args, kwargs
  930. def __int__(self): return 42
  931. def __float__(self): return 42.0
  932. def __str__(self): return 'Python'
  933. def __long__(self): return 42L
  934. def __complex__(self): return 42j
  935. def __nonzero__(self): return False
  936. def __getitem__(self, index):
  937. return index
  938. def __setitem__(self, index, value):
  939. self.LastSetItem = (index, value)
  940. SomeDelegate = somecallable
  941. class ns_getattr(object):
  942. ClassVal = 'ClassVal'
  943. def __init__(self):
  944. self.InstVal = 'InstVal'
  945. def TestFunc(self):
  946. return 'TestFunc'
  947. def __getattr__(self, name):
  948. if name == 'SomeDelegate':
  949. return somecallable
  950. elif name == 'something':
  951. return 'getattrsomething'
  952. return name
  953. class ns_getattribute(object):
  954. ClassVal = 'ClassVal'
  955. def __init__(self):
  956. self.InstVal = 'InstVal'
  957. def TestFunc(self):
  958. return 'TestFunc'
  959. def __getattribute__(self, name):
  960. if name == 'SomeDelegate':
  961. return somecallable
  962. return name
  963. class MyArrayList(ArrayList):
  964. ClassVal = 'ClassVal'
  965. def __init__(self):
  966. self.InstVal = 'InstVal'
  967. def TestFunc(self):
  968. return 'TestFunc'
  969. class MyArrayList_getattr(ArrayList):
  970. ClassVal = 'ClassVal'
  971. def __init__(self):
  972. self.InstVal = 'InstVal'
  973. def TestFunc(self):
  974. return 'TestFunc'
  975. def __getattr__(self, name):
  976. return name
  977. class MyArrayList_getattribute(ArrayList):
  978. ClassVal = 'ClassVal'
  979. def __init__(self):
  980. self.InstVal = 'InstVal'
  981. def TestFunc(self):
  982. return 'TestFunc'
  983. def __getattribute__(self, name):
  984. return name
  985. class IterableObject(object):
  986. def __iter__(self):
  987. yield 1
  988. yield 2
  989. yield 3
  990. class IterableObjectOs:
  991. def __iter__(self):
  992. yield 1
  993. yield 2
  994. yield 3
  995. class os:
  996. ClassVal = 'ClassVal'
  997. def __init__(self):
  998. self.InstVal = 'InstVal'
  999. self.InstCallable = somecallable
  1000. self.LastSetItem = None
  1001. def TestFunc(self):
  1002. return 'TestFunc'
  1003. def __call__(self, *args, **kwargs):
  1004. return args, kwargs
  1005. def __int__(self): return 42
  1006. def __float__(self): return 42.0
  1007. def __str__(self): return 'Python'
  1008. def __long__(self): return 42L
  1009. def __nonzero__(self): return False
  1010. def __complex__(self): return 42j
  1011. def __getitem__(self, index):
  1012. return index
  1013. def __setitem__(self, index, value):
  1014. self.LastSetItem = (index, value)
  1015. SomeDelegate = somecallable
  1016. class plain_os:
  1017. pass
  1018. class plain_ns(object): pass
  1019. class os_getattr:
  1020. ClassVal = 'ClassVal'
  1021. def __init__(self):
  1022. self.InstVal = 'InstVal'
  1023. def __getattr__(self, name):
  1024. if name == 'SomeDelegate':
  1025. return somecallable
  1026. return name
  1027. def TestFunc(self):
  1028. return 'TestFunc'
  1029. class ns_nonzero(object):
  1030. def __nonzero__(self):
  1031. return True
  1032. ns_nonzero_inst = ns_nonzero()
  1033. class ns_len1(object):
  1034. def __len__(self): return 1
  1035. ns_len1_inst = ns_len1()
  1036. class ns_len0(object):
  1037. def __len__(self): return 0
  1038. ns_len0_inst = ns_len0()
  1039. def TestFunc():
  1040. return 'TestFunc'
  1041. TestFunc.SubFunc = TestFunc
  1042. def Invokable(*args, **kwargs):
  1043. return args, kwargs
  1044. TestFunc.TestFunc = TestFunc
  1045. TestFunc.InstVal = 'InstVal'
  1046. TestFunc.ClassVal = 'ClassVal' # just here to simplify tests
  1047. if not clr.IsNetStandard and not clr.IsMono:
  1048. controlinst = control()
  1049. nsinst = ns()
  1050. iterable = IterableObject()
  1051. iterableos = IterableObjectOs()
  1052. plainnsinst = plain_ns()
  1053. nsmethod = nsinst.NsMethod
  1054. alinst = MyArrayList()
  1055. osinst = os()
  1056. plainosinst = plain_os()
  1057. os_getattrinst = os_getattr()
  1058. ns_getattrinst = ns_getattr()
  1059. al_getattrinst = MyArrayList_getattr()
  1060. ns_getattributeinst = ns_getattribute()
  1061. al_getattributeinst = MyArrayList_getattribute()
  1062. xrange = xrange
  1063. ", SourceCodeKind.Statements);
  1064. src.Execute(scope);
  1065. // InvokeMember tests
  1066. var allObjects = new object[] { scope.GetVariable("nsinst"), scope.GetVariable("osinst"), scope.GetVariable("alinst"), scope.GetVariable("TestFunc") };
  1067. var getattrObjects = new object[] { scope.GetVariable("ns_getattrinst"), scope.GetVariable("os_getattrinst"), scope.GetVariable("al_getattrinst") };
  1068. var getattributeObjects = new object[] { scope.GetVariable("ns_getattributeinst"), scope.GetVariable("al_getattributeinst") };
  1069. var indexableObjects = new object[] { scope.GetVariable("nsinst"), scope.GetVariable("osinst") };
  1070. var unindexableObjects = new object[] { scope.GetVariable("TestFunc"), scope.GetVariable("ns_getattrinst"), scope.GetVariable("somecallable") }; // scope.GetVariable("plainosinst"),
  1071. var invokableObjects = new object[] { scope.GetVariable("Invokable"), scope.GetVariable("nsinst"), scope.GetVariable("osinst"), scope.GetVariable("nsmethod"), };
  1072. var convertableObjects = new object[] { scope.GetVariable("nsinst"), scope.GetVariable("osinst") };
  1073. var unconvertableObjects = new object[] { scope.GetVariable("plainnsinst"), scope.GetVariable("plainosinst") };
  1074. var iterableObjects = new object[] { scope.GetVariable("iterable"), scope.GetVariable("iterableos") };
  1075. // if it lives on a system type we should do a fallback invoke member
  1076. var site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("Count", new CallInfo(0)));
  1077. AreEqual(site.Target(site, (object)scope.GetVariable("alinst")), "FallbackInvokeMember");
  1078. // invoke a function that's a member on an object
  1079. foreach (object inst in allObjects) {
  1080. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("TestFunc", new CallInfo(0)));
  1081. AreEqual(site.Target(site, inst), "TestFunc");
  1082. }
  1083. // invoke a field / property that's on an object
  1084. foreach (object inst in allObjects) {
  1085. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("InstVal", new CallInfo(0)));
  1086. AreEqual(site.Target(site, inst), "FallbackInvokeInstVal");
  1087. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("ClassVal", new CallInfo(0)));
  1088. AreEqual(site.Target(site, inst), "FallbackInvokeClassVal");
  1089. if (!(inst is PythonFunction)) {
  1090. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("SomeMethodThatNeverExists", new CallInfo(0)));
  1091. AreEqual(site.Target(site, inst), "FallbackInvokeMember");
  1092. }
  1093. }
  1094. // invoke a field / property that's not defined on objects w/ __getattr__
  1095. foreach (object inst in getattrObjects) {
  1096. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("DoesNotExist", new CallInfo(0)));
  1097. AreEqual(site.Target(site, inst), "FallbackInvokeDoesNotExist");
  1098. }
  1099. // invoke a field / property that's not defined on objects w/ __getattribute__
  1100. foreach (object inst in getattributeObjects) {
  1101. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("DoesNotExist", new CallInfo(0)));
  1102. AreEqual(site.Target(site, inst), "FallbackInvokeDoesNotExist");
  1103. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("Count", new CallInfo(0)));
  1104. AreEqual(site.Target(site, inst), "FallbackInvokeCount");
  1105. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("TestFunc", new CallInfo(0)));
  1106. AreEqual(site.Target(site, inst), "FallbackInvokeTestFunc");
  1107. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("InstVal", new CallInfo(0)));
  1108. AreEqual(site.Target(site, inst), "FallbackInvokeInstVal");
  1109. site = CallSite<Func<CallSite, object, object>>.Create(new MyInvokeMemberBinder("ClassVal", new CallInfo(0)));
  1110. AreEqual(site.Target(site, inst), "FallbackInvokeClassVal");
  1111. }
  1112. foreach (object inst in indexableObjects) {
  1113. var site2 = CallSite<Func<CallSite, object, object, object>>.Create(new MyGetIndexBinder(new CallInfo(1)));
  1114. AreEqual(site2.Target(site2, inst, "index"), "index");
  1115. var site3 = CallSite<Func<CallSite, object, object, object, object>>.Create(new MySetIndexBinder(new CallInfo(1)));
  1116. AreEqual(site3.Target(site3, inst, "index", "value"), "value");
  1117. site = CallSite<Func<CallSite, object, object>>.Create(new MyGetMemberBinder("LastSetItem"));
  1118. IList<object> res = (IList<object>)site.Target(site, inst);
  1119. AreEqual(res.Count, 2);
  1120. AreEqual(res[0], "index");
  1121. AreEqual(res[1], "value");
  1122. }
  1123. foreach (object inst in unindexableObjects) {
  1124. var site2 = CallSite<Func<CallSite, object, object, object>>.Create(new MyGetIndexBinder(new CallInfo(1)));
  1125. //Console.WriteLine(inst);
  1126. AreEqual(site2.Target(site2, inst, "index"), "FallbackGetIndexindex");
  1127. var sit

Large files files are truncated, but you can click here to view the full file