PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/Merlin/Main/Languages/IronPython/IronPython/Runtime/Operations/UserTypeOps.cs

https://github.com/xerxesb/ironruby
C# | 431 lines | 329 code | 68 blank | 34 comment | 103 complexity | 8a06bb343f53d01f77cb1c67f9e9dd41 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. #if !CLR2
  16. using System.Linq.Expressions;
  17. #else
  18. using Microsoft.Scripting.Ast;
  19. #endif
  20. using System;
  21. using System.Diagnostics;
  22. using System.Dynamic;
  23. using System.Runtime.CompilerServices;
  24. using System.Threading;
  25. using Microsoft.Scripting;
  26. using Microsoft.Scripting.Generation;
  27. using Microsoft.Scripting.Runtime;
  28. using Microsoft.Scripting.Utils;
  29. using IronPython.Runtime.Types;
  30. using IronPython.Runtime.Binding;
  31. namespace IronPython.Runtime.Operations {
  32. // These operations get linked into all new-style classes.
  33. public static class UserTypeOps {
  34. public static string ToStringReturnHelper(object o) {
  35. if (o is string && o != null) {
  36. return (string)o;
  37. }
  38. throw PythonOps.TypeError("__str__ returned non-string type ({0})", PythonTypeOps.GetName(o));
  39. }
  40. public static PythonDictionary SetDictHelper(ref PythonDictionary dict, PythonDictionary value) {
  41. if (System.Threading.Interlocked.CompareExchange<PythonDictionary>(ref dict, value, null) == null)
  42. return value;
  43. return dict;
  44. }
  45. public static object GetPropertyHelper(object prop, object instance, string name) {
  46. PythonTypeSlot desc = prop as PythonTypeSlot;
  47. if (desc == null) {
  48. throw PythonOps.TypeError("Expected property for {0}, but found {1}",
  49. name.ToString(), DynamicHelpers.GetPythonType(prop).Name);
  50. }
  51. object value;
  52. desc.TryGetValue(DefaultContext.Default, instance, DynamicHelpers.GetPythonType(instance), out value);
  53. return value;
  54. }
  55. public static void SetPropertyHelper(object prop, object instance, object newValue, string name) {
  56. PythonTypeSlot desc = prop as PythonTypeSlot;
  57. if (desc == null) {
  58. throw PythonOps.TypeError("Expected settable property for {0}, but found {1}",
  59. name.ToString(), DynamicHelpers.GetPythonType(prop).Name);
  60. }
  61. desc.TrySetValue(DefaultContext.Default, instance, DynamicHelpers.GetPythonType(instance), newValue);
  62. }
  63. public static bool SetWeakRefHelper(IPythonObject obj, WeakRefTracker value) {
  64. if (!obj.PythonType.IsWeakReferencable) {
  65. return false;
  66. }
  67. object[] slots = obj.GetSlotsCreate();
  68. slots[slots.Length - 1] = value;
  69. return true;
  70. }
  71. public static WeakRefTracker GetWeakRefHelper(IPythonObject obj) {
  72. object[] slots = obj.GetSlots();
  73. if (slots == null) {
  74. return null;
  75. }
  76. return (WeakRefTracker)slots[slots.Length - 1];
  77. }
  78. public static void SetFinalizerHelper(IPythonObject obj, WeakRefTracker value) {
  79. object[] slots = obj.GetSlotsCreate();
  80. if (Interlocked.CompareExchange(ref slots[slots.Length - 1], value, null) != null) {
  81. GC.SuppressFinalize(value);
  82. }
  83. }
  84. public static object[] GetSlotsCreate(IPythonObject obj, ref object[] slots) {
  85. if (slots != null) {
  86. return slots;
  87. }
  88. Interlocked.CompareExchange(
  89. ref slots,
  90. new object[obj.PythonType.SlotCount + 1], // weakref is stored at the end
  91. null);
  92. return slots;
  93. }
  94. public static void AddRemoveEventHelper(object method, IPythonObject instance, object eventValue, string name) {
  95. object callable = method;
  96. // TODO: dt gives us a PythonContext which we should use
  97. PythonType dt = instance.PythonType;
  98. PythonTypeSlot dts = method as PythonTypeSlot;
  99. if (dts != null) {
  100. if (!dts.TryGetValue(DefaultContext.Default, instance, dt, out callable))
  101. throw PythonOps.AttributeErrorForMissingAttribute(dt.Name, name);
  102. }
  103. if (!PythonOps.IsCallable(DefaultContext.Default, callable)) {
  104. throw PythonOps.TypeError("Expected callable value for {0}, but found {1}", name.ToString(),
  105. PythonTypeOps.GetName(method));
  106. }
  107. PythonCalls.Call(callable, eventValue);
  108. }
  109. public static DynamicMetaObject/*!*/ GetMetaObjectHelper(IPythonObject self, Expression/*!*/ parameter, DynamicMetaObject baseMetaObject) {
  110. return new Binding.MetaUserObject(parameter, BindingRestrictions.Empty, baseMetaObject, self);
  111. }
  112. public static bool TryGetMixedNewStyleOldStyleSlot(CodeContext context, object instance, string name, out object value) {
  113. IPythonObject sdo = instance as IPythonObject;
  114. if (sdo != null) {
  115. PythonDictionary dict = sdo.Dict;
  116. if (dict != null && dict.TryGetValue(name, out value)) {
  117. return true;
  118. }
  119. }
  120. PythonType dt = DynamicHelpers.GetPythonType(instance);
  121. foreach (PythonType type in dt.ResolutionOrder) {
  122. PythonTypeSlot dts;
  123. if (type != TypeCache.Object && type.OldClass != null) {
  124. // we're an old class, check the old-class way
  125. OldClass oc = type.OldClass;
  126. if (oc.TryGetBoundCustomMember(context, name, out value)) {
  127. value = oc.GetOldStyleDescriptor(context, value, instance, oc);
  128. return true;
  129. }
  130. } else if (type.TryLookupSlot(context, name, out dts)) {
  131. // we're a dynamic type, check the dynamic type way
  132. return dts.TryGetValue(context, instance, dt, out value);
  133. }
  134. }
  135. value = null;
  136. return false;
  137. }
  138. public static object SetDictionaryValue(IPythonObject self, string name, object value) {
  139. PythonDictionary dict = GetDictionary(self);
  140. return dict[name] = value;
  141. }
  142. public static object FastSetDictionaryValue(ref PythonDictionary dict, string name, object value) {
  143. if (dict == null) {
  144. Interlocked.CompareExchange(ref dict, PythonDictionary.MakeSymbolDictionary(), null);
  145. }
  146. return dict[name] = value;
  147. }
  148. public static object RemoveDictionaryValue(IPythonObject self, string name) {
  149. PythonDictionary dict = self.Dict;
  150. if (dict != null) {
  151. if (dict.Remove(name)) {
  152. return null;
  153. }
  154. }
  155. throw PythonOps.AttributeErrorForMissingAttribute(self.PythonType, name);
  156. }
  157. internal static PythonDictionary GetDictionary(IPythonObject self) {
  158. PythonDictionary dict = self.Dict;
  159. if (dict == null && self.PythonType.HasDictionary) {
  160. dict = self.SetDict(PythonDictionary.MakeSymbolDictionary());
  161. }
  162. return dict;
  163. }
  164. /// <summary>
  165. /// Object.ToString() displays the CLI type name. But we want to display the class name (e.g.
  166. /// '&lt;foo object at 0x000000000000002C&gt;' unless we've overridden __repr__ but not __str__ in
  167. /// which case we'll display the result of __repr__.
  168. /// </summary>
  169. public static string ToStringHelper(IPythonObject o) {
  170. return ObjectOps.__str__(DefaultContext.Default, o);
  171. }
  172. public static bool TryGetNonInheritedMethodHelper(PythonType dt, object instance, string name, out object callTarget) {
  173. // search MRO for other user-types in the chain that are overriding the method
  174. foreach (PythonType type in dt.ResolutionOrder) {
  175. if (type.IsSystemType) break; // hit the .NET types, we're done
  176. if (LookupValue(type, instance, name, out callTarget)) {
  177. return true;
  178. }
  179. }
  180. // check instance
  181. IPythonObject isdo = instance as IPythonObject;
  182. PythonDictionary dict;
  183. if (isdo != null && (dict = isdo.Dict) != null) {
  184. if (dict.TryGetValue(name, out callTarget))
  185. return true;
  186. }
  187. callTarget = null;
  188. return false;
  189. }
  190. private static bool LookupValue(PythonType dt, object instance, string name, out object value) {
  191. PythonTypeSlot dts;
  192. if (dt.TryLookupSlot(DefaultContext.Default, name, out dts) &&
  193. dts.TryGetValue(DefaultContext.Default, instance, dt, out value)) {
  194. return true;
  195. }
  196. value = null;
  197. return false;
  198. }
  199. public static bool TryGetNonInheritedValueHelper(IPythonObject instance, string name, out object callTarget) {
  200. PythonType dt = instance.PythonType;
  201. PythonTypeSlot dts;
  202. // search MRO for other user-types in the chain that are overriding the method
  203. foreach (PythonType type in dt.ResolutionOrder) {
  204. if (type.IsSystemType) break; // hit the .NET types, we're done
  205. if (type.TryLookupSlot(DefaultContext.Default, name, out dts)) {
  206. callTarget = dts;
  207. return true;
  208. }
  209. }
  210. // check instance
  211. IPythonObject isdo = instance as IPythonObject;
  212. PythonDictionary dict;
  213. if (isdo != null && (dict = isdo.Dict) != null) {
  214. if (dict.TryGetValue(name, out callTarget))
  215. return true;
  216. }
  217. callTarget = null;
  218. return false;
  219. }
  220. public static object GetAttribute(CodeContext/*!*/ context, object self, string name, PythonTypeSlot getAttributeSlot, PythonTypeSlot getAttrSlot, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, string, object>>>/*!*/ callSite) {
  221. object value;
  222. if (callSite.Data == null) {
  223. callSite.Data = MakeGetAttrSite(context);
  224. }
  225. try {
  226. if (getAttributeSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) {
  227. return callSite.Data.Target(callSite.Data, context, value, name);
  228. }
  229. } catch (MissingMemberException) {
  230. if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) {
  231. return callSite.Data.Target(callSite.Data, context, value, name);
  232. }
  233. throw;
  234. }
  235. if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) {
  236. return callSite.Data.Target(callSite.Data, context, value, name);
  237. }
  238. throw PythonOps.AttributeError(name);
  239. }
  240. public static object GetAttributeNoThrow(CodeContext/*!*/ context, object self, string name, PythonTypeSlot getAttributeSlot, PythonTypeSlot getAttrSlot, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, string, object>>>/*!*/ callSite) {
  241. object value;
  242. if (callSite.Data == null) {
  243. callSite.Data = MakeGetAttrSite(context);
  244. }
  245. try {
  246. if (getAttributeSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) {
  247. return callSite.Data.Target(callSite.Data, context, value, name);
  248. }
  249. } catch (MissingMemberException) {
  250. try {
  251. if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) {
  252. return callSite.Data.Target(callSite.Data, context, value, name);
  253. }
  254. return OperationFailed.Value;
  255. } catch (MissingMemberException) {
  256. return OperationFailed.Value;
  257. }
  258. }
  259. try {
  260. if (getAttrSlot != null && getAttrSlot.TryGetValue(context, self, ((IPythonObject)self).PythonType, out value)) {
  261. return callSite.Data.Target(callSite.Data, context, value, name);
  262. }
  263. } catch (MissingMemberException) {
  264. }
  265. return OperationFailed.Value;
  266. }
  267. private static CallSite<Func<CallSite, CodeContext, object, string, object>> MakeGetAttrSite(CodeContext context) {
  268. return CallSite<Func<CallSite, CodeContext, object, string, object>>.Create(
  269. PythonContext.GetContext(context).InvokeOne
  270. );
  271. }
  272. #region IValueEquality Helpers
  273. public static int GetValueHashCodeHelper(object self) {
  274. // new-style classes only lookup in slots, not in instance
  275. // members
  276. object func;
  277. if (DynamicHelpers.GetPythonType(self).TryGetBoundMember(DefaultContext.Default, self, "__hash__", out func)) {
  278. return Converter.ConvertToInt32(PythonCalls.Call(func));
  279. }
  280. return self.GetHashCode();
  281. }
  282. public static bool ValueEqualsHelper(object self, object other) {
  283. object res = RichEqualsHelper(self, other);
  284. if (res != NotImplementedType.Value && res != null && res.GetType() == typeof(bool))
  285. return (bool)res;
  286. return false;
  287. }
  288. private static object RichEqualsHelper(object self, object other) {
  289. object res;
  290. if (PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default, self, other, "__eq__", out res))
  291. return res;
  292. return NotImplementedType.Value;
  293. }
  294. #endregion
  295. internal static Binding.FastBindResult<T> MakeGetBinding<T>(CodeContext codeContext, CallSite<T> site, IPythonObject self, Binding.PythonGetMemberBinder getBinder) where T : class {
  296. Type finalType = PythonTypeOps.GetFinalSystemType(self.PythonType.UnderlyingSystemType);
  297. if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType) &&
  298. !(self is IFastGettable)) {
  299. // very tricky, user is inheriting from a class which implements IDO, we
  300. // don't optimize this yet.
  301. return new Binding.FastBindResult<T>();
  302. }
  303. return (Binding.FastBindResult<T>)(object)new Binding.MetaUserObject.FastGetBinderHelper(
  304. codeContext,
  305. (CallSite<Func<CallSite, object, CodeContext, object>>)(object)site,
  306. self,
  307. getBinder).GetBinding(codeContext, getBinder.Name);
  308. }
  309. internal static FastBindResult<T> MakeSetBinding<T>(CodeContext codeContext, CallSite<T> site, IPythonObject self, object value, Binding.PythonSetMemberBinder setBinder) where T : class {
  310. if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(self.GetType().BaseType)) {
  311. // very tricky, user is inheriting from a class which implements IDO, we
  312. // don't optimize this yet.
  313. return new FastBindResult<T>();
  314. }
  315. // optimized versions for possible literals that can show up in code.
  316. Type setType = typeof(T);
  317. if (setType == typeof(Func<CallSite, object, object, object>)) {
  318. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<object>(
  319. codeContext,
  320. self,
  321. value,
  322. setBinder).MakeSet();
  323. } else if (setType == typeof(Func<CallSite, object, string, object>)) {
  324. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<string>(
  325. codeContext,
  326. self,
  327. value,
  328. setBinder).MakeSet();
  329. } else if (setType == typeof(Func<CallSite, object, int, object>)) {
  330. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<int>(
  331. codeContext,
  332. self,
  333. value,
  334. setBinder).MakeSet();
  335. } else if (setType == typeof(Func<CallSite, object, double, object>)) {
  336. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<double>(
  337. codeContext,
  338. self,
  339. value,
  340. setBinder).MakeSet();
  341. } else if (setType == typeof(Func<CallSite, object, List, object>)) {
  342. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<List>(
  343. codeContext,
  344. self,
  345. value,
  346. setBinder).MakeSet();
  347. } else if (setType == typeof(Func<CallSite, object, PythonTuple, object>)) {
  348. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<PythonTuple>(
  349. codeContext,
  350. self,
  351. value,
  352. setBinder).MakeSet();
  353. } else if (setType == typeof(Func<CallSite, object, PythonDictionary, object>)) {
  354. return (FastBindResult<T>)(object)new Binding.MetaUserObject.FastSetBinderHelper<PythonDictionary>(
  355. codeContext,
  356. self,
  357. value,
  358. setBinder).MakeSet();
  359. }
  360. return new FastBindResult<T>();
  361. }
  362. }
  363. }