Skip to content
Purview Dev logo

AttributeDataModelGenerator generates readonly record struct parser models for .NET attributes. Instead of hand-writing FromAttributeData methods for every attribute you inspect in a source generator, declare a readonly partial record struct with [Generate] and the generator fills in the Empty sentinel, FromAttributeData overloads, and property extraction logic.

The generator is implemented in Purview.SourceGeneratorFramework.Generators and ships inside the Purview.SourceGeneratorFramework package under analyzers/dotnet/cs/, so it runs automatically when you reference the package.

The generator emits marker attributes into your compilation:

Attribute Purpose
[Generate(Type targetAttribute)] Placed on a readonly partial record struct to opt into generation.
[Generate(string targetAttribute)] Resolves the attribute by fully-qualified name. Use when the attribute type is not available in the generator’s compilation (e.g. LengthAttribute in .NET 8+ or a self-generated attribute).
[Property] A record parameter is populated from a named attribute property (the property name is inferred from the parameter name unless overridden). When combined with [Argument] on the same parameter, the named argument is read first.
[Property(string name)] Explicit named property source.
[Property(..., DefaultValue = ...)] Fallback value when the named property is not present.
[Argument] Populated from the constructor parameter named after the record parameter, camel-cased (MessageTemplate → messageTemplate).
[Argument(int index)] Constructor argument by parameter index.
[Argument(string name)] Constructor argument by parameter name.
[Argument(..., DefaultValue = ...)] Fallback when the constructor argument is not present.
[NestedModel] Populated from the same attribute by calling the nested generated model’s FromAttributeDataUnchecked, which skips its target-attribute check.
[Exclude] Skips auto-discovery for this parameter.
[GenericTypeArgument] Populated from a generic type argument of the attribute class.
[GenericTypeArgument(int index)] Generic type argument by position.
[GenericTypeArgument(string name)] Generic type argument by type parameter name.
using Microsoft.CodeAnalysis;
using Purview.SourceGeneratorFramework.Generators;
using System.ComponentModel.DataAnnotations;
namespace MySourceGenerator.Models;
[Generate(typeof(RequiredAttribute))]
public readonly partial record struct RequiredAttributeData(
bool AllowEmptyStrings
);

Generated output:

readonly record struct RequiredAttributeData(bool Exists, bool AllowEmptyStrings)
{
public static readonly RequiredAttributeData Empty = new(false, default(bool));
public static RequiredAttributeData FromAttributeData(ImmutableArray<AttributeData> attributes)
{
// ...
}
public static RequiredAttributeData FromAttributeData(AttributeData attributeData)
{
if (!TargetAttribute.Equals(attributeData.AttributeClass))
return Empty;
return FromAttributeDataUnchecked(attributeData);
}
public static RequiredAttributeData FromAttributeDataUnchecked(AttributeData attributeData)
{
attributeData.TryGetNamedArgument<bool>("AllowEmptyStrings", out var allowEmptyStrings);
return new(true, allowEmptyStrings);
}
}

FromAttributeData and TryFromAttributeData check the attribute’s type against TargetAttribute. FromAttributeDataUnchecked holds the argument reading without that check; it exists for nested models, and is rarely called directly.

When the attribute type is not referenced in the generator project, pass the fully-qualified name as a string. This is useful for attributes newer than the generator’s target framework (e.g. LengthAttribute in .NET 8+) or attributes that are generated by the same generator:

[Generate("System.ComponentModel.DataAnnotations.RequiredAttribute")]
public readonly partial record struct RequiredAttributeData(
bool AllowEmptyStrings
);

A plain type name ("RequiredAttribute") can also be used, which matches an attribute in the global namespace or in any namespace. AutoDiscover requires the real Type overload because it must inspect the attribute’s constructors and properties.

[Generate(typeof(LengthAttribute))]
public readonly partial record struct LengthAttributeData(
[Argument(0)] int MinimumLength,
[Argument(1)] int MaximumLength
);

Or by constructor parameter name:

[Generate(typeof(StringLengthAttribute))]
public readonly partial record struct StringLengthAttributeData(
[Argument("maximumLength", DefaultValue = 2147483647)] int MaximumLength,
int MinimumLength
);

