Skip to content

Instantly share code, notes, and snippets.

@conartist6
Last active March 1, 2023 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conartist6/5ce190c77bc3f69293b0a11c41defb75 to your computer and use it in GitHub Desktop.
Save conartist6/5ce190c77bc3f69293b0a11c41defb75 to your computer and use it in GitHub Desktop.
cst-tokens grammar snippet
import { prod, tok, sym, Grammar } from '@/helpers';
new Grammar({
productions: {
// This version of ImportSpecifier uses helpers to be concise:
*ImportSpecifier() {
yield eat(prod`Identifier:imported`);
yield eatMatch(tok`Keyword:as`, prod`Identifier:local`);
},
// The helpers were being used to build up instructions/actions
// Here is what the same production looks like when the actions are written explicitly:
*ImportSpecifier() {
yield {
type: sym.eat,
value: {
type: sym.production,
value: { type: 'Identifier', property: 'imported' },
},
};
yield {
type: sym.eatMatch,
value: {
// passing multiple arguments to the eatMatch helper was actually creating an All production
type: sym.production,
value: {
type: sym.All,
// this production does not map to a real AST node
property: undefined,
props: {
matchables: [
{
type: sym.terminal,
value: { type: 'Keyword', value: 'as' },
},
{
type: sym.production,
value: { type: 'Identifier', property: 'local' },
},
],
},
},
},
};
},
*Identifier() {
yield eat(tok`Identifier`);
},
*[sym.All]({ matchables }) {
for (const matchable of matchables) {
yield eat(matchable);
}
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment