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}
The Clone
method must be public
or internal
.
1namespace ErrorProtectedCloneMethod;
2
3[Cloneable]
4internal class Game
5{
6 [Child]
Error CLONE03: The 'Player.Clone()' method must be public or internal.
7 public Player Player { get; private set; }
8}
9
10internal class Player
11{
12 public string Name { get; init; }
13
14 protected Player Clone()
15 => new Player() { Name = this.Name };
16}
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 CLONE04: 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
11 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
12 _fieldOrPropertyCannotBeReadOnly =
13 new("CLONE01", Severity.Error, "The {0} '{1}' cannot be read-only because it is marked as a [Child].");
14
15 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty, IType)> _missingCloneMethod =
16 new("CLONE02", Severity.Error,
17 "The {0} '{1}' cannot be a [Child] because its type '{2}' does not have a 'Clone' parameterless method.");
18
19 private static readonly DiagnosticDefinition<IMethod> _cloneMethodMustBePublic =
20 new( "CLONE03", Severity.Error,
21 "The '{0}' method must be public or internal." );
22
23 private static readonly DiagnosticDefinition<IProperty> _childPropertyMustBeAutomatic =
24 new("CLONE04", Severity.Error,
25 "The property '{0}' cannot be a [Child] because is not an automatic property.");
26
27 public override void BuildAspect( IAspectBuilder<INamedType> builder )
28 {
29 // Verify child fields and properties.
30 if ( !this.VerifyFieldsAndProperties( builder ) )
31 {
32 builder.SkipAspect();
33 return;
34 }
35
36 // Introduce the Clone method.
37 builder.Advice.IntroduceMethod(
38 builder.Target,
39 nameof(this.CloneImpl),
40 whenExists: OverrideStrategy.Override,
41 args: new { T = builder.Target },
42 buildMethod: m =>
43 {
44 m.Name = "Clone";
45 m.ReturnType = builder.Target;
46 } );
47
48 // Implement the ICloneable interface.
49 builder.Advice.ImplementInterface(
50 builder.Target,
51 typeof(ICloneable),
52 OverrideStrategy.Ignore );
53 }
54
55 private bool VerifyFieldsAndProperties( IAspectBuilder<INamedType> builder )
56 {
57 var success = true;
58
59 // Verify that child fields are valid.
60 foreach ( var fieldOrProperty in GetCloneableFieldsOrProperties( builder.Target ) )
61 {
62 // The field or property must be writable.
63 if ( fieldOrProperty.Writeability != Writeability.All )
64 {
65 builder.Diagnostics.Report(
66 _fieldOrPropertyCannotBeReadOnly.WithArguments( (fieldOrProperty.DeclarationKind,
67 fieldOrProperty) ), fieldOrProperty );
68 success = false;
69 }
70
71 // If it is a field, it must be an automatic property.
72 if ( fieldOrProperty is IProperty property && property.IsAutoPropertyOrField == false )
73 {
74 builder.Diagnostics.Report( _childPropertyMustBeAutomatic.WithArguments( property ), property );
75 success = false;
76 }
77
78 // The type of the field must be cloneable.
79 void ReportMissingMethod()
80 {
81 builder.Diagnostics.Report(
82 _missingCloneMethod.WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty,
83 fieldOrProperty.Type) ), fieldOrProperty );
84 }
85
86 if ( fieldOrProperty.Type is not INamedType fieldType )
87 {
88 // The field type is an array, a pointer or another special type, which do not have a Clone method.
89 ReportMissingMethod();
90 success = false;
91 }
92 else
93 {
94 var cloneMethod = fieldType.AllMethods.OfName( "Clone" )
95 .SingleOrDefault( p => p.Parameters.Count == 0 );
96
97 if ( cloneMethod == null )
98 {
99 // There is no Clone method.
100 // If may be implemented by an aspect, but we don't have access to aspects on other types
101 // at design time.
102 if ( !MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime )
103 {
104 if ( !fieldType.BelongsToCurrentProject ||
105 !fieldType.Enhancements().HasAspect<CloneableAttribute>() )
106 {
107 ReportMissingMethod();
108 success = false;
109 }
110 }
111 }
112 else if ( cloneMethod.Accessibility is not (Accessibility.Public or Accessibility.Internal) )
113 {
114 // If we have a Clone method, it must be public.
115 builder.Diagnostics.Report(
116 _cloneMethodMustBePublic.WithArguments( cloneMethod ), fieldOrProperty );
117 success = false;
118
119 }
120 }
121 }
122
123 return success;
124 }
125
126
127 private static IEnumerable<IFieldOrProperty> GetCloneableFieldsOrProperties( INamedType type )
128 => type.FieldsAndProperties.Where( f => f.Attributes.OfAttributeType( typeof(ChildAttribute) ).Any() );
129
130 [Template]
131 public virtual T CloneImpl<[CompileTime] T>()
132 {
133 // This compile-time variable will receive the expression representing the base call.
134 // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
135 // we will call MemberwiseClone (this is the initialization of the pattern).
136 IExpression baseCall;
137
138 if ( meta.Target.Method.IsOverride )
139 {
140 baseCall = (IExpression) meta.Base.Clone();
141 }
142 else
143 {
144 baseCall = (IExpression) meta.This.MemberwiseClone();
145 }
146
147 // Define a local variable of the same type as the target type.
148 var clone = (T) baseCall.Value!;
149
150 // Select cloneable fields.
151 var cloneableFields = GetCloneableFieldsOrProperties( meta.Target.Type );
152
153 foreach ( var field in cloneableFields )
154 {
155 // Check if we have a public method 'Clone()' for the type of the field.
156 var fieldType = (INamedType) field.Type;
157
158 field.With( clone ).Value = meta.Cast( fieldType, field.Value?.Clone() );
159 }
160
161 return clone;
162 }
163
164 [InterfaceMember( IsExplicit = true )]
165 private object Clone() => meta.This.Clone();
166}
The first thing to do is to define the errors we want to report as static fields.
10
11 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
12 _fieldOrPropertyCannotBeReadOnly =
13 new("CLONE01", Severity.Error, "The {0} '{1}' cannot be read-only because it is marked as a [Child].");
14
15 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty, IType)> _missingCloneMethod =
16 new("CLONE02", Severity.Error,
17 "The {0} '{1}' cannot be a [Child] because its type '{2}' does not have a 'Clone' parameterless method.");
18
19 private static readonly DiagnosticDefinition<IMethod> _cloneMethodMustBePublic =
20 new( "CLONE03", Severity.Error,
21 "The '{0}' method must be public or internal." );
22
23 private static readonly DiagnosticDefinition<IProperty> _childPropertyMustBeAutomatic =
24 new("CLONE04", Severity.Error,
25 "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 add the VerifyFieldsAndProperties
method and call it from BuildAspect
.
55 private bool VerifyFieldsAndProperties( IAspectBuilder<INamedType> builder )
56 {
57 var success = true;
58
59 // Verify that child fields are valid.
60 foreach ( var fieldOrProperty in GetCloneableFieldsOrProperties( builder.Target ) )
61 {
62 // The field or property must be writable.
63 if ( fieldOrProperty.Writeability != Writeability.All )
64 {
65 builder.Diagnostics.Report(
66 _fieldOrPropertyCannotBeReadOnly.WithArguments( (fieldOrProperty.DeclarationKind,
67 fieldOrProperty) ), fieldOrProperty );
68 success = false;
69 }
70
71 // If it is a field, it must be an automatic property.
72 if ( fieldOrProperty is IProperty property && property.IsAutoPropertyOrField == false )
73 {
74 builder.Diagnostics.Report( _childPropertyMustBeAutomatic.WithArguments( property ), property );
75 success = false;
76 }
77
78 // The type of the field must be cloneable.
79 void ReportMissingMethod()
80 {
81 builder.Diagnostics.Report(
82 _missingCloneMethod.WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty,
83 fieldOrProperty.Type) ), fieldOrProperty );
84 }
85
86 if ( fieldOrProperty.Type is not INamedType fieldType )
87 {
88 // The field type is an array, a pointer or another special type, which do not have a Clone method.
89 ReportMissingMethod();
90 success = false;
91 }
92 else
93 {
94 var cloneMethod = fieldType.AllMethods.OfName( "Clone" )
95 .SingleOrDefault( p => p.Parameters.Count == 0 );
96
97 if ( cloneMethod == null )
98 {
99 // There is no Clone method.
100 // If may be implemented by an aspect, but we don't have access to aspects on other types
101 // at design time.
102 if ( !MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime )
103 {
104 if ( !fieldType.BelongsToCurrentProject ||
105 !fieldType.Enhancements().HasAspect<CloneableAttribute>() )
106 {
107 ReportMissingMethod();
108 success = false;
109 }
110 }
111 }
112 else if ( cloneMethod.Accessibility is not (Accessibility.Public or Accessibility.Internal) )
113 {
114 // If we have a Clone method, it must be public.
115 builder.Diagnostics.Report(
116 _cloneMethodMustBePublic.WithArguments( cloneMethod ), fieldOrProperty );
117 success = false;
118
119 }
120 }
121 }
122
123 return success;
124 }
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, and the second 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?