Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "fragment" mean in ANTLR?

Tags:

antlr

What does fragment mean in ANTLR?

I've seen both rules:

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

and

DIGIT : '0'..'9'; 

What is the difference?

like image 231
Oscar Mederos Avatar asked Jun 27 '11 00:06

Oscar Mederos


1 Answers

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

like image 174
sirbrialliance Avatar answered Oct 02 '22 06:10

sirbrialliance