Constructor and named arguments on the same property

Section titled “Constructor and named arguments on the same property”

A property can declare both sources:

[Generate(typeof(GenerateServiceAttribute))]
public readonly partial record struct GenerateServiceAttributeData(
[Argument("lifetime", IsEnum = true, DefaultValue = "…ServiceLifetime.Singleton")] string? Lifetime,
[Argument("name")] [Property] string? Name
);

The named argument is read first. A named argument assigns the property/field after the constructor runs, so it is the effective value whenever a caller supplies both — mirroring the attribute instance’s own assignment order. Reading it first also prevents an omitted optional constructor parameter’s default from shadowing an explicitly set property:

[GenerateService(Name = "Billing")] // reads "Billing"
[GenerateService(ServiceLifetime.Scoped, "Billing")] // reads "Billing"

Any property whose type is itself annotated with [Generate] can be populated as a nested model. This is useful for shared base attribute data, such as ValidationAttribute in System.ComponentModel.DataAnnotations:

[Generate(typeof(ValidationAttribute), MatchByInheritance = true)]
public readonly partial record struct ValidationAttributeData(
[Property] string? ErrorMessage,
[Property] string? ErrorMessageResourceName,
[Property] ITypeSymbol? ErrorMessageResourceType
);
[Generate(typeof(RequiredAttribute))]
public readonly partial record struct RequiredAttributeData(
bool AllowEmptyStrings,
[NestedModel] ValidationAttributeData ValidationAttribute
);

The nested model is read from the outer attribute’s constructor and named arguments, using its own [Argument]/[Property] mappings, through its FromAttributeDataUnchecked method. Its own TargetAttribute is not checked, because the outer model has already matched its attribute. So the outer attribute does not have to derive from the nested model’s target: it only needs to declare the same constructor parameter and property names. ValidationAttributeData also uses MatchByInheritance = true, so it can be used on its own against any attribute deriving from ValidationAttribute.

A nested model populated this way always has Exists set to true. A mapped argument or property that the outer attribute does not declare takes the nested model’s DefaultValue, or default(T) when it has none:

[Generate(typeof(LogEventAttribute))]
public readonly partial record struct LogEventAttributeData(
[Argument("level")] [Property(DefaultValue = LogLevel.Information)] LogLevel Level,
[Argument("messageTemplate")] [Property] string? MessageTemplate,
[Argument("eventId")] [Property(DefaultValue = -1)] int EventId,
[Property] string? Name
);
// InfoEventAttribute does not derive from LogEventAttribute, and has no `level`.
[Generate(typeof(InfoEventAttribute))]
public readonly partial record struct InfoEventAttributeData([NestedModel] LogEventAttributeData Log);

[InfoEvent("Cycle done: {Count}")] gives Log.MessageTemplate == "Cycle done: {Count}", Log.EventId == -1 and Log.Level == LogLevel.Information.

The generated code looks every name up case-sensitively at run time, and a name it cannot find yields the property’s DefaultValue (or default(T)). A mapping mistake therefore compiles cleanly and produces default values. Follow these rules, and let the naming analyzer check them:

  • A constructor source must name a parameter exactly: [Argument("messageTemplate")], not [Argument("MessageTemplate")]. A bare [Argument] uses the record parameter’s name, camel-cased.
  • A named source ([Property], or a parameter with no mapping attribute) must name a public settable property or field of the attribute. A property with a private or internal setter can only be read through the constructor parameter that sets it.
  • Prefer constructor sources by name over [Argument(index)]: an index silently moves to another parameter when overloads change, and means a different parameter on each attribute a nested model is read from.
  • A property must not be named Exists, Empty, TargetAttribute, AllAttributeData, FromAttributeData, TryFromAttributeData or FromAttributeDataUnchecked; those are generated. Keyword names such as Event or Class are supported.

AttributeDataModelNamingAnalyzer mirrors the generator’s source resolution and reports at the mapping:

