Liling
Liling

Reputation: 11

ANTLR type (ID choosing)

I am writing the grammar of JavaScript which includes more types, such like float, int, boolean, etc. when I am typing to get the information from Hash Map by using the ID(letter or words) as key, my program will always go to the first ID, and that will cause a big problem, anyone knows how can I solve it?

For example:

bool returns [boolean value]
:    ID {$value = hashmap.get($ID.text);}
;

float returns [float value]
:    ID {$value = hashmap.get($ID.text);}
;

Since I am using ID to get the return for both bool and float, it will always go to bool first, and run the bool part instead of float part even ID is storing the float number.

Upvotes: 0

Views: 98

Answers (1)

sepp2k
sepp2k

Reputation: 370162

When you say that "my program will always go to the first ID", I'm assuming your mean that somewhere else in your grammar you have a rule like this:

expr: ...
    | bool
    | float
    ;

And that this will always go into the bool rule because that comes first and matches the same tokens as float. Generally there's no point in having two alternatives within a rule that both expand to the same tokens.

You could make bool and float only match if the ID is contained in the corresponding map by using predicates, but this is generally not a good idea. A much more common approach is to have a single map that contains entries for all variables regardless of their type.


PS: On a more general note, it looks like you're trying to evaluate expressions directly in the parser (at least the name of your return value suggests that you're trying to calculate the value of the expression). Note that this approach will not work beyond simple calculator. As soon as you introduce any kind of control flow (function calls, if-statements, loops), you'll find it impossible to control when and how often the code in the actions should execute (it will always execute exactly once when the given code is parsed). Instead of doing it this way, your parser should simply produce a tree or bytecode, which you can then execute in a separate step.

Upvotes: 1

Related Questions