In the previous articles, we built a Cloneable
aspect that worked well with simple classes and one-to-one
relationships. But what if we need to support external types for which we cannot add a Clone
method, or one-to-many
relationships, such as collection fields?
Ideally, we would build a pluggable cloning service for external types, as we did for caching key builders of external types (see Caching example, step 4: cache key for external types) and supply cloners for system collections. But before that, an even better strategy is to design an extension point that the aspect's users can use when our aspect has limitations. How can we allow the aspect's users to inject their custom logic?
We will let users add their custom logic after the aspect-generated logic by allowing them to supply a method with the
following signature, where T
is the current type:
private void CloneMembers(T clone)
The aspect will inject its logic before the user's implementation.
Let's see this pattern in action. In this new example, the Game
class has a one-to-many relationship with the Player
class. The cloning of the collection is implemented manually.
1[Cloneable]
2internal class Game
3{
4 public List<Player> Players { get; private set; } = new();
5
6 [Child]
7 public GameSettings Settings { get; set; }
8
9 private void CloneMembers( Game clone ) => clone.Players = new List<Player>( this.Players );
10}
1using System;
2
3[Cloneable]
4internal class Game
5: ICloneable
6{
7 public List<Player> Players { get; private set; } = new();
8
9 [Child]
10 public GameSettings Settings { get; set; }
11
12 private void CloneMembers( Game clone ) { clone.Settings = ((GameSettings)this.Settings.Clone());
13 clone.Players = new List<Player>(this.Players);
14 }
15public virtual Game Clone()
16 {
17 var clone = (Game)this.MemberwiseClone();
18 this.CloneMembers(clone);
19 return clone;
20 }
21
22 object ICloneable.Clone()
23 {
24 return Clone();
25 }
26}
1[Cloneable]
2internal class GameSettings
3{
4 public int Level { get; set; }
5
6 public string World { get; set; }
7}
1using System;
2
3[Cloneable]
4internal class GameSettings
5: ICloneable
6{
7 public int Level { get; set; }
8
9 public string World { get; set; }
10public virtual GameSettings Clone()
11 {
12 var clone = (GameSettings)this.MemberwiseClone();
13 this.CloneMembers(clone);
14 return clone;
15 }
16 private void CloneMembers(GameSettings clone)
17 { }
18
19 object ICloneable.Clone()
20 {
21 return Clone();
22 }
23}
Aspect implementation
Here is the updated CloneableAttribute
class:
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
12 DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
13 _fieldOrPropertyCannotBeReadOnly =
14 new(
15 "CLONE01",
16 Severity.Error,
17 "The {0} '{1}' cannot be read-only because it is marked as a [Child]." );
18
19 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty, IType)>
20 _missingCloneMethod =
21 new(
22 "CLONE02",
23 Severity.Error,
24 "The {0} '{1}' cannot be a [Child] because its type '{2}' does not have a 'Clone' parameterless method." );
25
26 private static readonly DiagnosticDefinition<IMethod> _cloneMethodMustBePublic =
27 new(
28 "CLONE03",
29 Severity.Error,
30 "The '{0}' method must be public or internal." );
31
32 private static readonly DiagnosticDefinition<IProperty> _childPropertyMustBeAutomatic =
33 new(
34 "CLONE04",
35 Severity.Error,
36 "The property '{0}' cannot be a [Child] because is not an automatic property." );
37
38 //
39
40 public override void BuildAspect( IAspectBuilder<INamedType> builder )
41 {
42 // Verify child fields and properties.
43 if ( !this.VerifyFieldsAndProperties( builder ) )
44 {
45 builder.SkipAspect();
46
47 return;
48 }
49
50 // Introduce the Clone method.
51 builder.Advice.IntroduceMethod(
52 builder.Target,
53 nameof(this.CloneImpl),
54 whenExists: OverrideStrategy.Override,
55 args: new { T = builder.Target },
56 buildMethod: m =>
57 {
58 m.Name = "Clone";
59 m.ReturnType = builder.Target;
60 } );
61
62//
63 builder.Advice.IntroduceMethod(
64 builder.Target,
65 nameof(this.CloneMembers),
66 whenExists: OverrideStrategy.Override,
67 args: new { T = builder.Target } );
68
69//
70
71 // Implement the ICloneable interface.
72 builder.Advice.ImplementInterface(
73 builder.Target,
74 typeof(ICloneable),
75 OverrideStrategy.Ignore );
76 }
77
78 private bool VerifyFieldsAndProperties( IAspectBuilder<INamedType> builder )
79 {
80 var success = true;
81
82 // Verify that child fields are valid.
83 foreach ( var fieldOrProperty in GetCloneableFieldsOrProperties( builder.Target ) )
84 {
85 // The field or property must be writable.
86 if ( fieldOrProperty.Writeability != Writeability.All )
87 {
88 builder.Diagnostics.Report(
89 _fieldOrPropertyCannotBeReadOnly.WithArguments(
90 (
91 fieldOrProperty.DeclarationKind,
92 fieldOrProperty) ),
93 fieldOrProperty );
94
95 success = false;
96 }
97
98 // If it is a field, it must be an automatic property.
99 if ( fieldOrProperty is IProperty { IsAutoPropertyOrField: false } property )
100 {
101 builder.Diagnostics.Report(
102 _childPropertyMustBeAutomatic.WithArguments( property ),
103 property );
104
105 success = false;
106 }
107
108 // The type of the field must be cloneable.
109 void ReportMissingMethod()
110 {
111 builder.Diagnostics.Report(
112 _missingCloneMethod.WithArguments(
113 (fieldOrProperty.DeclarationKind,
114 fieldOrProperty,
115 fieldOrProperty.Type) ),
116 fieldOrProperty );
117 }
118
119 if ( fieldOrProperty.Type is not INamedType fieldType )
120 {
121 // The field type is an array, a pointer or another special type, which do not have a Clone method.
122 ReportMissingMethod();
123 success = false;
124 }
125 else
126 {
127 var cloneMethod = fieldType.AllMethods.OfName( "Clone" )
128 .SingleOrDefault( p => p.Parameters.Count == 0 );
129
130 if ( cloneMethod == null )
131 {
132 // There is no Clone method.
133 // It may be implemented by an aspect, but we don't have access to aspects on other types
134 // at design time.
135 if ( !MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime )
136 {
137 if ( !fieldType.BelongsToCurrentProject ||
138 !fieldType.Enhancements().HasAspect<CloneableAttribute>() )
139 {
140 ReportMissingMethod();
141 success = false;
142 }
143 }
144 }
145 else if ( cloneMethod.Accessibility is not (Accessibility.Public
146 or Accessibility.Internal) )
147 {
148 // If we have a Clone method, it must be public.
149 builder.Diagnostics.Report(
150 _cloneMethodMustBePublic.WithArguments( cloneMethod ),
151 fieldOrProperty );
152
153 success = false;
154 }
155 }
156 }
157
158 return success;
159 }
160
161 private static IEnumerable<IFieldOrProperty> GetCloneableFieldsOrProperties( INamedType type )
162 => type.FieldsAndProperties.Where(
163 f =>
164 f.Attributes.OfAttributeType( typeof(ChildAttribute) ).Any() );
165
166 [Template]
167 public virtual T CloneImpl<[CompileTime] T>()
168 {
169 // This compile-time variable will receive the expression representing the base call.
170 // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
171 // we will call MemberwiseClone (this is the initialization of the pattern).
172 IExpression baseCall;
173
174 if ( meta.Target.Method.IsOverride )
175 {
176 baseCall = (IExpression) meta.Base.Clone();
177 }
178 else
179 {
180 baseCall = (IExpression) meta.This.MemberwiseClone();
181 }
182
183 // Define a local variable of the same type as the target type.
184 var clone = (T) baseCall.Value!;
185
186 // Call CloneMembers, which may have a handwritten part.
187 meta.This.CloneMembers( clone );
188
189 return clone;
190 }
191
192 [Template]
193 private void CloneMembers<[CompileTime] T>( T clone )
194 {
195 // Select cloneable fields.
196 var cloneableFields = GetCloneableFieldsOrProperties( meta.Target.Type );
197
198 foreach ( var field in cloneableFields )
199 {
200 // Check if we have a public method 'Clone()' for the type of the field.
201 var fieldType = (INamedType) field.Type;
202
203 field.With( clone ).Value = meta.Cast( fieldType, field.Value?.Clone() );
204 }
205
206 // Call the handwritten implementation, if any.
207 meta.Proceed();
208 }
209
210 [InterfaceMember( IsExplicit = true )]
211 private object Clone() => meta.This.Clone();
212}
We added the following code in the BuildAspect
method:
63builder.Advice.IntroduceMethod(
64 builder.Target,
65 nameof(this.CloneMembers),
66 whenExists: OverrideStrategy.Override,
67 args: new { T = builder.Target } );
68
The template for the CloneMembers
method is as follows:
192[Template]
193private void CloneMembers<[CompileTime] T>( T clone )
194{
195 // Select cloneable fields.
196 var cloneableFields = GetCloneableFieldsOrProperties( meta.Target.Type );
197
198 foreach ( var field in cloneableFields )
199 {
200 // Check if we have a public method 'Clone()' for the type of the field.
201 var fieldType = (INamedType) field.Type;
202
203 field.With( clone ).Value = meta.Cast( fieldType, field.Value?.Clone() );
204 }
205
206 // Call the handwritten implementation, if any.
207 meta.Proceed();
208}
209
As you can see, we moved the logic that clones individual fields to this method. We call meta.Proceed()
last, so
hand-written code is executed after aspect-generated code and can fix whatever gap the aspect left.
Summary
We updated the aspect to add an extensibility mechanism allowing the user to implement scenarios that lack genuine
support by the aspect. The problem with this approach is that users may easily forget that they have to supply
a private void CloneMembers(T clone)
method. To remedy this issue, we will provide them with suggestions in the code
refactoring menu.