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.

27// Find the Builder nested type in the base type.
28INamedType? baseBuilderType = null;
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                sourceType.BaseType, baseTypeConstructors.Count)));
45        hasError = true;
46    }
47    else
48    {
49        baseConstructor = baseTypeConstructors[0];
50    }
51
52
53    var baseBuilderTypes =
54        sourceType.BaseType.Definition.Types.OfName("Builder").ToList();
55
56    switch (baseBuilderTypes.Count)
57    {
58        case 0:
59            builder.Diagnostics.Report(
60                BuilderDiagnosticDefinitions.BaseTypeMustContainABuilderType.WithArguments(
61                    sourceType.BaseType.Definition));
62            return;
63
64        case > 1:
65            builder.Diagnostics.Report(
66                BuilderDiagnosticDefinitions.BaseTypeCannotContainMoreThanOneBuilderType
67                    .WithArguments(sourceType.BaseType.Definition));
68            return;
69
70        default:
71            baseBuilderType = baseBuilderTypes[0];
72
73            // Check that we have exactly two constructors.
74            if (baseBuilderType.Constructors.Count != 2)
75            {
76                builder.Diagnostics.Report(
77                    BuilderDiagnosticDefinitions.BaseBuilderMustContainOneNonCopyConstructor
78                        .WithArguments((baseBuilderType,
79                            baseBuilderType.Constructors.Count)));
80                return;
81            }
82
83            // Find the copy constructor.
84            baseBuilderCopyConstructor = baseBuilderType.Constructors
85                .SingleOrDefault(c =>
86                    c.Parameters.Count == 1 &&
87                    c.Parameters[0].Type == sourceType.BaseType);
88
89            if (baseBuilderCopyConstructor == null)
90            {
91                builder.Diagnostics.Report(
92                    BuilderDiagnosticDefinitions.BaseBuilderMustContainCopyConstructor
93                        .WithArguments((baseBuilderType,
94                            sourceType.BaseType)));
95                return;
96            }
97
98            // The normal constructor is the other constructor.
99            baseBuilderConstructor =
100                baseBuilderType.Constructors.Single(c => c != baseBuilderCopyConstructor);
101
102            break;
103    }
104}
105
106if (hasError)
107{
108    return;
109}

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:

129// Introduce the Builder nested type.
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:

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

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

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.