Skip to content

Optimize grammar matcher by eliminating unnecessary value tracking#1925

Open
curtisman wants to merge 2 commits intomainfrom
value
Open

Optimize grammar matcher by eliminating unnecessary value tracking#1925
curtisman wants to merge 2 commits intomainfrom
value

Conversation

@curtisman
Copy link
Member

Summary

Optimize grammar matcher by eliminating unnecessary value tracking when values aren't needed. This improves performance by avoiding value capture operations for nested rules that don't bind to variables.

Changes

  • Introduced null as a distinct state for valueIds: Added null type to valueIds in MatchState and NestedMatchState to explicitly represent "no value tracking needed", distinct from undefined which means "value tracking active but no values captured yet"

  • Conditional value tracking for nested rules: When expanding nested rules, only enable value tracking if both conditions are met:

    • The parent rule is tracking values (valueIds !== null)
    • The current part has a variable to bind to (part.variable !== undefined)

    Otherwise, valueIds is set to null to skip all value operations

  • Guarded value operations: Added checks throughout to skip value capture operations when valueId is undefined or when valueIds is null:

    • captureWildcard(): Only calls addValueWithId() when valueId !== undefined
    • addValue(): Only calls addValueWithId() when valueId is returned
    • addValueId(): Returns early without creating value nodes when valueIds === null
    • finalizeState(): Skips value capture for wildcards when valueId === undefined
    • matchGrammarCompletion(): Only processes wildcard completions when valueId !== undefined
  • Safety validation: Added error check in finalizeMatch() to catch internal errors if valueIds is unexpectedly null

  • Code clarity: Improved comments and added explanatory notes about state restoration in nested rule matching

Impact

This optimization reduces unnecessary allocations and operations in the grammar matcher, particularly for complex grammars with multiple nested rules where many branches don't need value capture.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant