PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

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