Skip to content

Commit f5914c2

Browse files
committed
Code gets generated, RoslynDemo project works but having assembly load exceptions when running tests.
1 parent 822096a commit f5914c2

6 files changed

Lines changed: 50 additions & 7 deletions

File tree

src/ImmutableObjectGraph.Generation.Tests/CodeGenTests.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ public CodeGenTests(ITestOutputHelper logger)
3636
var project = workspace.CurrentSolution.AddProject("test", "test", "C#")
3737
.WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
3838
.AddMetadataReferences(GetReferences("Profile78"))
39+
.AddMetadataReference(MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location))
3940
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(GenerateImmutableAttribute).Assembly.Location))
4041
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(CodeGenerationAttributeAttribute).Assembly.Location))
4142
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(Optional).Assembly.Location))
@@ -266,7 +267,11 @@ protected async Task<GenerationResult> GenerateAsync(SourceText inputSource)
266267
var inputDocument = solution.GetDocument(this.inputDocumentId);
267268
var generatorDiagnostics = new List<Diagnostic>();
268269
var progress = new SynchronousProgress<Diagnostic>(generatorDiagnostics.Add);
269-
var outputDocument = await DocumentTransform.TransformAsync(inputDocument, progress);
270+
var inputCompilation = (CSharpCompilation)await inputDocument.Project.GetCompilationAsync();
271+
var inputSyntaxTree = await inputDocument.GetSyntaxTreeAsync();
272+
var outputSyntaxTree = await DocumentTransform.TransformAsync(inputCompilation, inputSyntaxTree, null, Assembly.Load, progress);
273+
var outputDocument = inputDocument.Project
274+
.AddDocument("output.cs", outputSyntaxTree.GetRoot());
270275

271276
// Make sure the result compiles without errors or warnings.
272277
var compilation = await outputDocument.Project.GetCompilationAsync();

src/ImmutableObjectGraph.Generation.Tests/ImmutableObjectGraph.Generation.Tests.csproj

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@
99
<Compile Update="TestSources\AbstractClassMidTypeHierarchyWithRequiredField.cs">
1010
<Generator>MSBuild:GenerateCodeFromAttributes</Generator>
1111
</Compile>
12+
<EmbeddedResource Include="TestSources\AlmostRecursive.cs" />
1213
<EmbeddedResource Include="TestSources\ByteArray.cs" />
14+
<EmbeddedResource Include="TestSources\HierarchyLevels.cs" />
15+
<EmbeddedResource Include="TestSources\IgnoreField.cs" />
1316
<EmbeddedResource Include="TestSources\ImmutableArray.cs" />
17+
<EmbeddedResource Include="TestSources\RootedStruct_Without_WithMethodsPerProperty.cs" />
1418
<Compile Update="TestSources\Generations.cs">
1519
<Generator>MSBuild:GenerateCodeFromAttributes</Generator>
1620
</Compile>
@@ -71,6 +75,10 @@
7175
<Generator>MSBuild:GenerateCodeFromAttributes</Generator>
7276
</Compile>
7377
<Compile Remove="@(EmbeddedResource)" />
78+
<Compile Remove="TestSources\AlmostRecursive.cs" />
79+
<Compile Remove="TestSources\HierarchyLevels.cs" />
80+
<Compile Remove="TestSources\IgnoreField.cs" />
81+
<Compile Remove="TestSources\RootedStruct_Without_WithMethodsPerProperty.cs" />
7482
</ItemGroup>
7583
<ItemGroup>
7684
<PackageReference Include="Microsoft.Build" />

src/ImmutableObjectGraph.Generation/CodeGen.cs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ public partial class CodeGen
5454
SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(typeof(NotImplementedException).FullName), SyntaxFactory.ArgumentList(), null));
5555
private static readonly ArgumentSyntax DoNotSkipValidationArgument = SyntaxFactory.Argument(SyntaxFactory.NameColon(SkipValidationParameterName), NoneToken, SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));
5656
private static readonly AttributeSyntax ObsoletePublicCtor = SyntaxFactory.Attribute(Syntax.GetTypeSyntax(typeof(ObsoleteAttribute))).AddArgumentListArguments(SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("This constructor for use with deserializers only. Use the static Create factory method instead."))));
57+
private static ImmutableHashSet<INamedTypeSymbol> CheckedTypes = ImmutableHashSet<INamedTypeSymbol>.Empty;
5758

