antlr4

ANTLR4 - Remove commented code from visitMethod_declaration


I would like to tweak my grammar so that the visitMethod_declaration() can ignore the commented code

public void bark() {
      Console.WriteLine("Bark Bark !!");
       // Complex calculations involving parentheses
        double resultComplex = ((10 + 5) * (20 - 7)) / (8 * 4);
        Console.WriteLine("Complex Calculation: " + resultComplex);
        
             int i = 0;
             while (i < 15)
             {
                // // While loop
                
                 Console.WriteLine("Value of i: " + i);
                 int x = 10;
                // // if (x > 5)
                // // {
                    // // Console.WriteLine("x is greater than 5");
                // // }
                 i++;
             }
            
            
    }

this method body returned from visitMethod_declaration() should be without the commented code.

Any tips to achieve this using ANTLR4 only and not regex.


Solution

  • You probably have one or more -> channel(HIDDEN); in your grammar. Replace them with -> skip;

    EDIT

    Or if your comment rule(s) look like this (where XYZ is something different):

    COMMENT : '//' ~[\r\n]* -> channel(XYZ);
    

    change it to:

    COMMENT : '//' ~[\r\n]* -> skip;