extract-fragment
Extract common lexer patterns into reusable fragments to reduce duplication and improve maintainability in ANTLR4 grammars.
Instructions
Extract a reusable fragment rule from a pattern to reduce duplication.
When to use: Share common patterns, improve maintainability, reduce duplication in lexer rules.
Example - Extract digit pattern: fragment_name: "DIGIT" pattern: "[0-9]"
Example - Extract letter pattern: fragment_name: "LETTER" pattern: "[a-zA-Z]"
After extraction, use the fragment in other rules: ID: LETTER (LETTER | DIGIT)*
Benefits:
Single source of truth for common patterns
Easier maintenance
Clearer lexer organization
Fragments are not tokens themselves (helper patterns only)
Returns: Modified grammar with fragment added, original pattern preserved in existing rules.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| pattern | Yes | The pattern to extract as a fragment (e.g., "[0-9]", "[a-zA-Z]") | |
| from_file | No | Optional: path to a grammar file to read | |
| fragment_name | Yes | Name for the fragment (must be UPPERCASE, e.g., DIGIT, LETTER, IDENTIFIER_PART) | |
| grammar_content | No | The ANTLR4 grammar file content |