diff --git a/src/Nullean.Entities.SourceGenerators/ConstraintGenerator.cs b/src/Nullean.Entities.SourceGenerators/ConstraintGenerator.cs index f21c9b1..a4fc69d 100644 --- a/src/Nullean.Entities.SourceGenerators/ConstraintGenerator.cs +++ b/src/Nullean.Entities.SourceGenerators/ConstraintGenerator.cs @@ -108,7 +108,7 @@ private static ImmutableArray AnalyzeAutoType(GeneratorAttributeSynt } var found = ImmutableArray.CreateBuilder(); - found.AddRange(AutoMembers(type)); + found.AddRange(AutoMembers(type, ctx.SemanticModel, _)); // A [Constraints] type that declares no Constraint field but carries DataAnnotations still gets a set: the annotations are the rules. var implicitRequired = ImplicitRequiredOf(ctx); var validatableObject = ValidatableObjectOf(ctx); @@ -132,7 +132,7 @@ private static ImmutableArray AnalyzeGenericType(GeneratorAttributeS } var implicitRequired = ImplicitRequiredOf(ctx); return [ - .. AutoMembers(type).Select(m => m with { ImplicitRequired = implicitRequired }), + .. AutoMembers(type, ctx.SemanticModel, _).Select(m => m with { ImplicitRequired = implicitRequired }), new MemberInfo( type, about, @@ -154,7 +154,7 @@ private static bool ImplicitRequiredOf(GeneratorAttributeSyntaxContext ctx) => private static bool ValidatableObjectOf(GeneratorAttributeSyntaxContext ctx) => ctx.Attributes[0].NamedArguments.Any(n => n.Key == "ValidatableObject" && n.Value.Value is true); - private static IEnumerable AutoMembers(INamedTypeSymbol type) => + private static IEnumerable AutoMembers(INamedTypeSymbol type, SemanticModel model, CancellationToken ct) => type .GetMembers() // An auto-property's compiler-made backing field is not a member the author wrote: the property is the member. @@ -170,7 +170,54 @@ private static IEnumerable AutoMembers(INamedTypeSymbol type) => }) ) .Where(t => TryClassify(t.MemberType, out var unusedKind, out var unusedTypeArgument)) - .Select(t => new MemberInfo(type, t.MemberType, t.Member.Name, true, t.Member.Locations.FirstOrDefault() ?? Location.None)); + .Select( + t => new MemberInfo(type, t.MemberType, t.Member.Name, true, t.Member.Locations.FirstOrDefault() ?? Location.None) + { + LaterReads = LaterStaticReads(t.Member, type, model, ct) + } + ); + + /// + /// Static fields of the same type that the member's initializer reads while it runs and that are declared after it in the same file: C# initialises static + /// fields in declaration order, so the read sees default. A read inside a lambda or local function is skipped, it happens when the delegate is called. + /// + private static ImmutableArray LaterStaticReads(ISymbol member, INamedTypeSymbol type, SemanticModel model, CancellationToken ct) + { + var reads = ImmutableArray.CreateBuilder(); + foreach (var reference in member.DeclaringSyntaxReferences) + { + if (reference.SyntaxTree != model.SyntaxTree) + { + continue; + } + var initializer = reference.GetSyntax(ct) switch + { + VariableDeclaratorSyntax v => v.Initializer?.Value, + PropertyDeclarationSyntax p => p.Initializer?.Value, + _ => null + }; + if (initializer is null) + { + continue; + } + foreach (var name in initializer.DescendantNodesAndSelf( + n => n is not AnonymousFunctionExpressionSyntax and not LocalFunctionStatementSyntax + ).OfType()) + { + if ( + model.GetSymbolInfo(name, ct).Symbol is IFieldSymbol { IsStatic: true, IsConst: false } field && SymbolEqualityComparer.Default.Equals( + field.ContainingType, + type + ) && + field.DeclaringSyntaxReferences.FirstOrDefault(r => r.SyntaxTree == reference.SyntaxTree) is { } declared && declared.Span.Start > reference.Span.Start + ) + { + reads.Add(new LaterRead(field.Name, name.GetLocation())); + } + } + } + return reads.ToImmutable(); + } /// /// A type read via [Constraints] takes over entirely for that type: its explicit [Constraint] @@ -241,6 +288,14 @@ private static void Generate(SourceProductionContext spc, ImmutableArray !m.LaterReads.IsDefault)) + { + foreach (var read in member.LaterReads) + { + spc.ReportDiagnostic(Diagnostic.Create(Diagnostics.ReadsLaterStaticField, read.Location, member.MemberName, read.FieldName)); + } + } + var valid = new List<(MemberInfo Member, ConstraintKind Kind, ITypeSymbol TypeArgument)>(); var hadMemberError = false; foreach (var member in groupMembers) @@ -815,5 +870,10 @@ private sealed record MemberInfo( ITypeSymbol? AnnotationType = null, bool ImplicitRequired = true, bool ValidatableObject = false - ); + ) + { + public ImmutableArray LaterReads { get; init; } + } + + private sealed record LaterRead(string FieldName, Location Location); } diff --git a/src/Nullean.Entities.SourceGenerators/Diagnostics.cs b/src/Nullean.Entities.SourceGenerators/Diagnostics.cs index ff59784..aa40d98 100644 --- a/src/Nullean.Entities.SourceGenerators/Diagnostics.cs +++ b/src/Nullean.Entities.SourceGenerators/Diagnostics.cs @@ -86,6 +86,16 @@ internal static class Diagnostics isEnabledByDefault: true ); + // A warning: the code compiles and runs, it just hands the rule a default value. Not an error, since a read that only wants the field's type or is guarded is legal. + public static readonly DiagnosticDescriptor ReadsLaterStaticField = new( + "NECG030", + "Constraint reads a static field declared after it", + "'{0}' reads '{1}' while it is initialised, but '{1}' is declared below it so it is still default (null) at that point; static fields initialise in declaration order, move '{1}' above '{0}'", + Category, + DiagnosticSeverity.Warning, + isEnabledByDefault: true + ); + // Info, not a warning: a consumer that treats warnings as errors must not fail to build because a model carries [Phone] or a custom validation attribute. public static readonly DiagnosticDescriptor UnsupportedAnnotation = new( "NECG010", diff --git a/src/Nullean.Entities.SourceGenerators/README.md b/src/Nullean.Entities.SourceGenerators/README.md index a611ab1..e012ef6 100644 --- a/src/Nullean.Entities.SourceGenerators/README.md +++ b/src/Nullean.Entities.SourceGenerators/README.md @@ -87,7 +87,7 @@ error NECG001: 'ThingRules' has [Constraint] members but is not declared partial | `[Constraints(ValidatableObject = true)]` | `IValidatableObject`, so DataAnnotations validation (`Validator`, `AddValidation()`, MVC, Blazor, Options) runs the set's errors, minus the attribute rules it already checks. | | `[ConstraintIgnore]` | Leaves a member, property or method out. | -Diagnostics: `NECG001` to `NECG007` are errors (not partial, not static, wrong type, a non-partial container, mixed kinds, inconsistent type argument, a member about another type), and so are `NECG011` (`ValidatableObject = true` on a type that already has an `IValidatableObject.Validate`) and `NECG012` (`ValidatableObject = true` on a set about another type). `NECG010` (an unsupported validation attribute) and `NECG020` (a method not used as an action) are Info. +Diagnostics: `NECG001` to `NECG007` are errors (not partial, not static, wrong type, a non-partial container, mixed kinds, inconsistent type argument, a member about another type), and so are `NECG011` (`ValidatableObject = true` on a type that already has an `IValidatableObject.Validate`) and `NECG012` (`ValidatableObject = true` on a set about another type). `NECG010` (an unsupported validation attribute) and `NECG020` (a method not used as an action) are Info. `NECG030` is a warning: a constraint's initializer reads a static field declared below it, which is still `default` while the rule is built (static fields initialise in declaration order); a read inside a lambda is fine, it happens when the lambda runs. ## Pitfalls and limits diff --git a/tests/Nullean.Entities.SourceGenerators.Tests/FieldOrderTests.cs b/tests/Nullean.Entities.SourceGenerators.Tests/FieldOrderTests.cs new file mode 100644 index 0000000..0429edd --- /dev/null +++ b/tests/Nullean.Entities.SourceGenerators.Tests/FieldOrderTests.cs @@ -0,0 +1,54 @@ +using AwesomeAssertions; + +namespace Nullean.Entities.SourceGenerators.Tests; + +// C# initialises static fields in declaration order, so a rule that reads a field declared below it while it is built gets default. +public class FieldOrderTests +{ + private static string Source(string members) => + $$""" + using System; + using Nullean.Entities; + + namespace Sample; + + public sealed record User(string Name); + public sealed record Order(int Id); + + [Constraints] + public static partial class OrderRules + { + {{members}} + } + """; + + private const string Rule = "public static readonly Constraint Named = Constraints.Always(Make(Clerk), \"named\");"; + private const string Make = "private static Func Make(User u) => _ => u.Name.Length > 0;"; + private const string Clerk = "private static readonly User Clerk = new(\"clerk\");"; + + [Test] + public void A_direct_read_of_a_field_declared_below_is_reported() + { + var run = GeneratorTestHost.Run(Source($"{Rule}\n{Make}\n{Clerk}")); + + var d = run.Diagnostics.Single(d => d.Id == "NECG030"); + d.GetMessage().Should().Contain("'Named'").And.Contain("'Clerk'"); + } + + [Test] + public void A_field_declared_above_is_not_reported() + { + var run = GeneratorTestHost.Run(Source($"{Clerk}\n{Make}\n{Rule}")); + + run.HasDiagnostic("NECG030").Should().BeFalse(); + } + + [Test] + public void A_read_inside_a_lambda_is_not_reported_because_it_happens_when_the_lambda_runs() + { + var rule = "public static readonly Constraint Named = Constraints.Always(_ => Clerk.Name.Length > 0, \"named\");"; + var run = GeneratorTestHost.Run(Source($"{rule}\n{Clerk}")); + + run.HasDiagnostic("NECG030").Should().BeFalse(); + } +}