Ternary `cond ? [] : alt` misparsed as nullable array type when collection is empty · Issue #406 · tree-sitter/tree-sitter-c-sharp · GitHub
Skip to content

Ternary cond ? [] : alt misparsed as nullable array type when collection is empty #406

Description

@boukeversteegh

Summary

Empty collection expressions [] immediately after ? in conditional (ternary) expressions are misparsed. The parser interprets cond? as a nullable type and [] as an array rank specifier, instead of recognizing the ternary operator.

Reproduction

var x = condition ? [] : list;

Expected: Parsed as conditional expression with empty collection expression as consequence

Actual: Parsed as nullable array type declaration condition?[] followed by errors

Analysis

The grammar has an ambiguity: when it sees identifier?[], it can mean either:

  1. identifier ? [] : ... - ternary with empty collection expression
  2. identifier?[] - nullable array type (like int?[])

The grammar currently prefers interpretation #2, causing parse errors when : follows.

What Works

Notably, non-empty collection expressions in ternaries parse correctly:

// These all work:
var a = [];                    // standalone empty collection
var b = [1, 2, 3];             // collection with elements
var c = [..list];              // spread operator
var d = cond ? [1] : list;     // non-empty in ternary ✓

// This fails:
var e = cond ? [] : list;      // empty in ternary ✗

The issue is specifically the token sequence ? [] where [] is empty.

Real-World Impact

This pattern appears in production code:

var items = shouldClear ? [] : existingItems;

var result = new Response {
    Tags = includeAll 
        ? []  // Parse error here
        : FilterTags(input)
};

Possible Fix

The grammar may need disambiguation rules to prefer conditional_expression interpretation when ? is followed by [ ] : sequence.

Related

This is a specific edge case of the broader C# 12 collection expressions feature. See #401 for the general feature request, though most collection expression syntax already works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions