PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/IronPython/Modules/Builtin.cs

http://github.com/IronLanguages/main
C# | 2501 lines | 2025 code | 388 blank | 88 comment | 567 complexity | 5b36eeac9abc8c60a8fd497eb341839c MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

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

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

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