Open sandboxFocusImprove this doc

Builder example, step 2: Handling derived types

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.

Source Code
1using System.ComponentModel.DataAnnotations;
2
3namespace Metalama.Samples.Builder2.Tests.DerivedType;
4
5#pragma warning disable CS8618 //  Non-nullable property must contain a non-null value when exiting constructor.
6
7[GenerateBuilder]
8public class Article
9{
10    [Required] public string Url { get; }
11
12    [Required] public string Name { get; }







































13}
14























15public class WebArticle : Article
16{

























17    public string Keywords { get; }


















18}
Transformed Code
1using System.ComponentModel.DataAnnotations;
2
3namespace Metalama.Samples.Builder2.Tests.DerivedType;
4
5#pragma warning disable CS8618 //  Non-nullable property must contain a non-null value when exiting constructor.
6
7[GenerateBuilder]
8public class Article
9{
10    [Required] public string Url { get; }
11
12    [Required] 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("BUILDER01", Severity.Error,
13                "The type '{0}' cannot contain more than one nested type named 'Builder'.",
14                "The base type cannot contain more than one nested type named 'Builder'.");
15
16    public static readonly DiagnosticDefinition<INamedType> BaseTypeMustContainABuilderType
17        = new("BUILDER02", Severity.Error, "The type '{0}' must contain a 'Builder' nested type.",
18            "The base type cannot contain more than one builder type.");
19
20    public static readonly DiagnosticDefinition<(INamedType, string)> BaseBuilderMustContainProperty
21        = new("BUILDER03", Severity.Error,
22            "The '{0}' type must contain a property named '{1}'.",
23            "The base builder type must contain properties for all properties of the base built type.");
24
25    public static readonly DiagnosticDefinition<(INamedType, int)> BaseTypeMustContainOneConstructor
26        = new("BUILDER04", Severity.Error,
27            "The '{0}' type must contain a single constructor but has {1}.",
28            "The base type must contain a single constructor.");
29
30    public static readonly DiagnosticDefinition<(IConstructor, string)>
31        BaseTypeConstructorHasUnexpectedParameter
32            = new("BUILDER05", Severity.Error,
33                "The '{1}' parameter of '{0}' cannot be mapped to a property.",
34                "A parameter of the base type cannot be mapped to a property.");
35
36    public static readonly DiagnosticDefinition<(INamedType BuilderType, INamedType SourceType)>
37        BaseBuilderMustContainCopyConstructor
38            = new("BUILDER06", Severity.Error,
39                "The '{0}' type must contain a constructor, called the copy constructor, with a single parameter of type '{1}'.",
40                "The base type must contain a copy constructor.");
41
42    public static readonly DiagnosticDefinition<(INamedType, int)>
43        BaseBuilderMustContainOneNonCopyConstructor
44            = new("BUILDER07", Severity.Error,
45                "The '{0}' type must contain exactly two constructors but has {1}.",
46                "The base builder type must contain exactly two constructors.");
47}

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.

28// Find the Builder nested type in the base type.
29INamedType? baseBuilderType = null;
30IConstructor? baseConstructor = null,
31    baseBuilderConstructor = null,
32    baseBuilderCopyConstructor = null;
33
34if (sourceType.BaseType != null && sourceType.BaseType.SpecialType != SpecialType.Object)
35{
36    // We need to filter parameters to work around a bug where the Constructors collection
37    // contains the implicit constructor.
38    var baseTypeConstructors =
39        sourceType.BaseType.Constructors.Where(c => c.Parameters.Count > 0).ToList();
40
41    if (baseTypeConstructors.Count != 1)
42    {
43        builder.Diagnostics.Report(
44            BuilderDiagnosticDefinitions.BaseTypeMustContainOneConstructor.WithArguments((
45                sourceType.BaseType, baseTypeConstructors.Count)));
46        hasError = true;
47    }
48    else
49    {
50        baseConstructor = baseTypeConstructors[0];
51    }
52
53
54    var baseBuilderTypes =
55        sourceType.BaseType.Definition.Types.OfName("Builder").ToList();
56
57    switch (baseBuilderTypes.Count)
58    {
59        case 0:
60            builder.Diagnostics.Report(
61                BuilderDiagnosticDefinitions.BaseTypeMustContainABuilderType.WithArguments(
62                    sourceType.BaseType.Definition));
63            return;
64
65        case > 1:
66            builder.Diagnostics.Report(
67                BuilderDiagnosticDefinitions.BaseTypeCannotContainMoreThanOneBuilderType
68                    .WithArguments(sourceType.BaseType.Definition));
69            return;
70
71        default:
72            baseBuilderType = baseBuilderTypes[0];
73
74            // Check that we have exactly two constructors.
75            if (baseBuilderType.Constructors.Count != 2)
76            {
77                builder.Diagnostics.Report(
78                    BuilderDiagnosticDefinitions.BaseBuilderMustContainOneNonCopyConstructor
79                        .WithArguments((baseBuilderType,
80                            baseBuilderType.Constructors.Count)));
81                return;
82            }
83
84            // Find the copy constructor.
85            baseBuilderCopyConstructor = baseBuilderType.Constructors
86                .SingleOrDefault(c =>
87                    c.Parameters.Count == 1 &&
88                    c.Parameters[0].Type == sourceType.BaseType);
89
90            if (baseBuilderCopyConstructor == null)
91            {
92                builder.Diagnostics.Report(
93                    BuilderDiagnosticDefinitions.BaseBuilderMustContainCopyConstructor
94                        .WithArguments((baseBuilderType,
95                            sourceType.BaseType)));
96                return;
97            }
98
99            // The normal constructor is the other constructor.
100            baseBuilderConstructor =
101                baseBuilderType.Constructors.Single(c => c != baseBuilderCopyConstructor);
102
103            break;
104    }
105}
106
107if (hasError)
108{
109    return;
110}

