PageRenderTime 408ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

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

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