forked from neo-project/neo-devpack-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompilationEngine.cs
More file actions
879 lines (781 loc) · 40.4 KB
/
Copy pathCompilationEngine.cs
File metadata and controls
879 lines (781 loc) · 40.4 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
// Copyright (C) 2015-2026 The Neo Project.
//
// CompilationEngine.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
extern alias scfx;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Neo.Json;
using Neo.SmartContract.Analyzer;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using BigInteger = System.Numerics.BigInteger;
namespace Neo.Compiler
{
public class CompilationEngine(CompilationOptions options)
{
internal Compilation? Compilation;
internal MetadataReference? FrameworkReference;
internal ImmutableArray<Diagnostic> AnalyzerDiagnostics { get; private set; } = [];
internal CompilationOptions Options { get; private set; } = options;
private static readonly MetadataReference[] CommonReferences;
private static readonly ImmutableArray<DiagnosticAnalyzer> NeoAnalyzers = NeoAnalyzerSuite.Create();
private static readonly Guid FrameworkModuleVersionId = typeof(scfx::Neo.SmartContract.Framework.Attributes.SafeAttribute).Assembly.ManifestModule.ModuleVersionId;
private const string FrameworkAssemblyName = "Neo.SmartContract.Framework";
private static readonly StringComparison ProjectPathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private readonly Dictionary<string, MetadataReference> MetaReferences = new();
private string? PreparedProjectPath;
private string? ProjectPath;
private string? ProjectVersion;
private string? ProjectVersionPrefix;
private string? ProjectVersionSuffix;
internal readonly ConcurrentDictionary<INamedTypeSymbol, CompilationContext> Contexts = new(SymbolEqualityComparer.Default);
private readonly Lock tempProjectLock = new();
private readonly TemporaryProjectWorkspace _temporaryProjectWorkspace = new();
/// <summary>
/// Gets the version that was extracted from the project
/// </summary>
/// <returns>The version value based on available version properties</returns>
public string? GetProjectVersion()
{
// If Version is set, use it directly
if (!string.IsNullOrEmpty(ProjectVersion))
{
return ProjectVersion;
}
// If both VersionPrefix and VersionSuffix are set, combine them
if (!string.IsNullOrEmpty(ProjectVersionPrefix) && !string.IsNullOrEmpty(ProjectVersionSuffix))
{
return $"{ProjectVersionPrefix}-{ProjectVersionSuffix}";
}
// If only one of them is set, use that one
if (!string.IsNullOrEmpty(ProjectVersionPrefix))
{
return ProjectVersionPrefix;
}
if (!string.IsNullOrEmpty(ProjectVersionSuffix))
{
return ProjectVersionSuffix;
}
// No version information found
return null;
}
static CompilationEngine()
{
CommonReferences =
[
RuntimeAssemblyResolver.CreateFrameworkReference("System.Runtime.dll"),
RuntimeAssemblyResolver.CreateFrameworkReference("System.Runtime.InteropServices.dll"),
RuntimeAssemblyResolver.CreateFrameworkReference("System.ComponentModel.Primitives.dll"),
RuntimeAssemblyResolver.CreateFrameworkReference("System.Runtime.Numerics.dll"),
RuntimeAssemblyResolver.CreateFrameworkReference("System.Collections.dll"),
RuntimeAssemblyResolver.CreateFrameworkReference("System.Memory.dll")
];
}
internal List<CompilationContext> CompileFromCodeBlock(string codeBlock)
{
var sourceCode = $"using Neo.SmartContract.Framework.Native;\n" +
$"using Neo.SmartContract.Framework.Services;\n" +
$"using System;\n" +
$"using System.Text;\n" +
$"using System.Numerics;\n" +
$"using Neo.SmartContract.Framework;\n\n" +
$"namespace Neo.Compiler.CSharp.TestContracts;\n\n" +
$"public class CodeBlockTest : SmartContract.Framework.SmartContract\n{{\n\n" +
$" public static void CodeBlock()\n" +
$" {{\n" +
$" {codeBlock}\n" +
$" }}\n" +
$"}}\n";
// Create a secure temporary directory with unique name to avoid race conditions
string tempDir = Path.Combine(Path.GetTempPath(), $"neo-compiler-{Guid.NewGuid():N}");
Directory.CreateDirectory(tempDir);
string tempFilePath = Path.Combine(tempDir, "CodeBlockTest.cs");
try
{
// Write source code to the secure temp file
File.WriteAllText(tempFilePath, sourceCode);
return CompileSources(tempFilePath);
}
finally
{
// Ensure cleanup of temp directory and all contents
try
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
catch
{
// Best effort cleanup - don't throw from finally
}
}
}
public List<CompilationContext> Compile(IEnumerable<string> sourceFiles, IEnumerable<MetadataReference> references)
{
return Compile(sourceFiles, references, frameworkReference: null);
}
internal List<CompilationContext> Compile(IEnumerable<string> sourceFiles, IEnumerable<MetadataReference> references, MetadataReference? frameworkReference)
{
IEnumerable<SyntaxTree> syntaxTrees = sourceFiles.OrderBy(p => p).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), options: Options.GetParseOptions(), path: p));
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true, nullableContextOptions: Options.Nullable, allowUnsafe: false);
MetadataReference[] referenceArray = references.ToArray();
if (frameworkReference is not null && !referenceArray.Contains(frameworkReference))
throw new ArgumentException("The framework reference must be included in references.", nameof(frameworkReference));
FrameworkReference = frameworkReference ?? referenceArray.FirstOrDefault(IsTrustedFrameworkReference);
Compilation = CSharpCompilation.Create(null, syntaxTrees, referenceArray, compilationOptions);
AnalyzeCompilation();
return CompileProjectContracts(Compilation);
}
public List<CompilationContext> CompileSources(params string[] sourceFiles)
{
var references = new CompilationSourceReferences();
if (TryGetLocalFrameworkProject(out var frameworkProject))
{
references.Projects = [frameworkProject];
}
else
{
references.Packages = [new("Neo.SmartContract.Framework", "3.10.0")];
}
return CompileSources(references, sourceFiles);
}
public List<CompilationContext> CompileSources(CompilationSourceReferences references, params string[] sourceFiles)
{
if (sourceFiles is null || sourceFiles.Length == 0)
{
throw new ArgumentException("At least one source file must be provided.", nameof(sourceFiles));
}
lock (tempProjectLock)
{
if (Options.SkipRestoreIfAssetsPresent)
{
_temporaryProjectWorkspace.EnsurePersistent(TemporaryProjectWorkspace.BuildReferencesKey(references));
}
else
{
_temporaryProjectWorkspace.PrepareTransient();
}
_temporaryProjectWorkspace.WriteProject(references, sourceFiles);
Compilation = null;
try
{
return CompileProject(_temporaryProjectWorkspace.ProjectPath);
}
finally
{
if (!Options.SkipRestoreIfAssetsPresent)
{
_temporaryProjectWorkspace.Cleanup();
}
}
}
}
public List<CompilationContext> CompileProject(string csproj)
{
var compilation = LoadProjectCompilation(csproj, forceReload: true);
return CompileProjectContracts(compilation);
}
private Compilation LoadProjectCompilation(string csproj, bool forceReload)
{
string projectPath = Path.GetFullPath(csproj);
if (!forceReload && Compilation is not null && string.Equals(ProjectPath, projectPath, ProjectPathComparison))
{
return Compilation;
}
ResetProjectState();
Compilation = GetCompilation(projectPath);
FrameworkReference = ResolveProjectFrameworkReference(Compilation);
AnalyzeCompilation();
ProjectPath = projectPath;
return Compilation;
}
private void ResetProjectState()
{
Compilation = null;
FrameworkReference = null;
AnalyzerDiagnostics = [];
MetaReferences.Clear();
PreparedProjectPath = null;
ProjectPath = null;
ProjectVersion = null;
ProjectVersionPrefix = null;
ProjectVersionSuffix = null;
Contexts.Clear();
}
private MetadataReference? ResolveProjectFrameworkReference(Compilation compilation)
{
return MetaReferences
.Where(pair => IsFrameworkLibrary(pair.Key))
.Select(pair => pair.Value)
.FirstOrDefault(reference => compilation.References.Contains(reference));
}
private static bool IsFrameworkLibrary(string libraryName)
{
int separator = libraryName.IndexOf('/');
ReadOnlySpan<char> packageName = separator < 0 ? libraryName.AsSpan() : libraryName.AsSpan(0, separator);
return packageName.Equals(FrameworkAssemblyName, StringComparison.OrdinalIgnoreCase);
}
internal static bool IsTrustedFrameworkReference(MetadataReference reference)
{
if (reference is not PortableExecutableReference portableReference)
return false;
try
{
return portableReference.GetMetadata() is AssemblyMetadata assemblyMetadata &&
assemblyMetadata.GetModules().Any(module => module.GetModuleVersionId() == FrameworkModuleVersionId);
}
catch (Exception exception) when (exception is BadImageFormatException or IOException)
{
return false;
}
}
private void AnalyzeCompilation()
{
if (!Options.RunAnalyzers)
{
AnalyzerDiagnostics = [];
return;
}
AnalyzerDiagnostics = Compilation!
.WithAnalyzers(NeoAnalyzers)
.GetAnalyzerDiagnosticsAsync()
.GetAwaiter()
.GetResult()
.Where(diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden)
.OrderBy(diagnostic => diagnostic.Location.SourceTree?.FilePath ?? string.Empty, StringComparer.Ordinal)
.ThenBy(diagnostic => diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan.Start : -1)
.ThenBy(diagnostic => diagnostic.Id, StringComparer.Ordinal)
.ThenBy(diagnostic => diagnostic.GetMessage(), StringComparer.Ordinal)
.ToImmutableArray();
}
public List<CompilationContext> CompileProject(string csproj, List<INamedTypeSymbol> sortedClasses, Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>> classDependencies, List<INamedTypeSymbol?> allClassSymbols, string? targetContractName = null)
{
if (sortedClasses == null || classDependencies == null || allClassSymbols == null)
{
throw new InvalidOperationException("Please call PrepareProjectContracts before calling CompileProject with sortedClasses, classDependencies and allClassSymbols parameters.");
}
string projectPath = Path.GetFullPath(csproj);
if (Compilation is null || PreparedProjectPath is null || !string.Equals(PreparedProjectPath, projectPath, ProjectPathComparison))
{
throw new InvalidOperationException($"Project '{projectPath}' is not the project currently prepared by this compilation engine. Call {nameof(PrepareProjectContracts)} for this project before calling the prepared {nameof(CompileProject)} overload.");
}
Contexts.Clear();
return targetContractName == null ? CompileProjectContractsWithPrepare(sortedClasses, classDependencies, allClassSymbols) : [CompileProjectContractWithPrepare(sortedClasses, classDependencies, allClassSymbols, targetContractName)];
}
public (List<INamedTypeSymbol> sortedClasses, Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>> classDependencies, List<INamedTypeSymbol?> allClassSymbols) PrepareProjectContracts(string csproj)
{
var compilation = LoadProjectCompilation(csproj, forceReload: false);
PreparedProjectPath = null;
var classDependencies = new Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>>(SymbolEqualityComparer.Default);
var allSmartContracts = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
var allClassSymbols = new List<INamedTypeSymbol?>();
var classSymbols = new List<INamedTypeSymbol>();
foreach (var tree in compilation.SyntaxTrees)
{
var semanticModel = compilation.GetSemanticModel(tree);
var classNodes = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach (var classNode in classNodes)
{
var classSymbol = semanticModel.GetDeclaredSymbol(classNode);
allClassSymbols.Add(classSymbol);
if (classSymbol is null) continue;
classSymbols.Add(classSymbol);
if (classSymbol is { IsAbstract: false, DeclaredAccessibility: Accessibility.Public } && IsDerivedFromSmartContract(classSymbol))
{
allSmartContracts.Add(classSymbol);
classDependencies[classSymbol] = [];
}
}
}
foreach (var classSymbol in classSymbols)
{
if (!allSmartContracts.Contains(classSymbol))
continue;
foreach (var member in classSymbol.GetMembers())
{
var memberTypeSymbol = (member as IFieldSymbol)?.Type ?? (member as IPropertySymbol)?.Type;
if (memberTypeSymbol is not INamedTypeSymbol namedTypeSymbol)
continue;
if (namedTypeSymbol.IsAbstract)
continue;
if (!allSmartContracts.Contains(namedTypeSymbol))
continue;
if (classDependencies[classSymbol].Any(p => SymbolEqualityComparer.Default.Equals(p, namedTypeSymbol)))
continue;
classDependencies[classSymbol].Add(namedTypeSymbol);
}
}
// Verify if there is any valid smart contract class
if (classDependencies.Count == 0) throw new NoSmartContractFoundException();
// Check contract dependencies, make sure there is no cycle in the dependency graph
var sortedClasses = TopologicalSort(classDependencies);
PreparedProjectPath = ProjectPath;
return (sortedClasses, classDependencies, allClassSymbols);
}
private CompilationContext CompileProjectContractWithPrepare(List<INamedTypeSymbol> sortedClasses, Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>> classDependencies, List<INamedTypeSymbol?> allClassSymbols, string targetContractName)
{
var c = ResolveTargetContract(sortedClasses, targetContractName);
var dependencies = classDependencies.TryGetValue(c, out var dependency) ? dependency : [];
var classesNotInDependencies = GetClassesNotInDependencies(allClassSymbols, dependencies);
var context = new CompilationContext(this, c, classesNotInDependencies, allowBaseName: true);
context.Compile();
return context;
}
private static INamedTypeSymbol ResolveTargetContract(List<INamedTypeSymbol> sortedClasses, string targetContractName)
{
var qualifiedMatch = sortedClasses.FirstOrDefault(contract =>
string.Equals(GetContractIdentity(contract), targetContractName, StringComparison.Ordinal));
if (qualifiedMatch != null)
return qualifiedMatch;
var simpleMatches = sortedClasses
.Where(contract => string.Equals(contract.Name, targetContractName, StringComparison.Ordinal))
.OrderBy(GetContractIdentity, StringComparer.Ordinal)
.ToArray();
if (simpleMatches.Length == 1)
return simpleMatches[0];
if (simpleMatches.Length == 0)
throw new ArgumentException($"targetContractName '{targetContractName}' was not found");
throw new ArgumentException(
$"targetContractName '{targetContractName}' is ambiguous. Use one of: {string.Join(", ", simpleMatches.Select(GetContractIdentity))}");
}
internal static string GetContractIdentity(INamedTypeSymbol contract)
{
return contract.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
}
private static List<INamedTypeSymbol> GetClassesNotInDependencies(List<INamedTypeSymbol?> allClassSymbols, List<INamedTypeSymbol> dependencies)
{
var dependencySet = new HashSet<INamedTypeSymbol>(dependencies, SymbolEqualityComparer.Default);
return allClassSymbols.OfType<INamedTypeSymbol>().Where(symbol => !dependencySet.Contains(symbol)).ToList();
}
private List<CompilationContext> CompileProjectContractsWithPrepare(List<INamedTypeSymbol> sortedClasses, Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>> classDependencies, List<INamedTypeSymbol?> allClassSymbols)
{
Contexts.Clear();
bool allowBaseName = sortedClasses.Count <= 1;
Parallel.ForEach(sortedClasses, c =>
{
var dependencies = classDependencies.TryGetValue(c, out var dependency) ? dependency : [];
var classesNotInDependencies = GetClassesNotInDependencies(allClassSymbols, dependencies);
var context = new CompilationContext(this, c, classesNotInDependencies, allowBaseName);
context.Compile();
// Process the target contract add this compilation context
Contexts.TryAdd(c, context);
});
return Contexts.Select(p => p.Value).ToList();
}
private List<CompilationContext> CompileProjectContracts(Compilation compilation)
{
Contexts.Clear();
var classDependencies = new Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>>(SymbolEqualityComparer.Default);
var allSmartContracts = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
var allClassSymbols = new List<INamedTypeSymbol?>();
var classSymbols = new List<INamedTypeSymbol>();
foreach (var tree in compilation.SyntaxTrees)
{
var semanticModel = compilation.GetSemanticModel(tree);
var classNodes = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach (var classNode in classNodes)
{
var classSymbol = semanticModel.GetDeclaredSymbol(classNode);
allClassSymbols.Add(classSymbol);
if (classSymbol is null) continue;
classSymbols.Add(classSymbol);
if (classSymbol is { IsAbstract: false, DeclaredAccessibility: Accessibility.Public } && IsDerivedFromSmartContract(classSymbol))
{
allSmartContracts.Add(classSymbol);
classDependencies[classSymbol] = [];
}
}
}
foreach (var classSymbol in classSymbols)
{
if (!allSmartContracts.Contains(classSymbol))
continue;
foreach (var member in classSymbol.GetMembers())
{
var memberTypeSymbol = (member as IFieldSymbol)?.Type ?? (member as IPropertySymbol)?.Type;
if (memberTypeSymbol is not INamedTypeSymbol namedTypeSymbol)
continue;
if (namedTypeSymbol.IsAbstract)
continue;
if (!allSmartContracts.Contains(namedTypeSymbol))
continue;
if (classDependencies[classSymbol].Any(p => SymbolEqualityComparer.Default.Equals(p, namedTypeSymbol)))
continue;
classDependencies[classSymbol].Add(namedTypeSymbol);
}
}
// Verify if there is any valid smart contract class
if (classDependencies.Count == 0) throw new NoSmartContractFoundException();
// Check contract dependencies, make sure there is no cycle in the dependency graph
var sortedClasses = TopologicalSort(classDependencies);
bool allowBaseName = sortedClasses.Count <= 1;
Parallel.ForEach(sortedClasses, c =>
{
var dependencies = classDependencies.TryGetValue(c, out var dependency) ? dependency : [];
var classesNotInDependencies = GetClassesNotInDependencies(allClassSymbols, dependencies);
var context = new CompilationContext(this, c, classesNotInDependencies, allowBaseName);
context.Compile();
// Process the target contract add this compilation context
Contexts.TryAdd(c, context);
});
return Contexts.Select(p => p.Value).ToList();
}
/// <summary>
/// Sort the classes based on their topological dependencies
/// </summary>
/// <param name="dependencies">Contract dependencies map</param>
/// <returns>List of sorted contracts</returns>
/// <exception cref="InvalidOperationException"></exception>
private static List<INamedTypeSymbol> TopologicalSort(Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>> dependencies)
{
var sorted = new List<INamedTypeSymbol>();
var visited = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
var visiting = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); // for detecting cycles
void Visit(INamedTypeSymbol classSymbol)
{
if (visited.Contains(classSymbol))
{
return;
}
if (!visiting.Add(classSymbol))
{
throw new InvalidOperationException("Cyclic dependency detected");
}
if (dependencies.TryGetValue(classSymbol, out var dependency))
{
foreach (var dep in dependency)
{
Visit(dep);
}
}
visiting.Remove(classSymbol);
visited.Add(classSymbol);
sorted.Add(classSymbol);
}
foreach (var classSymbol in dependencies.Keys)
{
Visit(classSymbol);
}
return sorted;
}
private const string SmartContractTypeName = "SmartContract";
private const string SmartContractNamespace = "Neo.SmartContract.Framework";
internal static bool IsDerivedFromSmartContract(INamedTypeSymbol classSymbol)
{
var baseType = classSymbol.BaseType;
while (baseType != null)
{
if (baseType.Name == SmartContractTypeName &&
baseType.ContainingNamespace?.ToString() == SmartContractNamespace)
{
return true;
}
baseType = baseType.BaseType;
}
return false;
}
public Compilation GetCompilation(string csproj)
{
// Restore project
csproj = Path.GetFullPath(csproj);
string folder = Path.GetDirectoryName(csproj)!;
var assetsPath = Path.Combine(folder, "obj", "project.assets.json");
var shouldSkipRestore = Options.SkipRestoreIfAssetsPresent && File.Exists(assetsPath);
if (!shouldSkipRestore)
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = $"restore \"{csproj}\"",
WorkingDirectory = folder
});
ArgumentNullException.ThrowIfNull(process);
process.WaitForExit();
if (process.ExitCode != 0)
throw new InvalidOperationException($"dotnet restore failed with exit code {process.ExitCode} for '{csproj}'.");
}
if (!File.Exists(assetsPath))
{
throw new FileNotFoundException($"Unable to locate '{assetsPath}'. Ensure the project has been restored.");
}
// Parse csproj
XDocument document = XDocument.Load(csproj);
// Extract Version information from the project file or its Directory.Build.props
ExtractVersionInfo(document, Path.GetDirectoryName(csproj)!);
var (sourceFiles, preprocessorSymbols) = EvaluateProject(csproj, folder);
var assets = (JObject)JToken.Parse(File.ReadAllBytes(assetsPath))!;
List<MetadataReference> references = new(CommonReferences);
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true, nullableContextOptions: Options.Nullable, allowUnsafe: false);
foreach (var (name, package) in ((JObject)assets["targets"]![0]!).Properties)
{
MetadataReference? reference = GetReference(name, (JObject)package!, assets, folder, compilationOptions);
if (reference is not null) references.Add(reference);
}
CSharpParseOptions parseOptions = Options.GetParseOptions().WithPreprocessorSymbols(
Options.GetParseOptions().PreprocessorSymbolNames.Concat(preprocessorSymbols).Distinct(StringComparer.Ordinal));
IEnumerable<SyntaxTree> syntaxTrees = sourceFiles.OrderBy(p => p).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), options: parseOptions, path: p));
return CSharpCompilation.Create(assets["project"]!["restore"]!["projectName"]!.GetString(), syntaxTrees, references, compilationOptions);
}
private static (string[] SourceFiles, string[] PreprocessorSymbols) EvaluateProject(string csproj, string folder)
{
var startInfo = new ProcessStartInfo
{
FileName = "dotnet",
WorkingDirectory = folder,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
startInfo.ArgumentList.Add("msbuild");
startInfo.ArgumentList.Add(csproj);
startInfo.ArgumentList.Add("-nologo");
startInfo.ArgumentList.Add("-verbosity:quiet");
startInfo.ArgumentList.Add("-getItem:Compile");
startInfo.ArgumentList.Add("-getProperty:DefineConstants");
using var process = Process.Start(startInfo);
ArgumentNullException.ThrowIfNull(process);
Task<string> standardOutput = process.StandardOutput.ReadToEndAsync();
Task<string> standardError = process.StandardError.ReadToEndAsync();
process.WaitForExit();
string output = standardOutput.GetAwaiter().GetResult();
string error = standardError.GetAwaiter().GetResult();
if (process.ExitCode != 0)
{
throw new InvalidOperationException($"dotnet msbuild project evaluation failed with exit code {process.ExitCode} for '{csproj}': {error.Trim()}");
}
using JsonDocument evaluation = JsonDocument.Parse(output);
JsonElement root = evaluation.RootElement;
if (!root.TryGetProperty("Items", out JsonElement items) ||
!items.TryGetProperty("Compile", out JsonElement compileItems) ||
!root.TryGetProperty("Properties", out JsonElement properties) ||
!properties.TryGetProperty("DefineConstants", out JsonElement defineConstants))
{
throw new InvalidOperationException($"dotnet msbuild returned incomplete project evaluation data for '{csproj}'.");
}
string[] sourceFiles = compileItems.EnumerateArray()
.Select(item => item.GetProperty("FullPath").GetString()
?? throw new InvalidOperationException($"A Compile item in '{csproj}' did not have a FullPath."))
.ToArray();
string[] preprocessorSymbols = (defineConstants.GetString() ?? string.Empty)
.Split([';', ','], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
return (sourceFiles, preprocessorSymbols);
}
private MetadataReference? GetReference(string name, JObject package, JObject assets, string folder, CSharpCompilationOptions compilationOptions)
{
if (!MetaReferences.TryGetValue(name, out var reference))
{
string assetType = assets["libraries"]![name]!["type"]!.GetString();
switch (assetType)
{
case "package":
string packagesPath = assets["project"]!["restore"]!["packagesPath"]!.GetString();
string namePath = assets["libraries"]![name]!["path"]!.GetString();
string[] files = ((JArray)assets["libraries"]![name]!["files"]!)
.Select(p => p!.GetString())
.Where(p => p.StartsWith("src/"))
.ToArray();
if (files.Length == 0)
{
JObject? dllFiles = (JObject?)(package["compile"] ?? package["runtime"]);
if (dllFiles is null) return null;
foreach (var (file, _) in dllFiles.Properties)
{
if (file.EndsWith("_._")) continue;
string path = Path.Combine(packagesPath, namePath, file);
if (!File.Exists(path)) continue;
reference = MetadataReference.CreateFromFile(path);
break;
}
if (reference is null) return null;
}
else
{
string assemblyName = Path.GetDirectoryName(name)!;
IEnumerable<SyntaxTree> st = files.OrderBy(p => p).Select(p => Path.Combine(packagesPath, namePath, p)).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), path: p));
CSharpCompilation cr = CSharpCompilation.Create(assemblyName, st, CommonReferences, compilationOptions);
reference = cr.ToMetadataReference();
}
break;
case "project":
string msbuildProject = assets["libraries"]![name]!["msbuildProject"]!.GetString();
msbuildProject = Path.GetFullPath(msbuildProject, folder);
reference = GetCompilationPreservingVersion(msbuildProject).ToMetadataReference();
break;
default:
throw new NotSupportedException($"Unsupported dependency asset type '{assetType}' for '{name}'.");
}
MetaReferences.Add(name, reference);
}
return reference;
}
private static bool TryGetLocalFrameworkProject(out string frameworkProject)
{
var searchRoots = new[]
{
Directory.GetCurrentDirectory(),
AppContext.BaseDirectory,
Path.GetDirectoryName(typeof(CompilationEngine).Assembly.Location) ?? string.Empty
};
foreach (var root in searchRoots.Where(r => !string.IsNullOrEmpty(r)))
{
var directory = new DirectoryInfo(root);
while (directory is not null)
{
var candidate = Path.Combine(directory.FullName, "src", "Neo.SmartContract.Framework", "Neo.SmartContract.Framework.csproj");
if (File.Exists(candidate))
{
frameworkProject = candidate;
return true;
}
directory = directory.Parent;
}
}
frameworkProject = string.Empty;
return false;
}
private Compilation GetCompilationPreservingVersion(string csproj)
{
bool preserveProjectVersion = !string.IsNullOrEmpty(ProjectVersion) ||
!string.IsNullOrEmpty(ProjectVersionPrefix) ||
!string.IsNullOrEmpty(ProjectVersionSuffix);
string? projectVersion = ProjectVersion;
string? projectVersionPrefix = ProjectVersionPrefix;
string? projectVersionSuffix = ProjectVersionSuffix;
try
{
return GetCompilation(csproj);
}
finally
{
if (preserveProjectVersion)
{
ProjectVersion = projectVersion;
ProjectVersionPrefix = projectVersionPrefix;
ProjectVersionSuffix = projectVersionSuffix;
}
}
}
/// <summary>
/// Extracts the Version information from a project file or its referenced Directory.Build.props
/// </summary>
/// <param name="projectDocument">The loaded project document</param>
/// <param name="projectDirectory">The directory containing the project file</param>
private void ExtractVersionInfo(XDocument projectDocument, string projectDirectory)
{
// Try to get Version information directly from the project file
// Get the XML namespace if it exists
XNamespace ns = projectDocument.Root?.Name.Namespace ?? string.Empty;
// Check for Version
ProjectVersion = projectDocument.Root?
.Elements(ns + "PropertyGroup")
.Elements(ns + "Version")
.FirstOrDefault()?.Value;
// Check for VersionPrefix
ProjectVersionPrefix = projectDocument.Root?
.Elements(ns + "PropertyGroup")
.Elements(ns + "VersionPrefix")
.FirstOrDefault()?.Value;
// Check for VersionSuffix
ProjectVersionSuffix = projectDocument.Root?
.Elements(ns + "PropertyGroup")
.Elements(ns + "VersionSuffix")
.FirstOrDefault()?.Value;
// If not found in the project file, try to look for Directory.Build.props
if (string.IsNullOrEmpty(ProjectVersion) &&
string.IsNullOrEmpty(ProjectVersionPrefix) &&
string.IsNullOrEmpty(ProjectVersionSuffix))
{
string? directoryBuildPropsPath = FindDirectoryBuildProps(projectDirectory);
if (directoryBuildPropsPath != null)
{
try
{
XDocument directoryBuildProps = XDocument.Load(directoryBuildPropsPath);
// Get the XML namespace if it exists
ns = directoryBuildProps.Root?.Name.Namespace ?? string.Empty;
// Check for Version
if (string.IsNullOrEmpty(ProjectVersion))
{
ProjectVersion = directoryBuildProps.Root?
.Elements(ns + "PropertyGroup")
.Elements(ns + "Version")
.FirstOrDefault()?.Value;
}
// Check for VersionPrefix
if (string.IsNullOrEmpty(ProjectVersionPrefix))
{
ProjectVersionPrefix = directoryBuildProps.Root?
.Elements(ns + "PropertyGroup")
.Elements(ns + "VersionPrefix")
.FirstOrDefault()?.Value;
}
// Check for VersionSuffix
if (string.IsNullOrEmpty(ProjectVersionSuffix))
{
ProjectVersionSuffix = directoryBuildProps.Root?
.Elements(ns + "PropertyGroup")
.Elements(ns + "VersionSuffix")
.FirstOrDefault()?.Value;
}
}
catch
{
// Ignore errors when trying to load Directory.Build.props
}
}
}
}
/// <summary>
/// Recursively searches for Directory.Build.props starting from the specified directory and moving up
/// </summary>
/// <param name="directory">Starting directory</param>
/// <returns>Path to Directory.Build.props file or null if not found</returns>
private string? FindDirectoryBuildProps(string directory)
{
try
{
// Check if Directory.Build.props exists in the current directory
string directoryBuildPropsPath = Path.Combine(directory, "Directory.Build.props");
if (File.Exists(directoryBuildPropsPath))
{
return directoryBuildPropsPath;
}
// Move up one directory if possible
string? parentDirectory = Path.GetDirectoryName(directory);
if (parentDirectory != null && parentDirectory != directory)
{
return FindDirectoryBuildProps(parentDirectory);
}
// Not found
return null;
}
catch
{
// Handle any exceptions that might occur during directory traversal
return null;
}
}
}
}