This repository was archived by the owner on Dec 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathTestCompilation.cs
71 lines (58 loc) · 2.66 KB
/
TestCompilation.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
// 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.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Extensions.DependencyModel;
using Xunit;
namespace Microsoft.CodeAnalysis
{
public static class TestCompilation
{
private static readonly ConcurrentDictionary<Assembly, IEnumerable<MetadataReference>> _referenceCache =
new ConcurrentDictionary<Assembly, IEnumerable<MetadataReference>>();
public static IEnumerable<MetadataReference> GetMetadataReferences(Assembly assembly)
{
var dependencyContext = DependencyContext.Load(assembly);
var metadataReferences = dependencyContext.CompileLibraries
.SelectMany(l => l.ResolveReferencePaths())
.Select(assemblyPath => MetadataReference.CreateFromFile(assemblyPath))
.ToArray();
return metadataReferences;
}
public static string AssemblyName => "TestAssembly";
public static CSharpCompilation Create(Assembly assembly, SyntaxTree syntaxTree = null)
{
IEnumerable<SyntaxTree> syntaxTrees = null;
if (syntaxTree != null)
{
syntaxTrees = new[] { syntaxTree };
}
if (!_referenceCache.TryGetValue(assembly, out IEnumerable<MetadataReference> metadataReferences))
{
metadataReferences = GetMetadataReferences(assembly);
_referenceCache.TryAdd(assembly, metadataReferences);
}
var compilation = CSharpCompilation.Create(AssemblyName, syntaxTrees, metadataReferences, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
EnsureValidCompilation(compilation);
return compilation;
}
private static void EnsureValidCompilation(CSharpCompilation compilation)
{
using (var stream = new MemoryStream())
{
var emitResult = compilation
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.Emit(stream);
var diagnostics = string.Join(
Environment.NewLine,
emitResult.Diagnostics.Select(d => CSharpDiagnosticFormatter.Instance.Format(d)));
Assert.True(emitResult.Success, $"Compilation is invalid : {Environment.NewLine}{diagnostics}");
}
}
}
}