Aspects, fabrics, and validators look like ordinary C# classes, but they don't live like ordinary objects. Metalama creates them once and reuses them, for many target declarations and, in the IDE, for many versions of your project.
Each version of a project is called a compilation, a term that comes from Roslyn, the C# compiler. A compilation is an immutable snapshot of a project: all its source code, its references, and everything the compiler derives from them, such as syntax trees and symbols. A command-line build creates one compilation and exits. In the IDE, every keystroke creates a new compilation.
Compile-time code must therefore follow two rules:
- Immutability: an object that Metalama reuses must not change after it has been created.
- Durability: an object that Metalama keeps across compilations must not reference anything that belongs to one compilation.
Starting with Metalama 2027.0, analyzers verify both rules while you type and report warnings when your code breaks them. This article explains the rules and how to fix the warnings.
Why compile-time objects need rules
An aspect instance is created once and can be reused for every declaration it applies to. At design time, the IDE produces a new compilation on essentially every keystroke, and Metalama keeps reusing the same aspect instances, fabrics, and validators, and everything they registered, for as long as the compile-time code doesn't change.
This has two consequences:
- State leaks between targets. If an aspect changes a field while it processes one target, the next target sees the changed value. The order in which Metalama processes the targets isn't defined, so the result can differ between builds, and between a build and the IDE.
- Memory leaks in the IDE. An object kept across compilations that references a declaration of the code model, a Roslyn symbol, or a syntax tree keeps the whole version of the project it came from in memory. Memory then grows for as long as you edit. See Diagnosing memory leaks caused by compile-time code.
A static field of compile-time code is the extreme case of both: it's shared by every aspect instance, every target, and every compilation, and in the IDE it keeps its value for as long as the analysis process runs.
The immutability rule
The IAspect interface and the Fabric class are marked with the [ImmutableType] attribute, and every type that derives from them or implements them inherits the contract. Validators are checked in the same way. In a type subject to the contract:
- Every instance field must be
readonly, or private and assigned only in a constructor or aninitaccessor. - Every automatic property must have no setter, an
initaccessor, or a private setter that is assigned only in a constructor or aninitaccessor. - The type of every field and property must itself be immutable, all the way down. Intrinsic types, enums, delegates, and the collections of
System.Collections.Immutableare immutable, and an immutable collection is immutable only when its type arguments are. Any other type is mutable unless it's marked[ImmutableType]or declared as immutable in the project file.
The warnings of this rule are LAMA0880 to LAMA0888. For the full list, see Durability and immutability errors and warnings.
The following aspect breaks the rule twice. It counts its targets in an instance field, and it caches data in a static dictionary:
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using System;
4using System.Collections.Generic;
5
6namespace Doc.CompileTimeRules_Wrong;
7
8public sealed class LogAttribute : OverrideMethodAspect
9{
10 // WRONG. The same aspect instance can be reused for several targets and, at design time,
11 // for several compilations, so this counter does not count what you expect.
12 private int _targetCount;
13
14 // WRONG. A static field of compile-time code is shared by every aspect instance, every
15 // target and every compilation, and it lives as long as the IDE process.
Warning LAMA0891: 'LogAttribute' is a run-time-or-compile-time type, but the static member '_displayNames' is of type 'Dictionary<string, string>', which is not immutable (path: LogAttribute -> _displayNames -> Dictionary<string, string> (a mutable collection; use the corresponding type of System.Collections.Immutable)). A static field of a compile-time type is shared by every aspect instance, every target and every compilation, and at design time it keeps its value for as long as the analysis process runs. Mark the member with [RunTime] so that it exists only at run time, or make it read-only and of an immutable type.
16 private static readonly Dictionary<string, string> _displayNames = new();
17
18 public override void BuildAspect( IAspectBuilder<IMethod> builder )
19 {
Warning LAMA0887: 'LogAttribute' must be written in an immutable style because it is an aspect, a fabric, a validator, or another type bound by the [ImmutableType] contract, but '_targetCount' is assigned here, outside a constructor. Move the assignment into a constructor or an 'init' accessor.
20 this._targetCount++;
21 _displayNames[builder.Target.Name] = builder.Target.ToDisplayString();
22
23 base.BuildAspect( builder );
24 }
25
26 public override dynamic? OverrideMethod()
27 {
28 Console.WriteLine( $"Executing {meta.Target.Method}." );
29
30 return meta.Proceed();
31 }
32}
33
1namespace Doc.CompileTimeRules_Wrong;
2
3public class C
4{
5 [Log]
6 public void M() { }
7}
8
1using System;
2
3namespace Doc.CompileTimeRules_Wrong;
4
5public class C
6{
7 [Log]
8 public void M()
9 {
10 Console.WriteLine("Executing C.M().");
11 }
12}
13
Configuring an aspect without breaking the rule
The properties that users set with named arguments of the custom attribute don't need a setter: an init accessor is enough, and it makes the aspect immutable once it has been created.
1using Metalama.Framework.Aspects;
2using System;
3
4namespace Doc.CompileTimeRules_Immutable;
5
6public sealed class LogAttribute : OverrideMethodAspect
7{
8 // The property is set by a named argument of the custom attribute. An init accessor
9 // is enough for that, and it keeps the aspect immutable once it has been created.
10 public string Category { get; init; } = "General";
11
12 public override dynamic? OverrideMethod()
13 {
14 Console.WriteLine( $"[{this.Category}] Executing {meta.Target.Method}." );
15
16 return meta.Proceed();
17 }
18}
19
1namespace Doc.CompileTimeRules_Immutable;
2
3public class OrderService
4{
5 [Log( Category = "Orders" )]
6 public void PlaceOrder( string product, int quantity ) { }
7}
8
1using System;
2
3namespace Doc.CompileTimeRules_Immutable;
4
5public class OrderService
6{
7 [Log(Category = "Orders")]
8 public void PlaceOrder(string product, int quantity)
9 {
10 Console.WriteLine("[Orders] Executing OrderService.PlaceOrder(string, int).");
11 }
12}
13
Keeping per-target state
When an aspect needs to compute data for one target and use it later, keep the data in the objects that BuildAspect creates for that target, not in the aspect:
- Use local variables of
BuildAspect, and pass them to the template as tags or as template arguments. See Sharing state with advice. - Use the IAspectState of the aspect instance when child aspects or aspects of derived types need the data.
- Use annotations to attach data to a declaration for other aspects.
The durability rule
The [Durable] attribute declares that an object can be held across compilations. Aspects, fabrics, annotations, and aspect states are bound by this contract, because Metalama keeps them across compilations at design time. A durable object must not hold a strong reference to a compilation, a syntax tree, a semantic model, a Roslyn symbol, a declaration of the code model, or a non-durable reference, directly or through another object.
Intrinsic types are durable, and a system collection is durable when its type arguments are. Any other type isn't durable unless it's marked [Durable] or declared as durable in the project file. A delegate type is never durable by its declared type, because a delegate holds everything its closure captured. The analyzer examines what each lambda actually captures where a durable value is required.
The warnings of this rule are LAMA0870 to LAMA0879. To fix them:
- Store an identifier instead of the object. Replace a declaration with a durable reference: call
ToDurableRef()on the declaration, store the IDurableRef<T>, and resolve it withGetTarget( compilation )when you need the declaration. When the identifier must cross a process or a project boundary, store a SerializableDeclarationId. A reference to an attribute can't be durable, because an attribute has no identifier of its own: store a durable reference to the declaration that carries it, and find the attribute again in itsAttributescollection. - Store a durable expression instead of an IExpression, by calling ToDurable.
- Use DurableLazy<T> instead of
Lazy<T>.Lazy<T>holds its factory delegate, and therefore everything the delegate captured. - Mark your own type
[Durable]when it holds only durable members. The analyzer then verifies its members. - Use DurableDangerous<T> as a last resort, when a value is durable in fact but the analyzer can't establish it. The wrapper states the assertion in the signature of the member, which is better than suppressing the warning.
Example: storing a durable reference
The following fabric looks up a type once and passes it to the aspects that it adds, which store it in a field. An INamedType belongs to the compilation it came from, and the aspects outlive every compilation, so the field keeps one whole version of the project in memory for as long as the solution is open. Metalama reports LAMA0870 on the field:
using Metalama.Framework.Aspects;
using Metalama.Framework.Code;
using Metalama.Framework.Fabrics;
using System;
using System.Linq;
namespace Doc.RetainedDeclaration_Wrong;
public class Fabric : ProjectFabric
{
public override void AmendProject( IProjectAmender amender )
{
if ( TypeFactory.TryGetType( "Doc.Model.EntityRegistry", out var registry ) )
{
amender
.SelectTypes()
.Where( t => t.Name.EndsWith( "Entity", StringComparison.Ordinal ) )
.AddAspect( _ => new RegisterEntityAspect( registry ) );
}
}
}
internal sealed class RegisterEntityAspect : IAspect<INamedType>
{
// WRONG. An INamedType belongs to the compilation it came from, and the aspect outlives every
// compilation, so this field pins one whole version of the project for as long as the solution is open.
private readonly INamedType _registry;
public RegisterEntityAspect( INamedType registry )
{
this._registry = registry;
}
public void BuildAspect( IAspectBuilder<INamedType> builder )
{
// Use this._registry here.
}
}
The fix is to change the type of the field to IDurableRef<T>, and to convert the declaration with ToDurableRef() before the lambda captures it. A durable reference holds only a string identifier. Because the field type requires a durable reference, a later edit can't omit the conversion. To use the type, resolve the reference with GetTarget( compilation ), passing the compilation that you're working on, never a stored one:
using Metalama.Framework.Aspects;
using Metalama.Framework.Code;
using Metalama.Framework.Fabrics;
using System;
using System.Linq;
namespace Doc.RetainedDeclaration_Good;
public class Fabric : ProjectFabric
{
public override void AmendProject( IProjectAmender amender )
{
if ( TypeFactory.TryGetType( "Doc.Model.EntityRegistry", out var registry ) )
{
// Convert the declaration once. The lambda then captures only the durable reference.
var registryRef = registry.ToDurableRef();
amender
.SelectTypes()
.Where( t => t.Name.EndsWith( "Entity", StringComparison.Ordinal ) )
.AddAspect( _ => new RegisterEntityAspect( registryRef ) );
}
}
}
internal sealed class RegisterEntityAspect : IAspect<INamedType>
{
// A durable reference holds only a string identifier. Declaring the field as IDurableRef<INamedType>
// also makes the conversion mandatory at every assignment, so a later edit cannot omit it.
private readonly IDurableRef<INamedType> _registry;
public RegisterEntityAspect( IDurableRef<INamedType> registry )
{
this._registry = registry;
}
public void BuildAspect( IAspectBuilder<INamedType> builder )
{
// Resolve against the compilation you are working on, never against a stored one.
var registry = this._registry.GetTarget( builder.Target.Compilation );
}
}
To find out which objects keep a compilation alive at run time of the IDE, see Diagnosing memory leaks caused by compile-time code.
Static fields and properties
A static field or automatic property of a compile-time or run-time-or-compile-time type must be read-only, of an immutable type, and of a durable type. Constants aren't concerned. Metalama reports the first rule that a member breaks:
| Problem | Compile-time type | Run-time-or-compile-time type |
|---|---|---|
| The member isn't read-only. | LAMA0889 | LAMA0891 |
| The member is read-only, but its type isn't immutable. | LAMA0890 | LAMA0891 |
| The member is read-only and immutable, but its type isn't durable. | LAMA0892 | LAMA0892 |
In a run-time-or-compile-time type, such as an aspect class, a static field that only run-time code uses can be marked with [RunTime], so that it exists only at run time and isn't checked.
To keep a cache across targets, don't use a static field. Compute the data again for each target, or store it in an annotation or in the aspect state of the declaration it belongs to.
Marking your own types
When an aspect or a fabric stores an object of your own type, that type must satisfy the same rules. Mark it with [ImmutableType] and [Durable]: the analyzer then verifies its members, and types that derive from it inherit the contracts.
In the following example, a fabric creates one LogPolicy object and passes it to every aspect it adds. Because the aspects store the policy, LogPolicy is marked as immutable and durable:
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Code.SyntaxBuilders;
4using System;
5
6namespace Doc.CompileTimeRules_OwnType;
7
8internal sealed class LogAspect : IAspect<IMethod>
9{
10 private readonly LogPolicy _policy;
11
12 public LogAspect( LogPolicy policy )
13 {
14 this._policy = policy;
15 }
16
17 public void BuildAspect( IAspectBuilder<IMethod> builder )
18 {
19 builder.Override( nameof(this.OverrideMethod) );
20 }
21
22 [Template]
23 private dynamic? OverrideMethod()
24 {
25 var message = new InterpolatedStringBuilder();
26 message.AddText( $"[{this._policy.Category}] Executing {meta.Target.Method.Name}(" );
27
28 foreach ( var parameter in meta.Target.Parameters )
29 {
30 if ( parameter.Index > 0 )
31 {
32 message.AddText( ", " );
33 }
34
35 message.AddText( $"{parameter.Name}: " );
36
37 if ( this._policy.HiddenParameters.Contains( parameter.Name ) )
38 {
39 message.AddText( "***" );
40 }
41 else
42 {
43 message.AddExpression( parameter );
44 }
45 }
46
47 message.AddText( ")." );
48 Console.WriteLine( message.ToValue() );
49
50 return meta.Proceed();
51 }
52}
53
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Fabrics;
4using System.Collections.Immutable;
5using System.Linq;
6
7namespace Doc.CompileTimeRules_OwnType;
8
9internal class Fabric : ProjectFabric
10{
11 public override void AmendProject( IProjectAmender amender )
12 {
13 var policy = new LogPolicy( "Accounts", ImmutableArray.Create( "password" ) );
14
15 amender
16 .SelectMany( p => p.Types )
17 .Where( t => t.Name.EndsWith( "Service" ) )
18 .SelectMany( t => t.Methods )
19 .Where( m => m.Accessibility == Accessibility.Public )
20 .AddAspect( _ => new LogAspect( policy ) );
21 }
22}
23
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Utilities;
3using System.Collections.Immutable;
4
5namespace Doc.CompileTimeRules_OwnType;
6
7// The policy is stored in an aspect, so it must be immutable and durable too.
8// The attributes state these contracts, and the analyzer verifies every member.
9[CompileTime]
10[ImmutableType]
11[Durable]
12internal sealed class LogPolicy
13{
14 public LogPolicy( string category, ImmutableArray<string> hiddenParameters )
15 {
16 this.Category = category;
17 this.HiddenParameters = hiddenParameters;
18 }
19
20 public string Category { get; }
21
22 public ImmutableArray<string> HiddenParameters { get; }
23}
24
1namespace Doc.CompileTimeRules_OwnType;
2
3public class AccountService
4{
5 public void CreateAccount( string userName, string password ) { }
6}
7
1using System;
2
3namespace Doc.CompileTimeRules_OwnType;
4
5public class AccountService
6{
7 public void CreateAccount(string userName, string password)
8 {
9 Console.WriteLine($"[Accounts] Executing CreateAccount(userName: {userName}, password: ***).");
10 }
11}
12
For types that you don't own, declare the verdict in the project file with MSBuild items. Each item contains the full metadata name of a type, with the arity of generic types, as in Contoso.Pair`2:
| Item | Meaning |
|---|---|
MetalamaImmutableType |
The type is immutable. |
MetalamaImmutableContractType |
The types that derive from this type or implement it must be immutable, as if it were marked [ImmutableType]. |
MetalamaDurableType |
The type is durable. |
MetalamaNonDurableType |
The type isn't durable, even if the analyzer would otherwise consider it durable. |
A name that matches no type is reported with LAMA0879 or LAMA0885.
Turning the warnings off
All the diagnostics of these rules are warnings. When a rule doesn't apply to one declaration, suppress the warning with the usual mechanisms: #pragma warning disable, [SuppressMessage] with a justification, or a severity in an .editorconfig file. There is deliberately no attribute that exempts a type.
The MetalamaEnforceImmutabilityContract MSBuild property turns off the immutability rule and the checks of static fields for a whole project. It's intended for projects that implement Metalama itself, not for projects that use it.