简体   繁体   English

Antlr语法Java代码

[英]Antlr Grammar Java Code

I have defined a grammar language using Antlr3. 我已经使用Antlr3定义了语法语言。 ANTLRWorks generates the lexer and parser code. ANTLRWorks生成词法分析器和解析器代码。

Below is a sample grammar: 下面是一个示例语法:

grammar i;

@header {
package com.data;
}

elements    : (value (',' value)*)?;
insert      : 'INSERT INTO table' 'VALUES' '('elements')'';';
WS      : (' '|'\t'|'\f'|'\n'|'\r')+ {skip();}; // handle white space between keywords

The above grammar is only a example. 上面的语法只是一个例子。 I am actually developing a big grammar for my company. 我实际上正在为我的公司开发一种大语法。

I have imported the grammar into com.data package of my project and can use the Lexer and Parser generated. 我已将语法导入到项目的com.data包中,并且可以使用生成的Lexer和Parser。 What I would like to find out: 我想找出的是:

  • Does the Java code have to be written within the grammar? Java代码是否必须在语法中编写?
  • I would prefer to use the Lexer and Parser, and write the Java code within another class instead within the grammar. 我更喜欢使用Lexer和Parser,并在另一个类中而不是在语法中编写Java代码。

According to the following post: ANTLR: Is there a simple example? 根据以下帖子: ANTLR:有一个简单的例子吗? it shows a simple example. 它显示了一个简单的示例。 However, in my case the grammar is big and would prefer the grammar to be imported and used. 但是,在我的情况下,语法很大,希望将其导入和使用。 I have many rules: 我有很多规则:

For example, the above grammar generates this code: 例如,上面的语法生成以下代码:

public void insert() throws RecognitionException;

What is the best way to handle this? 处理此问题的最佳方法是什么? I have lots of rules, which are return type of void. 我有很多规则,它们都是void的返回类型。

Each rule has a specific meaning in Java terms. 每个规则在Java术语中都有特定的含义。 I don't think the best way would be to get the syntax and then check call my code. 我认为最好的方法不是获取语法然后检查调用我的代码。 For example: 例如:

String input = "INSERT INTO table VALUES (null);";
if(input.equals("INSERT INTO table VALUES (null);") {
     insertData();
}

public void insertData() {
   // insert data into database
}

It is a good idea to check against every syntax and call my code? 最好检查每种语法并调用我的代码?

The answer to your two questions: 您的两个问题的答案:

  1. No, the Java code does NOT have to be embedded within the grammar. 不,Java代码不一定必须嵌入语法中。 You can generate an AST instead. 您可以改为生成AST。 My grammar is simple enough, so I don't do that. 我的语法很简单,所以我不这样做。
  2. The generated AST can be processed using the Observer/Vistor pattern. 可以使用Observer / Vistor模式来处理生成的AST。 Google should turn up something there for you. Google应该为您提供一些帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM