Skip to content

Commit

Permalink
Fixer for MA0008 supports record struct (#448)
Browse files Browse the repository at this point in the history
  • Loading branch information
meziantou authored Jan 24, 2023
1 parent b206007 commit e1d03e3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/Meziantou.Analyzer/Rules/UseStructLayoutAttributeFixer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true);
if (nodeToFix == null)
if (nodeToFix == null || nodeToFix is not TypeDeclarationSyntax)
return;

context.RegisterCodeFix(
Expand Down Expand Up @@ -58,15 +58,13 @@ private static async Task<Document> Refactor(Document document, SyntaxNode nodeT
generator.TypeExpression(structLayoutAttribute, addImport: true),
new[]
{
generator.AttributeArgument(
generator.MemberAccessExpression(
generator.TypeExpression(layoutKindEnum, addImport: true),
layoutKind.ToString())),
generator.AttributeArgument(
generator.MemberAccessExpression(
generator.TypeExpression(layoutKindEnum, addImport: true),
layoutKind.ToString())),
});

var structNode = (StructDeclarationSyntax)nodeToFix;

editor.AddAttribute(structNode, attribute);
editor.AddAttribute(nodeToFix, attribute);
return editor.GetChangedDocument();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,20 @@ await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ValidateAsync();
}

#if CSHARP10_OR_GREATER
[Fact]
public async Task RecordStruct()
{
const string SourceCode = @"record struct [||]TypeName(int A, int B);";

const string CodeFix = @"[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Auto)]
record struct TypeName(int A, int B);";

await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ShouldFixCodeWith(CodeFix)
.ValidateAsync();
}
#endif
}

0 comments on commit e1d03e3

Please sign in to comment.