got new tib tokenizer going
[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         this.br = br;
33         istack.add(-1);
34         //cur = parse(br);
35         //System.out.println("\rparsing: \"" + cur.toString(0, -1) + "\"");
36     }
37
38     private Block cur;
39     private String s = "";
40     int pos = 0;
41     int spos = 0;
42
43     int _row = 1;
44     int _col = 0;
45     public Token.Location getLocation() { return new CharToken.CartesianLocation(_row, _col); }
46     private BufferedReader br;
47
48     boolean waiting = false;
49     char waitingChar = ' ';
50     boolean indenting = true;
51     int indentation = 0;
52     private ArrayList<Integer> istack = new ArrayList<Integer>();
53     public CharToken next(int numstates) throws IOException {
54         CharToken ret = nextc(numstates);
55         if      (ret==CharToken.left)  System.out.print("\033[31m{\033[0m");
56         else if (ret==CharToken.right) System.out.print("\033[31m}\033[0m");
57         else if (ret==null) return null;
58         else System.out.print(ret.c);
59         return ret;
60     }
61
62     CharToken waitingBrace = null;
63     public CharToken nextc(int numstates) throws IOException {
64         char c;
65         if (waitingBrace != null) {
66             CharToken ret = waitingBrace;
67             waitingBrace = null;
68             return ret;
69         }
70         if (waiting) {
71             waiting = false;
72             c = waitingChar;
73         } else {
74             int i = br.read();
75             if (i==-1) {
76                 if (istack.size() > 1) {
77                     istack.remove(istack.size()-1);
78                     return CharToken.right;
79                 }
80                 return null;
81             }
82             c = (char)i;
83         }
84         if (c=='\n') { _row++; _col=0; }
85         else         _col++;
86         if (indenting) {
87             if (c==' ') { indentation++; return done(c); }
88             if (c=='\n') { indentation = 0; if (blank) return nextc(numstates); blank = true; waiting = true; waitingChar='\n'; return new CharToken('\n'); }
89             int last = istack.size()==0 ? -1 : istack.get(istack.size()-1);
90             if (indentation==last) {
91                 if (blank) {
92                     indenting = false;
93                     waitingChar = c;
94                     waiting = true;
95                     waitingBrace = CharToken.left;
96                     return CharToken.right;
97                     //return nextc(numstates);
98                 }
99                 blank = false;
100                 indenting = false;
101                 return done(c);
102             }
103             blank = false;
104             waitingChar = c;
105             waiting = true;
106             if (indentation > last) {
107                 indenting = false;
108                 istack.add(indentation);
109                 System.out.print("\033[31m+"+indentation+"+\033[0m");
110                 return CharToken.left;
111             } else /*if (indentation < last)*/ {
112                 istack.remove(istack.size()-1);
113                 System.out.print("\033[31m-"+last+"-\033[0m");
114                 blank = true;
115                 return CharToken.right;
116             }
117         } else {
118             blank = false;
119             if (c=='\n') { indenting=true; indentation = 0; }
120             return done(c);
121         }
122     }
123     public CharToken done(char c) {
124         switch(c) {
125             case '{': return CharToken.left;
126             case '}': return CharToken.right;
127             default: return new CharToken(c);
128         }
129     }
130     boolean blank = false;
131     /*
132     public CharToken next(int numstates) throws IOException {
133         if (cur==null) return null;
134         if (s != null) {
135             if (spos < s.length()) {
136                 char c = s.charAt(spos++);
137                 if (c=='\n') { _row++; _col = 0; }
138                 else _col++;
139                 return new CharToken(c);
140             }
141             s = null;
142         }
143         if (pos >= cur.size()) {
144             pos = cur.iip+1;
145             _row = cur.endrow;
146             _col = cur.endcol;
147             cur = cur.parent;
148             if (cur==null) return null;
149             return CharToken.right;
150         }
151         Object o = cur.child(pos++);
152         if (o instanceof String) {
153             spos = 0;
154             s = (String)o;
155             return next(numstates);
156         }
157         if (o instanceof Block) {
158             Block b = (Block)o;
159             _row = b.row;
160             _col = b.col;
161         }
162         if (((Block)o).isLiteral()) {
163             spos = 0;
164             s = ((Block.Literal)o).text();
165             return next(numstates);
166         }
167         cur = (Block)o;
168         pos = 0;
169         return CharToken.left;
170     }
171     */
172     public static Block parse(BufferedReader br) throws Invalid, IOException {
173         int row=0, col=0;
174         try {
175             boolean blankLine = false;
176             Block top = new Block.Root();
177             for(String s = br.readLine(); s != null; s = br.readLine()) {
178                 row++;
179                 col=0;
180                 while (s.length() > 0 &&
181                        s.charAt(0) == ' ' &&
182                        (!(top instanceof Block.Literal) || col < top.col)) { col++; s = s.substring(1); }
183                 if ((top instanceof Block.Literal) && col >= top.col) { top.add(s); continue; }
184                 if (s.length()==0)                                    { blankLine = true; continue; }
185                 while (col < top.col) {
186                     if (s.startsWith("{}") && top instanceof Block.Literal && ((Block.Literal)top).braceCol == col) break;
187                     blankLine = false;
188                     top.endrow = row;
189                     top.endcol = col;
190                     top = top.closeIndent();
191                 }
192                 if (s.startsWith("{}")) {
193                     int bc = col;
194                     boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
195                     s = s.substring(2);
196                     col += 2;
197                     while (s.length() > 0 && s.charAt(0) == ' ' && !(append && col >= top.col) ) { col++; s = s.substring(1); }
198                     if (append) top.add(s); else (top = new Block.Literal(top, row, col, bc)).add(s);
199                     continue;
200                 }
201                 while (s.length() > 0 && s.charAt(s.length()-1)==' ') { s = s.substring(0, s.length()-1); }
202                 if (col > top.col) top = new Block.Indent(top, row, col);
203                 else if (blankLine) { top.endrow=row; top.endcol=col; top = top.closeIndent(); top = new Block.Indent(top, row, col); }
204                 blankLine = false;
205                 for(int i=0; i<s.length(); i++) {
206                     top.add(s.charAt(i));
207                     switch(s.charAt(i)) {
208                         case '{':  top = new Block.Brace(top, row, col);   break;
209                         case '}':  top.endrow=row; top.endcol=col; top = top.closeBrace();                 break;
210                     }
211                 }
212                 top.add('\n');
213                 top.finishWord();
214             }
215             // FIXME
216             Block ret = top;
217             while (ret.parent != null) ret = ret.parent;
218             return ret;
219         } catch (InternalException ie) {
220             throw new Invalid(ie, row, col);
221         }
222     }
223
224     public static class Block {
225                       Block  parent;
226         public  final int    row;
227         public  final int    col;
228         public   int    endrow;
229         public   int    endcol;
230         public final int iip;
231         private final Vector children = new Vector();
232         private       String pending  = "";
233
234         public int    size() { return children.size(); }
235         public Object child(int i) { return children.elementAt(i); }
236         public boolean isLiteral() {  return false; }
237
238         protected Block(int row, int col)                {
239             this.row=row;
240             this.col=col;
241             this.iip = -1;
242             parent = null;
243         }
244         public    Block(Block parent, int row, int col)  {
245             this.row=row;
246             this.col=col;
247             this.iip = parent.size();
248             (this.parent = parent).add(this);
249         }
250
251         public void    add(String s)        { children.addElement(s); }
252         public void    add(char c)          {
253             if (c == '{' || c == '}') { finishWord(); return; }
254             if (c != ' ') { pending += c; return; }
255             if (pending.length() > 0) { finishWord(); add(" "); return; }
256             if (size()==0) return;
257             if (child(size()-1).equals(" ")) return;
258             add(" ");
259             return;
260         }
261
262         public void    add(Block  b)        { children.addElement(b); }
263         public Block   promote()            { parent.parent.replaceLast(this); return close(); }
264         public Object  lastChild()          { return children.lastElement(); }
265         public Block   lastChildAsBlock()   { return (Block)lastChild(); }
266         public void    replaceLast(Block b) { children.setElementAt(b, children.size()-1); b.parent = this; }
267
268         public void    finishWord()         { if (pending.length() > 0) { add(pending); pending = ""; } }
269
270         public Block   closeBrace()         { throw new InternalException("attempt to closeBrace() a "+getClass().getName()); }
271         public Block   closeIndent()        { throw new InternalException("attempt to closeIndent() a "+getClass().getName()); }
272         public Block   close() {
273             while(size() > 0 && child(size()-1).equals(" ")) children.setSize(children.size()-1);
274             if (size()==0) throw new InternalException("PARSER BUG: attempt to close an empty block (should never happen)");
275             if (size() > 1 || !(lastChild() instanceof Block)) return parent;
276             return lastChildAsBlock().promote();
277         }
278         public String toString() { return toString(80); }
279         public String toString(int justificationLimit) { return toString(0, 80); }
280         protected String toString(int indent, int justificationLimit) {
281             StringBuffer ret = new StringBuffer();
282             StringBuffer line = new StringBuffer();
283             for(int i=0; i<children.size(); i++) {
284                 Object o = children.elementAt(i);
285                 if (i>0 && children.elementAt(i-1) instanceof Block && justificationLimit!=-1) ret.append("\n");
286                 if (o instanceof Block) {
287                     ret.append(justify(line.toString(), indent, justificationLimit));
288                     line.setLength(0);
289                     if (justificationLimit==-1) {
290                         ret.append("{");
291                         ret.append(((Block)o).toString(indent+2, justificationLimit));
292                         ret.append("}");
293                     } else {
294                         ret.append(((Block)o).toString(indent+2, justificationLimit));
295                     }
296                 } else {
297                     line.append(o.toString());
298                 }
299             }
300             ret.append(justify(line.toString(), indent, justificationLimit));
301             return ret.toString();
302         }
303
304         private static class Root extends Block {
305             public Root() { super(0, Integer.MIN_VALUE); }
306             public Block close() { throw new InternalException("attempted to close top block"); }
307             public String toString(int justificationLimit) { return toString(-2, justificationLimit); }
308         }
309
310         private static class Brace  extends Block {
311             public Brace(Block parent, int row, int col) { super(parent, row, col); }
312             public Block closeBrace() { return super.close(); }
313         }
314     
315         private static class Indent extends Block {
316             public Indent(Block parent, int row, int col) { super(parent, row, col); }
317             public Block closeIndent() { return super.close(); }
318         }
319
320         private static class Literal extends Block {
321             private StringBuffer content = new StringBuffer();
322             public final int braceCol;
323             public    Literal(Block parent, int row, int col, int braceCol) { super(parent,row,col); this.braceCol = braceCol; }
324             public    boolean isLiteral() {  return true; }
325             public    int size() { return 1; }
326             public    Object child(int i) { return i==0 ? content.toString() : null; }
327             public    Block  close() { return parent; }
328             public    Block  closeIndent() { return close(); }
329             public    void   add(String s) { if (content.length()>0) content.append('\n'); content.append(s); }
330             public    String text() { return content.toString(); }
331             protected String toString(int indent, int justificationLimit) {
332                 StringBuffer ret = new StringBuffer();
333                 String s = content.toString();
334                 while(s.length() > 0) {
335                     int nl = s.indexOf('\n');
336                     if (nl==-1) nl = s.length();
337                     ret.append(spaces(indent));
338                     ret.append("{}  ");
339                     ret.append(s.substring(0, nl));
340                     s = s.substring(Math.min(s.length(),nl+1));
341                     ret.append('\n');
342                 }
343                 return ret.toString();
344             }
345         }
346     }
347
348
349     // Exceptions //////////////////////////////////////////////////////////////////////////////
350
351     private static class InternalException extends RuntimeException { public InternalException(String s) { super(s); } }
352     public static class Invalid extends /*IOException*/RuntimeException {
353         public Invalid(InternalException ie, int row, int col) {
354             super(ie.getMessage() + " at " + row + ":" + col);
355         }
356     }
357
358     // Testing //////////////////////////////////////////////////////////////////////////////
359
360     public static void main(String[] s) throws Exception {
361         System.out.println(parse(new BufferedReader(new InputStreamReader(System.in))).toString(-1)); }
362     
363     // Utilities //////////////////////////////////////////////////////////////////////////////
364
365     public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
366
367     private static String justify(String s, int indent, int justificationLimit) {
368         if (s.length() == 0) return "";
369         if (justificationLimit==-1) return s;
370         StringBuffer ret = new StringBuffer();
371         while(s.length() > 0) {
372             if (s.charAt(0) == ' ') { s = s.substring(1); continue; }
373             ret.append(spaces(indent));
374             int i = s.indexOf(' ');
375             if (i==-1) i = s.length();
376             while(s.indexOf(' ', i+1) != -1 && s.indexOf(' ', i+1) < justificationLimit-indent) i = s.indexOf(' ', i+1);
377             if (s.length() + indent < justificationLimit) i = s.length();
378             ret.append(s.substring(0, i));
379             s = s.substring(i);
380             ret.append('\n');
381         }
382         return ret.toString();
383     }
384
385     // Grammar //////////////////////////////////////////////////////////////////////////////
386
387     public static class Grammar extends MetaGrammar {
388         private int anon = 0;
389         private final Element ws = Repeat.maximal0(nonTerminal("w"));
390         public Grammar() { dropAll.add(ws); }
391         public Object walk(Tree<String> tree) {
392             String head = tree.head();
393             if (tree.numChildren()==0) return super.walk(tree);
394             if ("{".equals(head)) {
395                 String s = "braced"+(anon++);
396                 Union u = nonTerminal(s);
397                 Union u2 = ((PreSequence)walk(tree, 0)).sparse(ws).buildUnion();
398                 u2.add(Sequence.singleton(new Element[] { u }, 0, null, null));
399                 return nonTerminal(s,
400                                    new PreSequence[][] {
401                                        new PreSequence[] {
402                                            new PreSequence(new Element[] { CharToken.leftBrace,
403                                                                            ws,
404                                                                            u2,
405                                                                            ws,
406                                                                            CharToken.rightBrace
407                                            })
408                                        }
409                                    },
410                                    false,
411                                    false);
412             }
413             return super.walk(tree);
414         }
415     }
416
417 }
418