[antlr-interest] best way to deal with nested statements

Gordon Tyler Gordon.Tyler at quest.com
Fri Jun 25 06:50:49 PDT 2010


Why not something like this:

statements: (stuff|codeBlock);
codeBlock: BEGIN statements END;

-----Original Message-----
From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-bounces at antlr.org] On Behalf Of Scherer Markus
Sent: June 25, 2010 9:03 AM
To: antlr-interest at antlr.org
Subject: [antlr-interest] best way to deal with nested statements

Hi there antlr folk!

As I have mentioned in a former thread I am currently working on a grammar that splits SQL*PLUS files in normal SQL-statements and PL/SQL-blocks.

The PL/SQL-blocks are a bit tricky, because the can contain nested blocks like

BEGIN
            …
            BEGIN
                        …
            END;
END;

I thought about a mechanism, that increases a counter when a BEGIN is found and decreases it when a END; is found:

@members {
            int _iNestLevel = 0;
}

pl_sql_block
            :
            (           ((BEGIN {System.out.println("begin (nestlevel: " + (++_iNestLevel) + ")");})| DECLARE)
            |           CREATE         (OR REPLACE
                                   |PROCEDURE
                                   |FUNCTION
                                   |PACKAGE)
            )           pl_sql_block_content
            ;


pl_sql_block_content
            :           {_iNestLevel < 16}? (options {greedy=false;} : .)*
                        (           BEGIN {System.out.println("begin (nestlevel: " + (++_iNestLevel) + ")");}
                        |           END SEMI{System.out.println("end (nestlevel: " + (--_iNestLevel) + ")");})
                        (           {_iNestLevel > 0}? pl_sql_block_content
                        )
            ;

I tried to eliminate recursion-issues with the predicates, but antlr nevertheless considers the grammar wrong and throws following error when I try to compile it:

[14:46:43] error(206): PLSQLSplitter.g:62:34: Alternative 2: after matching input such as SEMI SL_COMMENT ML_COMMENT BEGIN BEGIN SEMI END SEMI END SEMI END SEMI BEGIN decision cannot predict what comes next due to recursion overflow to pl_sql_block_content from pl_sql_block_content


The second solution that came to my mind was a proper recursive grammar (like e.g. the expression grammar from the book), but I think that’s a little overkill for a simple splitter.

I attached the whole grammar in case the error isn’t obvious from the two rules above.

Thanks in advance
Markus




More information about the antlr-interest mailing list