Skip to content

PragmaScope with a list of empty warning IDs writes #pragma warning disable , (CS1072) instead of nothing #166

Closed

Description

@matt-edmondson

What happens

#97 and #98 made PragmaScope do nothing when it has no warnings to suppress, using a check on the joined string with string.IsNullOrWhiteSpace(warnings). The IEnumerable<string> constructor joins its entries with ", " before that check runs. A list whose entries are all empty therefore joins to ", ", which is not whitespace, and both directives are written.

The code is at

public PragmaScope(CodeBlocker codeBlocker, IEnumerable<string> warnings)
: this(codeBlocker, string.Join(", ", warnings ?? []))
{
}
private static void Begin(CodeBlocker codeBlocker, string warnings)
{
Ensure.NotNull(codeBlocker);
if (string.IsNullOrWhiteSpace(warnings))
{
return;
}
codeBlocker.WriteLine($"#pragma warning disable {warnings}");
}
private static void End(CodeBlocker codeBlocker, string warnings)
{
Ensure.NotNull(codeBlocker);
if (string.IsNullOrWhiteSpace(warnings))
{
return;
}
codeBlocker.WriteLine($"#pragma warning restore {warnings}");
}

Repro

Run against main at 21ac04c, and parsed with Roslyn:

using (new PragmaScope(cb, new[] { "", "" }))
{
	cb.WriteLine("int x = 1;");
}

Output:

#pragma warning disable , 
int x = 1;
#pragma warning restore , 

Roslyn reports warning CS1072: Expected identifier or numeric literal on each directive. A build that treats warnings as errors fails, and nothing is suppressed. With a single empty entry (new[] { "" }) the scope correctly does nothing. A mixed list such as { "CS0168", "" } writes CS0168, with a trailing comma.

Why it matters

Generators commonly build this list from data, such as the IDs a member needs suppressed. Some of those IDs can come out empty. An empty list is meant to be a no-op since #97. A list of empties should behave the same way, not break the build of the generated file.

This is separate from #154, which covers an empty DirectiveScope condition and line breaks inside directive arguments.

Suggested fix

In the IEnumerable<string> constructor, drop null and whitespace entries before joining, for example with warnings.Where(w => !string.IsNullOrWhiteSpace(w)), and trim each one.

Acceptance criteria

  • new PragmaScope(cb, new[] { "", "" }) writes no directives.
  • new PragmaScope(cb, new[] { "CS0168", "" }) writes #pragma warning disable CS0168, with no trailing comma.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions