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<TreeToken<String>>*/ {
30 public final String str;
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); }
37 public Token next() throws IOException {
38 if (pos >= str.length()) return Atom.EOF;
39 return Atom.fromChar(str.charAt(pos++));
42 public static Block parse(BufferedReader br) throws Invalid {
45 boolean blankLine = false;
46 Block top = new Block.Root();
47 for(String s = br.readLine(); s != null; s = br.readLine()) {
49 while (s.length() > 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;
57 top = top.closeIndent();
59 if (s.startsWith("{}")) {
61 boolean append = top instanceof Block.Literal && ((Block.Literal)top).braceCol == bc;
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);
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); }
72 for(int i=0; i<s.length(); i++) {
75 case '{': top = new Block.Brace(top, row, col); break;
76 case '}': top = top.closeBrace(); break;
84 while (ret.parent != null) ret = ret.parent;
86 } catch (InternalException ie) {
87 throw new Invalid(ie, row, col);
91 public static class Block implements Token {
95 private final Vec children = new Vec();
96 private String pending = "";
98 public Tree<String> result() {
102 public Location getLocation() { return new Location.Cartesian(row, col); }
103 public boolean isEOF() { return false; }
105 public int size() { return children.size(); }
106 public Object child(int i) { return children.elementAt(i); }
107 public boolean isLiteral() { return false; }
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); }
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;
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; }
129 public void finishWord() { if (pending.length() > 0) { add(pending); pending = ""; } }
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();
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));
150 if (justificationLimit==-1) {
152 ret.append(((Block)o).toString(indent+2, justificationLimit));
155 ret.append(((Block)o).toString(indent+2, justificationLimit));
158 line.append(o.toString());
161 ret.append(justify(line.toString(), indent, justificationLimit));
162 return ret.toString();
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); }
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(); }
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(); }
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));
199 ret.append(s.substring(0, nl));
200 s = s.substring(Math.min(s.length(),nl+1));
203 return ret.toString();
209 // Exceptions //////////////////////////////////////////////////////////////////////////////
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);
218 // Testing //////////////////////////////////////////////////////////////////////////////
220 public static void main(String[] s) throws Exception { System.out.println(parse(new Stream(System.in)).toString(-1)); }
222 // Utilities //////////////////////////////////////////////////////////////////////////////
224 public static String spaces(int i) { if (i<=0) return ""; return " " + spaces(i-1); }
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));
241 return ret.toString();