Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Consumers.sln
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExampleExtensions", "sample
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vogen.Benchmarks", "tests\Vogen.Benchmarks\Vogen.Benchmarks.csproj", "{0FF8DF8D-76E3-4511-B204-44687615429D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "1MyProg", "samples\1MyProg\1MyProg.csproj", "{2CDDD2E7-2CC0-470B-AE5A-60B018F08998}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -96,6 +98,10 @@ Global
{0FF8DF8D-76E3-4511-B204-44687615429D}.Debug|Any CPU.Build.0 = Release|Any CPU
{0FF8DF8D-76E3-4511-B204-44687615429D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0FF8DF8D-76E3-4511-B204-44687615429D}.Release|Any CPU.Build.0 = Release|Any CPU
{2CDDD2E7-2CC0-470B-AE5A-60B018F08998}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2CDDD2E7-2CC0-470B-AE5A-60B018F08998}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2CDDD2E7-2CC0-470B-AE5A-60B018F08998}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2CDDD2E7-2CC0-470B-AE5A-60B018F08998}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
25 changes: 25 additions & 0 deletions samples/1MyProg/1MyProg.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_1MyProg</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UseLocallyBuiltPackage>true</UseLocallyBuiltPackage>
</PropertyGroup>

<ItemGroup Condition=" '$(UseLocallyBuiltPackage)' != ''">
<PackageReference Include="Vogen" Version="999.9.*" />
<PackageReference Update="MinVer" Version="7.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup Condition=" '$(UseLocallyBuiltPackage)' == ''">
<PackageReference Include="Vogen" Version="8.0.6-beta.2" />
</ItemGroup>


</Project>
6 changes: 6 additions & 0 deletions samples/1MyProg/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
using Vogen;

Console.WriteLine("Hello, World!");

[ValueObject]
public partial class MyId;
3 changes: 2 additions & 1 deletion samples/AotTrimmedSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using AotTrimmedSample;
using MyApp;
//using AotTrimmedSample;
using Vogen;