Step 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:

130var builderType = builder.IntroduceClass( 
131    "Builder",
132    OverrideStrategy.New,
133    t =>
134    {
135        t.Accessibility = Accessibility.Public;
136        t.BaseType = baseBuilderType;
137        t.IsSealed = sourceType.IsSealed;
138    }); 

Note 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:

114// Create a list of PropertyMapping items for all properties that we want to build using the Builder.
115var properties = sourceType.AllProperties.Where(
116        p => p.Writeability != Writeability.None &&
117             !p.IsStatic)
118    .Select(
119        p =>
120        {
121            var isRequired = p.Attributes.OfAttributeType(typeof(RequiredAttribute))
122                .Any();
123            var isInherited = p.DeclaringType != sourceType;
124            return new PropertyMapping(p, isRequired, isInherited);
125        })
126    .ToList();

The 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.

142// Add builder properties and update the mapping.  
143foreach (var property in properties)
144{
145    if (property.IsInherited)
146    {
147        // For properties of the base type, find the matching property.
148        var baseProperty =
149            baseBuilderType!.AllProperties.OfName(property.SourceProperty.Name)
150                .SingleOrDefault();
151
152        if (baseProperty == null)
153        {
154            builder.Diagnostics.Report(
155                BuilderDiagnosticDefinitions.BaseBuilderMustContainProperty.WithArguments((
156                    baseBuilderType, property.SourceProperty.Name)));
157            hasError = true;
158        }
159        else
160        {
161            property.BuilderProperty = baseProperty;
162        }
163    }
164    else
165    {
166        // For properties of the current type, introduce a new property.
167        property.BuilderProperty =
168            builderType.IntroduceAutomaticProperty(
169                    property.SourceProperty.Name,
170                    property.SourceProperty.Type,
171                    IntroductionScope.Instance,
172                    buildProperty: p =>
173                    {
174                        p.Accessibility = Accessibility.Public;
175                        p.InitializerExpression =
176                            property.SourceProperty.InitializerExpression;
177                    })
178                .Declaration;
179    }
180} 

Note 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:

188// Add a builder constructor accepting the required properties and update the mapping.
189builderType.IntroduceConstructor(
190    nameof(this.BuilderConstructorTemplate),
191    buildConstructor: c =>
192    {
193        c.Accessibility = Accessibility.Public;
194
195        // Adding parameters.
196        foreach (var property in properties.Where(m => m.IsRequired))
197        {
198            var parameter = c.AddParameter(
199                NameHelper.ToParameterName(property.SourceProperty.Name),
200                property.SourceProperty.Type);
201
202            property.BuilderConstructorParameterIndex = parameter.Index;
203        }
204
205        // Calling the base constructor.
206        if (baseBuilderConstructor != null)
207        {
208            c.InitializerKind = ConstructorInitializerKind.Base;
209
210            foreach (var baseConstructorParameter in baseBuilderConstructor.Parameters)
211            {
212                var thisParameter =
213                    c.Parameters.SingleOrDefault(p =>
214                        p.Name == baseConstructorParameter.Name);
215
216                if (thisParameter != null)
217                {
218                    c.AddInitializerArgument(thisParameter);
219                }
220                else
221                {
222                    builder.Diagnostics.Report(
223                        BuilderDiagnosticDefinitions
224                            .BaseTypeConstructorHasUnexpectedParameter.WithArguments((
225                                baseBuilderConstructor,
226                                baseConstructorParameter.Name)));
227                    hasError = true;
228                }
229            }
230        }
231    });

The 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.