PageRenderTime 67ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/IronPython_2_6/Src/IronPython/Runtime/Operations/PythonOps.cs

#
C# | 4377 lines | 3188 code | 789 blank | 400 comment | 892 complexity | 6829dd2918e59b7e57b120c59ff5cf0f MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0
  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Microsoft Public License. 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 Microsoft Public License, 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 Microsoft Public License.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. #if !CLR2
  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.Reflection.Emit;
  31. using System.Runtime.CompilerServices;
  32. using System.Runtime.InteropServices;
  33. using System.Text;
  34. using System.Threading;
  35. using Microsoft.Scripting;
  36. using Microsoft.Scripting.Actions;
  37. using Microsoft.Scripting.Generation;
  38. using Microsoft.Scripting.Hosting.Providers;
  39. using Microsoft.Scripting.Hosting.Shell;
  40. using Microsoft.Scripting.Runtime;
  41. using Microsoft.Scripting.Utils;
  42. using IronPython.Compiler;
  43. using IronPython.Hosting;
  44. using IronPython.Modules;
  45. using IronPython.Runtime.Binding;
  46. using IronPython.Runtime.Exceptions;
  47. using IronPython.Runtime.Types;
  48. #if !SILVERLIGHT
  49. using System.ComponentModel;
  50. #endif
  51. namespace IronPython.Runtime.Operations {
  52. /// <summary>
  53. /// Contains functions that are called directly from
  54. /// generated code to perform low-level runtime functionality.
  55. /// </summary>
  56. public static partial class PythonOps {
  57. #region Shared static data
  58. [ThreadStatic]
  59. private static List<object> InfiniteRepr;
  60. // The "current" exception on this thread that will be returned via sys.exc_info()
  61. [ThreadStatic]
  62. internal static Exception RawException;
  63. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
  64. public static readonly PythonTuple EmptyTuple = PythonTuple.EMPTY;
  65. private static readonly Type[] _DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) };
  66. #endregion
  67. public static BigInteger MakeIntegerFromHex(string s) {
  68. return LiteralParser.ParseBigInteger(s, 16);
  69. }
  70. public static PythonDictionary MakeDict(int size) {
  71. return new PythonDictionary(size);
  72. }
  73. /// <summary>
  74. /// Creates a new dictionary extracting the keys and values from the
  75. /// provided data array. Keys/values are adjacent in the array with
  76. /// the value coming first.
  77. /// </summary>
  78. public static PythonDictionary MakeDictFromItems(params object[] data) {
  79. return new PythonDictionary(new CommonDictionaryStorage(data, false));
  80. }
  81. /// <summary>
  82. /// Creates a new dictionary extracting the keys and values from the
  83. /// provided data array. Keys/values are adjacent in the array with
  84. /// the value coming first.
  85. /// </summary>
  86. public static PythonDictionary MakeHomogeneousDictFromItems(object[] data) {
  87. return new PythonDictionary(new CommonDictionaryStorage(data, true));
  88. }
  89. public static bool IsCallable(CodeContext/*!*/ context, object o) {
  90. // This tells if an object can be called, but does not make a claim about the parameter list.
  91. // In 1.x, we could check for certain interfaces like ICallable*, but those interfaces were deprecated
  92. // in favor of dynamic sites.
  93. // This is difficult to infer because we'd need to simulate the entire callbinder, which can include
  94. // looking for [SpecialName] call methods and checking for a rule from IDynamicMetaObjectProvider. But even that wouldn't
  95. // be complete since sites require the argument list of the call, and we only have the instance here.
  96. // Thus check a dedicated IsCallable operator. This lets each object describe if it's callable.
  97. // Invoke Operator.IsCallable on the object.
  98. return PythonContext.GetContext(context).IsCallable(o);
  99. }
  100. public static bool IsTrue(object o) {
  101. return Converter.ConvertToBoolean(o);
  102. }
  103. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
  104. public static List<object> GetReprInfinite() {
  105. if (InfiniteRepr == null) {
  106. InfiniteRepr = new List<object>();
  107. }
  108. return InfiniteRepr;
  109. }
  110. internal static object LookupEncodingError(CodeContext/*!*/ context, string name) {
  111. Dictionary<string, object> errorHandlers = PythonContext.GetContext(context).ErrorHandlers;
  112. lock (errorHandlers) {
  113. if (errorHandlers.ContainsKey(name))
  114. return errorHandlers[name];
  115. else
  116. throw PythonOps.LookupError("unknown error handler name '{0}'", name);
  117. }
  118. }
  119. internal static void RegisterEncodingError(CodeContext/*!*/ context, string name, object handler) {
  120. Dictionary<string, object> errorHandlers = PythonContext.GetContext(context).ErrorHandlers;
  121. lock (errorHandlers) {
  122. if (!PythonOps.IsCallable(context, handler))
  123. throw PythonOps.TypeError("handler must be callable");
  124. errorHandlers[name] = handler;
  125. }
  126. }
  127. internal static PythonTuple LookupEncoding(CodeContext/*!*/ context, string encoding) {
  128. PythonContext.GetContext(context).EnsureEncodings();
  129. List<object> searchFunctions = PythonContext.GetContext(context).SearchFunctions;
  130. string normalized = encoding.ToLower().Replace(' ', '-');
  131. if (normalized.IndexOf(Char.MinValue) != -1) {
  132. throw PythonOps.TypeError("lookup string cannot contain null character");
  133. }
  134. lock (searchFunctions) {
  135. for (int i = 0; i < searchFunctions.Count; i++) {
  136. object res = PythonCalls.Call(context, searchFunctions[i], normalized);
  137. if (res != null) return (PythonTuple)res;
  138. }
  139. }
  140. throw PythonOps.LookupError("unknown encoding: {0}", encoding);
  141. }
  142. internal static void RegisterEncoding(CodeContext/*!*/ context, object search_function) {
  143. if (!PythonOps.IsCallable(context, search_function))
  144. throw PythonOps.TypeError("search_function must be callable");
  145. List<object> searchFunctions = PythonContext.GetContext(context).SearchFunctions;
  146. lock (searchFunctions) {
  147. searchFunctions.Add(search_function);
  148. }
  149. }
  150. internal static string GetPythonTypeName(object obj) {
  151. OldInstance oi = obj as OldInstance;
  152. if (oi != null) return oi._class._name.ToString();
  153. else return PythonTypeOps.GetName(obj);
  154. }
  155. public static string Repr(CodeContext/*!*/ context, object o) {
  156. if (o == null) return "None";
  157. string s;
  158. if ((s = o as string) != null) return StringOps.__repr__(s);
  159. if (o is int) return Int32Ops.__repr__((int)o);
  160. if (o is long) return ((long)o).ToString() + "L";
  161. // could be a container object, we need to detect recursion, but only
  162. // for our own built-in types that we're aware of. The user can setup
  163. // infinite recursion in their own class if they want.
  164. ICodeFormattable f = o as ICodeFormattable;
  165. if (f != null) {
  166. return f.__repr__(context);
  167. }
  168. PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "Repr " + o.GetType().FullName);
  169. return PythonContext.InvokeUnaryOperator(context, UnaryOperators.Repr, o) as string;
  170. }
  171. public static List<object> GetAndCheckInfinite(object o) {
  172. List<object> infinite = GetReprInfinite();
  173. foreach (object o2 in infinite) {
  174. if (o == o2) {
  175. return null;
  176. }
  177. }
  178. return infinite;
  179. }
  180. public static string ToString(object o) {
  181. return ToString(DefaultContext.Default, o);
  182. }
  183. public static string ToString(CodeContext/*!*/ context, object o) {
  184. string x = o as string;
  185. PythonType dt;
  186. OldClass oc;
  187. if (x != null) return x;
  188. if (o == null) return "None";
  189. if (o is double) return DoubleOps.__str__(context, (double)o);
  190. if ((dt = o as PythonType) != null) return dt.__repr__(DefaultContext.Default);
  191. if ((oc = o as OldClass) != null) return oc.ToString();
  192. object value = PythonContext.InvokeUnaryOperator(context, UnaryOperators.String, o);
  193. string ret = value as string;
  194. if (ret == null) {
  195. Extensible<string> es = value as Extensible<string>;
  196. if (es == null) {
  197. throw PythonOps.TypeError("expected str, got {0} from __str__", PythonTypeOps.GetName(value));
  198. }
  199. ret = es.Value;
  200. }
  201. return ret;
  202. }
  203. public static string FormatString(CodeContext context, string str, object data) {
  204. return new StringFormatter(context, str, data).Format();
  205. }
  206. public static string FormatUnicode(CodeContext context, string str, object data) {
  207. return new StringFormatter(context, str, data, true).Format();
  208. }
  209. public static object Plus(object o) {
  210. object ret;
  211. if (o is int) return o;
  212. else if (o is double) return o;
  213. else if (o is BigInteger) return o;
  214. else if (o is Complex) return o;
  215. else if (o is long) return o;
  216. else if (o is float) return o;
  217. else if (o is bool) return ScriptingRuntimeHelpers.Int32ToObject((bool)o ? 1 : 0);
  218. if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__pos__", out ret) &&
  219. ret != NotImplementedType.Value) {
  220. return ret;
  221. }
  222. throw PythonOps.TypeError("bad operand type for unary +");
  223. }
  224. public static object Negate(object o) {
  225. if (o is int) return Int32Ops.Negate((int)o);
  226. else if (o is double) return DoubleOps.Negate((double)o);
  227. else if (o is long) return Int64Ops.Negate((long)o);
  228. else if (o is BigInteger) return BigIntegerOps.Negate((BigInteger)o);
  229. else if (o is Complex) return -(Complex)o;
  230. else if (o is float) return DoubleOps.Negate((float)o);
  231. else if (o is bool) return ScriptingRuntimeHelpers.Int32ToObject((bool)o ? -1 : 0);
  232. object ret;
  233. if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__neg__", out ret) &&
  234. ret != NotImplementedType.Value) {
  235. return ret;
  236. }
  237. throw PythonOps.TypeError("bad operand type for unary -");
  238. }
  239. public static bool IsSubClass(PythonType/*!*/ c, PythonType/*!*/ typeinfo) {
  240. Assert.NotNull(c, typeinfo);
  241. if (c.OldClass != null) {
  242. return typeinfo.__subclasscheck__(c.OldClass);
  243. }
  244. return typeinfo.__subclasscheck__(c);
  245. }
  246. public static bool IsSubClass(CodeContext context, PythonType c, object typeinfo) {
  247. if (c == null) throw PythonOps.TypeError("issubclass: arg 1 must be a class");
  248. if (typeinfo == null) throw PythonOps.TypeError("issubclass: arg 2 must be a class");
  249. PythonTuple pt = typeinfo as PythonTuple;
  250. PythonContext pyContext = PythonContext.GetContext(context);
  251. if (pt != null) {
  252. // Recursively inspect nested tuple(s)
  253. foreach (object o in pt) {
  254. try {
  255. FunctionPushFrame(pyContext);
  256. if (IsSubClass(context, c, o)) {
  257. return true;
  258. }
  259. } finally {
  260. FunctionPopFrame();
  261. }
  262. }
  263. return false;
  264. }
  265. OldClass oc = typeinfo as OldClass;
  266. if (oc != null) {
  267. return c.IsSubclassOf(oc.TypeObject);
  268. }
  269. Type t = typeinfo as Type;
  270. if (t != null) {
  271. typeinfo = DynamicHelpers.GetPythonTypeFromType(t);
  272. }
  273. object bases;
  274. PythonType dt = typeinfo as PythonType;
  275. if (dt == null) {
  276. if (!PythonOps.TryGetBoundAttr(typeinfo, "__bases__", out bases)) {
  277. //!!! deal with classes w/ just __bases__ defined.
  278. throw PythonOps.TypeErrorForBadInstance("issubclass(): {0} is not a class nor a tuple of classes", typeinfo);
  279. }
  280. IEnumerator ie = PythonOps.GetEnumerator(bases);
  281. while (ie.MoveNext()) {
  282. PythonType baseType = ie.Current as PythonType;
  283. if (baseType == null) {
  284. OldClass ocType = ie.Current as OldClass;
  285. if (ocType == null) {
  286. continue;
  287. }
  288. baseType = ocType.TypeObject;
  289. }
  290. if (c.IsSubclassOf(baseType)) return true;
  291. }
  292. return false;
  293. }
  294. return IsSubClass(c, dt);
  295. }
  296. public static bool IsInstance(object o, PythonType typeinfo) {
  297. if (typeinfo.__instancecheck__(o)) {
  298. return true;
  299. }
  300. return IsInstanceDynamic(o, typeinfo, DynamicHelpers.GetPythonType(o));
  301. }
  302. public static bool IsInstance(CodeContext context, object o, PythonTuple typeinfo) {
  303. PythonContext pyContext = PythonContext.GetContext(context);
  304. foreach (object type in typeinfo) {
  305. try {
  306. PythonOps.FunctionPushFrame(pyContext);
  307. if (type is PythonType) {
  308. if (IsInstance(o, (PythonType)type)) {
  309. return true;
  310. }
  311. } else if (type is PythonTuple) {
  312. if (IsInstance(context, o, (PythonTuple)type)) {
  313. return true;
  314. }
  315. } else if (IsInstance(context, o, type)) {
  316. return true;
  317. }
  318. } finally {
  319. PythonOps.FunctionPopFrame();
  320. }
  321. }
  322. return false;
  323. }
  324. public static bool IsInstance(CodeContext context, object o, object typeinfo) {
  325. if (typeinfo == null) throw PythonOps.TypeError("isinstance: arg 2 must be a class, type, or tuple of classes and types");
  326. PythonTuple tt = typeinfo as PythonTuple;
  327. if (tt != null) {
  328. return IsInstance(context, o, tt);
  329. }
  330. if (typeinfo is OldClass) {
  331. // old instances are strange - they all share a common type
  332. // of instance but they can "be subclasses" of other
  333. // OldClass's. To check their types we need the actual
  334. // instance.
  335. OldInstance oi = o as OldInstance;
  336. if (oi != null) return oi._class.IsSubclassOf(typeinfo);
  337. }
  338. PythonType odt = DynamicHelpers.GetPythonType(o);
  339. if (IsSubClass(context, odt, typeinfo)) {
  340. return true;
  341. }
  342. return IsInstanceDynamic(o, typeinfo);
  343. }
  344. private static bool IsInstanceDynamic(object o, object typeinfo) {
  345. return IsInstanceDynamic(o, typeinfo, DynamicHelpers.GetPythonType(o));
  346. }
  347. private static bool IsInstanceDynamic(object o, object typeinfo, PythonType odt) {
  348. if (o is IPythonObject || o is OldInstance) {
  349. object cls;
  350. if (PythonOps.TryGetBoundAttr(o, "__class__", out cls) &&
  351. (!object.ReferenceEquals(odt, cls))) {
  352. return IsSubclassSlow(cls, typeinfo);
  353. }
  354. }
  355. return false;
  356. }
  357. private static bool IsSubclassSlow(object cls, object typeinfo) {
  358. Debug.Assert(typeinfo != null);
  359. if (cls == null) return false;
  360. // Same type
  361. if (cls.Equals(typeinfo)) {
  362. return true;
  363. }
  364. // Get bases
  365. object bases;
  366. if (!PythonOps.TryGetBoundAttr(cls, "__bases__", out bases)) {
  367. return false; // no bases, cannot be subclass
  368. }
  369. PythonTuple tbases = bases as PythonTuple;
  370. if (tbases == null) {
  371. return false; // not a tuple, cannot be subclass
  372. }
  373. foreach (object baseclass in tbases) {
  374. if (IsSubclassSlow(baseclass, typeinfo)) return true;
  375. }
  376. return false;
  377. }
  378. public static object OnesComplement(object o) {
  379. if (o is int) return ~(int)o;
  380. if (o is long) return ~(long)o;
  381. if (o is BigInteger) return ~((BigInteger)o);
  382. if (o is bool) return ScriptingRuntimeHelpers.Int32ToObject((bool)o ? -2 : -1);
  383. object ret;
  384. if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__invert__", out ret) &&
  385. ret != NotImplementedType.Value)
  386. return ret;
  387. throw PythonOps.TypeError("bad operand type for unary ~");
  388. }
  389. public static bool Not(object o) {
  390. return !IsTrue(o);
  391. }
  392. public static object Is(object x, object y) {
  393. return x == y ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  394. }
  395. public static bool IsRetBool(object x, object y) {
  396. return x == y;
  397. }
  398. public static object IsNot(object x, object y) {
  399. return x != y ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  400. }
  401. public static bool IsNotRetBool(object x, object y) {
  402. return x != y;
  403. }
  404. internal delegate T MultiplySequenceWorker<T>(T self, int count);
  405. /// <summary>
  406. /// Wraps up all the semantics of multiplying sequences so that all of our sequences
  407. /// don't duplicate the same logic. When multiplying sequences we need to deal with
  408. /// only multiplying by valid sequence types (ints, not floats), support coercion
  409. /// to integers if the type supports it, not multiplying by None, and getting the
  410. /// right semantics for multiplying by negative numbers and 1 (w/ and w/o subclasses).
  411. ///
  412. /// This function assumes that it is only called for case where count is not implicitly
  413. /// coercible to int so that check is skipped.
  414. /// </summary>
  415. internal static object MultiplySequence<T>(MultiplySequenceWorker<T> multiplier, T sequence, Index count, bool isForward) {
  416. if (isForward && count != null) {
  417. object ret;
  418. if (PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default, count.Value, sequence, "__rmul__", out ret)) {
  419. if (ret != NotImplementedType.Value) return ret;
  420. }
  421. }
  422. int icount = GetSequenceMultiplier(sequence, count.Value);
  423. if (icount < 0) icount = 0;
  424. return multiplier(sequence, icount);
  425. }
  426. internal static int GetSequenceMultiplier(object sequence, object count) {
  427. int icount;
  428. if (!Converter.TryConvertToIndex(count, out icount)) {
  429. PythonTuple pt = null;
  430. if (count is OldInstance || !DynamicHelpers.GetPythonType(count).IsSystemType) {
  431. pt = Builtin.TryCoerce(DefaultContext.Default, count, sequence) as PythonTuple;
  432. }
  433. if (pt == null || !Converter.TryConvertToIndex(pt[0], out icount)) {
  434. throw TypeError("can't multiply sequence by non-int of type '{0}'", PythonTypeOps.GetName(count));
  435. }
  436. }
  437. return icount;
  438. }
  439. public static object Equal(CodeContext/*!*/ context, object x, object y) {
  440. PythonContext pc = PythonContext.GetContext(context);
  441. return pc.EqualSite.Target(pc.EqualSite, x, y);
  442. }
  443. public static bool EqualRetBool(object x, object y) {
  444. //TODO just can't seem to shake these fast paths
  445. if (x is int && y is int) { return ((int)x) == ((int)y); }
  446. if (x is string && y is string) { return ((string)x).Equals((string)y); }
  447. return DynamicHelpers.GetPythonType(x).EqualRetBool(x, y);
  448. }
  449. public static bool EqualRetBool(CodeContext/*!*/ context, object x, object y) {
  450. // TODO: use context
  451. //TODO just can't seem to shake these fast paths
  452. if (x is int && y is int) { return ((int)x) == ((int)y); }
  453. if (x is string && y is string) { return ((string)x).Equals((string)y); }
  454. return DynamicHelpers.GetPythonType(x).EqualRetBool(x, y);
  455. }
  456. public static int Compare(object x, object y) {
  457. return Compare(DefaultContext.Default, x, y);
  458. }
  459. public static int Compare(CodeContext/*!*/ context, object x, object y) {
  460. if (x == y) return 0;
  461. return DynamicHelpers.GetPythonType(x).Compare(x, y);
  462. }
  463. public static object CompareEqual(int res) {
  464. return res == 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  465. }
  466. public static object CompareNotEqual(int res) {
  467. return res == 0 ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True;
  468. }
  469. public static object CompareGreaterThan(int res) {
  470. return res > 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  471. }
  472. public static object CompareGreaterThanOrEqual(int res) {
  473. return res >= 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  474. }
  475. public static object CompareLessThan(int res) {
  476. return res < 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  477. }
  478. public static object CompareLessThanOrEqual(int res) {
  479. return res <= 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  480. }
  481. public static bool CompareTypesEqual(CodeContext/*!*/ context, object x, object y) {
  482. if (x == null && y == null) return true;
  483. if (x == null) return false;
  484. if (y == null) return false;
  485. if (DynamicHelpers.GetPythonType(x) == DynamicHelpers.GetPythonType(y)) {
  486. // avoid going to the ID dispenser if we have the same types...
  487. return x == y;
  488. }
  489. return PythonOps.CompareTypesWorker(context, false, x, y) == 0;
  490. }
  491. public static bool CompareTypesNotEqual(CodeContext/*!*/ context, object x, object y) {
  492. return PythonOps.CompareTypesWorker(context, false, x, y) != 0;
  493. }
  494. public static bool CompareTypesGreaterThan(CodeContext/*!*/ context, object x, object y) {
  495. return PythonOps.CompareTypes(context, x, y) > 0;
  496. }
  497. public static bool CompareTypesLessThan(CodeContext/*!*/ context, object x, object y) {
  498. return PythonOps.CompareTypes(context, x, y) < 0;
  499. }
  500. public static bool CompareTypesGreaterThanOrEqual(CodeContext/*!*/ context, object x, object y) {
  501. return PythonOps.CompareTypes(context, x, y) >= 0;
  502. }
  503. public static bool CompareTypesLessThanOrEqual(CodeContext/*!*/ context, object x, object y) {
  504. return PythonOps.CompareTypes(context, x, y) <= 0;
  505. }
  506. public static int CompareTypesWorker(CodeContext/*!*/ context, bool shouldWarn, object x, object y) {
  507. if (x == null && y == null) return 0;
  508. if (x == null) return -1;
  509. if (y == null) return 1;
  510. string name1, name2;
  511. int diff;
  512. if (DynamicHelpers.GetPythonType(x) != DynamicHelpers.GetPythonType(y)) {
  513. if (shouldWarn && PythonContext.GetContext(context).PythonOptions.WarnPython30) {
  514. PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "comparing unequal types not supported in 3.x");
  515. }
  516. if (x.GetType() == typeof(OldInstance)) {
  517. name1 = ((OldInstance)x)._class.Name;
  518. if (y.GetType() == typeof(OldInstance)) {
  519. name2 = ((OldInstance)y)._class.Name;
  520. } else {
  521. // old instances are always less than new-style classes
  522. return -1;
  523. }
  524. } else if (y.GetType() == typeof(OldInstance)) {
  525. // old instances are always less than new-style classes
  526. return 1;
  527. } else {
  528. name1 = PythonTypeOps.GetName(x);
  529. name2 = PythonTypeOps.GetName(y);
  530. }
  531. diff = String.CompareOrdinal(name1, name2);
  532. if (diff == 0) {
  533. // if the types are different but have the same name compare based upon their types.
  534. diff = (int)(IdDispenser.GetId(DynamicHelpers.GetPythonType(x)) - IdDispenser.GetId(DynamicHelpers.GetPythonType(y)));
  535. }
  536. } else {
  537. diff = (int)(IdDispenser.GetId(x) - IdDispenser.GetId(y));
  538. }
  539. if (diff < 0) return -1;
  540. if (diff == 0) return 0;
  541. return 1;
  542. }
  543. public static int CompareTypes(CodeContext/*!*/ context, object x, object y) {
  544. return CompareTypesWorker(context, true, x, y);
  545. }
  546. public static object GreaterThanHelper(CodeContext/*!*/ context, object self, object other) {
  547. return InternalCompare(context, PythonOperationKind.GreaterThan, self, other);
  548. }
  549. public static object LessThanHelper(CodeContext/*!*/ context, object self, object other) {
  550. return InternalCompare(context, PythonOperationKind.LessThan, self, other);
  551. }
  552. public static object GreaterThanOrEqualHelper(CodeContext/*!*/ context, object self, object other) {
  553. return InternalCompare(context, PythonOperationKind.GreaterThanOrEqual, self, other);
  554. }
  555. public static object LessThanOrEqualHelper(CodeContext/*!*/ context, object self, object other) {
  556. return InternalCompare(context, PythonOperationKind.LessThanOrEqual, self, other);
  557. }
  558. internal static object InternalCompare(CodeContext/*!*/ context, PythonOperationKind op, object self, object other) {
  559. object ret;
  560. if (PythonTypeOps.TryInvokeBinaryOperator(context, self, other, Symbols.OperatorToSymbol(op), out ret))
  561. return ret;
  562. return NotImplementedType.Value;
  563. }
  564. public static int CompareToZero(object value) {
  565. double val;
  566. if (Converter.TryConvertToDouble(value, out val)) {
  567. if (val > 0) return 1;
  568. if (val < 0) return -1;
  569. return 0;
  570. }
  571. throw PythonOps.TypeErrorForBadInstance("an integer is required (got {0})", value);
  572. }
  573. public static int CompareArrays(object[] data0, int size0, object[] data1, int size1) {
  574. int size = Math.Min(size0, size1);
  575. for (int i = 0; i < size; i++) {
  576. int c = PythonOps.Compare(data0[i], data1[i]);
  577. if (c != 0) return c;
  578. }
  579. if (size0 == size1) return 0;
  580. return size0 > size1 ? +1 : -1;
  581. }
  582. public static int CompareArrays(object[] data0, int size0, object[] data1, int size1, IComparer comparer) {
  583. int size = Math.Min(size0, size1);
  584. for (int i = 0; i < size; i++) {
  585. int c = comparer.Compare(data0[i], data1[i]);
  586. if (c != 0) return c;
  587. }
  588. if (size0 == size1) return 0;
  589. return size0 > size1 ? +1 : -1;
  590. }
  591. public static bool ArraysEqual(object[] data0, int size0, object[] data1, int size1) {
  592. if (size0 != size1) {
  593. return false;
  594. }
  595. for (int i = 0; i < size0; i++) {
  596. if (data0[i] != null) {
  597. if (!EqualRetBool(data0[i], data1[i])) {
  598. return false;
  599. }
  600. } else if (data1[i] != null) {
  601. return false;
  602. }
  603. }
  604. return true;
  605. }
  606. public static bool ArraysEqual(object[] data0, int size0, object[] data1, int size1, IEqualityComparer comparer) {
  607. if (size0 != size1) {
  608. return false;
  609. }
  610. for (int i = 0; i < size0; i++) {
  611. if (data0[i] != null) {
  612. if (!comparer.Equals(data0[i], data1[i])) {
  613. return false;
  614. }
  615. } else if (data1[i] != null) {
  616. return false;
  617. }
  618. }
  619. return true;
  620. }
  621. public static object PowerMod(CodeContext/*!*/ context, object x, object y, object z) {
  622. object ret;
  623. if (z == null) {
  624. return PythonContext.GetContext(context).Operation(PythonOperationKind.Power, x, y);
  625. }
  626. if (x is int && y is int && z is int) {
  627. ret = Int32Ops.Power((int)x, (int)y, (int)z);
  628. if (ret != NotImplementedType.Value) return ret;
  629. } else if (x is BigInteger) {
  630. ret = BigIntegerOps.Power((BigInteger)x, y, z);
  631. if (ret != NotImplementedType.Value) return ret;
  632. }
  633. if (x is Complex || y is Complex || z is Complex) {
  634. throw PythonOps.ValueError("complex modulo");
  635. }
  636. if (PythonTypeOps.TryInvokeTernaryOperator(context, x, y, z, "__pow__", out ret)) {
  637. if (ret != NotImplementedType.Value) {
  638. return ret;
  639. } else if (!IsNumericObject(y) || !IsNumericObject(z)) {
  640. // special error message in this case...
  641. throw TypeError("pow() 3rd argument not allowed unless all arguments are integers");
  642. }
  643. }
  644. throw PythonOps.TypeErrorForBinaryOp("power with modulus", x, y);
  645. }
  646. public static long Id(object o) {
  647. return IdDispenser.GetId(o);
  648. }
  649. public static string HexId(object o) {
  650. return string.Format("0x{0:X16}", Id(o));
  651. }
  652. // For hash operators, it's essential that:
  653. // Cmp(x,y)==0 implies hash(x) == hash(y)
  654. //
  655. // Equality is a language semantic determined by the Python's numerical Compare() ops
  656. // in IronPython.Runtime.Operations namespaces.
  657. // For example, the CLR compares float(1.0) and int32(1) as different, but Python
  658. // compares them as equal. So Hash(1.0f) and Hash(1) must be equal.
  659. //
  660. // Python allows an equality relationship between int, double, BigInteger, and complex.
  661. // So each of these hash functions must be aware of their possible equality relationships
  662. // and hash appropriately.
  663. //
  664. // Types which differ in hashing from .NET have __hash__ functions defined in their
  665. // ops classes which do the appropriate hashing.
  666. public static int Hash(CodeContext/*!*/ context, object o) {
  667. return PythonContext.Hash(o);
  668. }
  669. public static object Hex(object o) {
  670. if (o is int) return Int32Ops.__hex__((int)o);
  671. else if (o is BigInteger) return BigIntegerOps.__hex__((BigInteger)o);
  672. object hex;
  673. if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default,
  674. o,
  675. "__hex__",
  676. out hex)) {
  677. if (!(hex is string) && !(hex is ExtensibleString))
  678. throw PythonOps.TypeError("hex expected string type as return, got '{0}'", PythonTypeOps.GetName(hex));
  679. return hex;
  680. }
  681. throw TypeError("hex() argument cannot be converted to hex");
  682. }
  683. public static object Oct(object o) {
  684. if (o is int) {
  685. return Int32Ops.__oct__((int)o);
  686. } else if (o is BigInteger) {
  687. return BigIntegerOps.__oct__((BigInteger)o);
  688. }
  689. object octal;
  690. if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default,
  691. o,
  692. "__oct__",
  693. out octal)) {
  694. if (!(octal is string) && !(octal is ExtensibleString))
  695. throw PythonOps.TypeError("hex expected string type as return, got '{0}'", PythonTypeOps.GetName(octal));
  696. return octal;
  697. }
  698. throw TypeError("oct() argument cannot be converted to octal");
  699. }
  700. public static int Length(object o) {
  701. string s = o as string;
  702. if (s != null) {
  703. return s.Length;
  704. }
  705. object[] os = o as object[];
  706. if (os != null) {
  707. return os.Length;
  708. }
  709. object len = PythonContext.InvokeUnaryOperator(DefaultContext.Default, UnaryOperators.Length, o, "len() of unsized object");
  710. int res;
  711. if (len is int) {
  712. res = (int)len;
  713. } else {
  714. res = Converter.ConvertToInt32(len);
  715. }
  716. if (res < 0) {
  717. throw PythonOps.ValueError("__len__ should return >= 0, got {0}", res);
  718. }
  719. return res;
  720. }
  721. public static object CallWithContext(CodeContext/*!*/ context, object func, params object[] args) {
  722. return PythonCalls.Call(context, func, args);
  723. }
  724. /// <summary>
  725. /// Supports calling of functions that require an explicit 'this'
  726. /// Currently, we check if the function object implements the interface
  727. /// that supports calling with 'this'. If not, the 'this' object is dropped
  728. /// and a normal call is made.
  729. /// </summary>
  730. public static object CallWithContextAndThis(CodeContext/*!*/ context, object func, object instance, params object[] args) {
  731. // drop the 'this' and make the call
  732. return CallWithContext(context, func, args);
  733. }
  734. public static object ToPythonType(PythonType dt) {
  735. if (dt != null) {
  736. return ((object)dt.OldClass) ?? ((object)dt);
  737. }
  738. return null;
  739. }
  740. public static object CallWithArgsTupleAndContext(CodeContext/*!*/ context, object func, object[] args, object argsTuple) {
  741. PythonTuple tp = argsTuple as PythonTuple;
  742. if (tp != null) {
  743. object[] nargs = new object[args.Length + tp.__len__()];
  744. for (int i = 0; i < args.Length; i++) nargs[i] = args[i];
  745. for (int i = 0; i < tp.__len__(); i++) nargs[i + args.Length] = tp[i];
  746. return CallWithContext(context, func, nargs);
  747. }
  748. List allArgs = PythonOps.MakeEmptyList(args.Length + 10);
  749. allArgs.AddRange(args);
  750. IEnumerator e = PythonOps.GetEnumerator(argsTuple);
  751. while (e.MoveNext()) allArgs.AddNoLock(e.Current);
  752. return CallWithContext(context, func, allArgs.GetObjectArray());
  753. }
  754. [Obsolete("Use ObjectOpertaions instead")]
  755. public static object CallWithArgsTupleAndKeywordDictAndContext(CodeContext/*!*/ context, object func, object[] args, string[] names, object argsTuple, object kwDict) {
  756. IDictionary kws = kwDict as IDictionary;
  757. if (kws == null && kwDict != null) throw PythonOps.TypeError("argument after ** must be a dictionary");
  758. if ((kws == null || kws.Count == 0) && names.Length == 0) {
  759. List<object> largs = new List<object>(args);
  760. if (argsTuple != null) {
  761. foreach (object arg in PythonOps.GetCollection(argsTuple))
  762. largs.Add(arg);
  763. }
  764. return CallWithContext(context, func, largs.ToArray());
  765. } else {
  766. List<object> largs;
  767. if (argsTuple != null && args.Length == names.Length) {
  768. PythonTuple tuple = argsTuple as PythonTuple;
  769. if (tuple == null) tuple = new PythonTuple(argsTuple);
  770. largs = new List<object>(tuple);
  771. largs.AddRange(args);
  772. } else {
  773. largs = new List<object>(args);
  774. if (argsTuple != null) {
  775. largs.InsertRange(args.Length - names.Length, PythonTuple.Make(argsTuple));
  776. }
  777. }
  778. List<string> lnames = new List<string>(names);
  779. if (kws != null) {
  780. IDictionaryEnumerator ide = kws.GetEnumerator();
  781. while (ide.MoveNext()) {
  782. lnames.Add((string)ide.Key);
  783. largs.Add(ide.Value);
  784. }
  785. }
  786. return PythonCalls.CallWithKeywordArgs(context, func, largs.ToArray(), lnames.ToArray());
  787. }
  788. }
  789. public static object CallWithKeywordArgs(CodeContext/*!*/ context, object func, object[] args, string[] names) {
  790. return PythonCalls.CallWithKeywordArgs(context, func, args, names);
  791. }
  792. public static object CallWithArgsTuple(object func, object[] args, object argsTuple) {
  793. PythonTuple tp = argsTuple as PythonTuple;
  794. if (tp != null) {
  795. object[] nargs = new object[args.Length + tp.__len__()];
  796. for (int i = 0; i < args.Length; i++) nargs[i] = args[i];
  797. for (int i = 0; i < tp.__len__(); i++) nargs[i + args.Length] = tp[i];
  798. return PythonCalls.Call(func, nargs);
  799. }
  800. List allArgs = PythonOps.MakeEmptyList(args.Length + 10);
  801. allArgs.AddRange(args);
  802. IEnumerator e = PythonOps.GetEnumerator(argsTuple);
  803. while (e.MoveNext()) allArgs.AddNoLock(e.Current);
  804. return PythonCalls.Call(func, allArgs.GetObjectArray());
  805. }
  806. public static object GetIndex(CodeContext/*!*/ context, object o, object index) {
  807. PythonContext pc = PythonContext.GetContext(context);
  808. return pc.GetIndexSite.Target(pc.GetIndexSite, o, index);
  809. }
  810. public static bool TryGetBoundAttr(object o, string name, out object ret) {
  811. return TryGetBoundAttr(DefaultContext.Default, o, name, out ret);
  812. }
  813. public static void SetAttr(CodeContext/*!*/ context, object o, string name, object value) {
  814. PythonContext.GetContext(context).SetAttr(context, o, name, value);
  815. }
  816. public static bool TryGetBoundAttr(CodeContext/*!*/ context, object o, string name, out object ret) {
  817. return DynamicHelpers.GetPythonType(o).TryGetBoundAttr(context, o, name, out ret);
  818. }
  819. public static void DeleteAttr(CodeContext/*!*/ context, object o, string name) {
  820. PythonContext.GetContext(context).DeleteAttr(context, o, name);
  821. }
  822. public static bool HasAttr(CodeContext/*!*/ context, object o, string name) {
  823. object dummy;
  824. try {
  825. return TryGetBoundAttr(context, o, name, out dummy);
  826. } catch (SystemExitException) {
  827. throw;
  828. } catch (KeyboardInterruptException) {
  829. // we don't catch ThreadAbortException because it will
  830. // automatically re-throw on it's own.
  831. throw;
  832. } catch {
  833. ExceptionHelpers.DynamicStackFrames = null;
  834. return false;
  835. }
  836. }
  837. public static object GetBoundAttr(CodeContext/*!*/ context, object o, string name) {
  838. object ret;
  839. if (!DynamicHelpers.GetPythonType(o).TryGetBoundAttr(context, o, name, out ret)) {
  840. if (o is OldClass) {
  841. throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'",
  842. ((OldClass)o).Name, name);
  843. } else {
  844. throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonTypeOps.GetName(o), name);
  845. }
  846. }
  847. return ret;
  848. }
  849. public static void ObjectSetAttribute(CodeContext/*!*/ context, object o, string name, object value) {
  850. if (!DynamicHelpers.GetPythonType(o).TrySetNonCustomMember(context, o, name, value))
  851. throw AttributeErrorForMissingOrReadonly(context, DynamicHelpers.GetPythonType(o), name);
  852. }
  853. public static void ObjectDeleteAttribute(CodeContext/*!*/ context, object o, string name) {
  854. if (!DynamicHelpers.GetPythonType(o).TryDeleteNonCustomMember(context, o, name)) {
  855. throw AttributeErrorForMissingOrReadonly(context, DynamicHelpers.GetPythonType(o), name);
  856. }
  857. }
  858. public static object ObjectGetAttribute(CodeContext/*!*/ context, object o, string name) {
  859. OldClass oc = o as OldClass;
  860. if (oc != null) {
  861. return oc.GetMember(context, name);
  862. }
  863. object value;
  864. if (DynamicHelpers.GetPythonType(o).TryGetNonCustomMember(context, o, name, out value)) {
  865. return value;
  866. }
  867. throw PythonOps.AttributeErrorForObjectMissingAttribute(o, name);
  868. }
  869. internal static IList<string> GetStringMemberList(IPythonMembersList pyMemList) {
  870. List<string> res = new List<string>();
  871. foreach (object o in pyMemList.GetMemberNames(DefaultContext.Default)) {
  872. if (o is string) {
  873. res.Add((string)o);
  874. }
  875. }
  876. return res;
  877. }
  878. public static IList<object> GetAttrNames(CodeContext/*!*/ context, object o) {
  879. IPythonMembersList pyMemList = o as IPythonMembersList;
  880. if (pyMemList != null) {
  881. return pyMemList.GetMemberNames(context);
  882. }
  883. IMembersList memList = o as IMembersList;
  884. if (memList != null) {
  885. return new List(memList.GetMemberNames());
  886. }
  887. IPythonObject po = o as IPythonObject;
  888. if (po != null) {
  889. return po.PythonType.GetMemberNames(context, o);
  890. }
  891. List res = DynamicHelpers.GetPythonType(o).GetMemberNames(context, o);
  892. #if !SILVERLIGHT
  893. if (o != null && Microsoft.Scripting.ComInterop.ComBinder.IsComObject(o)) {
  894. foreach (string name in Microsoft.Scripting.ComInterop.ComBinder.GetDynamicMemberNames(o)) {
  895. if (!res.Contains(name)) {
  896. res.AddNoLock(name);
  897. }
  898. }
  899. }
  900. #endif
  901. return res;
  902. }
  903. /// <summary>
  904. /// Called from generated code emitted by NewTypeMaker.
  905. /// </summary>
  906. public static void CheckInitializedAttribute(object o, object self, string name) {
  907. if (o == Uninitialized.Instance) {
  908. throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'",
  909. PythonTypeOps.GetName(self),
  910. name);
  911. }
  912. }
  913. public static object GetUserSlotValue(CodeContext context, PythonTypeUserDescriptorSlot slot, object instance, PythonType type) {
  914. return slot.GetValue(context, instance, type);
  915. }
  916. /// <summary>
  917. /// Handles the descriptor protocol for user-defined objects that may implement __get__
  918. /// </summary>
  919. public static object GetUserDescriptor(object o, object instance, object context) {
  920. if (o is IPythonObject) {
  921. // slow, but only encountred for user defined descriptors.
  922. PerfTrack.NoteEvent(PerfTrack.Categories.DictInvoke, "__get__");
  923. object ret;
  924. if (PythonContext.TryInvokeTernaryOperator(DefaultContext.Default,
  925. TernaryOperators.GetDescriptor,
  926. o,
  927. instance,
  928. context,
  929. out ret)) {
  930. return ret;
  931. }
  932. }
  933. return o;
  934. }
  935. /// <summary>
  936. /// Handles the descriptor protocol for user-defined objects that may implement __set__
  937. /// </summary>
  938. public static bool TrySetUserDescriptor(object o, object instance, object value) {
  939. if (o != null && o.GetType() == typeof(OldInstance)) return false; // only new-style classes have descriptors
  940. // slow, but only encountred for user defined descriptors.
  941. PerfTrack.NoteEvent(PerfTrack.Categories.DictInvoke, "__set__");
  942. object dummy;
  943. return PythonContext.TryInvokeTernaryOperator(DefaultContext.Default,
  944. TernaryOperators.SetDescriptor,
  945. o,
  946. instance,
  947. value,
  948. out dummy);
  949. }
  950. /// <summary>
  951. /// Handles the descriptor protocol for user-defined objects that may implement __delete__
  952. /// </summary>
  953. public static bool TryDeleteUserDescriptor(object o, object instance) {
  954. if (o != null && o.GetType() == typeof(OldInstance)) return false; // only new-style classes can have descriptors
  955. // slow, but only encountred for user defined descriptors.
  956. PerfTrack.NoteEvent(PerfTrack.Categories.DictInvoke, "__delete__");
  957. object dummy;
  958. return PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default,
  959. o,
  960. instance,
  961. "__delete__",
  962. out dummy);
  963. }
  964. public static object Invoke(CodeContext/*!*/ context, object target, string name, params object[] args) {
  965. return PythonCalls.Call(context, PythonOps.GetBoundAttr(context, target, name), args);
  966. }
  967. public static Delegate CreateDynamicDelegate(DynamicMethod meth, Type delegateType, object target) {
  968. // Always close delegate around its own instance of the frame
  969. return meth.CreateDelegate(delegateType, target);
  970. }
  971. public static double CheckMath(double v) {
  972. if (double.IsInfinity(v)) {
  973. throw PythonOps.OverflowError("math range error");
  974. } else if (double.IsNaN(v)) {
  975. throw PythonOps.ValueError("math domain error");
  976. } else {
  977. return v;
  978. }
  979. }
  980. public static object IsMappingType(CodeContext/*!*/ context, object o) {
  981. if (o is IDictionary || o is PythonDictionary || o is IDictionary<object, object> || o is PythonDictionary) {
  982. return ScriptingRuntimeHelpers.True;
  983. }
  984. object getitem;
  985. if ((o is IPythonObject || o is OldInstance) && PythonOps.TryGetBoundAttr(context, o, "__getitem__", out getitem)) {
  986. if (!PythonOps.IsClsVisible(context)) {
  987. // in standard Python methods aren't mapping types, therefore
  988. // if the user hasn't broken out of that box yet don't treat
  989. // them as mapping types.
  990. if (o is BuiltinFunction) return ScriptingRuntimeHelpers.False;
  991. }
  992. return ScriptingRuntimeHelpers.True;
  993. }
  994. return ScriptingRuntimeHelpers.False;
  995. }
  996. public static int FixSliceIndex(int v, int len) {
  997. if (v < 0) v = len + v;
  998. if (v < 0) return 0;
  999. if (v > len) return len;
  1000. return v;
  1001. }
  1002. public static void FixSlice(int length, object start, object stop, object step,
  1003. out int ostart, out int ostop, out int ostep, out int ocount) {
  1004. if (step == null) {
  1005. ostep = 1;
  1006. } else {
  1007. ostep = Converter.ConvertToIndex(step);
  1008. if (ostep == 0) {
  1009. throw PythonOps.ValueError("step cannot be zero");
  1010. }
  1011. }
  1012. if (start == null) {
  1013. ostart = ostep > 0 ? 0 : length - 1;
  1014. } else {
  1015. ostart = Converter.ConvertToIndex(start);
  1016. if (ostart < 0) {
  1017. ostart += length;
  1018. if (ostart < 0) {
  1019. ostart = ostep > 0 ? Math.Min(length, 0) : Math.Min(length - 1, -1);
  1020. }
  1021. } else if (ostart >= length) {
  1022. ostart = ostep > 0 ? length : length - 1;
  1023. }
  1024. }
  1025. if (stop == null) {
  1026. ostop = ostep > 0 ? length : -1;
  1027. } else {
  1028. ostop = Converter.ConvertToIndex(stop);
  1029. if (ostop < 0) {
  1030. ostop += length;
  1031. if (ostop < 0) {
  1032. ostop = ostep > 0 ? Math.Min(length, 0) : Math.Min(length - 1, -1);
  1033. }
  1034. } else if (ostop >= length) {
  1035. ostop = ostep > 0 ? length : length - 1;
  1036. }
  1037. }
  1038. ocount = ostep > 0 ? (ostop - ostart + ostep - 1) / ostep
  1039. : (ostop - ostart + ostep + 1) / ostep;
  1040. }
  1041. public static int FixIndex(int v, int len) {
  1042. if (v < 0) {
  1043. v += len;
  1044. if (v < 0) {
  1045. throw PythonOps.IndexError("index out of range: {0}", v - len);
  1046. }
  1047. } else if (v >= len) {
  1048. throw PythonOps.IndexError("index out of range: {0}", v);
  1049. }
  1050. return v;
  1051. }
  1052. public static void InitializeForFinalization(CodeContext/*!*/ context, object newObject) {
  1053. IWeakReferenceable iwr = newObject as IWeakReferenceable;
  1054. Debug.Assert(iwr != null);
  1055. InstanceFinalizer nif = new InstanceFinalizer(context, newObject);
  1056. iwr.SetFinalizer(new WeakRefTracker(nif, nif));
  1057. }
  1058. private static object FindMetaclass(CodeContext/*!*/ context, PythonTuple bases, PythonDictionary dict) {
  1059. // If dict['__metaclass__'] exists, it is used.
  1060. object ret;
  1061. if (dict.TryGetValue("__metaclass__", out ret) && ret != null) return ret;
  1062. // Otherwise, if there is at least one base class, its metaclass is used
  1063. for (int i = 0; i < bases.__len__(); i++) {
  1064. if (!(bases[i] is OldClass)) return DynamicHelpers.GetPythonType(bases[i]);
  1065. }
  1066. // Otherwise, if there's a global variable named __metaclass__, it is used.
  1067. if (context.TryGetGlobalVariable("__metaclass__", out ret) && ret != null) {
  1068. return ret;
  1069. }
  1070. //Otherwise, the classic metaclass (types.ClassType) is used.
  1071. return TypeCache.OldInstance;
  1072. }
  1073. public static object MakeClass(object body, CodeContext/*!*/ parentContext, string name, object[] bases, string selfNames) {
  1074. Func<CodeContext, CodeContext> func = GetClassCode(parentContext, body);
  1075. return MakeClass(parentContext, name, bases, selfNames, func(parentContext).Dict);
  1076. }
  1077. private static Func<CodeContext, CodeContext> GetClassCode(CodeContext context, object body) {
  1078. Func<CodeContext, CodeContext> func = body as Func<CodeContext, CodeContext>;
  1079. if (func == null) {
  1080. FunctionCode code = (FunctionCode)body;
  1081. if (code.Target == null) {
  1082. code.UpdateDelegate(context.LanguageContext, true);
  1083. }
  1084. return (Func<CodeContext, CodeContext>)code.Target;
  1085. }
  1086. return func;
  1087. }
  1088. internal static object MakeClass(CodeContext context, string name, object[] bases, string selfNames, PythonDictionary vars) {
  1089. foreach (object dt in bases) {
  1090. if (dt is TypeGroup) {
  1091. object[] newBases = new object[bases.Length];
  1092. for (int i = 0; i < bases.Length; i++) {
  1093. TypeGroup tc = bases[i] as TypeGroup;
  1094. if (tc != null) {
  1095. Type nonGenericType;
  1096. if (!tc.TryGetNonGenericType(out nonGenericType)) {
  1097. throw PythonOps.TypeError("cannot derive from open generic types " + Builtin.repr(context, tc).ToString());
  1098. }
  1099. newBases[i] = DynamicHelpers.GetPythonTypeFromType(nonGenericType);
  1100. } else {
  1101. newBases[i] = bases[i];
  1102. }
  1103. }
  1104. bases = newBases;
  1105. break;
  1106. }
  1107. }
  1108. PythonTuple tupleBases = PythonTuple.MakeTuple(bases);
  1109. object metaclass = FindMetaclass(context, tupleBases, vars);
  1110. if (metaclass == TypeCache.OldInstance) {
  1111. return new OldClass(name, tupleBases, vars, selfNames);
  1112. } else if (metaclass == TypeCache.PythonType) {
  1113. return PythonType.__new__(context, TypeCache.PythonType, name, tupleBases, vars, selfNames);
  1114. }
  1115. // eg:
  1116. // def foo(*args): print args
  1117. // __metaclass__ = foo
  1118. // class bar: pass
  1119. // calls our function...
  1120. PythonContext pc = PythonContext.GetContext(context);
  1121. return pc.MetaClassCallSite.Target(
  1122. pc.MetaClassCallSite,
  1123. context,
  1124. metaclass,
  1125. name,
  1126. tupleBases,
  1127. vars
  1128. );
  1129. }
  1130. /// <summary>
  1131. /// Python runtime helper for raising assertions. Used by AssertStatement.
  1132. /// </summary>
  1133. /// <param name="msg">Object representing the assertion message</param>
  1134. public static void RaiseAssertionError(object msg) {
  1135. if (msg == null) {
  1136. throw PythonOps.AssertionError(String.Empty, ArrayUtils.EmptyObjects);
  1137. } else {
  1138. string message = PythonOps.ToString(msg);
  1139. throw PythonOps.AssertionError("{0}", new object[] { message });
  1140. }
  1141. }
  1142. /// <summary>
  1143. /// Python runtime helper to create instance of Python List object.
  1144. /// </summary>
  1145. /// <returns>New instance of List</returns>
  1146. public static List MakeList() {
  1147. return new List();
  1148. }
  1149. /// <summary>
  1150. /// Python runtime helper to create a populated instance of Python List object.
  1151. /// </summary>
  1152. public static List MakeList(params object[] items) {
  1153. return new List(items);
  1154. }
  1155. /// <summary>
  1156. /// Python runtime helper to create a populated instance of Python List object w/o
  1157. /// copying the array contents.
  1158. /// </summary>
  1159. [NoSideEffects]
  1160. public static List MakeListNoCopy(params object[] items) {
  1161. return List.FromArrayNoCopy(items);
  1162. }
  1163. /// <summary>
  1164. /// Python runtime helper to create a populated instance of Python List object.
  1165. ///
  1166. /// List is populated by arbitrary user defined object.
  1167. /// </summary>
  1168. public static List MakeListFromSequence(object sequence) {
  1169. return new List(sequence);
  1170. }
  1171. /// <summary>
  1172. /// Python runtime helper to create an instance of Python List object.
  1173. ///
  1174. /// List has the initial provided capacity.
  1175. /// </summary>
  1176. [NoSideEffects]
  1177. public static List MakeEmptyList(int capacity) {
  1178. return new List(capacity);
  1179. }
  1180. [NoSideEffects]
  1181. public static List MakeEmptyListFromCode() {
  1182. return List.FromArrayNoCopy(ArrayUtils.EmptyObjects);
  1183. }
  1184. /// <summary>
  1185. /// Python runtime helper to create an instance of Tuple
  1186. /// </summary>
  1187. /// <param name="items"></param>
  1188. /// <returns></returns>
  1189. [NoSideEffects]
  1190. public static PythonTuple MakeTuple(params object[] items) {
  1191. return PythonTuple.MakeTuple(items);
  1192. }
  1193. /// <summary>
  1194. /// Python runtime helper to create an instance of Tuple
  1195. /// </summary>
  1196. /// <param name="items"></param>
  1197. [NoSideEffects]
  1198. public static PythonTuple MakeTupleFromSequence(object items) {
  1199. return PythonTuple.Make(items);
  1200. }
  1201. /// <summary>
  1202. /// Python Runtime Helper for enumerator unpacking (tuple assignments, ...)
  1203. /// Creates enumerator from the input parameter e, and then extracts
  1204. /// expected number of values, returning them as array
  1205. ///
  1206. /// If the input is a Python tuple returns the tuples underlying data array. Callers
  1207. /// should not mutate the resulting tuple.
  1208. /// </summary>
  1209. /// <param name="context">The code context of the AST getting enumerator values.</param>
  1210. /// <param name="e">object to enumerate</param>
  1211. /// <param name="expected">expected number of objects to extract from the enumerator</param>
  1212. /// <returns>
  1213. /// array of objects (.Lengh == expected) if exactly expected objects are in the enumerator.
  1214. /// Otherwise throws exception
  1215. /// </returns>
  1216. public static object[] GetEnumeratorValues(CodeContext/*!*/ context, object e, int expected) {
  1217. if (e != null && e.GetType() == typeof(PythonTuple)) {
  1218. // fast path for tuples, avoid enumerating & copying the tuple.
  1219. return GetEnumeratorValuesFromTuple((PythonTuple)e, expected);
  1220. }
  1221. IEnumerator ie = PythonOps.GetEnumeratorForUnpack(context, e);
  1222. int count = 0;
  1223. object[] values = new object[expected];
  1224. while (count < expected) {
  1225. if (!ie.MoveNext()) {
  1226. throw PythonOps.ValueErrorForUnpackMismatch(expected, count);
  1227. }
  1228. values[count] = ie.Current;
  1229. count++;
  1230. }
  1231. if (ie.MoveNext()) {
  1232. throw PythonOps.ValueErrorForUnpackMismatch(expected, count + 1);
  1233. }
  1234. return values;
  1235. }
  1236. private static object[] GetEnumeratorValuesFromTuple(PythonTuple pythonTuple, int expected) {
  1237. if (pythonTuple.Count == expected) {
  1238. return pythonTuple._data;
  1239. }
  1240. throw PythonOps.ValueErrorForUnpackMismatch(expected, pythonTuple.Count);
  1241. }
  1242. /// <summary>
  1243. /// Python runtime helper to create instance of Slice object
  1244. /// </summary>
  1245. /// <param name="start">Start of the slice.</param>
  1246. /// <param name="stop">End of the slice.</param>
  1247. /// <param name="step">Step of the slice.</param>
  1248. /// <returns>Slice</returns>
  1249. public static Slice MakeSlice(object start, object stop, object step) {
  1250. return new Slice(start, stop, step);
  1251. }
  1252. #region Standard I/O support
  1253. public static void Write(CodeContext/*!*/ context, object f, string text) {
  1254. PythonContext pc = PythonContext.GetContext(context);
  1255. if (f == null) {
  1256. f = pc.SystemStandardOut;
  1257. }
  1258. if (f == null || f == Uninitialized.Instance) {
  1259. throw PythonOps.RuntimeError("lost sys.stdout");
  1260. }
  1261. PythonFile pf = f as PythonFile;
  1262. if (pf != null) {
  1263. // avoid spinning up a site in the normal case
  1264. pf.write(text);
  1265. return;
  1266. }
  1267. pc.WriteCallSite.Target(
  1268. pc.WriteCallSite,
  1269. context,
  1270. GetBoundAttr(context, f, "write"),
  1271. text
  1272. );
  1273. }
  1274. private static object ReadLine(CodeContext/*!*/ context, object f) {
  1275. if (f == null || f == Uninitialized.Instance) throw PythonOps.RuntimeError("lost sys.std_in");
  1276. return PythonOps.Invoke(context, f, "readline");
  1277. }
  1278. public static void WriteSoftspace(CodeContext/*!*/ context, object f) {
  1279. if (CheckSoftspace(f)) {
  1280. SetSoftspace(f, ScriptingRuntimeHelpers.False);
  1281. Write(context, f, " ");
  1282. }
  1283. }
  1284. public static void SetSoftspace(object f, object value) {
  1285. PythonOps.SetAttr(DefaultContext.Default, f, "softspace", value);
  1286. }
  1287. public static bool CheckSoftspace(object f) {
  1288. PythonFile pf = f as PythonFile;
  1289. if (pf != null) {
  1290. // avoid spinning up a site in the common case
  1291. return pf.softspace;
  1292. }
  1293. object result;
  1294. if (PythonOps.TryGetBoundAttr(f, "softspace", out result)) {
  1295. return PythonOps.IsTrue(result);
  1296. }
  1297. return false;
  1298. }
  1299. // Must stay here for now because libs depend on it.
  1300. public static void Print(CodeContext/*!*/ context, object o) {
  1301. PrintWithDest(context, PythonContext.GetContext(context).SystemStandardOut, o);
  1302. }
  1303. public static void PrintNoNewline(CodeContext/*!*/ context, object o) {
  1304. PrintWithDestNoNewline(context, PythonContext.GetContext(context).SystemStandardOut, o);
  1305. }
  1306. public static void PrintWithDest(CodeContext/*!*/ context, object dest, object o) {
  1307. PrintWithDestNoNewline(context, dest, o);
  1308. Write(context, dest, "\n");
  1309. }
  1310. public static void PrintWithDestNoNewline(CodeContext/*!*/ context, object dest, object o) {
  1311. WriteSoftspace(context, dest);
  1312. Write(context, dest, o == null ? "None" : ToString(o));
  1313. }
  1314. public static object ReadLineFromSrc(CodeContext/*!*/ context, object src) {
  1315. return ReadLine(context, src);
  1316. }
  1317. /// <summary>
  1318. /// Prints newline into default standard output
  1319. /// </summary>
  1320. public static void PrintNewline(CodeContext/*!*/ context) {
  1321. PrintNewlineWithDest(context, PythonContext.GetContext(context).SystemStandardOut);
  1322. }
  1323. /// <summary>
  1324. /// Prints newline into specified destination. Sets softspace property to false.
  1325. /// </summary>
  1326. public static void PrintNewlineWithDest(CodeContext/*!*/ context, object dest) {
  1327. PythonOps.Write(context, dest, "\n");
  1328. PythonOps.SetSoftspace(dest, ScriptingRuntimeHelpers.False);
  1329. }
  1330. /// <summary>
  1331. /// Prints value into default standard output with Python comma semantics.
  1332. /// </summary>
  1333. public static void PrintComma(CodeContext/*!*/ context, object o) {
  1334. PrintCommaWithDest(context, PythonContext.GetContext(context).SystemStandardOut, o);
  1335. }
  1336. /// <summary>
  1337. /// Prints value into specified destination with Python comma semantics.
  1338. /// </summary>
  1339. public static void PrintCommaWithDest(CodeContext/*!*/ context, object dest, object o) {
  1340. PythonOps.WriteSoftspace(context, dest);
  1341. string s = o == null ? "None" : PythonOps.ToString(o);
  1342. PythonOps.Write(context, dest, s);
  1343. PythonOps.SetSoftspace(dest, !s.EndsWith("\n"));
  1344. }
  1345. /// <summary>
  1346. /// Called from generated code when we are supposed to print an expression value
  1347. /// </summary>
  1348. public static void PrintExpressionValue(CodeContext/*!*/ context, object value) {
  1349. PythonContext pc = PythonContext.GetContext(context);
  1350. object dispHook = pc.GetSystemStateValue("displayhook");
  1351. pc.CallWithContext(context, dispHook, value);
  1352. }
  1353. #if !SILVERLIGHT
  1354. public static void PrintException(CodeContext/*!*/ context, Exception/*!*/ exception, IConsole console) {
  1355. PythonContext pc = PythonContext.GetContext(context);
  1356. PythonTuple exInfo = GetExceptionInfoLocal(context, exception);
  1357. pc.SetSystemStateValue("last_type", exInfo[0]);
  1358. pc.SetSystemStateValue("last_value", exInfo[1]);
  1359. pc.SetSystemStateValue("last_traceback", exInfo[2]);
  1360. object exceptHook = pc.GetSystemStateValue("excepthook");
  1361. BuiltinFunction bf = exceptHook as BuiltinFunction;
  1362. if (console != null && bf != null && bf.DeclaringType == typeof(SysModule) && bf.Name == "excepthook") {
  1363. // builtin except hook, display it to the console which may do nice coloring
  1364. console.WriteLine(pc.FormatException(exception), Style.Error);
  1365. } else {
  1366. // user defined except hook or no console
  1367. try {
  1368. PythonCalls.Call(context, exceptHook, exInfo[0], exInfo[1], exInfo[2]);
  1369. } catch (Exception e) {
  1370. PrintWithDest(context, pc.SystemStandardError, "Error in sys.excepthook:");
  1371. PrintWithDest(context, pc.SystemStandardError, pc.FormatException(e));
  1372. PrintNewlineWithDest(context, pc.SystemStandardError);
  1373. PrintWithDest(context, pc.SystemStandardError, "Original exception was:");
  1374. PrintWithDest(context, pc.SystemStandardError, pc.FormatException(exception));
  1375. ExceptionHelpers.DynamicStackFrames = null;
  1376. }
  1377. }
  1378. }
  1379. #endif
  1380. #endregion
  1381. #region Import support
  1382. /// <summary>
  1383. /// Called from generated code for:
  1384. ///
  1385. /// import spam.eggs
  1386. /// </summary>
  1387. [ProfilerTreatsAsExternal]
  1388. public static object ImportTop(CodeContext/*!*/ context, string fullName, int level) {
  1389. return Importer.Import(context, fullName, null, level);
  1390. }
  1391. /// <summary>
  1392. /// Python helper method called from generated code for:
  1393. ///
  1394. /// import spam.eggs as ham
  1395. /// </summary>
  1396. [ProfilerTreatsAsExternal]
  1397. public static object ImportBottom(CodeContext/*!*/ context, string fullName, int level) {
  1398. object module = Importer.Import(context, fullName, null, level);
  1399. if (fullName.IndexOf('.') >= 0) {
  1400. // Extract bottom from the imported module chain
  1401. string[] parts = fullName.Split('.');
  1402. for (int i = 1; i < parts.Length; i++) {
  1403. module = PythonOps.GetBoundAttr(context, module, parts[i]);
  1404. }
  1405. }
  1406. return module;
  1407. }
  1408. /// <summary>
  1409. /// Called from generated code for:
  1410. ///
  1411. /// from spam import eggs1, eggs2
  1412. /// </summary>
  1413. [ProfilerTreatsAsExternal]
  1414. public static object ImportWithNames(CodeContext/*!*/ context, string fullName, string[] names, int level) {
  1415. return Importer.Import(context, fullName, PythonTuple.MakeTuple(names), level);
  1416. }
  1417. /// <summary>
  1418. /// Imports one element from the module in the context of:
  1419. ///
  1420. /// from module import a, b, c, d
  1421. ///
  1422. /// Called repeatedly for all elements being imported (a, b, c, d above)
  1423. /// </summary>
  1424. public static object ImportFrom(CodeContext/*!*/ context, object module, string name) {
  1425. return Importer.ImportFrom(context, module, name);
  1426. }
  1427. /// <summary>
  1428. /// Called from generated code for:
  1429. ///
  1430. /// from spam import *
  1431. /// </summary>
  1432. [ProfilerTreatsAsExternal]
  1433. public static void ImportStar(CodeContext/*!*/ context, string fullName, int level) {
  1434. object newmod = Importer.Import(context, fullName, PythonTuple.MakeTuple("*"), level);
  1435. PythonModule scope = newmod as PythonModule;
  1436. NamespaceTracker nt = newmod as NamespaceTracker;
  1437. PythonType pt = newmod as PythonType;
  1438. if (pt != null &&
  1439. !pt.UnderlyingSystemType.IsEnum &&
  1440. (!pt.UnderlyingSystemType.IsAbstract || !pt.UnderlyingSystemType.IsSealed)) {
  1441. // from type import * only allowed on static classes (and enums)
  1442. throw PythonOps.ImportError("no module named {0}", pt.Name);
  1443. }
  1444. IEnumerator exports;
  1445. object all;
  1446. bool filterPrivates = false;
  1447. // look for __all__, if it's defined then use that to get the attribute names,
  1448. // otherwise get all the names and filter out members starting w/ _'s.
  1449. if (PythonOps.TryGetBoundAttr(context, newmod, "__all__", out all)) {
  1450. exports = PythonOps.GetEnumerator(all);
  1451. } else {
  1452. exports = PythonOps.GetAttrNames(context, newmod).GetEnumerator();
  1453. filterPrivates = true;
  1454. }
  1455. // iterate through the names and populate the scope with the values.
  1456. while (exports.MoveNext()) {
  1457. string name = exports.Current as string;
  1458. if (name == null) {
  1459. throw PythonOps.TypeErrorForNonStringAttribute();
  1460. } else if (filterPrivates && name.Length > 0 && name[0] == '_') {
  1461. continue;
  1462. }
  1463. // we special case several types to avoid one-off code gen of dynamic sites
  1464. if (scope != null) {
  1465. context.SetVariable(name, scope.__dict__[name]);
  1466. } else if (nt != null) {
  1467. object value = NamespaceTrackerOps.GetCustomMember(context, nt, name);
  1468. if (value != OperationFailed.Value) {
  1469. context.SetVariable(name, value);
  1470. }
  1471. } else if (pt != null) {
  1472. PythonTypeSlot pts;
  1473. object value;
  1474. if (pt.TryResolveSlot(context, name, out pts) &&
  1475. pts.TryGetValue(context, null, pt, out value)) {
  1476. context.SetVariable(name, value);
  1477. }
  1478. } else {
  1479. // not a known type, we'll do use a site to do the get...
  1480. context.SetVariable(name, PythonOps.GetBoundAttr(context, newmod, name));
  1481. }
  1482. }
  1483. }
  1484. #endregion
  1485. #region Exec
  1486. /// <summary>
  1487. /// Unqualified exec statement support.
  1488. /// A Python helper which will be called for the statement:
  1489. ///
  1490. /// exec code
  1491. /// </summary>
  1492. [ProfilerTreatsAsExternal]
  1493. public static void UnqualifiedExec(CodeContext/*!*/ context, object code) {
  1494. PythonDictionary locals = null;
  1495. PythonDictionary globals = null;
  1496. // if the user passes us a tuple we'll extract the 3 values out of it
  1497. PythonTuple codeTuple = code as PythonTuple;
  1498. if (codeTuple != null && codeTuple.__len__() > 0 && codeTuple.__len__() <= 3) {
  1499. code = codeTuple[0];
  1500. if (codeTuple.__len__() > 1 && codeTuple[1] != null) {
  1501. globals = codeTuple[1] as PythonDictionary;
  1502. if (globals == null) throw PythonOps.TypeError("globals must be dictionary or none");
  1503. }
  1504. if (codeTuple.__len__() > 2 && codeTuple[2] != null) {
  1505. locals = codeTuple[2] as PythonDictionary;
  1506. if (locals == null) throw PythonOps.TypeError("locals must be dictionary or none");
  1507. } else {
  1508. locals = globals;
  1509. }
  1510. }
  1511. QualifiedExec(context, code, globals, locals);
  1512. }
  1513. /// <summary>
  1514. /// Qualified exec statement support,
  1515. /// Python helper which will be called for the statement:
  1516. ///
  1517. /// exec code in globals [, locals ]
  1518. /// </summary>
  1519. [ProfilerTreatsAsExternal]
  1520. public static void QualifiedExec(CodeContext/*!*/ context, object code, PythonDictionary globals, object locals) {
  1521. PythonFile pf;
  1522. Stream cs;
  1523. var pythonContext = PythonContext.GetContext(context);
  1524. bool noLineFeed = true;
  1525. // TODO: use ContentProvider?
  1526. if ((pf = code as PythonFile) != null) {
  1527. List lines = pf.readlines();
  1528. StringBuilder fullCode = new StringBuilder();
  1529. for (int i = 0; i < lines.__len__(); i++) {
  1530. fullCode.Append(lines[i]);
  1531. }
  1532. code = fullCode.ToString();
  1533. } else if ((cs = code as Stream) != null) {
  1534. using (StreamReader reader = new StreamReader(cs)) { // TODO: encoding?
  1535. code = reader.ReadToEnd();
  1536. }
  1537. noLineFeed = false;
  1538. }
  1539. string strCode = code as string;
  1540. if (strCode != null) {
  1541. SourceUnit source;
  1542. if (noLineFeed) {
  1543. source = pythonContext.CreateSourceUnit(new NoLineFeedSourceContentProvider(strCode), "<string>", SourceCodeKind.Statements);
  1544. } else {
  1545. source = pythonContext.CreateSnippet(strCode, SourceCodeKind.Statements);
  1546. }
  1547. PythonCompilerOptions compilerOptions = Builtin.GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
  1548. // do interpretation only on strings -- not on files, streams, or code objects
  1549. code = FunctionCode.FromSourceUnit(source, compilerOptions);
  1550. }
  1551. FunctionCode fc = code as FunctionCode;
  1552. if (fc == null) {
  1553. throw PythonOps.TypeError("arg 1 must be a string, file, Stream, or code object, not {0}", PythonTypeOps.GetName(code));
  1554. }
  1555. if (locals == null) locals = globals;
  1556. if (globals == null) globals = context.GlobalDict;
  1557. if (locals != null && PythonOps.IsMappingType(context, locals) != ScriptingRuntimeHelpers.True) {
  1558. throw PythonOps.TypeError("exec: arg 3 must be mapping or None");
  1559. }
  1560. CodeContext execContext = Builtin.GetExecEvalScope(context, globals, Builtin.GetAttrLocals(context, locals), true, false);
  1561. if (context.LanguageContext.PythonOptions.Frames) {
  1562. List<FunctionStack> stack = PushFrame(execContext, fc);
  1563. try {
  1564. fc.Call(execContext);
  1565. } finally {
  1566. stack.RemoveAt(stack.Count - 1);
  1567. }
  1568. } else {
  1569. fc.Call(execContext);
  1570. }
  1571. }
  1572. #endregion
  1573. public static ICollection GetCollection(object o) {
  1574. ICollection ret = o as ICollection;
  1575. if (ret != null) return ret;
  1576. List<object> al = new List<object>();
  1577. IEnumerator e = GetEnumerator(o);
  1578. while (e.MoveNext()) al.Add(e.Current);
  1579. return al;
  1580. }
  1581. public static IEnumerator GetEnumerator(object o) {
  1582. return GetEnumerator(DefaultContext.Default, o);
  1583. }
  1584. public static IEnumerator GetEnumerator(CodeContext/*!*/ context, object o) {
  1585. IEnumerator ie;
  1586. if (!TryGetEnumerator(context, o, out ie)) {
  1587. throw PythonOps.TypeError("{0} is not iterable", PythonTypeOps.GetName(o));
  1588. }
  1589. return ie;
  1590. }
  1591. // Lack of type restrictions allows this method to return the direct result of __iter__ without
  1592. // wrapping it. This is the proper behavior for Builtin.iter().
  1593. public static object GetEnumeratorObject(CodeContext/*!*/ context, object o) {
  1594. object iterFunc;
  1595. if (PythonOps.TryGetBoundAttr(context, o, "__iter__", out iterFunc) &&
  1596. !Object.ReferenceEquals(iterFunc, NotImplementedType.Value)) {
  1597. return PythonOps.CallWithContext(context, iterFunc);
  1598. }
  1599. return GetEnumerator(context, o);
  1600. }
  1601. public static IEnumerator GetEnumeratorForUnpack(CodeContext/*!*/ context, object enumerable) {
  1602. IEnumerator enumerator;
  1603. if (!TryGetEnumerator(context, enumerable, out enumerator)) {
  1604. throw PythonOps.TypeError("'{0}' object is not iterable", PythonTypeOps.GetName(enumerable));
  1605. }
  1606. return enumerator;
  1607. }
  1608. public static KeyValuePair<IEnumerator, IDisposable> ThrowTypeErrorForBadIteration(CodeContext context, object enumerable) {
  1609. throw PythonOps.TypeError("iteration over non-sequence of type {0}", PythonTypeOps.GetName(enumerable));
  1610. }
  1611. internal static bool TryGetEnumerator(CodeContext/*!*/ context, object enumerable, out IEnumerator enumerator) {
  1612. enumerator = null;
  1613. IEnumerable enumer;
  1614. if (PythonContext.GetContext(context).TryConvertToIEnumerable(enumerable, out enumer)) {
  1615. enumerator = enumer.GetEnumerator();
  1616. return true;
  1617. }
  1618. return false;
  1619. }
  1620. public static void ForLoopDispose(KeyValuePair<IEnumerator, IDisposable> iteratorInfo) {
  1621. if (iteratorInfo.Value != null) {
  1622. iteratorInfo.Value.Dispose();
  1623. }
  1624. }
  1625. public static KeyValuePair<IEnumerator, IDisposable> StringEnumerator(string str) {
  1626. return new KeyValuePair<IEnumerator, IDisposable>(StringOps.StringEnumerator(str), null);
  1627. }
  1628. public static KeyValuePair<IEnumerator, IDisposable> BytesEnumerator(IList<byte> bytes) {
  1629. return new KeyValuePair<IEnumerator, IDisposable>(IListOfByteOps.BytesEnumerator(bytes), null);
  1630. }
  1631. public static KeyValuePair<IEnumerator, IDisposable> BytesIntEnumerator(IList<byte> bytes) {
  1632. return new KeyValuePair<IEnumerator, IDisposable>(IListOfByteOps.BytesIntEnumerator(bytes), null);
  1633. }
  1634. public static KeyValuePair<IEnumerator, IDisposable> GetEnumeratorFromEnumerable(IEnumerable enumerable) {
  1635. IEnumerator enumerator = enumerable.GetEnumerator();
  1636. return new KeyValuePair<IEnumerator, IDisposable>(enumerator, enumerator as IDisposable);
  1637. }
  1638. public static IEnumerable StringEnumerable(string str) {
  1639. return StringOps.StringEnumerable(str);
  1640. }
  1641. public static IEnumerable BytesEnumerable(IList<byte> bytes) {
  1642. return IListOfByteOps.BytesEnumerable(bytes);
  1643. }
  1644. public static IEnumerable BytesIntEnumerable(IList<byte> bytes) {
  1645. return IListOfByteOps.BytesIntEnumerable(bytes);
  1646. }
  1647. #region Exception handling
  1648. // The semantics here are:
  1649. // 1. Each thread has a "current exception", which is returned as a tuple by sys.exc_info().
  1650. // 2. The current exception is set on encountering an except block, even if the except block doesn't
  1651. // match the exception.
  1652. // 3. Each function on exit (either via exception, return, or yield) will restore the "current exception"
  1653. // to the value it had on function-entry.
  1654. //
  1655. // So common codegen would be:
  1656. //
  1657. // function() {
  1658. // $save = SaveCurrentException();
  1659. // try {
  1660. // def foo():
  1661. // try:
  1662. // except:
  1663. // SetCurrentException($exception)
  1664. // <except body>
  1665. //
  1666. // finally {
  1667. // RestoreCurrentException($save)
  1668. // }
  1669. // Called at the start of the except handlers to set the current exception.
  1670. public static object SetCurrentException(CodeContext/*!*/ context, Exception/*!*/ clrException) {
  1671. Assert.NotNull(clrException);
  1672. // we need to extract before we check because ThreadAbort.ExceptionState is cleared after
  1673. // we reset the abort.
  1674. object res = PythonExceptions.ToPython(clrException);
  1675. #if !SILVERLIGHT
  1676. // Check for thread abort exceptions.
  1677. // This is necessary to be able to catch python's KeyboardInterrupt exceptions.
  1678. // CLR restrictions require that this must be called from within a catch block. This gets
  1679. // called even if we aren't going to handle the exception - we'll just reset the abort
  1680. ThreadAbortException tae = clrException as ThreadAbortException;
  1681. if (tae != null && tae.ExceptionState is KeyboardInterruptException) {
  1682. Thread.ResetAbort();
  1683. }
  1684. #endif
  1685. RawException = clrException;
  1686. return res;
  1687. }
  1688. public static void BuildExceptionInfo(CodeContext/*!*/ context, Exception clrException) {
  1689. ExceptionHelpers.AssociateDynamicStackFrames(clrException);
  1690. GetExceptionInfo(context);
  1691. ClearDynamicStackFrames();
  1692. }
  1693. // Clear the current exception. Most callers should restore the exception.
  1694. // This is mainly for sys.exc_clear()
  1695. public static void ClearCurrentException() {
  1696. RestoreCurrentException(null);
  1697. }
  1698. public static void ExceptionHandled(CodeContext context) {
  1699. PythonContext.GetContext(context).DelSystemStateValue("exc_traceback");
  1700. PythonContext.GetContext(context).DelSystemStateValue("exc_value");
  1701. PythonContext.GetContext(context).DelSystemStateValue("exc_type");
  1702. }
  1703. // Called by code-gen to save it. Codegen just needs to pass this back to RestoreCurrentException.
  1704. public static Exception SaveCurrentException() {
  1705. return RawException;
  1706. }
  1707. // Called at function exit (like popping). Pass value from SaveCurrentException.
  1708. public static void RestoreCurrentException(Exception clrException) {
  1709. RawException = clrException;
  1710. }
  1711. public static object CheckException(CodeContext context, object exception, object test) {
  1712. Debug.Assert(exception != null);
  1713. ObjectException objex;
  1714. if (test is PythonTuple) {
  1715. // we handle multiple exceptions, we'll check them one at a time.
  1716. PythonTuple tt = test as PythonTuple;
  1717. for (int i = 0; i < tt.__len__(); i++) {
  1718. object res = CheckException(context, exception, tt[i]);
  1719. if (res != null) return res;
  1720. }
  1721. } else if ((objex = exception as ObjectException) != null) {
  1722. if (PythonOps.IsSubClass(context, objex.Type, test)) {
  1723. return objex.Instance;
  1724. }
  1725. return null;
  1726. } else if (test is OldClass) {
  1727. if (PythonOps.IsInstance(context, exception, test)) {
  1728. // catching a Python type.
  1729. return exception;
  1730. }
  1731. } else if (test is PythonType) {
  1732. if (PythonOps.IsSubClass(test as PythonType, TypeCache.BaseException)) {
  1733. // catching a Python exception type explicitly.
  1734. if (PythonOps.IsInstance(context, exception, test)) return exception;
  1735. } else if (PythonOps.IsSubClass(test as PythonType, DynamicHelpers.GetPythonTypeFromType(typeof(Exception)))) {
  1736. // catching a CLR exception type explicitly.
  1737. Exception clrEx = PythonExceptions.ToClr(exception);
  1738. if (PythonOps.IsInstance(context, clrEx, test)) return clrEx;
  1739. }
  1740. }
  1741. return null;
  1742. }
  1743. private static TraceBack CreateTraceBack(PythonContext pyContext, Exception e) {
  1744. // user provided trace back
  1745. if (e.Data.Contains(typeof(TraceBack))) {
  1746. return (TraceBack)e.Data[typeof(TraceBack)];
  1747. }
  1748. DynamicStackFrame[] frames = ScriptingRuntimeHelpers.GetDynamicStackFrames(e, false);
  1749. TraceBack tb = null;
  1750. for (int i = 0; i < frames.Length; i++) {
  1751. DynamicStackFrame frame = frames[i];
  1752. string name = frame.GetMethodName();
  1753. if (name.IndexOf('#') > 0) {
  1754. // dynamic method, strip the trailing id...
  1755. name = name.Substring(0, name.IndexOf('#'));
  1756. }
  1757. PythonDynamicStackFrame pyFrame = frame as PythonDynamicStackFrame;
  1758. if (pyFrame != null) {
  1759. CodeContext context = pyFrame.CodeContext;
  1760. FunctionCode code = pyFrame.Code;
  1761. TraceBackFrame tbf = new TraceBackFrame(
  1762. context,
  1763. context.GlobalDict,
  1764. context.Dict,
  1765. code);
  1766. tb = new TraceBack(tb, tbf);
  1767. tb.SetLine(frame.GetFileLineNumber());
  1768. }
  1769. }
  1770. e.Data[typeof(TraceBack)] = tb;
  1771. return tb;
  1772. }
  1773. /// <summary>
  1774. /// Get an exception tuple for the "current" exception. This is used for sys.exc_info()
  1775. /// </summary>
  1776. public static PythonTuple GetExceptionInfo(CodeContext/*!*/ context) {
  1777. return GetExceptionInfoLocal(context, RawException);
  1778. }
  1779. /// <summary>
  1780. /// Get an exception tuple for a given exception. This is like the inverse of MakeException.
  1781. /// </summary>
  1782. /// <param name="context">the code context</param>
  1783. /// <param name="ex">the exception to create a tuple for.</param>
  1784. /// <returns>a tuple of (type, value, traceback)</returns>
  1785. /// <remarks>This is called directly by the With statement so that it can get an exception tuple
  1786. /// in its own private except handler without disturbing the thread-wide sys.exc_info(). </remarks>
  1787. public static PythonTuple/*!*/ GetExceptionInfoLocal(CodeContext/*!*/ context, Exception ex) {
  1788. if (ex == null) {
  1789. return PythonTuple.MakeTuple(null, null, null);
  1790. }
  1791. object pyExcep = PythonExceptions.ToPython(ex);
  1792. PythonContext pc = PythonContext.GetContext(context);
  1793. TraceBack tb = CreateTraceBack(pc, ex);
  1794. pc.SystemExceptionTraceBack = tb;
  1795. object excType = PythonOps.GetBoundAttr(context, pyExcep, "__class__");
  1796. pc.SystemExceptionType = excType;
  1797. pc.SystemExceptionValue = pyExcep;
  1798. return PythonTuple.MakeTuple(
  1799. excType,
  1800. pyExcep,
  1801. tb);
  1802. }
  1803. /// <summary>
  1804. /// helper function for re-raised exceptions.
  1805. /// </summary>
  1806. public static Exception MakeRethrownException(CodeContext/*!*/ context) {
  1807. PythonTuple t = GetExceptionInfo(context);
  1808. Exception e = MakeExceptionWorker(context, t[0], t[1], t[2], true);
  1809. return MakeRethrowExceptionWorker(e);
  1810. }
  1811. public static Exception MakeRethrowExceptionWorker(Exception e) {
  1812. e.Data.Remove(typeof(TraceBack));
  1813. ExceptionHelpers.UpdateForRethrow(e);
  1814. return e;
  1815. }
  1816. /// <summary>
  1817. /// helper function for non-re-raise exceptions.
  1818. ///
  1819. /// type is the type of exception to throw or an instance. If it
  1820. /// is an instance then value should be null.
  1821. ///
  1822. /// If type is a type then value can either be an instance of type,
  1823. /// a Tuple, or a single value. This case is handled by EC.CreateThrowable.
  1824. /// </summary>
  1825. public static Exception MakeException(CodeContext/*!*/ context, object type, object value, object traceback) {
  1826. return MakeExceptionWorker(context, type, value, traceback, false);
  1827. }
  1828. private static Exception MakeExceptionWorker(CodeContext context, object type, object value, object traceback, bool forRethrow) {
  1829. Exception throwable;
  1830. PythonType pt;
  1831. if (type is Exception) {
  1832. throwable = type as Exception;
  1833. } else if (type is PythonExceptions.BaseException) {
  1834. throwable = PythonExceptions.ToClr(type);
  1835. } else if ((pt = type as PythonType) != null && typeof(PythonExceptions.BaseException).IsAssignableFrom(pt.UnderlyingSystemType)) {
  1836. throwable = PythonExceptions.CreateThrowableForRaise(context, pt, value);
  1837. } else if (type is OldClass) {
  1838. if (value == null) {
  1839. throwable = new OldInstanceException((OldInstance)PythonCalls.Call(context, type));
  1840. } else {
  1841. throwable = PythonExceptions.CreateThrowableForRaise(context, (OldClass)type, value);
  1842. }
  1843. } else if (type is OldInstance) {
  1844. throwable = new OldInstanceException((OldInstance)type);
  1845. } else {
  1846. throwable = MakeExceptionTypeError(type);
  1847. }
  1848. IDictionary dict = throwable.Data;
  1849. if (traceback != null) {
  1850. if (!forRethrow) {
  1851. TraceBack tb = traceback as TraceBack;
  1852. if (tb == null) throw PythonOps.TypeError("traceback argument must be a traceback object");
  1853. dict[typeof(TraceBack)] = tb;
  1854. }
  1855. } else if (dict.Contains(typeof(TraceBack))) {
  1856. dict.Remove(typeof(TraceBack));
  1857. }
  1858. if (!forRethrow) {
  1859. ExceptionHelpers.ClearDynamicStackFrames(throwable);
  1860. }
  1861. PerfTrack.NoteEvent(PerfTrack.Categories.Exceptions, throwable);
  1862. return throwable;
  1863. }
  1864. public static Exception CreateThrowable(PythonType type, params object[] args) {
  1865. return PythonExceptions.CreateThrowable(type, args);
  1866. }
  1867. public static void ClearDynamicStackFrames() {
  1868. ExceptionHelpers.DynamicStackFrames = null;
  1869. }
  1870. public static List<DynamicStackFrame> GetAndClearDynamicStackFrames() {
  1871. List<DynamicStackFrame> res = ExceptionHelpers.DynamicStackFrames;
  1872. ClearDynamicStackFrames();
  1873. return res;
  1874. }
  1875. public static void SetDynamicStackFrames(List<DynamicStackFrame> frames) {
  1876. ExceptionHelpers.DynamicStackFrames = frames;
  1877. }
  1878. #endregion
  1879. public static string[] GetFunctionSignature(PythonFunction function) {
  1880. return new string[] { function.GetSignatureString() };
  1881. }
  1882. public static PythonDictionary CopyAndVerifyDictionary(PythonFunction function, IDictionary dict) {
  1883. foreach (object o in dict.Keys) {
  1884. if (!(o is string)) {
  1885. throw TypeError("{0}() keywords most be strings", function.__name__);
  1886. }
  1887. }
  1888. return new PythonDictionary(dict);
  1889. }
  1890. public static PythonDictionary/*!*/ CopyAndVerifyUserMapping(PythonFunction/*!*/ function, object dict) {
  1891. return UserMappingToPythonDictionary(function.Context, dict, function.func_name);
  1892. }
  1893. public static PythonDictionary UserMappingToPythonDictionary(CodeContext context, object dict, string funcName) {
  1894. // call dict.keys()
  1895. object keys;
  1896. if (!PythonTypeOps.TryInvokeUnaryOperator(context, dict, "keys", out keys)) {
  1897. throw PythonOps.TypeError("{0}() argument after ** must be a mapping, not {1}",
  1898. funcName,
  1899. PythonTypeOps.GetName(dict));
  1900. }
  1901. PythonDictionary res = new PythonDictionary();
  1902. // enumerate the keys getting their values
  1903. IEnumerator enumerator = GetEnumerator(keys);
  1904. while (enumerator.MoveNext()) {
  1905. object o = enumerator.Current;
  1906. string s = o as string;
  1907. if (s == null) {
  1908. Extensible<string> es = o as Extensible<string>;
  1909. if (es == null) {
  1910. throw PythonOps.TypeError("{0}() keywords most be strings, not {0}",
  1911. funcName,
  1912. PythonTypeOps.GetName(dict));
  1913. }
  1914. s = es.Value;
  1915. }
  1916. res[o] = PythonOps.GetIndex(context, dict, o);
  1917. }
  1918. return res;
  1919. }
  1920. public static PythonDictionary CopyAndVerifyPythonDictionary(PythonFunction function, PythonDictionary dict) {
  1921. if (dict._storage.HasNonStringAttributes()) {
  1922. throw TypeError("{0}() keywords most be strings", function.__name__);
  1923. }
  1924. return new PythonDictionary(dict);
  1925. }
  1926. public static object ExtractDictionaryArgument(PythonFunction function, string name, int argCnt, PythonDictionary dict) {
  1927. object val;
  1928. if (dict.TryGetValue(name, out val)) {
  1929. dict.Remove(name);
  1930. return val;
  1931. }
  1932. throw PythonOps.TypeError("{0}() takes exactly {1} non-keyword arguments ({2} given)",
  1933. function.__name__,
  1934. function.NormalArgumentCount,
  1935. argCnt);
  1936. }
  1937. public static void AddDictionaryArgument(PythonFunction function, string name, object value, PythonDictionary dict) {
  1938. if (dict.ContainsKey(name)) {
  1939. throw MultipleKeywordArgumentError(function, name);
  1940. }
  1941. dict[name] = value;
  1942. }
  1943. public static void VerifyUnduplicatedByPosition(PythonFunction function, string name, int position, int listlen) {
  1944. if (listlen > 0 && listlen > position) {
  1945. throw MultipleKeywordArgumentError(function, name);
  1946. }
  1947. }
  1948. public static List CopyAndVerifyParamsList(PythonFunction function, object list) {
  1949. return new List(list);
  1950. }
  1951. public static PythonTuple GetOrCopyParamsTuple(PythonFunction function, object input) {
  1952. if (input == null) {
  1953. throw PythonOps.TypeError("{0}() argument after * must be a sequence, not NoneType", function.func_name);
  1954. } else if (input.GetType() == typeof(PythonTuple)) {
  1955. return (PythonTuple)input;
  1956. }
  1957. return PythonTuple.Make(input);
  1958. }
  1959. public static object ExtractParamsArgument(PythonFunction function, int argCnt, List list) {
  1960. if (list.__len__() != 0) {
  1961. return list.pop(0);
  1962. }
  1963. throw function.BadArgumentError(argCnt);
  1964. }
  1965. public static void AddParamsArguments(List list, params object[] args) {
  1966. for (int i = 0; i < args.Length; i++) {
  1967. list.insert(i, args[i]);
  1968. }
  1969. }
  1970. /// <summary>
  1971. /// Extracts an argument from either the dictionary or params
  1972. /// </summary>
  1973. public static object ExtractAnyArgument(PythonFunction function, string name, int argCnt, List list, IDictionary dict) {
  1974. object val;
  1975. if (dict.Contains(name)) {
  1976. if (list.__len__() != 0) {
  1977. throw MultipleKeywordArgumentError(function, name);
  1978. }
  1979. val = dict[name];
  1980. dict.Remove(name);
  1981. return val;
  1982. }
  1983. if (list.__len__() != 0) {
  1984. return list.pop(0);
  1985. }
  1986. if (function.ExpandDictPosition == -1 && dict.Count > 0) {
  1987. // python raises an error for extra splatted kw keys before missing arguments.
  1988. // therefore we check for this in the error case here.
  1989. foreach (string x in dict.Keys) {
  1990. bool found = false;
  1991. foreach (string y in function.ArgNames) {
  1992. if (x == y) {
  1993. found = true;
  1994. break;
  1995. }
  1996. }
  1997. if (!found) {
  1998. throw UnexpectedKeywordArgumentError(function, x);
  1999. }
  2000. }
  2001. }
  2002. throw BinderOps.TypeErrorForIncorrectArgumentCount(
  2003. function.__name__,
  2004. function.NormalArgumentCount,
  2005. function.Defaults.Length,
  2006. argCnt,
  2007. function.ExpandListPosition != -1,
  2008. dict.Count > 0);
  2009. }
  2010. public static object GetParamsValueOrDefault(PythonFunction function, int index, List extraArgs) {
  2011. if (extraArgs.__len__() > 0) {
  2012. return extraArgs.pop(0);
  2013. }
  2014. return function.Defaults[index];
  2015. }
  2016. public static object GetFunctionParameterValue(PythonFunction function, int index, string name, List extraArgs, PythonDictionary dict) {
  2017. if (extraArgs != null && extraArgs.__len__() > 0) {
  2018. return extraArgs.pop(0);
  2019. }
  2020. object val;
  2021. if (dict != null && dict.TryRemoveValue(name, out val)) {
  2022. return val;
  2023. }
  2024. return function.Defaults[index];
  2025. }
  2026. public static void CheckParamsZero(PythonFunction function, List extraArgs) {
  2027. if (extraArgs.__len__() != 0) {
  2028. throw function.BadArgumentError(extraArgs.__len__() + function.NormalArgumentCount);
  2029. }
  2030. }
  2031. public static void CheckUserParamsZero(PythonFunction function, object sequence) {
  2032. int len = PythonOps.Length(sequence);
  2033. if (len != 0) {
  2034. throw function.BadArgumentError(len + function.NormalArgumentCount);
  2035. }
  2036. }
  2037. public static void CheckDictionaryZero(PythonFunction function, IDictionary dict) {
  2038. if (dict.Count != 0) {
  2039. IDictionaryEnumerator ie = dict.GetEnumerator();
  2040. ie.MoveNext();
  2041. throw UnexpectedKeywordArgumentError(function, (string)ie.Key);
  2042. }
  2043. }
  2044. public static bool CheckDictionaryMembers(PythonDictionary dict, string[] names) {
  2045. if (dict.Count != names.Length) {
  2046. return false;
  2047. }
  2048. foreach (string name in names) {
  2049. if (!dict.ContainsKey(name)) {
  2050. return false;
  2051. }
  2052. }
  2053. return true;
  2054. }
  2055. public static object PythonFunctionGetMember(PythonFunction function, string name) {
  2056. object res;
  2057. if (function._dict != null && function._dict.TryGetValue(name, out res)) {
  2058. return res;
  2059. }
  2060. return OperationFailed.Value;
  2061. }
  2062. public static object PythonFunctionSetMember(PythonFunction function, string name, object value) {
  2063. return function.__dict__[name] = value;
  2064. }
  2065. public static void PythonFunctionDeleteDict() {
  2066. throw PythonOps.TypeError("function's dictionary may not be deleted");
  2067. }
  2068. public static void PythonFunctionDeleteDoc(PythonFunction function) {
  2069. function.__doc__ = null;
  2070. }
  2071. public static void PythonFunctionDeleteDefaults(PythonFunction function) {
  2072. function.__defaults__ = null;
  2073. }
  2074. public static bool PythonFunctionDeleteMember(PythonFunction function, string name) {
  2075. if (function._dict == null) return false;
  2076. return function._dict.Remove(name);
  2077. }
  2078. /// <summary>
  2079. /// Creates a new array the values set to Uninitialized.Instance. The array
  2080. /// is large enough to hold for all of the slots allocated for the type and
  2081. /// its sub types.
  2082. /// </summary>
  2083. public static object[] InitializeUserTypeSlots(PythonType/*!*/ type) {
  2084. if (type.SlotCount == 0) {
  2085. // if we later set the weak reference obj we'll create the array
  2086. return null;
  2087. }
  2088. // weak reference is stored at end of slots
  2089. object[] res = new object[type.SlotCount + 1];
  2090. for (int i = 0; i < res.Length - 1; i++) {
  2091. res[i] = Uninitialized.Instance;
  2092. }
  2093. return res;
  2094. }
  2095. public static bool IsClsVisible(CodeContext/*!*/ context) {
  2096. return context.ModuleContext.ShowCls;
  2097. }
  2098. public static object GetInitMember(CodeContext/*!*/ context, PythonType type, object instance) {
  2099. object value;
  2100. bool res = type.TryGetNonCustomBoundMember(context, instance, "__init__", out value);
  2101. Debug.Assert(res);
  2102. return value;
  2103. }
  2104. public static object GetInitSlotMember(CodeContext/*!*/ context, PythonType type, PythonTypeSlot slot, object instance) {
  2105. object value;
  2106. if (!slot.TryGetValue(context, instance, type, out value)) {
  2107. throw PythonOps.TypeError("bad __init__");
  2108. }
  2109. return value;
  2110. }
  2111. public static object GetMixedMember(CodeContext/*!*/ context, PythonType type, object instance, string name) {
  2112. foreach (PythonType t in type.ResolutionOrder) {
  2113. if (t.IsOldClass) {
  2114. OldClass oc = (OldClass)ToPythonType(t);
  2115. object ret;
  2116. if (oc._dict._storage.TryGetValue(name, out ret)) {
  2117. if (instance != null) return oc.GetOldStyleDescriptor(context, ret, instance, oc);
  2118. return ret;
  2119. }
  2120. } else {
  2121. PythonTypeSlot dts;
  2122. if (t.TryLookupSlot(context, name, out dts)) {
  2123. object ret;
  2124. if (dts.TryGetValue(context, instance, type, out ret)) {
  2125. return ret;
  2126. }
  2127. return dts;
  2128. }
  2129. }
  2130. }
  2131. throw AttributeErrorForMissingAttribute(type, name);
  2132. }
  2133. #region Slicing support
  2134. /// <summary>
  2135. /// Helper to determine if the value is a simple numeric type (int or big int or bool) - used for OldInstance
  2136. /// deprecated form of slicing.
  2137. /// </summary>
  2138. public static bool IsNumericObject(object value) {
  2139. return value is int || value is Extensible<int> || value is BigInteger || value is Extensible<BigInteger> || value is bool;
  2140. }
  2141. /// <summary>
  2142. /// Helper to determine if the type is a simple numeric type (int or big int or bool) - used for OldInstance
  2143. /// deprecated form of slicing.
  2144. /// </summary>
  2145. internal static bool IsNumericType(Type t) {
  2146. return IsNonExtensibleNumericType(t) ||
  2147. t.IsSubclassOf(typeof(Extensible<int>)) ||
  2148. t.IsSubclassOf(typeof(Extensible<BigInteger>));
  2149. }
  2150. /// <summary>
  2151. /// Helper to determine if the type is a simple numeric type (int or big int or bool) but not a subclass
  2152. /// </summary>
  2153. internal static bool IsNonExtensibleNumericType(Type t) {
  2154. return t == typeof(int) ||
  2155. t == typeof(bool) ||
  2156. t == typeof(BigInteger);
  2157. }
  2158. /// <summary>
  2159. /// For slicing. Fixes up a BigInteger and returns an integer w/ the length of the
  2160. /// object added if the value is negative.
  2161. /// </summary>
  2162. public static int NormalizeBigInteger(object self, BigInteger bi, ref Nullable<int> length) {
  2163. int val;
  2164. if (bi < BigInteger.Zero) {
  2165. GetLengthOnce(self, ref length);
  2166. if (bi.AsInt32(out val)) {
  2167. Debug.Assert(length.HasValue);
  2168. return val + length.Value;
  2169. } else {
  2170. return -1;
  2171. }
  2172. } else if (bi.AsInt32(out val)) {
  2173. return val;
  2174. }
  2175. return Int32.MaxValue;
  2176. }
  2177. /// <summary>
  2178. /// For slicing. Gets the length of the object, used to only get the length once.
  2179. /// </summary>
  2180. public static int GetLengthOnce(object self, ref Nullable<int> length) {
  2181. if (length != null) return length.Value;
  2182. length = PythonOps.Length(self);
  2183. return length.Value;
  2184. }
  2185. #endregion
  2186. public static ReflectedEvent.BoundEvent MakeBoundEvent(ReflectedEvent eventObj, object instance, Type type) {
  2187. return new ReflectedEvent.BoundEvent(eventObj, instance, DynamicHelpers.GetPythonTypeFromType(type));
  2188. }
  2189. /// <summary>
  2190. /// Helper method for DynamicSite rules that check the version of their dynamic object
  2191. /// TODO - Remove this method for more direct field accesses
  2192. /// </summary>
  2193. /// <param name="o"></param>
  2194. /// <param name="version"></param>
  2195. /// <returns></returns>
  2196. public static bool CheckTypeVersion(object o, int version) {
  2197. IPythonObject po = o as IPythonObject;
  2198. if (po == null) return false;
  2199. return po.PythonType.Version == version;
  2200. }
  2201. public static bool CheckSpecificTypeVersion(PythonType type, int version) {
  2202. return type.Version == version;
  2203. }
  2204. #region Conversion helpers
  2205. internal static MethodInfo GetConversionHelper(string name, ConversionResultKind resultKind) {
  2206. MethodInfo res;
  2207. switch (resultKind) {
  2208. case ConversionResultKind.ExplicitCast:
  2209. case ConversionResultKind.ImplicitCast:
  2210. res = typeof(PythonOps).GetMethod("Throwing" + name);
  2211. break;
  2212. case ConversionResultKind.ImplicitTry:
  2213. case ConversionResultKind.ExplicitTry:
  2214. res = typeof(PythonOps).GetMethod("NonThrowing" + name);
  2215. break;
  2216. default: throw new InvalidOperationException();
  2217. }
  2218. Debug.Assert(res != null);
  2219. return res;
  2220. }
  2221. public static IEnumerable OldInstanceConvertToIEnumerableNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2222. object callable;
  2223. if (self.TryGetBoundCustomMember(context, "__iter__", out callable)) {
  2224. return CreatePythonEnumerable(self);
  2225. } else if (self.TryGetBoundCustomMember(context, "__getitem__", out callable)) {
  2226. return CreateItemEnumerable(callable, PythonContext.GetContext(context).GetItemCallSite);
  2227. }
  2228. return null;
  2229. }
  2230. public static IEnumerable/*!*/ OldInstanceConvertToIEnumerableThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2231. IEnumerable res = OldInstanceConvertToIEnumerableNonThrowing(context, self);
  2232. if (res == null) {
  2233. throw TypeErrorForTypeMismatch("IEnumerable", self);
  2234. }
  2235. return res;
  2236. }
  2237. public static IEnumerable<T> OldInstanceConvertToIEnumerableOfTNonThrowing<T>(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2238. object callable;
  2239. if (self.TryGetBoundCustomMember(context, "__iter__", out callable)) {
  2240. return new IEnumerableOfTWrapper<T>(CreatePythonEnumerable(self));
  2241. } else if (self.TryGetBoundCustomMember(context, "__getitem__", out callable)) {
  2242. return new IEnumerableOfTWrapper<T>(CreateItemEnumerable(callable, PythonContext.GetContext(context).GetItemCallSite));
  2243. }
  2244. return null;
  2245. }
  2246. public static IEnumerable<T>/*!*/ OldInstanceConvertToIEnumerableOfTThrowing<T>(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2247. IEnumerable<T> res = OldInstanceConvertToIEnumerableOfTNonThrowing<T>(context, self);
  2248. if (res == null) {
  2249. throw TypeErrorForTypeMismatch("IEnumerable[T]", self);
  2250. }
  2251. return res;
  2252. }
  2253. public static IEnumerator OldInstanceConvertToIEnumeratorNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2254. object callable;
  2255. if (self.TryGetBoundCustomMember(context, "__iter__", out callable)) {
  2256. return CreatePythonEnumerator(self);
  2257. } else if (self.TryGetBoundCustomMember(context, "__getitem__", out callable)) {
  2258. return CreateItemEnumerator(callable, PythonContext.GetContext(context).GetItemCallSite);
  2259. }
  2260. return null;
  2261. }
  2262. public static IEnumerator/*!*/ OldInstanceConvertToIEnumeratorThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2263. IEnumerator res = OldInstanceConvertToIEnumeratorNonThrowing(context, self);
  2264. if (res == null) {
  2265. throw TypeErrorForTypeMismatch("IEnumerator", self);
  2266. }
  2267. return res;
  2268. }
  2269. public static bool? OldInstanceConvertToBoolNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi) {
  2270. object value;
  2271. if (oi.TryGetBoundCustomMember(context, "__nonzero__", out value)) {
  2272. object res = NonThrowingConvertToNonZero(PythonCalls.Call(context, value));
  2273. if (res is int) {
  2274. return ((int)res) != 0;
  2275. } else if (res is bool) {
  2276. return (bool)res;
  2277. }
  2278. } else if (oi.TryGetBoundCustomMember(context, "__len__", out value)) {
  2279. int res;
  2280. if (Converter.TryConvertToInt32(PythonCalls.Call(context, value), out res)) {
  2281. return res != 0;
  2282. }
  2283. }
  2284. return null;
  2285. }
  2286. public static object OldInstanceConvertToBoolThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi) {
  2287. object value;
  2288. if (oi.TryGetBoundCustomMember(context, "__nonzero__", out value)) {
  2289. return ThrowingConvertToNonZero(PythonCalls.Call(context, value));
  2290. } else if (oi.TryGetBoundCustomMember(context, "__len__", out value)) {
  2291. return PythonContext.GetContext(context).ConvertToInt32(PythonCalls.Call(context, value)) != 0;
  2292. }
  2293. return null;
  2294. }
  2295. public static object OldInstanceConvertNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi, string conversion) {
  2296. object value;
  2297. if (oi.TryGetBoundCustomMember(context, conversion, out value)) {
  2298. if (conversion == "__int__") {
  2299. return NonThrowingConvertToInt(PythonCalls.Call(context, value));
  2300. } else if (conversion == "__long__") {
  2301. return NonThrowingConvertToLong(PythonCalls.Call(context, value));
  2302. } else if (conversion == "__float__") {
  2303. return NonThrowingConvertToFloat(PythonCalls.Call(context, value));
  2304. } else if (conversion == "__complex__") {
  2305. return NonThrowingConvertToComplex(PythonCalls.Call(context, value));
  2306. } else if (conversion == "__str__") {
  2307. return NonThrowingConvertToString(PythonCalls.Call(context, value));
  2308. } else {
  2309. Debug.Assert(false);
  2310. }
  2311. } else if (conversion == "__complex__") {
  2312. object res = OldInstanceConvertNonThrowing(context, oi, "__float__");
  2313. if (res == null) {
  2314. return null;
  2315. }
  2316. return Converter.ConvertToComplex(res);
  2317. }
  2318. return null;
  2319. }
  2320. public static object OldInstanceConvertThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi, string conversion) {
  2321. object value;
  2322. if (oi.TryGetBoundCustomMember(context, conversion, out value)) {
  2323. if (conversion == "__int__") {
  2324. return ThrowingConvertToInt(PythonCalls.Call(context, value));
  2325. } else if (conversion == "__long__") {
  2326. return ThrowingConvertToLong(PythonCalls.Call(context, value));
  2327. } else if (conversion == "__float__") {
  2328. return ThrowingConvertToFloat(PythonCalls.Call(context, value));
  2329. } else if (conversion == "__complex__") {
  2330. return ThrowingConvertToComplex(PythonCalls.Call(context, value));
  2331. } else if (conversion == "__str__") {
  2332. return ThrowingConvertToString(PythonCalls.Call(context, value));
  2333. } else {
  2334. Debug.Assert(false);
  2335. }
  2336. } else if (conversion == "__complex__") {
  2337. return OldInstanceConvertThrowing(context, oi, "__float__");
  2338. }
  2339. return null;
  2340. }
  2341. public static object ConvertFloatToComplex(object value) {
  2342. if (value == null) {
  2343. return null;
  2344. }
  2345. double d = (double)value;
  2346. return new Complex(d, 0.0);
  2347. }
  2348. internal static bool CheckingConvertToInt(object value) {
  2349. return value is int || value is BigInteger || value is Extensible<int> || value is Extensible<BigInteger>;
  2350. }
  2351. internal static bool CheckingConvertToLong(object value) {
  2352. return CheckingConvertToInt(value);
  2353. }
  2354. internal static bool CheckingConvertToFloat(object value) {
  2355. return value is double || (value != null && value is Extensible<double>);
  2356. }
  2357. internal static bool CheckingConvertToComplex(object value) {
  2358. return value is Complex || value is Extensible<Complex> || CheckingConvertToInt(value) || CheckingConvertToFloat(value);
  2359. }
  2360. internal static bool CheckingConvertToString(object value) {
  2361. return value is string || value is Extensible<string>;
  2362. }
  2363. public static bool CheckingConvertToNonZero(object value) {
  2364. return value is bool || value is int;
  2365. }
  2366. public static object NonThrowingConvertToInt(object value) {
  2367. if (!CheckingConvertToInt(value)) return null;
  2368. return value;
  2369. }
  2370. public static object NonThrowingConvertToLong(object value) {
  2371. if (!CheckingConvertToInt(value)) return null;
  2372. return value;
  2373. }
  2374. public static object NonThrowingConvertToFloat(object value) {
  2375. if (!CheckingConvertToFloat(value)) return null;
  2376. return value;
  2377. }
  2378. public static object NonThrowingConvertToComplex(object value) {
  2379. if (!CheckingConvertToComplex(value)) return null;
  2380. return value;
  2381. }
  2382. public static object NonThrowingConvertToString(object value) {
  2383. if (!CheckingConvertToString(value)) return null;
  2384. return value;
  2385. }
  2386. public static object NonThrowingConvertToNonZero(object value) {
  2387. if (!CheckingConvertToNonZero(value)) return null;
  2388. return value;
  2389. }
  2390. public static object ThrowingConvertToInt(object value) {
  2391. if (!CheckingConvertToInt(value)) throw TypeError(" __int__ returned non-int (type {0})", PythonTypeOps.GetName(value));
  2392. return value;
  2393. }
  2394. public static object ThrowingConvertToFloat(object value) {
  2395. if (!CheckingConvertToFloat(value)) throw TypeError(" __float__ returned non-float (type {0})", PythonTypeOps.GetName(value));
  2396. return value;
  2397. }
  2398. public static object ThrowingConvertToComplex(object value) {
  2399. if (!CheckingConvertToComplex(value)) throw TypeError(" __complex__ returned non-complex (type {0})", PythonTypeOps.GetName(value));
  2400. return value;
  2401. }
  2402. public static object ThrowingConvertToLong(object value) {
  2403. if (!CheckingConvertToComplex(value)) throw TypeError(" __long__ returned non-long (type {0})", PythonTypeOps.GetName(value));
  2404. return value;
  2405. }
  2406. public static object ThrowingConvertToString(object value) {
  2407. if (!CheckingConvertToString(value)) throw TypeError(" __str__ returned non-str (type {0})", PythonTypeOps.GetName(value));
  2408. return value;
  2409. }
  2410. public static bool ThrowingConvertToNonZero(object value) {
  2411. if (!CheckingConvertToNonZero(value)) throw TypeError("__nonzero__ should return bool or int, returned {0}", PythonTypeOps.GetName(value));
  2412. if (value is bool) {
  2413. return (bool)value;
  2414. }
  2415. return ((int)value) != 0;
  2416. }
  2417. #endregion
  2418. public static bool SlotTryGetBoundValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, out object value) {
  2419. Debug.Assert(slot != null);
  2420. return slot.TryGetValue(context, instance, owner, out value);
  2421. }
  2422. public static bool SlotTryGetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, out object value) {
  2423. return slot.TryGetValue(context, instance, owner, out value);
  2424. }
  2425. public static object SlotGetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner) {
  2426. object value;
  2427. if (!slot.TryGetValue(context, instance, owner, out value)) {
  2428. throw new InvalidOperationException();
  2429. }
  2430. return value;
  2431. }
  2432. public static bool SlotTrySetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, object value) {
  2433. return slot.TrySetValue(context, instance, owner, value);
  2434. }
  2435. public static object SlotSetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, object value) {
  2436. if (!slot.TrySetValue(context, instance, owner, value)) {
  2437. throw new InvalidOperationException();
  2438. }
  2439. return value;
  2440. }
  2441. public static bool SlotTryDeleteValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner) {
  2442. return slot.TryDeleteValue(context, instance, owner);
  2443. }
  2444. public static BuiltinFunction/*!*/ MakeBoundBuiltinFunction(BuiltinFunction/*!*/ function, object/*!*/ target) {
  2445. return function.BindToInstance(target);
  2446. }
  2447. /// <summary>
  2448. /// Called from generated code. Gets a builtin function and the BuiltinFunctionData associated
  2449. /// with the object. Tests to see if the function is bound and has the same data for the generated
  2450. /// rule.
  2451. /// </summary>
  2452. public static bool TestBoundBuiltinFunction(BuiltinFunction/*!*/ function, object data) {
  2453. if (function.IsUnbound) {
  2454. // not bound
  2455. return false;
  2456. }
  2457. return function.TestData(data);
  2458. }
  2459. public static BuiltinFunction/*!*/ GetBuiltinMethodDescriptorTemplate(BuiltinMethodDescriptor/*!*/ descriptor) {
  2460. return descriptor.Template;
  2461. }
  2462. public static int GetTypeVersion(PythonType type) {
  2463. return type.Version;
  2464. }
  2465. public static bool TryResolveTypeSlot(CodeContext/*!*/ context, PythonType type, string name, out PythonTypeSlot slot) {
  2466. return type.TryResolveSlot(context, name, out slot);
  2467. }
  2468. public static T[] ConvertTupleToArray<T>(PythonTuple tuple) {
  2469. T[] res = new T[tuple.__len__()];
  2470. for (int i = 0; i < tuple.__len__(); i++) {
  2471. try {
  2472. res[i] = (T)tuple[i];
  2473. } catch (InvalidCastException) {
  2474. res[i] = Converter.Convert<T>(tuple[i]);
  2475. }
  2476. }
  2477. return res;
  2478. }
  2479. #region Function helpers
  2480. public static PythonGenerator MakeGenerator(PythonFunction function, MutableTuple data, object generatorCode) {
  2481. Func<MutableTuple, object> next = generatorCode as Func<MutableTuple, object>;
  2482. if (next == null) {
  2483. next = ((LazyCode<Func<MutableTuple, object>>)generatorCode).EnsureDelegate();
  2484. }
  2485. return new PythonGenerator(function, next, data);
  2486. }
  2487. public static object MakeGeneratorExpression(object function, object input) {
  2488. PythonFunction func = (PythonFunction)function;
  2489. return ((Func<PythonFunction, object, object>)func.func_code.Target)(func, input);
  2490. }
  2491. public static FunctionCode MakeFunctionCode(CodeContext context, string name, string documentation, string[] argNames, FunctionAttributes flags, SourceSpan span, string path, Delegate code, string[] freeVars, string[] names, string[] cellVars, string[] varNames, int localCount) {
  2492. Compiler.Ast.SerializedScopeStatement scope = new Compiler.Ast.SerializedScopeStatement(name, argNames, flags, span, path, freeVars, names, cellVars, varNames);
  2493. return new FunctionCode(PythonContext.GetContext(context), code, scope, documentation, localCount);
  2494. }
  2495. [NoSideEffects]
  2496. public static object MakeFunction(CodeContext/*!*/ context, FunctionCode funcInfo, object modName, object[] defaults) {
  2497. return new PythonFunction(context, funcInfo, modName, defaults, null);
  2498. }
  2499. [NoSideEffects]
  2500. public static object MakeFunctionDebug(CodeContext/*!*/ context, FunctionCode funcInfo, object modName, object[] defaults, Delegate target) {
  2501. funcInfo.SetDebugTarget(PythonContext.GetContext(context), target);
  2502. return new PythonFunction(context, funcInfo, modName, defaults, null);
  2503. }
  2504. public static CodeContext FunctionGetContext(PythonFunction func) {
  2505. return func.Context;
  2506. }
  2507. public static object FunctionGetDefaultValue(PythonFunction func, int index) {
  2508. return func.Defaults[index];
  2509. }
  2510. public static int FunctionGetCompatibility(PythonFunction func) {
  2511. return func.FunctionCompatibility;
  2512. }
  2513. public static int FunctionGetID(PythonFunction func) {
  2514. return func.FunctionID;
  2515. }
  2516. public static Delegate FunctionGetTarget(PythonFunction func) {
  2517. return func.func_code.Target;
  2518. }
  2519. public static void FunctionPushFrame(PythonContext context) {
  2520. if (PythonFunction.AddRecursionDepth(1) > context.RecursionLimit) {
  2521. throw PythonOps.RuntimeError("maximum recursion depth exceeded");
  2522. }
  2523. }
  2524. public static void FunctionPushFrameCodeContext(CodeContext context) {
  2525. FunctionPushFrame(PythonContext.GetContext(context));
  2526. }
  2527. public static void FunctionPopFrame() {
  2528. PythonFunction.AddRecursionDepth(-1);
  2529. }
  2530. #endregion
  2531. public static object ReturnConversionResult(object value) {
  2532. PythonTuple pt = value as PythonTuple;
  2533. if (pt != null) {
  2534. return pt[0];
  2535. }
  2536. return NotImplementedType.Value;
  2537. }
  2538. /// <summary>
  2539. /// Convert object to a given type. This code is equivalent to NewTypeMaker.EmitConvertFromObject
  2540. /// except that it happens at runtime instead of compile time.
  2541. /// </summary>
  2542. public static T ConvertFromObject<T>(object obj) {
  2543. Type toType = typeof(T);
  2544. object result;
  2545. MethodInfo fastConvertMethod = PythonBinder.GetFastConvertMethod(toType);
  2546. if (fastConvertMethod != null) {
  2547. result = fastConvertMethod.Invoke(null, new object[] { obj });
  2548. } else if (typeof(Delegate).IsAssignableFrom(toType)) {
  2549. result = Converter.ConvertToDelegate(obj, toType);
  2550. } else {
  2551. result = obj;
  2552. }
  2553. return (T)obj;
  2554. }
  2555. public static DynamicMetaObjectBinder MakeComplexCallAction(int count, bool list, string[] keywords) {
  2556. Argument[] infos = CompilerHelpers.MakeRepeatedArray(Argument.Simple, count + keywords.Length);
  2557. if (list) {
  2558. infos[checked(count - 1)] = new Argument(ArgumentType.List);
  2559. }
  2560. for (int i = 0; i < keywords.Length; i++) {
  2561. infos[count + i] = new Argument(keywords[i]);
  2562. }
  2563. return DefaultContext.DefaultPythonContext.Invoke(
  2564. new CallSignature(infos)
  2565. );
  2566. }
  2567. public static DynamicMetaObjectBinder MakeSimpleCallAction(int count) {
  2568. return DefaultContext.DefaultPythonContext.Invoke(
  2569. new CallSignature(CompilerHelpers.MakeRepeatedArray(Argument.Simple, count))
  2570. );
  2571. }
  2572. public static PythonTuple ValidateCoerceResult(object coerceResult) {
  2573. if (coerceResult == null || coerceResult == NotImplementedType.Value) {
  2574. return null;
  2575. }
  2576. PythonTuple pt = coerceResult as PythonTuple;
  2577. if (pt == null) throw PythonOps.TypeError("coercion should return None, NotImplemented, or 2-tuple, got {0}", PythonTypeOps.GetName(coerceResult));
  2578. return pt;
  2579. }
  2580. public static object GetCoerceResultOne(PythonTuple coerceResult) {
  2581. return coerceResult._data[0];
  2582. }
  2583. public static object GetCoerceResultTwo(PythonTuple coerceResult) {
  2584. return coerceResult._data[1];
  2585. }
  2586. public static object MethodCheckSelf(CodeContext context, Method method, object self) {
  2587. return method.CheckSelf(context, self);
  2588. }
  2589. public static object GeneratorCheckThrowableAndReturnSendValue(object self) {
  2590. return ((PythonGenerator)self).CheckThrowableAndReturnSendValue();
  2591. }
  2592. public static ItemEnumerable CreateItemEnumerable(object callable, CallSite<Func<CallSite, CodeContext, object, int, object>> site) {
  2593. return new ItemEnumerable(callable, site);
  2594. }
  2595. public static DictionaryKeyEnumerator MakeDictionaryKeyEnumerator(PythonDictionary dict) {
  2596. return new DictionaryKeyEnumerator(dict._storage);
  2597. }
  2598. public static IEnumerable CreatePythonEnumerable(object baseObject) {
  2599. return PythonEnumerable.Create(baseObject);
  2600. }
  2601. public static IEnumerator CreateItemEnumerator(object callable, CallSite<Func<CallSite, CodeContext, object, int, object>> site) {
  2602. return new ItemEnumerator(callable, site);
  2603. }
  2604. public static IEnumerator CreatePythonEnumerator(object baseObject) {
  2605. return PythonEnumerator.Create(baseObject);
  2606. }
  2607. public static bool ContainsFromEnumerable(CodeContext/*!*/ context, object enumerable, object value) {
  2608. IEnumerator ie = enumerable as IEnumerator;
  2609. if (ie == null) {
  2610. IEnumerable ienum = enumerable as IEnumerable;
  2611. if (ienum != null) {
  2612. ie = ienum.GetEnumerator();
  2613. } else {
  2614. ie = Converter.ConvertToIEnumerator(enumerable);
  2615. }
  2616. }
  2617. while (ie.MoveNext()) {
  2618. if (PythonOps.EqualRetBool(context, ie.Current, value)) {
  2619. return true;
  2620. }
  2621. }
  2622. return false;
  2623. }
  2624. public static object PythonTypeGetMember(CodeContext/*!*/ context, PythonType type, object instance, string name) {
  2625. return type.GetMember(context, instance, name);
  2626. }
  2627. [NoSideEffects]
  2628. public static object CheckUninitialized(object value, string name) {
  2629. if (value == Uninitialized.Instance) {
  2630. throw new UnboundLocalException(String.Format("Local variable '{0}' referenced before assignment.", name));
  2631. }
  2632. return value;
  2633. }
  2634. #region OldClass/OldInstance public helpers
  2635. public static PythonDictionary OldClassGetDictionary(OldClass klass) {
  2636. return klass._dict;
  2637. }
  2638. public static string OldClassGetName(OldClass klass) {
  2639. return klass.Name;
  2640. }
  2641. public static bool OldInstanceIsCallable(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2642. object dummy;
  2643. return self.TryGetBoundCustomMember(context, "__call__", out dummy);
  2644. }
  2645. public static object OldClassCheckCallError(OldClass/*!*/ self, object dictionary, object list) {
  2646. if ((dictionary != null && PythonOps.Length(dictionary) != 0) ||
  2647. (list != null && PythonOps.Length(list) != 0)) {
  2648. return OldClass.MakeCallError();
  2649. }
  2650. return null;
  2651. }
  2652. public static object OldClassSetBases(OldClass oc, object value) {
  2653. oc.SetBases(value);
  2654. return value;
  2655. }
  2656. public static object OldClassSetName(OldClass oc, object value) {
  2657. oc.SetName(value);
  2658. return value;
  2659. }
  2660. public static object OldClassSetDictionary(OldClass oc, object value) {
  2661. oc.SetDictionary(value);
  2662. return value;
  2663. }
  2664. public static object OldClassSetNameHelper(OldClass oc, string name, object value) {
  2665. oc.SetNameHelper(name, value);
  2666. return value;
  2667. }
  2668. public static bool OldClassTryLookupInit(OldClass oc, object inst, out object ret) {
  2669. return oc.TryLookupInit(inst, out ret);
  2670. }
  2671. public static object OldClassMakeCallError(OldClass oc) {
  2672. return OldClass.MakeCallError();
  2673. }
  2674. public static PythonTuple OldClassGetBaseClasses(OldClass oc) {
  2675. return PythonTuple.MakeTuple(oc.BaseClasses.ToArray());
  2676. }
  2677. public static void OldClassDictionaryIsPublic(OldClass oc) {
  2678. oc.DictionaryIsPublic();
  2679. }
  2680. public static bool OldClassTryLookupValue(CodeContext context, OldClass oc, string name, out object value) {
  2681. return oc.TryLookupValue(context, name, out value);
  2682. }
  2683. public static object OldClassLookupValue(CodeContext context, OldClass oc, string name) {
  2684. return oc.LookupValue(context, name);
  2685. }
  2686. public static object OldInstanceGetOptimizedDictionary(OldInstance instance, int keyVersion) {
  2687. CustomInstanceDictionaryStorage storage = instance.Dictionary._storage as CustomInstanceDictionaryStorage;
  2688. if (storage == null || instance._class.HasSetAttr || storage.KeyVersion != keyVersion) {
  2689. return null;
  2690. }
  2691. return storage;
  2692. }
  2693. public static object OldInstanceDictionaryGetValueHelper(object dict, int index, object oldInstance) {
  2694. return ((CustomInstanceDictionaryStorage)dict).GetValueHelper(index, oldInstance);
  2695. }
  2696. public static bool TryOldInstanceDictionaryGetValueHelper(object dict, int index, object oldInstance, out object res) {
  2697. return ((CustomInstanceDictionaryStorage)dict).TryGetValueHelper(index, oldInstance, out res);
  2698. }
  2699. public static object OldInstanceGetBoundMember(CodeContext context, OldInstance instance, string name) {
  2700. return instance.GetBoundMember(context, name);
  2701. }
  2702. public static object OldInstanceDictionarySetExtraValue(object dict, int index, object value) {
  2703. ((CustomInstanceDictionaryStorage)dict).SetExtraValue(index, value);
  2704. return value;
  2705. }
  2706. public static object OldClassDeleteMember(CodeContext context, OldClass self, string name) {
  2707. self.DeleteCustomMember(context, name);
  2708. return null;
  2709. }
  2710. public static bool OldClassTryLookupOneSlot(PythonType type, OldClass self, string name, out object value) {
  2711. return self.TryLookupOneSlot(type, name, out value);
  2712. }
  2713. public static bool OldInstanceTryGetBoundCustomMember(CodeContext context, OldInstance self, string name, out object value) {
  2714. return self.TryGetBoundCustomMember(context, name, out value);
  2715. }
  2716. public static object OldInstanceSetCustomMember(CodeContext context, OldInstance self, string name, object value) {
  2717. self.SetCustomMember(context, name, value);
  2718. return value;
  2719. }
  2720. public static object OldInstanceDeleteCustomMember(CodeContext context, OldInstance self, string name) {
  2721. self.DeleteCustomMember(context, name);
  2722. return null;
  2723. }
  2724. #endregion
  2725. public static object PythonTypeSetCustomMember(CodeContext context, PythonType self, string name, object value) {
  2726. self.SetCustomMember(context, name, value);
  2727. return value;
  2728. }
  2729. public static object PythonTypeDeleteCustomMember(CodeContext context, PythonType self, string name) {
  2730. self.DeleteCustomMember(context, name);
  2731. return null;
  2732. }
  2733. public static bool IsPythonType(PythonType type) {
  2734. return type.IsPythonType;
  2735. }
  2736. public static object PublishModule(CodeContext/*!*/ context, string name) {
  2737. object original = null;
  2738. context.LanguageContext.SystemStateModules.TryGetValue(name, out original);
  2739. var module = ((PythonScopeExtension)context.GlobalScope.GetExtension(context.LanguageContext.ContextId)).Module;
  2740. context.LanguageContext.SystemStateModules[name] = module;
  2741. return original;
  2742. }
  2743. public static void RemoveModule(CodeContext/*!*/ context, string name, object oldValue) {
  2744. if (oldValue != null) {
  2745. PythonContext.GetContext(context).SystemStateModules[name] = oldValue;
  2746. } else {
  2747. PythonContext.GetContext(context).SystemStateModules.Remove(name);
  2748. }
  2749. }
  2750. public static Ellipsis Ellipsis {
  2751. get {
  2752. return Ellipsis.Value;
  2753. }
  2754. }
  2755. public static NotImplementedType NotImplemented {
  2756. get {
  2757. return NotImplementedType.Value;
  2758. }
  2759. }
  2760. public static void ListAddForComprehension(List l, object o) {
  2761. l.AddNoLock(o);
  2762. }
  2763. public static void ModuleStarted(CodeContext/*!*/ context, ModuleOptions features) {
  2764. context.ModuleContext.Features |= features;
  2765. }
  2766. public static void Warn(CodeContext/*!*/ context, PythonType category, string message, params object[] args) {
  2767. PythonContext pc = PythonContext.GetContext(context);
  2768. object warnings = pc.GetWarningsModule(), warn = null;
  2769. if (warnings != null) {
  2770. warn = PythonOps.GetBoundAttr(context, warnings, "warn");
  2771. }
  2772. message = FormatWarning(message, args);
  2773. if (warn == null) {
  2774. PythonOps.PrintWithDest(context, pc.SystemStandardError, "warning: " + category.Name + ": " + message);
  2775. } else {
  2776. PythonOps.CallWithContext(context, warn, message, category);
  2777. }
  2778. }
  2779. public static void ShowWarning(CodeContext/*!*/ context, PythonType category, string message, string filename, int lineNo) {
  2780. PythonContext pc = PythonContext.GetContext(context);
  2781. object warnings = pc.GetWarningsModule(), warn = null;
  2782. if (warnings != null) {
  2783. warn = PythonOps.GetBoundAttr(context, warnings, "showwarning");
  2784. }
  2785. if (warn == null) {
  2786. PythonOps.PrintWithDestNoNewline(context, pc.SystemStandardError, String.Format("{0}:{1}: {2}: {3}\n", filename, lineNo, category.Name, message));
  2787. } else {
  2788. PythonOps.CallWithContext(context, warn, message, category, filename ?? "", lineNo);
  2789. }
  2790. }
  2791. private static string FormatWarning(string message, object[] args) {
  2792. for (int i = 0; i < args.Length; i++) {
  2793. args[i] = PythonOps.ToString(args[i]);
  2794. }
  2795. message = String.Format(message, args);
  2796. return message;
  2797. }
  2798. private static bool IsPrimitiveNumber(object o) {
  2799. return IsNumericObject(o) ||
  2800. o is Complex ||
  2801. o is double ||
  2802. o is Extensible<Complex> ||
  2803. o is Extensible<double>;
  2804. }
  2805. public static void WarnDivision(CodeContext/*!*/ context, PythonDivisionOptions options, object self, object other) {
  2806. if (options == PythonDivisionOptions.WarnAll) {
  2807. if (IsPrimitiveNumber(self) && IsPrimitiveNumber(other)) {
  2808. if (self is Complex || other is Complex || self is Extensible<Complex> || other is Extensible<Complex>) {
  2809. Warn(context, PythonExceptions.DeprecationWarning, "classic complex division");
  2810. return;
  2811. } else if (self is double || other is double || self is Extensible<double> || other is Extensible<double>) {
  2812. Warn(context, PythonExceptions.DeprecationWarning, "classic float division");
  2813. return;
  2814. } else {
  2815. WarnDivisionInts(context, self, other);
  2816. }
  2817. }
  2818. } else if (IsNumericObject(self) && IsNumericObject(other)) {
  2819. WarnDivisionInts(context, self, other);
  2820. }
  2821. }
  2822. private static void WarnDivisionInts(CodeContext/*!*/ context, object self, object other) {
  2823. if (self is BigInteger || other is BigInteger || self is Extensible<BigInteger> || other is Extensible<BigInteger>) {
  2824. Warn(context, PythonExceptions.DeprecationWarning, "classic long division");
  2825. } else {
  2826. Warn(context, PythonExceptions.DeprecationWarning, "classic int division");
  2827. }
  2828. }
  2829. public static DynamicMetaObjectBinder MakeComboAction(CodeContext/*!*/ context, DynamicMetaObjectBinder opBinder, DynamicMetaObjectBinder convBinder) {
  2830. return PythonContext.GetContext(context).BinaryOperationRetType((PythonBinaryOperationBinder)opBinder, (PythonConversionBinder)convBinder);
  2831. }
  2832. public static DynamicMetaObjectBinder MakeInvokeAction(CodeContext/*!*/ context, CallSignature signature) {
  2833. return PythonContext.GetContext(context).Invoke(signature);
  2834. }
  2835. public static DynamicMetaObjectBinder MakeGetAction(CodeContext/*!*/ context, string name, bool isNoThrow) {
  2836. return PythonContext.GetContext(context).GetMember(name);
  2837. }
  2838. public static DynamicMetaObjectBinder MakeCompatGetAction(CodeContext/*!*/ context, string name) {
  2839. return PythonContext.GetContext(context).CompatGetMember(name, false);
  2840. }
  2841. public static DynamicMetaObjectBinder MakeCompatInvokeAction(CodeContext/*!*/ context, CallInfo callInfo) {
  2842. return PythonContext.GetContext(context).CompatInvoke(callInfo);
  2843. }
  2844. public static DynamicMetaObjectBinder MakeCompatConvertAction(CodeContext/*!*/ context, Type toType, bool isExplicit) {
  2845. return PythonContext.GetContext(context).Convert(toType, isExplicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast).CompatBinder;
  2846. }
  2847. public static DynamicMetaObjectBinder MakeSetAction(CodeContext/*!*/ context, string name) {
  2848. return PythonContext.GetContext(context).SetMember(name);
  2849. }
  2850. public static DynamicMetaObjectBinder MakeDeleteAction(CodeContext/*!*/ context, string name) {
  2851. return PythonContext.GetContext(context).DeleteMember(name);
  2852. }
  2853. public static DynamicMetaObjectBinder MakeConversionAction(CodeContext/*!*/ context, Type type, ConversionResultKind kind) {
  2854. return PythonContext.GetContext(context).Convert(type, kind);
  2855. }
  2856. public static DynamicMetaObjectBinder MakeTryConversionAction(CodeContext/*!*/ context, Type type, ConversionResultKind kind) {
  2857. return PythonContext.GetContext(context).Convert(type, kind);
  2858. }
  2859. public static DynamicMetaObjectBinder MakeOperationAction(CodeContext/*!*/ context, int operationName) {
  2860. return PythonContext.GetContext(context).Operation((PythonOperationKind)operationName);
  2861. }
  2862. public static DynamicMetaObjectBinder MakeUnaryOperationAction(CodeContext/*!*/ context, ExpressionType expressionType) {
  2863. return PythonContext.GetContext(context).UnaryOperation(expressionType);
  2864. }
  2865. public static DynamicMetaObjectBinder MakeBinaryOperationAction(CodeContext/*!*/ context, ExpressionType expressionType) {
  2866. return PythonContext.GetContext(context).BinaryOperation(expressionType);
  2867. }
  2868. public static DynamicMetaObjectBinder MakeGetIndexAction(CodeContext/*!*/ context, int argCount) {
  2869. return PythonContext.GetContext(context).GetIndex(argCount);
  2870. }
  2871. public static DynamicMetaObjectBinder MakeSetIndexAction(CodeContext/*!*/ context, int argCount) {
  2872. return PythonContext.GetContext(context).SetIndex(argCount);
  2873. }
  2874. public static DynamicMetaObjectBinder MakeDeleteIndexAction(CodeContext/*!*/ context, int argCount) {
  2875. return PythonContext.GetContext(context).DeleteIndex(argCount);
  2876. }
  2877. public static DynamicMetaObjectBinder MakeGetSliceBinder(CodeContext/*!*/ context) {
  2878. return PythonContext.GetContext(context).GetSlice;
  2879. }
  2880. public static DynamicMetaObjectBinder MakeSetSliceBinder(CodeContext/*!*/ context) {
  2881. return PythonContext.GetContext(context).SetSliceBinder;
  2882. }
  2883. public static DynamicMetaObjectBinder MakeDeleteSliceBinder(CodeContext/*!*/ context) {
  2884. return PythonContext.GetContext(context).DeleteSlice;
  2885. }
  2886. /// <summary>
  2887. /// Provides access to AppDomain.DefineDynamicAssembly which cannot be called from a DynamicMethod
  2888. /// </summary>
  2889. public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) {
  2890. return AppDomain.CurrentDomain.DefineDynamicAssembly(name, access);
  2891. }
  2892. /// <summary>
  2893. /// Generates a new delegate type. The last type in the array is the return type.
  2894. /// </summary>
  2895. public static Type/*!*/ MakeNewCustomDelegate(Type/*!*/[]/*!*/ types) {
  2896. return MakeNewCustomDelegate(types, null);
  2897. }
  2898. /// <summary>
  2899. /// Generates a new delegate type. The last type in the array is the return type.
  2900. /// </summary>
  2901. public static Type/*!*/ MakeNewCustomDelegate(Type/*!*/[]/*!*/ types, CallingConvention? callingConvention) {
  2902. const MethodAttributes CtorAttributes = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
  2903. const MethodImplAttributes ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
  2904. const MethodAttributes InvokeAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;
  2905. Type returnType = types[types.Length - 1];
  2906. Type[] parameters = ArrayUtils.RemoveLast(types);
  2907. TypeBuilder builder = Snippets.Shared.DefineDelegateType("Delegate" + types.Length);
  2908. builder.DefineConstructor(CtorAttributes, CallingConventions.Standard, _DelegateCtorSignature).SetImplementationFlags(ImplAttributes);
  2909. builder.DefineMethod("Invoke", InvokeAttributes, returnType, parameters).SetImplementationFlags(ImplAttributes);
  2910. if (callingConvention != null) {
  2911. builder.SetCustomAttribute(new CustomAttributeBuilder(
  2912. typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new[] { typeof(CallingConvention) }),
  2913. new object[] { callingConvention })
  2914. );
  2915. }
  2916. return builder.CreateType();
  2917. }
  2918. #if !SILVERLIGHT
  2919. /// <summary>
  2920. /// Provides the entry point for a compiled module. The stub exe calls into InitializeModule which
  2921. /// does the actual work of adding references and importing the main module. Upon completion it returns
  2922. /// the exit code that the program reported via SystemExit or 0.
  2923. /// </summary>
  2924. public static int InitializeModule(Assembly/*!*/ precompiled, string/*!*/ main, string[] references) {
  2925. ContractUtils.RequiresNotNull(precompiled, "precompiled");
  2926. ContractUtils.RequiresNotNull(main, "main");
  2927. Dictionary<string, object> options = new Dictionary<string, object>();
  2928. options["Arguments"] = ArrayUtils.RemoveFirst(Environment.GetCommandLineArgs()); // remove the EXE
  2929. var pythonEngine = Python.CreateEngine(options);
  2930. var pythonContext = (PythonContext)HostingHelpers.GetLanguageContext(pythonEngine);
  2931. foreach (var scriptCode in SavableScriptCode.LoadFromAssembly(pythonContext.DomainManager, precompiled)) {
  2932. pythonContext.GetCompiledLoader().AddScriptCode(scriptCode);
  2933. }
  2934. if (references != null) {
  2935. foreach (string referenceName in references) {
  2936. pythonContext.DomainManager.LoadAssembly(Assembly.Load(referenceName));
  2937. }
  2938. }
  2939. ModuleContext modCtx = new ModuleContext(new PythonDictionary(), pythonContext);
  2940. // import __main__
  2941. try {
  2942. Importer.Import(modCtx.GlobalContext, main, PythonTuple.EMPTY, 0);
  2943. } catch (SystemExitException ex) {
  2944. ExceptionHelpers.DynamicStackFrames = null;
  2945. object dummy;
  2946. return ex.GetExitCode(out dummy);
  2947. }
  2948. return 0;
  2949. }
  2950. #endif
  2951. public static CodeContext GetPythonTypeContext(PythonType pt) {
  2952. return pt.PythonContext.SharedContext;
  2953. }
  2954. public static Delegate GetDelegate(CodeContext context, object target, Type type) {
  2955. return context.LanguageContext.DelegateCreator.GetDelegate(target, type);
  2956. }
  2957. public static int CompareLists(List self, List other) {
  2958. return self.CompareTo(other);
  2959. }
  2960. public static int CompareTuples(PythonTuple self, PythonTuple other) {
  2961. return self.CompareTo(other);
  2962. }
  2963. public static int CompareFloats(double self, double other) {
  2964. return DoubleOps.Compare(self, other);
  2965. }
  2966. public static Bytes MakeBytes(byte[] bytes) {
  2967. return new Bytes(bytes);
  2968. }
  2969. public static byte[] MakeByteArray(this string s) {
  2970. byte[] ret = new byte[s.Length];
  2971. for (int i = 0; i < s.Length; i++) {
  2972. if (s[i] < 0x100) ret[i] = (byte)s[i];
  2973. else throw PythonOps.UnicodeEncodeError("'ascii' codec can't decode byte {0:X} in position {1}: ordinal not in range", (int)ret[i], i);
  2974. }
  2975. return ret;
  2976. }
  2977. public static string MakeString(this IList<byte> bytes) {
  2978. return MakeString(bytes, bytes.Count);
  2979. }
  2980. internal static string MakeString(this byte[] preamble, IList<byte> bytes) {
  2981. char[] chars = new char[preamble.Length + bytes.Count];
  2982. for (int i = 0; i < preamble.Length; i++) {
  2983. chars[i] = (char)preamble[i];
  2984. }
  2985. for (int i = 0; i < bytes.Count; i++) {
  2986. chars[i + preamble.Length] = (char)bytes[i];
  2987. }
  2988. return new String(chars);
  2989. }
  2990. internal static string MakeString(this IList<byte> bytes, int maxBytes) {
  2991. int bytesToCopy = Math.Min(bytes.Count, maxBytes);
  2992. StringBuilder b = new StringBuilder(bytesToCopy);
  2993. for (int i = 0; i < bytesToCopy; i++) {
  2994. b.Append((char)bytes[i]);
  2995. }
  2996. return b.ToString();
  2997. }
  2998. /// <summary>
  2999. /// Called from generated code, helper to remove a name
  3000. /// </summary>
  3001. public static void RemoveName(CodeContext context, string name) {
  3002. if (!context.TryRemoveVariable(name)) {
  3003. throw PythonOps.NameError(name);
  3004. }
  3005. }
  3006. /// <summary>
  3007. /// Called from generated code, helper to do name lookup
  3008. /// </summary>
  3009. public static object LookupName(CodeContext context, string name) {
  3010. object value;
  3011. if (context.TryLookupName(name, out value)) {
  3012. return value;
  3013. } else if (context.TryLookupBuiltin(name, out value)) {
  3014. return value;
  3015. }
  3016. throw PythonOps.NameError(name);
  3017. }
  3018. /// <summary>
  3019. /// Called from generated code, helper to do name assignment
  3020. /// </summary>
  3021. public static object SetName(CodeContext context, string name, object value) {
  3022. context.SetVariable(name, value);
  3023. return value;
  3024. }
  3025. /// <summary>
  3026. /// Returns an IntPtr in the proper way to CPython - an int or a Python long
  3027. /// </summary>
  3028. public static object/*!*/ ToPython(this IntPtr handle) {
  3029. long value = handle.ToInt64();
  3030. if (value >= Int32.MinValue && value <= Int32.MaxValue) {
  3031. return ScriptingRuntimeHelpers.Int32ToObject((int)value);
  3032. }
  3033. return (BigInteger)value;
  3034. }
  3035. #region Global Access
  3036. public static CodeContext/*!*/ CreateLocalContext(CodeContext/*!*/ outerContext, MutableTuple boxes, string[] args) {
  3037. return new CodeContext(
  3038. new PythonDictionary(
  3039. new RuntimeVariablesDictionaryStorage(boxes, args)
  3040. ),
  3041. outerContext.ModuleContext
  3042. );
  3043. }
  3044. public static CodeContext/*!*/ GetGlobalContext(CodeContext/*!*/ context) {
  3045. return context.ModuleContext.GlobalContext;
  3046. }
  3047. public static ClosureCell/*!*/ MakeClosureCell() {
  3048. return new ClosureCell(Uninitialized.Instance);
  3049. }
  3050. public static ClosureCell/*!*/ MakeClosureCellWithValue(object initialValue) {
  3051. return new ClosureCell(initialValue);
  3052. }
  3053. public static MutableTuple/*!*/ GetClosureTupleFromFunction(PythonFunction/*!*/ function) {
  3054. return GetClosureTupleFromContext(function.Context);
  3055. }
  3056. public static MutableTuple/*!*/ GetClosureTupleFromGenerator(PythonGenerator/*!*/ generator) {
  3057. return GetClosureTupleFromContext(generator.Context);
  3058. }
  3059. public static MutableTuple/*!*/ GetClosureTupleFromContext(CodeContext/*!*/ context) {
  3060. return (context.Dict._storage as RuntimeVariablesDictionaryStorage).Tuple;
  3061. }
  3062. public static CodeContext/*!*/ GetParentContextFromFunction(PythonFunction/*!*/ function) {
  3063. return function.Context;
  3064. }
  3065. public static CodeContext/*!*/ GetParentContextFromGenerator(PythonGenerator/*!*/ generator) {
  3066. return generator.Context;
  3067. }
  3068. public static object GetGlobal(CodeContext/*!*/ context, string name) {
  3069. return GetVariable(context, name, true);
  3070. }
  3071. public static object GetLocal(CodeContext/*!*/ context, string name) {
  3072. return GetVariable(context, name, false);
  3073. }
  3074. private static object GetVariable(CodeContext/*!*/ context, string name, bool isGlobal) {
  3075. object res;
  3076. if (isGlobal) {
  3077. if (context.TryGetGlobalVariable(name, out res)) {
  3078. return res;
  3079. }
  3080. } else {
  3081. if (context.TryLookupName(name, out res)) {
  3082. return res;
  3083. }
  3084. }
  3085. PythonDictionary builtins = context.GetBuiltinsDict();
  3086. if (builtins != null && builtins.TryGetValue(name, out res)) {
  3087. return res;
  3088. }
  3089. if (isGlobal) {
  3090. throw GlobalNameError(name);
  3091. }
  3092. throw NameError(name);
  3093. }
  3094. public static object RawGetGlobal(CodeContext/*!*/ context, string name) {
  3095. object res;
  3096. if (context.TryGetGlobalVariable(name, out res)) {
  3097. return res;
  3098. }
  3099. return Uninitialized.Instance;
  3100. }
  3101. public static object RawGetLocal(CodeContext/*!*/ context, string name) {
  3102. object res;
  3103. if (context.TryLookupName(name, out res)) {
  3104. return res;
  3105. }
  3106. return Uninitialized.Instance;
  3107. }
  3108. public static void SetGlobal(CodeContext/*!*/ context, string name, object value) {
  3109. context.SetGlobalVariable(name, value);
  3110. }
  3111. public static void SetLocal(CodeContext/*!*/ context, string name, object value) {
  3112. context.SetVariable(name, value);
  3113. }
  3114. public static void DeleteGlobal(CodeContext/*!*/ context, string name) {
  3115. if (context.TryRemoveGlobalVariable(name)) {
  3116. return;
  3117. }
  3118. throw NameError(name);
  3119. }
  3120. public static void DeleteLocal(CodeContext/*!*/ context, string name) {
  3121. if (context.TryRemoveVariable(name)) {
  3122. return;
  3123. }
  3124. throw NameError(name);
  3125. }
  3126. public static PythonGlobal/*!*/[] GetGlobalArrayFromContext(CodeContext/*!*/ context) {
  3127. return context.GetGlobalArray();
  3128. }
  3129. #endregion
  3130. #region Exception Factories
  3131. public static Exception MultipleKeywordArgumentError(PythonFunction function, string name) {
  3132. return TypeError("{0}() got multiple values for keyword argument '{1}'", function.__name__, name);
  3133. }
  3134. public static Exception UnexpectedKeywordArgumentError(PythonFunction function, string name) {
  3135. return TypeError("{0}() got an unexpected keyword argument '{1}'", function.__name__, name);
  3136. }
  3137. public static Exception StaticAssignmentFromInstanceError(PropertyTracker tracker, bool isAssignment) {
  3138. if (isAssignment) {
  3139. if (DynamicHelpers.GetPythonTypeFromType(tracker.DeclaringType).IsPythonType) {
  3140. return PythonOps.TypeError(
  3141. "can't set attributes of built-in/extension type '{0}'",
  3142. NameConverter.GetTypeName(tracker.DeclaringType));
  3143. }
  3144. return new MissingMemberException(string.Format(
  3145. Resources.StaticAssignmentFromInstanceError,
  3146. tracker.Name,
  3147. NameConverter.GetTypeName(tracker.DeclaringType)));
  3148. }
  3149. return new MissingMemberException(string.Format(Resources.StaticAccessFromInstanceError,
  3150. tracker.Name,
  3151. NameConverter.GetTypeName(tracker.DeclaringType)));
  3152. }
  3153. public static Exception FunctionBadArgumentError(PythonFunction func, int count) {
  3154. return func.BadArgumentError(count);
  3155. }
  3156. public static Exception BadKeywordArgumentError(PythonFunction func, int count) {
  3157. return func.BadKeywordArgumentError(count);
  3158. }
  3159. public static Exception AttributeErrorForMissingOrReadonly(CodeContext/*!*/ context, PythonType dt, string name) {
  3160. PythonTypeSlot dts;
  3161. if (dt.TryResolveSlot(context, name, out dts)) {
  3162. throw PythonOps.AttributeErrorForReadonlyAttribute(dt.Name, name);
  3163. }
  3164. throw PythonOps.AttributeErrorForMissingAttribute(dt.Name, name);
  3165. }
  3166. public static Exception AttributeErrorForMissingAttribute(object o, string name) {
  3167. PythonType dt = o as PythonType;
  3168. if (dt != null)
  3169. return PythonOps.AttributeErrorForMissingAttribute(dt.Name, name);
  3170. return AttributeErrorForReadonlyAttribute(PythonTypeOps.GetName(o), name);
  3171. }
  3172. public static Exception ValueError(string format, params object[] args) {
  3173. return new ArgumentException(string.Format(format, args));
  3174. }
  3175. public static Exception KeyError(object key) {
  3176. return PythonExceptions.CreateThrowable(PythonExceptions.KeyError, key);
  3177. }
  3178. public static Exception KeyError(string format, params object[] args) {
  3179. return new KeyNotFoundException(string.Format(format, args));
  3180. }
  3181. public static Exception UnicodeDecodeError(string format, params object[] args) {
  3182. return new System.Text.DecoderFallbackException(string.Format(format, args));
  3183. }
  3184. public static Exception UnicodeEncodeError(string format, params object[] args) {
  3185. return new System.Text.EncoderFallbackException(string.Format(format, args));
  3186. }
  3187. public static Exception IOError(Exception inner) {
  3188. return new System.IO.IOException(inner.Message, inner);
  3189. }
  3190. public static Exception IOError(string format, params object[] args) {
  3191. return new System.IO.IOException(string.Format(format, args));
  3192. }
  3193. public static Exception EofError(string format, params object[] args) {
  3194. return new System.IO.EndOfStreamException(string.Format(format, args));
  3195. }
  3196. public static Exception StandardError(string format, params object[] args) {
  3197. return new SystemException(string.Format(format, args));
  3198. }
  3199. public static Exception ZeroDivisionError(string format, params object[] args) {
  3200. return new DivideByZeroException(string.Format(format, args));
  3201. }
  3202. public static Exception SystemError(string format, params object[] args) {
  3203. return new SystemException(string.Format(format, args));
  3204. }
  3205. public static Exception TypeError(string format, params object[] args) {
  3206. return new ArgumentTypeException(string.Format(format, args));
  3207. }
  3208. public static Exception IndexError(string format, params object[] args) {
  3209. return new System.IndexOutOfRangeException(string.Format(format, args));
  3210. }
  3211. public static Exception MemoryError(string format, params object[] args) {
  3212. return new OutOfMemoryException(string.Format(format, args));
  3213. }
  3214. public static Exception ArithmeticError(string format, params object[] args) {
  3215. return new ArithmeticException(string.Format(format, args));
  3216. }
  3217. public static Exception NotImplementedError(string format, params object[] args) {
  3218. return new NotImplementedException(string.Format(format, args));
  3219. }
  3220. public static Exception AttributeError(string format, params object[] args) {
  3221. return new MissingMemberException(string.Format(format, args));
  3222. }
  3223. public static Exception OverflowError(string format, params object[] args) {
  3224. return new System.OverflowException(string.Format(format, args));
  3225. }
  3226. public static Exception WindowsError(string format, params object[] args) {
  3227. #if !SILVERLIGHT // System.ComponentModel.Win32Exception
  3228. return new System.ComponentModel.Win32Exception(string.Format(format, args));
  3229. #else
  3230. return new System.SystemException(string.Format(format, args));
  3231. #endif
  3232. }
  3233. public static Exception SystemExit() {
  3234. return new SystemExitException();
  3235. }
  3236. public static void SyntaxWarning(string message, SourceUnit sourceUnit, SourceSpan span, int errorCode) {
  3237. PythonContext pc = (PythonContext)sourceUnit.LanguageContext;
  3238. CodeContext context = pc.SharedContext;
  3239. ShowWarning(context, PythonExceptions.SyntaxWarning, message, sourceUnit.Path, span.Start.Line);
  3240. }
  3241. public static SyntaxErrorException SyntaxError(string message, SourceUnit sourceUnit, SourceSpan span, int errorCode) {
  3242. switch (errorCode & ErrorCodes.ErrorMask) {
  3243. case ErrorCodes.IndentationError:
  3244. return new IndentationException(message, sourceUnit, span, errorCode, Severity.FatalError);
  3245. case ErrorCodes.TabError:
  3246. return new TabException(message, sourceUnit, span, errorCode, Severity.FatalError);
  3247. default:
  3248. var res = new SyntaxErrorException(message, sourceUnit, span, errorCode, Severity.FatalError);
  3249. if ((errorCode & ErrorCodes.NoCaret) != 0) {
  3250. res.Data[PythonContext._syntaxErrorNoCaret] = ScriptingRuntimeHelpers.True;
  3251. }
  3252. return res;
  3253. }
  3254. }
  3255. public static SyntaxErrorException BadSourceError(byte badByte, SourceSpan span, string path) {
  3256. SyntaxErrorException res = new SyntaxErrorException(
  3257. String.Format("Non-ASCII character '\\x{0:x2}' in file {2} on line {1}, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details",
  3258. badByte,
  3259. span.Start.Line,
  3260. path
  3261. ),
  3262. path,
  3263. null,
  3264. null,
  3265. span,
  3266. ErrorCodes.SyntaxError,
  3267. Severity.FatalError
  3268. );
  3269. res.Data[PythonContext._syntaxErrorNoCaret] = ScriptingRuntimeHelpers.True;
  3270. return res;
  3271. }
  3272. public static Exception StopIteration() {
  3273. return StopIteration("");
  3274. }
  3275. public static Exception InvalidType(object o, RuntimeTypeHandle handle) {
  3276. return PythonOps.TypeErrorForTypeMismatch(DynamicHelpers.GetPythonTypeFromType(Type.GetTypeFromHandle(handle)).Name, o);
  3277. }
  3278. public static Exception ZeroDivisionError() {
  3279. return ZeroDivisionError("Attempted to divide by zero.");
  3280. }
  3281. // If you do "(a, b) = (1, 2, 3, 4)"
  3282. public static Exception ValueErrorForUnpackMismatch(int left, int right) {
  3283. System.Diagnostics.Debug.Assert(left != right);
  3284. if (left > right)
  3285. return ValueError("need more than {0} values to unpack", right);
  3286. else
  3287. return ValueError("too many values to unpack");
  3288. }
  3289. public static Exception NameError(string name) {
  3290. return new UnboundNameException(string.Format("name '{0}' is not defined", name));
  3291. }
  3292. public static Exception GlobalNameError(string name) {
  3293. return new UnboundNameException(string.Format("global name '{0}' is not defined", name));
  3294. }
  3295. // If an unbound method is called without a "self" argument, or a "self" argument of a bad type
  3296. public static Exception TypeErrorForUnboundMethodCall(string methodName, Type methodType, object instance) {
  3297. return TypeErrorForUnboundMethodCall(methodName, DynamicHelpers.GetPythonTypeFromType(methodType), instance);
  3298. }
  3299. public static Exception TypeErrorForUnboundMethodCall(string methodName, PythonType methodType, object instance) {
  3300. string message = string.Format("unbound method {0}() must be called with {1} instance as first argument (got {2} instead)",
  3301. methodName, methodType.Name, PythonTypeOps.GetName(instance));
  3302. return TypeError(message);
  3303. }
  3304. // When a generator first starts, before it gets to the first yield point, you can't call generator.Send(x) where x != null.
  3305. // See Pep342 for details.
  3306. public static Exception TypeErrorForIllegalSend() {
  3307. string message = "can't send non-None value to a just-started generator";
  3308. return TypeError(message);
  3309. }
  3310. // If a method is called with an incorrect number of arguments
  3311. // You should use TypeErrorForUnboundMethodCall() for unbound methods called with 0 arguments
  3312. public static Exception TypeErrorForArgumentCountMismatch(string methodName, int expectedArgCount, int actualArgCount) {
  3313. return TypeError("{0}() takes exactly {1} argument{2} ({3} given)",
  3314. methodName, expectedArgCount, expectedArgCount == 1 ? "" : "s", actualArgCount);
  3315. }
  3316. public static Exception TypeErrorForTypeMismatch(string expectedTypeName, object instance) {
  3317. return TypeError("expected {0}, got {1}", expectedTypeName, PythonOps.GetPythonTypeName(instance));
  3318. }
  3319. // If hash is called on an instance of an unhashable type
  3320. public static Exception TypeErrorForUnhashableType(string typeName) {
  3321. return TypeError(typeName + " objects are unhashable");
  3322. }
  3323. public static Exception TypeErrorForUnhashableObject(object obj) {
  3324. return TypeErrorForUnhashableType(PythonTypeOps.GetName(obj));
  3325. }
  3326. internal static Exception TypeErrorForIncompatibleObjectLayout(string prefix, PythonType type, Type newType) {
  3327. return TypeError("{0}: '{1}' object layout differs from '{2}'", prefix, type.Name, newType);
  3328. }
  3329. public static Exception TypeErrorForNonStringAttribute() {
  3330. return TypeError("attribute name must be string");
  3331. }
  3332. internal static Exception TypeErrorForBadInstance(string template, object instance) {
  3333. return TypeError(template, PythonOps.GetPythonTypeName(instance));
  3334. }
  3335. public static Exception TypeErrorForBinaryOp(string opSymbol, object x, object y) {
  3336. throw PythonOps.TypeError("unsupported operand type(s) for {0}: '{1}' and '{2}'",
  3337. opSymbol, GetPythonTypeName(x), GetPythonTypeName(y));
  3338. }
  3339. public static Exception TypeErrorForUnaryOp(string opSymbol, object x) {
  3340. throw PythonOps.TypeError("unsupported operand type for {0}: '{1}'",
  3341. opSymbol, GetPythonTypeName(x));
  3342. }
  3343. public static Exception TypeErrorForNonIterableObject(object o) {
  3344. return PythonOps.TypeError(
  3345. "argument of type '{0}' is not iterable",
  3346. PythonTypeOps.GetName(o)
  3347. );
  3348. }
  3349. public static Exception TypeErrorForDefaultArgument(string message) {
  3350. return PythonOps.TypeError(message);
  3351. }
  3352. public static Exception AttributeErrorForReadonlyAttribute(string typeName, string attributeName) {
  3353. // CPython uses AttributeError for all attributes except "__class__"
  3354. if (attributeName == "__class__")
  3355. return PythonOps.TypeError("can't delete __class__ attribute");
  3356. return PythonOps.AttributeError("attribute '{0}' of '{1}' object is read-only", attributeName, typeName);
  3357. }
  3358. public static Exception AttributeErrorForBuiltinAttributeDeletion(string typeName, string attributeName) {
  3359. return PythonOps.AttributeError("cannot delete attribute '{0}' of builtin type '{1}'", attributeName, typeName);
  3360. }
  3361. public static Exception MissingInvokeMethodException(object o, string name) {
  3362. if (o is OldClass) {
  3363. throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'",
  3364. ((OldClass)o).Name, name);
  3365. } else {
  3366. throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", GetPythonTypeName(o), name);
  3367. }
  3368. }
  3369. /// <summary>
  3370. /// Create at TypeError exception for when Raise() can't create the exception requested.
  3371. /// </summary>
  3372. /// <param name="type">original type of exception requested</param>
  3373. /// <returns>a TypeEror exception</returns>
  3374. internal static Exception MakeExceptionTypeError(object type) {
  3375. return PythonOps.TypeError("exceptions must be classes or instances, not {0}", PythonTypeOps.GetName(type));
  3376. }
  3377. public static Exception AttributeErrorForObjectMissingAttribute(object obj, string attributeName) {
  3378. if (obj is OldInstance) {
  3379. return AttributeErrorForOldInstanceMissingAttribute(((OldInstance)obj)._class.Name, attributeName);
  3380. } else if (obj is OldClass) {
  3381. return AttributeErrorForOldClassMissingAttribute(((OldClass)obj).Name, attributeName);
  3382. } else {
  3383. return AttributeErrorForMissingAttribute(PythonTypeOps.GetName(obj), attributeName);
  3384. }
  3385. }
  3386. public static Exception AttributeErrorForMissingAttribute(string typeName, string attributeName) {
  3387. return PythonOps.AttributeError("'{0}' object has no attribute '{1}'", typeName, attributeName);
  3388. }
  3389. public static Exception AttributeErrorForOldInstanceMissingAttribute(string typeName, string attributeName) {
  3390. return PythonOps.AttributeError("{0} instance has no attribute '{1}'", typeName, attributeName);
  3391. }
  3392. public static Exception AttributeErrorForOldClassMissingAttribute(string typeName, string attributeName) {
  3393. return PythonOps.AttributeError("class {0} has no attribute '{1}'", typeName, attributeName);
  3394. }
  3395. public static Exception UncallableError(object func) {
  3396. return PythonOps.TypeError("{0} is not callable", PythonTypeOps.GetName(func));
  3397. }
  3398. public static Exception TypeErrorForProtectedMember(Type/*!*/ type, string/*!*/ name) {
  3399. return PythonOps.TypeError("cannot access protected member {0} without a python subclass of {1}", name, NameConverter.GetTypeName(type));
  3400. }
  3401. public static Exception TypeErrorForGenericMethod(Type/*!*/ type, string/*!*/ name) {
  3402. return PythonOps.TypeError("{0}.{1} is a generic method and must be indexed with types before calling", NameConverter.GetTypeName(type), name);
  3403. }
  3404. public static Exception TypeErrorForUnIndexableObject(object o) {
  3405. IPythonObject ipo;
  3406. if (o == null) {
  3407. return PythonOps.TypeError("'NoneType' object cannot be interpreted as an index");
  3408. } else if ((ipo = o as IPythonObject) != null) {
  3409. return TypeError("'{0}' object cannot be interpreted as an index", ipo.PythonType.Name);
  3410. }
  3411. return TypeError("object cannot be interpreted as an index");
  3412. }
  3413. [Obsolete("no longer used anywhere")]
  3414. public static Exception/*!*/ TypeErrorForBadDictionaryArgument(PythonFunction/*!*/ f) {
  3415. return PythonOps.TypeError("{0}() argument after ** must be a dictionary", f.__name__);
  3416. }
  3417. public static T TypeErrorForBadEnumConversion<T>(object value) {
  3418. throw TypeError("Cannot convert numeric value {0} to {1}. The value must be zero.", value, NameConverter.GetTypeName(typeof(T)));
  3419. }
  3420. public static Exception/*!*/ UnreadableProperty() {
  3421. return PythonOps.AttributeError("unreadable attribute");
  3422. }
  3423. public static Exception/*!*/ UnsetableProperty() {
  3424. return PythonOps.AttributeError("readonly attribute");
  3425. }
  3426. public static Exception/*!*/ UndeletableProperty() {
  3427. return PythonOps.AttributeError("undeletable attribute");
  3428. }
  3429. public static Exception Warning(string format, params object[] args) {
  3430. return new WarningException(string.Format(format, args));
  3431. }
  3432. #endregion
  3433. [ThreadStatic]
  3434. private static List<FunctionStack> _funcStack;
  3435. public static List<FunctionStack> GetFunctionStack() {
  3436. return _funcStack ?? (_funcStack = new List<FunctionStack>());
  3437. }
  3438. public static List<FunctionStack> GetFunctionStackNoCreate() {
  3439. return _funcStack;
  3440. }
  3441. public static List<FunctionStack> PushFrame(CodeContext context, FunctionCode function) {
  3442. List<FunctionStack> stack = GetFunctionStack();
  3443. stack.Add(new FunctionStack(context, function));
  3444. return stack;
  3445. }
  3446. internal static LambdaExpression ToGenerator(this LambdaExpression code, bool shouldInterpret, bool debuggable, int compilationThreshold) {
  3447. return Expression.Lambda(
  3448. code.Type,
  3449. new GeneratorRewriter(code.Name, code.Body).Reduce(shouldInterpret, debuggable, compilationThreshold, code.Parameters, x => x),
  3450. code.Name,
  3451. code.Parameters
  3452. );
  3453. }
  3454. public static void UpdateStackTrace(CodeContext context, FunctionCode funcCode, MethodBase method, string funcName, string filename, int line) {
  3455. if (line != -1) {
  3456. Debug.Assert(filename != null);
  3457. if (ExceptionHelpers.DynamicStackFrames == null) {
  3458. ExceptionHelpers.DynamicStackFrames = new List<DynamicStackFrame>();
  3459. }
  3460. Debug.Assert(line != SourceLocation.None.Line);
  3461. ExceptionHelpers.DynamicStackFrames.Add(new PythonDynamicStackFrame(context, funcCode, method, funcName, filename, line));
  3462. }
  3463. }
  3464. public static byte[] ConvertBufferToByteArray(PythonBuffer buffer) {
  3465. return buffer.ToString().MakeByteArray();
  3466. }
  3467. public static bool ModuleTryGetMember(CodeContext context, PythonModule module, string name, out object res) {
  3468. object value = module.GetAttributeNoThrow(context, name);
  3469. if (value != OperationFailed.Value) {
  3470. res = value;
  3471. return true;
  3472. }
  3473. res = null;
  3474. return false;
  3475. }
  3476. internal static void ScopeSetMember(CodeContext context, Scope scope, string name, object value) {
  3477. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3478. if (scopeStorage != null) {
  3479. scopeStorage.SetValue(name, false, value);
  3480. return;
  3481. }
  3482. PythonOps.SetAttr(context, scope, name, value);
  3483. }
  3484. internal static object ScopeGetMember(CodeContext context, Scope scope, string name) {
  3485. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3486. if (scopeStorage != null) {
  3487. return scopeStorage.GetValue(name, false);
  3488. }
  3489. return PythonOps.GetBoundAttr(context, scope, name);
  3490. }
  3491. internal static bool ScopeTryGetMember(CodeContext context, Scope scope, string name, out object value) {
  3492. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3493. if (scopeStorage != null) {
  3494. return scopeStorage.TryGetValue(name, false, out value);
  3495. }
  3496. return PythonOps.TryGetBoundAttr(context, scope, name, out value);
  3497. }
  3498. internal static bool ScopeContainsMember(CodeContext context, Scope scope, string name) {
  3499. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3500. if (scopeStorage != null) {
  3501. return scopeStorage.HasValue(name, false);
  3502. }
  3503. return PythonOps.HasAttr(context, scope, name);
  3504. }
  3505. internal static bool ScopeDeleteMember(CodeContext context, Scope scope, string name) {
  3506. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3507. if (scopeStorage != null) {
  3508. return scopeStorage.DeleteValue(name, false);
  3509. }
  3510. bool res = PythonOps.HasAttr(context, scope, name);
  3511. PythonOps.DeleteAttr(context, scope, name);
  3512. return res;
  3513. }
  3514. internal static IList<object> ScopeGetMemberNames(CodeContext context, Scope scope) {
  3515. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3516. if (scopeStorage != null) {
  3517. List<object> res = new List<object>();
  3518. foreach (string name in scopeStorage.GetMemberNames()) {
  3519. res.Add(name);
  3520. }
  3521. var objKeys = ((PythonScopeExtension)context.LanguageContext.EnsureScopeExtension(scope)).ObjectKeys;
  3522. if (objKeys != null) {
  3523. foreach (object o in objKeys.Keys) {
  3524. res.Add(o);
  3525. }
  3526. }
  3527. return res;
  3528. }
  3529. return PythonOps.GetAttrNames(context, scope);
  3530. }
  3531. public static bool IsUnicode(object unicodeObj) {
  3532. return unicodeObj == TypeCache.String;
  3533. }
  3534. public static BuiltinFunction GetUnicodeFuntion() {
  3535. return UnicodeHelper.Function;
  3536. }
  3537. }
  3538. /// <summary>
  3539. /// Helper clas for calls to unicode(...). We generate code which checks if unicode
  3540. /// is str and if it is we redirect those calls to the unicode function defined on this
  3541. /// class.
  3542. /// </summary>
  3543. public class UnicodeHelper {
  3544. internal static BuiltinFunction Function = BuiltinFunction.MakeFunction("unicode",
  3545. ArrayUtils.ConvertAll(
  3546. typeof(UnicodeHelper).GetMember("unicode"),
  3547. x => (MethodInfo)x
  3548. ),
  3549. typeof(string)
  3550. );
  3551. public static object unicode(CodeContext context) {
  3552. return String.Empty;
  3553. }
  3554. public static object unicode(CodeContext context, object @string) {
  3555. return StringOps.FastNewUnicode(context, @string);
  3556. }
  3557. public static object unicode(CodeContext context, object @string, object encoding) {
  3558. return StringOps.FastNewUnicode(context, @string, encoding);
  3559. }
  3560. public static object unicode(CodeContext context, object @string, [Optional]object encoding, object errors) {
  3561. return StringOps.FastNewUnicode(context, @string, encoding, errors);
  3562. }
  3563. }
  3564. public struct FunctionStack {
  3565. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
  3566. public readonly CodeContext/*!*/ Context;
  3567. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
  3568. public readonly FunctionCode/*!*/ Code;
  3569. public TraceBackFrame Frame;
  3570. internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code) {
  3571. Assert.NotNull(context, code);
  3572. Context = context;
  3573. Code = code;
  3574. Frame = null;
  3575. }
  3576. internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code, TraceBackFrame frame) {
  3577. Assert.NotNull(context, code);
  3578. Context = context;
  3579. Code = code;
  3580. Frame = frame;
  3581. }
  3582. internal FunctionStack(TraceBackFrame frame) {
  3583. Context = frame.Context;
  3584. Code = frame.f_code;
  3585. Frame = frame;
  3586. }
  3587. }
  3588. }