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 org.ibex.util.*;
7 //import org.ibex.io.*;
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<TreeToken<String>>*/ {
29     /*
30     public final String str;
31
32     public Tib(String s) { this(new StringReader(s)); }
33     public Tib(Reader r) { this(new BufferedReader(r)); }
34     public Tib(InputStream is) { this(new BufferedReader(new InputStreamReader(is))); }
35     public Tib(BufferedReader br) { str = parse(br).toString(0,-1); }
36
37     public Token next() throws IOException {
38         if (pos >= str.length()) return Atom.EOF;
39         return Atom.fromChar(str.charAt(pos++));
40     }
41
42     public static Block parse(BufferedReader br) throws Invalid {
43         int row=0, col=0;
44         try {
45             boolean blankLine = false;
46             Block top = new Block.Root();
47             for(String s = br.readLine(); s != null; s = br.readLine()) {
48                 col = 0;
49                 while (s.length() > 0 &&
50                        s.charAt(0) == ' ' &&
51                        (!(top instanceof Block.Literal) || col < top.col)) { col++; s = s.substring(1); }
52                 if ((top instanceof Block.Literal) && col >= top.col) { top.add(s); continue; }
53                 if (s.length()==0)                                    { blankLine = true; continue; }
54                 while (col < top.col) {
55                     if (s.startsWith("{}") && top instanceof Block.Literal && ((Block.Literal)top).braceCol == col) break;
56                     blankLine = false;
57                     top = top.closeIndent();
58                 }
59                 if (s.startsWith("{}")) {
60                     int bc = col;
61                     boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
62                     s = s.substring(2);
63                     col += 2;
64                     while (s.length() > 0 && s.charAt(0) == ' ' && !(append && col >= top.col) ) { col++; s = s.substring(1); }
65                     if (append) top.add(s); else (top = new Block.Literal(top, row, col, bc)).add(s);
66                     continue;
67                 }
68                 while (s.length() > 0 && s.charAt(s.length()-1)==' ') { s = s.substring(0, s.length()-1); }
69                 if (col > top.col) top = new Block.Indent(top, row, col);
70                 else if (blankLine) { top = top.closeIndent(); top = new Block.Indent(top, row, col); }
71                 blankLine = false;
72                 for(int i=0; i<s.length(); i++) {
73                     top.add(s.charAt(i));
74                     switch(s.charAt(i)) {
75                         case '{':  top = new Block.Brace(top, row, col);   break;
76                         case '}':  top = top.closeBrace();                 break;
77                     }
78                 }
79                 top.add(' ');
80                 top.finishWord();
81             }
82             // FIXME
83             Block ret = top;
84             while (ret.parent != null) ret = ret.parent;
85             return ret;
86         } catch (InternalException ie) {
87             throw new Invalid(ie, row, col);
88         }
89     }
90
91     public static class Block implements Token {
92                       Block  parent;
93         public  final int    row;
94         public  final int    col;
95         private final Vec    children = new Vec();
96         private       String pending  = "";
97
98         public Tree<String> result() {
99             // FIXME
100         }
101
102         public Location getLocation() { return new Location.Cartesian(row, col); }
103         public boolean isEOF() { return false; }
104
105         public int    size() { return children.size(); }
106         public Object child(int i) { return children.elementAt(i); }
107         public boolean isLiteral() {  return false; }
108
109         protected Block(int row, int col)                { this.row=row; this.col=col; parent = null; }
110         public    Block(Block parent, int row, int col)  { this.row=row; this.col=col; (this.parent = parent).add(this); }
111
112         public void    add(String s)        { children.addElement(s); }
113         public void    add(char c)          {
114             if (c == '{' || c == '}') { finishWord(); return; }
115             if (c != ' ') { pending += c; return; }
116             if (pending.length() > 0) { finishWord(); add(" "); return; }
117             if (size()==0) return;
118             if (child(size()-1).equals(" ")) return;
119             add(" ");
120             return;
121         }
122
123         public void    add(Block  b)        { children.addElement(b); }
124         public Block   promote()            { parent.parent.replaceLast(this); return close(); }
125         public Object  lastChild()          { return children.lastElement(); }
126         public Block   lastChildAsBlock()   { return (Block)lastChild(); }
127         public void    replaceLast(Block b) { children.setElementAt(b, children.size()-1); b.parent = this; }
128
129         public void    finishWord()         { if (pending.length() > 0) { add(pending); pending = ""; } }
130
131         public Block   closeBrace()         { throw new InternalException("attempt to closeBrace() a "+getClass().getName()); }
132         public Block   closeIndent()        { throw new InternalException("attempt to closeIndent() a "+getClass().getName()); }
133         public Block   close() {
134             while(size() > 0 && child(size()-1).equals(" ")) children.setSize(children.size()-1);
135             if (size()==0) throw new InternalException("PARSER BUG: attempt to close an empty block (should never happen)");
136             if (size() > 1 || !(lastChild() instanceof Block)) return parent;
137             return lastChildAsBlock().promote();
138         }
139         public String toString() { return toString(80); }
140         public String toString(int justificationLimit) { return toString(0, 80); }
141         protected String toString(int indent, int justificationLimit) {
142             StringBuffer ret = new StringBuffer();
143             StringBuffer line = new StringBuffer();
144             for(int i=0; i<children.size(); i++) {
145                 Object o = children.elementAt(i);
146                 if (i>0 && children.elementAt(i-1) instanceof Block && justificationLimit!=-1) ret.append("\n");
147                 if (o instanceof Block) {
148                     ret.append(justify(line.toString(), indent, justificationLimit));
149                     line.setLength(0);
150                     if (justificationLimit==-1) {
151                         ret.append("{");
152                         ret.append(((Block)o).toString(indent+2, justificationLimit));
153                         ret.append("}");
154                     } else {
155                         ret.append(((Block)o).toString(indent+2, justificationLimit));
156                     }
157                 } else {
158                     line.append(o.toString());
159                 }
160             }
161             ret.append(justify(line.toString(), indent, justificationLimit));
162             return ret.toString();
163         }
164
165         private static class Root extends Block {
166             public Root() { super(0, Integer.MIN_VALUE); }
167             public Block close() { throw new InternalException("attempted to close top block"); }
168             public String toString(int justificationLimit) { return toString(-2, justificationLimit); }
169         }
170
171         private static class Brace  extends Block {
172             public Brace(Block parent, int row, int col) { super(parent, row, col); }
173             public Block closeBrace() { return super.close(); }
174         }
175     
176         private static class Indent extends Block {
177             public Indent(Block parent, int row, int col) { super(parent, row, col); }
178             public Block closeIndent() { return super.close(); }
179         }
180
181         private static class Literal extends Block {
182             private StringBuffer content = new StringBuffer();
183             public final int braceCol;
184             public    Literal(Block parent, int row, int col, int braceCol) { super(parent,row,col); this.braceCol = braceCol; }
185             public    boolean isLiteral() {  return true; }
186             public    int size() { return 1; }
187             public    Object child(int i) { return i==0 ? content.toString() : null; }
188             public    Block  close() { return parent; }
189             public    Block  closeIndent() { return close(); }
190             public    void   add(String s) { if (content.length()>0) content.append('\n'); content.append(s); }
191             protected String toString(int indent, int justificationLimit) {
192                 StringBuffer ret = new StringBuffer();
193                 String s = content.toString();
194                 while(s.length() > 0) {
195                     int nl = s.indexOf('\n');
196                     if (nl==-1) nl = s.length();
197                     ret.append(spaces(indent));
198                     ret.append("{}  ");
199                     ret.append(s.substring(0, nl));
200                     s = s.substring(Math.min(s.length(),nl+1));
201                     ret.append('\n');
202                 }
203                 return ret.toString();
204             }
205         }
206     }
207
208
209     // Exceptions //////////////////////////////////////////////////////////////////////////////
210
211     private static class InternalException extends RuntimeException { public InternalException(String s) { super(s); } }
212     public static class Invalid extends IOException {
213         public Invalid(InternalException ie, int row, int col) {
214             super(ie.getMessage() + " at " + row + ":" + col);
215         }
216     }
217
218     // Testing //////////////////////////////////////////////////////////////////////////////
219
220     public static void main(String[] s) throws Exception { System.out.println(parse(new Stream(System.in)).toString(-1)); }
221     
222     // Utilities //////////////////////////////////////////////////////////////////////////////
223
224     public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
225
226     private static String justify(String s, int indent, int justificationLimit) {
227         if (s.length() == 0) return "";
228         if (justificationLimit==-1) return s;
229         StringBuffer ret = new StringBuffer();
230         while(s.length() > 0) {
231             if (s.charAt(0) == ' ') { s = s.substring(1); continue; }
232             ret.append(spaces(indent));
233             int i = s.indexOf(' ');
234             if (i==-1) i = s.length();
235             while(s.indexOf(' ', i+1) != -1 && s.indexOf(' ', i+1) < justificationLimit-indent) i = s.indexOf(' ', i+1);
236             if (s.length() + indent < justificationLimit) i = s.length();
237             ret.append(s.substring(0, i));
238             s = s.substring(i);
239             ret.append('\n');
240         }
241         return ret.toString();
242     }
243     */
244 }
245