Rule Severity Reported when
ADM0011 Warning A mapped constructor parameter or named argument matches an attribute member only when case is ignored.
ADM0012 Warning A named source is not a public settable member of the attribute, or a bare [Argument] implies a constructor parameter the attribute lacks.
ADM0013 Info A [NestedModel] property reads only names the outer attribute lacks, so it always takes its default.
ADM0014 Error A property has the name of a generated member. Generation is skipped for the model.
ADM0015 Warning A [NestedModel] property reads a constructor index that names a different parameter on the outer attribute.

An explicit [Argument("name")] or [Argument(index)] that matches nothing at all remains ADM0003. ADM0013 is informational because a nested model may read a value the outer attribute deliberately does not have (the level of a [Log] model nested in an [Info] model); check each one.

Test a model against the AttributeData Roslyn really produces. AttributeDataFactory (Purview.SourceGeneratorFramework.Testing) compiles an application without running a generator, and the TUnit AttributeDataAssertions pin each argument by ordinal, parameter name or named argument, including whether it was written positionally, by parameter name, as a named argument, or defaulted:

var options = new MyTestOptions { AdditionalNamespaces = ["My.Attributes"] };
var attribute = AttributeDataFactory.FromUsage("[InfoEvent(\"custom {Value}\")]", options);
await Assert.That(attribute).HasConstructorArgument("messageTemplate", "custom {Value}");
await Assert.That(attribute).DoesNotHaveNamedArgument("Name");
var model = InfoEventAttributeData.FromAttributeData(attribute);
await Assert.That(model.Log.MessageTemplate).IsEqualTo("custom {Value}");
await Assert.That(model.Log.EventId).IsEqualTo(-1); // DefaultValue, not default(int)
await Assert.That(model.Log.Level).IsEqualTo(LogLevel.Information);

For each model, cover positional, by-name and named-argument applications, an application that omits every optional argument, and — for a nested model — an outer attribute missing a mapped member. See Testing.md for the factory and Testing-TUnit.md for the assertions.

If the attribute class is generic, a record parameter can be populated from the attribute’s type argument:

[Generate(typeof(MyGenericAttribute<>))]
public readonly partial record struct MyGenericAttributeData<T>(
[GenericTypeArgument] T Value
);

Use [GenericTypeArgument(0)] or [GenericTypeArgument("TValue")] to disambiguate when the attribute has multiple type parameters.

For simple attributes you can let the generator discover all constructor parameters and public named properties automatically:

[Generate(typeof(RequiredAttribute), AutoDiscover = true)]
public readonly partial record struct RequiredAttributeData;

This generates the same RequiredAttributeData as the manual example above. Nested models are not auto-discovered; declare them explicitly if needed.

DefaultValue provides a runtime fallback when the attribute does not contain the requested property or argument. The Empty sentinel always uses default(T) for every property (including an Exists field set to false):

[Generate(typeof(HostKitAttribute))]
public readonly partial record struct HostKitAttributeData(
[Argument("name", DefaultValue = "MyApp")] string Name,
[Argument("generateOptions", DefaultValue = true)] bool GenerateOptions
);

A [TypeRef] member declared with GenerateFullNameConst produces a public const string {Member}FullName, which can be used as the [Generate] target of an attribute-data model instead of a typeof(...) value — see Type-Library.md for the full example.

Because the TypeLibrary class is emitted through TypeLibraryGenerator’s main pipeline, its constants are not present in the compilation that AttributeDataModelGenerator’s ForAttributeWithMetadataName pipeline sees (only post-initialization output is shared between generators in a single pass). AttributeDataModelGenerator therefore reassembles the target from the argument’s member-access expression — guarded so the root identifier must match a [GenerateTypeLibrary] spec’s ClassName — and resolves it against the compilation.

For [Argument]/[Property] members marked IsEnum = true, a DefaultValue supplied as a bare member name (for example "Inherit") is expanded to the fully-qualified "{EnumFullName}.{Member}" form using the enum type of the target attribute’s matching constructor parameter (for [Argument]) or property (for [Property]). Fully-qualified defaults and defaults whose enum type cannot be resolved are emitted unchanged.

This documentation is part of the MIT-licensed Purview.SourceGeneratorFramework project.