Skip to content

Disallow ignored directives in disabled regions - #85206

Closed
jjonescz wants to merge 8 commits into
dotnet:mainfrom
jjonescz:85203-ignored-in-disabled
Closed

jjonescz wants to merge 8 commits into
dotnet:mainfrom
jjonescz:85203-ignored-in-disabled

Conversation

@jjonescz

@jjonescz jjonescz commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Fixes #85203.
Speclet change: dotnet/csharplang#10329

Microsoft Reviewers: Open in CodeFlow

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

It changes compiler diagnostics for previously accepted source, and CI remains in progress.

Pull request overview

Fixes file-based apps incorrectly honoring #: directives inside disabled conditional regions.

Changes:

  • Diagnoses inactive #: directives in file-based programs.
  • Adds coverage for disabled and conditional regions across parse modes.
File summaries
File Description
DirectiveParser.cs Validates inactive file-based directives.
IgnoredDirectiveParsingTests.cs Adds regression and branch coverage.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0
  • Review effort level: Balanced

@jjonescz
jjonescz marked this pull request as ready for review September 8, 2026 14:40
@jjonescz
jjonescz requested a review from a team as a code owner September 8, 2026 14:40
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI review requested due to automatic review settings September 8, 2026 14:57
@jjonescz
jjonescz force-pushed the 85203-ignored-in-disabled branch from c1b4e7c to 58560a8 Compare September 8, 2026 14:57
@jjonescz
jjonescz requested a review from a team as a code owner September 8, 2026 14:57
@jjonescz
jjonescz force-pushed the 85203-ignored-in-disabled branch from 58560a8 to c1b4e7c Compare September 8, 2026 14:58
@jjonescz
jjonescz removed the request for review from a team September 8, 2026 15:01
@jjonescz jjonescz removed the VSCode label Sep 8, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Compiler diagnostic behavior changes and CI validation remains in progress.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

{
if (isActive)
// Tooling may not know the conditional compilation symbols when reading file-based directives.
if (isActive || lexer.Options.FileBasedProgram)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (isActive || lexer.Options.FileBasedProgram)

If this is a regression from #78158, why the fix isn't a simple revert (i.e. simple removal of the if)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because I think we can both fix the regression and preserve the intent of that PR.

The intent of that PR was to avoid errors in situations like this outside file-based apps:

#if false

System.Console.WriteLine("""
    #:sdk test
    """);

#endif

I've preserved that fix in this PR. Plus this PR disallows something like this in file-based apps:

#if false
#:package System.Threading.RateLimiting@10.0.11
#endif

On the other hand, I can see this being a bit confusing (basically the same syntax structure works differently in vs out of file-based apps).

But simply reverting would also introduce a larger breaking change. This PR does not introduce a breaking change in my opinion, since the behavior change needs a feature flag, and the resulting file-based app would never work in dotnet run file.cs end-to-end scenarios anyway.

@jjonescz jjonescz Sep 9, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the other hand, I can see this being a bit confusing (basically the same syntax structure works differently in vs out of file-based apps).

I think I can simplify the logic though to avoid this as well.

If we go with this change, I will clarify the speclet.

var source = """
#if X
#:a
#elif true

@AlekseyTs AlekseyTs Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#elif true

I think it will be good to test the following scenario:

            #if X
            #:a
            #else
            #:c
            #endif
``` #Closed

{
if (isActive)
// Tooling may not know the conditional compilation symbols when reading file-based directives.
if (isActive || lexer.Options.FileBasedProgram)

@AlekseyTs AlekseyTs Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

|| lexer.Options.FileBasedProgram

Are we testing effect of this condition? #Closed

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the added test InDisabledRegion tests with and without the feature flag FileBasedProgram which directly affects this condition.

@AlekseyTs

Copy link
Copy Markdown
Contributor

Done with review pass (commit 1)

Copilot AI review requested due to automatic review settings September 9, 2026 11:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The parser change reintroduces a false-positive diagnostic for raw-string content in disabled file-based code.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Balanced

@jjonescz
jjonescz marked this pull request as draft September 9, 2026 12:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Two diagnostic assertions must verify the active branch’s source location.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

src/Compilers/CSharp/Test/Syntax/Parsing/IgnoredDirectiveParsingTests.cs:583

  • This assertion does not verify that the non-file-based-program diagnostic is attached to the active branch: both candidate directives have the same squiggled text, and no location is required. Add the conditional location so the defineX combinations detect an active/inactive mix-up.
                // error CS9298: '#:' directives can be only used in file-based programs ('-features:FileBasedProgram')
                // #:a
                Diagnostic(ErrorCode.ERR_PPIgnoredNeedsFileBasedProgram, ":"),
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

private DirectiveTriviaSyntax ParseDefineOrUndefDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive, bool isFollowingToken)
{
if (isFollowingToken)
if (isFollowingToken && isActive)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

&& isActive

Are we testing effect of this added condition?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, there are preexisting tests, e.g., PreprocessorTests.TestDefineInIfExclusionAfterFirstToken.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, there are preexisting tests, e.g.,

I do not see any preexisting test observing a behavior change. I also do not see any new test added to target this code path. At the same time, I assume, the new condition is added for a reason. What is it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a behavior change. The added condition is needed because the semantics of isFollowingToken flag changed - we are now propagating it through disabled regions where previously it was always false in disabled regions.

.. commonDiagnostics,
// error CS9298: '#:' directives can be only used in file-based programs ('-features:FileBasedProgram')
// #:b
Diagnostic(ErrorCode.ERR_PPIgnoredNeedsFileBasedProgram, ":"),

@AlekseyTs AlekseyTs Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostic(ErrorCode.ERR_PPIgnoredNeedsFileBasedProgram, ":")

While, perhaps, it is not the primary goal of the test to verify which branch is considered to be active, I think it is our goal to verify which directive gets the error. One way to achieve that is to assert error's location. Note that the comment immediately above this line makes things very confusing, because there is no "#:b" in the source above. To strengthen the test and make it clearer, consider asserting diagnostics for defineX and !defineX scenarios separately, including location and quoting proper source line for the errors. #Closed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an alternative we could stop reporting ERR_PPIgnoredNeedsFileBasedProgram for directives that get ERR_PPIgnoredFollowsIf. One might say that reporting ERR_PPIgnoredNeedsFileBasedProgram doesn't really help a user in such scenarios because, whether the feature is enabled or not, the directive is going to be in a wrong position. If a user is fixing errors one by one, it is a waste of time to fix this error for the scenario. If we do that, the set of errors in this test will be the same for all combinations.

.. commonDiagnostics,
// error CS9298: '#:' directives can be only used in file-based programs ('-features:FileBasedProgram')
// #:a
Diagnostic(ErrorCode.ERR_PPIgnoredNeedsFileBasedProgram, ":"),

@AlekseyTs AlekseyTs Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostic(ErrorCode.ERR_PPIgnoredNeedsFileBasedProgram, ":"),

Similar comment as for the test above. #Closed

@AlekseyTs

AlekseyTs commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

I find the current logic very confusing and, perhaps, not making sense.
For example, no error reported for this code:

System.Console.WriteLine("Hello World!");
class C2;

#if false
#:package System.Threading.RateLimiting@10.0.11
#endif

class C1;

But there is an error for this:

#if false
// error CS9299: '#:' directives cannot be after '#if' directive
#:package System.Threading.RateLimiting@10.0.11
#endif

System.Console.WriteLine("Hello World!");
class C2;
class C1;

Not reporting CS9299 in disabled regions across the board would make sense to me. Always reporting it would make sense to me. But not the current behavior. Perhaps clearly specified rules in language spec terms could help.

@AlekseyTs

Copy link
Copy Markdown
Contributor

Done with review pass (commit 6)

@jjonescz
jjonescz marked this pull request as draft September 10, 2026 09:43
@jjonescz

Copy link
Copy Markdown
Member Author

Perhaps clearly specified rules in language spec terms could help.

Opened dotnet/csharplang#10329.

I agree it's unfortunate the rules a bit more complicated, but I feel like the benefit is worth that.

@jjonescz
jjonescz marked this pull request as ready for review September 10, 2026 11:46
Copilot AI review requested due to automatic review settings September 10, 2026 11:46
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The shipped-language breaking change needs documentation and completed language/compatibility review.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

tree.GetDiagnostics().Verify(
// (3,6): error CS9299: '#:' directives cannot be after '#if' directive
// #:sdk test
Diagnostic(ErrorCode.ERR_PPIgnoredFollowsIf, ":").WithLocation(3, 6));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostic(ErrorCode.ERR_PPIgnoredFollowsIf, ":").WithLocation(3, 6));

I do not think this behavior makes sense. There is no error for:

            System.Console.WriteLine();

            #if false
            System.Console.WriteLine("""
                #:sdk test
                """);
            #endif

or for:

            System.Console.WriteLine("""
                #:sdk test
                """);

But there is an error for:

            #if false
            System.Console.WriteLine("""
                #:sdk test
                """);
            #endif

            System.Console.WriteLine();

Effectively, we are reporting an error for syntactically valid code in disabled region.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Effectively, we are reporting an error for syntactically valid code in disabled region.

It's not a syntactically valid code. Disabled regions are not parsed as normal code. The lexer doesn't see a method call, a raw string, etc. It only checks for directives in disabled regions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, the combinatorial nature of the test makes it very hard to comprehend what is the actual user experience. Please split the unit test so that a reader wouldn't have to compile code in his/her head in order to understand what scenario is being tested.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a syntactically valid code.

It is. Remove conditional compilation and see.

Disabled regions are not parsed as normal code. The lexer doesn't see a method call, a raw string, etc. It only checks for directives in disabled regions.

That is not a reason to treat code as not syntactically valid.

@jjonescz jjonescz Sep 10, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean this is a preexisting issue. Consider:

#if false
string code = """
    #define
    """;
#endif

There is an error in the disabled region. Change the condition to #if true and it compiles fine.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean this is a preexisting issue.

It is pre-existing for #define, and I do not consider this as a correct or useful behavior.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I generally agree with that; that's why I fixed and want to preserve the fix for #78157 in the first place. I guess this is the same discussion as below: #85206 (comment)

tree.GetDiagnostics().Verify(
// (4,2): error CS9297: '#:' directives cannot be after first token in file
// #:package System.Threading.RateLimiting@10.0.11
Diagnostic(ErrorCode.ERR_PPIgnoredFollowsToken, ":").WithLocation(4, 2));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostic(ErrorCode.ERR_PPIgnoredFollowsToken, ":").WithLocation(4, 2));

Similar feedback about complexity to catch a difference between scenarios that produce different result as for InRawString_01_Condition. Please split the test so that differences are clear.

options = options.WithFeature(FeatureName);
}

SyntaxFactory.ParseSyntaxTree(source, options).GetDiagnostics().Verify();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SyntaxFactory.ParseSyntaxTree(source, options).GetDiagnostics().Verify();

Again, it is not clear to me why this scenario shouldn't have an error and the following should have an error.

#if false
System.Console.WriteLine("""
    #:sdk test
    """);
#endif

System.Console.WriteLine(); 

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does my other reply #85206 (comment) answer this or is this a different question?

@AlekseyTs

Copy link
Copy Markdown
Contributor

I agree it's unfortunate the rules a bit more complicated, but I feel like the benefit is worth that.

I guess I am having trouble to understand who or what benefits from the error in a disabled region. I assume the benefit from not reporting an error is the fact that an existing valid code isn't broken.

@jjonescz

Copy link
Copy Markdown
Member Author

I assume the benefit from not reporting an error is the fact that an existing valid code isn't broken.

That is one benefit, yes.

Another is this situation. Imagine you have tests like

void Test()
{
    string code = """
        #:directive
        """;
}

Everything compiles fine. Then you wrap them in for example #if NET:

#if NET
void Test()
{
    string code = """
        #:directive
        """;
}
#endif

Suddenly, when NET is not defined, the file does not compile anymore. This is a pre-existing issue for other directives, but we fixed that at least for the new #: directives. See the discussion under issue #78157 for more details.

@AlekseyTs

Copy link
Copy Markdown
Contributor

@jjonescz

I guess I am having trouble to understand who or what benefits from the error in a disabled region.

@jjonescz

Copy link
Copy Markdown
Member Author

I guess I am having trouble to understand who or what benefits from the error in a disabled region.

Hm, I see. Well, it feels useful to tell the user that the directive in an #if like

#if NEVER_DEFINED
#:directive
#endif

Does not have any effect, especially since we are lexing directives in disabled regions anyway.

But I think I understand your point now and I'm fine with just not reporting errors in disabled regions for these directives.

@AlekseyTs

Copy link
Copy Markdown
Contributor

Well, it feels useful to tell the user that the directive in an #if like ... Does not have any effect

I do not think it is that useful, especially given that it becomes a source of all kind of troubles.

especially since we are lexing directives in disabled regions anyway.

Are we? We are doing something, but that isn't proper lexing. Otherwise, we wouldn't have #78157. If we were doing proper lexing for that scenario, we wouldn't see any directive inside the disabled region for the scenario.

@AlekseyTs

Copy link
Copy Markdown
Contributor

@jjonescz I added a comment to the issue you are trying to address in this PR

@AlekseyTs

Copy link
Copy Markdown
Contributor

Done with review pass (commit 8)

@jjonescz jjonescz closed this Sep 11, 2026
@jjonescz
jjonescz deleted the 85203-ignored-in-disabled branch September 11, 2026 10:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compiler ignores preprocessor directives surrounding MSBuild directives in file-based apps

3 participants