2 ms·
yacc allows you to specify operator precedence declaratively (but not otherwise context sensitive). IIRC it's uses a shift-reduce algorithm. For a small yet rea
by hyperpallium 9y ago
yacc allows you to specify operator precedence declaratively (but not otherwise context sensitive). IIRC it's uses a shift-reduce algorithm. For a small yet real, working and useful example of parsing with yacc, have a look at jq (json query).
In practice, a common long-term pattern for project is to start with yacc (because it's close to what you want: defining the grammar, then automatically parsing with it), but then switch to a hand-written recursive descent grammar later, primarily for more informative error messages (trying to do that in yacc quickly becomes unbelievably intricate and complex, requiring changes in the grammar definition to expose where the error needs to be detected, in part because yacc doesn't parse a grammar the way a user thinks about it. I think this is intrinsic to your ideal of automatically parsing with the definition, because error reporting has a different structure). A special-purpose custom parser can also be optimized for better time amd space performance.
Much of those 20,000-30,000 LoC are for error reporting and efficiency.
Recursive descent parsers are related to the formalism, and there are standard theoretical transformations to put them into a working form (e.g. removing left-recursion)... but I have to admit, it's all pretty hacky and ad hoc, just specifying the way, not the why, and so not the elegant automatic translation you'd like.
I wpuld recommend you study parsers, an online course, or maybe read the excellent intro chapter of the second ed of the Aho et al Compilers book (aka the "dragon" book) which actually builds a simple compiler, but your ideals will only be disappointed.
tl;dr you're right, but...