Question

In my grammar I have the rule for an assignment. It is the form assignment: VAR_TYPE ID '=' expr;

In VAR_TYPE I have some hardcoded values like Integer, String etc.

What I want to know is how can I match any class name that is declared in the file ?

Suppose someone declared class Foo and Class Bar. How can I mark this as valid input without utilising ID. Because if I ad |ID to the VAR_TYPE rule, ID will never be matched and I don't want that.

Was it helpful?

Solution

You shouldn't hard code your type names unless they are actually keywords in your language. Then you create a parser rule to match any type:

varType : ID;
assignment : varType ID '=' expr;

Integer and String would then be treated as regular ID tokens.

Use a listener after the parse is complete to validate that the ID appearing in each varType actually refers to a type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top