antlr/tool/playground/TestT.java

62 lines
1.9 KiB
Java
Raw Normal View History

2012-09-24 23:54:32 +08:00
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenFactory;
import org.antlr.v4.runtime.CommonTokenStream;
2012-09-24 23:54:32 +08:00
import org.antlr.v4.runtime.ConsoleErrorListener;
import org.antlr.v4.runtime.DefaultErrorStrategy;
2012-07-22 07:27:00 +08:00
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.ParserRuleContext;
2012-09-24 23:54:32 +08:00
import org.antlr.v4.runtime.RecognitionException;
2012-06-18 07:56:26 +08:00
import org.antlr.v4.runtime.UnbufferedCharStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class TestT {
public static void main(String[] args) throws Exception {
String inputFile = null;
if ( args.length>0 ) inputFile = args[0];
InputStream is = System.in;
if ( inputFile!=null ) {
is = new FileInputStream(inputFile);
}
CharStream input = new UnbufferedCharStream(is);
2012-06-18 07:56:26 +08:00
TLexer lex = new TLexer(input);
lex.setTokenFactory(new CommonTokenFactory(true));
2012-06-18 07:56:26 +08:00
CommonTokenStream tokens = new CommonTokenStream(lex);
TParser parser = new TParser(tokens);
2012-07-22 07:27:00 +08:00
parser.addErrorListener(new DiagnosticErrorListener());
2012-09-24 23:54:32 +08:00
ParserRuleContext tree = null;
parser.getInterpreter().setSLL(true); // try with just SLL(*)
// no errors messages or recovery wanted during first try
parser.removeErrorListeners();
parser.setErrorHandler(new BailErrorStrategy());
try {
tree = parser.s();
}
catch (RuntimeException ex) {
if (ex.getClass() == RuntimeException.class &&
ex.getCause() instanceof RecognitionException)
{
System.out.println("trying with LL(*)");
tokens.reset(); // rewind
// back to standard listeners/handlers
parser.addErrorListener(ConsoleErrorListener.INSTANCE);
parser.setErrorHandler(new DefaultErrorStrategy());
parser.getInterpreter().setSLL(false); // try full LL(*)
tree = parser.s();
}
}
2012-08-28 02:25:54 +08:00
// parser.getInterpreter().setSLL(true);
// parser.setTrace(true);
System.out.println(tree.toStringTree(parser));
2012-07-22 07:27:00 +08:00
// tree.save(parser, "/tmp/t.ps");
}
}