Chevrotain
Home
Features
Tutorial
Guide
FAQ
Changes
APIs
Playground
Benchmark
Discussions
GitHub
Home
Features
Tutorial
Guide
FAQ
Changes
APIs
Playground
Benchmark
Discussions
GitHub
  • Features

    • Blazing Fast
    • LL(K) Grammars
    • Separation of Grammar and Semantics
    • Easy Debugging
    • Fault Tolerance
    • Multiple Start Rules
    • Customizable Error Messages
    • Parameterized Rules
    • Gates
    • Grammar Inheritance
    • Backtracking
    • Syntax Diagrams
    • RegExp Based Lexers
    • Position Tracking
    • Token Alternative Matches
    • Token Skipping
    • Token Categories
    • Token Grouping
    • Custom Token Patterns
    • Lexer Modes

Gates

Chevrotain supports Gates on parsing DSL methods. Gates act as a type of guard condition that prevents an alternative from being taken. Gates are often used in combination with parametrized rules to represent multiple variants of the same parsing rule while avoiding code duplication.

For example:

// for (let x = 1; ...) — declaration allowed
// for (x + 1; ...)     — expression only
$.RULE("Statement", (allowDeclaration) => {
  $.OR([
    { GATE: () => allowDeclaration, ALT: () => $.SUBRULE($.Declaration) },
    { ALT: () => $.SUBRULE($.Expression) },
  ]);
});

Using the Look Ahead method is often helpful with the use of Gates to determine if a path should be followed or not, for example:

// foo(a, b, c)   - three arguments
// foo(a, b,)     - two arguments with trailing comma
$.RULE("ArgumentList", () => {
  $.SUBRULE($.Expression);
  $.MANY({
    // stop consuming arguments if the token after the comma is ")"
    GATE: () => $.LA(2).tokenType !== RParen,
    DEF: () => {
      $.CONSUME(Comma);
      $.SUBRULE1($.Expression);
    },
  });
  $.OPTION(() => $.CONSUME1(Comma)); // optional trailing comma
});

Here $.LA(2) peeks past the comma to check whether a closing parenthesis follows. If it does, the GATE prevents the MANY from consuming the trailing comma as the start of another argument, leaving it for the OPTION to handle instead.

See executable examples for further details:

  • Parametrized Rules — using Gates with parameterized rules to control grammar flow.
  • Predicate Lookahead — using Gates with external state to enable/disable alternatives.
  • Backtracking — using Gates with BACKTRACK to resolve ambiguous alternatives.
Edit this page on GitHub
Last Updated: 3/13/26, 9:18 PM
Contributors: Shahar Soel, bd82, Austin Turner, I060847, Gaurav
Prev
Parameterized Rules
Next
Grammar Inheritance