2
votes

I am writing a C# grammar in Java using Antlr 4.5. When I am dealing with a C# source code having Preprocessor Directives. sample code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hansa
{
    class Program
    {
        public static void Main()
        {
            int b = 5;
            #if true
                int c = 0;
                #if false
                            union {
                                internal struct {
                                    uint    pmclass;
                                    ushort  pmenum;
                                };
                                ushort  bseg;
                                byte[]  Sym;
                                internal struct  {
                                    uint index;
                                    string name;
                                } btype;
                            } pbase;
                #endif
                printMe(c);
            #endif
            printMe(b);
            Console.ReadLine();
        }

        public static void printMe(int val)
        {
            Console.WriteLine(val);
        }
    }
}

In the above code sample, codes between "#if false" and next "#endif" generates an error as "no viable alternative at input 'union {'".

I need to ignore this error in code level or ignore lines through grammar.

In the above code, if I do not have any errors, I can get namespace name, class name, method names, method signatures and lines of statements. When I got an error near by "union {", I am able to reach namespace name, class name, Main() method name but I am unable to reach to printMe() method declaration.

My requirement is, when an error occurred, grammar parsing should not be terminated. It should be continued from next line till EOF.

How can I achieve that ?

1

1 Answers

2
votes

You will have to rewrite the ANTLR4 error recovery. DefaultErrorStrategy will report the NoViableAlternativeException and then recovers. It does not interrupt parsing. So if your program interrupts on the first error:

  • Maybe you use another ANTLRErrorStrategy. Then adjust it, that it recovers like the DefaultErrorStrategy
  • Or your ANTLRErrorListener interrupts the program, then you will have to adjust this one in a way that it skips the failure.

If you want that the error recovery does start at the next line, you will have to adjust the methods ErrorStrategy.recoverXXX. By default error recovery tries to delete/insert magic tokens, to come to a clean state.