繁体   English   中英

使用 Roslyn 生成格式良好的语法

[英]Generating well-formatted syntax with Roslyn

我正在使用 Roslyn 来修改 C# 文件的语法。 使用 CSharpSyntaxRewriter,可以很容易地在语法树中查找和替换节点。 但是,生成的代码非常难看,甚至不会在所有情况下都解析,因为我创建的语法节点(使用 SyntaxFactory)甚至缺少最少量的空白琐事。 Roslyn 是否提供了一些基本的格式化功能来避免这种情况,还是我必须手动向我创建的每个节点添加琐事?

是的 - 可以使用Microsoft.CodeAnalysis.Formatting.Formatter

var formattedResult = Formatter.Format(syntaxNode, workspace);

您可以在 Roslyn 源代码中看到不同 Roslyn 格式化程序的用法: http : //sourceroslyn.io/#Microsoft.CodeAnalysis.Workspaces/CodeActions/CodeAction.cs,267

internal static async Task<Document> CleanupDocumentAsync(
        Document document, CancellationToken cancellationToken)
{
    if (document.SupportsSyntaxTree)
    {
        document = await ImportAdder.AddImportsFromSymbolAnnotationAsync(
        document, Simplifier.AddImportsAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        // format any node with explicit formatter annotation
        document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        // format any elastic whitespace
        document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false);
     }

     return document;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM