MetalamaCommented examplesCloneStep 3.​ Allowing handmade customizations
Open sandboxFocusImprove this doc

Clone example, step 3: allowing handmade customizations

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.

Source Code


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 )
10        => clone.Players = new List<Player>( this.Players );













11}
Transformed Code
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 )
13        { clone.Settings = (this.Settings.Clone());
14        clone.Players = new List<Player>(this.Players);
15    }
16public virtual Game Clone()
17    {
18        var clone = (Game)this.MemberwiseClone();
19        this.CloneMembers(clone);
20        return clone;
21    }
22
23    object ICloneable.Clone()
24    {
25        return Clone();
26    }
27}
Source Code


1[Cloneable]
2internal class GameSettings
3{

4    public int Level { get; set; }
5    public string World { get; set; }













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

We added the following code in the BuildAspect method:

47        builder.Advice.IntroduceMethod( 
48            builder.Target,
49            nameof(this.CloneMembers),
50            whenExists: OverrideStrategy.Override,
51            args: new { T = builder.Target } ); 

The template for the CloneMembers method is as follows:

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

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.