forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompilerServiceBase.cs
More file actions
267 lines (225 loc) · 10.2 KB
/
CompilerServiceBase.cs
File metadata and controls
267 lines (225 loc) · 10.2 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
using System.CodeDom.Compiler;
using System.Web.Razor.Parser.SyntaxTree;
using ServiceStack.Razor.ServiceStack;
using ServiceStack.Razor.Templating;
using ServiceStack.Text;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Razor;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser;
namespace ServiceStack.Razor.Compilation
{
/// <summary>
/// Provides a base implementation of a compiler service.
/// </summary>
public abstract class CompilerServiceBase
{
private readonly CodeDomProvider CodeDomProvider;
protected CompilerServiceBase(
CodeDomProvider codeDomProvider,
RazorCodeLanguage codeLanguage, MarkupParser markupParser)
{
if (codeLanguage == null)
throw new ArgumentNullException("codeLanguage");
CodeDomProvider = codeDomProvider;
CodeLanguage = codeLanguage;
MarkupParser = markupParser ?? new HtmlMarkupParser();
}
/// <summary>
/// Gets the code language.
/// </summary>
public RazorCodeLanguage CodeLanguage { get; private set; }
/// <summary>
/// Gets the markup parser.
/// </summary>
public MarkupParser MarkupParser { get; private set; }
/// <summary>
/// Builds a type name for the specified template type and model type.
/// </summary>
/// <param name="templateType">The template type.</param>
/// <param name="modelType">The model type.</param>
/// <returns>The string type name (including namespace).</returns>
public virtual string BuildTypeName(Type templateType, Type modelType)
{
if (templateType == null)
throw new ArgumentNullException("templateType");
if (!templateType.IsGenericTypeDefinition && !templateType.IsGenericType)
return templateType.FullName;
if (modelType == null)
throw new ArgumentException("The template type is a generic defintion, and no model type has been supplied.");
bool @dynamic = CompilerServices.IsDynamicType(modelType);
Type genericType = templateType.MakeGenericType(modelType);
return BuildTypeNameInternal(genericType, @dynamic);
}
/// <summary>
/// Builds a type name for the specified generic type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="isDynamic">Is the model type dynamic?</param>
/// <returns>The string typename (including namespace and generic type parameters).</returns>
public abstract string BuildTypeNameInternal(Type type, bool isDynamic);
static string[] DuplicatedAssmebliesInMono = new string[] {
"mscorlib.dll",
"System/4.0.0.0__b77a5c561934e089/System.dll",
"System.Xml/4.0.0.0__b77a5c561934e089/System.Xml.dll",
"System.Core/4.0.0.0__b77a5c561934e089/System.Core.dll",
"Microsoft.CSharp/4.0.0.0__b03f5f7f11d50a3a/Microsoft.CSharp.dll",
};
/// <summary>
/// Creates the compile results for the specified <see cref="TypeContext"/>.
/// </summary>
/// <param name="context">The type context.</param>
/// <returns>The compiler results.</returns>
private CompilerResults Compile(TypeContext context)
{
var compileUnit = GetCodeCompileUnit(
context.ClassName,
context.TemplateContent,
context.Namespaces,
context.TemplateType,
context.ModelType);
var @params = new CompilerParameters {
GenerateInMemory = true,
GenerateExecutable = false,
IncludeDebugInformation = false,
CompilerOptions = "/target:library /optimize",
};
var assemblies = CompilerServices
.GetLoadedAssemblies()
.Where(a => !a.IsDynamic)
.Select(a => a.Location)
.ToArray();
@params.ReferencedAssemblies.AddRange(assemblies);
if (Env.IsMono)
{
for (var i=@params.ReferencedAssemblies.Count-1; i>=0; i--)
{
var assembly = @params.ReferencedAssemblies[i];
foreach (var filterAssembly in DuplicatedAssmebliesInMono)
{
if (assembly.Contains(filterAssembly)) {
@params.ReferencedAssemblies.RemoveAt(i);
}
}
}
}
return CodeDomProvider.CompileAssemblyFromDom(@params, compileUnit);
}
public Type CompileType(TypeContext context)
{
var results = Compile(context);
if (results.Errors != null && results.Errors.Count > 0)
{
throw new TemplateCompilationException(results.Errors);
}
return results.CompiledAssembly.GetType("CompiledRazorTemplates.Dynamic." + context.ClassName);
}
/// <summary>
/// Generates any required contructors for the specified type.
/// </summary>
/// <param name="constructors">The set of constructors.</param>
/// <param name="codeType">The code type declaration.</param>
private static void GenerateConstructors(IEnumerable<ConstructorInfo> constructors, CodeTypeDeclaration codeType)
{
if (constructors == null || !constructors.Any())
return;
var existingConstructors = codeType.Members.OfType<CodeConstructor>().ToArray();
foreach (var existingConstructor in existingConstructors)
codeType.Members.Remove(existingConstructor);
foreach (var constructor in constructors)
{
var ctor = new CodeConstructor { Attributes = MemberAttributes.Public };
foreach (var param in constructor.GetParameters())
{
ctor.Parameters.Add(new CodeParameterDeclarationExpression(param.ParameterType, param.Name));
ctor.BaseConstructorArgs.Add(new CodeSnippetExpression(param.Name));
}
codeType.Members.Add(ctor);
}
}
/// <summary>
/// Gets the code compile unit used to compile a type.
/// </summary>
/// <param name="className">The class name.</param>
/// <param name="template">The template to compile.</param>
/// <param name="namespaceImports">The set of namespace imports.</param>
/// <param name="templateType">The template type.</param>
/// <param name="modelType">The model type.</param>
/// <returns>A <see cref="CodeCompileUnit"/> used to compile a type.</returns>
public CodeCompileUnit GetCodeCompileUnit(string className, string template, ISet<string> namespaceImports, Type templateType, Type modelType)
{
if (string.IsNullOrEmpty(className))
throw new ArgumentException("Class name is required.");
if (string.IsNullOrEmpty(template))
throw new ArgumentException("Template is required.");
templateType = templateType
?? ((modelType == null)
? typeof(TemplateBase)
: typeof(TemplateBase<>));
var host = new MvcWebPageRazorHost(CodeLanguage, () => MarkupParser) {
DefaultBaseClass = BuildTypeName(templateType, modelType),
DefaultClassName = className,
DefaultNamespace = "CompiledRazorTemplates.Dynamic",
GeneratedClassContext = new GeneratedClassContext(
"Execute", "Write", "WriteLiteral",
"WriteTo", "WriteLiteralTo",
"ServiceStack.Razor.Templating.TemplateWriter",
"WriteSection")
};
var templateNamespaces = templateType.GetCustomAttributes(typeof(RequireNamespacesAttribute), true)
.Cast<RequireNamespacesAttribute>()
.SelectMany(att => att.Namespaces);
foreach (string ns in templateNamespaces)
namespaceImports.Add(ns);
foreach (string @namespace in namespaceImports)
host.NamespaceImports.Add(@namespace);
var engine = new RazorTemplateEngine(host);
GeneratorResults result;
using (var reader = new StringReader(template))
{
result = engine.GenerateCode(reader);
}
var type = result.GeneratedCode.Namespaces[0].Types[0];
if (modelType != null)
{
if (CompilerServices.IsAnonymousType(modelType))
{
type.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(HasDynamicModelAttribute))));
}
}
GenerateConstructors(CompilerServices.GetConstructors(templateType), type);
var statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear");
foreach (CodeTypeMember member in type.Members)
{
if (member.Name.Equals("Execute"))
{
((CodeMemberMethod)member).Statements.Insert(0, new CodeExpressionStatement(statement));
break;
}
}
return result.GeneratedCode;
}
public IEnumerable<T> AllNodesOfType<T>(Block block)
{
if (block is T)
yield return (T)(object)block;
foreach (var syntaxTreeNode in block.Children)
{
if (syntaxTreeNode is T)
yield return (T)(object)syntaxTreeNode;
var childBlock = syntaxTreeNode as Block;
if (childBlock == null) continue;
foreach (var variable in AllNodesOfType<T>(childBlock))
{
yield return variable;
}
}
}
}
}