0
votes

I have defined a grammar language using Antlr3. ANTLRWorks generates the lexer and parser code.

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. What I would like to find out:

  • Does the Java code have to be written within the grammar?
  • I would prefer to use the Lexer and Parser, and write the Java code within another class instead within the grammar.

According to the following post: ANTLR: Is there a simple example? 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.

Each rule has a specific meaning in Java terms. 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?

1
First, have you gone through Scott Stanchfield's video tutorials yet? javadude.com/articles/antlr3xtutJason
Second, if it's a complex grammar, you are better off with a AST rather than embedding. The one I'm working on is relatively simple (parsing some odd IF/THEN statements).Jason
Mine is a simple grammar. I have seen this before I approached stackoverflow.com. For some reasons my video does not seem to work. I have a very old laptop. Are you able to provide answers for above. Otherwise, I will first have to fix the computer. I don't have time right now.user1646481
I recommend downloading VLC Media Player and using it to view those videos, which are downloadable. I was thrashing around uselessly before watching them.Jason
Already tried this, still no solution. Is there another website which you could direct me so instead of video, their would be text. I really don't have time to fix my laptop.user1646481

1 Answers

0
votes

The answer to your two questions:

  1. No, the Java code does NOT have to be embedded within the grammar. You can generate an AST instead. My grammar is simple enough, so I don't do that.
  2. The generated AST can be processed using the Observer/Vistor pattern. Google should turn up something there for you.