In this second article, we will see how to modify our aspect to support type inheritance.
Strategizing
As always, we need to start reasoning and make some decisions about the implementation strategy before jumping into code.
We take the following approach:
- Each originator class will still have its own memento class, and these memento classes will inherit from each other. So if
Fish
derives fromFishtankArtifact
, thenFish.Memento
will derive fromFishtankArtifact.Memento
. Therefore, memento classes will beprotected
and notprivate
. Each memento class will be responsible for its own properties, not for the properties of the base class. - Each
RestoreMemento
will be responsible only for the fields and properties of the current class and will call thebase
implementation to cope with properties of the base class.
Result
When we are done with the aspect, it will transform code as follows.
Here is a base class:
1using Metalama.Patterns.Observability;
2
3[Memento]
4[Observable]
5public partial class FishtankArtifact
6{
7 public string? Name { get; set; }
8
9 public DateTime DateAdded { get; set; }
10}
1using System;
2using System.ComponentModel;
3using Metalama.Patterns.Observability;
4
5[Memento]
6[Observable]
7public partial class FishtankArtifact
8: INotifyPropertyChanged, IMementoable
9{
10private string? _name;
11
12 public string? Name { get { return this._name; } set { if (!object.ReferenceEquals(value, this._name)) { this._name = value; this.OnPropertyChanged("Name"); } } }
13 private DateTime _dateAdded;
14
15 public DateTime DateAdded { get { return this._dateAdded; } set { if (this._dateAdded != value) { this._dateAdded = value; this.OnPropertyChanged("DateAdded"); } } }
16 protected virtual void OnPropertyChanged(string propertyName)
17 {
18 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
19 }
20 public virtual void RestoreMemento(IMemento memento)
21 {
22 var typedMemento = (Memento)memento;
23 this.Name = (typedMemento).Name;
24 this.DateAdded = (typedMemento).DateAdded;
25 }
26 public virtual IMemento SaveToMemento()
27 {
28 return new Memento(this);
29 }
30 public event PropertyChangedEventHandler? PropertyChanged;
31
32 protected class Memento : IMemento
33 {
34 public Memento(FishtankArtifact originator)
35 {
36 this.Originator = originator;
37 this.Name = originator.Name;
38 this.DateAdded = originator.DateAdded;
39 }
40 public DateTime DateAdded { get; }
41 public string? Name { get; }
42 public IMementoable? Originator { get; }
43 }
44}
Here is a derived class:
1public partial class Fish : FishtankArtifact
2{
3 public string? Species { get; set; }
4}
1using System;
2
3public partial class Fish : FishtankArtifact
4{
5private string? _species;
6
7 public string? Species { get { return this._species; } set { if (!object.ReferenceEquals(value, this._species)) { this._species = value; this.OnPropertyChanged("Species"); } } }
8 protected override void OnPropertyChanged(string propertyName)
9 {
10 base.OnPropertyChanged(propertyName);
11 }
12 public override void RestoreMemento(IMemento memento)
13 {
14 base.RestoreMemento(memento);
15 var typedMemento = (Memento)memento;
16 this.Species = (typedMemento).Species;
17 }
18 public override IMemento SaveToMemento()
19 {
20 return new Memento(this);
21 }
22 protected new class Memento : FishtankArtifact.Memento, IMemento
23 {
24 public Memento(Fish originator) : base(originator)
25 {
26 this.Species = originator.Species;
27 }
28 public string? Species { get; }
29 }
30}
Step 1. Mark the aspect as inheritable
We certainly want our [Memento]
aspect to automatically apply to derived classes when we add it to a base class. We achieve this by adding the [Inheritable] attribute to the aspect class.
6[Inheritable]
7public sealed class MementoAttribute : TypeAspect
For details about aspect inheritance, see Applying aspects to derived types.
Step 2. Validating the base type
If the base type already implements IMementoable
, we need to check that the implementation fulfills our expectations. Indeed, it is possible that IMementoable
is implemented manually. The following rules must be respected:
- There must be a
Memento
nested type in the base type. - This nested type must be protected.
- This nested type must have a public or protected constructor accepting the base type as its only argument.
When doing any sort of validation, the first step is to define the errors we will use.
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Diagnostics;
4
5namespace DefaultNamespace;
6
7[CompileTime]
8internal static class DiagnosticDefinitions
9{
10 public static DiagnosticDefinition<INamedType> BaseTypeHasNoMementoType
11 = new("MEMENTO01", Severity.Error,
12 "The base type '{0}' does not have a 'Memento' nested type.");
13
14 public static DiagnosticDefinition<INamedType> MementoTypeMustBeProtected
15 = new("MEMENTO02", Severity.Error,
16 "The type '{0}' must be protected.");
17
18 public static DiagnosticDefinition<INamedType> MementoTypeMustNotBeSealed
19 = new("MEMENTO03", Severity.Error,
20 "The type '{0}' must be not be sealed.");
21
22 public static DiagnosticDefinition<(INamedType MementoType, IType ParameterType)>
23 MementoTypeMustHaveConstructor
24 = new("MEMENTO04", Severity.Error,
25 "The type '{0}' must have a constructor with a single parameter of type '{1}'.");
26
27 public static DiagnosticDefinition<IConstructor> MementoConstructorMustBePublicOrProtected
28 = new("MEMENTO05", Severity.Error,
29 "The constructor '{0}' must be public or protected.");
30}
We can then validate the code.
21
22 var isBaseMementotable = builder.Target.BaseType?.Is( typeof(IMementoable) ) == true;
23
24 INamedType? baseMementoType;
25 IConstructor? baseMementoConstructor;
26 if ( isBaseMementotable )
27 {
28 var baseTypeDefinition = builder.Target.BaseType!.Definition;
29 baseMementoType = baseTypeDefinition.Types.OfName( "Memento" )
30 .SingleOrDefault();
31
32 if ( baseMementoType == null )
33 {
34 builder.Diagnostics.Report(
35 DiagnosticDefinitions.BaseTypeHasNoMementoType.WithArguments(
36 baseTypeDefinition ) );
37 builder.SkipAspect();
38 return;
39 }
40
41 if ( baseMementoType.Accessibility !=
42 Metalama.Framework.Code.Accessibility.Protected )
43 {
44 builder.Diagnostics.Report(
45 DiagnosticDefinitions.MementoTypeMustBeProtected.WithArguments(
46 baseMementoType ) );
47 builder.SkipAspect();
48 return;
49 }
50
51 if ( baseMementoType.IsSealed )
52 {
53 builder.Diagnostics.Report(
54 DiagnosticDefinitions.MementoTypeMustNotBeSealed.WithArguments(
55 baseMementoType ) );
56 builder.SkipAspect();
57 return;
58 }
59
60 baseMementoConstructor = baseMementoType.Constructors
61 .FirstOrDefault( c => c.Parameters.Count == 1 &&
62 c.Parameters[0].Type.Is( baseTypeDefinition ) );
63
64 if ( baseMementoConstructor == null )
65 {
66 builder.Diagnostics.Report(
67 DiagnosticDefinitions.MementoTypeMustHaveConstructor
68 .WithArguments( (baseMementoType, baseTypeDefinition) ) );
69 builder.SkipAspect();
70 return;
71 }
72
73 if ( baseMementoConstructor.Accessibility is not (Metalama.Framework.Code.Accessibility
74 .Protected or Metalama.Framework.Code.Accessibility.Public) )
75 {
76 builder.Diagnostics.Report(
77 DiagnosticDefinitions.MementoConstructorMustBePublicOrProtected
78 .WithArguments( baseMementoConstructor ) );
79 builder.SkipAspect();
80 return;
81 }
82 }
83 else
84 {
85 baseMementoType = null;
86 baseMementoConstructor = null;
87 }
88
For details regarding error reporting, see Reporting and suppressing diagnostics.
Step 2. Specifying the OverrideAction
By default, advising methods such as IntroduceClass or IntroduceMethod will fail if the same member already exists in the current or base type. To specify how the advising method should behave in this case, we must supply an OverrideStrategy to the whenExists
parameter. The default value is Fail
. We must change it to Ignore
, Override
, or New
:
- When using IntroduceClass to introduce the
Memento
nested class, we useNew
. - When using IntroduceMethod to introduce
SaveToMemento
orRestoreMemento
, we useOverride
. - When using ImplementInterface to implement
IMemento
orIMementoable
, we useIgnore
.
Step 3. Setting the base type and constructor of the Memento type
Now that we know if there is a valid base type, we can modify the logic that introduces the nested class and set the BaseType property.
90
91 // Introduce a new private nested class called Memento.
92 var mementoType =
93 builder.IntroduceClass(
94 "Memento",
95 whenExists: OverrideStrategy.New,
96 buildType: b =>
97 {
98 b.Accessibility = Metalama.Framework.Code.Accessibility.Protected;
99 b.BaseType = baseMementoType;
100 } );
If we have a base class, we must also instruct the introduced constructor to call the base constructor. This is done by setting the InitializerKind property. We then call the AddInitializerArgument method and pass the IParameterBuilder returned by AddParameter.
134 mementoType.IntroduceConstructor(
135 nameof(this.MementoConstructorTemplate),
136 buildConstructor: b =>
137 {
138 var parameter = b.AddParameter( "originator", builder.Target );
139
140 if ( baseMementoConstructor != null )
141 {
142 b.InitializerKind = ConstructorInitializerKind.Base;
143 b.AddInitializerArgument( parameter );
144 }
145 } );
Step 4. Calling the base implementation from RestoreMemento
Finally, we must edit the RestoreMemento
template to ensure it calls the base
method if it exists. This can be done by simply calling meta.Proceed()
. If a base method exists, it will call it. Otherwise, this call will be ignored.
196 [Template]
197 public void RestoreMemento( IMemento memento )
198 {
199 var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
200
201 // Call the base method if any.
202 meta.Proceed();
203
204 var typedMemento = meta.Cast( buildAspectInfo.MementoType, memento );
205
206 // Set fields of this instance to the values stored in the Memento.
207 foreach ( var pair in buildAspectInfo.PropertyMap )
208 {
209 pair.Key.Value = pair.Value.With( (IExpression) typedMemento ).Value;
210 }
211 }
Complete aspect
Here is the MementoAttribute
, now supporting class inheritance.
1using DefaultNamespace;
2using Metalama.Framework.Advising;
3using Metalama.Framework.Aspects;
4using Metalama.Framework.Code;
5
6[Inheritable]
7public sealed class MementoAttribute : TypeAspect
8{
9 [CompileTime]
10 private record BuildAspectInfo(
11 // The newly introduced Memento type.
12 INamedType MementoType,
13 // Mapping from fields or properties in the Originator to the corresponding property
14 // in the Memento type.
15 Dictionary<IFieldOrProperty, IProperty> PropertyMap,
16 // The Originator property in the new Memento type.
17 IProperty? OriginatorProperty );
18
19 public override void BuildAspect( IAspectBuilder<INamedType> builder )
20 {
21
22 var isBaseMementotable = builder.Target.BaseType?.Is( typeof(IMementoable) ) == true;
23
24 INamedType? baseMementoType;
25 IConstructor? baseMementoConstructor;
26 if ( isBaseMementotable )
27 {
28 var baseTypeDefinition = builder.Target.BaseType!.Definition;
29 baseMementoType = baseTypeDefinition.Types.OfName( "Memento" )
30 .SingleOrDefault();
31
32 if ( baseMementoType == null )
33 {
34 builder.Diagnostics.Report(
35 DiagnosticDefinitions.BaseTypeHasNoMementoType.WithArguments(
36 baseTypeDefinition ) );
37 builder.SkipAspect();
38 return;
39 }
40
41 if ( baseMementoType.Accessibility !=
42 Metalama.Framework.Code.Accessibility.Protected )
43 {
44 builder.Diagnostics.Report(
45 DiagnosticDefinitions.MementoTypeMustBeProtected.WithArguments(
46 baseMementoType ) );
47 builder.SkipAspect();
48 return;
49 }
50
51 if ( baseMementoType.IsSealed )
52 {
53 builder.Diagnostics.Report(
54 DiagnosticDefinitions.MementoTypeMustNotBeSealed.WithArguments(
55 baseMementoType ) );
56 builder.SkipAspect();
57 return;
58 }
59
60 baseMementoConstructor = baseMementoType.Constructors
61 .FirstOrDefault( c => c.Parameters.Count == 1 &&
62 c.Parameters[0].Type.Is( baseTypeDefinition ) );
63
64 if ( baseMementoConstructor == null )
65 {
66 builder.Diagnostics.Report(
67 DiagnosticDefinitions.MementoTypeMustHaveConstructor
68 .WithArguments( (baseMementoType, baseTypeDefinition) ) );
69 builder.SkipAspect();
70 return;
71 }
72
73 if ( baseMementoConstructor.Accessibility is not (Metalama.Framework.Code.Accessibility
74 .Protected or Metalama.Framework.Code.Accessibility.Public) )
75 {
76 builder.Diagnostics.Report(
77 DiagnosticDefinitions.MementoConstructorMustBePublicOrProtected
78 .WithArguments( baseMementoConstructor ) );
79 builder.SkipAspect();
80 return;
81 }
82 }
83 else
84 {
85 baseMementoType = null;
86 baseMementoConstructor = null;
87 }
88
89
90
91 // Introduce a new private nested class called Memento.
92 var mementoType =
93 builder.IntroduceClass(
94 "Memento",
95 whenExists: OverrideStrategy.New,
96 buildType: b =>
97 {
98 b.Accessibility = Metalama.Framework.Code.Accessibility.Protected;
99 b.BaseType = baseMementoType;
100 } );
101
102 var originatorFieldsAndProperties = builder.Target.FieldsAndProperties /* <SelectFields> */
103 .Where( p => p is
104 {
105 IsStatic: false,
106 IsAutoPropertyOrField: true,
107 IsImplicitlyDeclared: false,
108 Writeability: Writeability.All
109 } )
110 .Where( p =>
111 !p.Attributes.OfAttributeType( typeof(MementoIgnoreAttribute) )
112 .Any() ); /* </SelectFields> */
113
114 // Introduce data properties to the Memento class for each field of the target class.
115 var propertyMap = new Dictionary<IFieldOrProperty, IProperty>(); /* <IntroduceProperties> */
116
117 foreach ( var fieldOrProperty in originatorFieldsAndProperties )
118 {
119 var introducedField = mementoType.IntroduceProperty(
120 nameof(this.MementoProperty),
121 buildProperty: b =>
122 {
123 var trimmedName = fieldOrProperty.Name.TrimStart( '_' );
124
125 b.Name = trimmedName.Substring( 0, 1 ).ToUpperInvariant() +
126 trimmedName.Substring( 1 );
127 b.Type = fieldOrProperty.Type;
128 } );
129
130 propertyMap.Add( fieldOrProperty, introducedField.Declaration );
131 } /* </IntroduceProperties> */
132
133 // Add a constructor to the Memento class that records the state of the originator.
134 mementoType.IntroduceConstructor(
135 nameof(this.MementoConstructorTemplate),
136 buildConstructor: b =>
137 {
138 var parameter = b.AddParameter( "originator", builder.Target );
139
140 if ( baseMementoConstructor != null )
141 {
142 b.InitializerKind = ConstructorInitializerKind.Base;
143 b.AddInitializerArgument( parameter );
144 }
145 } );
146
147
148 // Implement the IMemento interface on the Memento class and add its members.
149 mementoType.ImplementInterface( typeof(IMemento),
150 whenExists: OverrideStrategy.Ignore );
151
152 var introducePropertyResult = mementoType.IntroduceProperty(
153 nameof(this.Originator),
154 whenExists: OverrideStrategy.Ignore );
155 var originatorProperty = introducePropertyResult.Outcome == AdviceOutcome.Default
156 ? introducePropertyResult.Declaration
157 : null;
158
159
160
161
162 // Implement the rest of the IOriginator interface and its members.
163 builder.ImplementInterface( typeof(IMementoable), OverrideStrategy.Ignore );
164
165 builder.IntroduceMethod(
166 nameof(this.SaveToMemento),
167 whenExists: OverrideStrategy.Override,
168 buildMethod: m => m.IsVirtual = !builder.Target.IsSealed,
169 args: new { mementoType = mementoType.Declaration } );
170
171 builder.IntroduceMethod(
172 nameof(this.RestoreMemento),
173 buildMethod: m => m.IsVirtual = !builder.Target.IsSealed,
174 whenExists: OverrideStrategy.Override );
175
176 // Pass the state to the templates.
177 builder.Tags = new BuildAspectInfo( mementoType.Declaration, propertyMap, /* <SetTag> */
178 originatorProperty ); /* </SetTag> */
179 }
180
181 [Template] public object? MementoProperty { get; }
182
183 [Template] public IMementoable? Originator { get; }
184
185 [Template]
186 public IMemento SaveToMemento()
187 {
188 var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!; /* <GetTag> */
189 /* </GetTag> */
190
191 // Invoke the constructor of the Memento class and pass this object as the originator.
192 return buildAspectInfo.MementoType.Constructors.Single()
193 .Invoke( (IExpression) meta.This )!;
194 }
195
196 [Template]
197 public void RestoreMemento( IMemento memento )
198 {
199 var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
200
201 // Call the base method if any.
202 meta.Proceed();
203
204 var typedMemento = meta.Cast( buildAspectInfo.MementoType, memento );
205
206 // Set fields of this instance to the values stored in the Memento.
207 foreach ( var pair in buildAspectInfo.PropertyMap )
208 {
209 pair.Key.Value = pair.Value.With( (IExpression) typedMemento ).Value;
210 }
211 }
212
213 [Template] /* <ConstructorTemplate> */
214 public void MementoConstructorTemplate()
215 {
216 var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
217
218 // Set the originator property and the data properties of the Memento.
219 if ( buildAspectInfo.OriginatorProperty != null )
220 {
221 buildAspectInfo.OriginatorProperty.Value = meta.Target.Parameters[0];
222 }
223 else
224 {
225 // We are in a derived type and there is no need to assign the property.
226 }
227
228 foreach ( var pair in buildAspectInfo.PropertyMap )
229 {
230 pair.Value.Value = pair.Key.With( meta.Target.Parameters[0] ).Value;
231 }
232 } /* </ConstructorTemplate> */
233}