Changed attribute builder to derive from correct class, also added method to pass base class parameters using string refs. Regenerated the files

This commit is contained in:
Samuele Lorefice
2025-03-06 17:37:55 +01:00
parent a784eed61d
commit 02aa7db319
6 changed files with 46 additions and 18 deletions

View File

@@ -1,12 +1,14 @@
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace CodeGenerator {
// ReSharper disable always BitwiseOperatorOnEnumWithoutFlags
public class AttributeBuilder {
private CodeTypeDeclaration _attrDecl = new();
private CodeTypeDeclaration _attrDecl;
private List<(Type, string)> _fields = new();
@@ -28,9 +30,11 @@ namespace CodeGenerator {
/// Creates a new instance of the <see cref="AttributeBuilder"/> class.
/// </summary>
public AttributeBuilder() {
_attrDecl.IsClass = true;
_attrDecl.Attributes = MemberAttributes.Public;
_attrDecl.BaseTypes.Add(typeof(Attribute));
_attrDecl = new() {
IsClass = true,
Attributes = MemberAttributes.Public,
BaseTypes = { typeof(Attribute) }
};
}
/// <summary>
@@ -47,7 +51,11 @@ namespace CodeGenerator {
/// </summary>
/// <remarks>clears the internal metadata for fields and properties, also reinstantiates the <see cref="CodeTypeDeclaration"/> internal instance</remarks>
public AttributeBuilder New() {
_attrDecl = new CodeTypeDeclaration();
_attrDecl = new() {
IsClass = true,
Attributes = MemberAttributes.Public,
BaseTypes = { typeof(Attribute) }
};
_fields.Clear();
_properties.Clear();
return this;
@@ -57,11 +65,8 @@ namespace CodeGenerator {
/// Sets the base type of the attribute.
/// </summary>
/// <param name="baseType">Fully qualified name from which this is going to be derived</param>
public AttributeBuilder DeriveFromClass(string baseType) {
if (_attrDecl.BaseTypes.Count == 0)
_attrDecl.BaseTypes.Add(typeof(Attribute));
else
_attrDecl.BaseTypes[0] = new(baseType);
public AttributeBuilder DeriveFromClass(string baseType = "System.Attribute") {
_attrDecl.BaseTypes[0] = new(baseType);
return this;
}
@@ -199,6 +204,21 @@ namespace CodeGenerator {
});
return this;
}
//TODO: tyhis should use something more robust and less error prone than just strings
/// <summary>
/// Adds parameters to be passed to the base class
/// </summary>
/// <param name="parameters">Array of strings which reference the params</param>
/// <exception cref="InvalidOperationException"> thrown when no constructor is defined yet.</exception>
public AttributeBuilder AddBaseConstructorParams(string[] parameters) {
var ctor = _attrDecl.Members.OfType<CodeConstructor>().FirstOrDefault();
if (ctor == null) throw new InvalidOperationException("There is no constructor defined yet.");
foreach (var param in parameters) {
ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(param));
}
return this;
}
/// <summary>
/// Builds the <see cref="CodeTypeDeclaration"/> instance.