MetalamaConceptual documentationCreating aspectsReporting and suppressing diagnostics
Open sandboxFocusImprove this doc

Reporting and suppressing diagnostics

This article provides guidance on how to report a diagnostic, including errors, warnings, or information messages, from an aspect or suppress a diagnostic reported by the C# compiler or another aspect.

Benefits

  • Prevent non-intuitive compilation errors: Aspects applied to unexpected or untested kinds of declarations can lead to confusing exceptions or errors during the compilation of the transformed code. This confusion can be mitigated by reporting clear error messages when the target of the aspect fails to meet expectations. Refer to Defining the eligibility of aspects for this use case.
  • Eliminate confusing warnings: The C# compiler and other analyzers, unaware of the code transformation by your aspect, may report irrelevant warnings. Suppressing these warnings with your aspect can reduce confusion and save developers from manually suppressing these warnings.
  • Enhance user productivity: Overall, reporting and suppressing relevant diagnostics can significantly improve the productivity of those using your aspect.
  • Diagnostic-only aspects: You can create aspects that solely report or suppress diagnostics without transforming any source code. Refer to Verifying architecture for additional details and benefits.

Reporting a diagnostic

To report a diagnostic:

  1. Import the Metalama.Framework.Diagnostics namespace.

  2. Define a static field of type DiagnosticDefinition in your aspect class. DiagnosticDefinition specifies the diagnostic id, the severity, and the message formatting string.

    • For a message without formatting parameters or with weakly-typed formatting parameters, utilize the non-generic DiagnosticDefinition class.
    • For a message with a single strongly-typed formatting parameter, employ the generic DiagnosticDefinition<T> class, e.g., DiagnosticDefinition<int>.
    • For a message with several strongly-typed formatting parameters, apply the generic DiagnosticDefinition<T> with a tuple, e.g., DiagnosticDefinition<(int,string)> for a message with two formatting parameters expecting a value of type int and string.

      Warning

      The aspect framework relies on diagnostics being defined as static fields of aspect classes. You will not be able to report a diagnostic that has not been declared on an aspect class of the current project.

  3. To report a diagnostic, use the builder.Diagnostics.Report method.

    The second parameter of the Report method is optional: it specifies the declaration to which the diagnostic relates. Based on this declaration, the aspect framework computes the diagnostic file, line, and column. If you don't provide a value for this parameter, the diagnostic will be reported for the target declaration of the aspect.

Example

The following aspect requires a field named _logger to exist in the target type. Its BuildAspect method checks the existence of this field and reports an error if it is absent.

1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Diagnostics;
4using System.Linq;
5
6namespace Doc.ReportError
7{
8    internal class LogAttribute : OverrideMethodAspect
9    {
10        // You MUST have a static field that defines the diagnostic.
11        private static DiagnosticDefinition<INamedType> _error = new(
12            "MY001",
13            Severity.Error,
14            "The type {0} must have a field named '_logger'." );
15
16        public override void BuildAspect( IAspectBuilder<IMethod> builder )
17        {
18            base.BuildAspect( builder );
19
20            // Validation must be done in BuildAspect. In OverrideMethod, it's too late.
21            if ( !builder.Target.DeclaringType.Fields.OfName( "_logger" ).Any() )
22            {
23                builder.Diagnostics.Report( _error.WithArguments( builder.Target.DeclaringType ) );
24            }
25        }
26
27        public override dynamic? OverrideMethod()
28        {
29            meta.This._logger.WriteLine( $"Executing {meta.Target.Method}." );
30
31            return meta.Proceed();
32        }
33    }
34}
1namespace Doc.ReportError
2{
3    internal class Program
4    {
5        // Intentionally omitting the _logger field so an error is reported.
6
7        [Log]
        Error MY001: The type Program must have a field named '_logger'.

8        private void Foo() { }
9
10        private static void Main()
11        {
12            new Program().Foo();
13        }
14    }
15}

Suppressing a diagnostic

The C# compiler or other analyzers may report warnings to the target code of your aspects. Since neither the C# compiler nor the analyzers are aware of your aspect, some of these warnings may be irrelevant. As an aspect author, it is good practice to prevent the reporting of irrelevant warnings.

To suppress a diagnostic:

  1. Import the Metalama.Framework.Diagnostics namespace.

  2. Define a static field of type SuppressionDefinition in your aspect class. SuppressionDefinition specifies the identifier of the diagnostic to suppress.

  3. Call the Suppress method using builder.Diagnostics.Suppress(...) in the BuildAspect method.

Example

The following logging aspect requires a _logger field. This field will be used in generated code but never in user code. Because the IDE does not see the generated code, it will report the CS0169 warning, which is misleading and annoying to the user. The aspect suppresses this warning.

