| Severity | Error |
| Reported by | Metalama.Framework |
| Message | '<Declaration>' cannot contain unsafe code because it is <Scope> code. |
Cause
Metalama extracts your compile-time code, such as aspects, fabrics, and classes marked with [CompileTimeAttribute], into a separate compile-time assembly. Metalama doesn't allow unsafe code in this compile-time code.
Metalama reports LAMA0248 when the declaration of a type or member whose scope isn't run-time-only has the unsafe modifier. This applies to compile-time declarations and to run-time-or-compile-time declarations. Aspect classes are run-time-or-compile-time, because IAspect is. The first placeholder of the message is the declaration, and the second one is its scope, for instance compile-time or run-time-or-compile-time.
When the unsafe declaration is a template, for instance an OverrideMethod method, Metalama reports LAMA0249 instead.
In the following example, the Log aspect class has the unsafe modifier.
1using Metalama.Framework.Aspects;
2using System;
3
4namespace Doc.LAMA0248.Error;
5
6// Error: the aspect class cannot be unsafe.
Error LAMA0248: 'LogAttribute' cannot contain unsafe code because it is run-time-or-compile-time code.
7public unsafe class LogAttribute : OverrideMethodAspect
8{
9 public override dynamic? OverrideMethod()
10 {
11 Console.WriteLine( $"Executing {meta.Target.Method}." );
12
13 return meta.Proceed();
14 }
15}
16
1namespace Doc.LAMA0248.Error;
2
3internal class Calculator
4{
5 [Log]
6 public int Add( int a, int b ) => a + b;
7}
8
Resolution
Remove the unsafe modifier from the compile-time declaration, and rewrite the code that needs it without pointers, for instance with Span or with the methods of the Unsafe and MemoryMarshal classes.
If the unsafe code belongs to the run-time part of your project, move it to a run-time type that doesn't contain any compile-time code.
In the following example, the unsafe modifier is removed from the aspect class.
1using Metalama.Framework.Aspects;
2using System;
3
4namespace Doc.LAMA0248.Fixed;
5
6// Fixed: the aspect class is not unsafe.
7public class LogAttribute : OverrideMethodAspect
8{
9 public override dynamic? OverrideMethod()
10 {
11 Console.WriteLine( $"Executing {meta.Target.Method}." );
12
13 return meta.Proceed();
14 }
15}
16
1namespace Doc.LAMA0248.Fixed;
2
3internal class Calculator
4{
5 [Log]
6 public int Add( int a, int b ) => a + b;
7}
8
1using System;
2
3namespace Doc.LAMA0248.Fixed;
4
5internal class Calculator
6{
7 [Log]
8 public int Add(int a, int b)
9 {
10 Console.WriteLine("Executing Calculator.Add(int, int).");
11 return a + b;
12 }
13}
14