PageRenderTime 88ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/Languages/IronPython/IronPython/Runtime/Operations/PythonOps.cs

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