[antlr-interest] Parsing multiple messages using one parser

Andy Tripp antlr at jazillian.com
Tue Feb 7 12:17:21 PST 2006


Here are my ReusableJavaParser and ReusableJavaLexer classes.
The comments refer to the relevant mailing list post.
Call resetState() and prepareNextInput() rather than creating new
parser and lexer objects.

Andy

/**
 * The <code>ReusableJavaParser</code> class allows you to create
 * one instanceofan ANTLR-generated parser that you
* can reuse over and over. see
* http://www.antlr.org/pipermail/antlr-interest/2003-April/003631.html
 *
 * @author  Andy Tripp
 */

public class ReusableJavaParser extends JavaRecognizer {

        public ReusableJavaParser(TokenStream lexer) {
                super(lexer);
        }

        public void resetState() {
                // no set method for this protected field.
                this.traceDepth = 0;
                this.getInputState().reset();
        }
}

/**
 * The <code>ReusableJavaLexer</code> class allows you to create one
 * instanceof an ANTLR-generated lexer that you
 * can reuse over and over. See
 * <a 
href="http://www.antlr.org/pipermail/antlr-interest/2003-April/003631.html">here</a>.
  *
 * @author  Andy Tripp
 */
public class ReusableJavaLexer extends JavaLexer {
        private boolean savedCaseSensitive;
        private boolean savedCaseSensitiveLiterals;

        public ReusableJavaLexer(Reader in) {
                super(in);
                savedCaseSensitive = getCaseSensitive();
                savedCaseSensitiveLiterals = getCaseSensitiveLiterals();
        }

        public void prepareNextInput(Reader in) {

                LexerSharedInputState state = new LexerSharedInputState(in);
                this.setInputState(state);

                this.setCaseSensitive(savedCaseSensitive);

                // no set method for this protected field.
                this.caseSensitiveLiterals = savedCaseSensitiveLiterals;
        }
}



More information about the antlr-interest mailing list