Link <leon.lim.i
...@gmail.com> writes:
> In the grammar specification rules, i have two tokens which have the
> same definition.
> In my declarative langage i would like to distinguish an <IdentTypeA>
> from an <IdentTypeB>.
Your desire is not an uncommon one, and there is at least a partial
solution. However, first let me explain why you can't get exactly
what you want. When the lexer recognizes that a set of characters
matches one of the tokens, it returns the token matched. The lexer
does this without consulting the context or any other information.
The complex technical reasons essentially reduce to that doing it that
way makes it easy to prove correct and the resulting lexer runs
fast. (If you want an explanation of the why's of that, just ask.)
Given that the lexer doesn't look at anything but the characters that
make up token, if you have two tokens that have the same spelling, the
lexer has no way to tell which token type to return.
If you want to introduce context into the token type, you simply turn
the token into a non-terminal. Declare an IDENT token and identTypeA
and identTypeB non-terminals, each which simply reduce to an IDENT
token. The parser has context where the lexer doesn't. (In fact,
that is the essential difference between a lexer and a parser--the
parser is the technology that understands context.)
However, in your case, you probably want all uses of a token with the
same spelling to get the same "token" type. In that case, what you
want is to have the type kept in the symbol table, in essence a
"symbol" type. The symbol table is the place to keep information
about all tokens representing the same entity. In the rules which
turn IDENT tokens into identTypeA or identTypeB non-terminals, you
query the symbol table and check that the type you want to use matches
the type you have recorded in the symbol table and if necessary you
record the information you want saved for later uses.
Hope this helps,
-Chris
*************************************************************************** ***
Chris Clark Internet: christopher.f.cl...@compiler-resources.com
Compiler Resources, Inc. or: comp...@world.std.com
23 Bailey Rd Web Site: http://world.std.com/~compres
Berlin, MA 01503 voice: (508) 435-5016
USA fax: (978) 838-0263 (24 hours)
--------------------------------------------------------------------------- ---