Skip to content

Improve NormalizeWhitespace for nested fixed/using statements without blocks #61518

@elinor-fung

Description

@elinor-fung

Version Used:
Microsoft.CodeAnalysis.CSharp version 4.2.0

Steps to Reproduce:

Call NormalizeWhitespace() on code with nested fixed or using statements without a { } block between.

string code = @"
public unsafe void M1(string s1, string s2, string s3)
{
    fixed (char* ptr1 = s1)
    fixed (char* ptr2 = s2)
    fixed (char* ptr3 = s3)
    {
    }
}

public void M2(string path)
{
    using (FileStream fs = File.Create(path))
    using (StreamWriter sw = new StreamWriter(fs))
    {
    }
}";
Console.WriteLine(ParseSyntaxTree(code).GetRoot().NormalizeWhitespace().ToFullString());

Expected Behavior:

Output:

public unsafe void M1(string s1, string s2, string s3)
{
    fixed (char* ptr1 = s1)
    fixed (char* ptr2 = s2)
    fixed (char* ptr3 = s3)
    {
    }
}

public void M2(string path)
{
    using (FileStream fs = File.Create(path))
    using (StreamWriter sw = new StreamWriter(fs))
    {
    }
}

Actual Behavior:

Output:

public unsafe void M1(string s1, string s2, string s3)
{
    fixed (char* ptr1 = s1)
        fixed (char* ptr2 = s2)
            fixed (char* ptr3 = s3)
            {
            }
}

public void M2(string path)
{
    using (FileStream fs = File.Create(path))
        using (StreamWriter sw = new StreamWriter(fs))
        {
        }
}

Additional Notes:

With the usage of NormalizeWhitespace for source generators, this results in some awkwardly formatted generated code.

Auto-formatting code like this in Visual Studio stacks the statements without indentation like in the expected behaviour.

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions