PageRenderTime 81ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/DICK.B1/IronPython/Runtime/Operations/PythonOps.cs

https://bitbucket.org/williamybs/uidipythontool
C# | 4375 lines | 3186 code | 789 blank | 400 comment | 892 complexity | 0dcc9c00c22ed645861f50ee0e7334e4 MD5 | raw file
  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. object dummy;
  855. if (!PythonTypeOps.TryInvokeBinaryOperator(context, o, name, "__delete__", out dummy)) {
  856. throw AttributeErrorForMissingOrReadonly(context, DynamicHelpers.GetPythonType(o), name);
  857. }
  858. }
  859. public static object ObjectGetAttribute(CodeContext/*!*/ context, object o, string name) {
  860. OldClass oc = o as OldClass;
  861. if (oc != null) {
  862. return oc.GetMember(context, name);
  863. }
  864. object value;
  865. if (DynamicHelpers.GetPythonType(o).TryGetNonCustomMember(context, o, name, out value)) {
  866. return value;
  867. }
  868. throw PythonOps.AttributeErrorForObjectMissingAttribute(o, name);
  869. }
  870. internal static IList<string> GetStringMemberList(IPythonMembersList pyMemList) {
  871. List<string> res = new List<string>();
  872. foreach (object o in pyMemList.GetMemberNames(DefaultContext.Default)) {
  873. if (o is string) {
  874. res.Add((string)o);
  875. }
  876. }
  877. return res;
  878. }
  879. public static IList<object> GetAttrNames(CodeContext/*!*/ context, object o) {
  880. IPythonMembersList pyMemList = o as IPythonMembersList;
  881. if (pyMemList != null) {
  882. return pyMemList.GetMemberNames(context);
  883. }
  884. IMembersList memList = o as IMembersList;
  885. if (memList != null) {
  886. return new List(memList.GetMemberNames());
  887. }
  888. IPythonObject po = o as IPythonObject;
  889. if (po != null) {
  890. return po.PythonType.GetMemberNames(context, o);
  891. }
  892. List res = DynamicHelpers.GetPythonType(o).GetMemberNames(context, o);
  893. #if !SILVERLIGHT
  894. if (o != null && Microsoft.Scripting.ComInterop.ComBinder.IsComObject(o)) {
  895. foreach (string name in Microsoft.Scripting.ComInterop.ComBinder.GetDynamicMemberNames(o)) {
  896. if (!res.Contains(name)) {
  897. res.AddNoLock(name);
  898. }
  899. }
  900. }
  901. #endif
  902. return res;
  903. }
  904. /// <summary>
  905. /// Called from generated code emitted by NewTypeMaker.
  906. /// </summary>
  907. public static void CheckInitializedAttribute(object o, object self, string name) {
  908. if (o == Uninitialized.Instance) {
  909. throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'",
  910. PythonTypeOps.GetName(self),
  911. name);
  912. }
  913. }
  914. public static object GetUserSlotValue(CodeContext context, PythonTypeUserDescriptorSlot slot, object instance, PythonType type) {
  915. return slot.GetValue(context, instance, type);
  916. }
  917. /// <summary>
  918. /// Handles the descriptor protocol for user-defined objects that may implement __get__
  919. /// </summary>
  920. public static object GetUserDescriptor(object o, object instance, object context) {
  921. if (o is IPythonObject) {
  922. // slow, but only encountred for user defined descriptors.
  923. PerfTrack.NoteEvent(PerfTrack.Categories.DictInvoke, "__get__");
  924. object ret;
  925. if (PythonContext.TryInvokeTernaryOperator(DefaultContext.Default,
  926. TernaryOperators.GetDescriptor,
  927. o,
  928. instance,
  929. context,
  930. out ret)) {
  931. return ret;
  932. }
  933. }
  934. return o;
  935. }
  936. /// <summary>
  937. /// Handles the descriptor protocol for user-defined objects that may implement __set__
  938. /// </summary>
  939. public static bool TrySetUserDescriptor(object o, object instance, object value) {
  940. if (o != null && o.GetType() == typeof(OldInstance)) return false; // only new-style classes have descriptors
  941. // slow, but only encountred for user defined descriptors.
  942. PerfTrack.NoteEvent(PerfTrack.Categories.DictInvoke, "__set__");
  943. object dummy;
  944. return PythonContext.TryInvokeTernaryOperator(DefaultContext.Default,
  945. TernaryOperators.SetDescriptor,
  946. o,
  947. instance,
  948. value,
  949. out dummy);
  950. }
  951. /// <summary>
  952. /// Handles the descriptor protocol for user-defined objects that may implement __delete__
  953. /// </summary>
  954. public static bool TryDeleteUserDescriptor(object o, object instance) {
  955. if (o != null && o.GetType() == typeof(OldInstance)) return false; // only new-style classes can have descriptors
  956. // slow, but only encountred for user defined descriptors.
  957. PerfTrack.NoteEvent(PerfTrack.Categories.DictInvoke, "__delete__");
  958. object dummy;
  959. return PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default,
  960. o,
  961. instance,
  962. "__delete__",
  963. out dummy);
  964. }
  965. public static object Invoke(CodeContext/*!*/ context, object target, string name, params object[] args) {
  966. return PythonCalls.Call(context, PythonOps.GetBoundAttr(context, target, name), args);
  967. }
  968. public static Delegate CreateDynamicDelegate(DynamicMethod meth, Type delegateType, object target) {
  969. // Always close delegate around its own instance of the frame
  970. return meth.CreateDelegate(delegateType, target);
  971. }
  972. public static double CheckMath(double v) {
  973. if (double.IsInfinity(v)) {
  974. throw PythonOps.OverflowError("math range error");
  975. } else if (double.IsNaN(v)) {
  976. throw PythonOps.ValueError("math domain error");
  977. } else {
  978. return v;
  979. }
  980. }
  981. public static object IsMappingType(CodeContext/*!*/ context, object o) {
  982. if (o is IDictionary || o is PythonDictionary || o is IDictionary<object, object> || o is PythonDictionary) {
  983. return ScriptingRuntimeHelpers.True;
  984. }
  985. object getitem;
  986. if ((o is IPythonObject || o is OldInstance) && PythonOps.TryGetBoundAttr(context, o, "__getitem__", out getitem)) {
  987. if (!PythonOps.IsClsVisible(context)) {
  988. // in standard Python methods aren't mapping types, therefore
  989. // if the user hasn't broken out of that box yet don't treat
  990. // them as mapping types.
  991. if (o is BuiltinFunction) return ScriptingRuntimeHelpers.False;
  992. }
  993. return ScriptingRuntimeHelpers.True;
  994. }
  995. return ScriptingRuntimeHelpers.False;
  996. }
  997. public static int FixSliceIndex(int v, int len) {
  998. if (v < 0) v = len + v;
  999. if (v < 0) return 0;
  1000. if (v > len) return len;
  1001. return v;
  1002. }
  1003. public static void FixSlice(int length, object start, object stop, object step,
  1004. out int ostart, out int ostop, out int ostep, out int ocount) {
  1005. if (step == null) {
  1006. ostep = 1;
  1007. } else {
  1008. ostep = Converter.ConvertToIndex(step);
  1009. if (ostep == 0) {
  1010. throw PythonOps.ValueError("step cannot be zero");
  1011. }
  1012. }
  1013. if (start == null) {
  1014. ostart = ostep > 0 ? 0 : length - 1;
  1015. } else {
  1016. ostart = Converter.ConvertToIndex(start);
  1017. if (ostart < 0) {
  1018. ostart += length;
  1019. if (ostart < 0) {
  1020. ostart = ostep > 0 ? Math.Min(length, 0) : Math.Min(length - 1, -1);
  1021. }
  1022. } else if (ostart >= length) {
  1023. ostart = ostep > 0 ? length : length - 1;
  1024. }
  1025. }
  1026. if (stop == null) {
  1027. ostop = ostep > 0 ? length : -1;
  1028. } else {
  1029. ostop = Converter.ConvertToIndex(stop);
  1030. if (ostop < 0) {
  1031. ostop += length;
  1032. if (ostop < 0) {
  1033. ostop = ostep > 0 ? Math.Min(length, 0) : Math.Min(length - 1, -1);
  1034. }
  1035. } else if (ostop >= length) {
  1036. ostop = ostep > 0 ? length : length - 1;
  1037. }
  1038. }
  1039. ocount = ostep > 0 ? (ostop - ostart + ostep - 1) / ostep
  1040. : (ostop - ostart + ostep + 1) / ostep;
  1041. }
  1042. public static int FixIndex(int v, int len) {
  1043. if (v < 0) {
  1044. v += len;
  1045. if (v < 0) {
  1046. throw PythonOps.IndexError("index out of range: {0}", v - len);
  1047. }
  1048. } else if (v >= len) {
  1049. throw PythonOps.IndexError("index out of range: {0}", v);
  1050. }
  1051. return v;
  1052. }
  1053. public static void InitializeForFinalization(CodeContext/*!*/ context, object newObject) {
  1054. IWeakReferenceable iwr = newObject as IWeakReferenceable;
  1055. Debug.Assert(iwr != null);
  1056. InstanceFinalizer nif = new InstanceFinalizer(context, newObject);
  1057. iwr.SetFinalizer(new WeakRefTracker(nif, nif));
  1058. }
  1059. private static object FindMetaclass(CodeContext/*!*/ context, PythonTuple bases, PythonDictionary dict) {
  1060. // If dict['__metaclass__'] exists, it is used.
  1061. object ret;
  1062. if (dict.TryGetValue("__metaclass__", out ret) && ret != null) return ret;
  1063. // Otherwise, if there is at least one base class, its metaclass is used
  1064. for (int i = 0; i < bases.__len__(); i++) {
  1065. if (!(bases[i] is OldClass)) return DynamicHelpers.GetPythonType(bases[i]);
  1066. }
  1067. // Otherwise, if there's a global variable named __metaclass__, it is used.
  1068. if (context.TryGetGlobalVariable("__metaclass__", out ret) && ret != null) {
  1069. return ret;
  1070. }
  1071. //Otherwise, the classic metaclass (types.ClassType) is used.
  1072. return TypeCache.OldInstance;
  1073. }
  1074. public static object MakeClass(object body, CodeContext/*!*/ parentContext, string name, object[] bases, string selfNames) {
  1075. Func<CodeContext, CodeContext> func = GetClassCode(parentContext, body);
  1076. return MakeClass(parentContext, name, bases, selfNames, func(parentContext).Dict);
  1077. }
  1078. private static Func<CodeContext, CodeContext> GetClassCode(CodeContext context, object body) {
  1079. Func<CodeContext, CodeContext> func = body as Func<CodeContext, CodeContext>;
  1080. if (func == null) {
  1081. FunctionCode code = (FunctionCode)body;
  1082. if (code.Target == null) {
  1083. code.UpdateDelegate(context.LanguageContext, true);
  1084. }
  1085. return (Func<CodeContext, CodeContext>)code.Target;
  1086. }
  1087. return func;
  1088. }
  1089. internal static object MakeClass(CodeContext context, string name, object[] bases, string selfNames, PythonDictionary vars) {
  1090. foreach (object dt in bases) {
  1091. if (dt is TypeGroup) {
  1092. object[] newBases = new object[bases.Length];
  1093. for (int i = 0; i < bases.Length; i++) {
  1094. TypeGroup tc = bases[i] as TypeGroup;
  1095. if (tc != null) {
  1096. Type nonGenericType;
  1097. if (!tc.TryGetNonGenericType(out nonGenericType)) {
  1098. throw PythonOps.TypeError("cannot derive from open generic types " + Builtin.repr(context, tc).ToString());
  1099. }
  1100. newBases[i] = DynamicHelpers.GetPythonTypeFromType(nonGenericType);
  1101. } else {
  1102. newBases[i] = bases[i];
  1103. }
  1104. }
  1105. bases = newBases;
  1106. break;
  1107. }
  1108. }
  1109. PythonTuple tupleBases = PythonTuple.MakeTuple(bases);
  1110. object metaclass = FindMetaclass(context, tupleBases, vars);
  1111. if (metaclass == TypeCache.OldInstance) {
  1112. return new OldClass(name, tupleBases, vars, selfNames);
  1113. } else if (metaclass == TypeCache.PythonType) {
  1114. return PythonType.__new__(context, TypeCache.PythonType, name, tupleBases, vars, selfNames);
  1115. }
  1116. // eg:
  1117. // def foo(*args): print args
  1118. // __metaclass__ = foo
  1119. // class bar: pass
  1120. // calls our function...
  1121. PythonContext pc = PythonContext.GetContext(context);
  1122. return pc.MetaClassCallSite.Target(
  1123. pc.MetaClassCallSite,
  1124. context,
  1125. metaclass,
  1126. name,
  1127. tupleBases,
  1128. vars
  1129. );
  1130. }
  1131. /// <summary>
  1132. /// Python runtime helper for raising assertions. Used by AssertStatement.
  1133. /// </summary>
  1134. /// <param name="msg">Object representing the assertion message</param>
  1135. public static void RaiseAssertionError(object msg) {
  1136. if (msg == null) {
  1137. throw PythonOps.AssertionError(String.Empty, ArrayUtils.EmptyObjects);
  1138. } else {
  1139. string message = PythonOps.ToString(msg);
  1140. throw PythonOps.AssertionError("{0}", new object[] { message });
  1141. }
  1142. }
  1143. /// <summary>
  1144. /// Python runtime helper to create instance of Python List object.
  1145. /// </summary>
  1146. /// <returns>New instance of List</returns>
  1147. public static List MakeList() {
  1148. return new List();
  1149. }
  1150. /// <summary>
  1151. /// Python runtime helper to create a populated instance of Python List object.
  1152. /// </summary>
  1153. public static List MakeList(params object[] items) {
  1154. return new List(items);
  1155. }
  1156. /// <summary>
  1157. /// Python runtime helper to create a populated instance of Python List object w/o
  1158. /// copying the array contents.
  1159. /// </summary>
  1160. [NoSideEffects]
  1161. public static List MakeListNoCopy(params object[] items) {
  1162. return List.FromArrayNoCopy(items);
  1163. }
  1164. /// <summary>
  1165. /// Python runtime helper to create a populated instance of Python List object.
  1166. ///
  1167. /// List is populated by arbitrary user defined object.
  1168. /// </summary>
  1169. public static List MakeListFromSequence(object sequence) {
  1170. return new List(sequence);
  1171. }
  1172. /// <summary>
  1173. /// Python runtime helper to create an instance of Python List object.
  1174. ///
  1175. /// List has the initial provided capacity.
  1176. /// </summary>
  1177. [NoSideEffects]
  1178. public static List MakeEmptyList(int capacity) {
  1179. return new List(capacity);
  1180. }
  1181. [NoSideEffects]
  1182. public static List MakeEmptyListFromCode() {
  1183. return List.FromArrayNoCopy(ArrayUtils.EmptyObjects);
  1184. }
  1185. /// <summary>
  1186. /// Python runtime helper to create an instance of Tuple
  1187. /// </summary>
  1188. /// <param name="items"></param>
  1189. /// <returns></returns>
  1190. [NoSideEffects]
  1191. public static PythonTuple MakeTuple(params object[] items) {
  1192. return PythonTuple.MakeTuple(items);
  1193. }
  1194. /// <summary>
  1195. /// Python runtime helper to create an instance of Tuple
  1196. /// </summary>
  1197. /// <param name="items"></param>
  1198. [NoSideEffects]
  1199. public static PythonTuple MakeTupleFromSequence(object items) {
  1200. return PythonTuple.Make(items);
  1201. }
  1202. /// <summary>
  1203. /// Python Runtime Helper for enumerator unpacking (tuple assignments, ...)
  1204. /// Creates enumerator from the input parameter e, and then extracts
  1205. /// expected number of values, returning them as array
  1206. ///
  1207. /// If the input is a Python tuple returns the tuples underlying data array. Callers
  1208. /// should not mutate the resulting tuple.
  1209. /// </summary>
  1210. /// <param name="context">The code context of the AST getting enumerator values.</param>
  1211. /// <param name="e">object to enumerate</param>
  1212. /// <param name="expected">expected number of objects to extract from the enumerator</param>
  1213. /// <returns>
  1214. /// array of objects (.Lengh == expected) if exactly expected objects are in the enumerator.
  1215. /// Otherwise throws exception
  1216. /// </returns>
  1217. public static object[] GetEnumeratorValues(CodeContext/*!*/ context, object e, int expected) {
  1218. if (e != null && e.GetType() == typeof(PythonTuple)) {
  1219. // fast path for tuples, avoid enumerating & copying the tuple.
  1220. return GetEnumeratorValuesFromTuple((PythonTuple)e, expected);
  1221. }
  1222. IEnumerator ie = PythonOps.GetEnumeratorForUnpack(context, e);
  1223. int count = 0;
  1224. object[] values = new object[expected];
  1225. while (count < expected) {
  1226. if (!ie.MoveNext()) {
  1227. throw PythonOps.ValueErrorForUnpackMismatch(expected, count);
  1228. }
  1229. values[count] = ie.Current;
  1230. count++;
  1231. }
  1232. if (ie.MoveNext()) {
  1233. throw PythonOps.ValueErrorForUnpackMismatch(expected, count + 1);
  1234. }
  1235. return values;
  1236. }
  1237. private static object[] GetEnumeratorValuesFromTuple(PythonTuple pythonTuple, int expected) {
  1238. if (pythonTuple.Count == expected) {
  1239. return pythonTuple._data;
  1240. }
  1241. throw PythonOps.ValueErrorForUnpackMismatch(expected, pythonTuple.Count);
  1242. }
  1243. /// <summary>
  1244. /// Python runtime helper to create instance of Slice object
  1245. /// </summary>
  1246. /// <param name="start">Start of the slice.</param>
  1247. /// <param name="stop">End of the slice.</param>
  1248. /// <param name="step">Step of the slice.</param>
  1249. /// <returns>Slice</returns>
  1250. public static Slice MakeSlice(object start, object stop, object step) {
  1251. return new Slice(start, stop, step);
  1252. }
  1253. #region Standard I/O support
  1254. public static void Write(CodeContext/*!*/ context, object f, string text) {
  1255. PythonContext pc = PythonContext.GetContext(context);
  1256. if (f == null) {
  1257. f = pc.SystemStandardOut;
  1258. }
  1259. if (f == null || f == Uninitialized.Instance) {
  1260. throw PythonOps.RuntimeError("lost sys.stdout");
  1261. }
  1262. PythonFile pf = f as PythonFile;
  1263. if (pf != null) {
  1264. // avoid spinning up a site in the normal case
  1265. pf.write(text);
  1266. return;
  1267. }
  1268. pc.WriteCallSite.Target(
  1269. pc.WriteCallSite,
  1270. context,
  1271. GetBoundAttr(context, f, "write"),
  1272. text
  1273. );
  1274. }
  1275. private static object ReadLine(CodeContext/*!*/ context, object f) {
  1276. if (f == null || f == Uninitialized.Instance) throw PythonOps.RuntimeError("lost sys.std_in");
  1277. return PythonOps.Invoke(context, f, "readline");
  1278. }
  1279. public static void WriteSoftspace(CodeContext/*!*/ context, object f) {
  1280. if (CheckSoftspace(f)) {
  1281. SetSoftspace(f, ScriptingRuntimeHelpers.False);
  1282. Write(context, f, " ");
  1283. }
  1284. }
  1285. public static void SetSoftspace(object f, object value) {
  1286. PythonOps.SetAttr(DefaultContext.Default, f, "softspace", value);
  1287. }
  1288. public static bool CheckSoftspace(object f) {
  1289. PythonFile pf = f as PythonFile;
  1290. if (pf != null) {
  1291. // avoid spinning up a site in the common case
  1292. return pf.softspace;
  1293. }
  1294. object result;
  1295. if (PythonOps.TryGetBoundAttr(f, "softspace", out result)) {
  1296. return PythonOps.IsTrue(result);
  1297. }
  1298. return false;
  1299. }
  1300. // Must stay here for now because libs depend on it.
  1301. public static void Print(CodeContext/*!*/ context, object o) {
  1302. PrintWithDest(context, PythonContext.GetContext(context).SystemStandardOut, o);
  1303. }
  1304. public static void PrintNoNewline(CodeContext/*!*/ context, object o) {
  1305. PrintWithDestNoNewline(context, PythonContext.GetContext(context).SystemStandardOut, o);
  1306. }
  1307. public static void PrintWithDest(CodeContext/*!*/ context, object dest, object o) {
  1308. PrintWithDestNoNewline(context, dest, o);
  1309. Write(context, dest, "\n");
  1310. }
  1311. public static void PrintWithDestNoNewline(CodeContext/*!*/ context, object dest, object o) {
  1312. WriteSoftspace(context, dest);
  1313. Write(context, dest, o == null ? "None" : ToString(o));
  1314. }
  1315. public static object ReadLineFromSrc(CodeContext/*!*/ context, object src) {
  1316. return ReadLine(context, src);
  1317. }
  1318. /// <summary>
  1319. /// Prints newline into default standard output
  1320. /// </summary>
  1321. public static void PrintNewline(CodeContext/*!*/ context) {
  1322. PrintNewlineWithDest(context, PythonContext.GetContext(context).SystemStandardOut);
  1323. }
  1324. /// <summary>
  1325. /// Prints newline into specified destination. Sets softspace property to false.
  1326. /// </summary>
  1327. public static void PrintNewlineWithDest(CodeContext/*!*/ context, object dest) {
  1328. PythonOps.Write(context, dest, "\n");
  1329. PythonOps.SetSoftspace(dest, ScriptingRuntimeHelpers.False);
  1330. }
  1331. /// <summary>
  1332. /// Prints value into default standard output with Python comma semantics.
  1333. /// </summary>
  1334. public static void PrintComma(CodeContext/*!*/ context, object o) {
  1335. PrintCommaWithDest(context, PythonContext.GetContext(context).SystemStandardOut, o);
  1336. }
  1337. /// <summary>
  1338. /// Prints value into specified destination with Python comma semantics.
  1339. /// </summary>
  1340. public static void PrintCommaWithDest(CodeContext/*!*/ context, object dest, object o) {
  1341. PythonOps.WriteSoftspace(context, dest);
  1342. string s = o == null ? "None" : PythonOps.ToString(o);
  1343. PythonOps.Write(context, dest, s);
  1344. PythonOps.SetSoftspace(dest, !s.EndsWith("\n"));
  1345. }
  1346. /// <summary>
  1347. /// Called from generated code when we are supposed to print an expression value
  1348. /// </summary>
  1349. public static void PrintExpressionValue(CodeContext/*!*/ context, object value) {
  1350. PythonContext pc = PythonContext.GetContext(context);
  1351. object dispHook = pc.GetSystemStateValue("displayhook");
  1352. pc.CallWithContext(context, dispHook, value);
  1353. }
  1354. #if !SILVERLIGHT
  1355. public static void PrintException(CodeContext/*!*/ context, Exception/*!*/ exception, IConsole console) {
  1356. PythonContext pc = PythonContext.GetContext(context);
  1357. PythonTuple exInfo = GetExceptionInfoLocal(context, exception);
  1358. pc.SetSystemStateValue("last_type", exInfo[0]);
  1359. pc.SetSystemStateValue("last_value", exInfo[1]);
  1360. pc.SetSystemStateValue("last_traceback", exInfo[2]);
  1361. object exceptHook = pc.GetSystemStateValue("excepthook");
  1362. BuiltinFunction bf = exceptHook as BuiltinFunction;
  1363. if (console != null && bf != null && bf.DeclaringType == typeof(SysModule) && bf.Name == "excepthook") {
  1364. // builtin except hook, display it to the console which may do nice coloring
  1365. console.WriteLine(pc.FormatException(exception), Style.Error);
  1366. } else {
  1367. // user defined except hook or no console
  1368. try {
  1369. PythonCalls.Call(context, exceptHook, exInfo[0], exInfo[1], exInfo[2]);
  1370. } catch (Exception e) {
  1371. PrintWithDest(context, pc.SystemStandardError, "Error in sys.excepthook:");
  1372. PrintWithDest(context, pc.SystemStandardError, pc.FormatException(e));
  1373. PrintNewlineWithDest(context, pc.SystemStandardError);
  1374. PrintWithDest(context, pc.SystemStandardError, "Original exception was:");
  1375. PrintWithDest(context, pc.SystemStandardError, pc.FormatException(exception));
  1376. ExceptionHelpers.DynamicStackFrames = null;
  1377. }
  1378. }
  1379. }
  1380. #endif
  1381. #endregion
  1382. #region Import support
  1383. /// <summary>
  1384. /// Called from generated code for:
  1385. ///
  1386. /// import spam.eggs
  1387. /// </summary>
  1388. [ProfilerTreatsAsExternal]
  1389. public static object ImportTop(CodeContext/*!*/ context, string fullName, int level) {
  1390. return Importer.Import(context, fullName, null, level);
  1391. }
  1392. /// <summary>
  1393. /// Python helper method called from generated code for:
  1394. ///
  1395. /// import spam.eggs as ham
  1396. /// </summary>
  1397. [ProfilerTreatsAsExternal]
  1398. public static object ImportBottom(CodeContext/*!*/ context, string fullName, int level) {
  1399. object module = Importer.Import(context, fullName, null, level);
  1400. if (fullName.IndexOf('.') >= 0) {
  1401. // Extract bottom from the imported module chain
  1402. string[] parts = fullName.Split('.');
  1403. for (int i = 1; i < parts.Length; i++) {
  1404. module = PythonOps.GetBoundAttr(context, module, parts[i]);
  1405. }
  1406. }
  1407. return module;
  1408. }
  1409. /// <summary>
  1410. /// Called from generated code for:
  1411. ///
  1412. /// from spam import eggs1, eggs2
  1413. /// </summary>
  1414. [ProfilerTreatsAsExternal]
  1415. public static object ImportWithNames(CodeContext/*!*/ context, string fullName, string[] names, int level) {
  1416. return Importer.Import(context, fullName, PythonTuple.MakeTuple(names), level);
  1417. }
  1418. /// <summary>
  1419. /// Imports one element from the module in the context of:
  1420. ///
  1421. /// from module import a, b, c, d
  1422. ///
  1423. /// Called repeatedly for all elements being imported (a, b, c, d above)
  1424. /// </summary>
  1425. public static object ImportFrom(CodeContext/*!*/ context, object module, string name) {
  1426. return Importer.ImportFrom(context, module, name);
  1427. }
  1428. /// <summary>
  1429. /// Called from generated code for:
  1430. ///
  1431. /// from spam import *
  1432. /// </summary>
  1433. [ProfilerTreatsAsExternal]
  1434. public static void ImportStar(CodeContext/*!*/ context, string fullName, int level) {
  1435. object newmod = Importer.Import(context, fullName, PythonTuple.MakeTuple("*"), level);
  1436. PythonModule scope = newmod as PythonModule;
  1437. NamespaceTracker nt = newmod as NamespaceTracker;
  1438. PythonType pt = newmod as PythonType;
  1439. if (pt != null &&
  1440. !pt.UnderlyingSystemType.IsEnum &&
  1441. (!pt.UnderlyingSystemType.IsAbstract || !pt.UnderlyingSystemType.IsSealed)) {
  1442. // from type import * only allowed on static classes (and enums)
  1443. throw PythonOps.ImportError("no module named {0}", pt.Name);
  1444. }
  1445. IEnumerator exports;
  1446. object all;
  1447. bool filterPrivates = false;
  1448. // look for __all__, if it's defined then use that to get the attribute names,
  1449. // otherwise get all the names and filter out members starting w/ _'s.
  1450. if (PythonOps.TryGetBoundAttr(context, newmod, "__all__", out all)) {
  1451. exports = PythonOps.GetEnumerator(all);
  1452. } else {
  1453. exports = PythonOps.GetAttrNames(context, newmod).GetEnumerator();
  1454. filterPrivates = true;
  1455. }
  1456. // iterate through the names and populate the scope with the values.
  1457. while (exports.MoveNext()) {
  1458. string name = exports.Current as string;
  1459. if (name == null) {
  1460. throw PythonOps.TypeErrorForNonStringAttribute();
  1461. } else if (filterPrivates && name.Length > 0 && name[0] == '_') {
  1462. continue;
  1463. }
  1464. // we special case several types to avoid one-off code gen of dynamic sites
  1465. if (scope != null) {
  1466. context.SetVariable(name, scope.__dict__[name]);
  1467. } else if (nt != null) {
  1468. object value = NamespaceTrackerOps.GetCustomMember(context, nt, name);
  1469. if (value != OperationFailed.Value) {
  1470. context.SetVariable(name, value);
  1471. }
  1472. } else if (pt != null) {
  1473. PythonTypeSlot pts;
  1474. object value;
  1475. if (pt.TryResolveSlot(context, name, out pts) &&
  1476. pts.TryGetValue(context, null, pt, out value)) {
  1477. context.SetVariable(name, value);
  1478. }
  1479. } else {
  1480. // not a known type, we'll do use a site to do the get...
  1481. context.SetVariable(name, PythonOps.GetBoundAttr(context, newmod, name));
  1482. }
  1483. }
  1484. }
  1485. #endregion
  1486. #region Exec
  1487. /// <summary>
  1488. /// Unqualified exec statement support.
  1489. /// A Python helper which will be called for the statement:
  1490. ///
  1491. /// exec code
  1492. /// </summary>
  1493. [ProfilerTreatsAsExternal]
  1494. public static void UnqualifiedExec(CodeContext/*!*/ context, object code) {
  1495. PythonDictionary locals = null;
  1496. PythonDictionary globals = null;
  1497. // if the user passes us a tuple we'll extract the 3 values out of it
  1498. PythonTuple codeTuple = code as PythonTuple;
  1499. if (codeTuple != null && codeTuple.__len__() > 0 && codeTuple.__len__() <= 3) {
  1500. code = codeTuple[0];
  1501. if (codeTuple.__len__() > 1 && codeTuple[1] != null) {
  1502. globals = codeTuple[1] as PythonDictionary;
  1503. if (globals == null) throw PythonOps.TypeError("globals must be dictionary or none");
  1504. }
  1505. if (codeTuple.__len__() > 2 && codeTuple[2] != null) {
  1506. locals = codeTuple[2] as PythonDictionary;
  1507. if (locals == null) throw PythonOps.TypeError("locals must be dictionary or none");
  1508. } else {
  1509. locals = globals;
  1510. }
  1511. }
  1512. QualifiedExec(context, code, globals, locals);
  1513. }
  1514. /// <summary>
  1515. /// Qualified exec statement support,
  1516. /// Python helper which will be called for the statement:
  1517. ///
  1518. /// exec code in globals [, locals ]
  1519. /// </summary>
  1520. [ProfilerTreatsAsExternal]
  1521. public static void QualifiedExec(CodeContext/*!*/ context, object code, PythonDictionary globals, object locals) {
  1522. PythonFile pf;
  1523. Stream cs;
  1524. var pythonContext = PythonContext.GetContext(context);
  1525. bool noLineFeed = true;
  1526. // TODO: use ContentProvider?
  1527. if ((pf = code as PythonFile) != null) {
  1528. List lines = pf.readlines();
  1529. StringBuilder fullCode = new StringBuilder();
  1530. for (int i = 0; i < lines.__len__(); i++) {
  1531. fullCode.Append(lines[i]);
  1532. }
  1533. code = fullCode.ToString();
  1534. } else if ((cs = code as Stream) != null) {
  1535. using (StreamReader reader = new StreamReader(cs)) { // TODO: encoding?
  1536. code = reader.ReadToEnd();
  1537. }
  1538. noLineFeed = false;
  1539. }
  1540. string strCode = code as string;
  1541. if (strCode != null) {
  1542. SourceUnit source;
  1543. if (noLineFeed) {
  1544. source = pythonContext.CreateSourceUnit(new NoLineFeedSourceContentProvider(strCode), "<string>", SourceCodeKind.Statements);
  1545. } else {
  1546. source = pythonContext.CreateSnippet(strCode, SourceCodeKind.Statements);
  1547. }
  1548. PythonCompilerOptions compilerOptions = Builtin.GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
  1549. // do interpretation only on strings -- not on files, streams, or code objects
  1550. code = FunctionCode.FromSourceUnit(source, compilerOptions);
  1551. }
  1552. FunctionCode fc = code as FunctionCode;
  1553. if (fc == null) {
  1554. throw PythonOps.TypeError("arg 1 must be a string, file, Stream, or code object, not {0}", PythonTypeOps.GetName(code));
  1555. }
  1556. if (locals == null) locals = globals;
  1557. if (globals == null) globals = context.GlobalDict;
  1558. if (locals != null && PythonOps.IsMappingType(context, locals) != ScriptingRuntimeHelpers.True) {
  1559. throw PythonOps.TypeError("exec: arg 3 must be mapping or None");
  1560. }
  1561. CodeContext execContext = Builtin.GetExecEvalScope(context, globals, Builtin.GetAttrLocals(context, locals), true, false);
  1562. if (context.LanguageContext.PythonOptions.Frames) {
  1563. List<FunctionStack> stack = PushFrame(execContext, fc);
  1564. try {
  1565. fc.Call(execContext);
  1566. } finally {
  1567. stack.RemoveAt(stack.Count - 1);
  1568. }
  1569. } else {
  1570. fc.Call(execContext);
  1571. }
  1572. }
  1573. #endregion
  1574. public static ICollection GetCollection(object o) {
  1575. ICollection ret = o as ICollection;
  1576. if (ret != null) return ret;
  1577. List<object> al = new List<object>();
  1578. IEnumerator e = GetEnumerator(o);
  1579. while (e.MoveNext()) al.Add(e.Current);
  1580. return al;
  1581. }
  1582. public static IEnumerator GetEnumerator(object o) {
  1583. return GetEnumerator(DefaultContext.Default, o);
  1584. }
  1585. public static IEnumerator GetEnumerator(CodeContext/*!*/ context, object o) {
  1586. IEnumerator ie;
  1587. if (!TryGetEnumerator(context, o, out ie)) {
  1588. throw PythonOps.TypeError("{0} is not iterable", PythonTypeOps.GetName(o));
  1589. }
  1590. return ie;
  1591. }
  1592. // Lack of type restrictions allows this method to return the direct result of __iter__ without
  1593. // wrapping it. This is the proper behavior for Builtin.iter().
  1594. public static object GetEnumeratorObject(CodeContext/*!*/ context, object o) {
  1595. object iterFunc;
  1596. if (PythonOps.TryGetBoundAttr(context, o, "__iter__", out iterFunc) &&
  1597. !Object.ReferenceEquals(iterFunc, NotImplementedType.Value)) {
  1598. return PythonOps.CallWithContext(context, iterFunc);
  1599. }
  1600. return GetEnumerator(context, o);
  1601. }
  1602. public static IEnumerator GetEnumeratorForUnpack(CodeContext/*!*/ context, object enumerable) {
  1603. IEnumerator enumerator;
  1604. if (!TryGetEnumerator(context, enumerable, out enumerator)) {
  1605. throw PythonOps.TypeError("'{0}' object is not iterable", PythonTypeOps.GetName(enumerable));
  1606. }
  1607. return enumerator;
  1608. }
  1609. public static KeyValuePair<IEnumerator, IDisposable> ThrowTypeErrorForBadIteration(CodeContext context, object enumerable) {
  1610. throw PythonOps.TypeError("iteration over non-sequence of type {0}", PythonTypeOps.GetName(enumerable));
  1611. }
  1612. internal static bool TryGetEnumerator(CodeContext/*!*/ context, object enumerable, out IEnumerator enumerator) {
  1613. enumerator = null;
  1614. IEnumerable enumer;
  1615. if (PythonContext.GetContext(context).TryConvertToIEnumerable(enumerable, out enumer)) {
  1616. enumerator = enumer.GetEnumerator();
  1617. return true;
  1618. }
  1619. return false;
  1620. }
  1621. public static void ForLoopDispose(KeyValuePair<IEnumerator, IDisposable> iteratorInfo) {
  1622. if (iteratorInfo.Value != null) {
  1623. iteratorInfo.Value.Dispose();
  1624. }
  1625. }
  1626. public static KeyValuePair<IEnumerator, IDisposable> StringEnumerator(string str) {
  1627. return new KeyValuePair<IEnumerator, IDisposable>(StringOps.StringEnumerator(str), null);
  1628. }
  1629. public static KeyValuePair<IEnumerator, IDisposable> BytesEnumerator(IList<byte> bytes) {
  1630. return new KeyValuePair<IEnumerator, IDisposable>(IListOfByteOps.BytesEnumerator(bytes), null);
  1631. }
  1632. public static KeyValuePair<IEnumerator, IDisposable> BytesIntEnumerator(IList<byte> bytes) {
  1633. return new KeyValuePair<IEnumerator, IDisposable>(IListOfByteOps.BytesIntEnumerator(bytes), null);
  1634. }
  1635. public static KeyValuePair<IEnumerator, IDisposable> GetEnumeratorFromEnumerable(IEnumerable enumerable) {
  1636. IEnumerator enumerator = enumerable.GetEnumerator();
  1637. return new KeyValuePair<IEnumerator, IDisposable>(enumerator, enumerator as IDisposable);
  1638. }
  1639. public static IEnumerable StringEnumerable(string str) {
  1640. return StringOps.StringEnumerable(str);
  1641. }
  1642. public static IEnumerable BytesEnumerable(IList<byte> bytes) {
  1643. return IListOfByteOps.BytesEnumerable(bytes);
  1644. }
  1645. public static IEnumerable BytesIntEnumerable(IList<byte> bytes) {
  1646. return IListOfByteOps.BytesIntEnumerable(bytes);
  1647. }
  1648. #region Exception handling
  1649. // The semantics here are:
  1650. // 1. Each thread has a "current exception", which is returned as a tuple by sys.exc_info().
  1651. // 2. The current exception is set on encountering an except block, even if the except block doesn't
  1652. // match the exception.
  1653. // 3. Each function on exit (either via exception, return, or yield) will restore the "current exception"
  1654. // to the value it had on function-entry.
  1655. //
  1656. // So common codegen would be:
  1657. //
  1658. // function() {
  1659. // $save = SaveCurrentException();
  1660. // try {
  1661. // def foo():
  1662. // try:
  1663. // except:
  1664. // SetCurrentException($exception)
  1665. // <except body>
  1666. //
  1667. // finally {
  1668. // RestoreCurrentException($save)
  1669. // }
  1670. // Called at the start of the except handlers to set the current exception.
  1671. public static object SetCurrentException(CodeContext/*!*/ context, Exception/*!*/ clrException) {
  1672. Assert.NotNull(clrException);
  1673. // we need to extract before we check because ThreadAbort.ExceptionState is cleared after
  1674. // we reset the abort.
  1675. object res = PythonExceptions.ToPython(clrException);
  1676. #if !SILVERLIGHT
  1677. // Check for thread abort exceptions.
  1678. // This is necessary to be able to catch python's KeyboardInterrupt exceptions.
  1679. // CLR restrictions require that this must be called from within a catch block. This gets
  1680. // called even if we aren't going to handle the exception - we'll just reset the abort
  1681. ThreadAbortException tae = clrException as ThreadAbortException;
  1682. if (tae != null && tae.ExceptionState is KeyboardInterruptException) {
  1683. Thread.ResetAbort();
  1684. }
  1685. #endif
  1686. RawException = clrException;
  1687. return res;
  1688. }
  1689. public static void BuildExceptionInfo(CodeContext/*!*/ context, Exception clrException) {
  1690. ExceptionHelpers.AssociateDynamicStackFrames(clrException);
  1691. GetExceptionInfo(context);
  1692. ClearDynamicStackFrames();
  1693. }
  1694. // Clear the current exception. Most callers should restore the exception.
  1695. // This is mainly for sys.exc_clear()
  1696. public static void ClearCurrentException() {
  1697. RestoreCurrentException(null);
  1698. }
  1699. public static void ExceptionHandled(CodeContext context) {
  1700. PythonContext.GetContext(context).DelSystemStateValue("exc_traceback");
  1701. PythonContext.GetContext(context).DelSystemStateValue("exc_value");
  1702. PythonContext.GetContext(context).DelSystemStateValue("exc_type");
  1703. }
  1704. // Called by code-gen to save it. Codegen just needs to pass this back to RestoreCurrentException.
  1705. public static Exception SaveCurrentException() {
  1706. return RawException;
  1707. }
  1708. // Called at function exit (like popping). Pass value from SaveCurrentException.
  1709. public static void RestoreCurrentException(Exception clrException) {
  1710. RawException = clrException;
  1711. }
  1712. public static object CheckException(CodeContext context, object exception, object test) {
  1713. Debug.Assert(exception != null);
  1714. ObjectException objex;
  1715. if (test is PythonTuple) {
  1716. // we handle multiple exceptions, we'll check them one at a time.
  1717. PythonTuple tt = test as PythonTuple;
  1718. for (int i = 0; i < tt.__len__(); i++) {
  1719. object res = CheckException(context, exception, tt[i]);
  1720. if (res != null) return res;
  1721. }
  1722. } else if ((objex = exception as ObjectException) != null) {
  1723. if (PythonOps.IsSubClass(context, objex.Type, test)) {
  1724. return objex.Instance;
  1725. }
  1726. return null;
  1727. } else if (test is OldClass) {
  1728. if (PythonOps.IsInstance(context, exception, test)) {
  1729. // catching a Python type.
  1730. return exception;
  1731. }
  1732. } else if (test is PythonType) {
  1733. if (PythonOps.IsSubClass(test as PythonType, TypeCache.BaseException)) {
  1734. // catching a Python exception type explicitly.
  1735. if (PythonOps.IsInstance(context, exception, test)) return exception;
  1736. } else if (PythonOps.IsSubClass(test as PythonType, DynamicHelpers.GetPythonTypeFromType(typeof(Exception)))) {
  1737. // catching a CLR exception type explicitly.
  1738. Exception clrEx = PythonExceptions.ToClr(exception);
  1739. if (PythonOps.IsInstance(context, clrEx, test)) return clrEx;
  1740. }
  1741. }
  1742. return null;
  1743. }
  1744. private static TraceBack CreateTraceBack(PythonContext pyContext, Exception e) {
  1745. // user provided trace back
  1746. if (e.Data.Contains(typeof(TraceBack))) {
  1747. return (TraceBack)e.Data[typeof(TraceBack)];
  1748. }
  1749. DynamicStackFrame[] frames = ScriptingRuntimeHelpers.GetDynamicStackFrames(e, false);
  1750. TraceBack tb = null;
  1751. for (int i = 0; i < frames.Length; i++) {
  1752. DynamicStackFrame frame = frames[i];
  1753. string name = frame.GetMethodName();
  1754. if (name.IndexOf('#') > 0) {
  1755. // dynamic method, strip the trailing id...
  1756. name = name.Substring(0, name.IndexOf('#'));
  1757. }
  1758. PythonDynamicStackFrame pyFrame = frame as PythonDynamicStackFrame;
  1759. if (pyFrame != null) {
  1760. CodeContext context = pyFrame.CodeContext;
  1761. FunctionCode code = pyFrame.Code;
  1762. TraceBackFrame tbf = new TraceBackFrame(
  1763. context,
  1764. context.GlobalDict,
  1765. context.Dict,
  1766. code);
  1767. tb = new TraceBack(tb, tbf);
  1768. tb.SetLine(frame.GetFileLineNumber());
  1769. }
  1770. }
  1771. e.Data[typeof(TraceBack)] = tb;
  1772. return tb;
  1773. }
  1774. /// <summary>
  1775. /// Get an exception tuple for the "current" exception. This is used for sys.exc_info()
  1776. /// </summary>
  1777. public static PythonTuple GetExceptionInfo(CodeContext/*!*/ context) {
  1778. return GetExceptionInfoLocal(context, RawException);
  1779. }
  1780. /// <summary>
  1781. /// Get an exception tuple for a given exception. This is like the inverse of MakeException.
  1782. /// </summary>
  1783. /// <param name="context">the code context</param>
  1784. /// <param name="ex">the exception to create a tuple for.</param>
  1785. /// <returns>a tuple of (type, value, traceback)</returns>
  1786. /// <remarks>This is called directly by the With statement so that it can get an exception tuple
  1787. /// in its own private except handler without disturbing the thread-wide sys.exc_info(). </remarks>
  1788. public static PythonTuple/*!*/ GetExceptionInfoLocal(CodeContext/*!*/ context, Exception ex) {
  1789. if (ex == null) {
  1790. return PythonTuple.MakeTuple(null, null, null);
  1791. }
  1792. object pyExcep = PythonExceptions.ToPython(ex);
  1793. PythonContext pc = PythonContext.GetContext(context);
  1794. TraceBack tb = CreateTraceBack(pc, ex);
  1795. pc.SystemExceptionTraceBack = tb;
  1796. object excType = PythonOps.GetBoundAttr(context, pyExcep, "__class__");
  1797. pc.SystemExceptionType = excType;
  1798. pc.SystemExceptionValue = pyExcep;
  1799. return PythonTuple.MakeTuple(
  1800. excType,
  1801. pyExcep,
  1802. tb);
  1803. }
  1804. /// <summary>
  1805. /// helper function for re-raised exceptions.
  1806. /// </summary>
  1807. public static Exception MakeRethrownException(CodeContext/*!*/ context) {
  1808. PythonTuple t = GetExceptionInfo(context);
  1809. Exception e = MakeExceptionWorker(context, t[0], t[1], t[2], true);
  1810. return MakeRethrowExceptionWorker(e);
  1811. }
  1812. public static Exception MakeRethrowExceptionWorker(Exception e) {
  1813. e.Data.Remove(typeof(TraceBack));
  1814. ExceptionHelpers.UpdateForRethrow(e);
  1815. return e;
  1816. }
  1817. /// <summary>
  1818. /// helper function for non-re-raise exceptions.
  1819. ///
  1820. /// type is the type of exception to throw or an instance. If it
  1821. /// is an instance then value should be null.
  1822. ///
  1823. /// If type is a type then value can either be an instance of type,
  1824. /// a Tuple, or a single value. This case is handled by EC.CreateThrowable.
  1825. /// </summary>
  1826. public static Exception MakeException(CodeContext/*!*/ context, object type, object value, object traceback) {
  1827. return MakeExceptionWorker(context, type, value, traceback, false);
  1828. }
  1829. private static Exception MakeExceptionWorker(CodeContext context, object type, object value, object traceback, bool forRethrow) {
  1830. Exception throwable;
  1831. PythonType pt;
  1832. if (type is Exception) {
  1833. throwable = type as Exception;
  1834. } else if (type is PythonExceptions.BaseException) {
  1835. throwable = PythonExceptions.ToClr(type);
  1836. } else if ((pt = type as PythonType) != null && typeof(PythonExceptions.BaseException).IsAssignableFrom(pt.UnderlyingSystemType)) {
  1837. throwable = PythonExceptions.CreateThrowableForRaise(context, pt, value);
  1838. } else if (type is OldClass) {
  1839. if (value == null) {
  1840. throwable = new OldInstanceException((OldInstance)PythonCalls.Call(context, type));
  1841. } else {
  1842. throwable = PythonExceptions.CreateThrowableForRaise(context, (OldClass)type, value);
  1843. }
  1844. } else if (type is OldInstance) {
  1845. throwable = new OldInstanceException((OldInstance)type);
  1846. } else {
  1847. throwable = MakeExceptionTypeError(type);
  1848. }
  1849. IDictionary dict = throwable.Data;
  1850. if (traceback != null) {
  1851. if (!forRethrow) {
  1852. TraceBack tb = traceback as TraceBack;
  1853. if (tb == null) throw PythonOps.TypeError("traceback argument must be a traceback object");
  1854. dict[typeof(TraceBack)] = tb;
  1855. }
  1856. } else if (dict.Contains(typeof(TraceBack))) {
  1857. dict.Remove(typeof(TraceBack));
  1858. }
  1859. if (!forRethrow) {
  1860. ExceptionHelpers.ClearDynamicStackFrames(throwable);
  1861. }
  1862. PerfTrack.NoteEvent(PerfTrack.Categories.Exceptions, throwable);
  1863. return throwable;
  1864. }
  1865. public static Exception CreateThrowable(PythonType type, params object[] args) {
  1866. return PythonExceptions.CreateThrowable(type, args);
  1867. }
  1868. public static void ClearDynamicStackFrames() {
  1869. ExceptionHelpers.DynamicStackFrames = null;
  1870. }
  1871. public static List<DynamicStackFrame> GetAndClearDynamicStackFrames() {
  1872. List<DynamicStackFrame> res = ExceptionHelpers.DynamicStackFrames;
  1873. ClearDynamicStackFrames();
  1874. return res;
  1875. }
  1876. public static void SetDynamicStackFrames(List<DynamicStackFrame> frames) {
  1877. ExceptionHelpers.DynamicStackFrames = frames;
  1878. }
  1879. #endregion
  1880. public static string[] GetFunctionSignature(PythonFunction function) {
  1881. return new string[] { function.GetSignatureString() };
  1882. }
  1883. public static PythonDictionary CopyAndVerifyDictionary(PythonFunction function, IDictionary dict) {
  1884. foreach (object o in dict.Keys) {
  1885. if (!(o is string)) {
  1886. throw TypeError("{0}() keywords most be strings", function.__name__);
  1887. }
  1888. }
  1889. return new PythonDictionary(dict);
  1890. }
  1891. public static PythonDictionary/*!*/ CopyAndVerifyUserMapping(PythonFunction/*!*/ function, object dict) {
  1892. return UserMappingToPythonDictionary(function.Context, dict, function.func_name);
  1893. }
  1894. public static PythonDictionary UserMappingToPythonDictionary(CodeContext context, object dict, string funcName) {
  1895. // call dict.keys()
  1896. object keys;
  1897. if (!PythonTypeOps.TryInvokeUnaryOperator(context, dict, "keys", out keys)) {
  1898. throw PythonOps.TypeError("{0}() argument after ** must be a mapping, not {1}",
  1899. funcName,
  1900. PythonTypeOps.GetName(dict));
  1901. }
  1902. PythonDictionary res = new PythonDictionary();
  1903. // enumerate the keys getting their values
  1904. IEnumerator enumerator = GetEnumerator(keys);
  1905. while (enumerator.MoveNext()) {
  1906. object o = enumerator.Current;
  1907. string s = o as string;
  1908. if (s == null) {
  1909. Extensible<string> es = o as Extensible<string>;
  1910. if (es == null) {
  1911. throw PythonOps.TypeError("{0}() keywords most be strings, not {0}",
  1912. funcName,
  1913. PythonTypeOps.GetName(dict));
  1914. }
  1915. s = es.Value;
  1916. }
  1917. res[o] = PythonOps.GetIndex(context, dict, o);
  1918. }
  1919. return res;
  1920. }
  1921. public static PythonDictionary CopyAndVerifyPythonDictionary(PythonFunction function, PythonDictionary dict) {
  1922. if (dict._storage.HasNonStringAttributes()) {
  1923. throw TypeError("{0}() keywords most be strings", function.__name__);
  1924. }
  1925. return new PythonDictionary(dict);
  1926. }
  1927. public static object ExtractDictionaryArgument(PythonFunction function, string name, int argCnt, PythonDictionary dict) {
  1928. object val;
  1929. if (dict.TryGetValue(name, out val)) {
  1930. dict.Remove(name);
  1931. return val;
  1932. }
  1933. throw PythonOps.TypeError("{0}() takes exactly {1} non-keyword arguments ({2} given)",
  1934. function.__name__,
  1935. function.NormalArgumentCount,
  1936. argCnt);
  1937. }
  1938. public static void AddDictionaryArgument(PythonFunction function, string name, object value, PythonDictionary dict) {
  1939. if (dict.ContainsKey(name)) {
  1940. throw MultipleKeywordArgumentError(function, name);
  1941. }
  1942. dict[name] = value;
  1943. }
  1944. public static void VerifyUnduplicatedByPosition(PythonFunction function, string name, int position, int listlen) {
  1945. if (listlen > 0 && listlen > position) {
  1946. throw MultipleKeywordArgumentError(function, name);
  1947. }
  1948. }
  1949. public static List CopyAndVerifyParamsList(PythonFunction function, object list) {
  1950. return new List(list);
  1951. }
  1952. public static PythonTuple GetOrCopyParamsTuple(PythonFunction function, object input) {
  1953. if (input == null) {
  1954. throw PythonOps.TypeError("{0}() argument after * must be a sequence, not NoneType", function.func_name);
  1955. } else if (input.GetType() == typeof(PythonTuple)) {
  1956. return (PythonTuple)input;
  1957. }
  1958. return PythonTuple.Make(input);
  1959. }
  1960. public static object ExtractParamsArgument(PythonFunction function, int argCnt, List list) {
  1961. if (list.__len__() != 0) {
  1962. return list.pop(0);
  1963. }
  1964. throw function.BadArgumentError(argCnt);
  1965. }
  1966. public static void AddParamsArguments(List list, params object[] args) {
  1967. for (int i = 0; i < args.Length; i++) {
  1968. list.insert(i, args[i]);
  1969. }
  1970. }
  1971. /// <summary>
  1972. /// Extracts an argument from either the dictionary or params
  1973. /// </summary>
  1974. public static object ExtractAnyArgument(PythonFunction function, string name, int argCnt, List list, IDictionary dict) {
  1975. object val;
  1976. if (dict.Contains(name)) {
  1977. if (list.__len__() != 0) {
  1978. throw MultipleKeywordArgumentError(function, name);
  1979. }
  1980. val = dict[name];
  1981. dict.Remove(name);
  1982. return val;
  1983. }
  1984. if (list.__len__() != 0) {
  1985. return list.pop(0);
  1986. }
  1987. if (function.ExpandDictPosition == -1 && dict.Count > 0) {
  1988. // python raises an error for extra splatted kw keys before missing arguments.
  1989. // therefore we check for this in the error case here.
  1990. foreach (string x in dict.Keys) {
  1991. bool found = false;
  1992. foreach (string y in function.ArgNames) {
  1993. if (x == y) {
  1994. found = true;
  1995. break;
  1996. }
  1997. }
  1998. if (!found) {
  1999. throw UnexpectedKeywordArgumentError(function, x);
  2000. }
  2001. }
  2002. }
  2003. throw BinderOps.TypeErrorForIncorrectArgumentCount(
  2004. function.__name__,
  2005. function.NormalArgumentCount,
  2006. function.Defaults.Length,
  2007. argCnt,
  2008. function.ExpandListPosition != -1,
  2009. dict.Count > 0);
  2010. }
  2011. public static object GetParamsValueOrDefault(PythonFunction function, int index, List extraArgs) {
  2012. if (extraArgs.__len__() > 0) {
  2013. return extraArgs.pop(0);
  2014. }
  2015. return function.Defaults[index];
  2016. }
  2017. public static object GetFunctionParameterValue(PythonFunction function, int index, string name, List extraArgs, PythonDictionary dict) {
  2018. if (extraArgs != null && extraArgs.__len__() > 0) {
  2019. return extraArgs.pop(0);
  2020. }
  2021. object val;
  2022. if (dict != null && dict.TryRemoveValue(name, out val)) {
  2023. return val;
  2024. }
  2025. return function.Defaults[index];
  2026. }
  2027. public static void CheckParamsZero(PythonFunction function, List extraArgs) {
  2028. if (extraArgs.__len__() != 0) {
  2029. throw function.BadArgumentError(extraArgs.__len__() + function.NormalArgumentCount);
  2030. }
  2031. }
  2032. public static void CheckUserParamsZero(PythonFunction function, object sequence) {
  2033. int len = PythonOps.Length(sequence);
  2034. if (len != 0) {
  2035. throw function.BadArgumentError(len + function.NormalArgumentCount);
  2036. }
  2037. }
  2038. public static void CheckDictionaryZero(PythonFunction function, IDictionary dict) {
  2039. if (dict.Count != 0) {
  2040. IDictionaryEnumerator ie = dict.GetEnumerator();
  2041. ie.MoveNext();
  2042. throw UnexpectedKeywordArgumentError(function, (string)ie.Key);
  2043. }
  2044. }
  2045. public static bool CheckDictionaryMembers(PythonDictionary dict, string[] names) {
  2046. if (dict.Count != names.Length) {
  2047. return false;
  2048. }
  2049. foreach (string name in names) {
  2050. if (!dict.ContainsKey(name)) {
  2051. return false;
  2052. }
  2053. }
  2054. return true;
  2055. }
  2056. public static object PythonFunctionGetMember(PythonFunction function, string name) {
  2057. object res;
  2058. if (function._dict != null && function._dict.TryGetValue(name, out res)) {
  2059. return res;
  2060. }
  2061. return OperationFailed.Value;
  2062. }
  2063. public static object PythonFunctionSetMember(PythonFunction function, string name, object value) {
  2064. return function.__dict__[name] = value;
  2065. }
  2066. public static void PythonFunctionDeleteDict() {
  2067. throw PythonOps.TypeError("function's dictionary may not be deleted");
  2068. }
  2069. public static void PythonFunctionDeleteDoc(PythonFunction function) {
  2070. function.__doc__ = null;
  2071. }
  2072. public static void PythonFunctionDeleteDefaults(PythonFunction function) {
  2073. function.__defaults__ = null;
  2074. }
  2075. public static bool PythonFunctionDeleteMember(PythonFunction function, string name) {
  2076. if (function._dict == null) return false;
  2077. return function._dict.Remove(name);
  2078. }
  2079. /// <summary>
  2080. /// Creates a new array the values set to Uninitialized.Instance. The array
  2081. /// is large enough to hold for all of the slots allocated for the type and
  2082. /// its sub types.
  2083. /// </summary>
  2084. public static object[] InitializeUserTypeSlots(PythonType/*!*/ type) {
  2085. if (type.SlotCount == 0) {
  2086. // if we later set the weak reference obj we'll create the array
  2087. return null;
  2088. }
  2089. // weak reference is stored at end of slots
  2090. object[] res = new object[type.SlotCount + 1];
  2091. for (int i = 0; i < res.Length - 1; i++) {
  2092. res[i] = Uninitialized.Instance;
  2093. }
  2094. return res;
  2095. }
  2096. public static bool IsClsVisible(CodeContext/*!*/ context) {
  2097. return context.ModuleContext.ShowCls;
  2098. }
  2099. public static object GetInitMember(CodeContext/*!*/ context, PythonType type, object instance) {
  2100. object value;
  2101. bool res = type.TryGetNonCustomBoundMember(context, instance, "__init__", out value);
  2102. Debug.Assert(res);
  2103. return value;
  2104. }
  2105. public static object GetInitSlotMember(CodeContext/*!*/ context, PythonType type, PythonTypeSlot slot, object instance) {
  2106. object value;
  2107. if (!slot.TryGetValue(context, instance, type, out value)) {
  2108. throw PythonOps.TypeError("bad __init__");
  2109. }
  2110. return value;
  2111. }
  2112. public static object GetMixedMember(CodeContext/*!*/ context, PythonType type, object instance, string name) {
  2113. foreach (PythonType t in type.ResolutionOrder) {
  2114. if (t.IsOldClass) {
  2115. OldClass oc = (OldClass)ToPythonType(t);
  2116. object ret;
  2117. if (oc._dict._storage.TryGetValue(name, out ret)) {
  2118. if (instance != null) return oc.GetOldStyleDescriptor(context, ret, instance, oc);
  2119. return ret;
  2120. }
  2121. } else {
  2122. PythonTypeSlot dts;
  2123. if (t.TryLookupSlot(context, name, out dts)) {
  2124. object ret;
  2125. if (dts.TryGetValue(context, instance, type, out ret)) {
  2126. return ret;
  2127. }
  2128. return dts;
  2129. }
  2130. }
  2131. }
  2132. throw AttributeErrorForMissingAttribute(type, name);
  2133. }
  2134. #region Slicing support
  2135. /// <summary>
  2136. /// Helper to determine if the value is a simple numeric type (int or big int or bool) - used for OldInstance
  2137. /// deprecated form of slicing.
  2138. /// </summary>
  2139. public static bool IsNumericObject(object value) {
  2140. return value is int || value is Extensible<int> || value is BigInteger || value is Extensible<BigInteger> || value is bool;
  2141. }
  2142. /// <summary>
  2143. /// Helper to determine if the type is a simple numeric type (int or big int or bool) - used for OldInstance
  2144. /// deprecated form of slicing.
  2145. /// </summary>
  2146. internal static bool IsNumericType(Type t) {
  2147. return IsNonExtensibleNumericType(t) ||
  2148. t.IsSubclassOf(typeof(Extensible<int>)) ||
  2149. t.IsSubclassOf(typeof(Extensible<BigInteger>));
  2150. }
  2151. /// <summary>
  2152. /// Helper to determine if the type is a simple numeric type (int or big int or bool) but not a subclass
  2153. /// </summary>
  2154. internal static bool IsNonExtensibleNumericType(Type t) {
  2155. return t == typeof(int) ||
  2156. t == typeof(bool) ||
  2157. t == typeof(BigInteger);
  2158. }
  2159. /// <summary>
  2160. /// For slicing. Fixes up a BigInteger and returns an integer w/ the length of the
  2161. /// object added if the value is negative.
  2162. /// </summary>
  2163. public static int NormalizeBigInteger(object self, BigInteger bi, ref Nullable<int> length) {
  2164. int val;
  2165. if (bi < BigInteger.Zero) {
  2166. GetLengthOnce(self, ref length);
  2167. if (bi.AsInt32(out val)) {
  2168. Debug.Assert(length.HasValue);
  2169. return val + length.Value;
  2170. } else {
  2171. return -1;
  2172. }
  2173. } else if (bi.AsInt32(out val)) {
  2174. return val;
  2175. }
  2176. return Int32.MaxValue;
  2177. }
  2178. /// <summary>
  2179. /// For slicing. Gets the length of the object, used to only get the length once.
  2180. /// </summary>
  2181. public static int GetLengthOnce(object self, ref Nullable<int> length) {
  2182. if (length != null) return length.Value;
  2183. length = PythonOps.Length(self);
  2184. return length.Value;
  2185. }
  2186. #endregion
  2187. public static ReflectedEvent.BoundEvent MakeBoundEvent(ReflectedEvent eventObj, object instance, Type type) {
  2188. return new ReflectedEvent.BoundEvent(eventObj, instance, DynamicHelpers.GetPythonTypeFromType(type));
  2189. }
  2190. /// <summary>
  2191. /// Helper method for DynamicSite rules that check the version of their dynamic object
  2192. /// TODO - Remove this method for more direct field accesses
  2193. /// </summary>
  2194. /// <param name="o"></param>
  2195. /// <param name="version"></param>
  2196. /// <returns></returns>
  2197. public static bool CheckTypeVersion(object o, int version) {
  2198. IPythonObject po = o as IPythonObject;
  2199. if (po == null) return false;
  2200. return po.PythonType.Version == version;
  2201. }
  2202. public static bool CheckSpecificTypeVersion(PythonType type, int version) {
  2203. return type.Version == version;
  2204. }
  2205. #region Conversion helpers
  2206. internal static MethodInfo GetConversionHelper(string name, ConversionResultKind resultKind) {
  2207. MethodInfo res;
  2208. switch (resultKind) {
  2209. case ConversionResultKind.ExplicitCast:
  2210. case ConversionResultKind.ImplicitCast:
  2211. res = typeof(PythonOps).GetMethod("Throwing" + name);
  2212. break;
  2213. case ConversionResultKind.ImplicitTry:
  2214. case ConversionResultKind.ExplicitTry:
  2215. res = typeof(PythonOps).GetMethod("NonThrowing" + name);
  2216. break;
  2217. default: throw new InvalidOperationException();
  2218. }
  2219. Debug.Assert(res != null);
  2220. return res;
  2221. }
  2222. public static IEnumerable OldInstanceConvertToIEnumerableNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2223. object callable;
  2224. if (self.TryGetBoundCustomMember(context, "__iter__", out callable)) {
  2225. return CreatePythonEnumerable(self);
  2226. } else if (self.TryGetBoundCustomMember(context, "__getitem__", out callable)) {
  2227. return CreateItemEnumerable(callable, PythonContext.GetContext(context).GetItemCallSite);
  2228. }
  2229. return null;
  2230. }
  2231. public static IEnumerable/*!*/ OldInstanceConvertToIEnumerableThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2232. IEnumerable res = OldInstanceConvertToIEnumerableNonThrowing(context, self);
  2233. if (res == null) {
  2234. throw TypeErrorForTypeMismatch("IEnumerable", self);
  2235. }
  2236. return res;
  2237. }
  2238. public static IEnumerable<T> OldInstanceConvertToIEnumerableOfTNonThrowing<T>(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2239. object callable;
  2240. if (self.TryGetBoundCustomMember(context, "__iter__", out callable)) {
  2241. return new IEnumerableOfTWrapper<T>(CreatePythonEnumerable(self));
  2242. } else if (self.TryGetBoundCustomMember(context, "__getitem__", out callable)) {
  2243. return new IEnumerableOfTWrapper<T>(CreateItemEnumerable(callable, PythonContext.GetContext(context).GetItemCallSite));
  2244. }
  2245. return null;
  2246. }
  2247. public static IEnumerable<T>/*!*/ OldInstanceConvertToIEnumerableOfTThrowing<T>(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2248. IEnumerable<T> res = OldInstanceConvertToIEnumerableOfTNonThrowing<T>(context, self);
  2249. if (res == null) {
  2250. throw TypeErrorForTypeMismatch("IEnumerable[T]", self);
  2251. }
  2252. return res;
  2253. }
  2254. public static IEnumerator OldInstanceConvertToIEnumeratorNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2255. object callable;
  2256. if (self.TryGetBoundCustomMember(context, "__iter__", out callable)) {
  2257. return CreatePythonEnumerator(self);
  2258. } else if (self.TryGetBoundCustomMember(context, "__getitem__", out callable)) {
  2259. return CreateItemEnumerator(callable, PythonContext.GetContext(context).GetItemCallSite);
  2260. }
  2261. return null;
  2262. }
  2263. public static IEnumerator/*!*/ OldInstanceConvertToIEnumeratorThrowing(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2264. IEnumerator res = OldInstanceConvertToIEnumeratorNonThrowing(context, self);
  2265. if (res == null) {
  2266. throw TypeErrorForTypeMismatch("IEnumerator", self);
  2267. }
  2268. return res;
  2269. }
  2270. public static bool? OldInstanceConvertToBoolNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi) {
  2271. object value;
  2272. if (oi.TryGetBoundCustomMember(context, "__nonzero__", out value)) {
  2273. object res = NonThrowingConvertToNonZero(PythonCalls.Call(context, value));
  2274. if (res is int) {
  2275. return ((int)res) != 0;
  2276. } else if (res is bool) {
  2277. return (bool)res;
  2278. }
  2279. } else if (oi.TryGetBoundCustomMember(context, "__len__", out value)) {
  2280. int res;
  2281. if (Converter.TryConvertToInt32(PythonCalls.Call(context, value), out res)) {
  2282. return res != 0;
  2283. }
  2284. }
  2285. return null;
  2286. }
  2287. public static object OldInstanceConvertToBoolThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi) {
  2288. object value;
  2289. if (oi.TryGetBoundCustomMember(context, "__nonzero__", out value)) {
  2290. return ThrowingConvertToNonZero(PythonCalls.Call(context, value));
  2291. } else if (oi.TryGetBoundCustomMember(context, "__len__", out value)) {
  2292. return PythonContext.GetContext(context).ConvertToInt32(PythonCalls.Call(context, value)) != 0;
  2293. }
  2294. return null;
  2295. }
  2296. public static object OldInstanceConvertNonThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi, string conversion) {
  2297. object value;
  2298. if (oi.TryGetBoundCustomMember(context, conversion, out value)) {
  2299. if (conversion == "__int__") {
  2300. return NonThrowingConvertToInt(PythonCalls.Call(context, value));
  2301. } else if (conversion == "__long__") {
  2302. return NonThrowingConvertToLong(PythonCalls.Call(context, value));
  2303. } else if (conversion == "__float__") {
  2304. return NonThrowingConvertToFloat(PythonCalls.Call(context, value));
  2305. } else if (conversion == "__complex__") {
  2306. return NonThrowingConvertToComplex(PythonCalls.Call(context, value));
  2307. } else if (conversion == "__str__") {
  2308. return NonThrowingConvertToString(PythonCalls.Call(context, value));
  2309. } else {
  2310. Debug.Assert(false);
  2311. }
  2312. } else if (conversion == "__complex__") {
  2313. object res = OldInstanceConvertNonThrowing(context, oi, "__float__");
  2314. if (res == null) {
  2315. return null;
  2316. }
  2317. return Converter.ConvertToComplex(res);
  2318. }
  2319. return null;
  2320. }
  2321. public static object OldInstanceConvertThrowing(CodeContext/*!*/ context, OldInstance/*!*/ oi, string conversion) {
  2322. object value;
  2323. if (oi.TryGetBoundCustomMember(context, conversion, out value)) {
  2324. if (conversion == "__int__") {
  2325. return ThrowingConvertToInt(PythonCalls.Call(context, value));
  2326. } else if (conversion == "__long__") {
  2327. return ThrowingConvertToLong(PythonCalls.Call(context, value));
  2328. } else if (conversion == "__float__") {
  2329. return ThrowingConvertToFloat(PythonCalls.Call(context, value));
  2330. } else if (conversion == "__complex__") {
  2331. return ThrowingConvertToComplex(PythonCalls.Call(context, value));
  2332. } else if (conversion == "__str__") {
  2333. return ThrowingConvertToString(PythonCalls.Call(context, value));
  2334. } else {
  2335. Debug.Assert(false);
  2336. }
  2337. } else if (conversion == "__complex__") {
  2338. return OldInstanceConvertThrowing(context, oi, "__float__");
  2339. }
  2340. return null;
  2341. }
  2342. public static object ConvertFloatToComplex(object value) {
  2343. if (value == null) {
  2344. return null;
  2345. }
  2346. double d = (double)value;
  2347. return new Complex(d, 0.0);
  2348. }
  2349. internal static bool CheckingConvertToInt(object value) {
  2350. return value is int || value is BigInteger || value is Extensible<int> || value is Extensible<BigInteger>;
  2351. }
  2352. internal static bool CheckingConvertToLong(object value) {
  2353. return CheckingConvertToInt(value);
  2354. }
  2355. internal static bool CheckingConvertToFloat(object value) {
  2356. return value is double || (value != null && value is Extensible<double>);
  2357. }
  2358. internal static bool CheckingConvertToComplex(object value) {
  2359. return value is Complex || value is Extensible<Complex> || CheckingConvertToInt(value) || CheckingConvertToFloat(value);
  2360. }
  2361. internal static bool CheckingConvertToString(object value) {
  2362. return value is string || value is Extensible<string>;
  2363. }
  2364. public static bool CheckingConvertToNonZero(object value) {
  2365. return value is bool || value is int;
  2366. }
  2367. public static object NonThrowingConvertToInt(object value) {
  2368. if (!CheckingConvertToInt(value)) return null;
  2369. return value;
  2370. }
  2371. public static object NonThrowingConvertToLong(object value) {
  2372. if (!CheckingConvertToInt(value)) return null;
  2373. return value;
  2374. }
  2375. public static object NonThrowingConvertToFloat(object value) {
  2376. if (!CheckingConvertToFloat(value)) return null;
  2377. return value;
  2378. }
  2379. public static object NonThrowingConvertToComplex(object value) {
  2380. if (!CheckingConvertToComplex(value)) return null;
  2381. return value;
  2382. }
  2383. public static object NonThrowingConvertToString(object value) {
  2384. if (!CheckingConvertToString(value)) return null;
  2385. return value;
  2386. }
  2387. public static object NonThrowingConvertToNonZero(object value) {
  2388. if (!CheckingConvertToNonZero(value)) return null;
  2389. return value;
  2390. }
  2391. public static object ThrowingConvertToInt(object value) {
  2392. if (!CheckingConvertToInt(value)) throw TypeError(" __int__ returned non-int (type {0})", PythonTypeOps.GetName(value));
  2393. return value;
  2394. }
  2395. public static object ThrowingConvertToFloat(object value) {
  2396. if (!CheckingConvertToFloat(value)) throw TypeError(" __float__ returned non-float (type {0})", PythonTypeOps.GetName(value));
  2397. return value;
  2398. }
  2399. public static object ThrowingConvertToComplex(object value) {
  2400. if (!CheckingConvertToComplex(value)) throw TypeError(" __complex__ returned non-complex (type {0})", PythonTypeOps.GetName(value));
  2401. return value;
  2402. }
  2403. public static object ThrowingConvertToLong(object value) {
  2404. if (!CheckingConvertToComplex(value)) throw TypeError(" __long__ returned non-long (type {0})", PythonTypeOps.GetName(value));
  2405. return value;
  2406. }
  2407. public static object ThrowingConvertToString(object value) {
  2408. if (!CheckingConvertToString(value)) throw TypeError(" __str__ returned non-str (type {0})", PythonTypeOps.GetName(value));
  2409. return value;
  2410. }
  2411. public static bool ThrowingConvertToNonZero(object value) {
  2412. if (!CheckingConvertToNonZero(value)) throw TypeError("__nonzero__ should return bool or int, returned {0}", PythonTypeOps.GetName(value));
  2413. if (value is bool) {
  2414. return (bool)value;
  2415. }
  2416. return ((int)value) != 0;
  2417. }
  2418. #endregion
  2419. public static bool SlotTryGetBoundValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, out object value) {
  2420. Debug.Assert(slot != null);
  2421. return slot.TryGetValue(context, instance, owner, out value);
  2422. }
  2423. public static bool SlotTryGetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, out object value) {
  2424. return slot.TryGetValue(context, instance, owner, out value);
  2425. }
  2426. public static object SlotGetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner) {
  2427. object value;
  2428. if (!slot.TryGetValue(context, instance, owner, out value)) {
  2429. throw new InvalidOperationException();
  2430. }
  2431. return value;
  2432. }
  2433. public static bool SlotTrySetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, object value) {
  2434. return slot.TrySetValue(context, instance, owner, value);
  2435. }
  2436. public static object SlotSetValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner, object value) {
  2437. if (!slot.TrySetValue(context, instance, owner, value)) {
  2438. throw new InvalidOperationException();
  2439. }
  2440. return value;
  2441. }
  2442. public static bool SlotTryDeleteValue(CodeContext/*!*/ context, PythonTypeSlot/*!*/ slot, object instance, PythonType owner) {
  2443. return slot.TryDeleteValue(context, instance, owner);
  2444. }
  2445. public static BuiltinFunction/*!*/ MakeBoundBuiltinFunction(BuiltinFunction/*!*/ function, object/*!*/ target) {
  2446. return function.BindToInstance(target);
  2447. }
  2448. /// <summary>
  2449. /// Called from generated code. Gets a builtin function and the BuiltinFunctionData associated
  2450. /// with the object. Tests to see if the function is bound and has the same data for the generated
  2451. /// rule.
  2452. /// </summary>
  2453. public static bool TestBoundBuiltinFunction(BuiltinFunction/*!*/ function, object data) {
  2454. if (function.IsUnbound) {
  2455. // not bound
  2456. return false;
  2457. }
  2458. return function.TestData(data);
  2459. }
  2460. public static BuiltinFunction/*!*/ GetBuiltinMethodDescriptorTemplate(BuiltinMethodDescriptor/*!*/ descriptor) {
  2461. return descriptor.Template;
  2462. }
  2463. public static int GetTypeVersion(PythonType type) {
  2464. return type.Version;
  2465. }
  2466. public static bool TryResolveTypeSlot(CodeContext/*!*/ context, PythonType type, string name, out PythonTypeSlot slot) {
  2467. return type.TryResolveSlot(context, name, out slot);
  2468. }
  2469. public static T[] ConvertTupleToArray<T>(PythonTuple tuple) {
  2470. T[] res = new T[tuple.__len__()];
  2471. for (int i = 0; i < tuple.__len__(); i++) {
  2472. try {
  2473. res[i] = (T)tuple[i];
  2474. } catch (InvalidCastException) {
  2475. res[i] = Converter.Convert<T>(tuple[i]);
  2476. }
  2477. }
  2478. return res;
  2479. }
  2480. #region Function helpers
  2481. public static PythonGenerator MakeGenerator(PythonFunction function, MutableTuple data, object generatorCode) {
  2482. Func<MutableTuple, object> next = generatorCode as Func<MutableTuple, object>;
  2483. if (next == null) {
  2484. next = ((LazyCode<Func<MutableTuple, object>>)generatorCode).EnsureDelegate();
  2485. }
  2486. return new PythonGenerator(function, next, data);
  2487. }
  2488. public static object MakeGeneratorExpression(object function, object input) {
  2489. PythonFunction func = (PythonFunction)function;
  2490. return ((Func<PythonFunction, object, object>)func.func_code.Target)(func, input);
  2491. }
  2492. 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) {
  2493. Compiler.Ast.SerializedScopeStatement scope = new Compiler.Ast.SerializedScopeStatement(name, argNames, flags, span, path, freeVars, names, cellVars, varNames);
  2494. return new FunctionCode(PythonContext.GetContext(context), code, scope, documentation, localCount);
  2495. }
  2496. [NoSideEffects]
  2497. public static object MakeFunction(CodeContext/*!*/ context, FunctionCode funcInfo, object modName, object[] defaults) {
  2498. return new PythonFunction(context, funcInfo, modName, defaults, null);
  2499. }
  2500. [NoSideEffects]
  2501. public static object MakeFunctionDebug(CodeContext/*!*/ context, FunctionCode funcInfo, object modName, object[] defaults, Delegate target) {
  2502. funcInfo.SetDebugTarget(PythonContext.GetContext(context), target);
  2503. return new PythonFunction(context, funcInfo, modName, defaults, null);
  2504. }
  2505. public static CodeContext FunctionGetContext(PythonFunction func) {
  2506. return func.Context;
  2507. }
  2508. public static object FunctionGetDefaultValue(PythonFunction func, int index) {
  2509. return func.Defaults[index];
  2510. }
  2511. public static int FunctionGetCompatibility(PythonFunction func) {
  2512. return func.FunctionCompatibility;
  2513. }
  2514. public static int FunctionGetID(PythonFunction func) {
  2515. return func.FunctionID;
  2516. }
  2517. public static Delegate FunctionGetTarget(PythonFunction func) {
  2518. return func.func_code.Target;
  2519. }
  2520. public static void FunctionPushFrame(PythonContext context) {
  2521. if (PythonFunction.AddRecursionDepth(1) > context.RecursionLimit) {
  2522. throw PythonOps.RuntimeError("maximum recursion depth exceeded");
  2523. }
  2524. }
  2525. public static void FunctionPushFrameCodeContext(CodeContext context) {
  2526. FunctionPushFrame(PythonContext.GetContext(context));
  2527. }
  2528. public static void FunctionPopFrame() {
  2529. PythonFunction.AddRecursionDepth(-1);
  2530. }
  2531. #endregion
  2532. public static object ReturnConversionResult(object value) {
  2533. PythonTuple pt = value as PythonTuple;
  2534. if (pt != null) {
  2535. return pt[0];
  2536. }
  2537. return NotImplementedType.Value;
  2538. }
  2539. /// <summary>
  2540. /// Convert object to a given type. This code is equivalent to NewTypeMaker.EmitConvertFromObject
  2541. /// except that it happens at runtime instead of compile time.
  2542. /// </summary>
  2543. public static T ConvertFromObject<T>(object obj) {
  2544. Type toType = typeof(T);
  2545. object result;
  2546. MethodInfo fastConvertMethod = PythonBinder.GetFastConvertMethod(toType);
  2547. if (fastConvertMethod != null) {
  2548. result = fastConvertMethod.Invoke(null, new object[] { obj });
  2549. } else if (typeof(Delegate).IsAssignableFrom(toType)) {
  2550. result = Converter.ConvertToDelegate(obj, toType);
  2551. } else {
  2552. result = obj;
  2553. }
  2554. return (T)obj;
  2555. }
  2556. public static DynamicMetaObjectBinder MakeComplexCallAction(int count, bool list, string[] keywords) {
  2557. Argument[] infos = CompilerHelpers.MakeRepeatedArray(Argument.Simple, count + keywords.Length);
  2558. if (list) {
  2559. infos[checked(count - 1)] = new Argument(ArgumentType.List);
  2560. }
  2561. for (int i = 0; i < keywords.Length; i++) {
  2562. infos[count + i] = new Argument(keywords[i]);
  2563. }
  2564. return DefaultContext.DefaultPythonContext.Invoke(
  2565. new CallSignature(infos)
  2566. );
  2567. }
  2568. public static DynamicMetaObjectBinder MakeSimpleCallAction(int count) {
  2569. return DefaultContext.DefaultPythonContext.Invoke(
  2570. new CallSignature(CompilerHelpers.MakeRepeatedArray(Argument.Simple, count))
  2571. );
  2572. }
  2573. public static PythonTuple ValidateCoerceResult(object coerceResult) {
  2574. if (coerceResult == null || coerceResult == NotImplementedType.Value) {
  2575. return null;
  2576. }
  2577. PythonTuple pt = coerceResult as PythonTuple;
  2578. if (pt == null) throw PythonOps.TypeError("coercion should return None, NotImplemented, or 2-tuple, got {0}", PythonTypeOps.GetName(coerceResult));
  2579. return pt;
  2580. }
  2581. public static object GetCoerceResultOne(PythonTuple coerceResult) {
  2582. return coerceResult._data[0];
  2583. }
  2584. public static object GetCoerceResultTwo(PythonTuple coerceResult) {
  2585. return coerceResult._data[1];
  2586. }
  2587. public static object MethodCheckSelf(CodeContext context, Method method, object self) {
  2588. return method.CheckSelf(context, self);
  2589. }
  2590. public static object GeneratorCheckThrowableAndReturnSendValue(object self) {
  2591. return ((PythonGenerator)self).CheckThrowableAndReturnSendValue();
  2592. }
  2593. public static ItemEnumerable CreateItemEnumerable(object callable, CallSite<Func<CallSite, CodeContext, object, int, object>> site) {
  2594. return new ItemEnumerable(callable, site);
  2595. }
  2596. public static DictionaryKeyEnumerator MakeDictionaryKeyEnumerator(PythonDictionary dict) {
  2597. return new DictionaryKeyEnumerator(dict._storage);
  2598. }
  2599. public static IEnumerable CreatePythonEnumerable(object baseObject) {
  2600. return PythonEnumerable.Create(baseObject);
  2601. }
  2602. public static IEnumerator CreateItemEnumerator(object callable, CallSite<Func<CallSite, CodeContext, object, int, object>> site) {
  2603. return new ItemEnumerator(callable, site);
  2604. }
  2605. public static IEnumerator CreatePythonEnumerator(object baseObject) {
  2606. return PythonEnumerator.Create(baseObject);
  2607. }
  2608. public static bool ContainsFromEnumerable(CodeContext/*!*/ context, object enumerable, object value) {
  2609. IEnumerator ie = enumerable as IEnumerator;
  2610. if (ie == null) {
  2611. IEnumerable ienum = enumerable as IEnumerable;
  2612. if (ienum != null) {
  2613. ie = ienum.GetEnumerator();
  2614. } else {
  2615. ie = Converter.ConvertToIEnumerator(enumerable);
  2616. }
  2617. }
  2618. while (ie.MoveNext()) {
  2619. if (PythonOps.EqualRetBool(context, ie.Current, value)) {
  2620. return true;
  2621. }
  2622. }
  2623. return false;
  2624. }
  2625. public static object PythonTypeGetMember(CodeContext/*!*/ context, PythonType type, object instance, string name) {
  2626. return type.GetMember(context, instance, name);
  2627. }
  2628. [NoSideEffects]
  2629. public static object CheckUninitialized(object value, string name) {
  2630. if (value == Uninitialized.Instance) {
  2631. throw new UnboundLocalException(String.Format("Local variable '{0}' referenced before assignment.", name));
  2632. }
  2633. return value;
  2634. }
  2635. #region OldClass/OldInstance public helpers
  2636. public static PythonDictionary OldClassGetDictionary(OldClass klass) {
  2637. return klass._dict;
  2638. }
  2639. public static string OldClassGetName(OldClass klass) {
  2640. return klass.Name;
  2641. }
  2642. public static bool OldInstanceIsCallable(CodeContext/*!*/ context, OldInstance/*!*/ self) {
  2643. object dummy;
  2644. return self.TryGetBoundCustomMember(context, "__call__", out dummy);
  2645. }
  2646. public static object OldClassCheckCallError(OldClass/*!*/ self, object dictionary, object list) {
  2647. if ((dictionary != null && PythonOps.Length(dictionary) != 0) ||
  2648. (list != null && PythonOps.Length(list) != 0)) {
  2649. return OldClass.MakeCallError();
  2650. }
  2651. return null;
  2652. }
  2653. public static object OldClassSetBases(OldClass oc, object value) {
  2654. oc.SetBases(value);
  2655. return value;
  2656. }
  2657. public static object OldClassSetName(OldClass oc, object value) {
  2658. oc.SetName(value);
  2659. return value;
  2660. }
  2661. public static object OldClassSetDictionary(OldClass oc, object value) {
  2662. oc.SetDictionary(value);
  2663. return value;
  2664. }
  2665. public static object OldClassSetNameHelper(OldClass oc, string name, object value) {
  2666. oc.SetNameHelper(name, value);
  2667. return value;
  2668. }
  2669. public static bool OldClassTryLookupInit(OldClass oc, object inst, out object ret) {
  2670. return oc.TryLookupInit(inst, out ret);
  2671. }
  2672. public static object OldClassMakeCallError(OldClass oc) {
  2673. return OldClass.MakeCallError();
  2674. }
  2675. public static PythonTuple OldClassGetBaseClasses(OldClass oc) {
  2676. return PythonTuple.MakeTuple(oc.BaseClasses.ToArray());
  2677. }
  2678. public static void OldClassDictionaryIsPublic(OldClass oc) {
  2679. oc.DictionaryIsPublic();
  2680. }
  2681. public static bool OldClassTryLookupValue(CodeContext context, OldClass oc, string name, out object value) {
  2682. return oc.TryLookupValue(context, name, out value);
  2683. }
  2684. public static object OldClassLookupValue(CodeContext context, OldClass oc, string name) {
  2685. return oc.LookupValue(context, name);
  2686. }
  2687. public static object OldInstanceGetOptimizedDictionary(OldInstance instance, int keyVersion) {
  2688. CustomInstanceDictionaryStorage storage = instance.Dictionary._storage as CustomInstanceDictionaryStorage;
  2689. if (storage == null || instance._class.HasSetAttr || storage.KeyVersion != keyVersion) {
  2690. return null;
  2691. }
  2692. return storage;
  2693. }
  2694. public static object OldInstanceDictionaryGetValueHelper(object dict, int index, object oldInstance) {
  2695. return ((CustomInstanceDictionaryStorage)dict).GetValueHelper(index, oldInstance);
  2696. }
  2697. public static bool TryOldInstanceDictionaryGetValueHelper(object dict, int index, object oldInstance, out object res) {
  2698. return ((CustomInstanceDictionaryStorage)dict).TryGetValueHelper(index, oldInstance, out res);
  2699. }
  2700. public static object OldInstanceGetBoundMember(CodeContext context, OldInstance instance, string name) {
  2701. return instance.GetBoundMember(context, name);
  2702. }
  2703. public static object OldInstanceDictionarySetExtraValue(object dict, int index, object value) {
  2704. ((CustomInstanceDictionaryStorage)dict).SetExtraValue(index, value);
  2705. return value;
  2706. }
  2707. public static object OldClassDeleteMember(CodeContext context, OldClass self, string name) {
  2708. self.DeleteCustomMember(context, name);
  2709. return null;
  2710. }
  2711. public static bool OldClassTryLookupOneSlot(PythonType type, OldClass self, string name, out object value) {
  2712. return self.TryLookupOneSlot(type, name, out value);
  2713. }
  2714. public static bool OldInstanceTryGetBoundCustomMember(CodeContext context, OldInstance self, string name, out object value) {
  2715. return self.TryGetBoundCustomMember(context, name, out value);
  2716. }
  2717. public static object OldInstanceSetCustomMember(CodeContext context, OldInstance self, string name, object value) {
  2718. self.SetCustomMember(context, name, value);
  2719. return value;
  2720. }
  2721. public static object OldInstanceDeleteCustomMember(CodeContext context, OldInstance self, string name) {
  2722. self.DeleteCustomMember(context, name);
  2723. return null;
  2724. }
  2725. #endregion
  2726. public static object PythonTypeSetCustomMember(CodeContext context, PythonType self, string name, object value) {
  2727. self.SetCustomMember(context, name, value);
  2728. return value;
  2729. }
  2730. public static object PythonTypeDeleteCustomMember(CodeContext context, PythonType self, string name) {
  2731. self.DeleteCustomMember(context, name);
  2732. return null;
  2733. }
  2734. public static bool IsPythonType(PythonType type) {
  2735. return type.IsPythonType;
  2736. }
  2737. public static object PublishModule(CodeContext/*!*/ context, string name) {
  2738. object original = null;
  2739. context.LanguageContext.SystemStateModules.TryGetValue(name, out original);
  2740. var module = ((PythonScopeExtension)context.GlobalScope.GetExtension(context.LanguageContext.ContextId)).Module;
  2741. context.LanguageContext.SystemStateModules[name] = module;
  2742. return original;
  2743. }
  2744. public static void RemoveModule(CodeContext/*!*/ context, string name, object oldValue) {
  2745. if (oldValue != null) {
  2746. PythonContext.GetContext(context).SystemStateModules[name] = oldValue;
  2747. } else {
  2748. PythonContext.GetContext(context).SystemStateModules.Remove(name);
  2749. }
  2750. }
  2751. public static Ellipsis Ellipsis {
  2752. get {
  2753. return Ellipsis.Value;
  2754. }
  2755. }
  2756. public static NotImplementedType NotImplemented {
  2757. get {
  2758. return NotImplementedType.Value;
  2759. }
  2760. }
  2761. public static void ListAddForComprehension(List l, object o) {
  2762. l.AddNoLock(o);
  2763. }
  2764. public static void ModuleStarted(CodeContext/*!*/ context, ModuleOptions features) {
  2765. context.ModuleContext.Features |= features;
  2766. }
  2767. public static void Warn(CodeContext/*!*/ context, PythonType category, string message, params object[] args) {
  2768. PythonContext pc = PythonContext.GetContext(context);
  2769. object warnings = pc.GetWarningsModule(), warn = null;
  2770. if (warnings != null) {
  2771. warn = PythonOps.GetBoundAttr(context, warnings, "warn");
  2772. }
  2773. message = FormatWarning(message, args);
  2774. if (warn == null) {
  2775. PythonOps.PrintWithDest(context, pc.SystemStandardError, "warning: " + category.Name + ": " + message);
  2776. } else {
  2777. PythonOps.CallWithContext(context, warn, message, category);
  2778. }
  2779. }
  2780. public static void ShowWarning(CodeContext/*!*/ context, PythonType category, string message, string filename, int lineNo) {
  2781. PythonContext pc = PythonContext.GetContext(context);
  2782. object warnings = pc.GetWarningsModule(), warn = null;
  2783. if (warnings != null) {
  2784. warn = PythonOps.GetBoundAttr(context, warnings, "showwarning");
  2785. }
  2786. if (warn == null) {
  2787. PythonOps.PrintWithDestNoNewline(context, pc.SystemStandardError, String.Format("{0}:{1}: {2}: {3}\n", filename, lineNo, category.Name, message));
  2788. } else {
  2789. PythonOps.CallWithContext(context, warn, message, category, filename ?? "", lineNo);
  2790. }
  2791. }
  2792. private static string FormatWarning(string message, object[] args) {
  2793. for (int i = 0; i < args.Length; i++) {
  2794. args[i] = PythonOps.ToString(args[i]);
  2795. }
  2796. message = String.Format(message, args);
  2797. return message;
  2798. }
  2799. private static bool IsPrimitiveNumber(object o) {
  2800. return IsNumericObject(o) ||
  2801. o is Complex ||
  2802. o is double ||
  2803. o is Extensible<Complex> ||
  2804. o is Extensible<double>;
  2805. }
  2806. public static void WarnDivision(CodeContext/*!*/ context, PythonDivisionOptions options, object self, object other) {
  2807. if (options == PythonDivisionOptions.WarnAll) {
  2808. if (IsPrimitiveNumber(self) && IsPrimitiveNumber(other)) {
  2809. if (self is Complex || other is Complex || self is Extensible<Complex> || other is Extensible<Complex>) {
  2810. Warn(context, PythonExceptions.DeprecationWarning, "classic complex division");
  2811. return;
  2812. } else if (self is double || other is double || self is Extensible<double> || other is Extensible<double>) {
  2813. Warn(context, PythonExceptions.DeprecationWarning, "classic float division");
  2814. return;
  2815. } else {
  2816. WarnDivisionInts(context, self, other);
  2817. }
  2818. }
  2819. } else if (IsNumericObject(self) && IsNumericObject(other)) {
  2820. WarnDivisionInts(context, self, other);
  2821. }
  2822. }
  2823. private static void WarnDivisionInts(CodeContext/*!*/ context, object self, object other) {
  2824. if (self is BigInteger || other is BigInteger || self is Extensible<BigInteger> || other is Extensible<BigInteger>) {
  2825. Warn(context, PythonExceptions.DeprecationWarning, "classic long division");
  2826. } else {
  2827. Warn(context, PythonExceptions.DeprecationWarning, "classic int division");
  2828. }
  2829. }
  2830. public static DynamicMetaObjectBinder MakeComboAction(CodeContext/*!*/ context, DynamicMetaObjectBinder opBinder, DynamicMetaObjectBinder convBinder) {
  2831. return PythonContext.GetContext(context).BinaryOperationRetType((PythonBinaryOperationBinder)opBinder, (PythonConversionBinder)convBinder);
  2832. }
  2833. public static DynamicMetaObjectBinder MakeInvokeAction(CodeContext/*!*/ context, CallSignature signature) {
  2834. return PythonContext.GetContext(context).Invoke(signature);
  2835. }
  2836. public static DynamicMetaObjectBinder MakeGetAction(CodeContext/*!*/ context, string name, bool isNoThrow) {
  2837. return PythonContext.GetContext(context).GetMember(name);
  2838. }
  2839. public static DynamicMetaObjectBinder MakeCompatGetAction(CodeContext/*!*/ context, string name) {
  2840. return PythonContext.GetContext(context).CompatGetMember(name, false);
  2841. }
  2842. public static DynamicMetaObjectBinder MakeCompatInvokeAction(CodeContext/*!*/ context, CallInfo callInfo) {
  2843. return PythonContext.GetContext(context).CompatInvoke(callInfo);
  2844. }
  2845. public static DynamicMetaObjectBinder MakeCompatConvertAction(CodeContext/*!*/ context, Type toType, bool isExplicit) {
  2846. return PythonContext.GetContext(context).Convert(toType, isExplicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast).CompatBinder;
  2847. }
  2848. public static DynamicMetaObjectBinder MakeSetAction(CodeContext/*!*/ context, string name) {
  2849. return PythonContext.GetContext(context).SetMember(name);
  2850. }
  2851. public static DynamicMetaObjectBinder MakeDeleteAction(CodeContext/*!*/ context, string name) {
  2852. return PythonContext.GetContext(context).DeleteMember(name);
  2853. }
  2854. public static DynamicMetaObjectBinder MakeConversionAction(CodeContext/*!*/ context, Type type, ConversionResultKind kind) {
  2855. return PythonContext.GetContext(context).Convert(type, kind);
  2856. }
  2857. public static DynamicMetaObjectBinder MakeTryConversionAction(CodeContext/*!*/ context, Type type, ConversionResultKind kind) {
  2858. return PythonContext.GetContext(context).Convert(type, kind);
  2859. }
  2860. public static DynamicMetaObjectBinder MakeOperationAction(CodeContext/*!*/ context, int operationName) {
  2861. return PythonContext.GetContext(context).Operation((PythonOperationKind)operationName);
  2862. }
  2863. public static DynamicMetaObjectBinder MakeUnaryOperationAction(CodeContext/*!*/ context, ExpressionType expressionType) {
  2864. return PythonContext.GetContext(context).UnaryOperation(expressionType);
  2865. }
  2866. public static DynamicMetaObjectBinder MakeBinaryOperationAction(CodeContext/*!*/ context, ExpressionType expressionType) {
  2867. return PythonContext.GetContext(context).BinaryOperation(expressionType);
  2868. }
  2869. public static DynamicMetaObjectBinder MakeGetIndexAction(CodeContext/*!*/ context, int argCount) {
  2870. return PythonContext.GetContext(context).GetIndex(argCount);
  2871. }
  2872. public static DynamicMetaObjectBinder MakeSetIndexAction(CodeContext/*!*/ context, int argCount) {
  2873. return PythonContext.GetContext(context).SetIndex(argCount);
  2874. }
  2875. public static DynamicMetaObjectBinder MakeDeleteIndexAction(CodeContext/*!*/ context, int argCount) {
  2876. return PythonContext.GetContext(context).DeleteIndex(argCount);
  2877. }
  2878. public static DynamicMetaObjectBinder MakeGetSliceBinder(CodeContext/*!*/ context) {
  2879. return PythonContext.GetContext(context).GetSlice;
  2880. }
  2881. public static DynamicMetaObjectBinder MakeSetSliceBinder(CodeContext/*!*/ context) {
  2882. return PythonContext.GetContext(context).SetSliceBinder;
  2883. }
  2884. public static DynamicMetaObjectBinder MakeDeleteSliceBinder(CodeContext/*!*/ context) {
  2885. return PythonContext.GetContext(context).DeleteSlice;
  2886. }
  2887. /// <summary>
  2888. /// Provides access to AppDomain.DefineDynamicAssembly which cannot be called from a DynamicMethod
  2889. /// </summary>
  2890. public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) {
  2891. return AppDomain.CurrentDomain.DefineDynamicAssembly(name, access);
  2892. }
  2893. /// <summary>
  2894. /// Generates a new delegate type. The last type in the array is the return type.
  2895. /// </summary>
  2896. public static Type/*!*/ MakeNewCustomDelegate(Type/*!*/[]/*!*/ types) {
  2897. return MakeNewCustomDelegate(types, null);
  2898. }
  2899. /// <summary>
  2900. /// Generates a new delegate type. The last type in the array is the return type.
  2901. /// </summary>
  2902. public static Type/*!*/ MakeNewCustomDelegate(Type/*!*/[]/*!*/ types, CallingConvention? callingConvention) {
  2903. const MethodAttributes CtorAttributes = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
  2904. const MethodImplAttributes ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
  2905. const MethodAttributes InvokeAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;
  2906. Type returnType = types[types.Length - 1];
  2907. Type[] parameters = ArrayUtils.RemoveLast(types);
  2908. TypeBuilder builder = Snippets.Shared.DefineDelegateType("Delegate" + types.Length);
  2909. builder.DefineConstructor(CtorAttributes, CallingConventions.Standard, _DelegateCtorSignature).SetImplementationFlags(ImplAttributes);
  2910. builder.DefineMethod("Invoke", InvokeAttributes, returnType, parameters).SetImplementationFlags(ImplAttributes);
  2911. if (callingConvention != null) {
  2912. builder.SetCustomAttribute(new CustomAttributeBuilder(
  2913. typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new[] { typeof(CallingConvention) }),
  2914. new object[] { callingConvention })
  2915. );
  2916. }
  2917. return builder.CreateType();
  2918. }
  2919. #if !SILVERLIGHT
  2920. /// <summary>
  2921. /// Provides the entry point for a compiled module. The stub exe calls into InitializeModule which
  2922. /// does the actual work of adding references and importing the main module. Upon completion it returns
  2923. /// the exit code that the program reported via SystemExit or 0.
  2924. /// </summary>
  2925. public static int InitializeModule(Assembly/*!*/ precompiled, string/*!*/ main, string[] references) {
  2926. ContractUtils.RequiresNotNull(precompiled, "precompiled");
  2927. ContractUtils.RequiresNotNull(main, "main");
  2928. Dictionary<string, object> options = new Dictionary<string, object>();
  2929. options["Arguments"] = ArrayUtils.RemoveFirst(Environment.GetCommandLineArgs()); // remove the EXE
  2930. var pythonEngine = Python.CreateEngine(options);
  2931. var pythonContext = (PythonContext)HostingHelpers.GetLanguageContext(pythonEngine);
  2932. foreach (var scriptCode in SavableScriptCode.LoadFromAssembly(pythonContext.DomainManager, precompiled)) {
  2933. pythonContext.GetCompiledLoader().AddScriptCode(scriptCode);
  2934. }
  2935. if (references != null) {
  2936. foreach (string referenceName in references) {
  2937. pythonContext.DomainManager.LoadAssembly(Assembly.Load(referenceName));
  2938. }
  2939. }
  2940. ModuleContext modCtx = new ModuleContext(new PythonDictionary(), pythonContext);
  2941. // import __main__
  2942. try {
  2943. Importer.Import(modCtx.GlobalContext, main, PythonTuple.EMPTY, 0);
  2944. } catch (SystemExitException ex) {
  2945. ExceptionHelpers.DynamicStackFrames = null;
  2946. object dummy;
  2947. return ex.GetExitCode(out dummy);
  2948. }
  2949. return 0;
  2950. }
  2951. #endif
  2952. public static CodeContext GetPythonTypeContext(PythonType pt) {
  2953. return pt.PythonContext.SharedContext;
  2954. }
  2955. public static Delegate GetDelegate(CodeContext context, object target, Type type) {
  2956. return context.LanguageContext.DelegateCreator.GetDelegate(target, type);
  2957. }
  2958. public static int CompareLists(List self, List other) {
  2959. return self.CompareTo(other);
  2960. }
  2961. public static int CompareTuples(PythonTuple self, PythonTuple other) {
  2962. return self.CompareTo(other);
  2963. }
  2964. public static int CompareFloats(double self, double other) {
  2965. return DoubleOps.Compare(self, other);
  2966. }
  2967. public static Bytes MakeBytes(byte[] bytes) {
  2968. return new Bytes(bytes);
  2969. }
  2970. public static byte[] MakeByteArray(this string s) {
  2971. byte[] ret = new byte[s.Length];
  2972. for (int i = 0; i < s.Length; i++) {
  2973. if (s[i] < 0x100) ret[i] = (byte)s[i];
  2974. else throw PythonOps.UnicodeEncodeError("'ascii' codec can't decode byte {0:X} in position {1}: ordinal not in range", (int)ret[i], i);
  2975. }
  2976. return ret;
  2977. }
  2978. public static string MakeString(this IList<byte> bytes) {
  2979. return MakeString(bytes, bytes.Count);
  2980. }
  2981. internal static string MakeString(this byte[] preamble, IList<byte> bytes) {
  2982. char[] chars = new char[preamble.Length + bytes.Count];
  2983. for (int i = 0; i < preamble.Length; i++) {
  2984. chars[i] = (char)preamble[i];
  2985. }
  2986. for (int i = 0; i < bytes.Count; i++) {
  2987. chars[i + preamble.Length] = (char)bytes[i];
  2988. }
  2989. return new String(chars);
  2990. }
  2991. internal static string MakeString(this IList<byte> bytes, int maxBytes) {
  2992. int bytesToCopy = Math.Min(bytes.Count, maxBytes);
  2993. StringBuilder b = new StringBuilder(bytesToCopy);
  2994. for (int i = 0; i < bytesToCopy; i++) {
  2995. b.Append((char)bytes[i]);
  2996. }
  2997. return b.ToString();
  2998. }
  2999. /// <summary>
  3000. /// Called from generated code, helper to remove a name
  3001. /// </summary>
  3002. public static void RemoveName(CodeContext context, string name) {
  3003. if (!context.TryRemoveVariable(name)) {
  3004. throw PythonOps.NameError(name);
  3005. }
  3006. }
  3007. /// <summary>
  3008. /// Called from generated code, helper to do name lookup
  3009. /// </summary>
  3010. public static object LookupName(CodeContext context, string name) {
  3011. object value;
  3012. if (context.TryLookupName(name, out value)) {
  3013. return value;
  3014. } else if (context.TryLookupBuiltin(name, out value)) {
  3015. return value;
  3016. }
  3017. throw PythonOps.NameError(name);
  3018. }
  3019. /// <summary>
  3020. /// Called from generated code, helper to do name assignment
  3021. /// </summary>
  3022. public static object SetName(CodeContext context, string name, object value) {
  3023. context.SetVariable(name, value);
  3024. return value;
  3025. }
  3026. /// <summary>
  3027. /// Returns an IntPtr in the proper way to CPython - an int or a Python long
  3028. /// </summary>
  3029. public static object/*!*/ ToPython(this IntPtr handle) {
  3030. long value = handle.ToInt64();
  3031. if (value >= Int32.MinValue && value <= Int32.MaxValue) {
  3032. return ScriptingRuntimeHelpers.Int32ToObject((int)value);
  3033. }
  3034. return (BigInteger)value;
  3035. }
  3036. #region Global Access
  3037. public static CodeContext/*!*/ CreateLocalContext(CodeContext/*!*/ outerContext, MutableTuple boxes, string[] args) {
  3038. return new CodeContext(
  3039. new PythonDictionary(
  3040. new RuntimeVariablesDictionaryStorage(boxes, args)
  3041. ),
  3042. outerContext.ModuleContext
  3043. );
  3044. }
  3045. public static CodeContext/*!*/ GetGlobalContext(CodeContext/*!*/ context) {
  3046. return context.ModuleContext.GlobalContext;
  3047. }
  3048. public static ClosureCell/*!*/ MakeClosureCell() {
  3049. return new ClosureCell(Uninitialized.Instance);
  3050. }
  3051. public static ClosureCell/*!*/ MakeClosureCellWithValue(object initialValue) {
  3052. return new ClosureCell(initialValue);
  3053. }
  3054. public static MutableTuple/*!*/ GetClosureTupleFromFunction(PythonFunction/*!*/ function) {
  3055. return GetClosureTupleFromContext(function.Context);
  3056. }
  3057. public static MutableTuple/*!*/ GetClosureTupleFromGenerator(PythonGenerator/*!*/ generator) {
  3058. return GetClosureTupleFromContext(generator.Context);
  3059. }
  3060. public static MutableTuple/*!*/ GetClosureTupleFromContext(CodeContext/*!*/ context) {
  3061. return (context.Dict._storage as RuntimeVariablesDictionaryStorage).Tuple;
  3062. }
  3063. public static CodeContext/*!*/ GetParentContextFromFunction(PythonFunction/*!*/ function) {
  3064. return function.Context;
  3065. }
  3066. public static CodeContext/*!*/ GetParentContextFromGenerator(PythonGenerator/*!*/ generator) {
  3067. return generator.Context;
  3068. }
  3069. public static object GetGlobal(CodeContext/*!*/ context, string name) {
  3070. return GetVariable(context, name, true);
  3071. }
  3072. public static object GetLocal(CodeContext/*!*/ context, string name) {
  3073. return GetVariable(context, name, false);
  3074. }
  3075. private static object GetVariable(CodeContext/*!*/ context, string name, bool isGlobal) {
  3076. object res;
  3077. if (isGlobal) {
  3078. if (context.TryGetGlobalVariable(name, out res)) {
  3079. return res;
  3080. }
  3081. } else {
  3082. if (context.TryLookupName(name, out res)) {
  3083. return res;
  3084. }
  3085. }
  3086. PythonDictionary builtins = context.GetBuiltinsDict();
  3087. if (builtins != null && builtins.TryGetValue(name, out res)) {
  3088. return res;
  3089. }
  3090. if (isGlobal) {
  3091. throw GlobalNameError(name);
  3092. }
  3093. throw NameError(name);
  3094. }
  3095. public static object RawGetGlobal(CodeContext/*!*/ context, string name) {
  3096. object res;
  3097. if (context.TryGetGlobalVariable(name, out res)) {
  3098. return res;
  3099. }
  3100. return Uninitialized.Instance;
  3101. }
  3102. public static object RawGetLocal(CodeContext/*!*/ context, string name) {
  3103. object res;
  3104. if (context.TryLookupName(name, out res)) {
  3105. return res;
  3106. }
  3107. return Uninitialized.Instance;
  3108. }
  3109. public static void SetGlobal(CodeContext/*!*/ context, string name, object value) {
  3110. context.SetGlobalVariable(name, value);
  3111. }
  3112. public static void SetLocal(CodeContext/*!*/ context, string name, object value) {
  3113. context.SetVariable(name, value);
  3114. }
  3115. public static void DeleteGlobal(CodeContext/*!*/ context, string name) {
  3116. if (context.TryRemoveGlobalVariable(name)) {
  3117. return;
  3118. }
  3119. throw NameError(name);
  3120. }
  3121. public static void DeleteLocal(CodeContext/*!*/ context, string name) {
  3122. if (context.TryRemoveVariable(name)) {
  3123. return;
  3124. }
  3125. throw NameError(name);
  3126. }
  3127. public static PythonGlobal/*!*/[] GetGlobalArrayFromContext(CodeContext/*!*/ context) {
  3128. return context.GetGlobalArray();
  3129. }
  3130. #endregion
  3131. #region Exception Factories
  3132. public static Exception MultipleKeywordArgumentError(PythonFunction function, string name) {
  3133. return TypeError("{0}() got multiple values for keyword argument '{1}'", function.__name__, name);
  3134. }
  3135. public static Exception UnexpectedKeywordArgumentError(PythonFunction function, string name) {
  3136. return TypeError("{0}() got an unexpected keyword argument '{1}'", function.__name__, name);
  3137. }
  3138. public static Exception StaticAssignmentFromInstanceError(PropertyTracker tracker, bool isAssignment) {
  3139. if (isAssignment) {
  3140. if (DynamicHelpers.GetPythonTypeFromType(tracker.DeclaringType).IsPythonType) {
  3141. return PythonOps.TypeError(
  3142. "can't set attributes of built-in/extension type '{0}'",
  3143. NameConverter.GetTypeName(tracker.DeclaringType));
  3144. }
  3145. return new MissingMemberException(string.Format(
  3146. Resources.StaticAssignmentFromInstanceError,
  3147. tracker.Name,
  3148. NameConverter.GetTypeName(tracker.DeclaringType)));
  3149. }
  3150. return new MissingMemberException(string.Format(Resources.StaticAccessFromInstanceError,
  3151. tracker.Name,
  3152. NameConverter.GetTypeName(tracker.DeclaringType)));
  3153. }
  3154. public static Exception FunctionBadArgumentError(PythonFunction func, int count) {
  3155. return func.BadArgumentError(count);
  3156. }
  3157. public static Exception BadKeywordArgumentError(PythonFunction func, int count) {
  3158. return func.BadKeywordArgumentError(count);
  3159. }
  3160. public static Exception AttributeErrorForMissingOrReadonly(CodeContext/*!*/ context, PythonType dt, string name) {
  3161. PythonTypeSlot dts;
  3162. if (dt.TryResolveSlot(context, name, out dts)) {
  3163. throw PythonOps.AttributeErrorForReadonlyAttribute(dt.Name, name);
  3164. }
  3165. throw PythonOps.AttributeErrorForMissingAttribute(dt.Name, name);
  3166. }
  3167. public static Exception AttributeErrorForMissingAttribute(object o, string name) {
  3168. PythonType dt = o as PythonType;
  3169. if (dt != null)
  3170. return PythonOps.AttributeErrorForMissingAttribute(dt.Name, name);
  3171. return AttributeErrorForReadonlyAttribute(PythonTypeOps.GetName(o), name);
  3172. }
  3173. public static Exception ValueError(string format, params object[] args) {
  3174. return new ArgumentException(string.Format(format, args));
  3175. }
  3176. public static Exception KeyError(object key) {
  3177. return PythonExceptions.CreateThrowable(PythonExceptions.KeyError, key);
  3178. }
  3179. public static Exception KeyError(string format, params object[] args) {
  3180. return new KeyNotFoundException(string.Format(format, args));
  3181. }
  3182. public static Exception UnicodeDecodeError(string format, params object[] args) {
  3183. return new System.Text.DecoderFallbackException(string.Format(format, args));
  3184. }
  3185. public static Exception UnicodeEncodeError(string format, params object[] args) {
  3186. return new System.Text.EncoderFallbackException(string.Format(format, args));
  3187. }
  3188. public static Exception IOError(Exception inner) {
  3189. return new System.IO.IOException(inner.Message, inner);
  3190. }
  3191. public static Exception IOError(string format, params object[] args) {
  3192. return new System.IO.IOException(string.Format(format, args));
  3193. }
  3194. public static Exception EofError(string format, params object[] args) {
  3195. return new System.IO.EndOfStreamException(string.Format(format, args));
  3196. }
  3197. public static Exception StandardError(string format, params object[] args) {
  3198. return new SystemException(string.Format(format, args));
  3199. }
  3200. public static Exception ZeroDivisionError(string format, params object[] args) {
  3201. return new DivideByZeroException(string.Format(format, args));
  3202. }
  3203. public static Exception SystemError(string format, params object[] args) {
  3204. return new SystemException(string.Format(format, args));
  3205. }
  3206. public static Exception TypeError(string format, params object[] args) {
  3207. return new ArgumentTypeException(string.Format(format, args));
  3208. }
  3209. public static Exception IndexError(string format, params object[] args) {
  3210. return new System.IndexOutOfRangeException(string.Format(format, args));
  3211. }
  3212. public static Exception MemoryError(string format, params object[] args) {
  3213. return new OutOfMemoryException(string.Format(format, args));
  3214. }
  3215. public static Exception ArithmeticError(string format, params object[] args) {
  3216. return new ArithmeticException(string.Format(format, args));
  3217. }
  3218. public static Exception NotImplementedError(string format, params object[] args) {
  3219. return new NotImplementedException(string.Format(format, args));
  3220. }
  3221. public static Exception AttributeError(string format, params object[] args) {
  3222. return new MissingMemberException(string.Format(format, args));
  3223. }
  3224. public static Exception OverflowError(string format, params object[] args) {
  3225. return new System.OverflowException(string.Format(format, args));
  3226. }
  3227. public static Exception WindowsError(string format, params object[] args) {
  3228. #if !SILVERLIGHT // System.ComponentModel.Win32Exception
  3229. return new System.ComponentModel.Win32Exception(string.Format(format, args));
  3230. #else
  3231. return new System.SystemException(string.Format(format, args));
  3232. #endif
  3233. }
  3234. public static Exception SystemExit() {
  3235. return new SystemExitException();
  3236. }
  3237. public static void SyntaxWarning(string message, SourceUnit sourceUnit, SourceSpan span, int errorCode) {
  3238. PythonContext pc = (PythonContext)sourceUnit.LanguageContext;
  3239. CodeContext context = pc.SharedContext;
  3240. ShowWarning(context, PythonExceptions.SyntaxWarning, message, sourceUnit.Path, span.Start.Line);
  3241. }
  3242. public static SyntaxErrorException SyntaxError(string message, SourceUnit sourceUnit, SourceSpan span, int errorCode) {
  3243. switch (errorCode & ErrorCodes.ErrorMask) {
  3244. case ErrorCodes.IndentationError:
  3245. return new IndentationException(message, sourceUnit, span, errorCode, Severity.FatalError);
  3246. case ErrorCodes.TabError:
  3247. return new TabException(message, sourceUnit, span, errorCode, Severity.FatalError);
  3248. default:
  3249. var res = new SyntaxErrorException(message, sourceUnit, span, errorCode, Severity.FatalError);
  3250. if ((errorCode & ErrorCodes.NoCaret) != 0) {
  3251. res.Data[PythonContext._syntaxErrorNoCaret] = ScriptingRuntimeHelpers.True;
  3252. }
  3253. return res;
  3254. }
  3255. }
  3256. public static SyntaxErrorException BadSourceError(byte badByte, SourceSpan span, string path) {
  3257. SyntaxErrorException res = new SyntaxErrorException(
  3258. 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",
  3259. badByte,
  3260. span.Start.Line,
  3261. path
  3262. ),
  3263. path,
  3264. null,
  3265. null,
  3266. span,
  3267. ErrorCodes.SyntaxError,
  3268. Severity.FatalError
  3269. );
  3270. res.Data[PythonContext._syntaxErrorNoCaret] = ScriptingRuntimeHelpers.True;
  3271. return res;
  3272. }
  3273. public static Exception StopIteration() {
  3274. return StopIteration("");
  3275. }
  3276. public static Exception InvalidType(object o, RuntimeTypeHandle handle) {
  3277. return PythonOps.TypeErrorForTypeMismatch(DynamicHelpers.GetPythonTypeFromType(Type.GetTypeFromHandle(handle)).Name, o);
  3278. }
  3279. public static Exception ZeroDivisionError() {
  3280. return ZeroDivisionError("Attempted to divide by zero.");
  3281. }
  3282. // If you do "(a, b) = (1, 2, 3, 4)"
  3283. public static Exception ValueErrorForUnpackMismatch(int left, int right) {
  3284. System.Diagnostics.Debug.Assert(left != right);
  3285. if (left > right)
  3286. return ValueError("need more than {0} values to unpack", right);
  3287. else
  3288. return ValueError("too many values to unpack");
  3289. }
  3290. public static Exception NameError(string name) {
  3291. return new UnboundNameException(string.Format("name '{0}' is not defined", name));
  3292. }
  3293. public static Exception GlobalNameError(string name) {
  3294. return new UnboundNameException(string.Format("global name '{0}' is not defined", name));
  3295. }
  3296. // If an unbound method is called without a "self" argument, or a "self" argument of a bad type
  3297. public static Exception TypeErrorForUnboundMethodCall(string methodName, Type methodType, object instance) {
  3298. return TypeErrorForUnboundMethodCall(methodName, DynamicHelpers.GetPythonTypeFromType(methodType), instance);
  3299. }
  3300. public static Exception TypeErrorForUnboundMethodCall(string methodName, PythonType methodType, object instance) {
  3301. string message = string.Format("unbound method {0}() must be called with {1} instance as first argument (got {2} instead)",
  3302. methodName, methodType.Name, PythonTypeOps.GetName(instance));
  3303. return TypeError(message);
  3304. }
  3305. // When a generator first starts, before it gets to the first yield point, you can't call generator.Send(x) where x != null.
  3306. // See Pep342 for details.
  3307. public static Exception TypeErrorForIllegalSend() {
  3308. string message = "can't send non-None value to a just-started generator";
  3309. return TypeError(message);
  3310. }
  3311. // If a method is called with an incorrect number of arguments
  3312. // You should use TypeErrorForUnboundMethodCall() for unbound methods called with 0 arguments
  3313. public static Exception TypeErrorForArgumentCountMismatch(string methodName, int expectedArgCount, int actualArgCount) {
  3314. return TypeError("{0}() takes exactly {1} argument{2} ({3} given)",
  3315. methodName, expectedArgCount, expectedArgCount == 1 ? "" : "s", actualArgCount);
  3316. }
  3317. public static Exception TypeErrorForTypeMismatch(string expectedTypeName, object instance) {
  3318. return TypeError("expected {0}, got {1}", expectedTypeName, PythonOps.GetPythonTypeName(instance));
  3319. }
  3320. // If hash is called on an instance of an unhashable type
  3321. public static Exception TypeErrorForUnhashableType(string typeName) {
  3322. return TypeError(typeName + " objects are unhashable");
  3323. }
  3324. public static Exception TypeErrorForUnhashableObject(object obj) {
  3325. return TypeErrorForUnhashableType(PythonTypeOps.GetName(obj));
  3326. }
  3327. internal static Exception TypeErrorForIncompatibleObjectLayout(string prefix, PythonType type, Type newType) {
  3328. return TypeError("{0}: '{1}' object layout differs from '{2}'", prefix, type.Name, newType);
  3329. }
  3330. public static Exception TypeErrorForNonStringAttribute() {
  3331. return TypeError("attribute name must be string");
  3332. }
  3333. internal static Exception TypeErrorForBadInstance(string template, object instance) {
  3334. return TypeError(template, PythonOps.GetPythonTypeName(instance));
  3335. }
  3336. public static Exception TypeErrorForBinaryOp(string opSymbol, object x, object y) {
  3337. throw PythonOps.TypeError("unsupported operand type(s) for {0}: '{1}' and '{2}'",
  3338. opSymbol, GetPythonTypeName(x), GetPythonTypeName(y));
  3339. }
  3340. public static Exception TypeErrorForUnaryOp(string opSymbol, object x) {
  3341. throw PythonOps.TypeError("unsupported operand type for {0}: '{1}'",
  3342. opSymbol, GetPythonTypeName(x));
  3343. }
  3344. public static Exception TypeErrorForNonIterableObject(object o) {
  3345. return PythonOps.TypeError(
  3346. "argument of type '{0}' is not iterable",
  3347. PythonTypeOps.GetName(o)
  3348. );
  3349. }
  3350. public static Exception TypeErrorForDefaultArgument(string message) {
  3351. return PythonOps.TypeError(message);
  3352. }
  3353. public static Exception AttributeErrorForReadonlyAttribute(string typeName, string attributeName) {
  3354. // CPython uses AttributeError for all attributes except "__class__"
  3355. if (attributeName == "__class__")
  3356. return PythonOps.TypeError("can't delete __class__ attribute");
  3357. return PythonOps.AttributeError("attribute '{0}' of '{1}' object is read-only", attributeName, typeName);
  3358. }
  3359. public static Exception AttributeErrorForBuiltinAttributeDeletion(string typeName, string attributeName) {
  3360. return PythonOps.AttributeError("cannot delete attribute '{0}' of builtin type '{1}'", attributeName, typeName);
  3361. }
  3362. public static Exception MissingInvokeMethodException(object o, string name) {
  3363. if (o is OldClass) {
  3364. throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'",
  3365. ((OldClass)o).Name, name);
  3366. } else {
  3367. throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", GetPythonTypeName(o), name);
  3368. }
  3369. }
  3370. /// <summary>
  3371. /// Create at TypeError exception for when Raise() can't create the exception requested.
  3372. /// </summary>
  3373. /// <param name="type">original type of exception requested</param>
  3374. /// <returns>a TypeEror exception</returns>
  3375. internal static Exception MakeExceptionTypeError(object type) {
  3376. return PythonOps.TypeError("exceptions must be classes or instances, not {0}", PythonTypeOps.GetName(type));
  3377. }
  3378. public static Exception AttributeErrorForObjectMissingAttribute(object obj, string attributeName) {
  3379. if (obj is OldInstance) {
  3380. return AttributeErrorForOldInstanceMissingAttribute(((OldInstance)obj)._class.Name, attributeName);
  3381. } else if (obj is OldClass) {
  3382. return AttributeErrorForOldClassMissingAttribute(((OldClass)obj).Name, attributeName);
  3383. } else {
  3384. return AttributeErrorForMissingAttribute(PythonTypeOps.GetName(obj), attributeName);
  3385. }
  3386. }
  3387. public static Exception AttributeErrorForMissingAttribute(string typeName, string attributeName) {
  3388. return PythonOps.AttributeError("'{0}' object has no attribute '{1}'", typeName, attributeName);
  3389. }
  3390. public static Exception AttributeErrorForOldInstanceMissingAttribute(string typeName, string attributeName) {
  3391. return PythonOps.AttributeError("{0} instance has no attribute '{1}'", typeName, attributeName);
  3392. }
  3393. public static Exception AttributeErrorForOldClassMissingAttribute(string typeName, string attributeName) {
  3394. return PythonOps.AttributeError("class {0} has no attribute '{1}'", typeName, attributeName);
  3395. }
  3396. public static Exception UncallableError(object func) {
  3397. return PythonOps.TypeError("{0} is not callable", PythonTypeOps.GetName(func));
  3398. }
  3399. public static Exception TypeErrorForProtectedMember(Type/*!*/ type, string/*!*/ name) {
  3400. return PythonOps.TypeError("cannot access protected member {0} without a python subclass of {1}", name, NameConverter.GetTypeName(type));
  3401. }
  3402. public static Exception TypeErrorForGenericMethod(Type/*!*/ type, string/*!*/ name) {
  3403. return PythonOps.TypeError("{0}.{1} is a generic method and must be indexed with types before calling", NameConverter.GetTypeName(type), name);
  3404. }
  3405. public static Exception TypeErrorForUnIndexableObject(object o) {
  3406. IPythonObject ipo;
  3407. if (o == null) {
  3408. return PythonOps.TypeError("'NoneType' object cannot be interpreted as an index");
  3409. } else if ((ipo = o as IPythonObject) != null) {
  3410. return TypeError("'{0}' object cannot be interpreted as an index", ipo.PythonType.Name);
  3411. }
  3412. return TypeError("object cannot be interpreted as an index");
  3413. }
  3414. [Obsolete("no longer used anywhere")]
  3415. public static Exception/*!*/ TypeErrorForBadDictionaryArgument(PythonFunction/*!*/ f) {
  3416. return PythonOps.TypeError("{0}() argument after ** must be a dictionary", f.__name__);
  3417. }
  3418. public static T TypeErrorForBadEnumConversion<T>(object value) {
  3419. throw TypeError("Cannot convert numeric value {0} to {1}. The value must be zero.", value, NameConverter.GetTypeName(typeof(T)));
  3420. }
  3421. public static Exception/*!*/ UnreadableProperty() {
  3422. return PythonOps.AttributeError("unreadable attribute");
  3423. }
  3424. public static Exception/*!*/ UnsetableProperty() {
  3425. return PythonOps.AttributeError("readonly attribute");
  3426. }
  3427. public static Exception/*!*/ UndeletableProperty() {
  3428. return PythonOps.AttributeError("undeletable attribute");
  3429. }
  3430. public static Exception Warning(string format, params object[] args) {
  3431. return new WarningException(string.Format(format, args));
  3432. }
  3433. #endregion
  3434. [ThreadStatic]
  3435. private static List<FunctionStack> _funcStack;
  3436. public static List<FunctionStack> GetFunctionStack() {
  3437. return _funcStack ?? (_funcStack = new List<FunctionStack>());
  3438. }
  3439. public static List<FunctionStack> GetFunctionStackNoCreate() {
  3440. return _funcStack;
  3441. }
  3442. public static List<FunctionStack> PushFrame(CodeContext context, FunctionCode function) {
  3443. List<FunctionStack> stack = GetFunctionStack();
  3444. stack.Add(new FunctionStack(context, function));
  3445. return stack;
  3446. }
  3447. internal static LambdaExpression ToGenerator(this LambdaExpression code, bool shouldInterpret, bool debuggable, int compilationThreshold) {
  3448. return Expression.Lambda(
  3449. code.Type,
  3450. new GeneratorRewriter(code.Name, code.Body).Reduce(shouldInterpret, debuggable, compilationThreshold, code.Parameters, x => x),
  3451. code.Name,
  3452. code.Parameters
  3453. );
  3454. }
  3455. public static void UpdateStackTrace(CodeContext context, FunctionCode funcCode, MethodBase method, string funcName, string filename, int line) {
  3456. if (line != -1) {
  3457. Debug.Assert(filename != null);
  3458. if (ExceptionHelpers.DynamicStackFrames == null) {
  3459. ExceptionHelpers.DynamicStackFrames = new List<DynamicStackFrame>();
  3460. }
  3461. Debug.Assert(line != SourceLocation.None.Line);
  3462. ExceptionHelpers.DynamicStackFrames.Add(new PythonDynamicStackFrame(context, funcCode, method, funcName, filename, line));
  3463. }
  3464. }
  3465. public static byte[] ConvertBufferToByteArray(PythonBuffer buffer) {
  3466. return buffer.ToString().MakeByteArray();
  3467. }
  3468. public static bool ModuleTryGetMember(CodeContext context, PythonModule module, string name, out object res) {
  3469. object value = module.GetAttributeNoThrow(context, name);
  3470. if (value != OperationFailed.Value) {
  3471. res = value;
  3472. return true;
  3473. }
  3474. res = null;
  3475. return false;
  3476. }
  3477. internal static void ScopeSetMember(CodeContext context, Scope scope, string name, object value) {
  3478. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3479. if (scopeStorage != null) {
  3480. scopeStorage.SetValue(name, false, value);
  3481. return;
  3482. }
  3483. PythonOps.SetAttr(context, scope, name, value);
  3484. }
  3485. internal static object ScopeGetMember(CodeContext context, Scope scope, string name) {
  3486. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3487. if (scopeStorage != null) {
  3488. return scopeStorage.GetValue(name, false);
  3489. }
  3490. return PythonOps.GetBoundAttr(context, scope, name);
  3491. }
  3492. internal static bool ScopeTryGetMember(CodeContext context, Scope scope, string name, out object value) {
  3493. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3494. if (scopeStorage != null) {
  3495. return scopeStorage.TryGetValue(name, false, out value);
  3496. }
  3497. return PythonOps.TryGetBoundAttr(context, scope, name, out value);
  3498. }
  3499. internal static bool ScopeContainsMember(CodeContext context, Scope scope, string name) {
  3500. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3501. if (scopeStorage != null) {
  3502. return scopeStorage.HasValue(name, false);
  3503. }
  3504. return PythonOps.HasAttr(context, scope, name);
  3505. }
  3506. internal static bool ScopeDeleteMember(CodeContext context, Scope scope, string name) {
  3507. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3508. if (scopeStorage != null) {
  3509. return scopeStorage.DeleteValue(name, false);
  3510. }
  3511. bool res = PythonOps.HasAttr(context, scope, name);
  3512. PythonOps.DeleteAttr(context, scope, name);
  3513. return res;
  3514. }
  3515. internal static IList<object> ScopeGetMemberNames(CodeContext context, Scope scope) {
  3516. ScopeStorage scopeStorage = ((object)scope.Storage) as ScopeStorage;
  3517. if (scopeStorage != null) {
  3518. List<object> res = new List<object>();
  3519. foreach (string name in scopeStorage.GetMemberNames()) {
  3520. res.Add(name);
  3521. }
  3522. var objKeys = ((PythonScopeExtension)context.LanguageContext.EnsureScopeExtension(scope)).ObjectKeys;
  3523. if (objKeys != null) {
  3524. foreach (object o in objKeys.Keys) {
  3525. res.Add(o);
  3526. }
  3527. }
  3528. return res;
  3529. }
  3530. return PythonOps.GetAttrNames(context, scope);
  3531. }
  3532. public static bool IsUnicode(object unicodeObj) {
  3533. return unicodeObj == TypeCache.String;
  3534. }
  3535. }
  3536. /// <summary>
  3537. /// Helper clas for calls to unicode(...). We generate code which checks if unicode
  3538. /// is str and if it is we redirect those calls to the unicode function defined on this
  3539. /// class.
  3540. /// </summary>
  3541. public class UnicodeHelper {
  3542. internal static BuiltinFunction Function = BuiltinFunction.MakeFunction("unicode",
  3543. ArrayUtils.ConvertAll(
  3544. typeof(UnicodeHelper).GetMember("unicode"),
  3545. x => (MethodInfo)x
  3546. ),
  3547. typeof(string)
  3548. );
  3549. public static object unicode(CodeContext context) {
  3550. return String.Empty;
  3551. }
  3552. public static object unicode(CodeContext context, object @string) {
  3553. return StringOps.FastNewUnicode(context, @string);
  3554. }
  3555. public static object unicode(CodeContext context, object @string, object encoding) {
  3556. return StringOps.FastNewUnicode(context, @string, encoding);
  3557. }
  3558. public static object unicode(CodeContext context, object @string, [Optional]object encoding, object errors) {
  3559. return StringOps.FastNewUnicode(context, @string, encoding, errors);
  3560. }
  3561. }
  3562. public struct FunctionStack {
  3563. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
  3564. public readonly CodeContext/*!*/ Context;
  3565. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
  3566. public readonly FunctionCode/*!*/ Code;
  3567. public TraceBackFrame Frame;
  3568. internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code) {
  3569. Assert.NotNull(context, code);
  3570. Context = context;
  3571. Code = code;
  3572. Frame = null;
  3573. }
  3574. internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code, TraceBackFrame frame) {
  3575. Assert.NotNull(context, code);
  3576. Context = context;
  3577. Code = code;
  3578. Frame = frame;
  3579. }
  3580. internal FunctionStack(TraceBackFrame frame) {
  3581. Context = frame.Context;
  3582. Code = frame.f_code;
  3583. Frame = frame;
  3584. }
  3585. }
  3586. }