Actions and Attributes

In Chapter 10, ​Attributes and Actions​, we learned how to embed actions within grammars and looked at the most common token and rule attributes. This section summarizes the important syntax and semantics from that chapter and provides a complete list of all available attributes.

Actions are blocks of text written in the target language and enclosed in curly braces. The recognizer triggers them according to their locations within the grammar. For example, the following rule emits found a decl after the parser has seen a valid declaration:

​ decl​:​ type ID ​';'​ ​{​System​.​out​.​println​(​​"found a decl"​​);}​ ​;​
​ type​:​ ​'int'​ ​|​ ​'float'​ ​;​

Get The Definitive ANTLR 4 Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.