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.
5 package edu.berkeley.sbp.tib;
6 //import org.ibex.util.*;
7 //import org.ibex.io.*;
11 // TODO: multiple {{ }} for superquotation
16 * A slow, ugly, inefficient, inelegant, ad-hoc parser for TIB files.
18 * Despite being inelegant, this parser keeps all internal state on
19 * the stack (the only heap objects created are those which are
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
28 public class Tib /*implements Token.Stream<TibToken>*/ {
33 public Tib(InputStream is) { this(new BufferedReader(new InputStreamReader(is))); }
34 public Tib(BufferedReader br) {
38 public Token next() throws IOException {
39 if (pos >= str.length()) return Atom.EOF;
40 return Atom.fromChar(str.charAt(pos++));
43 public static Block parse(BufferedReader br) throws Invalid {
46 boolean blankLine = false;
47 Block top = new Block.Root();
48 for(String s = br.readLine(); s != null; s = br.readLine()) {
50 while (s.length() > 0 &&
52 (!(top instanceof Block.Literal) || col < top.col)) { col++; s = s.substring(1); }
53 if ((top instanceof Block.Literal) && col >= top.col) { top.add(s); continue; }
54 if (s.length()==0) { blankLine = true; continue; }
55 while (col < top.col) {
56 if (s.startsWith("{}") && top instanceof Block.Literal && ((Block.Literal)top).braceCol == col) break;
58 top = top.closeIndent();
60 if (s.startsWith("{}")) {
62 boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
65 while (s.length() > 0 && s.charAt(0) == ' ' && !(append && col >= top.col) ) { col++; s = s.substring(1); }
66 if (append) top.add(s); else (top = new Block.Literal(top, row, col, bc)).add(s);
69 while (s.length() > 0 && s.charAt(s.length()-1)==' ') { s = s.substring(0, s.length()-1); }
70 if (col > top.col) top = new Block.Indent(top, row, col);
71 else if (blankLine) { top = top.closeIndent(); top = new Block.Indent(top, row, col); }
73 for(int i=0; i<s.length(); i++) {
76 case '{': top = new Block.Brace(top, row, col); break;
77 case '}': top = top.closeBrace(); break;
85 while (ret.parent != null) ret = ret.parent;
87 } catch (InternalException ie) {
88 throw new Invalid(ie, row, col);
92 public static class Block implements Token {
96 private final Vec children = new Vec();
97 private String pending = "";
99 public Tree<String> result() {
103 public Location getLocation() { return new Location.Cartesian(row, col); }
104 public boolean isEOF() { return false; }
106 public int size() { return children.size(); }
107 public Object child(int i) { return children.elementAt(i); }
108 public boolean isLiteral() { return false; }
110 protected Block(int row, int col) { this.row=row; this.col=col; parent = null; }
111 public Block(Block parent, int row, int col) { this.row=row; this.col=col; (this.parent = parent).add(this); }
113 public void add(String s) { children.addElement(s); }
114 public void add(char c) {
115 if (c == '{' || c == '}') { finishWord(); return; }
116 if (c != ' ') { pending += c; return; }
117 if (pending.length() > 0) { finishWord(); add(" "); return; }
118 if (size()==0) return;
119 if (child(size()-1).equals(" ")) return;
124 public void add(Block b) { children.addElement(b); }
125 public Block promote() { parent.parent.replaceLast(this); return close(); }
126 public Object lastChild() { return children.lastElement(); }
127 public Block lastChildAsBlock() { return (Block)lastChild(); }
128 public void replaceLast(Block b) { children.setElementAt(b, children.size()-1); b.parent = this; }
130 public void finishWord() { if (pending.length() > 0) { add(pending); pending = ""; } }
132 public Block closeBrace() { throw new InternalException("attempt to closeBrace() a "+getClass().getName()); }
133 public Block closeIndent() { throw new InternalException("attempt to closeIndent() a "+getClass().getName()); }
134 public Block close() {
135 while(size() > 0 && child(size()-1).equals(" ")) children.setSize(children.size()-1);
136 if (size()==0) throw new InternalException("PARSER BUG: attempt to close an empty block (should never happen)");
137 if (size() > 1 || !(lastChild() instanceof Block)) return parent;
138 return lastChildAsBlock().promote();
140 public String toString() { return toString(80); }
141 public String toString(int justificationLimit) { return toString(0, 80); }
142 protected String toString(int indent, int justificationLimit) {
143 StringBuffer ret = new StringBuffer();
144 StringBuffer line = new StringBuffer();
145 for(int i=0; i<children.size(); i++) {
146 Object o = children.elementAt(i);
147 if (i>0 && children.elementAt(i-1) instanceof Block && justificationLimit!=-1) ret.append("\n");
148 if (o instanceof Block) {
149 ret.append(justify(line.toString(), indent, justificationLimit));
151 if (justificationLimit==-1) {
153 ret.append(((Block)o).toString(indent+2, justificationLimit));
156 ret.append(((Block)o).toString(indent+2, justificationLimit));
159 line.append(o.toString());
162 ret.append(justify(line.toString(), indent, justificationLimit));
163 return ret.toString();
166 private static class Root extends Block {
167 public Root() { super(0, Integer.MIN_VALUE); }
168 public Block close() { throw new InternalException("attempted to close top block"); }
169 public String toString(int justificationLimit) { return toString(-2, justificationLimit); }
172 private static class Brace extends Block {
173 public Brace(Block parent, int row, int col) { super(parent, row, col); }
174 public Block closeBrace() { return super.close(); }
177 private static class Indent extends Block {
178 public Indent(Block parent, int row, int col) { super(parent, row, col); }
179 public Block closeIndent() { return super.close(); }
182 private static class Literal extends Block {
183 private StringBuffer content = new StringBuffer();
184 public final int braceCol;
185 public Literal(Block parent, int row, int col, int braceCol) { super(parent,row,col); this.braceCol = braceCol; }
186 public boolean isLiteral() { return true; }
187 public int size() { return 1; }
188 public Object child(int i) { return i==0 ? content.toString() : null; }
189 public Block close() { return parent; }
190 public Block closeIndent() { return close(); }
191 public void add(String s) { if (content.length()>0) content.append('\n'); content.append(s); }
192 protected String toString(int indent, int justificationLimit) {
193 StringBuffer ret = new StringBuffer();
194 String s = content.toString();
195 while(s.length() > 0) {
196 int nl = s.indexOf('\n');
197 if (nl==-1) nl = s.length();
198 ret.append(spaces(indent));
200 ret.append(s.substring(0, nl));
201 s = s.substring(Math.min(s.length(),nl+1));
204 return ret.toString();
210 // Exceptions //////////////////////////////////////////////////////////////////////////////
212 private static class InternalException extends RuntimeException { public InternalException(String s) { super(s); } }
213 public static class Invalid extends IOException {
214 public Invalid(InternalException ie, int row, int col) {
215 super(ie.getMessage() + " at " + row + ":" + col);
219 // Testing //////////////////////////////////////////////////////////////////////////////
221 public static void main(String[] s) throws Exception { System.out.println(parse(new Stream(System.in)).toString(-1)); }
223 // Utilities //////////////////////////////////////////////////////////////////////////////
225 public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
227 private static String justify(String s, int indent, int justificationLimit) {
228 if (s.length() == 0) return "";
229 if (justificationLimit==-1) return s;
230 StringBuffer ret = new StringBuffer();
231 while(s.length() > 0) {
232 if (s.charAt(0) == ' ') { s = s.substring(1); continue; }
233 ret.append(spaces(indent));
234 int i = s.indexOf(' ');
235 if (i==-1) i = s.length();
236 while(s.indexOf(' ', i+1) != -1 && s.indexOf(' ', i+1) < justificationLimit-indent) i = s.indexOf(' ', i+1);
237 if (s.length() + indent < justificationLimit) i = s.length();
238 ret.append(s.substring(0, i));
242 return ret.toString();