3 ms·
I recently needed a custom expression language and using a Pratt-Parser to write the interpreter was a joy. https://github.com/taskcluster/json-e/blob/a0ab7701
by jopsen 9y ago
I recently needed a custom expression language and using a Pratt-Parser to write the interpreter was a joy.
https://github.com/taskcluster/json-e/blob/a0ab770157a5fdb5d2adfa5f211e57aefb7b800f/src/interpreter.js#L323-L357 https://github.com/taskcluster/json-e/blob/a0ab770157a5fdb5d...
I wrote up abstractions so you just declare token patterns, precedence ordering of tokens, and infix/prefix rules as mapping from token to function(token, ctx). Where ctx.attempt(...token)), ctx.require(...token) and ctx.parse(precedence) is all you need to implement almost anything.
I didn't get as far as to make it recursive and support multiple grammars. But I'm sure this concept can be made very elegant, without too many tricks.