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