cantlrantlr3antlrworks

ANTLRv3: C target error handling. Changing System.err out


Using ANTLRv3 I can build my parser which by default prints an error string to System.err typically on a console.

However, I have a different output to print errors out to, for example to a file (for logging), i.e. I am not working on a console. I was wondering what I have to do to print the error string in this case? I guess I would just have to change the definition of the function which is responsible for printing the error string but I can't locate it.

From this documentation https://theantlrguy.atlassian.net/wiki/spaces/ANTLR3/pages/2687258/Error+reporting+and+recovery I can find that I simply need to override emitErrorMessage() but I can't locate it in my C target so I'm a bit confused how that would work.

I am working on ANTLR 3.5.2 C target. Using ANTLRv4 is not an option.

Unfortunately, I cannot find much reference projects which use C so I can't learn from them.

I would be grateful for any help.


Solution

  • You cannot override a C function (since it isn't virtual in the C target), but you can replace the error handler with your own to get the errors forwarded instead. See how I did it in the old MySQL Workbench parser code.

    @parser::postinclude {
    #ifdef __cplusplus
    extern "C" { 
    #endif
    
      // Custom error reporting function.
      void onMySQLParseError(struct ANTLR3_BASE_RECOGNIZER_struct *recognizer, pANTLR3_UINT8 *tokenNames); 
    
    #ifdef __cplusplus
    };
    #endif
    }
    
    @parser::members {
    }
    
    @parser::apifuncs
    {
     // Install custom error collector for the front end.
     RECOGNIZER->displayRecognitionError = onMySQLParseError;
    }
    

    The function onMySQLParseError is obviously what you have to change and implement in your C code.