Eliminate invalid expressions with ANTLR (e.g. to complete code)

I have an ANTLR grammar for a simple DSL, and everything works smoothly when there are no syntax errors. Now, however, I need to support the autocomplete mechanism, where I need to get possible improvements from my tree-like grammars that perform basic type checking on attributes, functions, etc.

The problem is that ANTLR does not report syntax errors at the local level statement, but further to the parsing tree, for example, at the programor level function. Therefore, instead of AST, which looks like

             program
                |
             function   
            /   |    \
           /    |     \
       stat   hosed   stat

I get garbage nodes at the top of the tree, because the rule mismatch statement"bubbles up" and prevents the rule from matching function.

Is there a way to write a rule that has a catch-all clause so that there are unexpected tokens?

I am thinking of something like:

statement
    : var_declaration
    | if_statement
    | for_loop
    | garbage
    ;

garbage
    : /* Match unexpected tokens, etc. (not actual statements, or closing
         parens, braces, etc.).  Maybe just consume one input token and let
         the parser try again? */
    ;

There can be any number of garbage nodes in an AST, but everything that was before (and preferably after) the garbage should be normal.

I would be grateful for any hints / suggestions / pointers / etc. I am using ANTLR v3, the target of Java.

+1
source share
1 answer
+1

All Articles