In the previous article, we assumed the type hierarchy was flat. Now, we will consider type inheritance, handling cases where the base type already has a builder.
Our objective is to generate code like in the following example, where the WebArticle class derives from Article. Notice how WebArticle.Builder derives from Article.Builder and how WebArticle constructors call the base constructors of Article.
1using System.ComponentModel.DataAnnotations;
2
3namespace Metalama.Samples.Builder2.Tests.DerivedType;
4
5[GenerateBuilder]
6public class Article
7{
8 [Required]
9 public string Url { get; }
10
11 [Required]
12 public string Name { get; }
13}
14
15public class WebArticle : Article
16{
17 public string Keywords { get; }
18}
1using System.ComponentModel.DataAnnotations;
2
3namespace Metalama.Samples.Builder2.Tests.DerivedType;
4
5[GenerateBuilder]
6public class Article
7{
8 [Required]
9 public string Url { get; }
10
11 [Required]
12 public string Name { get; }
13
14 protected Article(string url, string name)
15 {
16 Url = url;
17 Name = name;
18 }
19
20 public virtual Builder ToBuilder()
21 {
22 return new Builder(this);
23 }
24
25 public class Builder
26 {
27 public Builder(string url, string name)
28 {
29 Url = url;
30 Name = name;
31 }
32
33 protected internal Builder(Article source)
34 {
35 Url = source.Url;
36 Name = source.Name;
37 }
38
39 private string _name = default!;
40
41 public string Name
42 {
43 get
44 {
45 return _name;
46 }
47
48 set
49 {
50 _name = value;
51 }
52 }
53
54 private string _url = default!;
55
56 public string Url
57 {
58 get
59 {
60 return _url;
61 }
62
63 set
64 {
65 _url = value;
66 }
67 }
68
69 public Article Build()
70 {
71 var instance = new Article(Url, Name);
72 return instance;
73 }
74 }
75}
76
77public class WebArticle : Article
78{
79 public string Keywords { get; }
80
81 protected WebArticle(string keywords, string url, string name) : base(url, name)
82 {
83 Keywords = keywords;
84 }
85
86 public override Builder ToBuilder()
87 {
88 return new Builder(this);
89 }
90
91 public new class Builder : Article.Builder
92 {
93 public Builder(string url, string name) : base(url, name)
94 {
95 }
96
97 protected internal Builder(WebArticle source) : base(source)
98 {
99 Keywords = source.Keywords;
100 }
101
102 private string _keywords = default!;
103
104 public string Keywords
105 {
106 get
107 {
108 return _keywords;
109 }
110
111 set
112 {
113 _keywords = value;
114 }
115 }
116
117 public new WebArticle Build()
118 {
119 var instance = new WebArticle(Keywords, Url, Name);
120 return instance;
121 }
122 }
123}
Step 1. Preparing to report errors
A general best practice when implementing patterns using an aspect is to consider the case where the pattern has been implemented manually on the base type and to report errors when hand-written code does not adhere to the conventions we have set for the patterns. For instance, the previous article set some rules regarding the generation of constructors. In this article, the aspect will assume that the base types (both the base source type and the base builder type) define the expected constructors. Otherwise, we will report an error. It's always better for the user than throwing an exception.
Before reporting any error, we must declare a DiagnosticDefinition static field for each type of error.
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Diagnostics;
4
5namespace Metalama.Samples.Builder2;
6
7[CompileTime]
8internal static class BuilderDiagnosticDefinitions
9{
10 public static readonly DiagnosticDefinition<INamedType>
11 BaseTypeCannotContainMoreThanOneBuilderType
12 = new(
13 "BUILDER01",
14 Severity.Error,
15 "The type '{0}' cannot contain more than one nested type named 'Builder'.",
16 "The base type cannot contain more than one nested type named 'Builder'." );
17
18 public static readonly DiagnosticDefinition<INamedType> BaseTypeMustContainABuilderType
19 = new(
20 "BUILDER02",
21 Severity.Error,
22 "The type '{0}' must contain a 'Builder' nested type.",
23 "The base type cannot contain more than one builder type." );
24
25 public static readonly DiagnosticDefinition<(INamedType, string)> BaseBuilderMustContainProperty
26 = new(
27 "BUILDER03",
28 Severity.Error,
29 "The '{0}' type must contain a property named '{1}'.",
30 "The base builder type must contain properties for all properties of the base built type." );
31
32 public static readonly DiagnosticDefinition<(INamedType, int)> BaseTypeMustContainOneConstructor
33 = new(
34 "BUILDER04",
35 Severity.Error,
36 "The '{0}' type must contain a single constructor but has {1}.",
37 "The base type must contain a single constructor." );
38
39 public static readonly DiagnosticDefinition<(IConstructor, string)>
40 BaseTypeConstructorHasUnexpectedParameter
41 = new(
42 "BUILDER05",
43 Severity.Error,
44 "The '{1}' parameter of '{0}' cannot be mapped to a property.",
45 "A parameter of the base type cannot be mapped to a property." );
46
47 public static readonly DiagnosticDefinition<(INamedType BuilderType, INamedType SourceType)>
48 BaseBuilderMustContainCopyConstructor
49 = new(
50 "BUILDER06",
51 Severity.Error,
52 "The '{0}' type must contain a constructor, called the copy constructor, with a single parameter of type '{1}'.",
53 "The base type must contain a copy constructor." );
54
55 public static readonly DiagnosticDefinition<(INamedType, int)>
56 BaseBuilderMustContainOneNonCopyConstructor
57 = new(
58 "BUILDER07",
59 Severity.Error,
60 "The '{0}' type must contain exactly two constructors but has {1}.",
61 "The base builder type must contain exactly two constructors." );
62}
For details, see Reporting and suppressing diagnostics.
Step 2. Finding the base type and its members
We can now inspect the base type and look for artifacts we will need: the constructors, the Builder type, and the constructors of the Builder type. If we don't find them, we report an error and quit.
26// Find the Builder nested type in the base type.
27INamedType? baseBuilderType = null;
28
29IConstructor? baseConstructor = null,
30 baseBuilderConstructor = null,
31 baseBuilderCopyConstructor = null;
32
33if ( sourceType.BaseType != null && sourceType.BaseType.SpecialType != SpecialType.Object )
34{
35 // We need to filter parameters to work around a bug where the Constructors collection
36 // contains the implicit constructor.
37 var baseTypeConstructors =
38 sourceType.BaseType.Constructors.Where( c => c.Parameters.Count > 0 ).ToList();
39
40 if ( baseTypeConstructors.Count != 1 )
41 {
42 builder.Diagnostics.Report(
43 BuilderDiagnosticDefinitions.BaseTypeMustContainOneConstructor.WithArguments(
44 (
45 sourceType.BaseType, baseTypeConstructors.Count) ) );
46
47 hasError = true;
48 }
49 else
50 {
51 baseConstructor = baseTypeConstructors[0];
52 }
53
54 var baseBuilderTypes =
55 sourceType.BaseType.Types.OfName( "Builder" ).ToList();
56
57 switch ( baseBuilderTypes.Count )
58 {
59 case 0:
60 builder.Diagnostics.Report(
61 BuilderDiagnosticDefinitions.BaseTypeMustContainABuilderType.WithArguments(
62 sourceType.BaseType ) );
63
64 return;
65
66 case > 1:
67 builder.Diagnostics.Report(
68 BuilderDiagnosticDefinitions.BaseTypeCannotContainMoreThanOneBuilderType
69 .WithArguments( sourceType.BaseType ) );
70
71 return;
72
73 default:
74 baseBuilderType = baseBuilderTypes[0];
75
76 // Check that we have exactly two constructors.
77 if ( baseBuilderType.Constructors.Count != 2 )
78 {
79 builder.Diagnostics.Report(
80 BuilderDiagnosticDefinitions.BaseBuilderMustContainOneNonCopyConstructor
81 .WithArguments(
82 (baseBuilderType,
83 baseBuilderType.Constructors.Count) ) );
84
85 return;
86 }
87
88 // Find the copy constructor.
89 baseBuilderCopyConstructor = baseBuilderType.Constructors
90 .SingleOrDefault( c =>
91 c.Parameters.Count == 1 &&
92 c.Parameters[0].Type.Equals( sourceType.BaseType ) );
93
94 if ( baseBuilderCopyConstructor == null )
95 {
96 builder.Diagnostics.Report(
97 BuilderDiagnosticDefinitions.BaseBuilderMustContainCopyConstructor
98 .WithArguments(
99 (baseBuilderType,
100 sourceType.BaseType) ) );
101
102 return;
103 }
104
105 // The normal constructor is the other constructor.
106 baseBuilderConstructor =
107 baseBuilderType.Constructors.Single( c => c != baseBuilderCopyConstructor );
108
109 break;
110 }
111}
112
113if ( hasError )
114{
115 return;
116}
117Step 3. Creating the Builder type
Now that we have found the artifacts in the base type, we can update the rest of the BuildAspect method to use them.
In the snippet that creates the Builder type, we specify the Builder of the base type as the base type of the new Builder:
138// Introduce the Builder nested type.
139var builderType = builder.IntroduceClass(
140 "Builder",
141 OverrideStrategy.New,
142 t =>
143 {
144 t.Accessibility = Accessibility.Public;
145 t.BaseType = baseBuilderType;
146 t.IsSealed = sourceType.IsSealed;
147 } );
148Note that we set the whenExist parameter to OverrideStrategy.New. This means we will generate a new class if the base type already contains a Builder class.
Step 4. Mapping properties
To discover properties, we now use the AllProperties collection which, unlike Properties, includes properties defined by base types. We added an IsInherited property into the PropertyMapping field.
Here is how we updated the code that discovers properties:
121// Create a list of PropertyMapping items for all properties that we want to build using the Builder.
122var properties = sourceType.AllProperties.Where( p => p.Writeability != Writeability.None &&
123 !p.IsStatic )
124 .Select( p =>
125 {
126 var isRequired = p.Attributes.OfAttributeType( typeof(RequiredAttribute) )
127 .Any();
128
129 var isInherited = !p.DeclaringType.Equals( sourceType );
130
131 return new PropertyMapping( p, isRequired, isInherited );
132 } )
133 .ToList();
134The code that creates properties must be updated too. We don't have to create builder properties for properties of the base type since these properties should already be defined in the base builder type. If we don't find such a property, we report an error.
152// Add builder properties and update the mapping.
153foreach ( var property in properties )
154{
155 if ( property.IsInherited )
156 {
157 // For properties of the base type, find the matching property.
158 var baseProperty =
159 baseBuilderType!.AllProperties.OfName( property.SourceProperty.Name )
160 .SingleOrDefault();
161
162 if ( baseProperty == null )
163 {
164 builder.Diagnostics.Report(
165 BuilderDiagnosticDefinitions.BaseBuilderMustContainProperty.WithArguments(
166 (
167 baseBuilderType, property.SourceProperty.Name) ) );
168
169 hasError = true;
170 }
171 else
172 {
173 property.BuilderProperty = baseProperty;
174 }
175 }
176 else
177 {
178 // For properties of the current type, introduce a new property.
179 property.BuilderProperty =
180 builderType.IntroduceAutomaticProperty(
181 property.SourceProperty.Name,
182 property.SourceProperty.Type,
183 IntroductionScope.Instance,
184 buildProperty: p =>
185 {
186 p.Accessibility = Accessibility.Public;
187
188 p.InitializerExpression =
189 property.SourceProperty.InitializerExpression;
190 } )
191 .Declaration;
192 }
193}
194Note that we could do more validation, such as checking the property type and its visibility.
Step 5. Updating constructors
All constructors must be updated to call the base constructor. Let's demonstrate the technique with the public constructor of the Builder class.
Here is the updated code:
203// Add a builder constructor accepting the required properties and update the mapping.
204builderType.IntroduceConstructor(
205 nameof(this.BuilderConstructorTemplate),
206 buildConstructor: c =>
207 {
208 c.Accessibility = Accessibility.Public;
209
210 // Adding parameters.
211 foreach ( var property in properties.Where( m => m.IsRequired ) )
212 {
213 var parameter = c.AddParameter(
214 NameHelper.ToParameterName( property.SourceProperty.Name ),
215 property.SourceProperty.Type );
216
217 property.BuilderConstructorParameterIndex = parameter.Index;
218 }
219
220 // Calling the base constructor.
221 if ( baseBuilderConstructor != null )
222 {
223 c.InitializerKind = ConstructorInitializerKind.Base;
224
225 foreach ( var baseConstructorParameter in baseBuilderConstructor.Parameters )
226 {
227 var thisParameter =
228 c.Parameters.SingleOrDefault( p =>
229 p.Name == baseConstructorParameter.Name );
230
231 if ( thisParameter != null )
232 {
233 c.AddInitializerArgument( thisParameter );
234 }
235 else
236 {
237 builder.Diagnostics.Report(
238 BuilderDiagnosticDefinitions
239 .BaseTypeConstructorHasUnexpectedParameter.WithArguments(
240 (
241 baseBuilderConstructor,
242 baseConstructorParameter.Name) ) );
243
244 hasError = true;
245 }
246 }
247 }
248 } );
249The first part of the logic is unchanged: we add a parameter for each required property, including inherited ones. Then, when we have a base class, we call the base constructor. First, we set the InitializerKind of the new constructor to Base. Then, for each parameter of the base constructor, we find the corresponding parameter in the new constructor, and we call the <xrefMMetalama.Framework.Code.DeclarationBuilders.IConstructorBuilder.AddInitializerArgument*> method to add an argument to the call to the base() constructor. If we don't find this parameter, we report an error.
Step 6. Other changes
Other parts of the BuildAspect method and most templates must be updated to take inherited properties into account. Please refer to the source code of the example on GitHub for details (see the links at the top of this article).
Conclusion
Handling type inheritance is generally not a trivial task because you have to consider the possibility that the base type does not define the expected declarations. Reporting errors is always better than failing with an exception, and certainly better than generating invalid code.
In the next article, we will see how to handle properties whose type is an immutable collection.