2

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) ); "; 
2
  • 1
    Usually your grammar will have one production that's meant to serve as the entry point to the grammar. It's usually the first one in the grammar and ends with EOF. That's usually the one you should call. I don't know what you mean by "typeless objects" though. Error nodes? Commented Jun 23, 2022 at 17:46
  • 1
    can you share which grammar you are using? frequently there is a "catch-all" top-level rule that you could invoke (it would just list all the possible top-level alternatives). If such does not exist, then there would be an assumption that you know which parse rule to use as your starting point. (There's nothing stopping you from creating a rule that lists all of the alternatives though) Commented Jun 23, 2022 at 19:09

1 Answer 1

2

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

myTree = parser.sql_script(); 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm using this grammar and I tried this method, but I don't have the expected result. (I edit my question).
@bokan the popup might show anything, but that does not mean it really is untyped. If you open the generated parser, surely the return type of sql_script is not any or object.
You're right tree.GetType().Name == "Sql_scriptContext"; Thank you verymuch.
Good to hear it's working!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.