// to *not* generate the factory, use:
Expand Down
10 changes: 6 additions & 4 deletions src/Vogen/GenerateCodeForBsonSerializers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ internal class GenerateCodeForBsonSerializers
public static void GenerateForApplicableValueObjects(SourceProductionContext context,
Compilation compilation,
List<VoWorkItem> workItems,
Customizations? customizations)
Customizations? customizations,
string? rootNamespace)
{
if (!compilation.IsAtLeastCSharp12())
{
Expand All @@ -39,7 +40,7 @@ public static void GenerateForApplicableValueObjects(SourceProductionContext con
Util.AddSourceToContext(filename, context, Util.FormatSource(eachGenerated));
}

WriteRegistration(applicableWrappers, compilation, context, customizations);
WriteRegistration(applicableWrappers, compilation, context, customizations, rootNamespace);
}

/// <summary>
Expand Down Expand Up @@ -138,7 +139,8 @@ string GenerateSerializers()
private static void WriteRegistration(List<VoWorkItem> items,
Compilation compilation,
SourceProductionContext context,
Customizations? customizations)
Customizations? customizations,
string? rootNamespace)
{
if (items.Count == 0)
{
Expand All @@ -154,7 +156,7 @@ private static void WriteRegistration(List<VoWorkItem> items,

string ClassNameForRegistering()
{
string projectName = ProjectName.FromAssemblyName(compilation.AssemblyName ?? "").Value;
string projectName = ProjectName.FromRootNamespaceOrAssemblyName(rootNamespace, compilation.AssemblyName ?? "").Value;

string s = "BsonSerializationRegister";
if(projectName.Length > 0)
Expand Down
5 changes: 3 additions & 2 deletions src/Vogen/GenerateCodeForOpenApiSchemaCustomization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ public static void WriteIfNeeded(VogenConfiguration? globalConfig,
List<VoWorkItem> workItems,
VogenKnownSymbols knownSymbols,
MarkersCollection markerClasses,
Compilation compilation)
Compilation compilation,
string? rootNamespace)
{
GenerateCodeForAspNetCoreOpenApiSchema.WriteOpenApiSpecForMarkers(context, workItems, knownSymbols, markerClasses);

var c = globalConfig?.OpenApiSchemaCustomizations ??
VogenConfiguration.DefaultInstance.OpenApiSchemaCustomizations;

var projectName = ProjectName.FromAssemblyName(compilation.Assembly.Name);
var projectName = ProjectName.FromRootNamespaceOrAssemblyName(rootNamespace, compilation.Assembly.Name);

var className = string.IsNullOrEmpty(projectName) ? string.Empty : $"MapVogenTypesIn{projectName}";

Expand Down
5 changes: 3 additions & 2 deletions src/Vogen/GenerateCodeForSystemTextJsonConverterFactories.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ public static void WriteIfNeeded(VogenConfiguration? globalConfig,
List<VoWorkItem> workItems,
SourceProductionContext context,
Compilation compilation,
VogenKnownSymbols vogenKnownSymbols)
VogenKnownSymbols vogenKnownSymbols,
string? rootNamespace)
{
if (vogenKnownSymbols.JsonConverterFactory is null)
{
Expand All @@ -29,7 +30,7 @@ public static void WriteIfNeeded(VogenConfiguration? globalConfig,

var entries = workItems.Where(i => i.Config.Conversions.HasFlag(Conversions.SystemTextJson)).Select(BuildEntry);

var fullNamespace = ProjectName.FromAssemblyName(compilation.Assembly.Name);
var fullNamespace = ProjectName.FromRootNamespaceOrAssemblyName(rootNamespace, compilation.Assembly.Name);

string source =
$$"""
Expand Down
31 changes: 22 additions & 9 deletions src/Vogen/Types/ProjectName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,31 @@ internal class ProjectName
private ProjectName(string value) => Value = value;

/// <summary>
/// Replaces [., -] with [_] for use as type type names etc.
/// Returns a <see cref="ProjectName"/> from the MSBuild <c>RootNamespace</c> property when it is set,
/// otherwise falls back to <see cref="FromAssemblyName"/>. Either value is normalised.
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
public static ProjectName FromAssemblyName(string assemblyName)
public static ProjectName FromRootNamespaceOrAssemblyName(string? rootNamespace, string assemblyName) =>
!string.IsNullOrWhiteSpace(rootNamespace) ? new(Normalise(rootNamespace!)) : FromAssemblyName(assemblyName);

/// <summary>
/// Replaces [., ,, space, -] with [_] for use as type names etc., and ensures the result
/// does not start with a digit (which would produce an invalid C# identifier).
/// </summary>
public static ProjectName FromAssemblyName(string assemblyName) => new(Normalise(assemblyName));

private static string Normalise(string value)
{
assemblyName = assemblyName.Replace(".", "_");
assemblyName = assemblyName.Replace(",", "_");
assemblyName = assemblyName.Replace(" ", "_");
assemblyName = assemblyName.Replace("-", "_");
value = value.Replace(".", "_");
value = value.Replace(",", "_");
value = value.Replace(" ", "_");
value = value.Replace("-", "_");

if (value.Length > 0 && char.IsDigit(value[0]))
{
value = "_" + value;
}

return new(assemblyName);
return value;
}

public string Value { get; }
Expand Down
30 changes: 22 additions & 8 deletions src/Vogen/ValueObjectGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,30 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
var compilationAndValues = context.CompilationProvider.Combine(targetsConfigAndMarkers);

var everything = compilationAndValues.Combine(knownSymbols);

IncrementalValueProvider<string?> rootNamespace = context.AnalyzerConfigOptionsProvider
.Select(static (options, _) =>
{
options.GlobalOptions.TryGetValue("build_property.RootNamespace", out var ns);
return ns;
});

var everythingWithNs = everything.Combine(rootNamespace);

context.RegisterSourceOutput(everything,
context.RegisterSourceOutput(everythingWithNs,
static (spc, source) =>
{
var left = source.Left;
var everything = source.Left;
string? rootNs = source.Right;

var left = everything.Left;

// todo: break apart building the work items, as that only needs global config,
// which will make the following less horrific!
Compilation compilation = left.Left;
var targets = left.Right.Left.Left;
var globalConfig = left.Right.Left.Right;
var ks = source.Right;
var ks = everything.Right;
ImmutableArray<MarkerDiscovery?> markerClasses = left.Right.Right;

Execute(
Expand All @@ -52,7 +64,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
targets,
globalConfig,
markerClasses,
spc);
spc,
rootNs);
});
}

Expand Down Expand Up @@ -88,7 +101,8 @@ private static void Execute(
ImmutableArray<VoTarget> targets,
ImmutableArray<VogenConfigurationBuildResult> globalConfigBuildResult,
ImmutableArray<MarkerDiscovery?> markerDiscoveries,
SourceProductionContext spc)
SourceProductionContext spc,
string? rootNamespace)
{
var csharpCompilation = compilation as CSharpCompilation;
if (csharpCompilation is null)
Expand Down Expand Up @@ -127,7 +141,7 @@ private static void Execute(
// get all the ValueObject types found.
List<VoWorkItem> workItems = GetWorkItems(targets, spc, globalConfig, csharpCompilation.LanguageVersion, vogenKnownSymbols, compilation).ToList();

GenerateCodeForOpenApiSchemaCustomization.WriteIfNeeded(globalConfig, spc, workItems, vogenKnownSymbols, markerClasses, compilation);
GenerateCodeForOpenApiSchemaCustomization.WriteIfNeeded(globalConfig, spc, workItems, vogenKnownSymbols, markerClasses, compilation, rootNamespace);

GenerateCodeForEfCoreMarkers.Generate(spc, compilation, markerClasses);

Expand All @@ -136,7 +150,7 @@ private static void Execute(
GenerateCodeForMessagePack.GenerateForApplicableValueObjects(spc, compilation, workItems);
GenerateCodeForMessagePack.GenerateForMarkerClasses(spc, markerClasses);

GenerateCodeForBsonSerializers.GenerateForApplicableValueObjects(spc, compilation, workItems, globalConfig?.Customizations);
GenerateCodeForBsonSerializers.GenerateForApplicableValueObjects(spc, compilation, workItems, globalConfig?.Customizations, rootNamespace);
GenerateCodeForBsonSerializers.GenerateForMarkerClasses(spc, markerClasses);

GenerateCodeForOrleansSerializers.WriteIfNeeded(spc, workItems);
Expand All @@ -149,7 +163,7 @@ private static void Execute(

GenerateCodeForStaticAbstracts.WriteInterfacesAndMethodsIfNeeded(mergedConfig, spc, compilation);

GenerateCodeForSystemTextJsonConverterFactories.WriteIfNeeded(mergedConfig, workItems, spc, compilation, vogenKnownSymbols);
GenerateCodeForSystemTextJsonConverterFactories.WriteIfNeeded(mergedConfig, workItems, spc, compilation, vogenKnownSymbols, rootNamespace);

foreach (var eachWorkItem in workItems)
{
Expand Down
13 changes: 11 additions & 2 deletions tests/Shared/ProjectBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public sealed class ProjectBuilder
private bool _excludeStj;
private LanguageVersion _languageVersion = LanguageVersion.Default;
private string _assemblyName = "generator";
private readonly Dictionary<string, string> _buildProperties = new();

public ProjectBuilder WithTargetFramework(TargetFramework targetFramework)
{
Expand Down Expand Up @@ -296,6 +297,13 @@ public ProjectBuilder WithAssemblyName(string assemblyName)
return this;
}

public ProjectBuilder WithBuildProperty(string key, string value)
{
_buildProperties[key] = value;

return this;
}

public ProjectBuilder WithNugetPackages(IEnumerable<NuGetPackage> packages)
{
foreach (var nuGetPackage in packages)
Expand Down Expand Up @@ -350,7 +358,7 @@ internal static class IsExternalInit {}
_references,
options);

AnalyzerConfigOptionsProvider optionsProvider = new TestAnalyzerConfigOptionsProvider(new Dictionary<string, string>());
AnalyzerConfigOptionsProvider optionsProvider = new TestAnalyzerConfigOptionsProvider(_buildProperties);

ImmutableArray<Diagnostic> initialDiags;

Expand Down Expand Up @@ -378,7 +386,8 @@ internal static class IsExternalInit {}

var driver = CSharpGeneratorDriver
.Create(generator)
.WithUpdatedParseOptions(parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
.WithUpdatedParseOptions(parseOptions.WithDocumentationMode(DocumentationMode.Diagnose))
.WithUpdatedAnalyzerConfigOptions(optionsProvider);

driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiags);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ public async Task Writes_bson_serializers()
using System;
using Vogen;

[assembly: VogenDefaults(conversions: Conversions.Bson)]
[assembly: VogenDefaults(
staticAbstractsGeneration: StaticAbstractsGeneration.MostCommon | StaticAbstractsGeneration.InstanceMethodsAndProperties,
conversions: Conversions.Default | Conversions.Bson)]

// [assembly: VogenDefaults(conversions: Conversions.Bson)]

namespace Whatever;
namespace Vogen.Examples.SerializationAndConversion.Mongo;
[ValueObject<int>]
public partial struct Age;

Expand All @@ -25,6 +29,7 @@ public partial struct Name;

await new SnapshotRunner<ValueObjectGenerator>()
.WithSource(source)
.WithAssemblyName("Vogen.Examples")
.IgnoreInitialCompilationErrors()
.RunOn(TargetFramework.Net8_0);
}
Expand Down
Loading
Loading