Repository navigation
Description
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
CodeBlocker/CodeBlocker/Scopes.cs
Lines 182 to 207 in 21ac04c
| 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.
Activity