|P is for Practical|
Re: RFC: Parsing with perl - Regexes and beyondby blokhead (Monsignor)
|on Apr 03, 2008 at 15:25 UTC||Need Help??|
When talking about lexing, you say:
Parsing CFLs takes O(n³) time.This is a little misleading. LALR parsers take linear time (where the size of its lookup tables is taken to be a constant, since it is independent of the input string to be parsed), while recursive descent can in principle take exponential time.
I'm guessing you are thinking of the CKY algorithm, which does take cubic time. This algorithm's importance is strictly theoretical, since it can be used to efficiently parse completely arbitrary grammars. In practice, we exploit the extra structure possesed by most practical grammars to obtain faster parsing than CKY provides.
So I don't think lexing is a matter of running-time efficiency. Its benefit is that if you blindly parse a character stream without lexing, you would have a separate leaf in the parse tree for every character (including whitespace!). Tokens like /\d+/, if expressed directly in the context-free grammar and parsed one character at a time, would then lead to very unwieldy parse trees like this:
Lexing "collects" all these nasty bottom sections of the parse tree, which would otherwise be everywhere, into chunks that reflect how the parse tree will be used. Of course this could also be cleaned up with special cases in the parser, but lexing separates out this step in an elegant way.
PS: "Chompsky" (with a p) is a name commonly given to pet dogs by linguists... either as an insult or homage to Chomsky, depending on which side of the great linguistic divide you fall ;)