Search code examples
cif-statementantlrgrammarantlrworks

the if satement does not work with my grammar


I have an issue with my if statement with my grammar, wich can be found here http://sd-g1.archive-host.com/membres/up/24fe084677d7655eb57ba66e1864081450017dd9/CNew.txt . When I type for example in Ctrl+D :

  int k = 0;
  if ( k ==0 ){
       return k;
  }

the tree parser stops at "if(" , and the console does not state any reason. Does anyone know where the issue may comes from please ?


Solution

  • Assuming the entry point of your grammar is translation_unit, it looks like the parser simply stops after it matched a single external_declaration. Try adding the EOF (end of file) token at the end of that rule so that the parser is forced to match the entire input:

    translation_unit
        : external_declaration+ EOF
        ;
    

    However, I don't see how an external_declaration would ever match an if-statement (a selection_statement) in your grammar. Perhaps you want to add a statement to your external_declaration:

    translation_unit
    scope Symbols; // entire file is a scope
    @init {
      $Symbols::types = new HashSet();
    }
        : (external_declaration)+ EOF
        ;
    
    external_declaration
        : function_definition
        | declaration
        | statement
        ;
    

    after which your input will get properly parsed.