PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/IronPython_2_6/Src/IronPython/Modules/Builtin.cs

#
C# | 2156 lines | 1718 code | 350 blank | 88 comment | 459 complexity | 4fce4066cdf24083a6396592bb535c7e MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0

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

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Microsoft Public License. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Microsoft Public License, please send an email to
  8. * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Microsoft Public License.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.IO;
  20. using System.Runtime.CompilerServices;
  21. using System.Runtime.InteropServices;
  22. using System.Text;
  23. using System.Threading;
  24. using Microsoft.Scripting;
  25. using Microsoft.Scripting.Actions;
  26. using Microsoft.Scripting.Runtime;
  27. using Microsoft.Scripting.Utils;
  28. using IronPython.Compiler;
  29. using IronPython.Runtime;
  30. using IronPython.Runtime.Binding;
  31. using IronPython.Runtime.Exceptions;
  32. using IronPython.Runtime.Operations;
  33. using IronPython.Runtime.Types;
  34. #if CLR2
  35. using Microsoft.Scripting.Math;
  36. using Complex = Microsoft.Scripting.Math.Complex64;
  37. #else
  38. using System.Numerics;
  39. #endif
  40. [assembly: PythonModule("__builtin__", typeof(IronPython.Modules.Builtin))]
  41. namespace IronPython.Modules {
  42. [Documentation("")] // Documentation suppresses XML Doc on startup.
  43. public static partial class Builtin {
  44. public const string __doc__ = "Provides access to commonly used built-in functions, exception objects, etc...";
  45. public const object __package__ = null;
  46. public const string __name__ = "__builtin__";
  47. public static object True {
  48. get {
  49. return ScriptingRuntimeHelpers.True;
  50. }
  51. }
  52. public static object False {
  53. get {
  54. return ScriptingRuntimeHelpers.False;
  55. }
  56. }
  57. // This will always stay null
  58. public static readonly object None;
  59. public static IronPython.Runtime.Types.Ellipsis Ellipsis {
  60. get {
  61. return IronPython.Runtime.Types.Ellipsis.Value;
  62. }
  63. }
  64. public static NotImplementedType NotImplemented {
  65. get {
  66. return NotImplementedType.Value;
  67. }
  68. }
  69. public static object exit {
  70. get {
  71. return "Use Ctrl-Z plus Return to exit";
  72. }
  73. }
  74. public static object quit {
  75. get {
  76. return "Use Ctrl-Z plus Return to exit";
  77. }
  78. }
  79. [Documentation("__import__(name) -> module\n\nImport a module.")]
  80. public static object __import__(CodeContext/*!*/ context, string name) {
  81. return __import__(context, name, null, null, null, -1);
  82. }
  83. [Documentation("__import__(name, globals, locals, fromlist, level) -> module\n\nImport a module.")]
  84. public static object __import__(CodeContext/*!*/ context, string name, [DefaultParameterValue(null)]object globals, [DefaultParameterValue(null)]object locals, [DefaultParameterValue(null)]object fromlist, [DefaultParameterValue(-1)]int level) {
  85. if (fromlist is string || fromlist is Extensible<string>) {
  86. fromlist = new List<object> { fromlist };
  87. }
  88. IList from = fromlist as IList;
  89. PythonContext pc = PythonContext.GetContext(context);
  90. object ret = Importer.ImportModule(context, globals, name, from != null && from.Count > 0, level);
  91. if (ret == null) {
  92. throw PythonOps.ImportError("No module named {0}", name);
  93. }
  94. PythonModule mod = ret as PythonModule;
  95. if (mod != null && from != null) {
  96. string strAttrName;
  97. for (int i = 0; i < from.Count; i++) {
  98. object attrName = from[i];
  99. if (pc.TryConvertToString(attrName, out strAttrName) &&
  100. !String.IsNullOrEmpty(strAttrName) &&
  101. strAttrName != "*") {
  102. try {
  103. Importer.ImportFrom(context, mod, strAttrName);
  104. } catch (ImportException) {
  105. continue;
  106. }
  107. }
  108. }
  109. }
  110. return ret;
  111. }
  112. [Documentation("abs(number) -> number\n\nReturn the absolute value of the argument.")]
  113. public static object abs(CodeContext/*!*/ context, object o) {
  114. if (o is int) return Int32Ops.Abs((int)o);
  115. if (o is long) return Int64Ops.Abs((long)o);
  116. if (o is double) return DoubleOps.Abs((double)o);
  117. if (o is bool) return (((bool)o) ? 1 : 0);
  118. if (o is BigInteger) return BigIntegerOps.__abs__((BigInteger)o);
  119. if (o is Complex) return ComplexOps.Abs((Complex)o);
  120. object value;
  121. if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__abs__", out value)) {
  122. return value;
  123. }
  124. throw PythonOps.TypeError("bad operand type for abs(): '{0}'", PythonTypeOps.GetName(o));
  125. }
  126. public static bool all(object x) {
  127. IEnumerator i = PythonOps.GetEnumerator(x);
  128. while (i.MoveNext()) {
  129. if (!PythonOps.IsTrue(i.Current)) return false;
  130. }
  131. return true;
  132. }
  133. public static bool any(object x) {
  134. IEnumerator i = PythonOps.GetEnumerator(x);
  135. while (i.MoveNext()) {
  136. if (PythonOps.IsTrue(i.Current)) return true;
  137. }
  138. return false;
  139. }
  140. [Documentation("apply(object[, args[, kwargs]]) -> value\n\nDeprecated.\nInstead, use:\n function(*args, **keywords).")]
  141. public static object apply(CodeContext/*!*/ context, object func) {
  142. return PythonOps.CallWithContext(context, func);
  143. }
  144. public static object apply(CodeContext/*!*/ context, object func, object args) {
  145. return PythonOps.CallWithArgsTupleAndContext(context, func, ArrayUtils.EmptyObjects, args);
  146. }
  147. public static object apply(CodeContext/*!*/ context, object func, object args, object kws) {
  148. return context.LanguageContext.CallWithKeywords(func, args, kws);
  149. }
  150. public static PythonType basestring {
  151. get {
  152. return DynamicHelpers.GetPythonTypeFromType(typeof(string));
  153. }
  154. }
  155. public static string bin(int number) {
  156. return Int32Ops.ToBinary(number);
  157. }
  158. public static string bin(Index number) {
  159. return Int32Ops.ToBinary(Converter.ConvertToIndex(number));
  160. }
  161. public static string bin(BigInteger number) {
  162. return BigIntegerOps.ToBinary(number);
  163. }
  164. public static string bin(double number) {
  165. throw PythonOps.TypeError("'float' object cannot be interpreted as an index");
  166. }
  167. public static PythonType @bool {
  168. get {
  169. return DynamicHelpers.GetPythonTypeFromType(typeof(bool));
  170. }
  171. }
  172. public static PythonType buffer {
  173. get {
  174. return DynamicHelpers.GetPythonTypeFromType(typeof(PythonBuffer));
  175. }
  176. }
  177. public static PythonType bytes {
  178. get {
  179. return DynamicHelpers.GetPythonTypeFromType(typeof(Bytes));
  180. }
  181. }
  182. public static PythonType bytearray {
  183. get {
  184. return DynamicHelpers.GetPythonTypeFromType(typeof(ByteArray));
  185. }
  186. }
  187. [Documentation("callable(object) -> bool\n\nReturn whether the object is callable (i.e., some kind of function).")]
  188. [Python3Warning("callable() is removed in 3.x. instead call hasattr(obj, '__call__')")]
  189. public static bool callable(CodeContext/*!*/ context, object o) {
  190. return PythonOps.IsCallable(context, o);
  191. }
  192. [Documentation("chr(i) -> character\n\nReturn a string of one character with ordinal i; 0 <= i< 256.")]
  193. public static string chr(int value) {
  194. if (value < 0 || value > 0xFF) {
  195. throw PythonOps.ValueError("{0} is not in required range", value);
  196. }
  197. return ScriptingRuntimeHelpers.CharToString((char)value);
  198. }
  199. internal static object TryCoerce(CodeContext/*!*/ context, object x, object y) {
  200. PythonTypeSlot pts;
  201. PythonType xType = DynamicHelpers.GetPythonType(x);
  202. if (xType.TryResolveSlot(context, "__coerce__", out pts)) {
  203. object callable;
  204. if (pts.TryGetValue(context, x, xType, out callable)) {
  205. return PythonCalls.Call(context, callable, y);
  206. }
  207. }
  208. return NotImplementedType.Value;
  209. }
  210. [Documentation("coerce(x, y) -> (x1, y1)\n\nReturn a tuple consisting of the two numeric arguments converted to\na common type. If coercion is not possible, raise TypeError.")]
  211. public static object coerce(CodeContext/*!*/ context, object x, object y) {
  212. object converted;
  213. if (x == null && y == null) {
  214. return PythonTuple.MakeTuple(null, null);
  215. }
  216. converted = TryCoerce(context, x, y);
  217. if (converted != null && converted != NotImplementedType.Value) {
  218. return converted;
  219. }
  220. converted = TryCoerce(context, y, x);
  221. if (converted != null && converted != NotImplementedType.Value) {
  222. PythonTuple pt = converted as PythonTuple;
  223. if (pt != null && pt.Count == 2) {
  224. return PythonTuple.MakeTuple(pt[1], pt[0]);
  225. }
  226. }
  227. throw PythonOps.TypeError("coercion failed");
  228. }
  229. [Documentation("compile a unit of source code.\n\nThe source can be compiled either as exec, eval, or single.\nexec compiles the code as if it were a file\neval compiles the code as if were an expression\nsingle compiles a single statement\n\n")]
  230. public static object compile(CodeContext/*!*/ context, string source, string filename, string mode, [DefaultParameterValue(null)]object flags, [DefaultParameterValue(null)]object dont_inherit) {
  231. if (source.IndexOf('\0') != -1) {
  232. throw PythonOps.TypeError("compile() expected string without null bytes");
  233. }
  234. source = RemoveBom(source);
  235. bool inheritContext = GetCompilerInheritance(dont_inherit);
  236. CompileFlags cflags = GetCompilerFlags(flags);
  237. PythonCompilerOptions opts = GetRuntimeGeneratedCodeCompilerOptions(context, inheritContext, cflags);
  238. if ((cflags & CompileFlags.CO_DONT_IMPLY_DEDENT) != 0) {
  239. opts.DontImplyDedent = true;
  240. }
  241. SourceUnit sourceUnit;
  242. string unitPath = String.IsNullOrEmpty(filename) ? null : filename;
  243. switch (mode) {
  244. case "exec": sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.Statements); break;
  245. case "eval": sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.Expression); break;
  246. case "single": sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.InteractiveCode); break;
  247. default:
  248. throw PythonOps.ValueError("compile() arg 3 must be 'exec' or 'eval' or 'single'");
  249. }
  250. return FunctionCode.FromSourceUnit(sourceUnit, opts);
  251. }
  252. private static string RemoveBom(string source) {
  253. // skip BOM (TODO: this is ugly workaround that is in fact not strictly correct, we need binary strings to handle it correctly)
  254. if (source.StartsWith("\u00ef\u00bb\u00bf")) {
  255. source = source.Substring(3, source.Length - 3);
  256. }
  257. return source;
  258. }
  259. public static PythonType classmethod {
  260. get {
  261. return DynamicHelpers.GetPythonTypeFromType(typeof(classmethod));
  262. }
  263. }
  264. public static int cmp(CodeContext/*!*/ context, object x, object y) {
  265. return PythonOps.Compare(context, x, y);
  266. }
  267. // having a cmp overload for double would be nice, but it breaks:
  268. // x = 1e66666
  269. // y = x/x
  270. // cmp(y,y)
  271. // which returns 0 because id(y) == id(y). If we added a double overload
  272. // we lose object identity.
  273. public static int cmp(CodeContext/*!*/ context, int x, int y) {
  274. return Int32Ops.Compare(x, y);
  275. }
  276. public static int cmp(CodeContext/*!*/ context, [NotNull]BigInteger x, [NotNull]BigInteger y) {
  277. if ((object)x == (object)y) {
  278. return 0;
  279. }
  280. return BigIntegerOps.Compare(x, y);
  281. }
  282. public static int cmp(CodeContext/*!*/ context, double x, [NotNull]BigInteger y) {
  283. return -BigIntegerOps.Compare(y, x);
  284. }
  285. public static int cmp(CodeContext/*!*/ context, [NotNull]BigInteger x, double y) {
  286. return BigIntegerOps.Compare(x, y);
  287. }
  288. public static int cmp(CodeContext/*!*/ context, [NotNull]string x, [NotNull]string y) {
  289. if ((object)x != (object)y) {
  290. int res = string.CompareOrdinal(x, y);
  291. if (res >= 1) {
  292. return 1;
  293. } else if (res <= -1) {
  294. return -1;
  295. }
  296. }
  297. return 0;
  298. }
  299. public static int cmp(CodeContext/*!*/ context, [NotNull]PythonTuple x, [NotNull]PythonTuple y) {
  300. if ((object)x == (object)y) {
  301. return 0;
  302. }
  303. return x.CompareTo(y);
  304. }
  305. public static PythonType complex {
  306. get {
  307. return DynamicHelpers.GetPythonTypeFromType(typeof(Complex));
  308. }
  309. }
  310. public static void delattr(CodeContext/*!*/ context, object o, string name) {
  311. PythonOps.DeleteAttr(context, o, name);
  312. }
  313. public static PythonType dict {
  314. get {
  315. return DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary));
  316. }
  317. }
  318. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
  319. public static List dir(CodeContext/*!*/ context) {
  320. List res = PythonOps.MakeListFromSequence(context.Dict.Keys);
  321. res.sort(context);
  322. return res;
  323. }
  324. public static List dir(CodeContext/*!*/ context, object o) {
  325. IList<object> ret = PythonOps.GetAttrNames(context, o);
  326. List lret = new List(ret);
  327. lret.sort(context);
  328. return lret;
  329. }
  330. public static object divmod(CodeContext/*!*/ context, object x, object y) {
  331. Debug.Assert(NotImplementedType.Value != null);
  332. return PythonContext.GetContext(context).DivMod(x, y);
  333. }
  334. public static PythonType enumerate {
  335. get {
  336. return DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate));
  337. }
  338. }
  339. public static object eval(CodeContext/*!*/ context, FunctionCode code) {
  340. Debug.Assert(context != null);
  341. if (code == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
  342. return eval(context, code, null);
  343. }
  344. public static object eval(CodeContext/*!*/ context, FunctionCode code, PythonDictionary globals) {
  345. Debug.Assert(context != null);
  346. if (code == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
  347. return eval(context, code, globals, globals);
  348. }
  349. public static object eval(CodeContext/*!*/ context, FunctionCode code, PythonDictionary globals, object locals) {
  350. Debug.Assert(context != null);
  351. if (code == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
  352. return code.Call(GetExecEvalScopeOptional(context, globals, locals, false));
  353. }
  354. internal static PythonDictionary GetAttrLocals(CodeContext/*!*/ context, object locals) {
  355. PythonDictionary attrLocals = null;
  356. if (locals == null) {
  357. if (context.IsTopLevel) {
  358. attrLocals = context.Dict;
  359. }
  360. } else {
  361. attrLocals = locals as PythonDictionary ?? new PythonDictionary(new ObjectAttributesAdapter(context, locals));
  362. }
  363. return attrLocals;
  364. }
  365. public static object eval(CodeContext/*!*/ context, string expression) {
  366. Debug.Assert(context != null);
  367. if (expression == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
  368. return eval(context, expression, globals(context), locals(context));
  369. }
  370. public static object eval(CodeContext/*!*/ context, string expression, PythonDictionary globals) {
  371. Debug.Assert(context != null);
  372. if (expression == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
  373. return eval(context, expression, globals, globals);
  374. }
  375. public static object eval(CodeContext/*!*/ context, string expression, PythonDictionary globals, object locals) {
  376. Debug.Assert(context != null);
  377. if (expression == null) throw PythonOps.TypeError("eval() argument 1 must be string or code object");
  378. if (locals != null && PythonOps.IsMappingType(context, locals) == ScriptingRuntimeHelpers.False) {
  379. throw PythonOps.TypeError("locals must be mapping");
  380. }
  381. expression = RemoveBom(expression);
  382. var scope = GetExecEvalScopeOptional(context, globals, locals, false);
  383. var pythonContext = PythonContext.GetContext(context);
  384. // TODO: remove TrimStart
  385. var sourceUnit = pythonContext.CreateSnippet(expression.TrimStart(' ', '\t'), SourceCodeKind.Expression);
  386. var compilerOptions = GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
  387. var code = FunctionCode.FromSourceUnit(sourceUnit, compilerOptions);
  388. return code.Call(scope);
  389. }
  390. public static void execfile(CodeContext/*!*/ context, object/*!*/ filename) {
  391. execfile(context, filename, null, null);
  392. }
  393. public static void execfile(CodeContext/*!*/ context, object/*!*/ filename, object globals) {
  394. execfile(context, filename, globals, null);
  395. }
  396. public static void execfile(CodeContext/*!*/ context, object/*!*/ filename, object globals, object locals) {
  397. if (filename == null) {
  398. throw PythonOps.TypeError("execfile() argument 1 must be string, not None");
  399. }
  400. PythonDictionary g = globals as PythonDictionary;
  401. if (g == null && globals != null) {
  402. throw PythonOps.TypeError("execfile() arg 2 must be dictionary");
  403. }
  404. PythonDictionary l = locals as PythonDictionary;
  405. if (l == null && locals != null) {
  406. throw PythonOps.TypeError("execfile() arg 3 must be dictionary");
  407. }
  408. if (l == null) {
  409. l = g;
  410. }
  411. var execScope = GetExecEvalScopeOptional(context, g, l, true);
  412. string path = Converter.ConvertToString(filename);
  413. PythonContext pc = PythonContext.GetContext(context);
  414. if (!pc.DomainManager.Platform.FileExists(path)) {
  415. throw PythonOps.IOError("execfile: specified file doesn't exist");
  416. }
  417. SourceUnit sourceUnit = pc.CreateFileUnit(path, pc.DefaultEncoding, SourceCodeKind.Statements);
  418. FunctionCode code;
  419. var options = GetRuntimeGeneratedCodeCompilerOptions(context, true, 0);
  420. //always generate an unoptimized module since we run these against a dictionary namespace
  421. options.Module &= ~ModuleOptions.Optimized;
  422. try {
  423. code = FunctionCode.FromSourceUnit(sourceUnit, options);
  424. } catch (UnauthorizedAccessException x) {
  425. throw PythonOps.IOError(x);
  426. }
  427. // Do not attempt evaluation mode for execfile
  428. code.Call(execScope);
  429. }
  430. public static PythonType file {
  431. get {
  432. return DynamicHelpers.GetPythonTypeFromType(typeof(PythonFile));
  433. }
  434. }
  435. public static string filter(CodeContext/*!*/ context, object function, [NotNull]string list) {
  436. if (function == null) return list;
  437. if (list == null) throw PythonOps.TypeError("NoneType is not iterable");
  438. StringBuilder sb = new StringBuilder();
  439. foreach (char c in list) {
  440. if (PythonOps.IsTrue(PythonCalls.Call(context, function, ScriptingRuntimeHelpers.CharToString(c)))) sb.Append(c);
  441. }
  442. return sb.ToString();
  443. }
  444. public static string filter(CodeContext/*!*/ context, object function, [NotNull]ExtensibleString list) {
  445. StringBuilder sb = new StringBuilder();
  446. IEnumerator e = PythonOps.GetEnumerator(list);
  447. while (e.MoveNext()) {
  448. object o = e.Current;
  449. object t = (function != null) ? PythonCalls.Call(context, function, o) : o;
  450. if (PythonOps.IsTrue(t)) {
  451. sb.Append(Converter.ConvertToString(o));
  452. }
  453. }
  454. return sb.ToString();
  455. }
  456. /// <summary>
  457. /// Specialized version because enumerating tuples by Python's definition
  458. /// doesn't call __getitem__, but filter does!
  459. /// </summary>
  460. public static PythonTuple filter(CodeContext/*!*/ context, object function, [NotNull]PythonTuple tuple) {
  461. List<object> res = new List<object>(tuple.__len__());
  462. for (int i = 0; i < tuple.__len__(); i++) {
  463. object obj = tuple[i];
  464. object t = (function != null) ? PythonCalls.Call(context, function, obj) : obj;
  465. if (PythonOps.IsTrue(t)) {
  466. res.Add(obj);
  467. }
  468. }
  469. return PythonTuple.MakeTuple(res.ToArray());
  470. }
  471. public static List filter(CodeContext/*!*/ context, object function, object list) {
  472. if (list == null) throw PythonOps.TypeError("NoneType is not iterable");
  473. List ret = new List();
  474. IEnumerator i = PythonOps.GetEnumerator(list);
  475. while (i.MoveNext()) {
  476. if (function == null) {
  477. if (PythonOps.IsTrue(i.Current)) ret.AddNoLock(i.Current);
  478. } else {
  479. if (PythonOps.IsTrue(PythonCalls.Call(context, function, i.Current))) ret.AddNoLock(i.Current);
  480. }
  481. }
  482. return ret;
  483. }
  484. public static PythonType @float {
  485. get {
  486. return DynamicHelpers.GetPythonTypeFromType(typeof(double));
  487. }
  488. }
  489. public static string format(CodeContext/*!*/ context, object argValue, [DefaultParameterValue("")]string formatSpec) {
  490. object res, formatMethod;
  491. OldInstance oi = argValue as OldInstance;
  492. if (oi != null && oi.TryGetBoundCustomMember(context, "__format__", out formatMethod)) {
  493. res = PythonOps.CallWithContext(context, formatMethod, formatSpec);
  494. } else {
  495. // call __format__ with the format spec (__format__ is defined on object, so this always succeeds)
  496. PythonTypeOps.TryInvokeBinaryOperator(
  497. context,
  498. argValue,
  499. formatSpec,
  500. "__format__",
  501. out res);
  502. }
  503. string strRes = res as string;
  504. if (strRes == null) {
  505. throw PythonOps.TypeError("{0}.__format__ must return string or unicode, not {1}", PythonTypeOps.GetName(argValue), PythonTypeOps.GetName(res));
  506. }
  507. return strRes;
  508. }
  509. public static object getattr(CodeContext/*!*/ context, object o, string name) {
  510. return PythonOps.GetBoundAttr(context, o, name);
  511. }
  512. public static object getattr(CodeContext/*!*/ context, object o, string name, object def) {
  513. object ret;
  514. if (PythonOps.TryGetBoundAttr(context, o, name, out ret)) return ret;
  515. else return def;
  516. }
  517. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
  518. public static PythonDictionary globals(CodeContext/*!*/ context) {
  519. return context.ModuleContext.Globals;
  520. }
  521. public static bool hasattr(CodeContext/*!*/ context, object o, string name) {
  522. return PythonOps.HasAttr(context, o, name);
  523. }
  524. public static int hash(CodeContext/*!*/ context, object o) {
  525. return PythonContext.Hash(o);
  526. }
  527. public static int hash(CodeContext/*!*/ context, [NotNull]PythonTuple o) {
  528. return ((IStructuralEquatable)o).GetHashCode(PythonContext.GetContext(context).EqualityComparerNonGeneric);
  529. }
  530. // this is necessary because overload resolution selects the int form.
  531. public static int hash(CodeContext/*!*/ context, char o) {
  532. return PythonContext.Hash(o);
  533. }
  534. public static int hash(CodeContext/*!*/ context, int o) {
  535. return o;
  536. }
  537. public static int hash(CodeContext/*!*/ context, [NotNull]string o) {
  538. return o.GetHashCode();
  539. }
  540. // this is necessary because overload resolution will coerce extensible strings to strings.
  541. public static int hash(CodeContext/*!*/ context, [NotNull]ExtensibleString o) {
  542. return hash(context, (object)o);
  543. }
  544. public static int hash(CodeContext/*!*/ context, [NotNull]BigInteger o) {
  545. return BigIntegerOps.__hash__(o);
  546. }
  547. public static int hash(CodeContext/*!*/ context, [NotNull]Extensible<BigInteger> o) {
  548. return hash(context, (object)o);
  549. }
  550. public static int hash(CodeContext/*!*/ context, double o) {
  551. return DoubleOps.__hash__(o);
  552. }
  553. public static void help(CodeContext/*!*/ context, object o) {
  554. StringBuilder doc = new StringBuilder();
  555. List<object> doced = new List<object>(); // document things only once
  556. help(context, doced, doc, 0, o);
  557. if (doc.Length == 0) {
  558. if (!(o is string)) {
  559. help(context, DynamicHelpers.GetPythonType(o));
  560. return;
  561. }
  562. doc.Append("no documentation found for ");
  563. doc.Append(PythonOps.Repr(context, o));
  564. }
  565. string[] strings = doc.ToString().Split('\n');
  566. for (int i = 0; i < strings.Length; i++) {
  567. /* should read only a key, not a line, but we don't seem
  568. * to have a way to do that...
  569. if ((i % Console.WindowHeight) == 0) {
  570. Ops.Print(context.SystemState, "-- More --");
  571. Ops.ReadLineFromSrc(context.SystemState);
  572. }*/
  573. PythonOps.Print(context, strings[i]);
  574. }
  575. }
  576. private static void help(CodeContext/*!*/ context, List<object>/*!*/ doced, StringBuilder/*!*/ doc, int indent, object obj) {
  577. PythonType type;
  578. BuiltinFunction builtinFunction;
  579. PythonFunction function;
  580. BuiltinMethodDescriptor methodDesc;
  581. Method method;
  582. string strVal;
  583. PythonModule pyModule;
  584. OldClass oldClass;
  585. if (doced.Contains(obj)) return; // document things only once
  586. doced.Add(obj);
  587. if ((strVal = obj as string) != null) {
  588. if (indent != 0) return;
  589. // try and find things that string could refer to,
  590. // then call help on them.
  591. foreach (object module in PythonContext.GetContext(context).SystemStateModules.Values) {
  592. IList<object> attrs = PythonOps.GetAttrNames(context, module);
  593. List candidates = new List();
  594. foreach (string s in attrs) {
  595. if (s == strVal) {
  596. object modVal;
  597. if (!PythonOps.TryGetBoundAttr(context, module, strVal, out modVal))
  598. continue;
  599. candidates.append(modVal);
  600. }
  601. }
  602. // favor types, then built-in functions, then python functions,
  603. // and then only display help for one.
  604. type = null;
  605. builtinFunction = null;
  606. function = null;
  607. for (int i = 0; i < candidates.__len__(); i++) {
  608. if ((type = candidates[i] as PythonType) != null) {
  609. break;
  610. }
  611. if (builtinFunction == null && (builtinFunction = candidates[i] as BuiltinFunction) != null)
  612. continue;
  613. if (function == null && (function = candidates[i] as PythonFunction) != null)
  614. continue;
  615. }
  616. if (type != null) help(context, doced, doc, indent, type);
  617. else if (builtinFunction != null) help(context, doced, doc, indent, builtinFunction);
  618. else if (function != null) help(context, doced, doc, indent, function);
  619. }
  620. } else if ((type = obj as PythonType) != null) {
  621. // find all the functions, and display their
  622. // documentation
  623. if (indent == 0) {
  624. doc.AppendFormat("Help on {0} in module {1}\n\n", type.Name, PythonOps.GetBoundAttr(context, type, "__module__"));
  625. }
  626. PythonTypeSlot dts;
  627. if (type.TryResolveSlot(context, "__doc__", out dts)) {
  628. object docText;
  629. if (dts.TryGetValue(context, null, type, out docText) && docText != null)
  630. AppendMultiLine(doc, docText.ToString() + Environment.NewLine, indent);
  631. AppendIndent(doc, indent);
  632. doc.AppendLine("Data and other attributes defined here:");
  633. AppendIndent(doc, indent);
  634. doc.AppendLine();
  635. }
  636. List names = type.GetMemberNames(context);
  637. names.sort(context);
  638. foreach (string name in names) {
  639. if (name == "__class__") continue;
  640. PythonTypeSlot value;
  641. object val;
  642. if (type.TryLookupSlot(context, name, out value) &&
  643. value.TryGetValue(context, null, type, out val)) {
  644. help(context, doced, doc, indent + 1, val);
  645. }
  646. }
  647. } else if ((methodDesc = obj as BuiltinMethodDescriptor) != null) {
  648. if (indent == 0) doc.AppendFormat("Help on method-descriptor {0}\n\n", methodDesc.__name__);
  649. AppendIndent(doc, indent);
  650. doc.Append(methodDesc.__name__);
  651. doc.Append("(...)\n");
  652. AppendMultiLine(doc, methodDesc.__doc__, indent + 1);
  653. } else if ((builtinFunction = obj as BuiltinFunction) != null) {
  654. if (indent == 0) doc.AppendFormat("Help on built-in function {0}\n\n", builtinFunction.Name);
  655. AppendIndent(doc, indent);
  656. doc.Append(builtinFunction.Name);
  657. doc.Append("(...)\n");
  658. AppendMultiLine(doc, builtinFunction.__doc__, indent + 1);
  659. } else if ((function = obj as PythonFunction) != null) {
  660. if (indent == 0) doc.AppendFormat("Help on function {0} in module {1}:\n\n", function.__name__, function.__module__);
  661. AppendIndent(doc, indent);
  662. doc.Append(function.GetSignatureString());
  663. string pfDoc = Converter.ConvertToString(function.__doc__);
  664. if (!String.IsNullOrEmpty(pfDoc)) {
  665. AppendMultiLine(doc, pfDoc, indent);
  666. }
  667. } else if ((method = obj as Method) != null && ((function = method.im_func as PythonFunction) != null)) {
  668. if (indent == 0) doc.AppendFormat("Help on method {0} in module {1}:\n\n", function.__name__, function.__module__);
  669. AppendIndent(doc, indent);
  670. doc.Append(function.GetSignatureString());
  671. if (method.im_self == null) {
  672. doc.AppendFormat(" unbound {0} method\n", PythonOps.ToString(method.im_class));
  673. } else {
  674. doc.AppendFormat(" method of {0} instance\n", PythonOps.ToString(method.im_class));
  675. }
  676. string pfDoc = Converter.ConvertToString(function.__doc__);
  677. if (!String.IsNullOrEmpty(pfDoc)) {
  678. AppendMultiLine(doc, pfDoc, indent);
  679. }
  680. } else if ((pyModule = obj as PythonModule) != null) {
  681. foreach (string name in pyModule.__dict__.Keys) {
  682. if (name == "__class__" || name == "__builtins__") continue;
  683. object value;
  684. if (pyModule.__dict__.TryGetValue(name, out value)) {
  685. help(context, doced, doc, indent + 1, value);
  686. }
  687. }
  688. } else if ((oldClass = obj as OldClass) != null) {
  689. if (indent == 0) {
  690. doc.AppendFormat("Help on {0} in module {1}\n\n", oldClass.Name, PythonOps.GetBoundAttr(context, oldClass, "__module__"));
  691. }
  692. object docText;
  693. if (oldClass.TryLookupSlot("__doc__", out docText) && docText != null) {
  694. AppendMultiLine(doc, docText.ToString() + Environment.NewLine, indent);
  695. AppendIndent(doc, indent);
  696. doc.AppendLine("Data and other attributes defined here:");
  697. AppendIndent(doc, indent);
  698. doc.AppendLine();
  699. }
  700. IList<object> names = ((IPythonMembersList)oldClass).GetMemberNames(context);
  701. List sortNames = new List(names);
  702. sortNames.sort(context);
  703. names = sortNames;
  704. foreach (string name in names) {
  705. if (name == "__class__") continue;
  706. object value;
  707. if (oldClass.TryLookupSlot(name, out value))
  708. help(context, doced, doc, indent + 1, value);
  709. }
  710. }
  711. }
  712. private static void AppendMultiLine(StringBuilder doc, string multiline, int indent) {
  713. string[] docs = multiline.Split('\n');
  714. for (int i = 0; i < docs.Length; i++) {
  715. AppendIndent(doc, indent + 1);
  716. doc.Append(docs[i]);
  717. doc.Append('\n');
  718. }
  719. }
  720. private static void AppendIndent(StringBuilder doc, int indent) {
  721. doc.Append(" | ");
  722. for (int i = 0; i < indent; i++) doc.Append(" ");
  723. }
  724. //??? type this to string
  725. public static object hex(object o) {
  726. return PythonOps.Hex(o);
  727. }
  728. public static object id(object o) {
  729. long res = PythonOps.Id(o);
  730. if (PythonOps.Id(o) <= Int32.MaxValue) {
  731. return (int)res;
  732. }
  733. return (BigInteger)res;
  734. }
  735. public static object input(CodeContext/*!*/ context) {
  736. return input(context, null);
  737. }
  738. public static object input(CodeContext/*!*/ context, object prompt) {
  739. return eval(context, raw_input(context, prompt));
  740. }
  741. public static PythonType @int {
  742. get {
  743. return DynamicHelpers.GetPythonTypeFromType(typeof(int));
  744. }
  745. }
  746. public static string intern(object o) {
  747. string s = o as string;
  748. if (s == null) {
  749. throw PythonOps.TypeError("intern: argument must be string");
  750. }
  751. return string.Intern(s);
  752. }
  753. public static bool isinstance(object o, [NotNull]PythonType typeinfo) {
  754. return PythonOps.IsInstance(o, typeinfo);
  755. }
  756. public static bool isinstance(CodeContext context, object o, [NotNull]PythonTuple typeinfo) {
  757. return PythonOps.IsInstance(context, o, typeinfo);
  758. }
  759. public static bool isinstance(CodeContext context, object o, object typeinfo) {
  760. return PythonOps.IsInstance(context, o, typeinfo);
  761. }
  762. public static bool issubclass(CodeContext context, [NotNull]OldClass c, object typeinfo) {
  763. return PythonOps.IsSubClass(context, c.TypeObject, typeinfo);
  764. }
  765. public static bool issubclass(CodeContext context, [NotNull]PythonType c, object typeinfo) {
  766. return PythonOps.IsSubClass(context, c, typeinfo);
  767. }
  768. public static bool issubclass(CodeContext context, [NotNull]PythonType c, [NotNull]PythonType typeinfo) {
  769. return PythonOps.IsSubClass(c, typeinfo);
  770. }
  771. public static bool issubclass(CodeContext/*!*/ context, object o, object typeinfo) {
  772. PythonTuple pt = typeinfo as PythonTuple;
  773. if (pt != null) {
  774. // Recursively inspect nested tuple(s)
  775. foreach (object subTypeInfo in pt) {
  776. try {
  777. PythonOps.FunctionPushFrame(PythonContext.GetContext(context));
  778. if (issubclass(context, o, subTypeInfo)) {
  779. return true;
  780. }
  781. } finally {
  782. PythonOps.FunctionPopFrame();
  783. }
  784. }
  785. return false;
  786. }
  787. object bases;
  788. PythonTuple tupleBases;
  789. if (!PythonOps.TryGetBoundAttr(o, "__bases__", out bases) || (tupleBases = bases as PythonTuple) == null) {
  790. throw PythonOps.TypeError("issubclass() arg 1 must be a class");
  791. }
  792. foreach (object baseCls in tupleBases) {
  793. PythonType pyType;
  794. OldClass oc;
  795. if (baseCls == typeinfo) {
  796. return true;
  797. } else if ((pyType = baseCls as PythonType) != null) {
  798. if (issubclass(context, pyType, typeinfo)) {
  799. return true;
  800. }
  801. } else if ((oc = baseCls as OldClass) != null) {
  802. if (issubclass(context, oc, typeinfo)) {
  803. return true;
  804. }
  805. } else if (hasattr(context, baseCls, "__bases__")) {
  806. if (issubclass(context, baseCls, typeinfo)) {
  807. return true;
  808. }
  809. }
  810. }
  811. return false;
  812. }
  813. public static object iter(CodeContext/*!*/ context, object o) {
  814. return PythonOps.GetEnumeratorObject(context, o);
  815. }
  816. public static object iter(CodeContext/*!*/ context, object func, object sentinel) {
  817. if (!PythonOps.IsCallable(context, func)) {
  818. throw PythonOps.TypeError("iter(v, w): v must be callable");
  819. }
  820. return new SentinelIterator(context, func, sentinel);
  821. }
  822. public static int len([NotNull]string/*!*/ str) {
  823. return str.Length;
  824. }
  825. public static int len([NotNull]ExtensibleString/*!*/ str) {
  826. return str.__len__();
  827. }
  828. public static int len([NotNull]List/*!*/ list) {
  829. return list.__len__();
  830. }
  831. public static int len([NotNull]PythonTuple/*!*/ tuple) {
  832. return tuple.__len__();
  833. }
  834. public static int len([NotNull]PythonDictionary/*!*/ dict) {
  835. return dict.__len__();
  836. }
  837. public static int len([NotNull]ICollection/*!*/ collection) {
  838. return collection.Count;
  839. }
  840. public static int len(object o) {
  841. return PythonOps.Length(o);
  842. }
  843. public static PythonType set {
  844. get {
  845. return DynamicHelpers.GetPythonTypeFromType(typeof(SetCollection));
  846. }
  847. }
  848. public static PythonType frozenset {
  849. get {
  850. return DynamicHelpers.GetPythonTypeFromType(typeof(FrozenSetCollection));
  851. }
  852. }
  853. public static PythonType list {
  854. get {
  855. return DynamicHelpers.GetPythonTypeFromType(typeof(List));
  856. }
  857. }
  858. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
  859. public static object locals(CodeContext/*!*/ context) {
  860. PythonDictionary dict = context.Dict;
  861. ObjectAttributesAdapter adapter = dict._storage as ObjectAttributesAdapter;
  862. if (adapter != null) {
  863. // we've wrapped Locals in an PythonDictionary, give the user back the
  864. // original object.
  865. return adapter.Backing;
  866. }
  867. return context.Dict;
  868. }
  869. public static PythonType @long {
  870. get {
  871. return TypeCache.BigInteger;
  872. }
  873. }
  874. private static CallSite<Func<CallSite, CodeContext, T, T1, object>> MakeMapSite<T, T1>(CodeContext/*!*/ context) {
  875. return CallSite<Func<CallSite, CodeContext, T, T1, object>>.Create(
  876. PythonContext.GetContext(context).InvokeOne
  877. );
  878. }
  879. public static List map(CodeContext/*!*/ context, object func, [NotNull]IEnumerable enumerator) {
  880. IEnumerator en = PythonOps.GetEnumerator(enumerator);
  881. List ret = new List();
  882. CallSite<Func<CallSite, CodeContext, object, object, object>> mapSite = null;
  883. if (func != null) {
  884. mapSite = MakeMapSite<object, object>(context);
  885. }
  886. while (en.MoveNext()) {
  887. if (func == null) {
  888. ret.AddNoLock(en.Current);
  889. } else {
  890. ret.AddNoLock(mapSite.Target(mapSite, context, func, en.Current));
  891. }
  892. }
  893. return ret;
  894. }
  895. public static List map(
  896. CodeContext/*!*/ context,
  897. SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object, object>>> storage,
  898. object func,
  899. [NotNull]string enumerator
  900. ) {
  901. CallSite<Func<CallSite, CodeContext, object, object, object>> mapSite;
  902. if (storage.Data == null && func != null) {
  903. storage.Data = MakeMapSite<object, object>(context);
  904. }
  905. mapSite = storage.Data;
  906. List ret = new List(enumerator.Length);
  907. foreach (char o in enumerator) {
  908. if (func == null) {
  909. ret.AddNoLock(ScriptingRuntimeHelpers.CharToString(o));
  910. } else {
  911. ret.AddNoLock(mapSite.Target(mapSite, context, func, ScriptingRuntimeHelpers.CharToString(o)));
  912. }
  913. }
  914. return ret;
  915. }
  916. public static List map(
  917. CodeContext/*!*/ context,
  918. SiteLocalStorage<CallSite<Func<CallSite, CodeContext, PythonType, object, object>>> storage,
  919. [NotNull]PythonType/*!*/ func,
  920. [NotNull]string enumerator
  921. ) {
  922. CallSite<Func<CallSite, CodeContext, PythonType, string, object>> mapSite = MakeMapSite<PythonType, string>(context);
  923. List ret = new List(enumerator.Length);
  924. foreach (char o in enumerator) {
  925. ret.AddNoLock(mapSite.Target(mapSite, context, func, ScriptingRuntimeHelpers.CharToString(o)));
  926. }
  927. return ret;
  928. }
  929. public static List map(
  930. CodeContext/*!*/ context,
  931. SiteLocalStorage<CallSite<Func<CallSite, CodeContext, PythonType, object, object>>> storage,
  932. [NotNull]PythonType/*!*/ func,
  933. [NotNull]IEnumerable enumerator
  934. ) {
  935. CallSite<Func<CallSite, CodeContext, PythonType, object, object>> mapSite;
  936. if (storage.Data == null) {
  937. storage.Data = MakeMapSite<PythonType, object>(context);
  938. }
  939. mapSite = storage.Data;
  940. IEnumerator en = PythonOps.GetEnumerator(enumerator);
  941. List ret = new List();
  942. while (en.MoveNext()) {
  943. ret.AddNoLock(mapSite.Target(mapSite, context, func, en.Current));
  944. }
  945. return ret;
  946. }
  947. public static List map(
  948. CodeContext/*!*/ context,
  949. SiteLocalStorage<CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>>> storage,
  950. [NotNull]BuiltinFunction/*!*/ func,
  951. [NotNull]string enumerator
  952. ) {
  953. CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>> mapSite;
  954. if (storage.Data == null) {
  955. storage.Data = MakeMapSite<BuiltinFunction, object>(context);
  956. }
  957. mapSite = storage.Data;
  958. List ret = new List(enumerator.Length);
  959. foreach (char o in enumerator) {
  960. ret.AddNoLock(mapSite.Target(mapSite, context, func, ScriptingRuntimeHelpers.CharToString(o)));
  961. }
  962. return ret;
  963. }
  964. public static List map(
  965. CodeContext/*!*/ context,
  966. SiteLocalStorage<CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>>> storage,
  967. [NotNull]BuiltinFunction/*!*/ func,
  968. [NotNull]IEnumerable enumerator
  969. ) {
  970. CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>> mapSite;
  971. if (storage.Data == null) {
  972. storage.Data = MakeMapSite<BuiltinFunction, object>(context);
  973. }
  974. mapSite = storage.Data;
  975. IEnumerator en = PythonOps.GetEnumerator(enumerator);
  976. List ret = new List();
  977. while (en.MoveNext()) {
  978. ret.AddNoLock(mapSite.Target(mapSite, context, func, en.Current));
  979. }
  980. return ret;
  981. }
  982. public static List map(
  983. CodeContext/*!*/ context,
  984. SiteLocalStorage<CallSite<Func<CallSite, CodeContext, PythonFunction, object, object>>> storage,
  985. [NotNull]PythonFunction/*!*/ func,
  986. [NotNull]IList enumerator
  987. ) {
  988. CallSite<Func<CallSite, CodeContext, PythonFunction, object, object>> mapSite;
  989. if (storage.Data == null) {
  990. storage.Data = MakeMapSite<PythonFunction, object>(context);
  991. }
  992. mapSite = storage.Data;
  993. IEnumerator en = PythonOps.GetEnumerator(enumerator);
  994. List ret = new List(enumerator.Count);
  995. while (en.MoveNext()) {
  996. ret.AddNoLock(mapSite.Target(mapSite, context, func, en.Current));
  997. }
  998. return ret;
  999. }
  1000. public static List map(CodeContext/*!*/ context, params object[] param) {
  1001. if (param == null || param.Length < 2) {
  1002. throw PythonOps.TypeError("at least 2 arguments required to map");
  1003. }
  1004. List ret = new List();
  1005. object func = param[0];

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