如何在ANTLR4中执行解析步骤。

huangapple go评论73阅读模式
英文:

How to do the parse step in ANTL4

问题

我已经根据 lexer.g4 和 parser.g4 文件生成了相关的 Java 类。

class Visitor : PostgreSQLParserBaseVisitor<Unit>() {

    override fun visitSelect_stmt(ctx: PostgreSQLParser.Select_stmtContext?) {
        println(ctx?.text)
        super.visitSelect_stmt(ctx)
    }

}

object Scratch {

    @JvmStatic
    fun main(args: Array<String>) {

        val sql = """
            SELECT * FROM table WHERE column = 1
        """.trimIndent()

        val lexer = PostgreSQLLexer(CharStreams.fromString(sql))
        val parser = PostgreSQLParser(CommonTokenStream(lexer))
        val parseTree: ParseTree = parser.??? <<<

        Visitor().visit(parseTree)

    }

}
英文:

I've generated the relevant Java classes given a lexer.g4 and parser.g4 file

如何在ANTLR4中执行解析步骤。

I've written a visitor, but in order to use the Visitor, i need an actual parse tree, how do i get the parse tree from the parser?

In other online examples, there's mention of parser.parse() but that doesn't compile under ANTLR4

class Visitor : PostgreSQLParserBaseVisitor&lt;Unit&gt;() {

	override fun visitSelect_stmt(ctx: PostgreSQLParser.Select_stmtContext?) {
		println(ctx?.text)
		super.visitSelect_stmt(ctx)
	}

}

object Scratch {

	@JvmStatic
	fun main(args: Array&lt;String&gt;) {

		val sql = &quot;&quot;&quot;
			SELECT * FROM table WHERE column = 1
		&quot;&quot;&quot;.trimIndent()

		val lexer = PostgreSQLLexer(CharStreams.fromString(sql))
		val parser = PostgreSQLParser(CommonTokenStream(lexer))
		val parseTree: ParseTree = parser.??? &lt;&lt;&lt;

		Visitor().visit(parseTree)

	}

}

答案1

得分: 1

parse() 方法对应于名为 parse 的解析器规则。如果您正在使用 这个 PostgreSQL 语法,您可能会想使用属于语法入口规则的 root() 方法:

root
    : stmt ((SEMI stmt)+ SEMI)? EOF
    ;
英文:

The parse() method corresponds to a parser rule called parse. If this is the PostgreSQL grammar you're using, you'll probably want to use the root() method belonging to the entry rule of the grammar:

root
    : stmt ((SEMI stmt)+ SEMI)? EOF
    ;

huangapple
  • 本文由 发表于 2020年9月11日 15:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63842396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定