Open sandboxFocusImprove this doc

LAMA0042: A low-level aspect is ordered between two layers of another aspect

Severity Error
Reported by Metalama.Framework
Message The aspect '<AspectType>' has several layers, but the low-level aspect '<WeaverAspectType>' is ordered between two of these layers. A low-level aspect, which is an aspect implemented by an IAspectWeaver, cannot be ordered between two layers of another aspect because it would split that aspect across two pipeline stages. Add an [assembly: AspectOrder(...)] attribute to order '<WeaverAspectType>' before or after all layers of '<AspectType>'.

Cause

Most aspects are high-level aspects: they transform code with advice and templates. A low-level aspect is implemented by an aspect weaver, a class implementing IAspectWeaver from the Metalama SDK, which rewrites the syntax tree directly. Some community packages, such as Metalama.Community.Virtuosity, are based on aspect weavers.

Metalama executes the aspects in their order, which is determined by [assembly: AspectOrder] attributes and, when no order is specified, by the aspect names. An aspect weaver always runs in its own stage of the pipeline, and all consecutive high-level aspects run together in another stage. An aspect can have several layers, for instance contract aspects of Metalama.Patterns.Contracts, and all layers of a high-level aspect must run in the same stage.

Metalama reports LAMA0042 when the order of aspects places a low-level aspect between two layers of the same high-level aspect, because this would split that aspect across two stages. In the message, <AspectType> is the aspect with several layers and <WeaverAspectType> is the low-level aspect. This can happen even if you didn't specify any order between these two aspects: when the order between two aspects isn't specified, Metalama sorts them by their position in the other [AspectOrder] attributes, including those of referenced aspect libraries, and then by name, so the low-level aspect can fall between the layers of the other aspect.

Metalama reports LAMA0042 only when the project applies the aspect <AspectType> at least once. An aspect class that the project can see but doesn't apply, such as a contract aspect of Metalama.Patterns.Contracts that the project doesn't use, doesn't cause the error. The diagnostic is reported once on the aspect class <AspectType>. Metalama skips the instances of this aspect, and because the diagnostic is an error, the build fails.

In the following example, the [assembly: AspectOrder] attributes order Log before both MakeVirtual, a low-level aspect, and NotNull, a contract aspect, but they don't order MakeVirtual relatively to NotNull. Metalama sorts these two aspects by name and places MakeVirtual between the two layers of NotNull.

1using Metalama.Framework.Aspects;
2using Metalama.Framework.Engine;
3using Metalama.Framework.Engine.AspectWeavers;
4using Metalama.Framework.Engine.Utilities.Roslyn;
5using Microsoft.CodeAnalysis;
6using Microsoft.CodeAnalysis.CSharp;
7using Microsoft.CodeAnalysis.CSharp.Syntax;
8using System;
9using System.Threading.Tasks;
10
11// [Log] executes before [MakeVirtual] and before [NotNull], but the order between [MakeVirtual] and [NotNull]
12// isn't specified.
13[assembly: AspectOrder( AspectOrderDirection.CompileTime, typeof(Doc.LAMA0042.Error.LogAttribute), typeof(Doc.LAMA0042.Error.MakeVirtualAttribute) )]
14[assembly: AspectOrder( AspectOrderDirection.CompileTime, typeof(Doc.LAMA0042.Error.LogAttribute), typeof(Doc.LAMA0042.Error.NotNullAttribute) )]
15
16namespace Doc.LAMA0042.Error;
17
18// A low-level aspect, implemented by an aspect weaver.
19[RequireAspectWeaver( "Doc.LAMA0042.Error.MakeVirtualWeaver" )]
20internal class MakeVirtualAttribute : TypeAspect { }
21
22[MetalamaPlugIn]
23internal class MakeVirtualWeaver : IAspectWeaver
24{
25    public Task TransformAsync( AspectWeaverContext context ) => context.RewriteAspectTargetsAsync( new Rewriter() );
26
27    private class Rewriter : SafeSyntaxRewriter
28    {
29        // Adds the virtual modifier to public methods.
30        public override SyntaxNode? VisitMethodDeclaration( MethodDeclarationSyntax node )
31            => node.Modifiers.Any( SyntaxKind.PublicKeyword ) && !node.Modifiers.Any( SyntaxKind.VirtualKeyword )
32                ? node.AddModifiers( SyntaxFactory.Token( SyntaxKind.VirtualKeyword ).WithTrailingTrivia( SyntaxFactory.Space ) )
33                : node;
34    }
35}
36
37// A contract aspect, which has two layers.
Error LAMA0042: The aspect 'NotNull' has several layers, but the low-level aspect 'MakeVirtual' is ordered between two of these layers. A low-level aspect, which is an aspect implemented by an IAspectWeaver, cannot be ordered between two layers of another aspect because it would split that aspect across two pipeline stages. Add an [assembly: AspectOrder(...)] attribute to order 'MakeVirtual' before or after all layers of 'NotNull'.

