1 package org.simantics.ltk.antlr;
3 import java.io.IOException;
5 import org.antlr.runtime.ANTLRInputStream;
6 import org.antlr.runtime.CharStream;
7 import org.antlr.runtime.CommonToken;
8 import org.antlr.runtime.CommonTokenStream;
9 import org.antlr.runtime.Lexer;
10 import org.antlr.runtime.Parser;
11 import org.antlr.runtime.RecognitionException;
12 import org.antlr.runtime.Token;
13 import org.antlr.runtime.tree.CommonTree;
14 import org.antlr.runtime.tree.Tree;
15 import org.simantics.ltk.ISource;
16 import org.simantics.ltk.Location;
17 import org.simantics.ltk.Problem;
19 public class ANTLRUtils {
21 public static void setUpParser(ISource source, Lexer lexer, Parser parser) throws IOException {
22 CharStream stream = new ANTLRInputStream(source.open());
23 lexer.setCharStream(stream);
24 parser.setTokenStream(new CommonTokenStream(lexer));
27 public static Location location(ISource source, Tree tree) {
28 return new Location(source,
35 public static int getStartLine(Tree tree) {
36 Token payload = ((CommonTree)tree).token;
37 int startLine = payload != null && payload.getTokenIndex() >= 0 ?
38 ((CommonToken)payload).getLine()
40 int count = tree.getChildCount();
41 for(int i=0;i<count;++i) {
42 Tree child = tree.getChild(i);
43 int temp = getStartLine(child);
50 public static int getStartIndex(Tree tree) {
51 Token payload = ((CommonTree)tree).token;
52 int startIndex = payload != null && payload.getTokenIndex() >= 0 ?
53 ((CommonToken)payload).getStartIndex()
55 int count = tree.getChildCount();
56 for(int i=0;i<count;++i) {
57 Tree child = tree.getChild(i);
58 int temp = getStartIndex(child);
65 public static int getStopIndex(Tree tree) {
66 Token payload = ((CommonTree)tree).token;
67 int stopIndex = payload != null && payload.getTokenIndex() >= 0 ?
68 ((CommonToken)payload).getStopIndex()
70 int count = tree.getChildCount();
71 for(int i=0;i<count;++i) {
72 Tree child = tree.getChild(i);
73 int temp = getStopIndex(child);
80 public static Location location(ISource source, Token token) {
81 return new Location(source,
83 ((CommonToken) token).getStartIndex(),
84 ((CommonToken) token).getStopIndex()+1
88 public static Problem error(ISource source, RecognitionException e, Parser parser) {
89 return new Problem(location(source, e.token),
90 parser.getErrorMessage(e, parser.getTokenNames()));
93 public static Problem error(ISource source, RecognitionException e, Lexer lexer) {
94 return new Problem(new Location(source, e.line, e.index, e.index+1),
95 lexer.getErrorMessage(e, lexer.getTokenNames()));