1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package org.objectweb.fractal.cecilia.adl.file;
25
26
27
28
29 public final class CodeWriter {
30
31 private static final int INDENTATION_SPACE = 2;
32 private final String producerName;
33 private int indentation = 0;
34 private boolean newLine = true;
35 private final StringBuilder buff = new StringBuilder();
36
37
38
39
40
41
42 public CodeWriter(final String producerName) {
43 this.producerName = producerName;
44 append("//+ Beginning of code produced by ").append(producerName).endl();
45 }
46
47
48
49
50 public CodeWriter() {
51 this.producerName = null;
52 }
53
54
55
56
57
58
59
60 public CodeWriter append(final String s) {
61 if (s == null) return this;
62 for (int i = 0; i < s.length(); i++) {
63 append(s.charAt(i));
64 }
65 return this;
66 }
67
68
69
70
71
72
73
74 public CodeWriter append(final char c) {
75 if (newLine && (c == ' ' || c == '\t')) return this;
76
77 if (c == '}') {
78 if (newLine && indentation >= INDENTATION_SPACE)
79 buff.delete(buff.length() - INDENTATION_SPACE, buff.length());
80 removeIndentLevel();
81 } else if (c == '{') addIndentLevel();
82 newLine = false;
83 buff.append(c);
84 if (c == '\n') {
85 newLine = true;
86 for (int j = 0; j < indentation; j++)
87 buff.append(' ');
88 }
89 return this;
90 }
91
92
93
94
95
96
97
98 public CodeWriter appendln(final String s) {
99 if (s == null) return this;
100 append(s).append('\n');
101 return this;
102 }
103
104
105
106
107
108
109
110 public CodeWriter append(final int i) {
111 buff.append(i);
112 return this;
113 }
114
115
116
117
118
119
120 public CodeWriter endl() {
121 append('\n');
122 return this;
123 }
124
125 protected CodeWriter addIndentLevel() {
126 indentation += INDENTATION_SPACE;
127 return this;
128 }
129
130 protected CodeWriter removeIndentLevel() {
131 if (indentation >= INDENTATION_SPACE) indentation -= INDENTATION_SPACE;
132 return this;
133 }
134
135 @Override
136 public String toString() {
137 if (producerName != null) {
138 if (!newLine) endl();
139 append("//- End of code produced by ").append(producerName).endl();
140 }
141 return buff.toString();
142 }
143
144 }