-
Notifications
You must be signed in to change notification settings - Fork 129
/
Mustache.java
1622 lines (1472 loc) · 68.8 KB
/
Mustache.java
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// JMustache - A Java implementation of the Mustache templating language
// http://github.com/samskivert/jmustache/blob/master/LICENSE
package com.samskivert.mustache;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Provides <a href="http://mustache.github.com/">Mustache</a> templating services.
*
* <p> Basic usage:
* <pre>{@code
* String source = "Hello {{arg}}!";
* Template tmpl = Mustache.compiler().compile(source);
* Map<String, Object> context = new HashMap<String, Object>();
* context.put("arg", "world");
* tmpl.execute(context); // returns "Hello world!"
* }</pre>
*/
public class Mustache {
/** Compiles templates into executable form. See {@link Mustache}. */
public static class Compiler {
/** Whether or not standards mode is enabled. */
public final boolean standardsMode;
/** Whether or not to throw an exception when a section resolves to a missing value. If
* false, the section is simply omitted (or included in the case of inverse sections). If
* true, a {@code MustacheException} is thrown. */
public final boolean strictSections;
/** A value to use when a variable resolves to null. If this value is null (which is the
* default null value), an exception will be thrown. If {@link #missingIsNull} is also
* true, this value will be used when a variable cannot be resolved.
*
* <p>If the nullValue contains a substring {@code {{name}}}, then this substring will be
* replaced by name of the variable. For example, if nullValue is {@code ?{{name}}?} and
* the missing variable is {@code foo}, then string {@code ?foo?} will be used.</p> */
public final String nullValue;
/** If this value is true, missing variables will be treated like variables that return
* null. {@link #nullValue} will be used in their place, assuming {@link #nullValue} is
* configured to a non-null value. */
public final boolean missingIsNull;
/** If this value is true, empty string will be treated as a false value, as in JavaScript
* mustache implementation. Default is false. */
public final boolean emptyStringIsFalse;
/** If this value is true, zero will be treated as a false value, as in JavaScript
* mustache implementation. Default is false. */
public final boolean zeroIsFalse;
/** Handles converting objects to strings when rendering a template. The default formatter
* uses {@link String#valueOf}. */
public final Formatter formatter;
/** Handles escaping characters in substituted text. */
public final Escaper escaper;
/** The template loader in use during this compilation. */
public final TemplateLoader loader;
/** The collector used by templates compiled with this compiler. */
public final Collector collector;
/** The delimiters used by default in templates compiled with this compiler. */
public final Delims delims;
/** Compiles the supplied template into a repeatedly executable intermediate form. */
public Template compile (String template) {
return compile(new StringReader(template));
}
/** Compiles the supplied template into a repeatedly executable intermediate form. */
public Template compile (Reader source) {
return Mustache.compile(source, this);
}
/** Returns a compiler that either does or does not escape HTML by default. Note: this
* overrides any escaper set via {@link #withEscaper}. */
public Compiler escapeHTML (boolean escapeHTML) {
return withEscaper(escapeHTML ? Escapers.HTML : Escapers.NONE);
}
/** Returns a compiler that either does or does not use standards mode. Standards mode
* disables the non-standard JMustache extensions like looking up missing names in a parent
* context. */
public Compiler standardsMode (boolean standardsMode) {
return new Compiler(standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
this.formatter, this.escaper, this.loader, this.collector,
this.delims);
}
/** Returns a compiler that throws an exception when a section references a missing value
* ({@code true}) or treats a missing value as {@code false} ({@code false}, the default).
*/
public Compiler strictSections (boolean strictSections) {
return new Compiler(this.standardsMode, strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
this.formatter, this.escaper, this.loader, this.collector,
this.delims);
}
/** Returns a compiler that will use the given value for any variable that is missing, or
* otherwise resolves to null. This is like {@link #nullValue} except that it returns the
* supplied default for missing keys and existing keys that return null values. */
public Compiler defaultValue (String defaultValue) {
return new Compiler(this.standardsMode, this.strictSections, defaultValue, true,
this.emptyStringIsFalse, this.zeroIsFalse, this.formatter,
this.escaper, this.loader, this.collector, this.delims);
}
/** Returns a compiler that will use the given value for any variable that resolves to
* null, but will still raise an exception for variables for which an accessor cannot be
* found. This is like {@link #defaultValue} except that it differentiates between missing
* accessors, and accessors that exist but return null.
* <ul>
* <li>In the case of a Java object being used as a context, if no field or method can be
* found for a variable, an exception will be raised.</li>
* <li>In the case of a {@link Map} being used as a context, if the map does not contain
* a mapping for a variable, an exception will be raised. If the map contains a mapping
* which maps to {@code null}, then {@code nullValue} is used.</li>
* </ul> */
public Compiler nullValue (String nullValue) {
return new Compiler(this.standardsMode, this.strictSections, nullValue, false,
this.emptyStringIsFalse, this.zeroIsFalse, this.formatter,
this.escaper, this.loader, this.collector, this.delims);
}
/** Returns a compiler that will treat empty string as a false value if parameter is true. */
public Compiler emptyStringIsFalse (boolean emptyStringIsFalse) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, emptyStringIsFalse, this.zeroIsFalse,
this.formatter, this.escaper, this.loader, this.collector,
this.delims);
}
/** Returns a compiler that will treat zero as a false value if parameter is true. */
public Compiler zeroIsFalse (boolean zeroIsFalse) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, zeroIsFalse,
this.formatter, this.escaper, this.loader, this.collector,
this.delims);
}
/** Configures the {@link Formatter} used to turn objects into strings. */
public Compiler withFormatter (Formatter formatter) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
formatter, this.escaper, this.loader, this.collector, this.delims);
}
/** Configures the {@link Escaper} used to escape substituted text. */
public Compiler withEscaper (Escaper escaper) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
this.formatter, escaper, this.loader, this.collector, this.delims);
}
/** Returns a compiler configured to use the supplied template loader to handle partials. */
public Compiler withLoader (TemplateLoader loader) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
this.formatter, this.escaper, loader, this.collector, this.delims);
}
/** Returns a compiler configured to use the supplied collector. */
public Compiler withCollector (Collector collector) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
this.formatter, this.escaper, this.loader, collector, this.delims);
}
/** Returns a compiler configured to use the supplied delims as default delimiters.
* @param delims a string of the form {@code AB CD} or {@code A D} where A and B are
* opening delims and C and D are closing delims. */
public Compiler withDelims (String delims) {
return new Compiler(this.standardsMode, this.strictSections, this.nullValue,
this.missingIsNull, this.emptyStringIsFalse, this.zeroIsFalse,
this.formatter, this.escaper, this.loader, this.collector,
new Delims().updateDelims(delims));
}
/** Returns the value to use in the template for the null-valued property {@code name}. See
* {@link #nullValue} for more details. */
public String computeNullValue (String name) {
return (nullValue == null) ? null : nullValue.replace("{{name}}", name);
}
/** Returns true if the supplied value is "falsey". If {@link #emptyStringIsFalse} is true,
* then empty strings are considered falsey. If {@link #zeroIsFalse} is true, then zero
* values are considered falsey. */
public boolean isFalsey (Object value) {
return ((emptyStringIsFalse && isEmptyCharSequence(formatter.format(value))) ||
(zeroIsFalse && (value instanceof Number) && ((Number)value).longValue() == 0));
}
/**
* Replaces "".equals(value). E.g. only not null values with length 0.
*/
private boolean isEmptyCharSequence (Object value) {
if (value == null) {
return false;
}
if (value instanceof CharSequence) {
return ((CharSequence) value).length() == 0;
}
return false;
}
/** Loads and compiles the template {@code name} using this compiler's configured template
* loader. Note that this does no caching: the caller should cache the loaded template if
* they expect to use it multiple times.
* @return the compiled template.
* @throws MustacheException if the template could not be loaded (due to I/O exception) or
* compiled (due to syntax error, etc.).
*/
public Template loadTemplate (String name) throws MustacheException {
Reader tin = null;
try {
tin = loader.getTemplate(name);
return compile(tin);
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else {
throw new MustacheException("Unable to load template: " + name, e);
}
} finally {
if (tin != null) try {
tin.close();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}
protected Compiler (boolean standardsMode, boolean strictSections, String nullValue,
boolean missingIsNull, boolean emptyStringIsFalse, boolean zeroIsFalse,
Formatter formatter, Escaper escaper, TemplateLoader loader,
Collector collector, Delims delims) {
this.standardsMode = standardsMode;
this.strictSections = strictSections;
this.nullValue = nullValue;
this.missingIsNull = missingIsNull;
this.emptyStringIsFalse = emptyStringIsFalse;
this.zeroIsFalse = zeroIsFalse;
this.formatter = formatter;
this.escaper = escaper;
this.loader = loader;
this.collector = collector;
this.delims = delims;
}
}
/** Handles converting objects to strings when rendering templates. */
public interface Formatter {
/** Converts {@code value} to a CharSequence for inclusion in a template. */
CharSequence format (Object value);
}
/** Handles lambdas. */
public interface Lambda {
/** Executes this lambda on the supplied template fragment. The lambda should write its
* results to {@code out}.
*
* @param frag the fragment of the template that was passed to the lambda.
* @param out the writer to which the lambda should write its output.
*/
void execute (Template.Fragment frag, Writer out) throws IOException;
}
/** Handles lambdas that are also invoked for inverse sections.. */
public interface InvertibleLambda extends Lambda {
/** Executes this lambda on the supplied template fragment, when the lambda is used in an
* inverse section. The lambda should write its results to {@code out}.
*
* @param frag the fragment of the template that was passed to the lambda.
* @param out the writer to which the lambda should write its output.
*/
void executeInverse (Template.Fragment frag, Writer out) throws IOException;
}
/** Reads variables from context objects. */
public interface VariableFetcher {
/** Reads the so-named variable from the supplied context object. */
Object get (Object ctx, String name) throws Exception;
}
/** Handles escaping characters in substituted text. */
public interface Escaper {
/** Returns {@code raw} with the appropriate characters replaced with escape sequences. */
String escape (String raw);
/** Returns {@code raw} with the appropriate characters replaced with escape sequences. **/
default CharSequence escape (CharSequence raw) {
return escape(raw.toString());
}
/**
* Escapes the raw characters with escape sequeneces if needed and appends to the appendable.
* The default implementation calls {@link #escape(CharSequence)}.
* @param a the stream like to append to.
* @param raw input string.
* @throws IOException if an error happens while writing to the appendable.
*/
default void escape (Appendable a, CharSequence raw) throws IOException {
a.append(escape(raw));
}
}
/** Handles loading partial templates. */
public interface TemplateLoader {
/** Returns a reader for the template with the supplied name.
* Reader will be closed by callee.
* @throws Exception if the template could not be loaded for any reason. */
Reader getTemplate (String name) throws Exception;
}
/** Handles interpreting objects as collections. */
public interface Collector {
/** Returns an iterator that can iterate over the supplied value, or null if the value is
* not a collection. */
Iterator<?> toIterator (final Object value);
/** Creates a fetcher for a so-named variable in the supplied context object, which will
* never be null. The fetcher will be cached and reused for future contexts for which
* {@code octx.getClass().equals(nctx.getClass()}. */
VariableFetcher createFetcher (Object ctx, String name);
/** Creates a map to be used to cache {@link VariableFetcher} instances. The GWT-compatible
* collector returns a HashMap here, but the reflection based fetcher (which only works on
* the JVM and Android, returns a concurrent hashmap. */
<K,V> Map<K,V> createFetcherCache ();
}
/**
* Provides a means to implement custom logic for variable lookup. If a context object
* implements this interface, its {@code get} method will be used to look up variables instead
* of the usual methods.
*
* This is simpler than having a context implement {@link Map} which would require that it also
* support the {@link Map#entrySet} method for iteration. A {@code CustomContext} object cannot
* be used for a list section.
*/
public interface CustomContext {
/** Fetches the value of a variable named {@code name}. */
Object get (String name) throws Exception;
}
/** Used to visit the tags in a template without executing it. */
public interface Visitor {
/** Visits a text segment. These are blocks of text that are normally just reproduced as
* is when executing a template.
* @param text the block of text. May contain newlines.
*/
void visitText (String text);
/** Visits a variable tag.
* @param name the name of the variable.
*/
void visitVariable (String name);
/** Visits an include (partial) tag.
* @param name the name of the partial template specified by the tag.
* @return true if the template should be resolved and visited, false to skip it.
*/
boolean visitInclude (String name);
/** Visits a parent partial tag. For backward compatibility by default
* <code>false</code> is returned.
* @param name the name of the parent partial template specified by the tag.
* @return true if the template should be resolved and visited, false to skip it.
*/
default boolean visitParent (String name) {
return false;
}
/** Visits a block tag. For backward compatibility by default is skipped.
* @param name the name of the block.
* @return true if the contents of the block should be visited, false to skip.
*/
default boolean visitBlock (String name) {
return false;
}
/** Visits a section tag.
* @param name the name of the section.
* @return true if the contents of the section should be visited, false to skip.
*/
boolean visitSection (String name);
/** Visits an inverted section tag.
* @param name the name of the inverted section.
* @return true if the contents of the section should be visited, false to skip.
*/
boolean visitInvertedSection (String name);
}
/**
* Returns a compiler that escapes HTML by default and does not use standards mode.
*/
public static Compiler compiler () {
return new Compiler(/*standardsMode=*/false, /*strictSections=*/false, /*nullValue=*/null,
/*missingIsNull=*/false, /*emptyStringIsFalse=*/false,
/*zeroIsFalse=*/false, DEFAULT_FORMATTER, Escapers.HTML, FAILING_LOADER,
new DefaultCollector(), new Delims());
}
/**
* Compiles the supplied template into a repeatedly executable intermediate form.
*/
protected static Template compile (Reader source, Compiler compiler) {
Accumulator accum = new Parser(compiler).parse(source);
return new Template(trim(accum.finish(), true), compiler);
}
private Mustache () {} // no instantiateski
protected static Template.Segment[] trim (Template.Segment[] segs, boolean top) {
// trim() modifies segs! Its return is not a copy!
// now that we have all of our segments, we make a pass through them to trim whitespace
// from section tags which stand alone on their lines
for (int ii = 0, ll = segs.length; ii < ll; ii++) {
Template.Segment seg = segs[ii];
Template.Segment pseg = (ii > 0 ) ? segs[ii-1] : null;
Template.Segment nseg = (ii < ll-1) ? segs[ii+1] : null;
StringSegment prev = (pseg instanceof StringSegment) ? (StringSegment)pseg : null;
StringSegment next = (nseg instanceof StringSegment) ? (StringSegment)nseg : null;
// if we're at the top-level there are virtual "blank lines" before & after segs
boolean prevBlank = ((pseg == null && top) || (prev != null && prev.trailsBlank()));
boolean nextBlank = ((nseg == null && top) || (next != null && next.leadsBlank()));
// potentially trim around the open and close tags of a block segment
if (seg instanceof StandaloneSection) {
StandaloneSection sect = (StandaloneSection)seg;
String indent = "";
if (prevBlank && sect.firstLeadsBlank()) {
if (prev != null) {
// capture the indent before we trim
indent = prev.indent();
segs[ii-1] = prev.trimTrailBlank();
}
sect.trimFirstBlank();
sect.standaloneStart(true);
}
if (nextBlank && sect.lastTrailsBlank()) {
sect.trimLastBlank();
if (next != null) segs[ii+1] = next.trimLeadBlank();
sect.standaloneEnd(true);
}
if (sect instanceof ParentTemplateSegment && ! indent.equals("")) {
ParentTemplateSegment pt = (ParentTemplateSegment) sect;
segs[ii] = pt.indent(indent, pseg == null, nseg == null);
}
}
// we have to indent partials if there is space before and they are also standalone.
else if (seg instanceof IncludedTemplateSegment) {
IncludedTemplateSegment include = (IncludedTemplateSegment) seg;
if (prev != null && prevBlank && nextBlank) {
String indent = prev.indent();
include._standalone = true;
if (!indent.equals("")) {
include = include.indent(indent, pseg == null,nseg == null);
segs[ii] = include;
}
/*
* We trim the end because partials follow standalone just like blocks.
* HOWEVER we do NOT trim the previous StringSegment as it provides the partial indentation.
* See indentSegs.
*/
if (next != null) {
segs[ii+1] = next.trimLeadBlank();
}
}
}
// potentially trim around non-printing (comments/delims) segments
else if (seg instanceof FauxSegment) {
if (prevBlank && nextBlank) {
if (pseg != null) segs[ii-1] = prev.trimTrailBlank();
if (nseg != null) segs[ii+1] = next.trimLeadBlank();
}
}
}
return segs;
}
/**
* Indents segments by indent.
* @param _segs segments to be cloned if indentation is needed
* @param indent the space to use for indent.
* @param _first whether to append an indent on the first segment
* @param _last whether to append an indent on the last segment last empty newline (no character after \n).
* @return cloned segments if changed
*/
static Template.Segment[] indentSegs (Template.Segment[] _segs, String indent, boolean _first, boolean _last) {
// unlike trim this method clones the segments if they have changed so the return value must
// be handled; a simple identity check on the return can be used to determine if there is
// change
if (indent.equals("")) {
return _segs;
}
int length = _segs.length;
Template.Segment[] copySegs = new Template.Segment[length];
boolean changed = false;
for (int i = 0; i < _segs.length; i++) {
Template.Segment seg = _segs[i];
Template.Segment pseg = (i > 0) ? _segs[i-1] : null;
Template.Segment nseg = (i < length - 1) ? _segs[i+1] : null;
Template.Segment copy;
if (seg instanceof AbstractSectionSegment) {
AbstractSectionSegment bs = (AbstractSectionSegment) seg;
boolean first;
boolean last;
if (pseg == null) {
// We are the first segment so we inherit
// outer first
first = _first;
}
else if (bs.isStandaloneStart()) {
first = true;
}
else {
first = false;
}
if (bs.isStandalone()) {
// the closing tag owns the last new line
// in the section so we do not indent
last = false;
}
else if (nseg == null) {
// We are the last segment so we inherit the
// outer last
last = _last;
}
else {
last = true;
}
copy = bs.indent(indent, first, last);
}
else if (seg instanceof StringSegment) {
boolean first;
boolean last;
if (pseg == null) {
first = _first;
}
else if (pseg.isStandalone()) {
first = true;
}
else {
first = false;
}
if (nseg == null) {
last = _last;
}
else if (nseg instanceof AbstractSectionSegment) {
AbstractSectionSegment bs = (AbstractSectionSegment) nseg;
last = ! bs.isStandaloneStart();
}
else if (nseg.isStandalone()) {
last = false;
}
else {
last = true;
}
copy = seg.indent(indent, first, last);
}
else if (seg instanceof IncludedTemplateSegment) {
/*
* If we are standalone then we rely on the indentation already present before the
* partial tag.
* [ WS ]{{> partial }}[\n]
*
* That is partial tags do not have the trailing blank removed during the trim process.
* This avoids needlessley creating StringSegment tags.
*/
if (seg.isStandalone()) {
boolean last;
if (nseg == null) {
last = _last;
}
else if (nseg.isStandalone()) {
last = false;
}
else {
last = true;
}
// Again first = false here because we
//already have the indentation set on a previous segment
copy = seg.indent(indent, false, last);
}
else {
copy = seg;
}
}
else {
copy = seg.indent(indent, _first, _last);
}
if (copy != seg) {
changed = true;
}
copySegs[i] = copy;
}
if (changed) {
return copySegs;
}
return _segs;
}
static Template.Segment[] replaceBlockSegs(Template.Segment[] _segs, Map<String, BlockSegment> blocks) {
if (blocks.isEmpty()) {
return _segs;
}
int length = _segs.length;
Template.Segment[] copySegs = new Template.Segment[length];
boolean changed = false;
for (int i = 0; i < _segs.length; i++) {
Template.Segment seg = _segs[i];
Template.Segment copy;
if (seg instanceof BlockReplaceable) {
BlockReplaceable br = (BlockReplaceable) seg;
copy = br.replaceBlocks(blocks);
}
else {
copy = seg;
}
if (copy != seg) {
changed = true;
}
copySegs[i] = copy;
}
if (changed) {
return copySegs;
}
return _segs;
}
protected static void restoreStartTag (StringBuilder text, Delims starts) {
text.insert(0, starts.start1);
if (starts.start2 != NO_CHAR) {
text.insert(1, starts.start2);
}
}
// TODO: this method was never called, what was my intention here?
protected static boolean allowsWhitespace (char typeChar) {
return (typeChar == '=' /* change delimiters */) || (typeChar == '!' /* comment */);
}
protected static final int TEXT = 0;
protected static final int MATCHING_START = 1;
protected static final int MATCHING_END = 2;
protected static final int TAG = 3;
// a hand-rolled parser; whee!
protected static class Parser {
final Delims delims;
final StringBuilder text = new StringBuilder();
Reader source;
Accumulator accum;
int state = TEXT;
int line = 1, column = 0;
int tagStartColumn = -1;
public Parser (Compiler compiler) {
this.accum = new Accumulator(compiler, true);
this.delims = compiler.delims.copy();
}
public Accumulator parse (Reader source) {
this.source = source;
int v;
while ((v = nextChar()) != -1) {
char c = (char)v;
++column; // our columns start at one, so increment before parse
parseChar(c);
// if we just parsed a newline, reset the column to zero and advance line
if (c == '\n') {
column = 0;
++line;
}
}
// accumulate any trailing text
switch (state) {
case TAG:
restoreStartTag(text, delims);
break;
case MATCHING_END:
restoreStartTag(text, delims);
text.append(delims.end1);
break;
case MATCHING_START:
text.append(delims.start1);
break;
case TEXT: // do nothing
break;
}
accum.addTextSegment(text);
return accum;
}
protected void parseChar (char c) {
switch (state) {
case TEXT:
if (c == delims.start1) {
state = MATCHING_START;
tagStartColumn = column;
if (delims.start2 == NO_CHAR) {
parseChar(NO_CHAR);
}
} else {
text.append(c);
}
break;
case MATCHING_START:
if (c == delims.start2) {
accum.addTextSegment(text);
state = TAG;
} else {
text.append(delims.start1);
state = TEXT;
parseChar(c);
}
break;
case TAG:
if (c == delims.end1) {
state = MATCHING_END;
if (delims.end2 == NO_CHAR) {
parseChar(NO_CHAR);
}
} else if (c == delims.start1 && text.length() > 0 && text.charAt(0) != '!') {
// if we've already matched some tag characters and we see a new start tag
// character (e.g. "{{foo {" but not "{{{"), treat the already matched text as
// plain text and start matching a new tag from this point, unless we're in
// a comment tag.
restoreStartTag(text, delims);
accum.addTextSegment(text);
tagStartColumn = column;
if (delims.start2 == NO_CHAR) {
accum.addTextSegment(text);
state = TAG;
} else {
state = MATCHING_START;
}
} else {
text.append(c);
}
break;
case MATCHING_END:
if (c == delims.end2) {
if (text.charAt(0) == '=') {
delims.updateDelims(text.substring(1, text.length()-1));
text.setLength(0);
accum.addFauxSegment(); // for newline trimming
} else {
// if the delimiters are {{ and }}, and the tag starts with {{{ then
// require that it end with }}} and disable escaping
if (delims.isStaches() && text.charAt(0) == delims.start1) {
// we've only parsed }} at this point, so we have to slurp in another
// character from the input stream and check it
int end3 = nextChar();
if (end3 != '}') {
String got = (end3 == -1) ? "" : String.valueOf((char)end3);
throw new MustacheParseException(
"Invalid triple-mustache tag: {{" + text + "}}" + got, line);
}
// convert it into (equivalent) {{&text}} which addTagSegment handles
text.replace(0, 1, "&");
}
// process the tag between the mustaches
accum = accum.addTagSegment(text, line);
}
state = TEXT;
} else {
text.append(delims.end1);
state = TAG;
parseChar(c);
}
break;
}
}
protected int nextChar () {
try {
return source.read();
} catch (IOException ioe) {
throw new MustacheException(ioe);
}
}
}
protected static class Delims {
public char start1 = '{', end1 = '}';
public char start2 = '{', end2 = '}';
public boolean isStaches () {
return start1 == '{' && start2 == '{' && end1 == '}' && end2 == '}';
}
public Delims updateDelims (String dtext) {
String[] delims = dtext.split(" ");
if (delims.length != 2) throw new MustacheException(errmsg(dtext));
switch (delims[0].length()) {
case 1:
start1 = delims[0].charAt(0);
start2 = NO_CHAR;
break;
case 2:
start1 = delims[0].charAt(0);
start2 = delims[0].charAt(1);
break;
default:
throw new MustacheException(errmsg(dtext));
}
switch (delims[1].length()) {
case 1:
end1 = delims[1].charAt(0);
end2 = NO_CHAR;
break;
case 2:
end1 = delims[1].charAt(0);
end2 = delims[1].charAt(1);
break;
default:
throw new MustacheException(errmsg(dtext));
}
return this;
}
public void addTag (char prefix, String name, StringBuilder into) {
into.append(start1);
into.append(start2);
if (prefix != ' ') into.append(prefix);
into.append(name);
into.append(end1);
into.append(end2);
}
Delims copy () {
Delims d = new Delims();
d.start1 = start1;
d.start2 = start2;
d.end1 = end1;
d.end2 = end2;
return d;
}
private static String errmsg (String dtext) {
return "Invalid delimiter configuration '" + dtext + "'. Must be of the " +
"form {{=1 2=}} or {{=12 34=}} where 1, 2, 3 and 4 are delimiter chars.";
}
}
protected static class Accumulator {
public Accumulator (Compiler compiler, boolean topLevel) {
_comp = compiler;
_topLevel = topLevel;
}
public void addTextSegment (StringBuilder text) {
if (text.length() > 0) {
_segs.add(new StringSegment(text.toString(), _segs.isEmpty() && _topLevel));
text.setLength(0);
}
}
public Accumulator addTagSegment (final StringBuilder accum, final int tagLine) {
final Accumulator outer = this;
String tag = accum.toString().trim();
final String tag1 = tag.substring(1).trim();
accum.setLength(0);
switch (tag.charAt(0)) {
case '#':
requireNoNewlines(tag, tagLine);
return new Accumulator(_comp, false) {
@Override public Template.Segment[] finish () {
throw new MustacheParseException(
"Section missing close tag '" + tag1 + "'", tagLine);
}
@Override protected Accumulator addCloseSectionSegment (String itag, int line) {
requireSameName(tag1, itag, line);
outer._segs.add(new SectionSegment(_comp, itag, super.finish(), tagLine));
return outer;
}
};
case '>':
_segs.add(new IncludedTemplateSegment(_comp, tag1, tagLine));
return this;
case '<':
requireNoNewlines(tag, tagLine);
return new Accumulator(_comp, false) {
@Override public Template.Segment[] finish () {
throw new MustacheParseException(
"Parent missing close tag '" + tag1 + "'", tagLine);
}
@Override protected Accumulator addCloseSectionSegment (String itag, int line) {
requireSameName(tag1, itag, line);
outer._segs.add(new ParentTemplateSegment(_comp, itag, super.finish(), tagLine));
return outer;
}
};
case '$':
requireNoNewlines(tag, tagLine);
return new Accumulator(_comp, false) {
@Override public Template.Segment[] finish () {
throw new MustacheParseException(
"Block missing close tag '" + tag1 + "'", tagLine);
}
@Override protected Accumulator addCloseSectionSegment (String itag, int line) {
requireSameName(tag1, itag, line);
outer._segs.add(new BlockSegment(_comp, itag, super.finish(), tagLine));
return outer;
}
};
case '^':
requireNoNewlines(tag, tagLine);
return new Accumulator(_comp, false) {
@Override public Template.Segment[] finish () {
throw new MustacheParseException(
"Inverted section missing close tag '" + tag1 + "'", tagLine);
}
@Override protected Accumulator addCloseSectionSegment (String itag, int line) {
requireSameName(tag1, itag, line);
outer._segs.add(new InvertedSegment(_comp, itag, super.finish(), tagLine));
return outer;
}
};
case '/':
requireNoNewlines(tag, tagLine);
return addCloseSectionSegment(tag1, tagLine);
case '!':
// comment!, ignore
_segs.add(new FauxSegment()); // for whitespace trimming
return this;
case '&':
requireNoNewlines(tag, tagLine);
_segs.add(new VariableSegment(tag1, tagLine, _comp.formatter, Escapers.NONE));
return this;
default:
requireNoNewlines(tag, tagLine);
_segs.add(new VariableSegment(tag, tagLine, _comp.formatter, _comp.escaper));
return this;
}
}
public void addFauxSegment () {
_segs.add(new FauxSegment());
}
public Template.Segment[] finish () {
return _segs.toArray(new Template.Segment[_segs.size()]);
}
protected Accumulator addCloseSectionSegment (String tag, int line) {
throw new MustacheParseException(
"Section close tag with no open tag '" + tag + "'", line);