Clone example, step 1: verifying code
In the previous article, we built an aspect that implements the Deep Clone pattern. The aspect assumes that all fields or properties annotated with the [Child]
attribute are both of a cloneable type and assignable. If this is not the case, the aspect generates uncompilable code, making the aspect's user confused.
In this article, we will improve the aspect so that it reports errors in the following three unsupported situations.
We report an error when the field or property is read-only.
1namespace ErrorReadOnlyField;
2
3[Cloneable]
4internal class Game
5{
6 public Player Player { get; }
7
8 [Child]
Error CLONE01: The property 'Game.Settings' cannot be read-only because it is marked as a [Child].
9 public GameSettings Settings { get; }
10}
11
12[Cloneable]
13internal class GameSettings
14{
15 public int Level { get; set; }
16 public string World { get; set; }
17}
18
19internal class Player
20{
21 public string Name { get; }
22}
We report an error when the type of the field or property does not have a Clone
method.
1namespace ErrorNotCloneableChild;
2
3[Cloneable]
4internal class Game
5{
6 [Child]
Error CLONE01: The property 'Game.Player' cannot be read-only because it is marked as a [Child].
7 public Player Player { get; }
8
9 [Child]
10 public GameSettings Settings { get; private set; }
11}
12
13[Cloneable]
14internal class GameSettings
15{
16 public int Level { get; set; }
17 public string World { get; set; }
18}
19
20internal class Player
21{
22 public string Name { get; }
23}
We report an error when the property is not an automatic property.
1namespace ErrorNotAutomaticProperty;
2
3[Cloneable]
4internal class Game
5{
6 private GameSettings _settings;
7
8 public Player Player { get; }
9
10 [Child]
Error CLONE03: The property 'Game.Settings' cannot be a [Child] because is not an automatic property.
11 public GameSettings Settings
12 {
13 get => this._settings;
14
15 private set
16 {
17 Console.WriteLine( "Setting the value." );
18 this._settings = value;
19 }
20 }
21}
22
23[Cloneable]
24internal class GameSettings
25{
26 public int Level { get; set; }
27 public string World { get; set; }
28}
29
30internal class Player
31{
32 public string Name { get; }
33}
Aspect implementation
The full updated aspect code is here:
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Diagnostics;
4using Metalama.Framework.Project;
5
6[Inheritable]
7[EditorExperience( SuggestAsLiveTemplate = true )]
8public class CloneableAttribute : TypeAspect
9{
10 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
11 _fieldOrPropertyCannotBeReadOnly =
12 new("CLONE01", Severity.Error, "The {0} '{1}' cannot be read-only because it is marked as a [Child].");
13
14 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty, IType)> _missingCloneMethod =
15 new("CLONE02", Severity.Error,
16 "The {0} '{1}' cannot be a [Child] because its type '{2}' does not have a 'Clone' parameterless method.");
17
18 private static readonly DiagnosticDefinition<IProperty> _childPropertyMustBeAutomatic =
19 new("CLONE03", Severity.Error,
20 "The property '{0}' cannot be a [Child] because is not an automatic property.");
21
22 public override void BuildAspect( IAspectBuilder<INamedType> builder )
23 {
24 // Verify that child fields are valid.
25 var hasError = false;
26 foreach ( var fieldOrProperty in GetClonableFieldsOrProperties( builder.Target ) )
27 {
28 // The field or property must be writable.
29 if ( fieldOrProperty.Writeability != Writeability.All )
30 {
31 builder.Diagnostics.Report(
32 _fieldOrPropertyCannotBeReadOnly.WithArguments( (fieldOrProperty.DeclarationKind,
33 fieldOrProperty) ), fieldOrProperty );
34 hasError = true;
35 }
36
37 // If it is a field, it must be an automatic property.
38 if ( fieldOrProperty is IProperty property && property.IsAutoPropertyOrField == false )
39 {
40 builder.Diagnostics.Report( _childPropertyMustBeAutomatic.WithArguments( property ), property );
41 hasError = true;
42 }
43
44 // The type of the field must be cloneable.
45 if ( !MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime )
46 {
47 var fieldType = fieldOrProperty.Type as INamedType;
48
49 if ( fieldType == null ||
50 !(fieldType.AllMethods.OfName( "Clone" ).Where( p => p.Parameters.Count == 0 ).Any() ||
51 (fieldType.BelongsToCurrentProject &&
52 fieldType.Enhancements().HasAspect<CloneableAttribute>())) )
53 {
54 builder.Diagnostics.Report(
55 _missingCloneMethod.WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty,
56 fieldOrProperty.Type) ), fieldOrProperty );
57 hasError = true;
58 }
59 }
60 }
61
62 // Stop here if we have errors.
63 if ( hasError )
64 {
65 builder.SkipAspect();
66 return;
67 }
68
69 // Introduce the Clone method.
70 builder.Advice.IntroduceMethod(
71 builder.Target,
72 nameof(this.CloneImpl),
73 whenExists: OverrideStrategy.Override,
74 args: new { T = builder.Target },
75 buildMethod: m =>
76 {
77 m.Name = "Clone";
78 m.ReturnType = builder.Target;
79 } );
80
81 // Implement the ICloneable interface.
82 builder.Advice.ImplementInterface(
83 builder.Target,
84 typeof(ICloneable),
85 OverrideStrategy.Ignore );
86 }
87
88 private static IEnumerable<IFieldOrProperty> GetClonableFieldsOrProperties( INamedType type )
89 => type.FieldsAndProperties.Where( f => f.Attributes.OfAttributeType( typeof(ChildAttribute) ).Any() );
90
91 [Template]
92 public virtual T CloneImpl<[CompileTime] T>()
93 {
94 // This compile-time variable will receive the expression representing the base call.
95 // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
96 // we will call MemberwiseClone (this is the initialization of the pattern).
97 IExpression baseCall;
98
99 if ( meta.Target.Method.IsOverride )
100 {
101 baseCall = (IExpression) meta.Base.Clone();
102 }
103 else
104 {
105 baseCall = (IExpression) meta.This.MemberwiseClone();
106 }
107
108 // Define a local variable of the same type as the target type.
109 var clone = (T) baseCall.Value!;
110
111 // Select clonable fields.
112 var clonableFields = GetClonableFieldsOrProperties( meta.Target.Type );
113
114 foreach ( var field in clonableFields )
115 {
116 // Check if we have a public method 'Clone()' for the type of the field.
117 var fieldType = (INamedType) field.Type;
118
119 field.With( clone ).Value = meta.Cast( fieldType, field.Value?.Clone() );
120 }
121
122 return clone;
123 }
124
125 [InterfaceMember( IsExplicit = true )]
126 private object Clone() => meta.This.Clone();
127}
The first thing to do is to define the errors we want to report as static fields.
11 _fieldOrPropertyCannotBeReadOnly =
12 new("CLONE01", Severity.Error, "The {0} '{1}' cannot be read-only because it is marked as a [Child].");
13
14 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty, IType)> _missingCloneMethod =
15 new("CLONE02", Severity.Error,
16 "The {0} '{1}' cannot be a [Child] because its type '{2}' does not have a 'Clone' parameterless method.");
17
18 private static readonly DiagnosticDefinition<IProperty> _childPropertyMustBeAutomatic =
19 new("CLONE03", Severity.Error,
20 "The property '{0}' cannot be a [Child] because is not an automatic property.");
For details about reporting errors, see Reporting and suppressing diagnostics.
Then, we edit the BuildAspect
method to verify the code.
25 var hasError = false;
26 foreach ( var fieldOrProperty in GetClonableFieldsOrProperties( builder.Target ) )
27 {
28 // The field or property must be writable.
29 if ( fieldOrProperty.Writeability != Writeability.All )
30 {
31 builder.Diagnostics.Report(
32 _fieldOrPropertyCannotBeReadOnly.WithArguments( (fieldOrProperty.DeclarationKind,
33 fieldOrProperty) ), fieldOrProperty );
34 hasError = true;
35 }
36
37 // If it is a field, it must be an automatic property.
38 if ( fieldOrProperty is IProperty property && property.IsAutoPropertyOrField == false )
39 {
40 builder.Diagnostics.Report( _childPropertyMustBeAutomatic.WithArguments( property ), property );
41 hasError = true;
42 }
43
44 // The type of the field must be cloneable.
45 if ( !MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime )
46 {
47 var fieldType = fieldOrProperty.Type as INamedType;
48
49 if ( fieldType == null ||
50 !(fieldType.AllMethods.OfName( "Clone" ).Where( p => p.Parameters.Count == 0 ).Any() ||
51 (fieldType.BelongsToCurrentProject &&
52 fieldType.Enhancements().HasAspect<CloneableAttribute>())) )
53 {
54 builder.Diagnostics.Report(
55 _missingCloneMethod.WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty,
56 fieldOrProperty.Type) ), fieldOrProperty );
57 hasError = true;
58 }
59 }
60 }
61
62 // Stop here if we have errors.
63 if ( hasError )
64 {
65 builder.SkipAspect();
66 return;
67 }
When we detect an unsupported situation, we report the error using the Report method. The first argument is the diagnostic constructed from the definition stored in the static field. The second argument is the invalid field or property.
The third verification requires additional discussion. Our aspect requires the type of child fields or properties to have a Clone
method. This method can be defined in three ways: in source code (i.e., hand-written), in a referenced assembly (compiled), or introduced by the Cloneable
aspect itself. In the latter case, the Clone
method may not yet be present in the code model because the child field type may not have been processed yet. Therefore, if we don't find the Clone
method, we should check if the child type has the Cloneable
aspect. This aspect can be added as a custom attribute which we could check using the code model, but it could also be added as a fabric without the help of a custom attribute. Thus, we must check the presence of the aspect, not the custom attribute. You can check the presence of the aspect using fieldType.Enhancements().HasAspect<CloneableAttribute>()
. The problem is that, at design time (inside the IDE), Metalama only knows aspects applied to the current type and its parent types. Metalama uses that strategy for performance reasons to avoid recompiling the whole assembly at each keystroke. Therefore, that verification cannot be performed at design time and must be skipped.
Summary
Instead of generating invalid code and confusing the user, our aspect now reports errors when it detects unsupported situations. It still lacks a mechanism to support anomalies. What if the Game
class includes a collection of Player
s instead of just one?