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