I was creating a language and discovered that my language tokenizer would have to change depending where in the parse it is.
I.e. abc[1]
would be parsed as 4 tokens (abc
, [
, 1
, ]
), where as { abc[1] }
would be parsed as 3 ({
, abc[1]
, }
).
Is a grammar that would change its tokenizer mid parse defined somewhere? Does a grammar even define such a thing or is it irrelevant to the grammar and is just not really done on a parser level?
15
There is no special name for this type of grammar that I know of. What you have there is still a LR(k) grammar that could be parsed by a parser that takes each character to be a token, and has k characters of lookahead.
The division of parsing into tokenization and syntax recognition stems from the desire to increase efficiency by reducing lookahead to 1 symbol. (That and the fact that a token is a concept in the syntax of a programming language, so why not have a matching representation in the language implementation.)
That is to say, the principal technical advantage of parsing tokens rather than characters is that we can distinguish interface
and integer
with one symbol of lookahead rather than three symbols of lookahead.
Separate tokenizers are an implementation detail of parsers. Separate tokenizers are not necessary; it is possible to create parsers without separate tokenizers.
However, separate tokenizers are often used in practice, and when they are, the tokens are often defined using (real) regular expressions.
If you’re using a separate tokenizer, you may find it difficult or impossible to switch tokenizers in the middle of a parse. However, there are no theoretical problems with doing this, just technological — if you choose the right technology, it’s actually quite easy to do.
So to answer your specific questions:
- “Is a grammar that would change it’s tokenizer mid parse defined somewhere?” This can happen with language composition. Separate, regular tokenizers do not interact well with language composition.
- “Does a grammar even define such a thing or is it irrelevant to the grammar and is just not really done on a parser level?” Tokenization is a part of a grammar, so yes, a grammar is free to dictate how tokenization occurs depending on what rule it’s trying to parse. However, you may not see this often in practice. Typically, at least in my experience, tokenization is regular and not context-free or context-sensitive.