dotnet/roslyn

CSharpSyntaxGenerator doesn't appear to simplify when generating an attribute on a local function

オープン

#52,039 opened on 2021/03/22

 (5 件のコメント) (0 件のリアクション) (0 人の担当者)C# (4,257 件のフォーク)batch import
Area-CompilersConcept-Continuous ImprovementFeature - Local Functionshelp wanted

Repository metrics

Stars
 (20,414 個のスター)
PR merge metrics
 (平均マージ 6d 17h) (30d で 256 merged PRs)

説明

I wrote the following code to add attributes to particular declarations

var editor = new SyntaxEditor (root, document.Project.Solution.Workspace);
var generator = editor.Generator;

var semanticModel = await document.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
if (semanticModel is null) {
	return document;
}
var methodSymbol = (IMethodSymbol) semanticModel.GetDeclaredSymbol (methodDecl);
var name = semanticModel.GetSymbolInfo (targetNode).Symbol?.Name;
SyntaxNode[] attrArgs;
if (string.IsNullOrEmpty (name) || HasPublicAccessibility (methodSymbol)) {
	attrArgs = Array.Empty<SyntaxNode> ();
} else {
	attrArgs = new[] { generator.LiteralExpression ($"calls {name}") };
}

var newAttribute = generator
	.Attribute (generator.TypeExpression (requiresUnreferencedCodeSymbol), attrArgs)
	.WithAdditionalAnnotations (
		Simplifier.Annotation,
		Simplifier.AddImportsAnnotation);

editor.AddAttribute (methodDecl, newAttribute);

return document.WithSyntaxRoot (editor.GetChangedRoot ());

This generates an attribute correctly for local functions, but the type name is always fully qualified. Declaration forms that are not local functions appear to work correctly.

コントリビューターガイド