Capturing "all other" characters in ANTLR

I am trying to integrate the grammar defined by ANTLR into NetBeans, and so far the valid syntax is working fine. However, at present, if you enter a character that is not defined in any language (for example, the "?" Character), the User Editor immediately crashes because it cannot find the rule for that character.

Is there a way in ANTLR to catch and skip EVERY character that does not comply with the rule (and possibly displays an error message) without a complete lexer and write failure? I would just like to flag invalid characters, skip them and continue lexing, something like:

//some rules + tokens

invalidCharacter
    :    <<catch all other characters>>
        {System.out.println("undefined character entered!")}
    ;

Any help would be assigned.

+3
source share
1

lexer, , :

grammar T;

@lexer::members {
  public List<String> errors = new ArrayList<String>();
}

parse
  :  .* EOF
  ;

INT
  :  '0'..'9'+
  ;

WORD
  :  ('a'..'z' | 'A'..'Z')+
  ;

SPACE
  :  ' ' {$channel=HIDDEN;}
  ;

INVALID
  :  . {
         errors.add("Invalid character: '" + $text + "' on line: " +
             getLine() + ", index: " + getCharPositionInLine());
       }
  ;

, ascii, List lexer. "abc 123 ? foo !" :

import org.antlr.runtime.*;

public class Main {
  public static void main(String[] args) throws Exception {
    TLexer lexer = new TLexer(new ANTLRStringStream("abc 123 ? foo !"));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    tokens.toString(); // dummy call to toString() which causes all tokens to be created
    if(!lexer.errors.isEmpty()) {
      for(String error : lexer.errors) {
        System.out.println(error);
      }
    }
    else {
      TParser parser = new TParser(tokens);
      parser.parse();
    }
  }
}

:

java -cp antlr-3.3.jar org.antlr.Tool T.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main

Invalid character: '?' on line: 1, index: 9
Invalid character: '!' on line: 1, index: 15
+6

All Articles