PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/DICK.B1/IronPython/Runtime/ClrModule.cs

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