no-context / moo

Optimised tokenizer/lexer generator! 🐄 Uses /y for performance. Moo.
BSD 3-Clause "New" or "Revised" License
814 stars 65 forks source link

How to compose/re-use rules? #150

Closed mspoulsen closed 3 years ago

mspoulsen commented 3 years ago

Hi,

In jison you can compose rules from other rules like this:

AMOUNT                     \d+([\d,]*\d+)?(.\d+)?
CHIPS                     '('\s*(\W)({AMOUNT})\s+\w+\s*')'

Is there a way to do this in moo so I can re-use complicated rules like in this case amount?

Thanks!

nathan commented 3 years ago

You can just write a template function that interpolates RegExps, e.g.:

function reg(strings, ...pieces) {
  return new RegExp(strings.raw.map((r, i) => r + (pieces[i] === undefined ? '' : '(?:' + pieces[i].source + ')')).join(''))
}
const AMOUNT = /\d+([\d,]*\d+)?(.\d+)?/
const CHIPS = reg`\(\s*(\W)(${AMOUNT})\s+\w+\s*\)`