Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Oct 16, 2025

Fixes #43145

This PR adds a regression test to verify that the compiler no longer crashes when encountering a syntax error in an indexer declaration, specifically when using This (with a capital T) instead of this.

Background

The original issue reported that the following code would cause a compiler crash with a System.InvalidOperationException when calling GetDiagnostics():

struct S
{
    public bool This[int t] { get { return false; } }
}

The crash occurred deep in the symbol analysis code, specifically in SourceMemberFieldSymbolFromDeclarator.get_HasPointerType() during struct circularity checking.

Changes

This PR adds a test CompilerShouldNotCrashOnSyntaxErrorInIndexerDeclaration to IndexerTests.cs that:

  • Uses the problematic code from the original issue
  • Calls GetDiagnostics() to verify the compiler doesn't crash
  • Verifies all expected diagnostic errors are produced correctly
  • Uses a raw-string literal for the source code as per C# 11 conventions
  • Includes a [WorkItem] attribute linking to issue Compiler crash with syntax error in indexer declaration #43145

The test demonstrates that the compiler now handles this syntax error gracefully, producing appropriate diagnostic messages (12 errors/warnings about invalid syntax) instead of crashing. This helps document that the issue has been resolved and prevents future regressions.

Testing

All 76 tests in IndexerTests pass, including the new regression test.

Original prompt

This section details on the original issue you should resolve

<issue_title>Compiler crash with syntax error in indexer declaration</issue_title>
<issue_description>The following proposed unit test crashes the compiler:

        [Fact]
        public void Test()
        {
            var source = @"
struct S
{
    public bool This[int t] { get { return false; } }
}
";
            var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
            compilation.GetDiagnostics();
        }

The result of running it is

 Microsoft.CodeAnalysis.CSharp.UnitTests.PatternMatchingTests3.Test
   Source: PatternMatchingTests3.cs line 3313
   Duration: 839 ms

  Message: 
    System.AggregateException : One or more errors occurred.
    ---- System.InvalidOperationException : 
    
  Stack Trace: 
    Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
    Task.Wait()
    Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
    Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body)
    SourceNamespaceSymbol.ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) line 56
    SourceModuleSymbol.ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) line 261
    SourceAssemblySymbol.ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) line 911
    CSharpCompilation.GetSourceDeclarationDiagnostics(SyntaxTree syntaxTree, Nullable`1 filterSpanWithinTree, Func`4 locationFilterOpt, CancellationToken cancellationToken) line 2508
    CSharpCompilation.GetDiagnostics(CompilationStage stage, Boolean includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken) line 2395
    CSharpCompilation.GetDiagnostics(CompilationStage stage, Boolean includeEarlierStages, CancellationToken cancellationToken) line 2316
    CSharpCompilation.GetDiagnostics(CancellationToken cancellationToken) line 2310
    PatternMatchingTests3.Test() line 3322
    ----- Inner Stack Trace -----
    ThrowingTraceListener.Fail(String message, String detailMessage) line 26
    TraceListener.Fail(String message)
    TraceInternal.Fail(String message)
    Debug.Assert(Boolean condition)
    SourceMemberFieldSymbolFromDeclarator.get_HasPointerType() line 376
    BaseTypeAnalysis.NonPointerType(FieldSymbol field) line 154
    SourceMemberContainerTypeSymbol.HasStructCircularity(DiagnosticBag diagnostics) line 1930
    SourceMemberContainerTypeSymbol.CheckStructCircularity(DiagnosticBag diagnostics) line 1911
    SourceMemberContainerTypeSymbol.get_KnownCircularStruct() line 1890
    SourceMemberContainerTypeSymbol.AfterMembersChecks(DiagnosticBag diagnostics) line 1418
    SourceMemberContainerTypeSymbol.ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) line 516
    Symbol.ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken) line 775
    <>c__DisplayClass49_1.<ForceComplete>b__0(Int32 i) line 61
    <>c__DisplayClass6_0`1.<WithCurrentUICulture>b__0(T param) line 171
    <>c__DisplayClass17_0`1.<ForWorker>b__1()
    Task.InnerInvoke()
    Task.InnerInvokeWithArg(Task childTask)
    <>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object <p0>)

</issue_description>

<agent_instructions>@copilot i don't reproduce the issue reported in the original post. Can you add the test listed there (in a good location, with a good name)? Also, use a raw-string literal for the source code sample, and add a WorkItem attribute to the test. We can use this to then close out this issue demonstrating it's not a problem current.</agent_instructions>

Comments on the Issue (you are @copilot in this section)

Fixes #43145


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

…eclaration

Co-authored-by: CyrusNajmabadi <4564579+CyrusNajmabadi@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix compiler crash with syntax error in indexer declaration Add regression test for compiler crash with syntax error in indexer declaration Oct 16, 2025
Copilot AI requested a review from CyrusNajmabadi October 16, 2025 20:08
Copilot finished work on behalf of CyrusNajmabadi October 16, 2025 20:08
@CyrusNajmabadi CyrusNajmabadi marked this pull request as ready for review October 20, 2025 17:17
@CyrusNajmabadi CyrusNajmabadi requested a review from a team as a code owner October 20, 2025 17:17
@CyrusNajmabadi
Copy link
Member

@dotnet/roslyn-compiler ptal

@CyrusNajmabadi CyrusNajmabadi merged commit 7198c8f into main Oct 23, 2025
24 checks passed
@CyrusNajmabadi CyrusNajmabadi deleted the copilot/fix-compiler-crash-indexer-declaration branch October 23, 2025 13:30
@dotnet-policy-service dotnet-policy-service bot added this to the Next milestone Oct 23, 2025
333fred added a commit to 333fred/roslyn that referenced this pull request Oct 24, 2025
* upstream/main: (332 commits)
  Cache lambdas in analyzer driver (dotnet#80759)
  Add information for NuGet package version 4.14 (dotnet#80870)
  Add missing search keywords to VB Advanced options page
  Fix IDE0031 false positive when preprocessor directives are used in if statements (dotnet#80878)
  Use core compiler on netfx hosts with toolset package (dotnet#80631)
  Make string concat assert more precise (dotnet#80619)
  Extensions: address some diagnostic quality issues (dotnet#80827)
  Add note on traversal order for bound nodes (dotnet#80872)
  Ensure that locals at the top level of a constructor have the same safe-context as parameters (dotnet#80807)
  Fix handling of SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes option for non-native symbol implementations (dotnet#80826)
  Update src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs
  Add IsValidContainingStatement check to prevent collection initializers in using declarations
  Add back old DocumentSpan constructor (dotnet#80864)
  Add tests verifying pointer types in type parameters require unsafe context (dotnet#80776)
  Add regression test for Interlocked.Exchange with nullable types (dotnet#80796)
  Add regression test for ParseAttributeArgumentList with invalid input (fixes dotnet#8699) (dotnet#80705)
  Add regression test for compiler crash with syntax error in indexer declaration (dotnet#80772)
  Add runtime NullReferenceException validation to foreach null iteration tests (dotnet#80839)
  Update MicrosoftBuildTasksCoreVersionForMetrics to 17.11.48 (dotnet#80812)
  Mark CS4009 error as a "build only" error. (dotnet#80698)
  ...
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 crash with syntax error in indexer declaration

3 participants