/
CompilerServicesUtility.cs
279 lines (242 loc) · 10.7 KB
/
CompilerServicesUtility.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
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
using System.Linq;
namespace RazorEngine.Compilation
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Collections;
/// <summary>
/// Provides service methods for compilation.
/// </summary>
public static class CompilerServicesUtility
{
#region Fields
private static readonly Type DynamicType = typeof(DynamicObject);
private static readonly Type ExpandoType = typeof(ExpandoObject);
private static readonly Type EnumerableType = typeof(IEnumerable);
private static readonly Type EnumeratorType = typeof(IEnumerator);
private static readonly Type GenericEnumerableType = typeof(IEnumerable<>);
#endregion
#region Methods
/// <summary>
/// Determines if the specified type is an anonymous type.
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns>True if the type is an anonymous type, otherwise false.</returns>
public static bool IsAnonymousType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return (type.IsClass
&& type.IsSealed
&& type.BaseType == typeof(object)
&& (type.Name.StartsWith("<>", StringComparison.Ordinal)
|| type.Name.StartsWith("VB$Anonymous", StringComparison.Ordinal))
&& type.IsDefined(typeof(CompilerGeneratedAttribute), true));
}
/// <summary>
/// Checks if the given type is a anonymous type or a generic type containing a
/// reference type as generic type argument
/// </summary>
/// <param name="t">the type to check</param>
/// <returns>true when there exists a reference to an anonymous type.</returns>
public static bool IsAnonymousTypeRecursive(Type t)
{
return t != null && (CompilerServicesUtility.IsAnonymousType(t) ||
// part of generic
t.GetGenericArguments().Any(arg => IsAnonymousTypeRecursive(arg)) ||
// Array is special
(t.IsArray && IsAnonymousTypeRecursive(t.GetElementType())));
}
/// <summary>
/// Determines if the specified type is a dynamic type.
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns>True if the type is an anonymous type, otherwise false.</returns>
public static bool IsDynamicType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return (DynamicType.IsAssignableFrom(type)
|| ExpandoType.IsAssignableFrom(type)
|| IsAnonymousType(type));
}
/// <summary>
/// Determines if the specified type is a compiler generated iterator type.
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns>True if the type is an iterator type, otherwise false.</returns>
public static bool IsIteratorType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return type.IsNestedPrivate
&& type.Name.StartsWith("<", StringComparison.Ordinal)
&& (EnumerableType.IsAssignableFrom(type) || EnumeratorType.IsAssignableFrom(type));
}
/// <summary>
/// Generates a random class name.
/// </summary>
/// <returns>A new random class name.</returns>
public static string GenerateClassName()
{
Guid guid = Guid.NewGuid();
return String.Format("{0}{1}", CompilerServiceBase.ClassNamePrefix, guid.ToString("N"));
}
/// <summary>
/// Gets the public or protected constructors of the specified type.
/// </summary>
/// <param name="type">The target type.</param>
/// <returns>An enumerable of constructors.</returns>
public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
var constructors = type
.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
return constructors;
}
/// <summary>
/// Resolves the C# name of the given type.
/// </summary>
/// <param name="type">the type to emit.</param>
/// <returns>The full type name or dynamic if the type is an instance of an dynamic type.</returns>
public static string ResolveCSharpTypeName(Type type)
{
if (IsIteratorType(type))
type = GetIteratorInterface(type);
if (IsDynamicType(type))
return "dynamic";
var rawFullName = CSharpGetRawTypeName(type);
if (!type.IsGenericType)
return rawFullName;
return rawFullName
+ "<"
+ string.Join(", ", type.GetGenericArguments().Select(ResolveCSharpTypeName))
+ ">";
}
/// <summary>
/// Resolves the VB.net name of the given type.
/// </summary>
/// <param name="type">the type to emit.</param>
/// <returns>The full type name or Object if the type is an instance of an dynamic type.</returns>
public static string ResolveVBTypeName(Type type)
{
if (IsIteratorType(type))
type = GetIteratorInterface(type);
if (IsDynamicType(type))
return "Object";
var rawFullName = VBGetRawTypeName(type);
if (!type.IsGenericType)
return rawFullName;
return rawFullName
+ "(Of"
+ string.Join(", ", type.GetGenericArguments().Select(ResolveVBTypeName))
+ ")";
}
/// <summary>
/// Gets the Iterator type for the given compiler generated iterator.
/// </summary>
/// <param name="type">The target type.</param>
/// <returns>Tries to return IEnumerable of T if possible.</returns>
public static Type GetIteratorInterface(Type type)
{
Type firstInterface = null;
// try to find IEnumerable<>
foreach (var @interface in type.GetInterfaces())
{
if (firstInterface == null)
firstInterface = @interface;
if (@interface.IsGenericType && !@interface.IsGenericTypeDefinition && @interface.GetGenericTypeDefinition() == GenericEnumerableType)
return @interface;
}
// ok just use the first generic one
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsGenericType)
return @interface;
}
// ok use the first one or the whole type.
return @firstInterface ?? type;
}
/// <summary>
/// Gets an enumerable of all assemblies loaded in the current domain.
/// </summary>
/// <returns>An enumerable of loaded assemblies.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public static IEnumerable<Assembly> GetLoadedAssemblies()
{
var domain = AppDomain.CurrentDomain;
return domain.GetAssemblies();
}
/// <summary>
/// Return the raw type name (including namespace) without any generic arguments.
/// Returns the typename in a way it can be used in C# code.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static string CSharpGetRawTypeName(Type type)
{
if (type == null)
throw new ArgumentNullException("templateType");
string fullName = type.FullName;
if (type.IsGenericTypeDefinition || type.IsGenericType)
fullName = type.FullName.Substring(0, type.FullName.IndexOf('`'));
return fullName.Replace("+", ".");;
}
/// <summary>
/// Return the raw type name (including namespace) without any generic arguments.
/// Returns the typename in a way it can be used in VB.net code.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static string VBGetRawTypeName(Type type) { return CSharpGetRawTypeName(type); }
/// <summary>
/// Return the raw type name (including namespace) with the given modelTypeName as generic argument (if applicable).
/// Returns the typename in a way it can be used in C# code.
/// </summary>
/// <param name="templateType"></param>
/// <param name="modelTypeName"></param>
/// <param name="throwWhenNotGeneric"></param>
/// <returns></returns>
public static string CSharpCreateGenericType(Type templateType, string modelTypeName, bool throwWhenNotGeneric)
{
var templateTypeName = CSharpGetRawTypeName(templateType);
if (!templateType.IsGenericTypeDefinition || !templateType.IsGenericType)
{
if (throwWhenNotGeneric)
{
throw new NotSupportedException("The given base type is not generic!");
}
return templateTypeName;
}
return templateTypeName + "<" + modelTypeName + ">";
}
/// <summary>
/// Return the raw type name (including namespace) with the given modelTypeName as generic argument (if applicable).
/// Returns the typename in a way it can be used in VB.net code.
/// </summary>
/// <param name="templateType"></param>
/// <param name="modelTypeName"></param>
/// <param name="throwWhenNotGeneric"></param>
/// <returns></returns>
public static string VBCreateGenericType(Type templateType, string modelTypeName, bool throwWhenNotGeneric)
{
var templateTypeName = VBGetRawTypeName(templateType);
if (!templateType.IsGenericTypeDefinition || !templateType.IsGenericType)
{
if (throwWhenNotGeneric)
{
throw new NotSupportedException("The given base type is not generic!");
}
return templateTypeName;
}
return templateTypeName + "(Of " + modelTypeName + ")";
}
#endregion
}
}