QueryableTransformer.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //
  2. // QueryableTransformer.cs
  3. //
  4. // Authors:
  5. // Roei Erez ([email protected])
  6. //
  7. // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Linq;
  31. using System.Text;
  32. using System.Linq.Expressions;
  33. using System.Reflection;
  34. using System.Runtime.CompilerServices;
  35. using System.Collections.ObjectModel;
  36. namespace System.Linq
  37. {
  38. internal class QueryableTransformer : ExpressionTransformer
  39. {
  40. internal QueryableTransformer () {}
  41. protected override MethodCallExpression VisitMethodCall (MethodCallExpression methodCall)
  42. {
  43. if ( IsQueryableExtension ( methodCall.Method ))
  44. {
  45. return ReplaceIQueryableMethod (methodCall);
  46. }
  47. return base.VisitMethodCall (methodCall);
  48. }
  49. protected override LambdaExpression VisitLambda (LambdaExpression lambda)
  50. {
  51. return lambda;
  52. }
  53. bool IsQueryableExtension (MethodInfo method)
  54. {
  55. return method.GetCustomAttributes(typeof(ExtensionAttribute), false).Count() > 0 &&
  56. typeof(IQueryable).IsAssignableFrom( method.GetParameters () [0].ParameterType );
  57. }
  58. MethodCallExpression ReplaceIQueryableMethod (MethodCallExpression oldCall)
  59. {
  60. Expression target = null;
  61. if (oldCall.Object != null){
  62. target = Visit (oldCall.Object);
  63. }
  64. MethodInfo newMethod = ReplaceIQueryableMethodInfo(oldCall.Method);
  65. Expression [] args = new Expression [oldCall.Arguments.Count];
  66. int counter = 0;
  67. foreach (Expression e in oldCall.Arguments) {
  68. Type methodParam = newMethod.GetParameters() [counter].ParameterType;
  69. args [counter++] = ReplaceQuotedLambdaIfNeeded(Visit (e), methodParam);
  70. }
  71. ReadOnlyCollection<Expression> col = args.ToReadOnlyCollection();
  72. MethodCallExpression newMethodCall = new MethodCallExpression (target, newMethod, col);
  73. return newMethodCall;
  74. }
  75. static Expression ReplaceQuotedLambdaIfNeeded (Expression e, Type delegateType)
  76. {
  77. UnaryExpression unary = e as UnaryExpression;
  78. if (unary != null) {
  79. LambdaExpression lambda = unary.Operand as LambdaExpression;
  80. if (lambda != null && lambda.Type == delegateType)
  81. return lambda;
  82. }
  83. return e;
  84. }
  85. static MethodInfo ReplaceIQueryableMethodInfo (MethodInfo qm)
  86. {
  87. Type typeToSearch = qm.DeclaringType == typeof (Queryable) ? typeof (Enumerable) : qm.DeclaringType;
  88. MethodInfo result = GetMatchingMethod (qm, typeToSearch);
  89. if (result == null)
  90. throw new InvalidOperationException (
  91. string.Format("There is no method {0} on type {1} that matches the specified arguments",
  92. qm.Name,
  93. qm.DeclaringType.FullName));
  94. return result;
  95. }
  96. static MethodInfo GetMatchingMethod (MethodInfo qm, Type fromType)
  97. {
  98. MethodInfo result = (from em in fromType.GetMethods ()
  99. where Match (em, qm)
  100. select em)
  101. .FirstOrDefault ();
  102. if (result != null && qm.IsGenericMethod)
  103. result = result.MakeGenericMethod (qm.GetGenericArguments ());
  104. return result;
  105. }
  106. static bool Match (MethodInfo em, MethodInfo qm) {
  107. if (em.GetCustomAttributes (typeof (ExtensionAttribute), false).Count() == 0)
  108. return false;
  109. if (em.Name != qm.Name)
  110. return false;
  111. if (em.GetGenericArguments ().Length != qm.GetGenericArguments ().Length)
  112. return false;
  113. Type [] parameters = (from p in qm.GetParameters () select p.ParameterType).ToArray ();
  114. Type returnType = qm.ReturnType;
  115. if (parameters.Length != em.GetParameters ().Length)
  116. return false;
  117. MethodInfo instanceMethod = em;
  118. if (qm.IsGenericMethod) {
  119. if (!qm.IsGenericMethod)
  120. return false;
  121. if (em.GetParameters ().Length != qm.GetParameters ().Length)
  122. return false;
  123. Type [] genArgs = qm.GetGenericArguments ();
  124. instanceMethod = em.MakeGenericMethod (genArgs);
  125. }
  126. Type [] enumerableParams = (from p in instanceMethod.GetParameters () select p.ParameterType).ToArray ();
  127. if (enumerableParams [0] != ConvertParameter (parameters [0]))
  128. return false;
  129. for (int i = 1; i < enumerableParams.Length; ++i)
  130. if (!ArgumentMatch(enumerableParams [i], parameters [i]))
  131. return false;
  132. if (!ArgumentMatch(instanceMethod.ReturnType, returnType))
  133. return false;
  134. return true;
  135. }
  136. static bool ArgumentMatch (Type enumerableParam, Type queryableParam)
  137. {
  138. return enumerableParam == queryableParam || enumerableParam == ConvertParameter (queryableParam);
  139. }
  140. static Type ConvertParameter (Type type)
  141. {
  142. if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IQueryable<>))
  143. type = typeof (IEnumerable<>).MakeGenericType (type.GetGenericArguments ());
  144. else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IOrderedQueryable<>))
  145. type = typeof (IOrderedEnumerable<>).MakeGenericType (type.GetGenericArguments ());
  146. else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Expression<>))
  147. type = type.GetGenericArguments () [0];
  148. else if (type == typeof (IQueryable))
  149. type = typeof (System.Collections.IEnumerable);
  150. return type;
  151. }
  152. }
  153. }