Skip to content

Csharp treesitter does not recognise primary constructors with base class constructor #587

@corneliuhoffman

Description

@corneliuhoffman

Describe the bug

C# 12 primary constructors with base class constructor calls fail to parse correctly. The tree-sitter-c-sharp
grammar's base_list rule only supports type names, not primary_constructor_base_type, causing classes like

class
   Foo(int x) : Base(x)  {}

to fail parsing.

To Reproduce

  1. Create a file test.cs:
  public class ClubsController_V1(IClubsService clubsService) : ApiControllerBase(clubsService)
  {
  }
  1. Run:
    bin/opengrep --dump-ast test.cs

  2. Observe parsing error - the base class call ApiControllerBase(clubsService) is not recognized.

Working case (simple primary constructor without base call):

  public class NamedItem(string name)
  {
      public string Name => name;
  }

This parses correctly.

Working case (regular inheritance without primary constructor):

  class MyClass : BaseClass
  {
  }

This also parses correctly.

Expected behavior

C# 12 primary constructors with base class constructor invocations should parse correctly, as this is valid C#
12 syntax documented at https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/primary-constructors

Root Cause

In grammar.js, the base_list rule (used for classes) only accepts types:
base_list: $ => seq(':', commaSep1($._type)),

But record_base (used for records) correctly supports primary_constructor_base_type:
record_base: $ => choice(
seq(':', commaSep1($._type_name)),
seq(':', $.primary_constructor_base_type, optional(seq(',', commaSep1($._type_name)))),
),

The fix would be to update base_list to also support primary_constructor_base_type.

Also confirmed same behaviour in Semgrep 1.150.0.

Metadata

Metadata

Assignees

No one assigned

    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