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

/Microsoft.Scripting/Actions/DefaultBinder.Invoke.cs

https://bitbucket.org/stefanrusek/xronos
C# | 309 lines | 199 code | 42 blank | 68 comment | 23 complexity | 4e9802fd3599dfafdfdba0d952596a97 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 CODEPLEX_40
  16. using System;
  17. #else
  18. using System; using Microsoft;
  19. #endif
  20. using System.Collections.Generic;
  21. using System.Diagnostics;
  22. #if CODEPLEX_40
  23. using System.Linq.Expressions;
  24. #else
  25. using Microsoft.Linq.Expressions;
  26. #endif
  27. using System.Reflection;
  28. #if CODEPLEX_40
  29. using System.Dynamic;
  30. #else
  31. using Microsoft.Scripting;
  32. #endif
  33. using Microsoft.Scripting.Generation;
  34. using Microsoft.Scripting.Runtime;
  35. using Microsoft.Scripting.Utils;
  36. using Microsoft.Scripting.Actions.Calls;
  37. using AstUtils = Microsoft.Scripting.Ast.Utils;
  38. namespace Microsoft.Scripting.Actions {
  39. #if CODEPLEX_40
  40. using Ast = System.Linq.Expressions.Expression;
  41. #else
  42. using Ast = Microsoft.Linq.Expressions.Expression;
  43. #endif
  44. public partial class DefaultBinder : ActionBinder {
  45. /// <summary>
  46. /// Provides default binding for performing a call on the specified meta objects.
  47. /// </summary>
  48. /// <param name="signature">The signature describing the call</param>
  49. /// <param name="target">The object to be called</param>
  50. /// <param name="args">
  51. /// Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction.
  52. /// </param>
  53. /// <returns>A MetaObject representing the call or the error.</returns>
  54. public DynamicMetaObject Call(CallSignature signature, DynamicMetaObject target, params DynamicMetaObject[] args) {
  55. return Call(signature, new ParameterBinder(this), target, args);
  56. }
  57. /// <summary>
  58. /// Provides default binding for performing a call on the specified meta objects.
  59. /// </summary>
  60. /// <param name="signature">The signature describing the call</param>
  61. /// <param name="target">The meta object to be called.</param>
  62. /// <param name="args">
  63. /// Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction.
  64. /// </param>
  65. /// <param name="parameterBinder">ParameterBinder used to map arguments to parameters.</param>
  66. /// <returns>A MetaObject representing the call or the error.</returns>
  67. public DynamicMetaObject Call(CallSignature signature, ParameterBinder parameterBinder, DynamicMetaObject target, params DynamicMetaObject[] args) {
  68. ContractUtils.RequiresNotNullItems(args, "args");
  69. ContractUtils.RequiresNotNull(parameterBinder, "parameterBinder");
  70. TargetInfo targetInfo = GetTargetInfo(signature, target, args);
  71. if (targetInfo != null) {
  72. // we're calling a well-known MethodBase
  73. return MakeMetaMethodCall(signature, parameterBinder, targetInfo);
  74. } else {
  75. // we can't call this object
  76. return MakeCannotCallRule(target, target.GetLimitType());
  77. }
  78. }
  79. #region Method Call Rule
  80. private DynamicMetaObject MakeMetaMethodCall(CallSignature signature, ParameterBinder parameterBinder, TargetInfo targetInfo) {
  81. BindingRestrictions restrictions = BindingRestrictions.Combine(targetInfo.Arguments).Merge(targetInfo.Restrictions);
  82. if (targetInfo.Instance != null) {
  83. restrictions = targetInfo.Instance.Restrictions.Merge(restrictions);
  84. }
  85. if (targetInfo.Instance != null) {
  86. return CallInstanceMethod(
  87. parameterBinder,
  88. targetInfo.Targets,
  89. targetInfo.Instance,
  90. targetInfo.Arguments,
  91. signature,
  92. restrictions
  93. );
  94. }
  95. return CallMethod(
  96. parameterBinder,
  97. targetInfo.Targets,
  98. targetInfo.Arguments,
  99. signature,
  100. restrictions);
  101. }
  102. #endregion
  103. #region Target acquisition
  104. /// <summary>
  105. /// Gets a TargetInfo object for performing a call on this object.
  106. ///
  107. /// If this object is a delegate we bind to the Invoke method.
  108. /// If this object is a MemberGroup or MethodGroup we bind to the methods in the member group.
  109. /// If this object is a BoundMemberTracker we bind to the methods with the bound instance.
  110. /// If the underlying type has defined an operator Call method we'll bind to that method.
  111. /// </summary>
  112. private TargetInfo GetTargetInfo(CallSignature signature, DynamicMetaObject target, DynamicMetaObject[] args) {
  113. Debug.Assert(target.HasValue);
  114. object objTarget = target.Value;
  115. return
  116. TryGetDelegateTargets(target, args, objTarget as Delegate) ??
  117. TryGetMemberGroupTargets(target, args, objTarget as MemberGroup) ??
  118. TryGetMethodGroupTargets(target, args, objTarget as MethodGroup) ??
  119. TryGetBoundMemberTargets(target, args, objTarget as BoundMemberTracker) ??
  120. TryGetOperatorTargets(target, args, target, signature);
  121. }
  122. /// <summary>
  123. /// Binds to the methods in a method group.
  124. /// </summary>
  125. private static TargetInfo TryGetMethodGroupTargets(DynamicMetaObject target, DynamicMetaObject[] args, MethodGroup mthgrp) {
  126. if (mthgrp != null) {
  127. List<MethodBase> foundTargets = new List<MethodBase>();
  128. foreach (MethodTracker mt in mthgrp.Methods) {
  129. foundTargets.Add(mt.Method);
  130. }
  131. return new TargetInfo(null, ArrayUtils.Insert(target, args), BindingRestrictions.GetInstanceRestriction(target.Expression, mthgrp), foundTargets.ToArray());
  132. }
  133. return null;
  134. }
  135. /// <summary>
  136. /// Binds to the methods in a member group.
  137. ///
  138. /// TODO: We should really only have either MemberGroup or MethodGroup, not both.
  139. /// </summary>
  140. private static TargetInfo TryGetMemberGroupTargets(DynamicMetaObject target, DynamicMetaObject[] args, MemberGroup mg) {
  141. if (mg != null) {
  142. MethodBase[] targets;
  143. List<MethodInfo> foundTargets = new List<MethodInfo>();
  144. foreach (MemberTracker mt in mg) {
  145. if (mt.MemberType == TrackerTypes.Method) {
  146. foundTargets.Add(((MethodTracker)mt).Method);
  147. }
  148. }
  149. targets = foundTargets.ToArray();
  150. return new TargetInfo(null, ArrayUtils.Insert(target, args), targets);
  151. }
  152. return null;
  153. }
  154. /// <summary>
  155. /// Binds to the BoundMemberTracker and uses the instance in the tracker and restricts
  156. /// based upon the object instance type.
  157. /// </summary>
  158. private TargetInfo TryGetBoundMemberTargets(DynamicMetaObject self, DynamicMetaObject[] args, BoundMemberTracker bmt) {
  159. if (bmt != null) {
  160. Debug.Assert(bmt.Instance == null); // should be null for trackers that leak to user code
  161. MethodBase[] targets;
  162. // instance is pulled from the BoundMemberTracker and restricted to the correct
  163. // type.
  164. DynamicMetaObject instance = new DynamicMetaObject(
  165. AstUtils.Convert(
  166. Ast.Property(
  167. Ast.Convert(self.Expression, typeof(BoundMemberTracker)),
  168. typeof(BoundMemberTracker).GetProperty("ObjectInstance")
  169. ),
  170. bmt.BoundTo.DeclaringType
  171. ),
  172. self.Restrictions
  173. ).Restrict(CompilerHelpers.GetType(bmt.ObjectInstance));
  174. // we also add a restriction to make sure we're going to the same BoundMemberTracker
  175. BindingRestrictions restrictions = BindingRestrictions.GetExpressionRestriction(
  176. Ast.Equal(
  177. Ast.Property(
  178. Ast.Convert(self.Expression, typeof(BoundMemberTracker)),
  179. typeof(BoundMemberTracker).GetProperty("BoundTo")
  180. ),
  181. AstUtils.Constant(bmt.BoundTo)
  182. )
  183. );
  184. switch (bmt.BoundTo.MemberType) {
  185. case TrackerTypes.MethodGroup:
  186. targets = ((MethodGroup)bmt.BoundTo).GetMethodBases();
  187. break;
  188. case TrackerTypes.Method:
  189. targets = new MethodBase[] { ((MethodTracker)bmt.BoundTo).Method };
  190. break;
  191. default:
  192. throw new InvalidOperationException(); // nothing else binds yet
  193. }
  194. return new TargetInfo(instance, args, restrictions, targets);
  195. }
  196. return null;
  197. }
  198. /// <summary>
  199. /// Binds to the Invoke method on a delegate if this is a delegate type.
  200. /// </summary>
  201. private static TargetInfo TryGetDelegateTargets(DynamicMetaObject target, DynamicMetaObject[] args, Delegate d) {
  202. if (d != null) {
  203. return new TargetInfo(target, args, d.GetType().GetMethod("Invoke"));
  204. }
  205. return null;
  206. }
  207. /// <summary>
  208. /// Attempts to bind to an operator Call method.
  209. /// </summary>
  210. private TargetInfo TryGetOperatorTargets(DynamicMetaObject self, DynamicMetaObject[] args, object target, CallSignature signature) {
  211. MethodBase[] targets;
  212. Type targetType = CompilerHelpers.GetType(target);
  213. MemberGroup callMembers = GetMember(OldCallAction.Make(this, signature), targetType, "Call");
  214. List<MethodBase> callTargets = new List<MethodBase>();
  215. foreach (MemberTracker mi in callMembers) {
  216. if (mi.MemberType == TrackerTypes.Method) {
  217. MethodInfo method = ((MethodTracker)mi).Method;
  218. if (method.IsSpecialName) {
  219. callTargets.Add(method);
  220. }
  221. }
  222. }
  223. Expression instance = null;
  224. if (callTargets.Count > 0) {
  225. targets = callTargets.ToArray();
  226. instance = Ast.Convert(self.Expression, CompilerHelpers.GetType(target));
  227. return new TargetInfo(null, ArrayUtils.Insert(self, args), targets);
  228. }
  229. return null;
  230. }
  231. #endregion
  232. #region Error support
  233. private DynamicMetaObject MakeCannotCallRule(DynamicMetaObject self, Type type) {
  234. return MakeError(
  235. ErrorInfo.FromException(
  236. Ast.New(
  237. typeof(ArgumentTypeException).GetConstructor(new Type[] { typeof(string) }),
  238. AstUtils.Constant(type.Name + " is not callable")
  239. )
  240. ),
  241. self.Restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, type))
  242. );
  243. }
  244. #endregion
  245. /// <summary>
  246. /// Encapsulates information about the target of the call. This includes an implicit instance for the call,
  247. /// the methods that we'll be calling as well as any restrictions required to perform the call.
  248. /// </summary>
  249. class TargetInfo {
  250. public readonly DynamicMetaObject Instance;
  251. public readonly DynamicMetaObject[] Arguments;
  252. public readonly MethodBase[] Targets;
  253. public readonly BindingRestrictions Restrictions;
  254. public TargetInfo(DynamicMetaObject instance, DynamicMetaObject[] arguments, params MethodBase[] args) :
  255. this(instance, arguments, BindingRestrictions.Empty, args) {
  256. }
  257. public TargetInfo(DynamicMetaObject instance, DynamicMetaObject[] arguments, BindingRestrictions restrictions, params MethodBase[] targets) {
  258. Assert.NotNullItems(targets);
  259. Assert.NotNull(restrictions);
  260. Instance = instance;
  261. Arguments = arguments;
  262. Targets = targets;
  263. Restrictions = restrictions;
  264. }
  265. }
  266. }
  267. }