本文介绍了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

推荐答案

说明

您的输入文件由两个语句组成,您正在解析该文件,就好像它是一个表达式(使用行 ParseTree parseTree = parser.expr();; rule expr 来自 Python 3 语法).

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 外部输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:44