Skip to content
Open
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
70 changes: 65 additions & 5 deletions src/Nullean.Entities.SourceGenerators/ConstraintGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private static ImmutableArray<MemberInfo> AnalyzeAutoType(GeneratorAttributeSynt
}

var found = ImmutableArray.CreateBuilder<MemberInfo>();
found.AddRange(AutoMembers(type));
found.AddRange(AutoMembers(type, ctx.SemanticModel, _));
// A [Constraints] type that declares no Constraint<T> field but carries DataAnnotations still gets a set: the annotations are the rules.
var implicitRequired = ImplicitRequiredOf(ctx);
var validatableObject = ValidatableObjectOf(ctx);
Expand All @@ -132,7 +132,7 @@ private static ImmutableArray<MemberInfo> 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,
Expand All @@ -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<MemberInfo> AutoMembers(INamedTypeSymbol type) =>
private static IEnumerable<MemberInfo> 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.
Expand All @@ -170,7 +170,54 @@ private static IEnumerable<MemberInfo> 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)
}
);

/// <summary>
/// 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 <c>default</c>. A read inside a lambda or local function is skipped, it happens when the delegate is called.
/// </summary>
private static ImmutableArray<LaterRead> LaterStaticReads(ISymbol member, INamedTypeSymbol type, SemanticModel model, CancellationToken ct)
{
var reads = ImmutableArray.CreateBuilder<LaterRead>();
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<IdentifierNameSyntax>())
{
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();
}

/// <summary>
/// A type read via [Constraints] takes over entirely for that type: its explicit [Constraint]
Expand Down Expand Up @@ -241,6 +288,14 @@ private static void Generate(SourceProductionContext spc, ImmutableArray<MemberI
continue;
}

foreach (var member in groupMembers.Where(m => !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)
Expand Down Expand Up @@ -815,5 +870,10 @@ private sealed record MemberInfo(
ITypeSymbol? AnnotationType = null,
bool ImplicitRequired = true,
bool ValidatableObject = false
);
)
{
public ImmutableArray<LaterRead> LaterReads { get; init; }
}

private sealed record LaterRead(string FieldName, Location Location);
}
10 changes: 10 additions & 0 deletions src/Nullean.Entities.SourceGenerators/Diagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/Nullean.Entities.SourceGenerators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
54 changes: 54 additions & 0 deletions tests/Nullean.Entities.SourceGenerators.Tests/FieldOrderTests.cs
Original file line number Diff line number Diff line change
@@ -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<Order>]
public static partial class OrderRules
{
{{members}}
}
""";

private const string Rule = "public static readonly Constraint<Order> Named = Constraints<Order>.Always(Make(Clerk), \"named\");";
private const string Make = "private static Func<Order, bool> 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<Order> Named = Constraints<Order>.Always(_ => Clerk.Name.Length > 0, \"named\");";
var run = GeneratorTestHost.Run(Source($"{rule}\n{Clerk}"));

run.HasDiagnostic("NECG030").Should().BeFalse();
}
}