ANTLR Parsing - Matches Wrong Thing but Fix is EOF?

怎甘沉沦 提交于 2019-12-11 07:38:23

问题


I try to parse:

return 3 + 4;

My parse code (see below) parses it as the second rule (statement statements program) instead of the first rule. If I comment out the second rule, then the parser interprets it as the third rule (functions statement program).

My "fix" that has worked so far is to make:

master : program EOF ;

Why does that fix my issue?

Relevant Parse Code:

program
    : statement { 
        System.out.println("STATEMENT PROGRAM");
      }     
    | statement statements program {
        System.out.println("MULTI STATEMENT PROGRAM");
      }
    | functions statement program {
        System.out.println("FUNCTION PROGRAM");
      };

statement :
   RETURN expr SEMICOLON {
        System.out.println("STATEMENT");
   };

Note: 'statements' and 'functions' can be nullable

Also, assume expr is correct :) (it cannot be nullable)

Some clarification:

statements : statement* ;

When I run parser.program(), I expect that return 3 + 4; should parse properly (and then the EOF comes after which is not caught by any parse rules); however, return 'return 3 + 4;' is not treated as a statement but a statement statements program.

Commenting out that rule, my parser still does not parse return 3 + 4; as a statement but as a functions statement program.

I would think that the return statement is parsed as

statement='return 3 + 4;' EOF

and not

statement='return 3 + 4;' statements='' program=?

and also not

functions='' statement='return 3 + 4;' program=?

My question is, why is ANTLR trying to parse it as the second and third rules?

来源:https://stackoverflow.com/questions/18952397/antlr-parsing-matches-wrong-thing-but-fix-is-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!