{notifyErrorListeners("unclosed char literal");}
{false}?<fail="unclosed char literal">
grammar CharExperiment_01;
stat : 'start' CharacterLiteral 'end' EOF;
// Lexer
CharacterLiteral
: '\'' SingleCharacter '\''
| '\'' SingleCharacter SingleCharacter+ '\'' {false}?<fail='Char literal may only have one char'>
// fail compiles if single quotes used instead of double,
// but does not issue message on error
| '\'' {notifyErrorListeners("unclosed char literal");}
// notifyErrorListeners method is not in the lexer error listener
;
fragment
SingleCharacter
: ~['\\\r\n]
;
WS : [ \r\t\n]+ -> skip ;
grammar CharExperiment_04;
stat : 'start' charLit 'end' EOF;
charLit
: CharacterLiteral
| BadCharLiteral {false}?<fail='Char literal may only contain one character'>
| EmptyCharLiteral {false}?<fail='Empty char literal'>
| UnclosedCharLiteral {false}?<fail='Unclosed character literal'>
;
// Lexer
CharacterLiteral
: '\'' SingleCharacter '\''
;
BadCharLiteral
: '\'' SingleCharacter SingleCharacter+ '\''
;
EmptyCharLiteral
: '\'' '\''
;
UnclosedCharLiteral
: '\''
;
fragment
SingleCharacter
: ~['\\\r\n]
;
WS : [ \r\t\n]+ -> skip ;
{notifyErrorListeners("my message");}
{false}?<fail='my message'>
I tried using both
{notifyErrorListeners("unclosed char literal");}
and
{false}?<fail="unclosed char literal">
in the lexer but couldn't get them to work. There were lots of surprising syntax errors and endless loops that I will spend some time documenting on GitHub, but for now I just wanted to raise the flag.
grammar CharExperiment_01;
stat : 'start' CharacterLiteral 'end' EOF;
// Lexer
CharacterLiteral
: '\'' SingleCharacter '\''
| '\'' SingleCharacter SingleCharacter+ '\'' {false}?<fail='Char literal may only have one char'>
// fail compiles if single quotes used instead of double,
// but does not issue message on error
| '\'' ~[\r\n] {notifyErrorListeners("unclosed char literal");}
// notifyErrorListeners method is not in the lexer error listener
;
fragment
SingleCharacter
: ~['\\\r\n]
;
WS : [ \r\t\n]+ -> skip ;
George