5859
private readonly ClassDeclarationSyntax applyTo;
5960
private readonly SemanticModel semanticModel;
@@ -92,8 +93,34 @@ public static async Task<SyntaxList<MemberDeclarationSyntax>> GenerateAsync(Clas
9293
Requires.NotNull(semanticModel, nameof(semanticModel));
9394
Requires.NotNull(progress, nameof(progress));
9495

95-
var instance = new CodeGen(applyTo, semanticModel, progress, options, cancellationToken);
96-
return await instance.GenerateAsync();
96+
// Ensure code gets generated only once per definition
97+
var typeSymbol = semanticModel.GetDeclaredSymbol(applyTo);
98+
if (typeSymbol != null)
99+
{
100+
var key = typeSymbol.OriginalDefinition ?? typeSymbol;
101+
if (TryAdd(ref CheckedTypes, key))
102+
{
103+
var instance = new CodeGen(applyTo, semanticModel, progress, options, cancellationToken);
104+
return await instance.GenerateAsync();
105+
}
106+
}
107+
return new SyntaxList<MemberDeclarationSyntax>();
108+
}
109+
110+
static bool TryAdd<T>(ref ImmutableHashSet<T> set, T value)
111+
{
112+
while (true)
113+
{
114+
var currentSet = Volatile.Read(ref set);
115+
var updatedSet = currentSet.Add(value);
116+
var originalSet = Interlocked.CompareExchange(ref set, updatedSet, currentSet);
117+
if (originalSet != currentSet)
118+
{
119+
// Try again
120+
continue;
121+
}
122+
return updatedSet != currentSet;
123+
}
97124
}
98125

99126
private void MergeFeature(FeatureGenerator featureGenerator)

src/ImmutableObjectGraph.Generation/ImmutableObjectGraph.Generation.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
<ProjectReference Include="..\ImmutableObjectGraph\ImmutableObjectGraph.csproj" PrivateAssets="none" />
3535
</ItemGroup>
3636
<ItemGroup>
37-
<PackageReference Include="CG.Pluralization" Version="0.3000.5" PrivateAssets="all" />
37+
<PackageReference Include="CG.Pluralization" Version="0.3000.12" PrivateAssets="all" />
3838
<PackageReference Include="CodeGeneration.Roslyn" PrivateAssets="all" />
3939
<PackageReference Include="CodeGeneration.Roslyn.BuildTime" PrivateAssets="none" />
4040
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="all" />

src/ImmutableObjectGraph.sln

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio 15
4-
VisualStudioVersion = 15.0.27713.0
4+
VisualStudioVersion = 15.0.28010.2036
55
MinimumVisualStudioVersion = 10.0.40219.1
66
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImmutableObjectGraph", "ImmutableObjectGraph\ImmutableObjectGraph.csproj", "{63930555-500F-4E7B-9F24-3D5C3D4F0573}"
77
EndProject
@@ -10,6 +10,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
1010
..\.gitignore = ..\.gitignore
1111
..\appveyor.yml = ..\appveyor.yml
1212
..\CONTRIBUTING.md = ..\CONTRIBUTING.md
13+
Directory.Build.props = Directory.Build.props
14+
Directory.Build.targets = Directory.Build.targets
15+
global.json = global.json
1316
..\LICENSE.txt = ..\LICENSE.txt
1417
NuGet.Config = NuGet.Config
1518
..\README.md = ..\README.md
@@ -55,6 +58,6 @@ Global
5558
HideSolutionNode = FALSE
5659
EndGlobalSection
5760
GlobalSection(ExtensibilityGlobals) = postSolution
58-
SolutionGuid = {71E43380-4A06-41E1-AAAD-A7EF06351FEA}
61+
SolutionGuid = {72000F80-488D-45BC-91CE-75ED06C92E6C}
5962
EndGlobalSection
6063
EndGlobal

src/global.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"sdk": {
3-
"version": "2.1.300"
3+
"version": "2.1.402"
44
},
55
"msbuild-sdks": {
66
"MSBuild.Sdk.Extras": "1.5.4"

0 commit comments

Comments
 (0)