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

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:

29    private static readonly DiagnosticDefinition<(DeclarationKind, IFieldOrProperty)>
30        _annotateFieldOrProperty =
31            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:

81        foreach ( var fieldOrProperty in eligibleChildren ) 
82        {
83            builder.Diagnostics.Report( _annotateFieldOrProperty
84                .WithArguments( (fieldOrProperty.DeclarationKind, fieldOrProperty) ).WithCodeFixes(
85                    CodeFixFactory.AddAttribute( fieldOrProperty, typeof(ChildAttribute),
86                        "Cloneable | Mark as child" ),
87                    CodeFixFactory.AddAttribute( fieldOrProperty, typeof(ReferenceAttribute),
88                        "Cloneable | Mark as reference" ) ), fieldOrProperty );
89        } 

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:

93                .Any() ) 
94        {
95            builder.Diagnostics.Suggest(
96                new CodeFix( "Cloneable | Customize manually",
97                    codeFix =>
98                        codeFix.ApplyAspectAsync( builder.Target,
99                            new AddEmptyCloneMembersAspect() ) ) );
100        } 

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.