antlr4_builder
A Dart package that integrates ANTLR4 grammar processing into the build_runner ecosystem, allowing you to automatically generate Dart lexer and parser files from your ANTLR4 grammars.
Features
- Automated Code Generation: Automatically generates Dart lexer, parser, listener, and base listener files from
.g4grammar files during the build process. build_runnerIntegration: Seamlessly integrates with Dart'sbuild_runnerfor efficient and incremental builds.- ANTLR JAR Management: Automatically downloads the necessary ANTLR4 JAR if not already present, simplifying setup.
- Temporary File Management: Utilizes
ScratchSpacefor robust and clean management of temporary files generated during the ANTLR processing. - Configurable ANTLR Version: Allows specifying the ANTLR version to use for code generation.
Getting started
Prerequisites
- Java Development Kit (JDK) (required for the ANTLR tool)
- Dart SDK (version 3.0.0 or higher)
build_runnerin your project'sdev_dependencies.
Installation
Add antlr4 to your project's pubspec.yaml under dependencies:
dependencies:
antlr4: ^4.13.0 # Required for generated ANTLR code
And add antlr4_builder and build_runner to your dev_dependencies:
dev_dependencies:
antlr4_builder: ^0.1.0 # Replace with the actual latest version
build_runner: ^2.0.0 # Replace with the actual latest version
Run dart pub get to fetch the new dependencies.
Configuration
Create or update your build.yaml file in the root of your project to enable the antlr4_builder:
targets:
$default:
builders:
antlr4_builder|antlrBuilder:
enabled: true
options:
# Specify the ANTLR version to use
version: "4.13.2"
# Other options
# ...
# generate_listener: true
# generate_visitor: true
# extra_args: ["-Werror"]
Configuration Options
The following options can be configured in your build.yaml under the options key:
version: (String, required) Specifies the version of the ANTLR tool to use.generate_listener: (boolean, optional) Controls whether to generate a parse tree listener. Defaults totrue. Corresponds to the ANTLR-listenerand-no-listenerflags.generate_visitor: (boolean, optional) Controls whether to generate a parse tree visitor. Defaults tofalse. Corresponds to the ANTLR-visitorand-no-visitorflags.extra_args: (List
Usage
For a complete example, refer to the example/ directory in this repository.
Running the Example
To run the example project:
- Navigate to the
exampledirectory:cd example - Fetch the example project's dependencies:
dart pub get - Run
build_runnerto generate the ANTLR Dart files:dart run build_runner build - Run the example application:
You should see "Parsing successful!" in the console output.dart run bin/main.dart