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 edu.berkeley.sbp.*;
7 import edu.berkeley.sbp.misc.*;
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<CharToken> {
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); }
36 private String s = null;
40 public CharToken next() throws IOException {
41 if (pos >= cur.size()) {
44 return CharToken.right;
48 if (spos < s.length())
49 return new CharToken(s.charAt(spos++), 0, 0);
52 Object o = cur.child(pos++);
53 if (o instanceof String) {
58 if (((Block)o).isLiteral()) {
60 s = ((Block.Literal)o).text();
65 return CharToken.left;
68 public static Block parse(BufferedReader br) throws Invalid, IOException {
71 boolean blankLine = false;
72 Block top = new Block.Root();
73 for(String s = br.readLine(); s != null; s = br.readLine()) {
75 while (s.length() > 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;
83 top = top.closeIndent();
85 if (s.startsWith("{}")) {
87 boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
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);
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); }
98 for(int i=0; i<s.length(); i++) {
100 switch(s.charAt(i)) {
101 case '{': top = new Block.Brace(top, row, col); break;
102 case '}': top = top.closeBrace(); break;
110 while (ret.parent != null) ret = ret.parent;
112 } catch (InternalException ie) {
113 throw new Invalid(ie, row, col);
117 public static class Block /*implements Token*/ {
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 = "";
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; }
130 protected Block(int row, int col) {
136 public Block(Block parent, int row, int col) {
139 this.iip = parent.size();
140 (this.parent = parent).add(this);
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;
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; }
160 public void finishWord() { if (pending.length() > 0) { add(pending); pending = ""; } }
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();
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));
181 if (justificationLimit==-1) {
183 ret.append(((Block)o).toString(indent+2, justificationLimit));
186 ret.append(((Block)o).toString(indent+2, justificationLimit));
189 line.append(o.toString());
192 ret.append(justify(line.toString(), indent, justificationLimit));
193 return ret.toString();
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); }
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(); }
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(); }
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));
231 ret.append(s.substring(0, nl));
232 s = s.substring(Math.min(s.length(),nl+1));
235 return ret.toString();
241 // Exceptions //////////////////////////////////////////////////////////////////////////////
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);
250 // Testing //////////////////////////////////////////////////////////////////////////////
252 public static void main(String[] s) throws Exception { System.out.println(parse(new BufferedReader(new InputStreamReader(System.in))).toString(-1)); }
254 // Utilities //////////////////////////////////////////////////////////////////////////////
256 public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
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));
273 return ret.toString();