eliminated Parser.Table.Top
[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.
25  */
26 public class Tib implements Token.Stream<CharToken> {
27
28     public Tib(String s) throws IOException, Invalid { this(new StringReader(s)); }
29     public Tib(Reader r) throws IOException, Invalid { this(new BufferedReader(r)); }
30     public Tib(InputStream is) throws IOException, Invalid { this(new BufferedReader(new InputStreamReader(is))); }
31     public Tib(BufferedReader br) throws IOException, Invalid {
32         cur = parse(br);
33         System.out.println("\rparsing: \"" + cur.toString(0, -1) + "\"");
34     }
35
36     private Block cur;
37     private String s = null;
38     int pos = 0;
39     int spos = 0;
40
41     int _row = 0;
42     int _col = 0;
43     public Token.Location getLocation() { return new CharToken.CartesianLocation(_row, _col); }
44     public CharToken next() throws IOException {
45         if (cur==null) return null;
46         if (s != null) {
47             if (spos < s.length()) {
48                 char c = s.charAt(spos++);
49                 if (c=='\n') { _row++; _col = 0; }
50                 else _col++;
51                 return new CharToken(c);
52             }
53             s = null;
54         }
55         if (pos >= cur.size()) {
56             pos = cur.iip+1;
57             cur = cur.parent;
58             if (cur==null) return null;
59             return CharToken.right;
60         }
61         Object o = cur.child(pos++);
62         if (o instanceof String) {
63             spos = 0;
64             s = (String)o;
65             return next();
66         }
67         if (o instanceof Block) {
68             Block b = (Block)o;
69             _row = b.row;
70             _col = b.col;
71         }
72         if (((Block)o).isLiteral()) {
73             spos = 0;
74             s = ((Block.Literal)o).text();
75             return next();
76         }
77         cur = (Block)o;
78         pos = 0;
79         return CharToken.left;
80     }
81
82     public static Block parse(BufferedReader br) throws Invalid, IOException {
83         int row=0, col=0;
84         try {
85             boolean blankLine = false;
86             Block top = new Block.Root();
87             for(String s = br.readLine(); s != null; s = br.readLine()) {
88                 col = 0;
89                 while (s.length() > 0 &&
90                        s.charAt(0) == ' ' &&
91                        (!(top instanceof Block.Literal) || col < top.col)) { col++; s = s.substring(1); }
92                 if ((top instanceof Block.Literal) && col >= top.col) { top.add(s); continue; }
93                 if (s.length()==0)                                    { blankLine = true; continue; }
94                 while (col < top.col) {
95                     if (s.startsWith("{}") && top instanceof Block.Literal && ((Block.Literal)top).braceCol == col) break;
96                     blankLine = false;
97                     top = top.closeIndent();
98                 }
99                 if (s.startsWith("{}")) {
100                     int bc = col;
101                     boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
102                     s = s.substring(2);
103                     col += 2;
104                     while (s.length() > 0 && s.charAt(0) == ' ' && !(append && col >= top.col) ) { col++; s = s.substring(1); }
105                     if (append) top.add(s); else (top = new Block.Literal(top, row, col, bc)).add(s);
106                     continue;
107                 }
108                 while (s.length() > 0 && s.charAt(s.length()-1)==' ') { s = s.substring(0, s.length()-1); }
109                 if (col > top.col) top = new Block.Indent(top, row, col);
110                 else if (blankLine) { top = top.closeIndent(); top = new Block.Indent(top, row, col); }
111                 blankLine = false;
112                 for(int i=0; i<s.length(); i++) {
113                     top.add(s.charAt(i));
114                     switch(s.charAt(i)) {
115                         case '{':  top = new Block.Brace(top, row, col);   break;
116                         case '}':  top = top.closeBrace();                 break;
117                     }
118                 }
119                 top.add(' ');
120                 top.finishWord();
121             }
122             // FIXME
123             Block ret = top;
124             while (ret.parent != null) ret = ret.parent;
125             return ret;
126         } catch (InternalException ie) {
127             throw new Invalid(ie, row, col);
128         }
129     }
130
131     public static class Block {
132                       Block  parent;
133         public  final int    row;
134         public  final int    col;
135         public final int iip;
136         private final Vector children = new Vector();
137         private       String pending  = "";
138
139         public int    size() { return children.size(); }
140         public Object child(int i) { return children.elementAt(i); }
141         public boolean isLiteral() {  return false; }
142
143         protected Block(int row, int col)                {
144             this.row=row;
145             this.col=col;
146             this.iip = -1;
147             parent = null;
148         }
149         public    Block(Block parent, int row, int col)  {
150             this.row=row;
151             this.col=col;
152             this.iip = parent.size();
153             (this.parent = parent).add(this);
154         }
155
156         public void    add(String s)        { children.addElement(s); }
157         public void    add(char c)          {
158             if (c == '{' || c == '}') { finishWord(); return; }
159             if (c != ' ') { pending += c; return; }
160             if (pending.length() > 0) { finishWord(); add(" "); return; }
161             if (size()==0) return;
162             if (child(size()-1).equals(" ")) return;
163             add(" ");
164             return;
165         }
166
167         public void    add(Block  b)        { children.addElement(b); }
168         public Block   promote()            { parent.parent.replaceLast(this); return close(); }
169         public Object  lastChild()          { return children.lastElement(); }
170         public Block   lastChildAsBlock()   { return (Block)lastChild(); }
171         public void    replaceLast(Block b) { children.setElementAt(b, children.size()-1); b.parent = this; }
172
173         public void    finishWord()         { if (pending.length() > 0) { add(pending); pending = ""; } }
174
175         public Block   closeBrace()         { throw new InternalException("attempt to closeBrace() a "+getClass().getName()); }
176         public Block   closeIndent()        { throw new InternalException("attempt to closeIndent() a "+getClass().getName()); }
177         public Block   close() {
178             while(size() > 0 && child(size()-1).equals(" ")) children.setSize(children.size()-1);
179             if (size()==0) throw new InternalException("PARSER BUG: attempt to close an empty block (should never happen)");
180             if (size() > 1 || !(lastChild() instanceof Block)) return parent;
181             return lastChildAsBlock().promote();
182         }
183         public String toString() { return toString(80); }
184         public String toString(int justificationLimit) { return toString(0, 80); }
185         protected String toString(int indent, int justificationLimit) {
186             StringBuffer ret = new StringBuffer();
187             StringBuffer line = new StringBuffer();
188             for(int i=0; i<children.size(); i++) {
189                 Object o = children.elementAt(i);
190                 if (i>0 && children.elementAt(i-1) instanceof Block && justificationLimit!=-1) ret.append("\n");
191                 if (o instanceof Block) {
192                     ret.append(justify(line.toString(), indent, justificationLimit));
193                     line.setLength(0);
194                     if (justificationLimit==-1) {
195                         ret.append("{");
196                         ret.append(((Block)o).toString(indent+2, justificationLimit));
197                         ret.append("}");
198                     } else {
199                         ret.append(((Block)o).toString(indent+2, justificationLimit));
200                     }
201                 } else {
202                     line.append(o.toString());
203                 }
204             }
205             ret.append(justify(line.toString(), indent, justificationLimit));
206             return ret.toString();
207         }
208
209         private static class Root extends Block {
210             public Root() { super(0, Integer.MIN_VALUE); }
211             public Block close() { throw new InternalException("attempted to close top block"); }
212             public String toString(int justificationLimit) { return toString(-2, justificationLimit); }
213         }
214
215         private static class Brace  extends Block {
216             public Brace(Block parent, int row, int col) { super(parent, row, col); }
217             public Block closeBrace() { return super.close(); }
218         }
219     
220         private static class Indent extends Block {
221             public Indent(Block parent, int row, int col) { super(parent, row, col); }
222             public Block closeIndent() { return super.close(); }
223         }
224
225         private static class Literal extends Block {
226             private StringBuffer content = new StringBuffer();
227             public final int braceCol;
228             public    Literal(Block parent, int row, int col, int braceCol) { super(parent,row,col); this.braceCol = braceCol; }
229             public    boolean isLiteral() {  return true; }
230             public    int size() { return 1; }
231             public    Object child(int i) { return i==0 ? content.toString() : null; }
232             public    Block  close() { return parent; }
233             public    Block  closeIndent() { return close(); }
234             public    void   add(String s) { if (content.length()>0) content.append('\n'); content.append(s); }
235             public    String text() { return content.toString(); }
236             protected String toString(int indent, int justificationLimit) {
237                 StringBuffer ret = new StringBuffer();
238                 String s = content.toString();
239                 while(s.length() > 0) {
240                     int nl = s.indexOf('\n');
241                     if (nl==-1) nl = s.length();
242                     ret.append(spaces(indent));
243                     ret.append("{}  ");
244                     ret.append(s.substring(0, nl));
245                     s = s.substring(Math.min(s.length(),nl+1));
246                     ret.append('\n');
247                 }
248                 return ret.toString();
249             }
250         }
251     }
252
253
254     // Exceptions //////////////////////////////////////////////////////////////////////////////
255
256     private static class InternalException extends RuntimeException { public InternalException(String s) { super(s); } }
257     public static class Invalid extends /*IOException*/RuntimeException {
258         public Invalid(InternalException ie, int row, int col) {
259             super(ie.getMessage() + " at " + row + ":" + col);
260         }
261     }
262
263     // Testing //////////////////////////////////////////////////////////////////////////////
264
265     public static void main(String[] s) throws Exception { System.out.println(parse(new BufferedReader(new InputStreamReader(System.in))).toString(-1)); }
266     
267     // Utilities //////////////////////////////////////////////////////////////////////////////
268
269     public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
270
271     private static String justify(String s, int indent, int justificationLimit) {
272         if (s.length() == 0) return "";
273         if (justificationLimit==-1) return s;
274         StringBuffer ret = new StringBuffer();
275         while(s.length() > 0) {
276             if (s.charAt(0) == ' ') { s = s.substring(1); continue; }
277             ret.append(spaces(indent));
278             int i = s.indexOf(' ');
279             if (i==-1) i = s.length();
280             while(s.indexOf(' ', i+1) != -1 && s.indexOf(' ', i+1) < justificationLimit-indent) i = s.indexOf(' ', i+1);
281             if (s.length() + indent < justificationLimit) i = s.length();
282             ret.append(s.substring(0, i));
283             s = s.substring(i);
284             ret.append('\n');
285         }
286         return ret.toString();
287     }
288
289     // Grammar //////////////////////////////////////////////////////////////////////////////
290
291     public static class Grammar extends MetaGrammar {
292         private int anon = 0;
293         private final Element ws = Repeat.maximal0(nonTerminal("w"));
294         public Grammar() { dropAll.add(ws); }
295         public Object walk(Tree<String> tree) {
296             String head = tree.head();
297             if (tree.numChildren()==0) return super.walk(tree);
298             if ("{".equals(head)) {
299                 String s = "braced"+(anon++);
300                 Union u = nonTerminal(s);
301                 Union u2 = ((PreSequence)walk(tree, 0)).sparse(ws).buildUnion();
302                 u2.add(Sequence.singleton(new Element[] { u }, 0, null, null));
303                 return nonTerminal(s,
304                                    new PreSequence[][] {
305                                        new PreSequence[] {
306                                            new PreSequence(new Element[] { CharToken.leftBrace,
307                                                                            ws,
308                                                                            u2,
309                                                                            ws,
310                                                                            CharToken.rightBrace
311                                            })
312                                        }
313                                    },
314                                    false,
315                                    false);
316             }
317             return super.walk(tree);
318         }
319     }
320
321 }
322