Antlr - Actions

Card Puncher Data Processing

About

Actions are code blocks in the grammar written in the target language. Grammar actions add code to the generated class.

Syntax / Characteristic

You can use actions in a number of places within a grammar, but the syntax is always the same: arbitrary text surrounded by curly braces.

You don’t need to escape a closing curly character if it’s in a string or comment: “}” or /*}*/. If the curlies are balanced, you also don’t need to escape: {…}. Otherwise, escape extra curlies with a backslash: \{ or \}. The action text should conform to the target language as specified with the language option.

Embedded code can appear in: @header and @members named actions, parser and lexer rules, exception catching specifications, attribute sections for parser rules (return values, arguments, and locals), and some rule element options (currently predicates).

The only interpretation ANTLR does inside actions relates to grammar attributes. Actions embedded within lexer rules are emitted without any interpretation or translation into generated lexers.

The generated class can be enhance through a (grammar action|code) on three points:

  • before the class body in order to specify a Java package name and/or an import
// @header will only affects the generated parser class
@header { ... }
// @lexer::header will affect the generated lexer class
@lexer::header { ... }
  • In the class definition in order to define constants, attributes and methods and/or to override methods in the super-classes of the generated classes.
// @members will only affects the generated parser class
@members { ... }
// @lexer::members will affect the generated lexer class
@lexer::members { ... }
  • Inside the catch blocks of the generated methods. The catch blocks generated for each method rule can be customized in order to for instance stop the processing after the first error.
@rulecatch { catch-blocks }

Documentation / Reference





Discover More
Card Puncher Data Processing
Antlr - (Grammar|Lexicon) (g4)

Grammar in the context of Antlr. The grammar definition of Antlr is called a antlr/antlr4/blob/master/doc/lexicon.mdLexicon because the grammar is used by the lexer (hence the lexer grammar) See: ...



Share this page:
Follow us:
Task Runner