Last active
December 4, 2022 21:35
-
-
Save conartist6/175e525042ad502fdc6abd6b7f941238 to your computer and use it in GitHub Desktop.
Parser spitballing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Grammar } from '@cst-tokens/grammar'; | |
import { objectEntries } from '@cst-tokens/helpers/iterable'; | |
import { eat, match } from '@cst-tokens/helpers/commands'; | |
import { capture, ref, PN } from '@cst-tokens/helpers/shorthand'; | |
// 2-+2+-2 | |
/* | |
$capture = '2'; | |
$node = { type: 'Digit', value: $caputure }; | |
$capture = '-'; | |
$node = replace({ type: 'BinaryExpression', left: $node, op: $capture, right: null }) | |
$capture = '+'; | |
$node = push({ type: 'UnaryExpression', op: $capture, expr: null }); | |
$capture = '2'; | |
$node = push({ type: 'Digit', value: $capture }); | |
$node = pop(); | |
$node.expr = $poppedNode; | |
$node = pop(); | |
$node.right = $poppedNode; | |
$capture = '+'; | |
$node = replace({ type: 'BinaryExpression', left: $node, op: $capture, right: null }) | |
*/ | |
// Productions that start with refs are candidates for replace operations | |
// ...but only when the stack is empty! | |
export const grammar = new Grammar({ | |
aliases: objectEntries({ | |
Expression: ['BinaryExpression', 'UnaryExpression', 'Digit'] | |
}), | |
productions: objectEntries({ | |
*Digit() { | |
yield* eat(DigitDescriptor(capture`value`)); | |
}, | |
*Array() { | |
yield* eat(PN`[`); | |
let sep = true; | |
while(sep && !(yield* match(PN`]`))) { | |
yield* eat(ref`values:[Expression]`); // Type can be an alias too | |
sep = !!(yield* eatMatch(',')); | |
} | |
yield* eat(PN`]`); | |
}, | |
*UnaryExpression() { | |
yield* capture('op', eat(PN(/[+-]/y))); | |
yield* eat(ref`expr:Expression`); | |
}, | |
*BinaryExpression() { | |
yield* eat(ref`left:Expression`); | |
yield* capture('op', eat(PN(/[+-]/y))); | |
yield* eat(ref`right:Expression`); | |
} | |
}), | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment