Are lexers and parsers really that different in theory?
It seems fashionable to hate regular expressions: coding horror, another blog post.
However, popular lexing based tools: pygments, geshi, or prettify, all use regular expressions. They seem to lex anything...
When is lexing enough, when do you need EBNF?
Has anyone used the tokens produced by these lexers with bison or antlr parser generators?
What parsers and lexers have in common:
*
, ==
, <=
, ^
will be classified as "operator" token by the C/C++ lexer.[number][operator][number]
, [id][operator][id]
, [id][operator][number][operator][number]
will be classified as "expression" nonterminal by the C/C++ parser.[TXT][TAG][TAG][TXT][TAG][TXT]...
.As you can see, parsers and tokenizers have much in common. One parser can be a tokenizer for other parser, which reads its input tokens as symbols from its own alphabet (tokens are simply symbols of some alphabet) in the same way as sentences from one language can be alphabetic symbols of some other, higher-level language. For example, if *
and -
are the symbols of the alphabet M
(as "Morse code symbols"), then you can build a parser which recognizes strings of these dots and lines as letters encoded in the Morse code. The sentences in the language "Morse Code" could be tokens for some other parser, for which these tokens are atomic symbols of its language (e.g. "English Words" language). And these "English Words" could be tokens (symbols of the alphabet) for some higher-level parser which understands "English Sentences" language. And all these languages differ only in the complexity of the grammar. Nothing more.
So what's all about these "Chomsky's grammar levels"? Well, Noam Chomsky classified grammars into four levels depending on their complexity:
a
,b
), their concatenations (ab
,aba
,bbb
etd.), or alternatives (e.g. a|b
).(()()(()()))
, nested HTML/BBcode tags, nested blocks etc. It's because state automata to deal with it should have to have infinitely many states to handle infinitely many nesting levels.x+3
and in one context this x
could be a name of a variable, and in other context it could be a name of a function etc.