JasperFx / JasperFx.CodeGeneration

Code Generation & Runtime Compilation Chicanery for .Net
MIT License
9 stars 7 forks source link

Injected fields with the same name as a base class arguments leads to failed compilation #7

Closed mrnustik closed 5 months ago

mrnustik commented 5 months ago

Hi, as a part of the investigation for this Marten issue I have found a problem with the way CodeGeneration currently works with duplicities of InjectedFields of the GeneratedType class. When you add a field with the same name as a base class argument, it leads to a compilation error.

I have tried to fix the issue myself, but I have found out it is quite a complicated one because I could not determine which of the InjectedField instances is the one that is used as a ctor argument.

Test to replicate the issue

public class Bug_xxx_InjectedFieldNamedAsBaseCtor
{
    [Fact]
    public void ArrangeFrames_WhereInjectedFieldHasTheSameNameAsBaseClass_ShouldUseThatNameInBaseCall()
    {
        // Arrange
        var generatedAssembly = GeneratedAssembly.Empty();
        generatedAssembly.ReferenceAssembly(typeof(BaseClass).Assembly);
        var generatedType = generatedAssembly.AddType("ChildClass", typeof(BaseClass));
        generatedType.AllInjectedFields.Add(new InjectedField(typeof(string), "dependency"));

        // Act
        generatedType.ArrangeFrames();

        // Assert
        generatedType.AllInjectedFields[0].CtorArgDeclaration.ShouldBe("int __dependency1");
        generatedType.AllInjectedFields[1].CtorArgDeclaration.ShouldBe("string __dependency2");

        // This fails because the ctor argument was not renamed
        generatedType.BaseConstructorArguments[0].Usage.ShouldBe("__dependency1");
    }

    public class BaseClass
    {
        private readonly int dependency;

        public BaseClass(int dependency)
        {
            this.dependency = dependency;
        }
    }
}