Skip to content

fix: Emitter generates redundant length checks in Parse/TryParse methods #51

@DrBarnabus

Description

@DrBarnabus

Description

The source generator emits redundant length validation in Parse and TryParse methods when a partition/sort key consists of a single value part (no split required). Two independent code generation paths — the global WriteLengthCheck guard and the per-property checks in WriteParsePropertiesImplementation — both emit length validation without coordinating, resulting in dead code.

Scenario 1: Duplicate exact-length check before Guid parsing

In the RepeatingPropertyCompositeKey scenario (UserTagKey), Parse validates partitionKey.Length != 36 at the top-level guard, then emits the identical partitionKey.Length != 36 check again before calling Guid.TryParseExact. The second check is always false at that point. Same pattern in TryParse.

Scenario 2: Minimum-length guard followed by dead zero-length check

In the InvariantCultureDisabled scenario (BasicPrimaryKey), Parse emits an early sortKey.Length < 1 guard that throws FormatException, then later checks sortKey.Length == 0 — which can never be true since the first guard already threw. The same pattern appears in TryParse.

Not actually redundant (corrected from original report)

The original report also listed the per-part Guid length check in BasicPrimaryKey for the partition key (partitionKey.Length < 40 followed by partitionKey[partitionKeyPartRanges[0]].Length != 38). This is not redundant — after splitting a multi-part key, an individual range can be shorter than expected even though the total input met the minimum length. The per-part check is valid in this case.

Reproduction

Visible in snapshot baselines:

  • SourceGeneratorSnapshotTests.RepeatingPropertyCompositeKey_SourceOutput#UnitTests.UserTagKey.g.verified.cs
    • Parse: line 167 (partitionKey.Length != 36) duplicated at line 178
    • TryParse: line 218 (partitionKey.Length != 36) duplicated at line 229
  • SourceGeneratorSnapshotTests.InvariantCultureDisabled_SourceOutput#UnitTests.BasicPrimaryKey.g.verified.cs
    • Parse: line 112 (sortKey.Length < 1) makes line 126 (sortKey.Length == 0) dead
    • TryParse: line 152 (sortKey.Length < 1) makes line 166 (sortKey.Length == 0) dead

Expected behaviour

The emitter should avoid emitting duplicate/redundant length checks. Each validation should appear exactly once in the generated code path. Per-property length checks should be suppressed when the input is unsplit and the global guard already covers the same condition.

Discovered via

Snapshot testing added in #48 — these are pre-existing generator issues, not regressions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions