Processing a String with ANTLR4
antlr4, java, migration, string
Solution
The changes that were made are:
- `ANTLRStringStream` has been replaced with a constructor in `ANTLRInputStream` that takes a `String`
- parser rules now return a context object which has a public field named according to the `returns` clause of your rule.
So if the `dataspec` rule says "`returns [DataExtractor extractor]`", v4 the method becomes:
public static DataExtractor create(String dataspec) {
CharStream stream = new ANTLRInputStream(dataspec);
DataSpecificationLexer lexer = new DataSpecificationLexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DataSpecificationParser parser = new DataSpecificationParser(tokens);
return parser.dataspec().extractor;
}
Problem
I'm trying to convert my grammar from v3 to v4 and having some trouble finding all the right pieces. In v3 to process a String, I used: ``` public static DataExtractor create(String dataspec) { CharStream stream = new ANTLRStringStream(dataspec); DataSpecificationLexer lexer = new DataSpecificationLexer(stream); CommonTokenStream tokens = new CommonTokenStream(lexer); DataSpecificationParser parser = new DataSpecificationParser(tokens); return parser.dataspec(); } ``` How do I change this to work in v4?