So far, we have built a powerful aspect that implements the Deep Clone pattern and has three pieces of API:
the [Cloneable]
and [Child]
attributes and the method void CloneMembers(T)
. Our aspect already reports errors in
unsupported cases. We will now see how we can improve the productivity of the aspect's users by providing coding
guidance.
First, we would like to save users from the need to remember the name and signature of the void CloneMembers(T)
method. When there is no such method in their code, we would like to add an action to the refactoring menu that would
create this action like this:
Secondly, suppose that we have deployed the Cloneable
aspect to the team, and we notice that developers frequently
forget to annotate cloneable fields with the [Child]
attribute, causing inconsistencies in the resulting cloned object
tree. Such inconsistencies are tedious to debug because they may appear randomly after the cloning process, losing much
time for the team and degrading trust in aspect-oriented programming and architecture decisions. As the aspect's
authors, it is our job to prevent the most frequent pitfalls by reporting a warning and suggesting remediations.
To make sure that developers do not forget to annotate properties with the [Child]
attribute, we will define a new
attribute [Reference]
and require developers to annotate any cloneable property with either [Child]
or [Reference]
. Otherwise, we will report a warning and suggest two code fixes: add [Child]
or add [Reference]
to
the field. Thanks to this strategy, we ensure that developers no longer forget to classify properties and instead make a
conscious choice.
The first thing developers will experience is the warning:
Note the link Show potential fixes. If developers click on that link or hit Alt+Enter
or Ctrl+.
, they will see two
code suggestions:
Let's see how we can add these features to our aspect.
Aspect implementation
Here is the complete and updated aspect:
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.CodeFixes;
4using Metalama.Framework.Diagnostics;
5using Metalama.Framework.Project;
6
7[Inheritable]
8[EditorExperience(SuggestAsLiveTemplate = true)]
9public class CloneableAttribute : TypeAspect
10{
11 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
12 _fieldOrPropertyCannotBeReadOnly =
13 new("CLONE01", Severity.Error,
14 "The {0} '{1}' cannot be read-only because it is marked as a [Child].");
15
16 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty, IType)>
17 _missingCloneMethod =
18 new("CLONE02", Severity.Error,
19 "The {0} '{1}' cannot be a [Child] because its type '{2}' does not have a 'Clone' parameterless method.");
20
21 private static readonly DiagnosticDefinition<IMethod> _cloneMethodMustBePublic =
22 new("CLONE03", Severity.Error,
23 "The '{0}' method must be public or internal.");
24
25 private static readonly DiagnosticDefinition<IProperty> _childPropertyMustBeAutomatic =
26 new("CLONE04", Severity.Error,
27 "The property '{0}' cannot be a [Child] because is not an automatic property.");
28
29 private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
30 _annotateFieldOrProperty =
31 new("CLONE05", Severity.Warning, "Mark the {0} '{1}' as a [Child] or [Reference].");
32
33
34 public override void BuildAspect(IAspectBuilder<INamedType> builder)
35 {
36 // Verify child fields and properties.
37 if (!this.VerifyFieldsAndProperties(builder))
38 {
39 builder.SkipAspect();
40 return;
41 }
42
43
44 // Introduce the Clone method.
45 builder.Advice.IntroduceMethod(
46 builder.Target,
47 nameof(this.CloneImpl),
48 whenExists: OverrideStrategy.Override,
49 args: new { T = builder.Target },
50 buildMethod: m =>
51 {
52 m.Name = "Clone";
53 m.ReturnType = builder.Target;
54 });
55
56 //
57 builder.Advice.IntroduceMethod(
58 builder.Target,
59 nameof(this.CloneMembers),
60 whenExists: OverrideStrategy.Override,
61 args: new { T = builder.Target });
62 //
63
64 // Implement the ICloneable interface.
65 builder.Advice.ImplementInterface(
66 builder.Target,
67 typeof(ICloneable),
68 OverrideStrategy.Ignore);
69
70 // When we have non-child fields or properties of a cloneable type,
71 // suggest to add the child attribute
72 var eligibleChildren = builder.Target.FieldsAndProperties
73 .Where(f => f.Writeability == Writeability.All &&
74 !f.IsImplicitlyDeclared &&
75 !f.Attributes.OfAttributeType(typeof(ChildAttribute)).Any() &&
76 !f.Attributes.OfAttributeType(typeof(ReferenceAttribute)).Any() &&
77 f.Type is INamedType fieldType &&
78 (fieldType.AllMethods.OfName("Clone")
79 .Where(m => m.Parameters.Count == 0).Any() ||
80 fieldType.Attributes.OfAttributeType(typeof(CloneableAttribute))
81 .Any()));
82
83
84 //
85 foreach (var fieldOrProperty in eligibleChildren)
86 {
87 builder.Diagnostics.Report(_annotateFieldOrProperty
88 .WithArguments((fieldOrProperty.DeclarationKind, fieldOrProperty)).WithCodeFixes(
89 CodeFixFactory.AddAttribute(fieldOrProperty, typeof(ChildAttribute),
90 "Cloneable | Mark as child"),
91 CodeFixFactory.AddAttribute(fieldOrProperty, typeof(ReferenceAttribute),
92 "Cloneable | Mark as reference")), fieldOrProperty);
93 }
94 //
95
96 //
97 // If we don't have a CloneMember method, suggest to add it.
98 if (!builder.Target.Methods.OfName(nameof(this.CloneMembers)).Any())
99 {
100 builder.Diagnostics.Suggest(
101 new CodeFix("Cloneable | Customize manually",
102 codeFix =>
103 codeFix.ApplyAspectAsync(builder.Target,
104 new AddEmptyCloneMembersAspect())));
105 }
106 //
107 }
108
109
110 private bool VerifyFieldsAndProperties(IAspectBuilder<INamedType> builder)
111 {
112 var success = true;
113
114 // Verify that child fields are valid.
115 foreach (var fieldOrProperty in GetCloneableFieldsOrProperties(builder.Target))
116 {
117 // The field or property must be writable.
118 if (fieldOrProperty.Writeability != Writeability.All)
119 {
120 builder.Diagnostics.Report(
121 _fieldOrPropertyCannotBeReadOnly.WithArguments((
122 fieldOrProperty.DeclarationKind,
123 fieldOrProperty)), fieldOrProperty);
124 success = false;
125 }
126
127 // If it is a field, it must be an automatic property.
128 if (fieldOrProperty is IProperty property && property.IsAutoPropertyOrField == false)
129 {
130 builder.Diagnostics.Report(_childPropertyMustBeAutomatic.WithArguments(property),
131 property);
132 success = false;
133 }
134
135 // The type of the field must be cloneable.
136 void ReportMissingMethod()
137 {
138 builder.Diagnostics.Report(
139 _missingCloneMethod.WithArguments((fieldOrProperty.DeclarationKind,
140 fieldOrProperty,
141 fieldOrProperty.Type)), fieldOrProperty);
142 }
143
144 if (fieldOrProperty.Type is not INamedType fieldType)
145 {
146 // The field type is an array, a pointer or another special type, which do not have a Clone method.
147 ReportMissingMethod();
148 success = false;
149 }
150 else
151 {
152 var cloneMethod = fieldType.AllMethods.OfName("Clone")
153 .SingleOrDefault(p => p.Parameters.Count == 0);
154
155 if (cloneMethod == null)
156 {
157 // There is no Clone method.
158 // If may be implemented by an aspect, but we don't have access to aspects on other types
159 // at design time.
160 if (!MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime)
161 {
162 if (!fieldType.BelongsToCurrentProject ||
163 !fieldType.Enhancements().HasAspect<CloneableAttribute>())
164 {
165 ReportMissingMethod();
166 success = false;
167 }
168 }
169 }
170 else if (cloneMethod.Accessibility is not (Accessibility.Public
171 or Accessibility.Internal))
172 {
173 // If we have a Clone method, it must be public.
174 builder.Diagnostics.Report(
175 _cloneMethodMustBePublic.WithArguments(cloneMethod), fieldOrProperty);
176 success = false;
177 }
178 }
179 }
180
181 return success;
182 }
183
184
185 private static IEnumerable<IFieldOrProperty> GetCloneableFieldsOrProperties(INamedType type)
186 => type.FieldsAndProperties.Where(f =>
187 f.Attributes.OfAttributeType(typeof(ChildAttribute)).Any());
188
189 [Template]
190 public virtual T CloneImpl<[CompileTime] T>()
191 {
192 // This compile-time variable will receive the expression representing the base call.
193 // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
194 // we will call MemberwiseClone (this is the initialization of the pattern).
195 IExpression baseCall;
196
197 if (meta.Target.Method.IsOverride)
198 {
199 baseCall = (IExpression)meta.Base.Clone();
200 }
201 else
202 {
203 baseCall = (IExpression)meta.This.MemberwiseClone();
204 }
205
206 // Define a local variable of the same type as the target type.
207 var clone = (T)baseCall.Value!;
208
209 // Call CloneMembers, which may have a hand-written part.
210 meta.This.CloneMembers(clone);
211
212
213 return clone;
214 }
215
216 [Template]
217 private void CloneMembers<[CompileTime] T>(T clone)
218 {
219 // Select cloneable fields.
220 var cloneableFields = GetCloneableFieldsOrProperties(meta.Target.Type);
221
222 foreach (var field in cloneableFields)
223 {
224 // Check if we have a public method 'Clone()' for the type of the field.
225 var fieldType = (INamedType)field.Type;
226
227 field.With(clone).Value = meta.Cast(fieldType, field.Value?.Clone());
228 }
229
230 // Call the hand-written implementation, if any.
231 meta.Proceed();
232 }
233
234 [InterfaceMember(IsExplicit = true)]
235 private object Clone() => meta.This.Clone();
236}
We will first explain the implementation of the second requirement.
Adding warnings with two code fixes
As usual, we first need to define the error as a static field of the class:
29private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
30 _annotateFieldOrProperty =
31 new("CLONE05", Severity.Warning, "Mark the {0} '{1}' as a [Child] or [Reference].");
32
33
Then, we detect unannotated properties of a cloneable type. And report the warnings with suggestions for code fixes:
85foreach (var fieldOrProperty in eligibleChildren)
86{
87 builder.Diagnostics.Report(_annotateFieldOrProperty
88 .WithArguments((fieldOrProperty.DeclarationKind, fieldOrProperty)).WithCodeFixes(
89 CodeFixFactory.AddAttribute(fieldOrProperty, typeof(ChildAttribute),
90 "Cloneable | Mark as child"),
91 CodeFixFactory.AddAttribute(fieldOrProperty, typeof(ReferenceAttribute),
92 "Cloneable | Mark as reference")), fieldOrProperty);
93}
Notice that we used the WithCodeFixes method to attach code fixes to the diagnostics. To create the code fixes, we use the CodeFixFactory.AddAttribute method. The CodeFixFactory class contains other methods to create simple code fixes.
Suggesting CloneMembers
When we detect that a cloneable type does not already have a CloneMembers
method, we suggest adding it without
reporting a warning using the Suggest method:
97// If we don't have a CloneMember method, suggest to add it.
98if (!builder.Target.Methods.OfName(nameof(this.CloneMembers)).Any())
99{
100 builder.Diagnostics.Suggest(
101 new CodeFix("Cloneable | Customize manually",
102 codeFix =>
103 codeFix.ApplyAspectAsync(builder.Target,
104 new AddEmptyCloneMembersAspect())));
105}
Unlike adding attributes, there is no ready-made code fix from the CodeFixFactory class to implement this method. We must implement the code transformation ourselves and provide an instance of the CodeFix class. This object comprises just two elements: the title of the code fix and a delegate performing the code transformation thanks to an ICodeActionBuilder. The list of transformations that are directly available from the ICodeActionBuilder is limited, but we can get enormous power using the ApplyAspectAsync method, which can apply any aspect to any declaration.
To implement the code fix, we create the ad-hoc aspect class AddEmptyCloneMembersAspect
, whose implementation should
now be familiar:
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3
4internal class AddEmptyCloneMembersAspect : IAspect<INamedType>
5{
6 public void BuildAspect(IAspectBuilder<INamedType> builder) =>
7 builder.Advice.IntroduceMethod(
8 builder.Target,
9 nameof(this.CloneMembers),
10 whenExists: OverrideStrategy.Override,
11 args: new { T = builder.Target });
12
13 [Template]
14 private void CloneMembers<[CompileTime] T>(T clone)
15 {
16 meta.InsertComment("Use this method to modify the 'clone' parameter.");
17 meta.InsertComment("Your code executes after the aspect.");
18 }
19}
Note that we did not derive AddEmptyCloneMembersAspect
from TypeAspect because it
would make the aspect a custom attribute. Instead, we directly implemented the IAspect
interface.
Summary
We implemented coding guidance into our Cloneable
aspect so that our users do not have to look at the design
documentation so often and to prevent them from making frequent mistakes. We used two new techniques: attaching code
fixes to warnings using
the IDiagnostic.WithCodeFixes method and
suggesting code fixes without warning using the Suggest
method.