-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathMustacheParser.java
More file actions
398 lines (359 loc) · 15.1 KB
/
MustacheParser.java
File metadata and controls
398 lines (359 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package com.github.mustachejava;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The parser generates callbacks into the MustacheFactory to build them. Do not use these
* directly as you must manage the Mustache object lifecycle as well.
* <p>
* User: sam
* Date: 5/14/11
* Time: 3:52 PM
*/
public class MustacheParser {
public static final String DEFAULT_SM = "{{";
public static final String DEFAULT_EM = "}}";
/**
* For legacy reasons we keep the non-spec conform parsing of whitespace unless this flag is true.
*/
private final boolean specConformWhitespace;
private MustacheFactory mf;
protected MustacheParser(MustacheFactory mf, boolean specConformWhitespace) {
this.mf = mf;
this.specConformWhitespace = specConformWhitespace;
}
protected MustacheParser(MustacheFactory mf) {
this(mf, false);
}
public Mustache compile(String file) {
Reader reader = mf.getReader(file);
if (reader == null) {
throw new MustacheNotFoundException(file);
}
return compile(reader, file);
}
public Mustache compile(Reader reader, String file) {
return compile(reader, file, DEFAULT_SM, DEFAULT_EM);
}
public Mustache compile(Reader reader, String file, String sm, String em) {
return compile(reader, null, new AtomicInteger(0), file, sm, em, true);
}
public Mustache compile(Reader reader, String file, String sm, String em, boolean startOfLine) {
return compile(reader, null, new AtomicInteger(0), file, sm, em, startOfLine);
}
@SuppressWarnings("ConstantConditions") // this method is too complex
protected Mustache compile(final Reader reader, String tag, final AtomicInteger currentLine, String file, String sm, String em, boolean startOfLine) throws MustacheException {
if (reader == null) {
throw new MustacheException("Reader is null");
}
Reader br;
if (reader.markSupported()) {
br = reader;
} else {
br = new BufferedReader(reader);
}
try {
boolean sawCR = false;
int startLine = currentLine.get();
MustacheVisitor mv = mf.createMustacheVisitor();
// Now we grab the mustache template
boolean onlywhitespace = true;
// Starting a new line
boolean iterable = currentLine.get() != 0;
currentLine.compareAndSet(0, 1);
StringBuilder out = new StringBuilder();
try {
int c;
while ((c = br.read()) != -1) {
// We remember that we saw a carriage return so we can put it back in later
if (c == '\r') {
sawCR = true;
continue;
}
// Increment the line
if (c == '\n') {
currentLine.incrementAndGet();
if (specConformWhitespace || !iterable || (iterable && !onlywhitespace)) {
if (sawCR) out.append("\r");
out.append("\n");
}
out = write(mv, out, file, currentLine.intValue(), startOfLine);
iterable = false;
onlywhitespace = true;
startOfLine = true;
continue;
}
sawCR = false;
// Check for a mustache start
if (c == sm.charAt(0)) {
br.mark(1);
if (sm.length() == 1 || br.read() == sm.charAt(1)) {
// If it is a delimiter change we need to specially handle it
// Two mustaches, now capture command
StringBuilder sb = new StringBuilder();
br.mark(1);
c = br.read();
boolean delimiter = c == '=';
if (delimiter) {
sb.append((char) c);
} else {
br.reset();
}
while ((c = br.read()) != -1) {
br.mark(1);
if (delimiter) {
if (c == '=') {
// Reached the end of the definition
delimiter = false;
} else {
sb.append((char) c);
}
continue;
}
if (c == em.charAt(0)) {
if (em.length() > 1) {
if (br.read() == em.charAt(1)) {
// Matched end
break;
} else {
// Only one
br.reset();
}
} else break;
}
sb.append((char) c);
}
final String command = mf.translate(sb.toString());
if (command.length() == 0) {
TemplateContext tc = new TemplateContext(sm, em, file, currentLine.get(), startOfLine);
throw new MustacheException("Empty mustache", tc);
}
final char ch = command.charAt(0);
final String variable = command.substring(1).trim();
switch (ch) {
case '#':
case '^':
case '<':
case '?':
case '$': {
boolean oldStartOfLine = startOfLine;
startOfLine = startOfLine & onlywhitespace;
boolean nextStartOfLine = specConformWhitespace && trimNewline(startOfLine, br);
int line = currentLine.get();
final Mustache mustache = compile(br, variable, currentLine, file, sm, em, startOfLine);
int lines = currentLine.get() - line;
if ((specConformWhitespace && !nextStartOfLine) ||
(!specConformWhitespace && (!onlywhitespace || lines == 0))) {
write(mv, out, file, currentLine.intValue(), oldStartOfLine);
}
out = new StringBuilder();
switch (ch) {
case '#':
mv.iterable(new TemplateContext(sm, em, file, line, startOfLine), variable, mustache);
break;
case '^':
mv.notIterable(new TemplateContext(sm, em, file, line, startOfLine), variable, mustache);
break;
case '<':
mv.extend(new TemplateContext(sm, em, file, line, startOfLine), variable, mustache);
break;
case '$':
mv.name(new TemplateContext(sm, em, file, line, startOfLine), variable, mustache);
break;
case '?':
mv.checkName(new TemplateContext(sm, em, file, line, startOfLine), variable, mustache);
break;
}
startOfLine = nextStartOfLine;
iterable = lines != 0;
break;
}
case '/': {
// Tag end
if (specConformWhitespace) {
if (!trimNewline(onlywhitespace & startOfLine, br)) {
write(mv, out, file, currentLine.intValue(), startOfLine);
}
} else if (!startOfLine || !onlywhitespace) {
write(mv, out, file, currentLine.intValue(), startOfLine);
}
if (!variable.equals(tag)) {
TemplateContext tc = new TemplateContext(sm, em, file, currentLine.get(), startOfLine);
throw new MustacheException(
"Mismatched start/end tags: " + tag + " != " + variable + " in " + file + ":" + currentLine, tc);
}
return mv.mustache(new TemplateContext(sm, em, file, 0, startOfLine));
}
case '>': {
String indent = (onlywhitespace && startOfLine) ? out.toString() : "";
out = write(mv, out, file, currentLine.intValue(), startOfLine);
startOfLine = startOfLine & onlywhitespace;
mv.partial(new TemplateContext(sm, em, file, currentLine.get(), startOfLine), variable, indent);
// a new line following a partial is dropped
startOfLine = specConformWhitespace && trimNewline(startOfLine, br);
break;
}
case '{': {
out = write(mv, out, file, currentLine.intValue(), startOfLine);
// Not escaped
String name = variable;
if (em.charAt(1) != '}') {
name = variable.substring(0, variable.length() - 1);
} else {
if (br.read() != '}') {
TemplateContext tc = new TemplateContext(sm, em, file, currentLine.get(), startOfLine);
throw new MustacheException(
"Improperly closed variable in " + file + ":" + currentLine, tc);
}
}
mv.value(new TemplateContext(sm, em, file, currentLine.get(), false), name, false);
startOfLine = false;
break;
}
case '&': {
// Not escaped
out = write(mv, out, file, currentLine.intValue(), startOfLine);
mv.value(new TemplateContext(sm, em, file, currentLine.get(), false), variable, false);
startOfLine = false;
break;
}
case '%':
// Pragmas
out = write(mv, out, file, currentLine.intValue(), startOfLine);
int index = variable.indexOf(" ");
String pragma;
String args;
if (index == -1) {
pragma = variable;
args = null;
} else {
pragma = variable.substring(0, index);
args = variable.substring(index + 1);
}
mv.pragma(new TemplateContext(sm, em, file, currentLine.get(), startOfLine), pragma, args);
startOfLine = false;
break;
case '!':
// Comment
mv.comment(new TemplateContext(sm, em, file, currentLine.get(), startOfLine), variable);
if (specConformWhitespace) {
boolean sol = trimNewline(startOfLine & onlywhitespace, br);
if (!sol) {
write(mv, out, file, currentLine.intValue(), startOfLine);
}
startOfLine = sol;
} else {
write(mv, out, file, currentLine.intValue(), startOfLine);
startOfLine = false;
}
out = new StringBuilder();
break;
case '=':
// Change delimiters
String trimmed = command.substring(1).trim();
String[] split = trimmed.split("\\s+");
if (split.length != 2) {
TemplateContext tc = new TemplateContext(sm, em, file, currentLine.get(), startOfLine);
throw new MustacheException("Invalid delimiter string: " + trimmed, tc);
}
sm = split[0];
em = split[1];
if (specConformWhitespace) {
boolean sol = trimNewline(startOfLine & onlywhitespace, br);
if (!sol) {
write(mv, out, file, currentLine.intValue(), startOfLine);
}
startOfLine = sol;
} else {
write(mv, out, file, currentLine.intValue(), startOfLine);
startOfLine = false;
}
out = new StringBuilder();
break;
default: {
if (c == -1) {
TemplateContext tc = new TemplateContext(sm, em, file, currentLine.get(), startOfLine);
throw new MustacheException("Improperly closed variable", tc);
}
// Reference
out = write(mv, out, file, currentLine.intValue(), startOfLine);
mv.value(new TemplateContext(sm, em, file, currentLine.get(), false), command.trim(), true);
startOfLine = false;
break;
}
}
if (!specConformWhitespace) {
// Additional text is no longer at the start of the line
// in spec-conform whitespace parsing we sometimes chop a whole line so we let the individual commands
// decide wether we are at the start of a line
startOfLine = false;
}
continue;
} else {
// Only one
br.reset();
}
}
onlywhitespace = onlywhitespace && (c == ' ' || c == '\t' || c == '\r');
out.append((char) c);
}
write(mv, out, file, currentLine.intValue(), startOfLine);
if (tag == null) {
br.close();
} else {
TemplateContext tc = new TemplateContext(sm, em, file, startLine, startOfLine);
throw new MustacheException("Failed to close '" + tag + "' tag", tc);
}
} catch (IOException e) {
TemplateContext tc = new TemplateContext(sm, em, file, currentLine.get(), startOfLine);
throw new MustacheException("Failed to read", tc);
}
mv.eof(new TemplateContext(sm, em, file, currentLine.get(), startOfLine));
return mv.mustache(new TemplateContext(sm, em, file, 0, startOfLine));
} catch (MustacheException me) {
try {
// We're going to blow the whole stack of compilation and
// close the readers on the way up.
br.close();
} catch (IOException e) {
// Ignore IOExceptions on close
}
throw me;
}
}
/**
* Ignore empty strings and append to the previous code if it was also a write.
*/
private StringBuilder write(MustacheVisitor mv, StringBuilder out, String file, int line, boolean startOfLine) {
String text = out.toString();
mv.write(new TemplateContext(null, null, file, line, startOfLine), text);
return new StringBuilder();
}
/**
* Some statements such as partials are treated as "standalone".
* This means that if they are the only content on this line (except whitespace) then the following newline is
* chopped.
* For backwards compatibility we only do this if the parser is explicitly configured so.
* @param firstStmt If the statement that was just read was at the start of line with only whitespace preceding it
* @param br The reader
* @return true if trimming was allowed and a following new line was removed or the buffer was finished;
* @throws IOException
*/
private boolean trimNewline(boolean firstStmt, Reader br) throws IOException {
boolean trimmed = false;
if (firstStmt) {
br.mark(2);
int ca = br.read();
if (ca == '\r') {
ca = br.read();
}
if (ca == '\n' || ca == -1) {
trimmed = true;
} else {
br.reset();
}
}
return trimmed;
}
}