What does “fragment” mean in ANTLR?

后端 未结 4 1465
太阳男子
太阳男子 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:23

    A fragment is somewhat akin to an inline function: It makes the grammar more readable and easier to maintain.

    A fragment will never be counted as a token, it only serves to simplify a grammar.

    Consider:

    NUMBER: DIGITS | OCTAL_DIGITS | HEX_DIGITS;
    fragment DIGITS: '1'..'9' '0'..'9'*;
    fragment OCTAL_DIGITS: '0' '0'..'7'+;
    fragment HEX_DIGITS: '0x' ('0'..'9' | 'a'..'f' | 'A'..'F')+;
    

    In this example, matching a NUMBER will always return a NUMBER to the lexer, regardless of if it matched "1234", "0xab12", or "0777".

    See item 3

提交回复
热议问题