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
    • Syntactic Content Assist
    • Grammar Inheritance
    • Backtracking
    • Syntax Diagrams
    • RegExp Based Lexers
    • Position Tracking
    • Token Alternative Matches
    • Token Skipping
    • Token Categories
    • Token Grouping
    • Custom Token Patterns
    • Lexer Modes

Backtracking

Chevrotain supports backtracking to resolve ambiguities. Backtracking means fully trying an alternative instead of using a fixed token lookahead, this is similar to a DFS versus a BFS.

Backtracking is not automatic and must be explicitly invoked. This is because it is inefficient and is mutually exclusive with error recovery. It is strongly recommended to avoid using backtracking if possible.

Backtracking is implemented by using Gates

For example, given the following grammar which is not LL(K), as both the alternatives in "statement" have a potentially infinitely long common prefix.

statement:
   longRule1 |
   longRule2 |

longRule1:
   A+ B

longRule2:
   A+ C

We can resolve the ambiguity by using backtracking, effectively fully trying out the alternatives (in order) instead of trying to choose one using a limited token lookahead.

$.RULE("statement", () => {
  $.OR([
    {
      GATE: $.BACKTRACK($.longRule1),
      ALT: () => $.SUBRULE($.longRule1),
    },
    {
      GATE: $.BACKTRACK($.longRule2),
      ALT: () => $.SUBRULE($.longRule2),
    },
  ]);
});

See executable example for further details.

Edit this page on GitHub
Last Updated: 7/9/23, 12:55 AM
Contributors: Shahar Soel, bd82, Sergey Kostyrko
Prev
Grammar Inheritance
Next
Syntax Diagrams