Skip to content

Wrong type of formatter for record with string keys #1797

Description

@dmitry-bym

Bug description

Source generator generates formatter with errors (unable to build) for record with one primary constructor. Only when string used as a key, with int everything works as expected.

Repro steps

just to use this to generate the code.

[MessagePackObject]
public record Record([property: Key("c")] string SomeId);

But it works if Key == Parameter name, btw ive seen that it was tested with similar record when key and name are the same

[MessagePackObject]
public record Record([property: Key("SomeId")] string SomeId);

Expected behavior

Formatter should create an object and put all args to constructor

Actual behavior

Formatter tries to create an object without parameters and then tries to set it.

Additional context

Investigated and have found that when it collect Member info it use string key as dictionary key

if (stringMembers.ContainsKey(stringKey!))
{
throw new MessagePackGeneratorResolveFailedException("key is duplicated, all members key must be unique." + " type: " + type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + " member:" + item.Name);
}
var member = new MemberSerializationInfo(true, isWritable, isReadable, hiddenIntKey++, stringKey!, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), customFormatterAttr?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
stringMembers.Add(member.StringKey, member);

then it creates lookup by this string key

var constructorLookupDictionary = stringMembers.ToLookup(x => x.Key, x => x, StringComparer.OrdinalIgnoreCase);

and then it tries to get member info using prop name

IEnumerable<KeyValuePair<string, MemberSerializationInfo>> hasKey = constructorLookupDictionary[item.Name];

It seems to me that the solution is to simply use the property name in the stringMembers dictionary.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions