Skip to content

SyntaxGenerator.AddAttributes does not add assembly: target if there are already assembly attributes in the file #60399

@jkoritzinsky

Description

@jkoritzinsky

Version Used: 4.2.0-2.22128.1

Steps to Reproduce:

  1. Get a SyntaxGenerator instance for a C# workspace (VB probably has the same bug) and name it gen.
  2. Run the following code snippet:
var root = gen.CompliationUnit();
root = gen.AddAttributes(root, gen.Attribute(gen.DottedName("Namespace.FirstAttribute")));
root = gen.AddAttributes(root, gen.Attribute(gen.DottedName("Namespace.SecondAttribute")));

Expected Behavior: Both attribute lists for FirstAttribute and SecondAttribute have the assembly: target specifier.

Actual Behavior: Only FirstAttribute has the target specifier.

This is bug is due to the fact that the path where CSharpSyntaxGenerator adds the specifier is only called when no attributes currently exist on the parent syntax node. In the provided code snippet, the WithAttributeLists method adds the target specifier; however, it is only called when there are no existing attributes.

private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes)
{
var newAttributes = AsAttributeLists(attributes);
var existingAttributes = this.GetAttributes(declaration);
if (index >= 0 && index < existingAttributes.Count)
{
return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes);
}
else if (existingAttributes.Count > 0)
{
return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes);
}
else
{
var lists = declaration.GetAttributeLists();
var newList = lists.AddRange(newAttributes);
return WithAttributeLists(declaration, newList);
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-IDEuntriagedIssues and PRs which have not yet been triaged by a lead

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions