KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > visit > StringPrettyPrinter


1 package polyglot.visit;
2
3 import polyglot.ast.*;
4 import polyglot.frontend.*;
5 import polyglot.util.*;
6
7 import java.io.*;
8 import java.util.*;
9
10 /**
11  * A PrettyPrinter generates output code from the processed AST.
12  *
13  * To use:
14  * new PrettyPrinter().printAst(node, new CodeWriter(out));
15  */

16 public class StringPrettyPrinter extends PrettyPrinter
17 {
18     int maxdepth;
19     int depth;
20
21     public StringPrettyPrinter(int maxdepth) {
22         this.maxdepth = maxdepth;
23         this.depth = 0;
24     }
25
26     public void print(Node parent, Node child, CodeWriter w) {
27         depth++;
28
29         if (depth < maxdepth) {
30             super.print(parent, child, w);
31         }
32         else {
33             w.write("...");
34         }
35
36         depth--;
37     }
38
39     public String JavaDoc toString(Node ast) {
40         StringCodeWriter w = new StringCodeWriter(new CharArrayWriter());
41
42         print(null, ast, w);
43
44         try {
45             w.flush();
46         }
47         catch (IOException e) {
48         }
49
50         return w.toString();
51     }
52
53     public static class StringCodeWriter extends CodeWriter {
54         CharArrayWriter w;
55
56         public StringCodeWriter(CharArrayWriter w) {
57             super(w, 1000);
58             this.w = w;
59         }
60
61         public void write(String JavaDoc s) {
62             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
63             char last = 0;
64
65             // remove duplicate spaces
66
for (int i = 0; i < s.length(); i++) {
67                 char c = s.charAt(i);
68                 if (Character.isSpaceChar(c) && Character.isSpaceChar(last))
69                     continue;
70                 sb.append(c);
71                 last = c;
72             }
73
74             super.write(sb.toString());
75         }
76
77         public void newline(int n) { super.write(" "); }
78         public void allowBreak(int n) { super.write(" "); }
79         public void allowBreak(int n, String JavaDoc alt) { super.write(alt); }
80         public void begin(int n) { super.begin(0); }
81
82         public String JavaDoc toString() {
83             return w.toString();
84         }
85     }
86 }
87
Popular Tags