I'm using following EmojiLexer.g4 together with ANTLR 4.7.2
lexer grammar EmojiLexer;
String
: '"' StringChar* '"'
;
fragment StringChar
: ~["\r\n]
;
Punctuation
: ( '['
| ':'
| ']'
| ';'
| '@'
)
;
fragment IdentifierNonDigit
: [a-zA-Z_$\u0080-\uffff]
;
Identifier
: IdentifierNonDigit+
;
Whitespace
: [ \t]+
-> skip
;
Newline
: ( '\r' '\n'?
| '\n'
)
-> skip
;
and following Java code to lex a string:
public class EmojiTest {
public static void main(String[] args) {
final String string = "[foo bar:bazz];\n"
+ "\n"
+ "@\"emojis break it: \uD83D\uDE31\";\n"
+ "\n"
+ "[foo bar:bazz];\n";
final CharStream charStream = CharStreams.fromString(string);
final EmojiLexer lexer = new EmojiLexer(charStream);
while (true) {
final Token token = lexer.nextToken();
final int type = token.getType();
if (type < 0) {
break;
}
final int startIndex = token.getStartIndex();
final int stopIndex = token.getStopIndex() + 1;
System.out.println(startIndex + "-" + stopIndex + ": " + type + ": " + escape(string.substring(startIndex, stopIndex)));
}
}
private static String escape(String s) {
final StringBuilder buffer = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
final char chr = s.charAt(i);
if (chr >= 0x20 && chr < 0x7f) {
buffer.append(chr);
}
else {
buffer.append("\\u");
final String hex = Integer.toHexString(chr);
for (int j = hex.length(); j < 4; j++) {
buffer.append('0');
}
buffer.append(hex);
}
}
return buffer.toString();
}
}
but somehow the emoji double-character confuses ANTLR, because the result is:
0-1: 2: [
1-4: 3: foo
5-8: 3: bar
8-9: 2: :
9-13: 3: bazz
13-14: 2: ]
14-15: 2: ;
17-18: 2: @
18-38: 1: "emojis break it: \ud83d\ude31
38-39: 2: "
41-42: 2: \u000a
42-45: 3: [fo
46-49: 3: ba
49-50: 2: r
50-54: 3: :baz
54-55: 2: z
55-56: 2: ]
Is this a bug in my code or in ANTLR?