PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/IronPython/Runtime/ClrModule.cs

http://github.com/IronLanguages/main
C# | 1209 lines | 785 code | 188 blank | 236 comment | 153 complexity | 78232e5a0cf0a239bcfe49c72ad81fb0 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. #if FEATURE_SERIALIZATION
  16. using System.Runtime.Serialization.Formatters.Binary;
  17. #endif
  18. #if !FEATURE_REMOTING
  19. using MarshalByRefObject = System.Object;
  20. #endif
  21. #if FEATURE_COM
  22. using ComTypeLibInfo = Microsoft.Scripting.ComInterop.ComTypeLibInfo;
  23. using ComTypeLibDesc = Microsoft.Scripting.ComInterop.ComTypeLibDesc;
  24. #endif
  25. using System;
  26. using System.Collections;
  27. using System.Collections.Generic;
  28. using System.IO;
  29. using System.Reflection;
  30. using System.Runtime.CompilerServices;
  31. using System.Runtime.InteropServices;
  32. using System.Text;
  33. using Microsoft.Scripting;
  34. using Microsoft.Scripting.Actions;
  35. using Microsoft.Scripting.Generation;
  36. using Microsoft.Scripting.Runtime;
  37. using Microsoft.Scripting.Utils;
  38. using IronPython.Runtime;
  39. using IronPython.Runtime.Exceptions;
  40. using IronPython.Runtime.Operations;
  41. using IronPython.Runtime.Types;
  42. [assembly: PythonModule("clr", typeof(IronPython.Runtime.ClrModule))]
  43. namespace IronPython.Runtime {
  44. /// <summary>
  45. /// this class contains objecs and static methods used for
  46. /// .NET/CLS interop with Python.
  47. /// </summary>
  48. public static class ClrModule {
  49. #if NETSTANDARD
  50. public static readonly bool IsNetStandard = true;
  51. #else
  52. public static readonly bool IsNetStandard = false;
  53. #endif
  54. private static int _isMono = -1;
  55. public static bool IsMono {
  56. get {
  57. if(_isMono == -1) {
  58. _isMono = Type.GetType ("Mono.Runtime") != null ? 1 : 0;
  59. }
  60. return _isMono == 1;
  61. }
  62. }
  63. [SpecialName]
  64. public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
  65. if (!dict.ContainsKey("References")) {
  66. dict["References"] = context.ReferencedAssemblies;
  67. }
  68. }
  69. #region Public methods
  70. /// <summary>
  71. /// Gets the current ScriptDomainManager that IronPython is loaded into. The
  72. /// ScriptDomainManager can then be used to work with the language portion of the
  73. /// DLR hosting APIs.
  74. /// </summary>
  75. public static ScriptDomainManager/*!*/ GetCurrentRuntime(CodeContext/*!*/ context) {
  76. return context.LanguageContext.DomainManager;
  77. }
  78. [Documentation(@"Adds a reference to a .NET assembly. Parameters can be an already loaded
  79. Assembly object, a full assembly name, or a partial assembly name. After the
  80. load the assemblies namespaces and top-level types will be available via
  81. import Namespace.")]
  82. public static void AddReference(CodeContext/*!*/ context, params object[] references) {
  83. if (references == null) throw new TypeErrorException("Expected string or Assembly, got NoneType");
  84. if (references.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
  85. ContractUtils.RequiresNotNull(context, "context");
  86. foreach (object reference in references) {
  87. AddReference(context, reference);
  88. }
  89. }
  90. [Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can
  91. be provided. The assembly is searched for in the directories specified in
  92. sys.path and dependencies will be loaded from sys.path as well. The assembly
  93. name should be the filename on disk without a directory specifier and
  94. optionally including the .EXE or .DLL extension. After the load the assemblies
  95. namespaces and top-level types will be available via import Namespace.")]
  96. public static void AddReferenceToFile(CodeContext/*!*/ context, params string[] files) {
  97. if (files == null) throw new TypeErrorException("Expected string, got NoneType");
  98. if (files.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
  99. ContractUtils.RequiresNotNull(context, "context");
  100. foreach (string file in files) {
  101. AddReferenceToFile(context, file);
  102. }
  103. }
  104. [Documentation(@"Adds a reference to a .NET assembly. Parameters are an assembly name.
  105. After the load the assemblies namespaces and top-level types will be available via
  106. import Namespace.")]
  107. public static void AddReferenceByName(CodeContext/*!*/ context, params string[] names) {
  108. if (names == null) throw new TypeErrorException("Expected string, got NoneType");
  109. if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
  110. ContractUtils.RequiresNotNull(context, "context");
  111. foreach (string name in names) {
  112. AddReferenceByName(context, name);
  113. }
  114. }
  115. #if FEATURE_LOADWITHPARTIALNAME
  116. [Documentation(@"Adds a reference to a .NET assembly. Parameters are a partial assembly name.
  117. After the load the assemblies namespaces and top-level types will be available via
  118. import Namespace.")]
  119. public static void AddReferenceByPartialName(CodeContext/*!*/ context, params string[] names) {
  120. if (names == null) throw new TypeErrorException("Expected string, got NoneType");
  121. if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
  122. ContractUtils.RequiresNotNull(context, "context");
  123. foreach (string name in names) {
  124. AddReferenceByPartialName(context, name);
  125. }
  126. }
  127. #endif
  128. #if FEATURE_FILESYSTEM
  129. [Documentation(@"Adds a reference to a .NET assembly. Parameters are a full path to an.
  130. assembly on disk. After the load the assemblies namespaces and top-level types
  131. will be available via import Namespace.")]
  132. public static Assembly/*!*/ LoadAssemblyFromFileWithPath(CodeContext/*!*/ context, string/*!*/ file) {
  133. if (file == null) throw new TypeErrorException("LoadAssemblyFromFileWithPath: arg 1 must be a string.");
  134. Assembly res;
  135. if (!context.LanguageContext.TryLoadAssemblyFromFileWithPath(file, out res)) {
  136. if (!Path.IsPathRooted(file)) {
  137. throw new ValueErrorException("LoadAssemblyFromFileWithPath: path must be rooted");
  138. } else if (!File.Exists(file)) {
  139. throw new ValueErrorException("LoadAssemblyFromFileWithPath: file not found");
  140. } else {
  141. throw new ValueErrorException("LoadAssemblyFromFileWithPath: error loading assembly");
  142. }
  143. }
  144. return res;
  145. }
  146. [Documentation(@"Loads an assembly from the specified filename and returns the assembly
  147. object. Namespaces or types in the assembly can be accessed directly from
  148. the assembly object.")]
  149. public static Assembly/*!*/ LoadAssemblyFromFile(CodeContext/*!*/ context, string/*!*/ file) {
  150. if (file == null) throw new TypeErrorException("Expected string, got NoneType");
  151. if (file.Length == 0) throw new ValueErrorException("assembly name must not be empty string");
  152. ContractUtils.RequiresNotNull(context, "context");
  153. if (file.IndexOf(System.IO.Path.DirectorySeparatorChar) != -1) {
  154. throw new ValueErrorException("filenames must not contain full paths, first add the path to sys.path");
  155. }
  156. return context.LanguageContext.LoadAssemblyFromFile(file);
  157. }
  158. #endif
  159. #if FEATURE_LOADWITHPARTIALNAME
  160. [Documentation(@"Loads an assembly from the specified partial assembly name and returns the
  161. assembly object. Namespaces or types in the assembly can be accessed directly
  162. from the assembly object.")]
  163. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")]
  164. public static Assembly/*!*/ LoadAssemblyByPartialName(string/*!*/ name) {
  165. if (name == null) {
  166. throw new TypeErrorException("LoadAssemblyByPartialName: arg 1 must be a string");
  167. }
  168. #pragma warning disable 618, 612 // csc
  169. return Assembly.LoadWithPartialName(name);
  170. #pragma warning restore 618, 612
  171. }
  172. #endif
  173. [Documentation(@"Loads an assembly from the specified assembly name and returns the assembly
  174. object. Namespaces or types in the assembly can be accessed directly from
  175. the assembly object.")]
  176. public static Assembly/*!*/ LoadAssemblyByName(CodeContext/*!*/ context, string/*!*/ name) {
  177. if (name == null) {
  178. throw new TypeErrorException("LoadAssemblyByName: arg 1 must be a string");
  179. }
  180. return PythonContext.GetContext(context).DomainManager.Platform.LoadAssembly(name);
  181. }
  182. /// <summary>
  183. /// Use(name) -> module
  184. ///
  185. /// Attempts to load the specified module searching all languages in the loaded ScriptRuntime.
  186. /// </summary>
  187. public static object Use(CodeContext/*!*/ context, string/*!*/ name) {
  188. ContractUtils.RequiresNotNull(context, "context");
  189. if (name == null) {
  190. throw new TypeErrorException("Use: arg 1 must be a string");
  191. }
  192. var scope = Importer.TryImportSourceFile(PythonContext.GetContext(context), name);
  193. if (scope == null) {
  194. throw new ValueErrorException(String.Format("couldn't find module {0} to use", name));
  195. }
  196. return scope;
  197. }
  198. [Documentation("Converts an array of bytes to a string.")]
  199. public static string GetString(byte[] bytes) {
  200. return GetString(bytes, bytes.Length);
  201. }
  202. [Documentation("Converts maxCount of an array of bytes to a string")]
  203. public static string GetString(byte[] bytes, int maxCount) {
  204. int bytesToCopy = Math.Min(bytes.Length, maxCount);
  205. return Encoding.GetEncoding("iso-8859-1").GetString(bytes, 0, bytesToCopy);
  206. }
  207. [Documentation("Converts a string to an array of bytes")]
  208. public static byte[] GetBytes(string s) {
  209. return GetBytes(s, s.Length);
  210. }
  211. [Documentation("Converts maxCount of a string to an array of bytes")]
  212. public static byte[] GetBytes(string s, int maxCount) {
  213. int charsToCopy = Math.Min(s.Length, maxCount);
  214. byte[] ret = new byte[charsToCopy];
  215. Encoding.GetEncoding("iso-8859-1").GetBytes(s, 0, charsToCopy, ret, 0);
  216. return ret;
  217. }
  218. /// <summary>
  219. /// Use(path, language) -> module
  220. ///
  221. /// Attempts to load the specified module belonging to a specific language loaded into the
  222. /// current ScriptRuntime.
  223. /// </summary>
  224. public static object/*!*/ Use(CodeContext/*!*/ context, string/*!*/ path, string/*!*/ language) {
  225. ContractUtils.RequiresNotNull(context, "context");
  226. if (path == null) {
  227. throw new TypeErrorException("Use: arg 1 must be a string");
  228. }
  229. if (language == null) {
  230. throw new TypeErrorException("Use: arg 2 must be a string");
  231. }
  232. var manager = context.LanguageContext.DomainManager;
  233. if (!manager.Platform.FileExists(path)) {
  234. throw new ValueErrorException(String.Format("couldn't load module at path '{0}' in language '{1}'", path, language));
  235. }
  236. var sourceUnit = manager.GetLanguageByName(language).CreateFileUnit(path);
  237. return Importer.ExecuteSourceUnit(context.LanguageContext, sourceUnit);
  238. }
  239. /// <summary>
  240. /// SetCommandDispatcher(commandDispatcher)
  241. ///
  242. /// Sets the current command dispatcher for the Python command line.
  243. ///
  244. /// The command dispatcher will be called with a delegate to be executed. The command dispatcher
  245. /// should invoke the target delegate in the desired context.
  246. ///
  247. /// A common use for this is to enable running all REPL commands on the UI thread while the REPL
  248. /// continues to run on a non-UI thread.
  249. /// </summary>
  250. public static Action<Action> SetCommandDispatcher(CodeContext/*!*/ context, Action<Action> dispatcher) {
  251. ContractUtils.RequiresNotNull(context, "context");
  252. return ((PythonContext)context.LanguageContext).GetSetCommandDispatcher(dispatcher);
  253. }
  254. public static void ImportExtensions(CodeContext/*!*/ context, PythonType type) {
  255. if (type == null) {
  256. throw PythonOps.TypeError("type must not be None");
  257. } else if (!type.IsSystemType) {
  258. throw PythonOps.ValueError("type must be .NET type");
  259. }
  260. lock (context.ModuleContext) {
  261. context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddType(context.LanguageContext, context.ModuleContext.ExtensionMethods, type);
  262. }
  263. }
  264. public static void ImportExtensions(CodeContext/*!*/ context, [NotNull]NamespaceTracker @namespace) {
  265. lock (context.ModuleContext) {
  266. context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddNamespace(context.LanguageContext, context.ModuleContext.ExtensionMethods, @namespace);
  267. }
  268. }
  269. #if FEATURE_COM
  270. /// <summary>
  271. /// LoadTypeLibrary(rcw) -> type lib desc
  272. ///
  273. /// Gets an ITypeLib object from OLE Automation compatible RCW ,
  274. /// reads definitions of CoClass'es and Enum's from this library
  275. /// and creates an object that allows to instantiate coclasses
  276. /// and get actual values for the enums.
  277. /// </summary>
  278. public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, object rcw) {
  279. return ComTypeLibDesc.CreateFromObject(rcw);
  280. }
  281. /// <summary>
  282. /// LoadTypeLibrary(guid) -> type lib desc
  283. ///
  284. /// Reads the latest registered type library for the corresponding GUID,
  285. /// reads definitions of CoClass'es and Enum's from this library
  286. /// and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses
  287. /// and get actual values for the enums.
  288. /// </summary>
  289. public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) {
  290. return ComTypeLibDesc.CreateFromGuid(typeLibGuid);
  291. }
  292. /// <summary>
  293. /// AddReferenceToTypeLibrary(rcw) -> None
  294. ///
  295. /// Makes the type lib desc available for importing. See also LoadTypeLibrary.
  296. /// </summary>
  297. public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, object rcw) {
  298. ComTypeLibInfo typeLibInfo;
  299. typeLibInfo = ComTypeLibDesc.CreateFromObject(rcw);
  300. PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc);
  301. }
  302. /// <summary>
  303. /// AddReferenceToTypeLibrary(guid) -> None
  304. ///
  305. /// Makes the type lib desc available for importing. See also LoadTypeLibrary.
  306. /// </summary>
  307. public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) {
  308. ComTypeLibInfo typeLibInfo;
  309. typeLibInfo = ComTypeLibDesc.CreateFromGuid(typeLibGuid);
  310. PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc);
  311. }
  312. private static void PublishTypeLibDesc(CodeContext context, ComTypeLibDesc typeLibDesc) {
  313. PythonOps.ScopeSetMember(context, context.LanguageContext.DomainManager.Globals, typeLibDesc.Name, typeLibDesc);
  314. }
  315. #endif
  316. #endregion
  317. #region Private implementation methods
  318. private static void AddReference(CodeContext/*!*/ context, object reference) {
  319. Assembly asmRef = reference as Assembly;
  320. if (asmRef != null) {
  321. AddReference(context, asmRef);
  322. return;
  323. }
  324. string strRef = reference as string;
  325. if (strRef != null) {
  326. AddReference(context, strRef);
  327. return;
  328. }
  329. throw new TypeErrorException(String.Format("Invalid assembly type. Expected string or Assembly, got {0}.", reference));
  330. }
  331. private static void AddReference(CodeContext/*!*/ context, Assembly assembly) {
  332. context.LanguageContext.DomainManager.LoadAssembly(assembly);
  333. }
  334. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // TODO: fix
  335. private static void AddReference(CodeContext/*!*/ context, string name) {
  336. if (name == null) throw new TypeErrorException("Expected string, got NoneType");
  337. Assembly asm = null;
  338. try {
  339. asm = LoadAssemblyByName(context, name);
  340. } catch { }
  341. // note we don't explicit call to get the file version
  342. // here because the assembly resolve event will do it for us.
  343. #if FEATURE_LOADWITHPARTIALNAME
  344. if (asm == null) {
  345. asm = LoadAssemblyByPartialName(name);
  346. }
  347. #endif
  348. if (asm == null) {
  349. throw new IOException(String.Format("Could not add reference to assembly {0}", name));
  350. }
  351. AddReference(context, asm);
  352. }
  353. private static void AddReferenceToFile(CodeContext/*!*/ context, string file) {
  354. if (file == null) throw new TypeErrorException("Expected string, got NoneType");
  355. #if FEATURE_FILESYSTEM
  356. Assembly asm = LoadAssemblyFromFile(context, file);
  357. #else
  358. Assembly asm = context.LanguageContext.DomainManager.Platform.LoadAssemblyFromPath(file);
  359. #endif
  360. if (asm == null) {
  361. throw new IOException(String.Format("Could not add reference to assembly {0}", file));
  362. }
  363. AddReference(context, asm);
  364. }
  365. #if FEATURE_LOADWITHPARTIALNAME
  366. private static void AddReferenceByPartialName(CodeContext/*!*/ context, string name) {
  367. if (name == null) throw new TypeErrorException("Expected string, got NoneType");
  368. ContractUtils.RequiresNotNull(context, "context");
  369. Assembly asm = LoadAssemblyByPartialName(name);
  370. if (asm == null) {
  371. throw new IOException(String.Format("Could not add reference to assembly {0}", name));
  372. }
  373. AddReference(context, asm);
  374. }
  375. #endif
  376. private static void AddReferenceByName(CodeContext/*!*/ context, string name) {
  377. if (name == null) throw new TypeErrorException("Expected string, got NoneType");
  378. Assembly asm = LoadAssemblyByName(context, name);
  379. if (asm == null) {
  380. throw new IOException(String.Format("Could not add reference to assembly {0}", name));
  381. }
  382. AddReference(context, asm);
  383. }
  384. #endregion
  385. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO: fix
  386. public sealed class ReferencesList : List<Assembly>, ICodeFormattable {
  387. public new void Add(Assembly other) {
  388. base.Add(other);
  389. }
  390. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists"), SpecialName]
  391. public ClrModule.ReferencesList Add(object other) {
  392. IEnumerator ie = PythonOps.GetEnumerator(other);
  393. while (ie.MoveNext()) {
  394. Assembly cur = ie.Current as Assembly;
  395. if (cur == null) throw PythonOps.TypeError("non-assembly added to references list");
  396. base.Add(cur);
  397. }
  398. return this;
  399. }
  400. public string/*!*/ __repr__(CodeContext/*!*/ context) {
  401. StringBuilder res = new StringBuilder("(");
  402. string comma = "";
  403. foreach (Assembly asm in this) {
  404. res.Append(comma);
  405. res.Append('<');
  406. res.Append(asm.FullName);
  407. res.Append('>');
  408. comma = "," + Environment.NewLine;
  409. }
  410. res.AppendLine(")");
  411. return res.ToString();
  412. }
  413. }
  414. private static PythonType _strongBoxType;
  415. #region Runtime Type Checking support
  416. #if FEATURE_FILESYSTEM
  417. [Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can
  418. be provided which are fully qualified names to the file on disk. The
  419. directory is added to sys.path and AddReferenceToFile is then called. After the
  420. load the assemblies namespaces and top-level types will be available via
  421. import Namespace.")]
  422. public static void AddReferenceToFileAndPath(CodeContext/*!*/ context, params string[] files) {
  423. if (files == null) throw new TypeErrorException("Expected string, got NoneType");
  424. ContractUtils.RequiresNotNull(context, "context");
  425. foreach (string file in files) {
  426. AddReferenceToFileAndPath(context, file);
  427. }
  428. }
  429. private static void AddReferenceToFileAndPath(CodeContext/*!*/ context, string file) {
  430. if (file == null) throw PythonOps.TypeError("Expected string, got NoneType");
  431. // update our path w/ the path of this file...
  432. string path = System.IO.Path.GetDirectoryName(Path.GetFullPath(file));
  433. List list;
  434. PythonContext pc = PythonContext.GetContext(context);
  435. if (!pc.TryGetSystemPath(out list)) {
  436. throw PythonOps.TypeError("cannot update path, it is not a list");
  437. }
  438. list.append(path);
  439. Assembly asm = pc.LoadAssemblyFromFile(file);
  440. if (asm == null) throw PythonOps.IOError("file does not exist: {0}", file);
  441. AddReference(context, asm);
  442. }
  443. #endif
  444. /// <summary>
  445. /// Gets the CLR Type object from a given Python type object.
  446. /// </summary>
  447. public static Type GetClrType(Type type) {
  448. return type;
  449. }
  450. /// <summary>
  451. /// Gets the Python type object from a given CLR Type object.
  452. /// </summary>
  453. public static PythonType GetPythonType(Type t) {
  454. return DynamicHelpers.GetPythonTypeFromType(t);
  455. }
  456. /// <summary>
  457. /// OBSOLETE: Gets the Python type object from a given CLR Type object.
  458. ///
  459. /// Use clr.GetPythonType instead.
  460. /// </summary>
  461. [Obsolete("Call clr.GetPythonType instead")]
  462. public static PythonType GetDynamicType(Type t) {
  463. return DynamicHelpers.GetPythonTypeFromType(t);
  464. }
  465. public static PythonType Reference {
  466. get {
  467. return StrongBox;
  468. }
  469. }
  470. public static PythonType StrongBox {
  471. get {
  472. if (_strongBoxType == null) {
  473. _strongBoxType = DynamicHelpers.GetPythonTypeFromType(typeof(StrongBox<>));
  474. }
  475. return _strongBoxType;
  476. }
  477. }
  478. /// <summary>
  479. /// accepts(*types) -> ArgChecker
  480. ///
  481. /// Decorator that returns a new callable object which will validate the arguments are of the specified types.
  482. /// </summary>
  483. /// <param name="types"></param>
  484. /// <returns></returns>
  485. public static object accepts(params object[] types) {
  486. return new ArgChecker(types);
  487. }
  488. /// <summary>
  489. /// returns(type) -> ReturnChecker
  490. ///
  491. /// Returns a new callable object which will validate the return type is of the specified type.
  492. /// </summary>
  493. public static object returns(object type) {
  494. return new ReturnChecker(type);
  495. }
  496. public static object Self() {
  497. return null;
  498. }
  499. #endregion
  500. /// <summary>
  501. /// Decorator for verifying the arguments to a function are of a specified type.
  502. /// </summary>
  503. public class ArgChecker {
  504. private object[] expected;
  505. public ArgChecker(object[] prms) {
  506. expected = prms;
  507. }
  508. #region ICallableWithCodeContext Members
  509. [SpecialName]
  510. public object Call(CodeContext context, object func) {
  511. // expect only to receive the function we'll call here.
  512. return new RuntimeArgChecker(func, expected);
  513. }
  514. #endregion
  515. }
  516. /// <summary>
  517. /// Returned value when using clr.accepts/ArgChecker. Validates the argument types and
  518. /// then calls the original function.
  519. /// </summary>
  520. public class RuntimeArgChecker : PythonTypeSlot {
  521. private object[] _expected;
  522. private object _func;
  523. private object _inst;
  524. public RuntimeArgChecker(object function, object[] expectedArgs) {
  525. _expected = expectedArgs;
  526. _func = function;
  527. }
  528. public RuntimeArgChecker(object instance, object function, object[] expectedArgs)
  529. : this(function, expectedArgs) {
  530. _inst = instance;
  531. }
  532. private void ValidateArgs(object[] args) {
  533. int start = 0;
  534. if (_inst != null) {
  535. start = 1;
  536. }
  537. // no need to validate self... the method should handle it.
  538. for (int i = start; i < args.Length + start; i++) {
  539. PythonType dt = DynamicHelpers.GetPythonType(args[i - start]);
  540. PythonType expct = _expected[i] as PythonType;
  541. if (expct == null) expct = ((OldClass)_expected[i]).TypeObject;
  542. if (dt != _expected[i] && !dt.IsSubclassOf(expct)) {
  543. throw PythonOps.AssertionError("argument {0} has bad value (got {1}, expected {2})", i, dt, _expected[i]);
  544. }
  545. }
  546. }
  547. #region ICallableWithCodeContext Members
  548. [SpecialName]
  549. public object Call(CodeContext context, params object[] args) {
  550. ValidateArgs(args);
  551. if (_inst != null) {
  552. return PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args));
  553. } else {
  554. return PythonOps.CallWithContext(context, _func, args);
  555. }
  556. }
  557. #endregion
  558. internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
  559. value = new RuntimeArgChecker(instance, _func, _expected);
  560. return true;
  561. }
  562. internal override bool GetAlwaysSucceeds {
  563. get {
  564. return true;
  565. }
  566. }
  567. #region IFancyCallable Members
  568. [SpecialName]
  569. public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
  570. ValidateArgs(args);
  571. if (_inst != null) {
  572. return PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict);
  573. } else {
  574. return PythonCalls.CallWithKeywordArgs(context, _func, args, dict);
  575. }
  576. }
  577. #endregion
  578. }
  579. /// <summary>
  580. /// Decorator for verifying the return type of functions.
  581. /// </summary>
  582. public class ReturnChecker {
  583. public object retType;
  584. public ReturnChecker(object returnType) {
  585. retType = returnType;
  586. }
  587. #region ICallableWithCodeContext Members
  588. [SpecialName]
  589. public object Call(CodeContext context, object func) {
  590. // expect only to receive the function we'll call here.
  591. return new RuntimeReturnChecker(func, retType);
  592. }
  593. #endregion
  594. }
  595. /// <summary>
  596. /// Returned value when using clr.returns/ReturnChecker. Calls the original function and
  597. /// validates the return type is of a specified type.
  598. /// </summary>
  599. public class RuntimeReturnChecker : PythonTypeSlot {
  600. private object _retType;
  601. private object _func;
  602. private object _inst;
  603. public RuntimeReturnChecker(object function, object expectedReturn) {
  604. _retType = expectedReturn;
  605. _func = function;
  606. }
  607. public RuntimeReturnChecker(object instance, object function, object expectedReturn)
  608. : this(function, expectedReturn) {
  609. _inst = instance;
  610. }
  611. private void ValidateReturn(object ret) {
  612. // we return void...
  613. if (ret == null && _retType == null) return;
  614. PythonType dt = DynamicHelpers.GetPythonType(ret);
  615. if (dt != _retType) {
  616. PythonType expct = _retType as PythonType;
  617. if (expct == null) expct = ((OldClass)_retType).TypeObject;
  618. if (!dt.IsSubclassOf(expct))
  619. throw PythonOps.AssertionError("bad return value returned (expected {0}, got {1})", _retType, dt);
  620. }
  621. }
  622. #region ICallableWithCodeContext Members
  623. [SpecialName]
  624. public object Call(CodeContext context, params object[] args) {
  625. object ret;
  626. if (_inst != null) {
  627. ret = PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args));
  628. } else {
  629. ret = PythonOps.CallWithContext(context, _func, args);
  630. }
  631. ValidateReturn(ret);
  632. return ret;
  633. }
  634. #endregion
  635. #region IDescriptor Members
  636. public object GetAttribute(object instance, object owner) {
  637. return new RuntimeReturnChecker(instance, _func, _retType);
  638. }
  639. #endregion
  640. internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
  641. value = GetAttribute(instance, owner);
  642. return true;
  643. }
  644. internal override bool GetAlwaysSucceeds {
  645. get {
  646. return true;
  647. }
  648. }
  649. #region IFancyCallable Members
  650. [SpecialName]
  651. public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
  652. object ret;
  653. if (_inst != null) {
  654. ret = PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict);
  655. } else {
  656. return PythonCalls.CallWithKeywordArgs(context, _func, args, dict);
  657. }
  658. ValidateReturn(ret);
  659. return ret;
  660. }
  661. #endregion
  662. }
  663. /// <summary>
  664. /// returns the result of dir(o) as-if "import clr" has not been performed.
  665. /// </summary>
  666. public static List Dir(object o) {
  667. IList<object> ret = PythonOps.GetAttrNames(DefaultContext.Default, o);
  668. List lret = new List(ret);
  669. lret.sort(DefaultContext.Default);
  670. return lret;
  671. }
  672. /// <summary>
  673. /// Returns the result of dir(o) as-if "import clr" has been performed.
  674. /// </summary>
  675. public static List DirClr(object o) {
  676. IList<object> ret = PythonOps.GetAttrNames(DefaultContext.DefaultCLS, o);
  677. List lret = new List(ret);
  678. lret.sort(DefaultContext.DefaultCLS);
  679. return lret;
  680. }
  681. /// <summary>
  682. /// Attempts to convert the provided object to the specified type. Conversions that
  683. /// will be attempted include standard Python conversions as well as .NET implicit
  684. /// and explicit conversions.
  685. ///
  686. /// If the conversion cannot be performed a TypeError will be raised.
  687. /// </summary>
  688. public static object Convert(CodeContext/*!*/ context, object o, Type toType) {
  689. return Converter.Convert(o, toType);
  690. }
  691. #if FEATURE_FILESYSTEM && FEATURE_REFEMIT
  692. /// <summary>
  693. /// Provides a helper for compiling a group of modules into a single assembly. The assembly can later be
  694. /// reloaded using the clr.AddReference API.
  695. /// </summary>
  696. public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assemblyName, [ParamDictionary]IDictionary<string, object> kwArgs, params string/*!*/[]/*!*/ filenames) {
  697. ContractUtils.RequiresNotNull(assemblyName, "assemblyName");
  698. ContractUtils.RequiresNotNullItems(filenames, "filenames");
  699. PythonContext pc = PythonContext.GetContext(context);
  700. for (int i = 0; i < filenames.Length; i++) {
  701. filenames[i] = Path.GetFullPath(filenames[i]);
  702. }
  703. Dictionary<string, string> packageMap = BuildPackageMap(filenames);
  704. List<SavableScriptCode> code = new List<SavableScriptCode>();
  705. foreach (string filename in filenames) {
  706. if (!pc.DomainManager.Platform.FileExists(filename)) {
  707. throw PythonOps.IOError("Couldn't find file for compilation: {0}", filename);
  708. }
  709. ScriptCode sc;
  710. string modName;
  711. string dname = Path.GetDirectoryName(filename);
  712. string outFilename = "";
  713. if (Path.GetFileName(filename) == "__init__.py") {
  714. // remove __init__.py to get package name
  715. dname = Path.GetDirectoryName(dname);
  716. if (String.IsNullOrEmpty(dname)) {
  717. modName = Path.GetDirectoryName(filename);
  718. } else {
  719. modName = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(filename));
  720. }
  721. outFilename = Path.DirectorySeparatorChar + "__init__.py";
  722. } else {
  723. modName = Path.GetFileNameWithoutExtension(filename);
  724. }
  725. // see if we have a parent package, if so incorporate it into
  726. // our name
  727. string parentPackage;
  728. if (packageMap.TryGetValue(dname, out parentPackage)) {
  729. modName = parentPackage + "." + modName;
  730. }
  731. outFilename = modName.Replace('.', Path.DirectorySeparatorChar) + outFilename;
  732. SourceUnit su = pc.CreateSourceUnit(
  733. new FileStreamContentProvider(
  734. context.LanguageContext.DomainManager.Platform,
  735. filename
  736. ),
  737. outFilename,
  738. pc.DefaultEncoding,
  739. SourceCodeKind.File
  740. );
  741. sc = PythonContext.GetContext(context).GetScriptCode(su, modName, ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk);
  742. code.Add((SavableScriptCode)sc);
  743. }
  744. object mainModule;
  745. if (kwArgs != null && kwArgs.TryGetValue("mainModule", out mainModule)) {
  746. string strModule = mainModule as string;
  747. if (strModule != null) {
  748. if (!pc.DomainManager.Platform.FileExists(strModule)) {
  749. throw PythonOps.IOError("Couldn't find main file for compilation: {0}", strModule);
  750. }
  751. SourceUnit su = pc.CreateFileUnit(strModule, pc.DefaultEncoding, SourceCodeKind.File);
  752. code.Add((SavableScriptCode)PythonContext.GetContext(context).GetScriptCode(su, "__main__", ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk));
  753. }
  754. }
  755. SavableScriptCode.SaveToAssembly(assemblyName, code.ToArray());
  756. }
  757. #endif
  758. #if FEATURE_REFEMIT
  759. /// <summary>
  760. /// clr.CompileSubclassTypes(assemblyName, *typeDescription)
  761. ///
  762. /// Provides a helper for creating an assembly which contains pre-generated .NET
  763. /// base types for new-style types.
  764. ///
  765. /// This assembly can then be AddReferenced or put sys.prefix\DLLs and the cached
  766. /// types will be used instead of generating the types at runtime.
  767. ///
  768. /// This function takes the name of the assembly to save to and then an arbitrary
  769. /// number of parameters describing the types to be created. Each of those
  770. /// parameter can either be a plain type or a sequence of base types.
  771. ///
  772. /// clr.CompileSubclassTypes(object) -> create a base type for object
  773. /// clr.CompileSubclassTypes(object, str, System.Collections.ArrayList) -> create
  774. /// base types for both object and ArrayList.
  775. ///
  776. /// clr.CompileSubclassTypes(object, (object, IComparable)) -> create base types for
  777. /// object and an object which implements IComparable.
  778. ///
  779. /// </summary>
  780. public static void CompileSubclassTypes(string/*!*/ assemblyName, params object[] newTypes) {
  781. if (assemblyName == null) {
  782. throw PythonOps.TypeError("CompileTypes expected str for assemblyName, got NoneType");
  783. }
  784. var typesToCreate = new List<PythonTuple>();
  785. foreach (object o in newTypes) {
  786. if (o is PythonType) {
  787. typesToCreate.Add(PythonTuple.MakeTuple(o));
  788. } else {
  789. typesToCreate.Add(PythonTuple.Make(o));
  790. }
  791. }
  792. NewTypeMaker.SaveNewTypes(assemblyName, typesToCreate);
  793. }
  794. #endif
  795. /// <summary>
  796. /// clr.GetSubclassedTypes() -> tuple
  797. ///
  798. /// Returns a tuple of information about the types which have been subclassed.
  799. ///
  800. /// This tuple can be passed to clr.CompileSubclassTypes to cache these
  801. /// types on disk such as:
  802. ///
  803. /// clr.CompileSubclassTypes('assembly', *clr.GetSubclassedTypes())
  804. /// </summary>
  805. public static PythonTuple GetSubclassedTypes() {
  806. List<object> res = new List<object>();
  807. foreach (NewTypeInfo info in NewTypeMaker._newTypes.Keys) {
  808. Type clrBaseType = info.BaseType;
  809. Type tempType = clrBaseType;
  810. while (tempType != null) {
  811. if (tempType.GetTypeInfo().IsGenericType && tempType.GetGenericTypeDefinition() == typeof(Extensible<>)) {
  812. clrBaseType = tempType.GetGenericArguments()[0];
  813. break;
  814. }
  815. tempType = tempType.GetTypeInfo().BaseType;
  816. }
  817. PythonType baseType = DynamicHelpers.GetPythonTypeFromType(clrBaseType);
  818. if (info.InterfaceTypes.Count == 0) {
  819. res.Add(baseType);
  820. } else if (info.InterfaceTypes.Count > 0) {
  821. PythonType[] types = new PythonType[info.InterfaceTypes.Count + 1];
  822. types[0] = baseType;
  823. for (int i = 0; i < info.InterfaceTypes.Count; i++) {
  824. types[i + 1] = DynamicHelpers.GetPythonTypeFromType(info.InterfaceTypes[i]);
  825. }
  826. res.Add(PythonTuple.MakeTuple(types));
  827. }
  828. }
  829. return PythonTuple.MakeTuple(res.ToArray());
  830. }
  831. /// <summary>
  832. /// Provides a StreamContentProvider for a stream of content backed by a file on disk.
  833. /// </summary>
  834. [Serializable]
  835. internal sealed class FileStreamContentProvider : StreamContentProvider {
  836. private readonly string _path;
  837. private readonly PALHolder _pal;
  838. internal string Path {
  839. get { return _path; }
  840. }
  841. #region Construction
  842. internal FileStreamContentProvider(PlatformAdaptationLayer manager, string path) {
  843. ContractUtils.RequiresNotNull(path, "path");
  844. _path = path;
  845. _pal = new PALHolder(manager);
  846. }
  847. #endregion
  848. public override Stream GetStream() {
  849. return _pal.GetStream(Path);
  850. }
  851. [Serializable]
  852. private class PALHolder : MarshalByRefObject {
  853. [NonSerialized]
  854. private readonly PlatformAdaptationLayer _pal;
  855. internal PALHolder(PlatformAdaptationLayer pal) {
  856. _pal = pal;
  857. }
  858. internal Stream GetStream(string path) {
  859. return _pal.OpenInputFileStream(path);
  860. }
  861. }
  862. }
  863. /// <summary>
  864. /// Goes through the list of files identifying the relationship between packages
  865. /// and subpackages. Returns a dictionary with all of the package filenames (minus __init__.py)
  866. /// mapping to their full name. For example given a structure:
  867. ///
  868. /// C:\
  869. /// someDir\
  870. /// package\
  871. /// __init__.py
  872. /// a.py
  873. /// b\
  874. /// __init.py
  875. /// c.py
  876. ///
  877. /// Returns:
  878. /// {r'C:\somedir\package' : 'package', r'C:\somedir\package\b', 'package.b'}
  879. ///
  880. /// This can then be used for calculating the full module name of individual files
  881. /// and packages. For example a's full name is "package.a" and c's full name is
  882. /// "package.b.c".
  883. /// </summary>
  884. private static Dictionary<string/*!*/, string/*!*/>/*!*/ BuildPackageMap(string/*!*/[]/*!*/ filenames) {
  885. // modules which are the children of packages should have the __name__
  886. // package.subpackage.modulename, not just modulename. So first
  887. // we need to get a list of all the modules...
  888. List<string> modules = new List<string>();
  889. foreach (string filename in filenames) {
  890. if (filename.EndsWith("__init__.py")) {
  891. // this is a package
  892. modules.Add(filename);
  893. }
  894. }
  895. // next we need to understand the relationship between the packages so
  896. // if we have package.subpackage1 and package.subpackage2 we know
  897. // both of these are children of the package. So sort the module names,
  898. // shortest name first...
  899. SortModules(modules);
  900. // finally build up the package names for the dirs...
  901. Dictionary<string, string> packageMap = new Dictionary<string, string>();
  902. foreach (string packageName in modules) {
  903. string dirName = Path.GetDirectoryName(packageName); // remove __init__.py
  904. string pkgName = String.Empty;
  905. string fullName = Path.GetFileName(Path.GetDirectoryName(packageName));
  906. if (packageMap.TryGetValue(Path.GetDirectoryName(dirName), out pkgName)) { // remove directory name
  907. fullName = pkgName + "." + fullName;
  908. }
  909. packageMap[Path.GetDirectoryName(packageName)] = fullName;
  910. }
  911. return packageMap;
  912. }
  913. private static void SortModules(List<string> modules) {
  914. modules.Sort((string x, string y) => x.Length - y.Length);
  915. }
  916. /// <summary>
  917. /// Returns a list of profile data. The values are tuples of Profiler.Data objects
  918. ///
  919. /// All times are expressed in the same unit of measure as DateTime.Ticks
  920. /// </summary>
  921. public static PythonTuple GetProfilerData(CodeContext/*!*/ context, [DefaultParameterValue(false)]bool includeUnused) {
  922. return new PythonTuple(Profiler.GetProfiler(PythonContext.GetContext(context)).GetProfile(includeUnused));
  923. }
  924. /// <summary>
  925. /// Resets all profiler counters back to zero
  926. /// </summary>
  927. public static void ClearProfilerData(CodeContext/*!*/ context) {
  928. Profiler.GetProfiler(PythonContext.GetContext(context)).Reset();
  929. }
  930. /// <summary>
  931. /// Enable or disable profiling for the current ScriptEngine. This will only affect code
  932. /// that is compiled after the setting is changed; previously-compiled code will retain
  933. /// whatever setting was active when the code was originally compiled.
  934. ///
  935. /// The easiest way to recompile a module is to reload() it.
  936. /// </summary>
  937. public static void EnableProfiler(CodeContext/*!*/ context, bool enable) {
  938. var pc = PythonContext.GetContext(context);
  939. var po = pc.Options as PythonOptions;
  940. po.EnableProfiler = enable;
  941. }
  942. #if FEATURE_SERIALIZATION
  943. /// <summary>
  944. /// Serializes data using the .NET serialization formatter for complex
  945. /// types. Returns a tuple identifying the serialization format and the serialized
  946. /// data which can be fed back into clr.Deserialize.
  947. ///
  948. /// Current serialization formats include custom formats for primitive .NET
  949. /// types which aren't already recognized as tuples. None is used to indicate
  950. /// that the Binary .NET formatter is used.
  951. /// </summary>
  952. public static PythonTuple/*!*/ Serialize(object self) {
  953. if (self == null) {
  954. return PythonTuple.MakeTuple(null, String.Empty);
  955. }
  956. string data, format;
  957. switch (CompilerHelpers.GetType(self).GetTypeCode()) {
  958. // for the primitive non-python types just do a simple
  959. // serialization
  960. case TypeCode.Byte:
  961. case TypeCode.Char:
  962. case TypeCode.DBNull:
  963. case TypeCode.Decimal:
  964. case TypeCode.Int16:
  965. case TypeCode.Int64:
  966. case TypeCode.SByte:
  967. case TypeCode.Single:
  968. case TypeCode.UInt16:
  969. case TypeCode.UInt32:
  970. case TypeCode.UInt64:
  971. data = self.ToString();
  972. format = CompilerHelpers.GetType(self).FullName;
  973. break;
  974. default:
  975. // something more complex, let the binary formatter handle it
  976. BinaryFormatter bf = new BinaryFormatter();
  977. MemoryStream stream = new MemoryStream();
  978. bf.Serialize(stream, self);
  979. data = stream.ToArray().MakeString();
  980. format = null;
  981. break;
  982. }
  983. return PythonTuple.MakeTuple(format, data);
  984. }
  985. /// <summary>
  986. /// Deserializes the result of a Serialize call. This can be used to perform serialization
  987. /// for .NET types which are serializable. This method is the callable object provided
  988. /// from __reduce_ex__ for .serializable .NET types.
  989. ///
  990. /// The first parameter indicates the serialization format and is the first tuple element
  991. /// returned from the Serialize call.
  992. ///
  993. /// The second parameter is the serialized data.
  994. /// </summary>
  995. public static object Deserialize(string serializationFormat, [NotNull]string/*!*/ data) {
  996. if (serializationFormat != null) {
  997. switch (serializationFormat) {
  998. case "System.Byte": return Byte.Parse(data);
  999. case "System.Char": return Char.Parse(data);
  1000. case "System.DBNull": return DBNull.Value;
  1001. case "System.Decimal": return Decimal.Parse(data);
  1002. case "System.Int16": return Int16.Parse(data);
  1003. case "System.Int64": return Int64.Parse(data);
  1004. case "System.SByte": return SByte.Parse(data);
  1005. case "System.Single": return Single.Parse(data);
  1006. case "System.UInt16": return UInt16.Parse(data);
  1007. case "System.UInt32": return UInt32.Parse(data);
  1008. case "System.UInt64": return UInt64.Parse(data);
  1009. default:
  1010. throw PythonOps.ValueError("unknown serialization format: {0}", serializationFormat);
  1011. }
  1012. } else if (String.IsNullOrEmpty(data)) {
  1013. return n

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