ANTLR4无关输入 [英] ANTLR4 extraneous input

查看:113
本文介绍了ANTLR4无关输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ANTLR4有问题.我正在尝试从python 3代码打印AST,但存在一些错误,我不知道如何解决.

I have a problem with my ANTLR4. I'm trying to print AST from python 3 code but there are some errors and I don't know how to fix them.

我编写了简单的测试代码:

I wrote simple code for test:

a=(1,2,3)
print(a)

我运行了程序,但是出现了这个错误:

I ran the program but this errors appeared:

line 1:1 extraneous input '=' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '@'}
line 2:0 extraneous input '\n' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '@'}
line 3:0 extraneous input '\n' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '@'}

我的主要班级:

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.*;
public class Main {

    public static void main(String[] args) {
        try {
            ANTLRInputStream input = new ANTLRFileStream("/home/grzegorz/Desktop/Python3/input.txt");
            Python3Lexer lexer = new Python3Lexer(input);
            CommonTokenStream token = new CommonTokenStream(lexer);
            Python3Parser parser = new Python3Parser(token);
            ParseTree parseTree = parser.expr();
            System.out.println(parseTree.toStringTree(parser));

        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}

我有这个网站的语法: https://github.com/antlr/grammars-v4/tree/master/python3

I have the grammar from this site: https://github.com/antlr/grammars-v4/tree/master/python3

推荐答案

说明

您的输入文件包含两个语句,您正在将文件解析为好像是一个表达式(行ParseTree parseTree = parser.expr();; Python 3语法中的规则expr).

Explanation

Your input file consists of two statements and you are parsing the file as if it was an expression (with line ParseTree parseTree = parser.expr();; rule expr from Python 3 grammar).

这也说明了第一个错误:标识符a被接受为表达式的一部分,但=符号却未被接受.这是因为=是赋值语句的一部分.

This also exaplains the first error: an identificator a is accepted as a part of expression but = sign is not. That's because = is a part of assignment statement.

使用另一个语法规则(例如file_input规则)解析输入,该规则将接受许多语句.将上述行更改为ParseTree parseTree = parser.file_input();.

Parse the input using another grammar rule for example file_input rule which will accept many statements. Change the abovementioned line to ParseTree parseTree = parser.file_input();.

这篇关于ANTLR4无关输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