Is it possible to visit a rule without any of the lexer tokens defined in grammar?

111 views Asked by At

If I have this rule:

player : SELF | OPP;

SELF : 'self';
OPP : 'opp' | 'opponent';

Is it possible to visit player rule without having SELF or OPP tokens?

Here is my code to be more concrete:

    @Override
    public Object visitPlayer(PlayerContext ctx) {
        if (ctx.SELF() != null) {
            return BehaviorExecutor.this.game.getPlayerStates()
                    .get(BehaviorExecutor.this.selfIndex);
        } else if (ctx.OPP() != null) {
            return BehaviorExecutor.this.game.getPlayerStates()
                    .get(BehaviorExecutor.this.oppIndex);
        }

        //is it possible to get to here?

        BehaviorExecutor.this
            .logger.log("Neither SELF nor OPP token found when visiting player rule.");

        return null;
    }
1

There are 1 answers

0
GRosenberg On BEST ANSWER

The visitor does not visit rules -- it visits parse tree nodes. A node is not created and added to the parse tree unless all of the symbols of the corresponding rule (or of an alternative subrule) were validly matched against a sequence of source token instances. So, normally, 'here' is not reachable.

Of course, if the parse tree is manually modified after construction, then there is no guarantee that the children of a node correspond to the parser rule's definition of that node.