checkpoint
[sbp.git] / src / edu / berkeley / sbp / tib / Tib.java
1 // Copyright 2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package edu.berkeley.sbp.tib;
6 import edu.berkeley.sbp.*;
7 import edu.berkeley.sbp.misc.*;
8 import java.util.*;
9 import java.io.*;
10
11 // TODO: multiple {{ }} for superquotation
12 // TODO: strings
13 // TODO: comments
14
15 /**
16  *   A slow, ugly, inefficient, inelegant, ad-hoc parser for TIB files.
17  *
18  *   Despite being inelegant, this parser keeps all internal state on
19  *   the stack (the only heap objects created are those which are
20  *   returned).
21  *
22  *   This was written as an ad-hoc parser to facilitate
23  *   experimentation with the TIB spec.  Once the spec is finalized it
24  *   should probably be rewritten using a parser-generator, if
25  *   possible (it is unclear whether or not the associated grammar is
26  *   context-free).
27  */
28 public class Tib implements Token.Stream<CharToken> {
29
30     public Tib(String s) throws IOException, Invalid { this(new StringReader(s)); }
31     public Tib(Reader r) throws IOException, Invalid { this(new BufferedReader(r)); }
32     public Tib(InputStream is) throws IOException, Invalid { this(new BufferedReader(new InputStreamReader(is))); }
33     public Tib(BufferedReader br) throws IOException, Invalid { cur = parse(br); }
34
35     private Block cur;
36     private String s = null;
37     int pos = 0;
38     int spos = 0;
39
40     public CharToken next() throws IOException {
41         if (pos >= cur.size()) {
42             pos = cur.iip+1;
43             cur = cur.parent;
44             return CharToken.right;
45         }
46
47         if (s != null) {
48             if (spos < s.length())
49                 return new CharToken(s.charAt(spos++), 0, 0);
50             s = null;
51         }
52         Object o = cur.child(pos++);
53         if (o instanceof String) {
54             spos = 0;
55             s = (String)o;
56             return next();
57         }
58         if (((Block)o).isLiteral()) {
59             spos = 0;
60             s = ((Block.Literal)o).text();
61             return next();
62         }
63         cur = (Block)o;
64         pos = 0;
65         return CharToken.left;
66     }
67
68     public static Block parse(BufferedReader br) throws Invalid, IOException {
69         int row=0, col=0;
70         try {
71             boolean blankLine = false;
72             Block top = new Block.Root();
73             for(String s = br.readLine(); s != null; s = br.readLine()) {
74                 col = 0;
75                 while (s.length() > 0 &&
76                        s.charAt(0) == ' ' &&
77                        (!(top instanceof Block.Literal) || col < top.col)) { col++; s = s.substring(1); }
78                 if ((top instanceof Block.Literal) && col >= top.col) { top.add(s); continue; }
79                 if (s.length()==0)                                    { blankLine = true; continue; }
80                 while (col < top.col) {
81                     if (s.startsWith("{}") && top instanceof Block.Literal && ((Block.Literal)top).braceCol == col) break;
82                     blankLine = false;
83                     top = top.closeIndent();
84                 }
85                 if (s.startsWith("{}")) {
86                     int bc = col;
87                     boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
88                     s = s.substring(2);
89                     col += 2;
90                     while (s.length() > 0 && s.charAt(0) == ' ' && !(append && col >= top.col) ) { col++; s = s.substring(1); }
91                     if (append) top.add(s); else (top = new Block.Literal(top, row, col, bc)).add(s);
92                     continue;
93                 }
94                 while (s.length() > 0 && s.charAt(s.length()-1)==' ') { s = s.substring(0, s.length()-1); }
95                 if (col > top.col) top = new Block.Indent(top, row, col);
96                 else if (blankLine) { top = top.closeIndent(); top = new Block.Indent(top, row, col); }
97                 blankLine = false;
98                 for(int i=0; i<s.length(); i++) {
99                     top.add(s.charAt(i));
100                     switch(s.charAt(i)) {
101                         case '{':  top = new Block.Brace(top, row, col);   break;
102                         case '}':  top = top.closeBrace();                 break;
103                     }
104                 }
105                 top.add(' ');
106                 top.finishWord();
107             }
108             // FIXME
109             Block ret = top;
110             while (ret.parent != null) ret = ret.parent;
111             return ret;
112         } catch (InternalException ie) {
113             throw new Invalid(ie, row, col);
114         }
115     }
116
117     public static class Block /*implements Token*/ {
118                       Block  parent;
119         public  final int    row;
120         public  final int    col;
121         public final int iip;
122         private final Vector children = new Vector();
123         private       String pending  = "";
124
125         //public Location getLocation() { return /*new Location.Cartesian(row, col)*/null; }
126         public int    size() { return children.size(); }
127         public Object child(int i) { return children.elementAt(i); }
128         public boolean isLiteral() {  return false; }
129
130         protected Block(int row, int col)                {
131             this.row=row;
132             this.col=col;
133             this.iip = -1;
134             parent = null;
135         }
136         public    Block(Block parent, int row, int col)  {
137             this.row=row;
138             this.col=col;
139             this.iip = parent.size();
140             (this.parent = parent).add(this);
141         }
142
143         public void    add(String s)        { children.addElement(s); }
144         public void    add(char c)          {
145             if (c == '{' || c == '}') { finishWord(); return; }
146             if (c != ' ') { pending += c; return; }
147             if (pending.length() > 0) { finishWord(); add(" "); return; }
148             if (size()==0) return;
149             if (child(size()-1).equals(" ")) return;
150             add(" ");
151             return;
152         }
153
154         public void    add(Block  b)        { children.addElement(b); }
155         public Block   promote()            { parent.parent.replaceLast(this); return close(); }
156         public Object  lastChild()          { return children.lastElement(); }
157         public Block   lastChildAsBlock()   { return (Block)lastChild(); }
158         public void    replaceLast(Block b) { children.setElementAt(b, children.size()-1); b.parent = this; }
159
160         public void    finishWord()         { if (pending.length() > 0) { add(pending); pending = ""; } }
161
162         public Block   closeBrace()         { throw new InternalException("attempt to closeBrace() a "+getClass().getName()); }
163         public Block   closeIndent()        { throw new InternalException("attempt to closeIndent() a "+getClass().getName()); }
164         public Block   close() {
165             while(size() > 0 && child(size()-1).equals(" ")) children.setSize(children.size()-1);
166             if (size()==0) throw new InternalException("PARSER BUG: attempt to close an empty block (should never happen)");
167             if (size() > 1 || !(lastChild() instanceof Block)) return parent;
168             return lastChildAsBlock().promote();
169         }
170         public String toString() { return toString(80); }
171         public String toString(int justificationLimit) { return toString(0, 80); }
172         protected String toString(int indent, int justificationLimit) {
173             StringBuffer ret = new StringBuffer();
174             StringBuffer line = new StringBuffer();
175             for(int i=0; i<children.size(); i++) {
176                 Object o = children.elementAt(i);
177                 if (i>0 && children.elementAt(i-1) instanceof Block && justificationLimit!=-1) ret.append("\n");
178                 if (o instanceof Block) {
179                     ret.append(justify(line.toString(), indent, justificationLimit));
180                     line.setLength(0);
181                     if (justificationLimit==-1) {
182                         ret.append("{");
183                         ret.append(((Block)o).toString(indent+2, justificationLimit));
184                         ret.append("}");
185                     } else {
186                         ret.append(((Block)o).toString(indent+2, justificationLimit));
187                     }
188                 } else {
189                     line.append(o.toString());
190                 }
191             }
192             ret.append(justify(line.toString(), indent, justificationLimit));
193             return ret.toString();
194         }
195
196         private static class Root extends Block {
197             public Root() { super(0, Integer.MIN_VALUE); }
198             public Block close() { throw new InternalException("attempted to close top block"); }
199             public String toString(int justificationLimit) { return toString(-2, justificationLimit); }
200         }
201
202         private static class Brace  extends Block {
203             public Brace(Block parent, int row, int col) { super(parent, row, col); }
204             public Block closeBrace() { return super.close(); }
205         }
206     
207         private static class Indent extends Block {
208             public Indent(Block parent, int row, int col) { super(parent, row, col); }
209             public Block closeIndent() { return super.close(); }
210         }
211
212         private static class Literal extends Block {
213             private StringBuffer content = new StringBuffer();
214             public final int braceCol;
215             public    Literal(Block parent, int row, int col, int braceCol) { super(parent,row,col); this.braceCol = braceCol; }
216             public    boolean isLiteral() {  return true; }
217             public    int size() { return 1; }
218             public    Object child(int i) { return i==0 ? content.toString() : null; }
219             public    Block  close() { return parent; }
220             public    Block  closeIndent() { return close(); }
221             public    void   add(String s) { if (content.length()>0) content.append('\n'); content.append(s); }
222             public    String text() { return content.toString(); }
223             protected String toString(int indent, int justificationLimit) {
224                 StringBuffer ret = new StringBuffer();
225                 String s = content.toString();
226                 while(s.length() > 0) {
227                     int nl = s.indexOf('\n');
228                     if (nl==-1) nl = s.length();
229                     ret.append(spaces(indent));
230                     ret.append("{}  ");
231                     ret.append(s.substring(0, nl));
232                     s = s.substring(Math.min(s.length(),nl+1));
233                     ret.append('\n');
234                 }
235                 return ret.toString();
236             }
237         }
238     }
239
240
241     // Exceptions //////////////////////////////////////////////////////////////////////////////
242
243     private static class InternalException extends RuntimeException { public InternalException(String s) { super(s); } }
244     public static class Invalid extends /*IOException*/RuntimeException {
245         public Invalid(InternalException ie, int row, int col) {
246             super(ie.getMessage() + " at " + row + ":" + col);
247         }
248     }
249
250     // Testing //////////////////////////////////////////////////////////////////////////////
251
252     public static void main(String[] s) throws Exception { System.out.println(parse(new BufferedReader(new InputStreamReader(System.in))).toString(-1)); }
253     
254     // Utilities //////////////////////////////////////////////////////////////////////////////
255
256     public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
257
258     private static String justify(String s, int indent, int justificationLimit) {
259         if (s.length() == 0) return "";
260         if (justificationLimit==-1) return s;
261         StringBuffer ret = new StringBuffer();
262         while(s.length() > 0) {
263             if (s.charAt(0) == ' ') { s = s.substring(1); continue; }
264             ret.append(spaces(indent));
265             int i = s.indexOf(' ');
266             if (i==-1) i = s.length();
267             while(s.indexOf(' ', i+1) != -1 && s.indexOf(' ', i+1) < justificationLimit-indent) i = s.indexOf(' ', i+1);
268             if (s.length() + indent < justificationLimit) i = s.length();
269             ret.append(s.substring(0, i));
270             s = s.substring(i);
271             ret.append('\n');
272         }
273         return ret.toString();
274     }
275
276 }
277