143c708a1441e2436d4057efc2acd5283f9201f4
[sbp.git] / src / edu / berkeley / sbp / misc / CharToken.java
1 package edu.berkeley.sbp.misc;
2 import java.io.*;
3 import java.util.*;
4 import java.lang.reflect.*;
5 import java.lang.ref.*;
6 import edu.berkeley.sbp.*;
7 import edu.berkeley.sbp.*;
8 import edu.berkeley.sbp.util.*;
9 import edu.berkeley.sbp.*;
10
11 /** an implementation of Token for streams of Java <tt>char</tt> values */
12 public class CharToken implements Token, IntegerTopology.IntegerMappable {
13
14     // Public //////////////////////////////////////////////////////////////////////////////
15
16     public static class CharRange extends Atom<CharToken> {
17         private String esc(char c) { return StringUtil.escapify(c+"", "[]-~\\\"\'"); }
18         private Topology<CharToken> t;
19         public CharRange(Topology<CharToken> t) { this.t = t; }
20         public Topology<CharToken> top() { return t; }
21         public String toString() {
22             StringBuffer sb = new StringBuffer();
23             sb.append('[');
24             Range.Set ranges = ((IntegerTopology)top()).getRanges();
25             if (ranges.size() == -1 || ranges.size() > Character.MAX_VALUE/2) {
26                 sb.append('~');
27                 ranges = ranges.complement();
28             }
29             ranges = ranges.intersect(all);
30             for(Range r : ranges) {
31                 if (r.isMinNegInf() || r.isMaxPosInf()) throw new Error("should not happen");
32                 if (r.getMin()==r.getMax()) {
33                     sb.append(esc((char)r.getMin()));
34                 } else{
35                     sb.append(esc((char)r.getMin()));
36                     sb.append('-');
37                     sb.append(esc((char)r.getMax()));
38                 }
39             }
40             sb.append(']');
41             return sb.toString();
42         }
43     }
44
45     /** returns an element matching all characters between <tt>start</tt> and <tt>end</tt>, inclusive */
46     public static Atom positiveRange(char start, char end) {
47         return new CharRange(new IntegerTopology<CharToken>(new Range.Set(new Range((int)start, (int)end))));
48     }
49
50     /** returns an element matching all characters <b>not</b> between <tt>start</tt> and <tt>end</tt>, inclusive */
51     public static Atom negativeRange(char start, char end) {
52         return new CharRange(new IntegerTopology<CharToken>(new Range.Set(new Range((int)start, (int)end)).complement().intersect(all)));
53     }
54
55     public static CharToken left(int row, int col) { return new CharToken((char)9998, 0, 0) { public String toString() { return "{"; } }; }
56     public static CharToken right(int row, int col) { return new CharToken((char)9999, 0, 0) { public String toString() { return "}"; } }; }
57     public static final Atom leftBrace  = new CharRange(new IntegerTopology<CharToken>(9998)) { public String toString() { return "{"; } };
58     public static final Atom rightBrace = new CharRange(new IntegerTopology<CharToken>(9999)) { public String toString() { return "}"; } };
59
60     private static final Range.Set all = new Range.Set(new Range(0, Character.MAX_VALUE));
61     public  static final Atom      any = new CharRange(new IntegerTopology<CharToken>(all));
62     public  static final Atom     none = new CharRange(new IntegerTopology<CharToken>());
63     public static IntegerTopology<CharToken> range(Range r) { return new IntegerTopology<CharToken>(r); }
64     public static Atom set(Range.Set r) { return new CharRange(new IntegerTopology<CharToken>(r)); }
65
66     /** returns an element which exactly matches the string given */
67     public static Element string(String s) {
68         if (s.length() == 0) return Union.epsilon;
69         final String escapified = "\""+StringUtil.escapify(s, "\"\r\n\\")+"\"";
70         Element ret;
71         if (s.length() == 1) {
72             ret =
73                 new CharRange(new IntegerTopology<CharToken>((int)s.charAt(0))) {
74                     public String toString() { return escapified; } };
75         } else {
76             Union ret2 = new Union("\""+s+"\"_str", true) {
77                     public String toString() { return escapified; } };
78             Element[] refs = new Element[s.length()];
79             for(int i=0; i<refs.length; i++) refs[i] = new CharRange(new IntegerTopology<CharToken>((int)s.charAt(i)));
80             ret2.add(Sequence.constant(refs, s, null, null));
81             ret = ret2;
82         }
83         return ret;
84     }
85
86     /** FIXME */
87     public static Topology<CharToken> top() { return new IntegerTopology<CharToken>(); }
88     public static Topology<CharToken> top(String s) throws java.text.ParseException {
89         return new IntegerTopology<CharToken>(Range.Set.parse(s));
90     }
91
92     // Private //////////////////////////////////////////////////////////////////////////////
93
94     public final char c;
95     public final Location location;
96     public CharToken(char c, int line, int col)   { this(c, new CartesianLocation(line, col)); }
97     private CharToken(char c, Location loc)        { this.c = c; this.location = loc; }
98     public String result()                         { return c+""; }
99     public Location getLocation()                  { return location; }
100     public String  toString()                      { return "\'"+StringUtil.escapify(c+"")+"\'"; }
101
102     //////////////////////////////////////////////////////////////////////////////////////////
103
104     public int toInt() { return (int)c; }
105
106     // Statics //////////////////////////////////////////////////////////////////////////////
107
108     static class CartesianLocation implements Location {
109         public final int line;
110         public final int col;
111         public String toString()            { return line + ":" + col; }
112         public CartesianLocation(int line, int col) { this.line = line; this.col = col; }
113         public String getContext() { return ""; }
114     }
115     
116     /** an implementation of Token.Stream for sequences of characters */
117     public static class Stream implements Token.Stream {
118         private final String message;
119         private final Reader r;
120         private int line  = 1;
121         private int col   = 1;
122
123         public Stream(String s)                { this(new StringReader(s)); }
124
125         public Stream(Reader r)                { this(r, null); }
126         public Stream(Reader r,      String s) { this.r = r; this.message = s; }
127
128         public Stream(InputStream i)           { this(i, null); }
129         public Stream(InputStream i, String s) { this(new InputStreamReader(i), s); }
130
131         private Line currentLine = new Line();
132         private class Line {
133             public StringBuffer line = new StringBuffer();
134         }
135
136         private class LocWrap implements Location {
137             Line myline = Stream.this.currentLine;
138             public final int line;
139             public final int col;
140             public String toString()            { return line + ":" + col; }
141             public LocWrap(int line, int col) { this.line = line; this.col = col; }
142             public String getContext() {
143                 StringBuffer spaces = new StringBuffer();
144                 for(int i=0; i<col-1; i++) spaces.append(' ');
145                 spaces.append('^');
146                 return "  " + myline.line.toString() + "\n  " + spaces.toString();
147             }
148         }
149
150         long then = 0;
151         public Token next() throws IOException {
152             int i = r.read();
153             if (i==-1) return null;
154             char c = (char)i;
155             Token ret = new CharToken(c, new LocWrap(line, col));
156             String s = line + "";
157             while(s.length() < 4) s = " " + s;
158             s = "line "+s+", col " + col;
159             long now = System.currentTimeMillis();
160             if (now-then > 10) {
161                 then = now;
162                 System.out.print("  "+(message==null?"":message)+" " + s + "                                                                      \r");
163             }
164             if (c=='\n') { 
165                 currentLine = new Line();
166                 line++;
167                 col = 1;
168             } else {
169                 currentLine.line.append(c);
170                 col++;
171             }
172             return ret;
173         }
174     }
175
176 }