Hamzawey
Hamzawey

Reputation: 416

parse C# preprocessors in antlr4

I'm trying to parse C# preprocessors using ANTLR4 instead of ignoring them. I'm using the grammar mentioned here: https://github.com/antlr/grammars-v4/tree/master/csharp

This is my addition (now i'm focusing only on pp_conditional):

pp_directive
    : Pp_declaration
    | pp_conditional
    | Pp_line
    | Pp_diagnostic
    | Pp_region
    | Pp_pragma
    ; 

pp_conditional
    : pp_if_section (pp_elif_section | pp_else_section | pp_conditional)*  pp_endif
;


pp_if_section:
  SHARP 'if' conditional_or_expression statement_list
;

pp_elif_section: 
   SHARP 'elif' conditional_or_expression statement_list
;

pp_else_section:
   SHARP 'else' (statement_list | pp_if_section)
;

pp_endif:
    SHARP 'endif'
;

I added its entry here:

block 
    : OPEN_BRACE statement_list? CLOSE_BRACE
    | pp_directive
    ;

i'm getting that error:

line 19:0 mismatched input '#if TEST\n' expecting '}'

when i use the following test case:

if (!IsPostBack){
 #if TEST 
   ltrBuild.Text = "**TEST**"; 

#else 
   ltrBuild.Text = "**LIVE**";

#endif
}

Upvotes: 1

Views: 156

Answers (1)

Mephy
Mephy

Reputation: 2986

The problem is that a block is composed of either '{' statement_list? '}' or a pp_directive. In this specific case, it chooses the first, because the first token it sees is a { (after the if condition). Now, it is expecting to maybe see a statement_list? and then a }, but what it find is #if TEST, a pp_directive.

What do we have to do? Make your pp_directive a statement. Since we know statement_list: statement+;, we search for statement and add pp_directive to it:

statement 
    : labeled_statement
    | declaration_statement
    | embedded_statement
    | pp_directive
    ;

And it should be working fine. However, we must also see if your block: ... | pp_directive should be removed or not, and it should be. I'll let it for you to find out why, but here's a test case that's ambiguous:

if (!IsPostBack)
    #pragma X
else {
}

Upvotes: 1

Related Questions