tsPEG uses discriminated unions to distinguish between different AST node types. Every AST node has a kind field containing a value from the ASTKinds enum. You can use this field to safely narrow types when processing the parse tree.
Kind Naming Conventions:
- Simple rules (
Rule := name='regex'): ASTKinds.Rule. - Choice rules (
Rule := choiceA='regexA' | choiceB='regexB'): ASTKinds.Rule_1, ASTKinds.Rule_2, etc., depending on which branch matched. - Sub-rules (
Rule := sub={ name='regex' }): ASTKinds.Rule_$N where N is the index of the sub-rule. - Direct references: Rules that simply reference another rule (e.g.,
rule := otherrule) inherit the kind of the referenced rule.
Example usage:
import { Choice, Parser, ASTKinds } from "./parser";
function makeChoice(c: Choice) {
if(c.kind === ASTKinds.Word) {
console.log('Matched word ', c.word)
} else if(c.kind === ASTKinds.Int) {
console.log('Matched int ', c.val)
}
}
import { Choice, Parser, ASTKinds } from "./parser";
function makeChoice(c: Choice) {
if(c.kind === ASTKinds.Word) {
console.log('Matched word ', c.word)
} else {
console.log('Matched int ', c.val)
}
}