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