1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Diagnostics;
4using System.Linq;
5
6namespace Doc.SuppressWarning
7{
8    internal class LogAttribute : OverrideMethodAspect
9    {
10        private static SuppressionDefinition _suppression = new( "CS0169" );
11
12        public override void BuildAspect( IAspectBuilder<IMethod> builder )
13        {
14            base.BuildAspect( builder );
15
16            var loggerField = builder.Target.DeclaringType.Fields.OfName( "_logger" ).FirstOrDefault();
17
18            if ( loggerField != null )
19            {
20                // Suppress "Field is never read" warning from Intellisense warning for this field.
21                builder.Diagnostics.Suppress( _suppression, loggerField );
22            }
23        }
24
25        public override dynamic? OverrideMethod()
26        {
27            meta.This._logger.WriteLine( $"Executing {meta.Target.Method}." );
28
29            return meta.Proceed();
30        }
31    }
32}
Source Code
1using System;
2using System.IO;
3
4namespace Doc.SuppressWarning
5{
6    internal class Program
7    {
8        private TextWriter _logger = Console.Out;
9


10        [Log]


11        private void Foo() { }
12
13        private static void Main()



14        {
15            new Program().Foo();
16        }
17    }
18}
Transformed Code
1using System;
2using System.IO;
3
4namespace Doc.SuppressWarning
5{
6    internal class Program
7    {
8
9#pragma warning disable CS0169
10        private TextWriter _logger = Console.Out;
11
12#pragma warning restore CS0169
13
14        [Log]
15        private void Foo()
16        {
17            this._logger.WriteLine("Executing Program.Foo().");
18        }
19
20        private static void Main()
21        {
22            new Program().Foo();
23        }
24    }
25}
Executing Program.Foo().

Advanced example

The following aspect can be added to a field or property. It overrides the getter implementation to retrieve the value from the service locator. This aspect assumes that the target class has a field named _serviceProvider and of type IServiceProvider. The aspect reports errors if this field is absent or does not match the expected type. The C# compiler may report a warning CS0169 because it appears from the source code that the _serviceProvider field is unused. Therefore, the aspect must suppress this diagnostic.

1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Diagnostics;
4using System;
5using System.Linq;
6
7namespace Doc.ImportService
8{
9    internal class ImportAspect : OverrideFieldOrPropertyAspect
10    {
11        private static readonly DiagnosticDefinition<INamedType> _serviceProviderFieldMissing = new(
12            "MY001",
13            Severity.Error,
14            "The 'ImportServiceAspect' aspects requires the type '{0}' to have a field named '_serviceProvider' and " +
15            " of type 'IServiceProvider'." );
16
17        private static readonly DiagnosticDefinition<(IField, IType)> _serviceProviderFieldTypeMismatch = new(
18            "MY002",
19            Severity.Error,
20            "The type of field '{0}' must be 'IServiceProvider', but it is '{1}." );
21
22        private static readonly SuppressionDefinition _suppressFieldIsNeverUsed = new( "CS0169" );
23
24        public override void BuildAspect( IAspectBuilder<IFieldOrProperty> builder )
25        {
26            // Get the field _serviceProvider and check its type.
27            var serviceProviderField =
28                builder.Target.DeclaringType.Fields.OfName( "_serviceProvider" ).SingleOrDefault();
29
30            if ( serviceProviderField == null )
31            {
32                builder.Diagnostics.Report( _serviceProviderFieldMissing.WithArguments( builder.Target.DeclaringType ) );
33
34                return;
35            }
36            else if ( !serviceProviderField.Type.Is( typeof(IServiceProvider) ) )
37            {
38                builder.Diagnostics.Report(
39                    _serviceProviderFieldTypeMismatch.WithArguments(
40                        (serviceProviderField,
41                         serviceProviderField.Type) ) );
42
43                return;
44            }
45
46            // Provide the advice.
47            base.BuildAspect( builder );
48
49            // Suppress the diagnostic.
50            builder.Diagnostics.Suppress( _suppressFieldIsNeverUsed, serviceProviderField );
51        }
52
53        public override dynamic? OverrideProperty
54        {
55            get => meta.This._serviceProvider.GetService( meta.Target.FieldOrProperty.Type.ToType() );
56
57            set => throw new NotSupportedException();
58        }
59    }
60}
1using System;
2
3namespace Doc.ImportService
4{
5    internal class Foo
6    {
7        // readonly IServiceProvider _serviceProvider;
8
9        [ImportAspect]
        Error MY001: The 'ImportServiceAspect' aspects requires the type 'Foo' to have a field named '_serviceProvider' and  of type 'IServiceProvider'.

10        private IFormatProvider? FormatProvider { get; }
11
12        public string Format( object? o )
13        {
14            return ((ICustomFormatter) this.FormatProvider!.GetFormat( typeof(ICustomFormatter) )!)
15                .Format( null, o, this.FormatProvider );
16        }
17    }
18}

Validating the target code after all aspects have been applied

When your aspect's BuildAspect method is executed, it views the code model as it was before the aspect was applied.

If you need to validate the code after all aspects have been applied, see Validating code from an aspect.