vast improvement in error reporting
[sbp.git] / src / edu / berkeley / sbp / chr / CharInput.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp.chr;
4 import java.io.*;
5 import java.util.*;
6 import java.lang.reflect.*;
7 import java.lang.ref.*;
8 import edu.berkeley.sbp.*;
9 import edu.berkeley.sbp.util.*;
10 import edu.berkeley.sbp.misc.*;
11 import edu.berkeley.sbp.Input.Location;
12
13 public class CharInput extends Cartesian.Input<Character> {
14     private final Reader r;
15     
16     public CharInput(String s)                { this(new StringReader(s)); }
17     public CharInput(Reader r)                { this(r, null); }
18     public CharInput(Reader r,      String s) { this.r = new BufferedReader(r); }
19     public CharInput(InputStream i)           { this(i, null); }
20     public CharInput(InputStream i, String s) { this(new InputStreamReader(i), s); }
21     
22     boolean cr = false;
23     private int count = 0;
24     private StringBuilder cache = new StringBuilder();
25     
26     public void setCacheEnabled(boolean enabled) {
27         if (!enabled) cache = null;
28         else if (cache == null) cache = new StringBuilder();
29     }
30
31     public boolean   isCR() { return cr; }
32     public Character _next() throws IOException {
33         cr = false;
34         int i = r.read();
35         if (i==-1) { /*System.err.print("\r...done       \r"); */return null; }
36         char c = (char)i;
37         if (cache != null) cache.append(c);
38         cr = c=='\n';
39         /*
40         if ((count++) % 100 == 0)
41           System.err.print("  " + count + "\r");
42         */
43         return c;
44     }
45
46     public String showRegion(Region<Character> rc) {
47         if (cache == null) return null;
48         Cartesian.Region r = (Cartesian.Region)rc;
49         int start = r.getStart().getScalar()+1;
50         int end = r.getEnd().getScalar()+1;
51         if (start < 0) start = 0;
52         if (end < start) end = start;
53         if (end > cache.length()) end = cache.length();
54         String ret;
55         if (end-start < 60) ret = cache.substring(start, end);
56         else ret = cache.substring(start, start+25) +
57                  "..." +
58                  cache.substring(end-25, end);
59         return StringUtil.escapify(ret, "\n\r");
60     }
61
62 }