forked from DerivcoIpswich/dsharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptCompiler.cs
More file actions
522 lines (429 loc) · 17.6 KB
/
Copy pathScriptCompiler.cs
File metadata and controls
522 lines (429 loc) · 17.6 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using DSharp.Compiler.CodeModel;
using DSharp.Compiler.CodeModel.Types;
using DSharp.Compiler.Compiler;
using DSharp.Compiler.Errors;
using DSharp.Compiler.Generator;
using DSharp.Compiler.Importer;
using DSharp.Compiler.Preprocessing;
using DSharp.Compiler.Preprocessing.Lowering;
using DSharp.Compiler.References;
using DSharp.Compiler.ScriptModel.Symbols;
using DSharp.Compiler.Validator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
namespace DSharp.Compiler
{
public sealed class ScriptCompiler : IErrorHandler
{
private readonly IErrorHandler errorHandler;
private ICollection<TypeSymbol> appSymbols;
private HashSet<CompilationUnitNode> compilationUnitList = new HashSet<CompilationUnitNode>();
private bool hasErrors;
private CompilerOptions options;
private SymbolSet symbols;
private CSharpCompilation compilation;
public ScriptCompiler()
: this(null)
{
}
public ScriptCompiler(IErrorHandler errorHandler)
{
this.errorHandler = errorHandler;
}
public bool Compile(CompilerOptions options)
{
this.options = options ?? throw new ArgumentNullException(nameof(options));
if (options.DebugMode)
{
Debugger.Launch();
}
hasErrors = false;
symbols = new SymbolSet();
ScriptReferenceProvider.Instance.Reset();
ImportMetadata();
if (hasErrors)
{
return false;
}
BuildCodeModel();
if (hasErrors)
{
return false;
}
BuildMetadata();
if (hasErrors)
{
return false;
}
BuildImplementation();
if (hasErrors)
{
return false;
}
GenerateScript();
GenerateMetadata();
if (hasErrors)
{
return false;
}
return true;
}
private void GenerateMetadata()
{
Stream outputStream = null;
TextWriter outputWriter = null;
try
{
outputStream = options.MetadataFile?.GetStream();
if (outputStream == null)
{
return;
}
outputWriter = new StreamWriter(outputStream, new UTF8Encoding(false));
ScriptMetadataGenerator scriptGenerator = new ScriptMetadataGenerator(outputWriter, options, symbols);
scriptGenerator.GenerateScriptMetadata(symbols);
}
catch (Exception e)
{
throw;
}
finally
{
outputWriter?.Flush();
if (outputStream != null)
{
options.ScriptFile.CloseStream(outputStream);
}
}
}
private void ImportMetadata()
{
MetadataImporter mdImporter = new MetadataImporter(this);
mdImporter.ImportMetadata(options.References, symbols);
}
private void BuildCodeModel()
{
CodeModelBuilder codeModelBuilder = new CodeModelBuilder(options, this);
CodeModelValidator codeModelValidator = new CodeModelValidator(this);
CodeModelProcessor validationProcessor = new CodeModelProcessor(codeModelValidator, options);
this.compilation = GetPreprocessedCompilation();
var sources = options.Sources.Select(s => GetPreprocessedSource(compilation, s));
foreach (IStreamSource source in sources)
{
CompilationUnitNode compilationUnit = codeModelBuilder.BuildCodeModel(source);
if (compilationUnit != null)
{
validationProcessor.Process(compilationUnit);
compilationUnitList.Add(compilationUnit);
}
}
}
private CSharpCompilation GetPreprocessedCompilation()
{
CSharpParseOptions parseOptions = new CSharpParseOptions(preprocessorSymbols: options.Defines);
var trees = options.Sources.Select(s => CSharpSyntaxTree.ParseText(path: s.FullName, text: SourceText.From(s.GetStream()), options: parseOptions));
var references = options.References.Select(r => MetadataReference.CreateFromFile(r));
var compilation = CSharpCompilation.Create(options.AssemblyName, trees, references);
var lowerers = new ILowerer[] {
new AnnotatedCSharpRewriter(),
new StaticUsingRewriter(),
new VarRewriter(this),
new GenericArgumentRewriter(),
new LambdaRewriter(this),
new EnumValueRewriter(),
new ObjectInitializerRewriter(this),
new ImplicitArrayCreationRewriter(),
new OperatorOverloadRewriter(),
};
IntermediarySourceManager intermediarySourceManager = new IntermediarySourceManager(options.IntermediarySourceFolder);
return new CompilationPreprocessor(intermediarySourceManager).Preprocess(compilation, lowerers);
}
private IStreamSource GetPreprocessedSource(CSharpCompilation comp, IStreamSource source)
{
return new SyntaxTreeSource(source.Name, comp.SyntaxTrees.Single(s => s.FilePath == source.FullName));
}
private void BuildMetadata()
{
if (options.Resources != null && options.Resources.Count != 0)
{
ResourcesBuilder resourcesBuilder = new ResourcesBuilder(symbols);
resourcesBuilder.BuildResources(options.Resources);
}
MetadataBuilder mdBuilder = new MetadataBuilder(this);
appSymbols = mdBuilder.BuildMetadata(compilationUnitList, symbols, options);
CheckForDuplicateTypes();
TransformSymbols();
}
private bool IsEmittableTypeSymbol(TypeSymbol typeSymbol)
{
//if (appType.IsApplicationType == false || appType.Type == SymbolType.Delegate)
//{
// // Skip the check for types that are marked as imported, as they
// // aren't going to be generated into the script.
// // Delegates are implicitly imported types, as they're never generated into
// // the script.
// continue;
//}
var classSymbol = typeSymbol as ClassSymbol;
if (classSymbol != null && classSymbol.PrimaryPartialClass != typeSymbol)
{
// Skip the check for partial types, since they should only be
// checked once.
return false;
}
return typeSymbol.IsApplicationType
&& typeSymbol.Type != SymbolType.Delegate
|| (classSymbol != null && classSymbol.PrimaryPartialClass != typeSymbol);
}
private void CheckForDuplicateTypes()
{
Dictionary<string, TypeSymbol> types = new Dictionary<string, TypeSymbol>();
foreach (TypeSymbol appType in appSymbols.Where(symbol => IsEmittableTypeSymbol(symbol)))
{
string name = appType.GeneratedName;
if (types.ContainsKey(name))
{
((IErrorHandler)this).ReportGeneralError(string.Format(DSharpStringResources.CONFLICTING_TYPE_NAME_ERROR_FORMAT, appType.FullName, types[name].FullName));
}
else
{
types[name] = appType;
}
}
}
private void TransformSymbols()
{
ISymbolTransformer transformer;
if (options.Minimize)
{
transformer = new SymbolObfuscator();
}
else
{
transformer = new SymbolInternalizer();
}
SymbolSetTransformer symbolSetTransformer = new SymbolSetTransformer(transformer);
symbolSetTransformer.TransformSymbolSet(symbols, useInheritanceOrder: true);
}
private void BuildImplementation()
{
CodeBuilder codeBuilder = new CodeBuilder(options, this);
ICollection<SymbolImplementation> implementations = codeBuilder.BuildCode(symbols);
if (options.Minimize)
{
foreach (SymbolImplementation impl in implementations)
{
if (impl.Scope == null)
{
continue;
}
SymbolObfuscator obfuscator = new SymbolObfuscator();
SymbolImplementationTransformer transformer = new SymbolImplementationTransformer(obfuscator);
transformer.TransformSymbolImplementation(impl);
}
}
}
private void GenerateScript()
{
Stream outputStream = null;
TextWriter outputWriter = null;
try
{
outputStream = options.ScriptFile.GetStream();
if (outputStream == null)
{
string scriptName = options.ScriptFile.FullName;
((IErrorHandler)this).ReportMissingStreamError(scriptName);
return;
}
outputWriter = new StreamWriter(outputStream, new UTF8Encoding(false));
string script = GenerateScriptWithTemplate();
outputWriter.Write(script);
}
catch (Exception e)
{
throw;
}
finally
{
if (outputWriter != null)
{
outputWriter.Flush();
}
if (outputStream != null)
{
options.ScriptFile.CloseStream(outputStream);
}
}
}
private string GenerateScriptCore()
{
StringWriter scriptWriter = new StringWriter();
try
{
ScriptGenerator scriptGenerator = new ScriptGenerator(scriptWriter, options, symbols);
scriptGenerator.GenerateScript(symbols);
}
catch (Exception e)
{
throw;
}
finally
{
scriptWriter.Flush();
}
return scriptWriter.ToString();
}
private string GenerateScriptWithTemplate()
{
string script = GenerateScriptCore();
string template = options.ScriptInfo.Template;
if (string.IsNullOrEmpty(template))
{
return script;
}
template = PreprocessTemplate(template);
StringBuilder requiresBuilder = new StringBuilder();
StringBuilder dependenciesBuilder = new StringBuilder();
StringBuilder depLookupBuilder = new StringBuilder();
bool firstDependency = true;
foreach (ScriptReference dependency in symbols.Dependencies)
{
if (dependency.DelayLoaded)
{
continue;
}
if (dependency.TypeReferenceCount <= 0
&& dependency.Identifier != DSharpStringResources.DSHARP_SCRIPT_NAME)
{
if (dependency.ConstReferenceCount <= 0)
{
Console.Error.WriteLine($"WARN: Unnecessary dependency to '{dependency.Identifier}'.");
}
continue;
}
if (firstDependency)
{
depLookupBuilder.Append("var ");
}
else
{
requiresBuilder.Append(", ");
dependenciesBuilder.Append(", ");
depLookupBuilder.Append(",\r\n ");
}
string name = dependency.Name;
if (name == DSharpStringResources.DSHARP_SCRIPT_NAME)
{
// TODO: This is a hack... to make generated node.js scripts
// be able to reference the 'dsharp' node module.
// Fix this in a better/1st class manner by allowing
// script assemblies to declare such things.
name = DSharpStringResources.DSHARP_SCRIPT_NAME;
}
requiresBuilder.Append("'" + dependency.Path + "'");
dependenciesBuilder.Append(dependency.Identifier);
depLookupBuilder.Append(dependency.Identifier);
depLookupBuilder.Append(" = require('" + name + "')");
firstDependency = false;
}
depLookupBuilder.Append(";");
return template.TrimStart()
.Replace("{name}", symbols.ScriptName)
.Replace("{description}", options.ScriptInfo.Description ?? string.Empty)
.Replace("{copyright}", options.ScriptInfo.Copyright ?? string.Empty)
.Replace("{version}", options.ScriptInfo.Version ?? string.Empty)
.Replace("{compiler}", typeof(ScriptCompiler).Assembly.GetName().Version.ToString())
.Replace("{description}", options.ScriptInfo.Description)
.Replace("{requires}", requiresBuilder.ToString())
.Replace("{dependencies}", dependenciesBuilder.ToString())
.Replace("{dependenciesLookup}", depLookupBuilder.ToString())
.Replace("{script}", script);
}
private string PreprocessTemplate(string template)
{
if (options.IncludeResolver == null)
{
return template;
}
Regex includePattern = new Regex("\\{include:([^\\}]+)\\}",
RegexOptions.Multiline | RegexOptions.CultureInvariant);
return includePattern.Replace(template, delegate (Match include)
{
string includedScript = string.Empty;
if (include.Groups.Count == 2)
{
string includePath = include.Groups[1].Value;
IStreamSource includeSource = options.IncludeResolver.Resolve(includePath);
if (includeSource != null)
{
Stream includeStream = includeSource.GetStream();
StreamReader reader = new StreamReader(includeStream);
includedScript = reader.ReadToEnd();
includeSource.CloseStream(includeStream);
}
}
return includedScript;
});
}
void IErrorHandler.ReportError(CompilerError error)
{
hasErrors = true;
if (errorHandler != null)
{
errorHandler.ReportError(MapErrorLocation(error, compilation));
return;
}
//TODO: Look at adding a logger interface
LogError(MapErrorLocation(error, compilation));
}
private void LogError(CompilerError error)
{
if (error.ColumnNumber != null || error.LineNumber != null)
{
Console.Error.WriteLine($"{error.File}({error.LineNumber.GetValueOrDefault()}, {error.ColumnNumber.GetValueOrDefault()})");
}
Console.Error.WriteLine(error.Description);
}
private static CompilerError MapErrorLocation(CompilerError compilerError, Compilation compilation)
{
try
{
if (!compilerError.LineNumber.HasValue || !compilerError.ColumnNumber.HasValue || string.IsNullOrEmpty(compilerError.File))
{
return compilerError;
}
var syntaxTree = compilation.SyntaxTrees.Where(s => s.FilePath == compilerError.File).SingleOrDefault();
var pos = syntaxTree.GetText().Lines[compilerError.LineNumber.Value - 1].Start + compilerError.ColumnNumber.Value - 1;
var node = syntaxTree.GetRoot().FindNode(new TextSpan(pos, 0));
return new CompilerError(
errorCode: compilerError.ErrorCode,
description: compilerError.Description,
file: compilerError.File,
lineNumber: ParseAnnotation(node, "OriginalLineStart", p => p.StartLinePosition.Line) + 1,
columnNumber: ParseAnnotation(node, "OriginalColumnStart", p => p.StartLinePosition.Character) + 1
);
}
catch
{
return compilerError;
}
int ParseAnnotation(SyntaxNode node, string name, Func<FileLinePositionSpan, int> getDefault)
{
if (node.GetAnnotations(name).FirstOrDefault() is SyntaxAnnotation annotation && annotation != default)
{
return int.Parse(annotation.Data);
}
return getDefault.Invoke(node.GetLocation().GetLineSpan());
}
}
}
}