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