forked from dynamicexpresso/DynamicExpresso
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMethodResolution.cs
More file actions
354 lines (295 loc) · 10.8 KB
/
MethodResolution.cs
File metadata and controls
354 lines (295 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security;
using DynamicExpresso.Exceptions;
using DynamicExpresso.Parsing;
using DynamicExpresso.Reflection;
using DynamicExpresso.Resources;
namespace DynamicExpresso.Resolution
{
internal static class MethodResolution
{
public static IList<MethodData> FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args)
{
return FindBestMethod(methods.Select(MethodData.Gen), args);
}
public static IList<MethodData> FindBestMethod(IEnumerable<MethodData> methods, Expression[] args)
{
var applicable = new List<MethodData>();
foreach (var method in methods)
{
if (CheckIfMethodIsApplicableAndPrepareIt(method, args))
applicable.Add(method);
}
if (applicable.Count > 1)
{
var bestCandidates = new List<MethodData>(applicable.Count);
foreach (var candidate in applicable)
{
if (IsBetterThanAllCandidates(candidate, applicable, args))
bestCandidates.Add(candidate);
}
// bestCandidates.Count == 0 means that no applicable method has priority
// we don't return bestCandidates to prevent callers from thinking no method was found
if (bestCandidates.Count > 0)
return bestCandidates;
}
return applicable;
}
private static bool IsBetterThanAllCandidates(MethodData candidate, IList<MethodData> otherCandidates, Expression[] args)
{
foreach (var other in otherCandidates)
{
if (candidate != other && !MethodHasPriority(args, candidate, other))
return false;
}
return true;
}
public static bool CheckIfMethodIsApplicableAndPrepareIt(MethodData method, Expression[] args)
{
if (method.Parameters.Count(y => !y.HasDefaultValue && !ReflectionExtensions.HasParamsArrayType(y)) > args.Length)
return false;
var promotedArgs = new List<Expression>(method.Parameters.Count);
var declaredWorkingParameters = 0;
Type paramsArrayTypeFound = null;
List<Expression> paramsArrayPromotedArgument = null;
foreach (var currentArgument in args)
{
Type parameterType;
if (paramsArrayTypeFound != null)
{
parameterType = paramsArrayTypeFound;
}
else
{
if (declaredWorkingParameters >= method.Parameters.Count)
{
return false;
}
var parameterDeclaration = method.Parameters[declaredWorkingParameters];
if (parameterDeclaration.IsOut)
{
return false;
}
parameterType = parameterDeclaration.ParameterType;
if (ReflectionExtensions.HasParamsArrayType(parameterDeclaration))
{
paramsArrayTypeFound = parameterType;
}
declaredWorkingParameters++;
}
if (paramsArrayPromotedArgument == null && (paramsArrayTypeFound == null || args.Length == method.Parameters.Count))
{
if (parameterType.IsGenericParameter)
{
// an interpreter expression can only be matched to a parameter of type Func
if (currentArgument is InterpreterExpression)
return false;
promotedArgs.Add(currentArgument);
continue;
}
var promoted = ExpressionUtils.PromoteExpression(currentArgument, parameterType);
if (promoted != null)
{
promotedArgs.Add(promoted);
continue;
}
}
if (paramsArrayTypeFound != null)
{
var paramsArrayElementType = paramsArrayTypeFound.GetElementType();
if (paramsArrayElementType.IsGenericParameter)
{
paramsArrayPromotedArgument = paramsArrayPromotedArgument ?? new List<Expression>();
paramsArrayPromotedArgument.Add(currentArgument);
continue;
}
var promoted = ExpressionUtils.PromoteExpression(currentArgument, paramsArrayElementType);
if (promoted != null)
{
paramsArrayPromotedArgument = paramsArrayPromotedArgument ?? new List<Expression>();
paramsArrayPromotedArgument.Add(promoted);
continue;
}
}
return false;
}
if (paramsArrayPromotedArgument != null)
{
method.HasParamsArray = true;
var paramsArrayElementType = paramsArrayTypeFound.GetElementType();
if (paramsArrayElementType == null)
throw ParseException.Create(-1, ErrorMessages.ParamsArrayTypeNotAnArray);
if (paramsArrayElementType.IsGenericParameter)
{
var actualTypes = paramsArrayPromotedArgument.Select(_ => _.Type).Distinct().ToArray();
if (actualTypes.Length != 1)
throw ParseException.Create(-1, ErrorMessages.MethodTypeParametersCantBeInferred, method.MethodBase);
paramsArrayElementType = actualTypes[0];
}
promotedArgs.Add(Expression.NewArrayInit(paramsArrayElementType, paramsArrayPromotedArgument));
}
// Add default params, if needed.
foreach (var parameter in method.Parameters.Skip(promotedArgs.Count))
{
if (parameter.HasDefaultValue)
{
var parameterType = TypeUtils.GetConcreteTypeForGenericMethod(parameter.ParameterType, promotedArgs, method);
var defaultValue = parameter.DefaultValue;
if (defaultValue is null && parameterType.IsValueType)
defaultValue = Activator.CreateInstance(parameterType);
promotedArgs.Add(Expression.Constant(defaultValue, parameterType));
}
else if (ReflectionExtensions.HasParamsArrayType(parameter))
{
method.HasParamsArray = true;
promotedArgs.Add(Expression.NewArrayInit(parameter.ParameterType.GetElementType()));
}
else
{
throw new Exception("No default value found!");
}
}
method.PromotedParameters = promotedArgs;
if (method.MethodBase != null && method.MethodBase.IsGenericMethodDefinition &&
method.MethodBase is MethodInfo)
{
var genericMethod = MakeGenericMethod(method);
if (genericMethod == null)
return false;
// we have all the type information we can get, update interpreter expressions and evaluate them
var actualMethodParameters = genericMethod.GetParameters();
for (var i = 0; i < method.PromotedParameters.Count; i++)
{
if (method.PromotedParameters[i] is InterpreterExpression ie)
{
var actualParamInfo = actualMethodParameters[i];
var lambdaExpr = ie.EvalAs(actualParamInfo.ParameterType);
if (lambdaExpr == null)
return false;
method.PromotedParameters[i] = lambdaExpr;
// we have inferred all types, update the method definition
genericMethod = MakeGenericMethod(method);
}
}
method.MethodBase = genericMethod;
}
return true;
}
private static bool MethodHasPriority(Expression[] args, MethodData method, MethodData otherMethod)
{
var better = false;
// check conversion from argument list to parameter list
for (int i = 0, m = 0, o = 0; i < args.Length; i++)
{
var arg = args[i];
var methodParam = method.Parameters[m];
var otherMethodParam = otherMethod.Parameters[o];
var methodParamType = ReflectionExtensions.GetParameterType(methodParam);
var otherMethodParamType = ReflectionExtensions.GetParameterType(otherMethodParam);
if (methodParamType.ContainsGenericParameters)
methodParamType = method.PromotedParameters[i].Type;
if (otherMethodParamType.ContainsGenericParameters)
otherMethodParamType = otherMethod.PromotedParameters[i].Type;
var c = TypeUtils.CompareConversions(arg.Type, methodParamType, otherMethodParamType);
if (c < 0)
return false;
if (c > 0)
better = true;
if (!ReflectionExtensions.HasParamsArrayType(methodParam)) m++;
if (!ReflectionExtensions.HasParamsArrayType(otherMethodParam)) o++;
}
if (better)
return true;
if (method.MethodBase != null &&
otherMethod.MethodBase != null &&
!method.MethodBase.IsGenericMethod &&
otherMethod.MethodBase.IsGenericMethod)
return true;
if (!method.HasParamsArray && otherMethod.HasParamsArray)
return true;
// if a method has a params parameter, it can have less parameters than the number of arguments
if (method.HasParamsArray && otherMethod.HasParamsArray && method.Parameters.Count > otherMethod.Parameters.Count)
return true;
if (method is IndexerData indexer && otherMethod is IndexerData otherIndexer)
{
var declaringType = indexer.Indexer.DeclaringType;
var otherDeclaringType = otherIndexer.Indexer.DeclaringType;
var isOtherIndexerIsInParentType = otherDeclaringType.IsAssignableFrom(declaringType);
if (isOtherIndexerIsInParentType)
{
var isIndexerIsInDescendantType = !declaringType.IsAssignableFrom(otherDeclaringType);
return isIndexerIsInDescendantType;
}
}
return better;
}
private static MethodInfo MakeGenericMethod(MethodData method)
{
var methodInfo = (MethodInfo)method.MethodBase;
var actualGenericArgs = ExtractActualGenericArguments(
method.Parameters.Select(p => p.ParameterType).ToArray(),
method.PromotedParameters.Select(p => p.Type).ToArray());
var genericArgs = methodInfo.GetGenericArguments()
.Select(p => actualGenericArgs.TryGetValue(p.Name, out var typ) ? typ : typeof(object))
.ToArray();
MethodInfo genericMethod = null;
try
{
genericMethod = methodInfo.MakeGenericMethod(genericArgs);
}
catch (ArgumentException e) when (e.InnerException is VerificationException)
{
// this exception is thrown when a generic argument violates the generic constraints
return null;
}
return genericMethod;
}
private static Dictionary<string, Type> ExtractActualGenericArguments(
Type[] methodGenericParameters,
Type[] methodActualParameters)
{
var extractedGenericTypes = new Dictionary<string, Type>();
for (var i = 0; i < methodGenericParameters.Length; i++)
{
var requestedType = methodGenericParameters[i];
var actualType = methodActualParameters[i];
if (requestedType.IsGenericParameter)
{
if (!actualType.IsGenericParameter)
extractedGenericTypes[requestedType.Name] = actualType;
}
else if (requestedType.IsArray && actualType.IsArray)
{
var innerGenericTypes = ExtractActualGenericArguments(
new[] { requestedType.GetElementType() },
new[] { actualType.GetElementType()
});
foreach (var innerGenericType in innerGenericTypes)
extractedGenericTypes[innerGenericType.Key] = innerGenericType.Value;
}
else if (requestedType.ContainsGenericParameters)
{
if (actualType.IsGenericParameter)
{
extractedGenericTypes[actualType.Name] = requestedType;
}
else
{
var requestedInnerGenericArgs = requestedType.GetGenericArguments();
var actualInnerGenericArgs = actualType.GetGenericArguments();
if (requestedInnerGenericArgs.Length != actualInnerGenericArgs.Length)
continue;
var innerGenericTypes = ExtractActualGenericArguments(requestedInnerGenericArgs, actualInnerGenericArgs);
foreach (var innerGenericType in innerGenericTypes)
extractedGenericTypes[innerGenericType.Key] = innerGenericType.Value;
}
}
}
return extractedGenericTypes;
}
}
}