comparison src/luan/lib/parser/ParseException.java @ 1111:88b5b81cad4a

move Parser to luan.lib.parser
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 02 Aug 2017 15:19:47 -0600
parents src/luan/modules/parsers/ParseException.java@38a42f437fd2
children 540e1940170f
comparison
equal deleted inserted replaced
1110:38a42f437fd2 1111:88b5b81cad4a
1 package luan.lib.parser;
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 public 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 public ParseException(Parser parser,Exception cause) {
17 this(parser,cause.getMessage(),cause);
18 }
19
20 public ParseException(Parser parser,String msg,Exception cause) {
21 super(msg,cause);
22 this.text = parser.text;
23 this.errorIndex = parser.currentIndex();
24 this.highIndex = parser.highIndex();
25 }
26
27 private class Location {
28 final int line;
29 final int pos;
30
31 Location(int index) {
32 int line = 0;
33 int i = -1;
34 while(true) {
35 int j = text.indexOf('\n',i+1);
36 if( j == -1 || j >= index )
37 break;
38 i = j;
39 line++;
40 }
41 this.line = line;
42 this.pos = index - i - 1;
43 }
44 }
45
46 private String[] lines() {
47 return text.split("\n",-1);
48 }
49
50 @Override public String getMessage() {
51 Location loc = new Location(errorIndex);
52 String line = lines()[loc.line];
53 String msg = super.getMessage() + " (line " + (loc.line+1) + ", pos " + (loc.pos+1) + ")\n";
54 StringBuilder sb = new StringBuilder(msg);
55 sb.append( line + "\n" );
56 for( int i=0; i<loc.pos; i++ ) {
57 sb.append( line.charAt(i)=='\t' ? '\t' : ' ' );
58 }
59 sb.append("^\n");
60 return sb.toString();
61 }
62 }