What is Generator Syntax?
Generator syntax provides an imperative-style way to write parsers using JavaScript/TypeScript generator functions. Instead of chaining methods, you useyield* to sequence parsers, making complex parsing logic more readable.
The parser() Function
Theparser() function (alias: Parser.gen()) creates a parser from a generator function:
Basic Usage
Simple Sequential Parsing
Discarding Results
Useyield* without assignment when you need to match something but don’t need its value:
vs Method Chaining
The same parser can be written using method chaining or generator syntax:Method Chaining
Generator Syntax
Conditional Parsing
Generator syntax makes conditional logic natural:Loops
You can use regular loops to repeatedly parse:Error Propagation
Errors automatically propagate through generator syntax:yield* expression fails, the entire parser fails immediately and subsequent yields are not executed.
Committing in Generators
Usecommit() to prevent backtracking after identifying the construct:
Real-World Example: JSON Parser
Here’s a complete JSON object parser using generator syntax:When to Use Generator Syntax
Use generator syntax when:- You have sequential parsing with multiple intermediate values
- Your parsing logic involves conditionals or loops
- You find imperative code more readable than method chains
- You need to perform transformations on intermediate results
- You’re building simple linear parsers
- You want to emphasize the functional composition
- The parser is short and straightforward