38internal class NotNullAttribute : ContractAspect
39{
40    public override void Validate( dynamic? value )
41    {
42        if ( value == null )
43        {
44            throw new ArgumentNullException( meta.Target.Parameter.Name );
45        }
46    }
47}
48
49// A high-level aspect, which has a single layer.
50internal class LogAttribute : OverrideMethodAspect
51{
52    public override dynamic? OverrideMethod()
53    {
54        Console.WriteLine( $"Executing {meta.Target.Method}." );
55
56        return meta.Proceed();
57    }
58}
59
1namespace Doc.LAMA0042.Error;
2
3// Error: the default order places the weaver of [MakeVirtual] between the two layers of [NotNull].
4[MakeVirtual]
5internal class OrderService
6{
7    [Log]
8    public string Process( [NotNull] string orderId ) => orderId;
9}

Resolution

Add an assembly-level AspectOrder attribute that orders the low-level aspect <WeaverAspectType> relatively to the aspect <AspectType>, for instance [assembly: AspectOrder( AspectOrderDirection.CompileTime, typeof(MakeVirtualAttribute), typeof(NotNullAttribute) )], where MakeVirtualAttribute is the low-level aspect and NotNullAttribute is the aspect with several layers. Because the attribute orders the aspect types and not individual layers, it moves the low-level aspect before or after all layers of the other aspect.

In the following example, a single [assembly: AspectOrder] attribute orders Log, MakeVirtual and NotNull, so the weaver executes before all layers of NotNull.

1using Metalama.Framework.Aspects;
2using Metalama.Framework.Engine;
3using Metalama.Framework.Engine.AspectWeavers;
4using Metalama.Framework.Engine.Utilities.Roslyn;
5using Microsoft.CodeAnalysis;
6using Microsoft.CodeAnalysis.CSharp;
7using Microsoft.CodeAnalysis.CSharp.Syntax;
8using System;
9using System.Threading.Tasks;
10
11// The order between [MakeVirtual] and [NotNull] is specified, so the weaver executes before all layers of [NotNull].
12[assembly: AspectOrder(
13    AspectOrderDirection.CompileTime,
14    typeof(Doc.LAMA0042.Fixed.LogAttribute),
15    typeof(Doc.LAMA0042.Fixed.MakeVirtualAttribute),
16    typeof(Doc.LAMA0042.Fixed.NotNullAttribute) )]
17
18namespace Doc.LAMA0042.Fixed;
19
20// A low-level aspect, implemented by an aspect weaver.
21[RequireAspectWeaver( "Doc.LAMA0042.Fixed.MakeVirtualWeaver" )]
22internal class MakeVirtualAttribute : TypeAspect { }
23
24[MetalamaPlugIn]
25internal class MakeVirtualWeaver : IAspectWeaver
26{
27    public Task TransformAsync( AspectWeaverContext context ) => context.RewriteAspectTargetsAsync( new Rewriter() );
28
29    private class Rewriter : SafeSyntaxRewriter
30    {
31        // Adds the virtual modifier to public methods.
32        public override SyntaxNode? VisitMethodDeclaration( MethodDeclarationSyntax node )
33            => node.Modifiers.Any( SyntaxKind.PublicKeyword ) && !node.Modifiers.Any( SyntaxKind.VirtualKeyword )
34                ? node.AddModifiers( SyntaxFactory.Token( SyntaxKind.VirtualKeyword ).WithTrailingTrivia( SyntaxFactory.Space ) )
35                : node;
36    }
37}
38
39// A contract aspect, which has two layers.
40internal class NotNullAttribute : ContractAspect
41{
42    public override void Validate( dynamic? value )
43    {
44        if ( value == null )
45        {
46            throw new ArgumentNullException( meta.Target.Parameter.Name );
47        }
48    }
49}
50
51// A high-level aspect, which has a single layer.
52internal class LogAttribute : OverrideMethodAspect
53{
54    public override dynamic? OverrideMethod()
55    {
56        Console.WriteLine( $"Executing {meta.Target.Method}." );
57
58        return meta.Proceed();
59    }
60}
61
Source Code
1namespace Doc.LAMA0042.Fixed;
2


3// Fixed: an [AspectOrder] attribute orders [MakeVirtual] relatively to [NotNull].
4[MakeVirtual]
5internal class OrderService
6{
7    [Log]
8    public string Process( [NotNull] string orderId ) => orderId;
9}
Transformed Code
1using System;
2
3namespace Doc.LAMA0042.Fixed;
4
5// Fixed: an [AspectOrder] attribute orders [MakeVirtual] relatively to [NotNull].
6[MakeVirtual]
7internal class OrderService
8{
9    [Log]
10    public virtual string Process([NotNull] string orderId)
11    {
12        if (orderId == null)
13        {
14            throw new ArgumentNullException("orderId");
15        }
16
17        Console.WriteLine("Executing OrderService.Process(string).");
18        return orderId;
19    }
20}

See also