-
-
Notifications
You must be signed in to change notification settings - Fork 535
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add C# Source Generator #1726
Open
valchetski
wants to merge
1
commit into
RicoSuter:master
Choose a base branch
from
valchetski:source-generator
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+886
−2
Open
Add C# Source Generator #1726
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<Import Project="../NJsonSchema.SourceGenerators.CSharp/NJsonSchema.SourceGenerators.CSharp.props" /> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
|
@@ -9,14 +10,26 @@ | |
<StartupObject /> | ||
<Nullable>disable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\NJsonSchema.Benchmark\NJsonSchema.Benchmark.csproj" /> | ||
<ProjectReference Include="..\NJsonSchema\NJsonSchema.csproj" /> | ||
<ProjectReference Include="..\NJsonSchema.SourceGenerators.CSharp\NJsonSchema.SourceGenerators.CSharp.csproj" | ||
ReferenceOutputAssembly="false" | ||
OutputItemType="Analyzer" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<None Update="Tests\**\*.json" CopyToOutputDirectory="PreserveNewest" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<AdditionalFiles | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In this project you can see how Source Generator actually works |
||
Include="schema.json" | ||
NJsonSchema_GenerateOptionalPropertiesAsNullable="true" | ||
NJsonSchema_Namespace="NJsonSchema.Demo.Generated" | ||
NJsonSchema_TypeNameHint="PersonGenerated" | ||
NJsonSchema_FileName="Person.g.cs" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
{ | ||
"$id": "https://example.com/person.schema.json", | ||
"$schema": "https://json-schema.org/draft/2020-12/schema", | ||
"title": "Person", | ||
"type": "object", | ||
"properties": { | ||
"firstName": { | ||
"type": "string", | ||
"description": "The person's first name." | ||
}, | ||
"lastName": { | ||
"type": "string", | ||
"description": "The person's last name." | ||
}, | ||
"age": { | ||
"description": "Age in years which must be equal to or greater than zero.", | ||
"type": "integer", | ||
"optional": true | ||
} | ||
} | ||
} |
269 changes: 269 additions & 0 deletions
269
src/NJsonSchema.SourceGenerators.CSharp.Tests/JsonSchemaSourceGeneratorTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,269 @@ | ||
using Microsoft.CodeAnalysis; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using Xunit.Abstractions; | ||
using static NJsonSchema.SourceGenerators.CSharp.GeneratorConfigurationKeys; | ||
|
||
namespace NJsonSchema.SourceGenerators.CSharp.Tests | ||
{ | ||
public class JsonSchemaSourceGeneratorTests : TestsBase | ||
{ | ||
public JsonSchemaSourceGeneratorTests(ITestOutputHelper output) : base(output) | ||
{ | ||
} | ||
|
||
[Fact] | ||
public void When_no_additional_files_specified_then_no_source_is_generated() | ||
{ | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput(null, []); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
Assert.Empty(compilation.SyntaxTrees); | ||
} | ||
|
||
[Fact] | ||
public void When_invalid_path_specified_then_nothing_is_generated() | ||
{ | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput(null, [new AdditionalTextStub("not_existing.json")]); | ||
|
||
Assert.NotEmpty(outputDiagnostics); | ||
Assert.Single(outputDiagnostics); | ||
var outputDiagnostic = outputDiagnostics[0]; | ||
Assert.Equal("NJSG001", outputDiagnostic.Id); | ||
Assert.Equal(DiagnosticSeverity.Error, outputDiagnostic.Severity); | ||
|
||
Assert.Empty(compilation.SyntaxTrees); | ||
} | ||
|
||
[Fact] | ||
public void When_without_config_then_generated_with_default_values() | ||
{ | ||
var firstName = "Alex"; | ||
var defaultNamespace = "MyNamespace"; | ||
|
||
string source = $@" | ||
namespace Example | ||
{{ | ||
class Test | ||
{{ | ||
public static string RunTest() | ||
{{ | ||
var json = new {defaultNamespace}.Person() | ||
{{ | ||
FirstName = ""{firstName}"" | ||
}}; | ||
return json.FirstName; | ||
}} | ||
}} | ||
}}"; | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput(source, [new AdditionalTextStub("References/schema.json")]); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
|
||
Assert.Equal(2, compilation.SyntaxTrees.Count()); | ||
|
||
Assert.Equal(firstName, RunTest(compilation)); | ||
} | ||
|
||
[Theory] | ||
[InlineData(null, false)] | ||
[InlineData("false", false)] | ||
[InlineData("False", false)] | ||
[InlineData("true", true)] | ||
[InlineData("True", true)] | ||
public void When_GenerateOptionalPropertiesAsNullable_in_global_options_then_generate_according_to_config( | ||
string generateOptionalPropertiesAsNullable, | ||
bool shouldBeNullable) | ||
{ | ||
string source = $@" | ||
namespace Example | ||
{{ | ||
class Test | ||
{{ | ||
public static string RunTest() | ||
{{ | ||
var json = new MyNamespace.Person(); | ||
return System.Convert.ToString(json.Age); | ||
}} | ||
}} | ||
}}"; | ||
var globalOptions = new Dictionary<string, string> | ||
{ | ||
{ GenerateOptionalPropertiesAsNullable, generateOptionalPropertiesAsNullable } | ||
}; | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput( | ||
source, | ||
[new AdditionalTextStub("References/schema.json")], | ||
globalOptions); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
|
||
Assert.Equal(2, compilation.SyntaxTrees.Count()); | ||
|
||
var expectedOutput = shouldBeNullable ? string.Empty : "0"; | ||
Assert.Equal(expectedOutput, RunTest(compilation)); | ||
} | ||
|
||
[Theory] | ||
[InlineData(null, "true", true)] | ||
[InlineData("false", "true", false)] | ||
[InlineData("False", "true", false)] | ||
[InlineData("true", "false", true)] | ||
[InlineData("True", "false", true)] | ||
public void When_GenerateOptionalPropertiesAsNullable_in_additional_files_then_generate_according_to_config_and_override_global_if_possible( | ||
string generateOptionalPropertiesAsNullableAdditionalFiles, | ||
string generateOptionalPropertiesAsNullableGlobalOptions, | ||
bool shouldBeNullable) | ||
{ | ||
string source = $@" | ||
namespace Example | ||
{{ | ||
class Test | ||
{{ | ||
public static string RunTest() | ||
{{ | ||
var json = new MyNamespace.Person(); | ||
return System.Convert.ToString(json.Age); | ||
}} | ||
}} | ||
}}"; | ||
var globalOptions = new Dictionary<string, string> | ||
{ | ||
{ GenerateOptionalPropertiesAsNullable, generateOptionalPropertiesAsNullableGlobalOptions } | ||
}; | ||
var additionalFilesOptions = new Dictionary<string, string> | ||
{ | ||
{ GenerateOptionalPropertiesAsNullable, generateOptionalPropertiesAsNullableAdditionalFiles } | ||
}; | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput( | ||
source, | ||
[new AdditionalTextStub("References/schema.json", additionalFilesOptions)], | ||
globalOptions); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
|
||
Assert.Equal(2, compilation.SyntaxTrees.Count()); | ||
|
||
var expectedOutput = shouldBeNullable ? string.Empty : "0"; | ||
Assert.Equal(expectedOutput, RunTest(compilation)); | ||
} | ||
|
||
[Theory] | ||
[InlineData(null, null, "MyNamespace")] | ||
[InlineData("", null, "MyNamespace")] | ||
[InlineData(null, "", "MyNamespace")] | ||
[InlineData(null, "NamespaceFromGlobalOptions", "NamespaceFromGlobalOptions")] | ||
[InlineData("NamespaceFromLocalOptions", null, "NamespaceFromLocalOptions")] | ||
[InlineData("NamespaceFromLocalOptions", "NamespaceFromGlobalOptions", "NamespaceFromLocalOptions")] | ||
public void When_Namespace_in_config_then_generate( | ||
string namespaceAdditionalFiles, | ||
string namespaceGlobalOptions, | ||
string expectedNamespace) | ||
{ | ||
string source = $@" | ||
namespace Example | ||
{{ | ||
class Test | ||
{{ | ||
public static string RunTest() | ||
{{ | ||
var json = new {expectedNamespace}.Person(); | ||
return ""compiled""; | ||
}} | ||
}} | ||
}}"; | ||
var globalOptions = new Dictionary<string, string> | ||
{ | ||
{ Namespace, namespaceGlobalOptions } | ||
}; | ||
var additionalFilesOptions = new Dictionary<string, string> | ||
{ | ||
{ Namespace, namespaceAdditionalFiles } | ||
}; | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput( | ||
source, | ||
[new AdditionalTextStub("References/schema.json", additionalFilesOptions)], | ||
globalOptions); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
|
||
Assert.Equal(2, compilation.SyntaxTrees.Count()); | ||
|
||
Assert.Equal("compiled", RunTest(compilation)); | ||
} | ||
|
||
[Theory] | ||
[InlineData(null, null, "Person")] | ||
[InlineData(null, "", "Person")] | ||
[InlineData("", null, "Person")] | ||
[InlineData(null, "ShouldNotOverride", "Person")] | ||
[InlineData("ShouldOverride", null, "ShouldOverride")] | ||
public void When_TypeNameHint_in_config_then_generate_using_additional_files_only( | ||
string typeNameHintAdditionalFiles, | ||
string typeNameHintGlobalOptions, | ||
string expectedTypeName) | ||
{ | ||
string source = $@" | ||
namespace Example | ||
{{ | ||
class Test | ||
{{ | ||
public static string RunTest() | ||
{{ | ||
var json = new MyNamespace.{expectedTypeName}(); | ||
return ""compiled""; | ||
}} | ||
}} | ||
}}"; | ||
var globalOptions = new Dictionary<string, string> | ||
{ | ||
{ TypeNameHint, typeNameHintGlobalOptions } | ||
}; | ||
var additionalFilesOptions = new Dictionary<string, string> | ||
{ | ||
{ TypeNameHint, typeNameHintAdditionalFiles } | ||
}; | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput( | ||
source, | ||
[new AdditionalTextStub("References/schema.json", additionalFilesOptions)], | ||
globalOptions); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
|
||
Assert.Equal(2, compilation.SyntaxTrees.Count()); | ||
|
||
Assert.Equal("compiled", RunTest(compilation)); | ||
} | ||
|
||
[Theory] | ||
[InlineData(null, null, "NJsonSchemaGenerated.g.cs")] | ||
[InlineData("", null, "NJsonSchemaGenerated.g.cs")] | ||
[InlineData(null, "", "NJsonSchemaGenerated.g.cs")] | ||
[InlineData(null, "ShouldNotOverride.g.cs", "NJsonSchemaGenerated.g.cs")] | ||
[InlineData("ShouldOverride.g.cs", null, "ShouldOverride.g.cs")] | ||
public void When_FileName_in_config_then_generate_using_additional_files_only( | ||
string fileNameAdditionalFiles, | ||
string fileNameGlobalOptions, | ||
string expectedFileName) | ||
{ | ||
var globalOptions = new Dictionary<string, string> | ||
{ | ||
{ FileName, fileNameGlobalOptions } | ||
}; | ||
var additionalFilesOptions = new Dictionary<string, string> | ||
{ | ||
{ FileName, fileNameAdditionalFiles } | ||
}; | ||
var (compilation, outputDiagnostics) = GetGeneratedOutput( | ||
null, | ||
[new AdditionalTextStub("References/schema.json", additionalFilesOptions)], | ||
globalOptions); | ||
|
||
Assert.Empty(outputDiagnostics); | ||
|
||
Assert.Single(compilation.SyntaxTrees); | ||
var syntaxTree = compilation.SyntaxTrees.First(); | ||
Assert.EndsWith(expectedFileName, syntaxTree.FilePath); | ||
} | ||
} | ||
} |
34 changes: 34 additions & 0 deletions
34
...JsonSchema.SourceGenerators.CSharp.Tests/NJsonSchema.SourceGenerators.CSharp.Tests.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<IsPackable>false</IsPackable> | ||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> | ||
<Nullable>disable</Nullable> | ||
<IsTestProject>true</IsTestProject> | ||
<EnableNETAnalyzers>false</EnableNETAnalyzers> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Content Include="..\NJsonSchema.Demo\schema.json" Link="References\schema.json"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
</Content> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.NET.Test.Sdk" /> | ||
<PackageReference Include="xunit" /> | ||
<PackageReference Include="xunit.runner.visualstudio" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\NJsonSchema.SourceGenerators.CSharp\NJsonSchema.SourceGenerators.CSharp.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Using Include="Xunit" /> | ||
</ItemGroup> | ||
|
||
</Project> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Source generators do not support transient dependencies: dotnet/sdk#17775
Because of that need to explicitly install some transient packages.
For example, it'll be used here to include
Parlot
into NuGet package https://github.com/RicoSuter/NJsonSchema/pull/1726/files#diff-ead3877feb09b2619c61d0feb8b85e0c85c627756febe0dda0829dafe13d5325R39