585
|
1 package luan.modules.parsers;
|
|
2
|
|
3
|
|
4 public final class ParseException extends Exception {
|
|
5 public final String text;
|
|
6 public final int errorIndex;
|
|
7 public final int highIndex;
|
|
8
|
|
9 ParseException(Parser parser,String msg) {
|
|
10 super(msg);
|
|
11 this.text = parser.text;
|
|
12 this.errorIndex = parser.currentIndex();
|
|
13 this.highIndex = parser.highIndex();
|
|
14 }
|
|
15
|
|
16 private class Location {
|
|
17 final int line;
|
|
18 final int pos;
|
|
19
|
|
20 Location(int index) {
|
|
21 int line = 0;
|
|
22 int i = -1;
|
|
23 while(true) {
|
|
24 int j = text.indexOf('\n',i+1);
|
|
25 if( j == -1 || j >= index )
|
|
26 break;
|
|
27 i = j;
|
|
28 line++;
|
|
29 }
|
|
30 this.line = line;
|
|
31 this.pos = index - i - 1;
|
|
32 }
|
|
33 }
|
|
34
|
|
35 private String[] lines() {
|
|
36 return text.split("\n",-1);
|
|
37 }
|
|
38
|
|
39 @Override public String getMessage() {
|
|
40 Location loc = new Location(errorIndex);
|
|
41 String line = lines()[loc.line];
|
|
42 String msg = super.getMessage() + " (line " + (loc.line+1) + ", pos " + (loc.pos+1) + ")\n";
|
|
43 StringBuilder sb = new StringBuilder(msg);
|
|
44 sb.append( line + "\n" );
|
|
45 for( int i=0; i<loc.pos; i++ ) {
|
|
46 sb.append( line.charAt(i)=='\t' ? '\t' : ' ' );
|
|
47 }
|
|
48 sb.append("^\n");
|
|
49 return sb.toString();
|
|
50 }
|
|
51 }
|