What does “fragment” mean in ANTLR?

后端 未结 4 1473
太阳男子
太阳男子 2020-11-27 04:21

What does fragment mean in ANTLR?

I\'ve seen both rules:

fragment DIGIT : \'0\'..\'9\';

and

DIGIT : \'0\'         


        
4条回答
  •  庸人自扰
    2020-11-27 04:25

    According to the Definitive Antlr4 references book :

    Rules prefixed with fragment can be called only from other lexer rules; they are not tokens in their own right.

    actually they'll improve readability of your grammars.

    look at this example :

    STRING : '"' (ESC | ~["\\])* '"' ;
    fragment ESC : '\\' (["\\/bfnrt] | UNICODE) ;
    fragment UNICODE : 'u' HEX HEX HEX HEX ;
    fragment HEX : [0-9a-fA-F] ;
    

    STRING is a lexer using fragment rule like ESC .Unicode is used in Esc rule and Hex is used in Unicode fragment rule. ESC and UNICODE and HEX rules can't be used explicitly.

提交回复
热议问题