This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathExpressionHelper.cs
208 lines (178 loc) · 7.65 KB
/
ExpressionHelper.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal
{
public static class ExpressionHelper
{
public static string GetExpressionText(string expression)
{
// If it's exactly "model", then give them an empty string, to replicate the lambda behavior.
return string.Equals(expression, "model", StringComparison.OrdinalIgnoreCase) ? string.Empty : expression;
}
public static string GetExpressionText(LambdaExpression expression)
{
return GetExpressionText(expression, expressionTextCache: null);
}
public static string GetExpressionText(LambdaExpression expression, ExpressionTextCache expressionTextCache)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
string expressionText;
if (expressionTextCache != null &&
expressionTextCache.Entries.TryGetValue(expression, out expressionText))
{
return expressionText;
}
var containsIndexers = false;
var part = expression.Body;
// Builder to concatenate the names for property/field accessors within an expression to create a string.
var builder = new StringBuilder();
while (part != null)
{
if (part.NodeType == ExpressionType.Call)
{
containsIndexers = true;
var methodExpression = (MethodCallExpression)part;
if (!IsSingleArgumentIndexer(methodExpression))
{
// Unsupported.
break;
}
InsertIndexerInvocationText(
builder,
methodExpression.Arguments.Single(),
expression);
part = methodExpression.Object;
}
else if (part.NodeType == ExpressionType.ArrayIndex)
{
containsIndexers = true;
var binaryExpression = (BinaryExpression)part;
InsertIndexerInvocationText(
builder,
binaryExpression.Right,
expression);
part = binaryExpression.Left;
}
else if (part.NodeType == ExpressionType.MemberAccess)
{
var memberExpressionPart = (MemberExpression)part;
var name = memberExpressionPart.Member.Name;
// If identifier contains "__", it is "reserved for use by the implementation" and likely compiler-
// or Razor-generated e.g. the name of a field in a delegate's generated class.
if (name.Contains("__"))
{
// Exit loop. Should have the entire name because previous MemberAccess has same name as the
// leftmost expression node (a variable).
break;
}
builder.Insert(0, name);
builder.Insert(0, '.');
part = memberExpressionPart.Expression;
}
else
{
break;
}
}
// If parts start with "model", then strip that part away.
if (part == null || part.NodeType != ExpressionType.Parameter)
{
var text = builder.ToString();
if (text.StartsWith(".model", StringComparison.OrdinalIgnoreCase))
{
// 6 is the length of the string ".model".
builder.Remove(0, 6);
}
}
if (builder.Length > 0)
{
// Trim the leading "." if present.
builder.Replace(".", string.Empty, 0, 1);
}
expressionText = builder.ToString();
if (expressionTextCache != null && !containsIndexers)
{
expressionTextCache.Entries.TryAdd(expression, expressionText);
}
return expressionText;
}
private static void InsertIndexerInvocationText(
StringBuilder builder,
Expression indexExpression,
LambdaExpression parentExpression)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (indexExpression == null)
{
throw new ArgumentNullException(nameof(indexExpression));
}
if (parentExpression == null)
{
throw new ArgumentNullException(nameof(parentExpression));
}
if (parentExpression.Parameters == null)
{
throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull(
nameof(parentExpression.Parameters),
nameof(parentExpression)));
}
var converted = Expression.Convert(indexExpression, typeof(object));
var fakeParameter = Expression.Parameter(typeof(object), null);
var lambda = Expression.Lambda<Func<object, object>>(converted, fakeParameter);
Func<object, object> func;
try
{
func = CachedExpressionCompiler.Process(lambda);
}
catch (InvalidOperationException ex)
{
var parameters = parentExpression.Parameters.ToArray();
throw new InvalidOperationException(
Resources.FormatExpressionHelper_InvalidIndexerExpression(indexExpression, parameters[0].Name),
ex);
}
builder.Insert(0, ']');
builder.Insert(0, Convert.ToString(func(null), CultureInfo.InvariantCulture));
builder.Insert(0, '[');
}
public static bool IsSingleArgumentIndexer(Expression expression)
{
var methodExpression = expression as MethodCallExpression;
if (methodExpression == null || methodExpression.Arguments.Count != 1)
{
return false;
}
// Check whether GetDefaultMembers() (if present in CoreCLR) would return a member of this type. Compiler
// names the indexer property, if any, in a generated [DefaultMember] attribute for the containing type.
var declaringType = methodExpression.Method.DeclaringType;
var defaultMember = declaringType.GetTypeInfo().GetCustomAttribute<DefaultMemberAttribute>(inherit: true);
if (defaultMember == null)
{
return false;
}
// Find default property (the indexer) and confirm its getter is the method in this expression.
var runtimeProperties = declaringType.GetRuntimeProperties();
foreach (var property in runtimeProperties)
{
if ((string.Equals(defaultMember.MemberName, property.Name, StringComparison.Ordinal) &&
property.GetMethod == methodExpression.Method))
{
return true;
}
}
return false;
}
}
}