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.
7[Inheritable]
8public 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.
24var isBaseMementotable = builder.Target.BaseType?.Is(typeof(IMementoable)) == true;
25
26INamedType? baseMementoType;
27IConstructor? baseMementoConstructor;
28if (isBaseMementotable)
29{
30 var baseTypeDefinition = builder.Target.BaseType!.Definition;
31 baseMementoType = baseTypeDefinition.Types.OfName("Memento")
32 .SingleOrDefault();
33
34 if (baseMementoType == null)
35 {
36 builder.Diagnostics.Report(
37 DiagnosticDefinitions.BaseTypeHasNoMementoType.WithArguments(
38 baseTypeDefinition));
39 builder.SkipAspect();
40 return;
41 }
42
43 if (baseMementoType.Accessibility !=
44 Metalama.Framework.Code.Accessibility.Protected)
45 {
46 builder.Diagnostics.Report(
47 DiagnosticDefinitions.MementoTypeMustBeProtected.WithArguments(
48 baseMementoType));
49 builder.SkipAspect();
50 return;
51 }
52
53 if (baseMementoType.IsSealed)
54 {
55 builder.Diagnostics.Report(
56 DiagnosticDefinitions.MementoTypeMustNotBeSealed.WithArguments(
57 baseMementoType));
58 builder.SkipAspect();
59 return;
60 }
61
62 baseMementoConstructor = baseMementoType.Constructors
63 .FirstOrDefault(c => c.Parameters.Count == 1 &&
64 c.Parameters[0].Type.Is(baseTypeDefinition));
65
66 if (baseMementoConstructor == null)
67 {
68 builder.Diagnostics.Report(
69 DiagnosticDefinitions.MementoTypeMustHaveConstructor
70 .WithArguments((baseMementoType, baseTypeDefinition)));
71 builder.SkipAspect();
72 return;
73 }
74
75 if (baseMementoConstructor.Accessibility is not (Metalama.Framework.Code.Accessibility
76 .Protected or Metalama.Framework.Code.Accessibility.Public))
77 {
78 builder.Diagnostics.Report(
79 DiagnosticDefinitions.MementoConstructorMustBePublicOrProtected
80 .WithArguments(baseMementoConstructor));
81 builder.SkipAspect();
82 return;
83 }
84}
85else
86{
87 baseMementoType = null;
88 baseMementoConstructor = null;
89}
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.
93// Introduce a new private nested class called Memento.
94var mementoType =
95 builder.IntroduceClass(
96 "Memento",
97 whenExists: OverrideStrategy.New,
98 buildType: b =>
99 {
100 b.Accessibility = Metalama.Framework.Code.Accessibility.Protected;
101 b.BaseType = baseMementoType;
102 });
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.
141// Add a constructor to the Memento class that records the state of the originator.
142mementoType.IntroduceConstructor(
143 nameof(this.MementoConstructorTemplate),
144 buildConstructor: b =>
145 {
146 var parameter = b.AddParameter("originator", builder.Target);
147
148 if (baseMementoConstructor != null)
149 {
150 b.InitializerKind = ConstructorInitializerKind.Base;
151 b.AddInitializerArgument(parameter);
152 }
153 });
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.
207[Template]
208public void RestoreMemento(IMemento memento)
209{
210 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
211
212 // Call the base method if any.
213 meta.Proceed();
214
215 var typedMemento = meta.Cast(buildAspectInfo.MementoType, memento);
216
217 // Set fields of this instance to the values stored in the Memento.
218 foreach (var pair in buildAspectInfo.PropertyMap)
219 {
220 pair.Key.Value = pair.Value.With((IExpression)typedMemento).Value;
221 }
222}
223
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//
7[Inheritable]
8public sealed class MementoAttribute : TypeAspect
9//
10{
11 [CompileTime]
12 private record BuildAspectInfo(
13 // The newly introduced Memento type.
14 INamedType MementoType,
15 // Mapping from fields or properties in the Originator to the corresponding property
16 // in the Memento type.
17 Dictionary<IFieldOrProperty, IProperty> PropertyMap,
18 // The Originator property in the new Memento type.
19 IProperty? OriginatorProperty);
20
21 public override void BuildAspect(IAspectBuilder<INamedType> builder)
22 {
23 //
24 var isBaseMementotable = builder.Target.BaseType?.Is(typeof(IMementoable)) == true;
25
26 INamedType? baseMementoType;
27 IConstructor? baseMementoConstructor;
28 if (isBaseMementotable)
29 {
30 var baseTypeDefinition = builder.Target.BaseType!.Definition;
31 baseMementoType = baseTypeDefinition.Types.OfName("Memento")
32 .SingleOrDefault();
33
34 if (baseMementoType == null)
35 {
36 builder.Diagnostics.Report(
37 DiagnosticDefinitions.BaseTypeHasNoMementoType.WithArguments(
38 baseTypeDefinition));
39 builder.SkipAspect();
40 return;
41 }
42
43 if (baseMementoType.Accessibility !=
44 Metalama.Framework.Code.Accessibility.Protected)
45 {
46 builder.Diagnostics.Report(
47 DiagnosticDefinitions.MementoTypeMustBeProtected.WithArguments(
48 baseMementoType));
49 builder.SkipAspect();
50 return;
51 }
52
53 if (baseMementoType.IsSealed)
54 {
55 builder.Diagnostics.Report(
56 DiagnosticDefinitions.MementoTypeMustNotBeSealed.WithArguments(
57 baseMementoType));
58 builder.SkipAspect();
59 return;
60 }
61
62 baseMementoConstructor = baseMementoType.Constructors
63 .FirstOrDefault(c => c.Parameters.Count == 1 &&
64 c.Parameters[0].Type.Is(baseTypeDefinition));
65
66 if (baseMementoConstructor == null)
67 {
68 builder.Diagnostics.Report(
69 DiagnosticDefinitions.MementoTypeMustHaveConstructor
70 .WithArguments((baseMementoType, baseTypeDefinition)));
71 builder.SkipAspect();
72 return;
73 }
74
75 if (baseMementoConstructor.Accessibility is not (Metalama.Framework.Code.Accessibility
76 .Protected or Metalama.Framework.Code.Accessibility.Public))
77 {
78 builder.Diagnostics.Report(
79 DiagnosticDefinitions.MementoConstructorMustBePublicOrProtected
80 .WithArguments(baseMementoConstructor));
81 builder.SkipAspect();
82 return;
83 }
84 }
85 else
86 {
87 baseMementoType = null;
88 baseMementoConstructor = null;
89 }
90 //
91
92 //
93 // Introduce a new private nested class called Memento.
94 var mementoType =
95 builder.IntroduceClass(
96 "Memento",
97 whenExists: OverrideStrategy.New,
98 buildType: b =>
99 {
100 b.Accessibility = Metalama.Framework.Code.Accessibility.Protected;
101 b.BaseType = baseMementoType;
102 });
103 //
104
105 //
106 var originatorFieldsAndProperties = builder.Target.FieldsAndProperties
107 .Where(p => p is
108 {
109 IsStatic: false,
110 IsAutoPropertyOrField: true,
111 IsImplicitlyDeclared: false,
112 Writeability: Writeability.All
113 })
114 .Where(p =>
115 !p.Attributes.OfAttributeType(typeof(MementoIgnoreAttribute))
116 .Any());
117 //
118
119 //
120 // Introduce data properties to the Memento class for each field of the target class.
121 var propertyMap = new Dictionary<IFieldOrProperty, IProperty>();
122
123 foreach (var fieldOrProperty in originatorFieldsAndProperties)
124 {
125 var introducedField = mementoType.IntroduceProperty(
126 nameof(this.MementoProperty),
127 buildProperty: b =>
128 {
129 var trimmedName = fieldOrProperty.Name.TrimStart('_');
130
131 b.Name = trimmedName.Substring(0, 1).ToUpperInvariant() +
132 trimmedName.Substring(1);
133 b.Type = fieldOrProperty.Type;
134 });
135
136 propertyMap.Add(fieldOrProperty, introducedField.Declaration);
137 }
138 //
139
140 //
141 // Add a constructor to the Memento class that records the state of the originator.
142 mementoType.IntroduceConstructor(
143 nameof(this.MementoConstructorTemplate),
144 buildConstructor: b =>
145 {
146 var parameter = b.AddParameter("originator", builder.Target);
147
148 if (baseMementoConstructor != null)
149 {
150 b.InitializerKind = ConstructorInitializerKind.Base;
151 b.AddInitializerArgument(parameter);
152 }
153 });
154 //
155
156
157 //
158 // Implement the IMemento interface on the Memento class and add its members.
159 mementoType.ImplementInterface(typeof(IMemento),
160 whenExists: OverrideStrategy.Ignore);
161
162 var introducePropertyResult = mementoType.IntroduceProperty(
163 nameof(this.Originator),
164 whenExists: OverrideStrategy.Ignore);
165 var originatorProperty = introducePropertyResult.Outcome == AdviceOutcome.Default
166 ? introducePropertyResult.Declaration
167 : null;
168 //
169
170 // Implement the rest of the IOriginator interface and its members.
171 builder.ImplementInterface(typeof(IMementoable), OverrideStrategy.Ignore);
172
173 builder.IntroduceMethod(
174 nameof(this.SaveToMemento),
175 whenExists: OverrideStrategy.Override,
176 buildMethod: m => m.IsVirtual = !builder.Target.IsSealed,
177 args: new { mementoType = mementoType.Declaration });
178
179 builder.IntroduceMethod(
180 nameof(this.RestoreMemento),
181 buildMethod: m => m.IsVirtual = !builder.Target.IsSealed,
182 whenExists: OverrideStrategy.Override);
183
184 // Pass the state to the templates.
185 //
186 builder.Tags = new BuildAspectInfo(mementoType.Declaration, propertyMap,
187 originatorProperty);
188 //
189 }
190
191 [Template] public object? MementoProperty { get; }
192
193 [Template] public IMementoable? Originator { get; }
194
195 [Template]
196 public IMemento SaveToMemento()
197 {
198 //
199 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
200 //
201
202 // Invoke the constructor of the Memento class and pass this object as the originator.
203 return buildAspectInfo.MementoType.Constructors.Single()
204 .Invoke((IExpression)meta.This)!;
205 }
206
207 [Template]
208 public void RestoreMemento(IMemento memento)
209 {
210 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
211
212 // Call the base method if any.
213 meta.Proceed();
214
215 var typedMemento = meta.Cast(buildAspectInfo.MementoType, memento);
216
217 // Set fields of this instance to the values stored in the Memento.
218 foreach (var pair in buildAspectInfo.PropertyMap)
219 {
220 pair.Key.Value = pair.Value.With((IExpression)typedMemento).Value;
221 }
222 }
223
224 //
225 [Template]
226 public void MementoConstructorTemplate()
227 {
228 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
229
230 // Set the originator property and the data properties of the Memento.
231 if (buildAspectInfo.OriginatorProperty != null)
232 {
233 buildAspectInfo.OriginatorProperty.Value = meta.Target.Parameters[0];
234 }
235 else
236 {
237 // We are in a derived type and there is no need to assign the property.
238 }
239
240 foreach (var pair in buildAspectInfo.PropertyMap)
241 {
242 pair.Value.Value = pair.Key.With(meta.Target.Parameters[0]).Value;
243 }
244 }
245 //
246}