MetalamaCommented examplesCloneStep 4.​ Providing coding guidance
Open sandboxFocusImprove this doc

Clone example, step 3: adding coding guidance

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:

Refactoring suggestion: add CloneMembers

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:

Refactoring suggestion: 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:

Refactoring suggestion: fixes

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, "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    private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)> _annotateFieldOrProperty =
28        new("CLONE05", Severity.Warning, "Mark the {0} '{1}' as a [Child] or [Reference].");
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        builder.Advice.IntroduceMethod( 
53            builder.Target,
54            nameof(this.CloneMembers),
55            whenExists: OverrideStrategy.Override,
56            args: new { T = builder.Target } ); 
57
58        // Implement the ICloneable interface.
59        builder.Advice.ImplementInterface(
60            builder.Target,
61            typeof(ICloneable),
62            OverrideStrategy.Ignore );
63
64        // When we have non-child fields or properties of a cloneable type,
65        // suggest to add the child attribute
66        var eligibleChildren = builder.Target.FieldsAndProperties
67            .Where( f => f.Writeability == Writeability.All &&
68                         !f.IsImplicitlyDeclared &&
69                         !f.Attributes.OfAttributeType( typeof(ChildAttribute) ).Any() &&
70                         !f.Attributes.OfAttributeType( typeof(ReferenceAttribute) ).Any() &&
71                         f.Type is INamedType fieldType &&
72                         (fieldType.AllMethods.OfName( "Clone" ).Where( m => m.Parameters.Count == 0 ).Any() ||
73                          fieldType.Attributes.OfAttributeType( typeof(CloneableAttribute) ).Any()) );
74
75
76        foreach ( var fieldOrProperty in eligibleChildren ) 
77        {
78            builder.Diagnostics.Report( _annotateFieldOrProperty
79                .WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty) ).WithCodeFixes(
80                    CodeFixFactory.AddAttribute( fieldOrProperty, typeof(ChildAttribute), "Cloneable | Mark as child" ),
81                    CodeFixFactory.AddAttribute( fieldOrProperty, typeof(ReferenceAttribute),
82                        "Cloneable | Mark as reference" ) ), fieldOrProperty );
83        } 
84
85        // If we don't have a CloneMember method, suggest to add it.
86        if ( !builder.Target.Methods.OfName( nameof(this.CloneMembers) ).Any() ) 
87        {
88            builder.Diagnostics.Suggest(
89                new CodeFix( "Cloneable | Customize manually",
90                    codeFix => codeFix.ApplyAspectAsync( builder.Target, new AddEmptyCloneMembersAspect() ) ) );
91        } 
92    }
93
94
95    private bool VerifyFieldsAndProperties( IAspectBuilder<INamedType> builder )
96    {
97        var success = true;
98
99        // Verify that child fields are valid.
100        foreach ( var fieldOrProperty in GetCloneableFieldsOrProperties( builder.Target ) )
101        {
102            // The field or property must be writable.
103            if ( fieldOrProperty.Writeability != Writeability.All )
104            {
105                builder.Diagnostics.Report(
106                    _fieldOrPropertyCannotBeReadOnly.WithArguments( (fieldOrProperty.DeclarationKind,
107                        fieldOrProperty) ), fieldOrProperty );
108                success = false;
109            }
110
111            // If it is a field, it must be an automatic property.
112            if ( fieldOrProperty is IProperty property && property.IsAutoPropertyOrField == false )
113            {
114                builder.Diagnostics.Report( _childPropertyMustBeAutomatic.WithArguments( property ), property );
115                success = false;
116            }
117
118            // The type of the field must be cloneable.
119            void ReportMissingMethod()
120            {
121                builder.Diagnostics.Report(
122                    _missingCloneMethod.WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty,
123                        fieldOrProperty.Type) ), fieldOrProperty );
124            }
125
126            if ( fieldOrProperty.Type is not INamedType fieldType )
127            {
128                // The field type is an array, a pointer or another special type, which do not have a Clone method.
129                ReportMissingMethod();
130                success = false;
131            }
132            else
133            {
134                var cloneMethod = fieldType.AllMethods.OfName( "Clone" )
135                    .SingleOrDefault( p => p.Parameters.Count == 0 );
136
137                if ( cloneMethod == null )
138                {
139                    // There is no Clone method.
140                    // If may be implemented by an aspect, but we don't have access to aspects on other types
141                    // at design time.
142                    if ( !MetalamaExecutionContext.Current.ExecutionScenario.IsDesignTime )
143                    {
144                        if ( !fieldType.BelongsToCurrentProject ||
145                             !fieldType.Enhancements().HasAspect<CloneableAttribute>() )
146                        {
147                            ReportMissingMethod();
148                            success = false;
149                        }
150                    }
151                }
152                else if ( cloneMethod.Accessibility is not (Accessibility.Public or Accessibility.Internal) )
153                {
154                    // If we have a Clone method, it must be public.
155                    builder.Diagnostics.Report(
156                        _cloneMethodMustBePublic.WithArguments( cloneMethod ), fieldOrProperty );
157                    success = false;
158                }
159            }
160        }
161
162        return success;
163    }
164
165
166    private static IEnumerable<IFieldOrProperty> GetCloneableFieldsOrProperties( INamedType type )
167        => type.FieldsAndProperties.Where( f => f.Attributes.OfAttributeType( typeof(ChildAttribute) ).Any() );
168
169    [Template]
170    public virtual T CloneImpl<[CompileTime] T>()
171    {
172        // This compile-time variable will receive the expression representing the base call.
173        // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
174        // we will call MemberwiseClone (this is the initialization of the pattern).
175        IExpression baseCall;
176
177        if ( meta.Target.Method.IsOverride )
178        {
179            baseCall = (IExpression) meta.Base.Clone();
180        }
181        else
182        {
183            baseCall = (IExpression) meta.This.MemberwiseClone();
184        }
185
186        // Define a local variable of the same type as the target type.
187        var clone = (T) baseCall.Value!;
188
189        // Call CloneMembers, which may have a hand-written part.
190        meta.This.CloneMembers( clone );
191
192
193        return clone;
194    }
195
196    [Template]
197    private void CloneMembers<[CompileTime] T>( T clone )
198    {
199        // Select cloneable fields.
200        var cloneableFields = GetCloneableFieldsOrProperties( meta.Target.Type );
201
202        foreach ( var field in cloneableFields )
203        {
204            // Check if we have a public method 'Clone()' for the type of the field.
205            var fieldType = (INamedType) field.Type;
206
207            field.With( clone ).Value = meta.Cast( fieldType, field.Value?.Clone() );
208        }
209
210        // Call the hand-written implementation, if any.
211        meta.Proceed();
212    }
213
214    [InterfaceMember( IsExplicit = true )]
215    private object Clone() => meta.This.Clone();
216}

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:

27    private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)> _annotateFieldOrProperty =
28        new("CLONE05", Severity.Warning, "Mark the {0} '{1}' as a [Child] or [Reference].");

Then, we detect unannotated properties of a cloneable type. And report the warnings with suggestions for code fixes:

76        foreach ( var fieldOrProperty in eligibleChildren ) 
77        {
78            builder.Diagnostics.Report( _annotateFieldOrProperty
79                .WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty) ).WithCodeFixes(
80                    CodeFixFactory.AddAttribute( fieldOrProperty, typeof(ChildAttribute), "Cloneable | Mark as child" ),
81                    CodeFixFactory.AddAttribute( fieldOrProperty, typeof(ReferenceAttribute),
82                        "Cloneable | Mark as reference" ) ), fieldOrProperty );
83        } 

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:

86        if ( !builder.Target.Methods.OfName( nameof(this.CloneMembers) ).Any() ) 
87        {
88            builder.Diagnostics.Suggest(
89                new CodeFix( "Cloneable | Customize manually",
90                    codeFix => codeFix.ApplyAspectAsync( builder.Target, new AddEmptyCloneMembersAspect() ) ) );
91        } 

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.