To extend the ANTLR grammar to support type definitions in the format key: type = value, we'll modify the existing grammar to include type annotations. The type will be defined as an identifier (alphabetical characters, numbers, and underscores, with no spaces). Below is the updated grammar and an example of how to use it.
Step 1: Updated ANTLR Grammar File (Config.g4)
Replace the contents of Config.g4 with the following:
grammar Config;
// Parser rules
config : (property NEWLINE)* EOF; // A config file consists of zero or more properties followed by EOF
property : key ':' type '=' value; // A property is a key, type, and value, separated by ':' and '='
key : IDENTIFIER; // A key is an identifier
type : IDENTIFIER; // A type is an identifier (no spaces, alphabetical, numbers, underscore)
value : STRING | NUMBER | IDENTIFIER; // A value can be a string, number, or identifier
// Lexer rules
IDENTIFIER : [a-zA-Z_][a-zA-Z0-9_]*; // Identifiers start with a letter or underscore, followed by letters, digits, or underscores
STRING : '"' (~["\r\n])* '"'; // Strings are enclosed in double quotes
NUMBER : [0-9]+ ('.' [0-9]+)?; // Numbers can be integers or decimals
NEWLINE : '\r'? '\n'; // Newline (handles both Unix and Windows line endings)
WS : [ \t]+ -> skip; // Whitespace is skipped
COMMENT : '#' ~[\r\n]* -> skip; // Comments start with '#' and are skipped
Explanation of Changes
-
Parser Rules:
- Modified
property to include a type annotation: key ':' type '=' value. This means each property now requires a key, followed by a colon (:), a type, an equals sign (=), and a value.
- Added a
type rule that matches an IDENTIFIER, ensuring types are valid identifiers (alphabetical, numbers, underscores, no spaces).
-
Lexer Rules:
- No changes are needed in the lexer rules since
IDENTIFIER already supports the required format for types.
Step 2: Generate ANTLR Code
Regenerate the parser and lexer code by running the ANTLR tool:
antlr4 Config.g4
Step 3: Updated Java Program
Update the Java program to handle the new grammar and demonstrate parsing of typed properties. Here's the updated ConfigParserMain.java:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class ConfigParserMain {
public static void main(String[] args) throws Exception {
// Sample configuration input with types
String configInput =
"server_name: string = \"MyServer\"\n" +
"port: int = 8080\n" +
"debug: bool = true\n" +
"# This is a comment\n" +
"timeout: float = 30.5\n";
// Create a CharStream from the input string
CharStream input = CharStreams.fromString(configInput);
// Create a lexer
ConfigLexer lexer = new ConfigLexer(input);
// Create a token stream
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser
ConfigParser parser = new ConfigParser(tokens);
// Parse the input starting from the 'config' rule
ParseTree tree = parser.config();
// Print the parse tree (for debugging)
System.out.println(tree.toStringTree(parser));
// Use a visitor to process the parse tree
ConfigVisitor visitor = new ConfigVisitor();
visitor.visit(tree);
}
}
Step 4: Updated Visitor
Update the ConfigVisitor to handle the type information. Here's the updated ConfigVisitor.java:
import org.antlr.v4.runtime.tree.*;
public class ConfigVisitor extends ConfigBaseVisitor<Void> {
@Override
public Void visitProperty(ConfigParser.PropertyContext ctx) {
String key = ctx.key().getText();
String type = ctx.type().getText();
String value = ctx.value().getText();
System.out.println("Key: " + key + ", Type: " + type + ", Value: " + value);
return null;
}
}
Step 5: Compile and Run
-
Compile the generated ANTLR files and your Java code, ensuring the ANTLR runtime library is in your classpath. For example, if using Maven, include the ANTLR runtime dependency as shown in the previous example.
-
Compile the Java files:
javac -cp .:antlr4-runtime-4.13.1.jar *.java
-
Run the program:
java -cp .:antlr4-runtime-4.13.1.jar ConfigParserMain
Sample Output
For the sample input provided in the Java program, the output will look something like this:
Key: server_name, Type: string, Value: "MyServer"
Key: port, Type: int, Value: 8080
Key: debug, Type: bool, Value: true
Key: timeout, Type: float, Value: 30.5
Notes
- Type Validation: The grammar ensures that types are valid identifiers (no spaces, starts with a letter or underscore, etc.). However, it does not enforce semantic rules (e.g., ensuring
int values are integers). You can add such validation in the visitor or a separate semantic analysis phase.
- Error Handling: For production use, consider adding an error listener to handle syntax errors. For example, you can extend
BaseErrorListener to customize error messages.
- Extending Further: If you need more complex type definitions (e.g.,
list<int> or map<string, int>), you can extend the type rule to support nested or parameterized types.
This updated example provides a solid foundation for parsing configuration files with type annotations using ANTLR.