AMP fixup initializers -> proper defaults

This commit is contained in:
honzapatCZ 2026-06-27 23:01:00 +02:00
parent c8ed747aa3
commit 1d2a08aeed

View File

@ -243,6 +243,17 @@ namespace AutoMapProperty
{ {
INamedTypeSymbol dataTypename = attr?.ConstructorArguments[1].Value as INamedTypeSymbol; INamedTypeSymbol dataTypename = attr?.ConstructorArguments[1].Value as INamedTypeSymbol;
mem = mem.WithType(SyntaxFactory.ParseTypeName(dataTypename.ToDisplayString() + " ")); mem = mem.WithType(SyntaxFactory.ParseTypeName(dataTypename.ToDisplayString() + " "));
var oldConcreteType = GetConcreteType(propSymbol.Type);
var newConcreteType = GetConcreteType(dataTypename);
if (mem.Initializer != null && !SymbolEqualityComparer.Default.Equals(oldConcreteType, newConcreteType))
{
var rewriter = new TypeReplacer(oldConcreteType.Name, newConcreteType.Name);
var newInitializer = (EqualsValueClauseSyntax)rewriter.Visit(mem.Initializer);
mem = mem.WithInitializer(newInitializer);
}
typeSymbol = dataTypename; typeSymbol = dataTypename;
} }
@ -262,7 +273,7 @@ namespace AutoMapProperty
}))); })));
//if property has initializer or expression body, remove them //if property has initializer or expression body, remove them
mem = mem.WithInitializer(null); //mem = mem.WithInitializer(null);
mem = mem.WithExpressionBody(null); mem = mem.WithExpressionBody(null);
//if property is abstract remove the abstract modifier //if property is abstract remove the abstract modifier
@ -272,7 +283,14 @@ namespace AutoMapProperty
} }
//now the has trailing semicolon, which is wrong //now the has trailing semicolon, which is wrong
if (mem.Initializer == null)
{
mem = mem.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); mem = mem.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None));
}
else
{
mem = mem.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
}
//if we dont want to generate converter //if we dont want to generate converter
bool customFrom = false; bool customFrom = false;
@ -1035,6 +1053,27 @@ namespace ").Append(classToGenerate.Namespace).Append(@"
return sb.ToString(); return sb.ToString();
} }
private class TypeReplacer : CSharpSyntaxRewriter
{
private readonly string _oldTypeName;
private readonly string _newTypeName;
public TypeReplacer(string oldTypeName, string newTypeName)
{
_oldTypeName = oldTypeName;
_newTypeName = newTypeName;
}
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
{
if (node.Identifier.ValueText == _oldTypeName)
{
return SyntaxFactory.IdentifierName(_newTypeName).WithTriviaFrom(node);
}
return base.VisitIdentifierName(node);
}
}
} }
public static class Utils public static class Utils