bokan
bokan

Reputation: 3692

How to get a parse tree from antlr4 parser?

I'm using ANTLR4 to parse SQL. I managed to generate the parser and it seems to work.

I'm now stuck at how to get a tree from the parser.

string input="SELECT * FROM myTable";
ITokenSource lexer = new PlSqlLexer(new AntlrInputStream(input));
ITokenStream tokens = new CommonTokenStream(lexer);

var parser = new PlSqlParser(tokens, writerOutput, writerError);
parser.AddErrorListener(new ThrowExceptionErrorListener());
parser.BuildParseTree = true;
myTree = parser.# what method here #();

I saw that I can use the sql_statement() method sometime, sql_create_table() all depending on what is inside the SQL source. But how am I supposed to know what type is the content before I parsed it ? I was expecting a generic method that create objects in a tree structure so I can later feed it to MyVisitor class and generate my objects. If I don't use the right method I got a tree of typeless objects that my visitor can't handle.

What am I doing wrong ?

Edit : I'm using this grammar

When I use sql_script() I got this untyped object (I can't see the type in the popup label)

An object without type

The input is this:

string input = @"
CREATE TABLE ot.persons(
    person_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
    first_name VARCHAR2(50) NOT NULL,
    last_name VARCHAR2(50) NOT NULL,
    PRIMARY KEY(person_id)
);
";

Upvotes: 2

Views: 1664

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170298

Assuming you're using this grammar, you'd invoke the sql_script rule:

myTree = parser.sql_script();

Upvotes: 2

Related Questions