-
Notifications
You must be signed in to change notification settings - Fork 231
/
Interpreter.java
1451 lines (1358 loc) · 58.9 KB
/
Interpreter.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
/*
* [The "BSD license"]
* Copyright (c) 2011 Terence Parr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.stringtemplate.v4;
import org.stringtemplate.v4.compiler.*;
import org.stringtemplate.v4.compiler.Compiler;
import org.stringtemplate.v4.debug.*;
import org.stringtemplate.v4.gui.STViz;
import org.stringtemplate.v4.misc.*;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.*;
/**
* This class knows how to execute template bytecodes relative to a particular
* {@link STGroup}. To execute the byte codes, we need an output stream and a
* reference to an {@link ST} instance. That instance's {@link ST#impl} field
* points at a {@link CompiledST}, which contains all of the byte codes and
* other information relevant to execution.
* <p>
* This interpreter is a stack-based bytecode interpreter. All operands go onto
* an operand stack.</p>
* <p>
* If {@link #debug} set, we track interpreter events. For now, I am only
* tracking instance creation events. These are used by {@link STViz} to pair up
* output chunks with the template expressions that generate them.</p>
* <p>
* We create a new interpreter for each invocation of
* {@link ST#render}, {@link ST#inspect}, or {@link ST#getEvents}.</p>
*/
public class Interpreter {
public enum Option { ANCHOR, FORMAT, NULL, SEPARATOR, WRAP }
public static final int DEFAULT_OPERAND_STACK_SIZE = 100;
public static final Set<String> predefinedAnonSubtemplateAttributes;
static {
final Set<String> set = new HashSet<String>();
set.add("i");
set.add("i0");
predefinedAnonSubtemplateAttributes = Collections.unmodifiableSet(set);
}
/** Operand stack, grows upwards. */
Object[] operands = new Object[DEFAULT_OPERAND_STACK_SIZE];
/** Stack pointer register. */
int sp = -1;
/** The number of characters written on this template line so far. */
int nwline = 0;
/** Render template with respect to this group.
*
* @see ST#groupThatCreatedThisInstance
* @see CompiledST#nativeGroup
*/
STGroup group;
/** For renderers, we have to pass in the locale. */
Locale locale;
ErrorManager errMgr;
/**
* Dump bytecode instructions as they are executed. This field is mostly for
* StringTemplate development.
*/
public static boolean trace = false;
/** If {@link #trace} is {@code true}, track trace here. */
// TODO: track the pieces not a string and track what it contributes to output
protected List<String> executeTrace;
/** When {@code true}, track events inside templates and in {@link #events}. */
public boolean debug = false;
/**
* Track everything happening in interpreter across all templates if
* {@link #debug}. The last event in this field is the
* {@link EvalTemplateEvent} for the root template.
*/
protected List<InterpEvent> events;
public Interpreter(STGroup group, boolean debug) {
this(group,Locale.getDefault(),group.errMgr, debug);
}
public Interpreter(STGroup group, Locale locale, boolean debug) {
this(group, locale, group.errMgr, debug);
}
public Interpreter(STGroup group, ErrorManager errMgr, boolean debug) {
this(group,Locale.getDefault(),errMgr, debug);
}
public Interpreter(STGroup group, Locale locale, ErrorManager errMgr, boolean debug) {
this.group = group;
this.locale = locale;
this.errMgr = errMgr;
this.debug = debug;
if ( debug ) {
events = new ArrayList<InterpEvent>();
executeTrace = new ArrayList<String>();
}
}
// public static int[] count = new int[Bytecode.MAX_BYTECODE+1];
// public static void dumpOpcodeFreq() {
// System.out.println("#### instr freq:");
// for (int i=1; i<=Bytecode.MAX_BYTECODE; i++) {
// System.out.println(count[i]+" "+Bytecode.instructions[i].name);
// }
// }
/** Execute template {@code self} and return how many characters it wrote to {@code out}.
*
* @return the number of characters written to {@code out}
*/
public int exec(STWriter out, InstanceScope scope) {
final ST self = scope.st;
if ( trace ) System.out.println("exec("+self.getName()+")");
try {
setDefaultArguments(out, scope);
return _exec(out, scope);
}
catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
errMgr.runTimeError(this, scope, ErrorType.INTERNAL_ERROR,
"internal error: "+sw.toString());
return 0;
}
}
protected int _exec(STWriter out, InstanceScope scope) {
final ST self = scope.st;
int start = out.index(); // track char we're about to write
int prevOpcode = 0;
int n = 0; // how many char we write out
int nargs;
int nameIndex;
int addr;
String name;
Object o, left, right;
ST st;
Object[] options;
byte[] code = self.impl.instrs; // which code block are we executing
int ip = 0;
while ( ip < self.impl.codeSize ) {
if ( trace || debug ) trace(scope, ip);
short opcode = code[ip];
//count[opcode]++;
scope.ip = ip;
ip++; //jump to next instruction or first byte of operand
switch (opcode) {
case Bytecode.INSTR_LOAD_STR :
// just testing...
load_str(self,ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
break;
case Bytecode.INSTR_LOAD_ATTR :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = self.impl.strings[nameIndex];
try {
o = getAttribute(scope, name);
if ( o==ST.EMPTY_ATTR ) o = null;
}
catch (STNoSuchAttributeException nsae) {
errMgr.runTimeError(this, scope, ErrorType.NO_SUCH_ATTRIBUTE, name);
o = null;
}
operands[++sp] = o;
break;
case Bytecode.INSTR_LOAD_LOCAL:
int valueIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
o = self.locals[valueIndex];
if ( o==ST.EMPTY_ATTR ) o = null;
operands[++sp] = o;
break;
case Bytecode.INSTR_LOAD_PROP :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
o = operands[sp--];
name = self.impl.strings[nameIndex];
operands[++sp] = getObjectProperty(out, scope, o, name);
break;
case Bytecode.INSTR_LOAD_PROP_IND :
Object propName = operands[sp--];
o = operands[sp];
operands[sp] = getObjectProperty(out, scope, o, propName);
break;
case Bytecode.INSTR_NEW :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = self.impl.strings[nameIndex];
nargs = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
// look up in original hierarchy not enclosing template (variable group)
// see TestSubtemplates.testEvalSTFromAnotherGroup()
st = self.groupThatCreatedThisInstance.getEmbeddedInstanceOf(this, scope, name);
// get n args and store into st's attr list
storeArgs(scope, nargs, st);
sp -= nargs;
operands[++sp] = st;
break;
case Bytecode.INSTR_NEW_IND:
nargs = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = (String)operands[sp-nargs];
st = self.groupThatCreatedThisInstance.getEmbeddedInstanceOf(this, scope, name);
storeArgs(scope, nargs, st);
sp -= nargs;
sp--; // pop template name
operands[++sp] = st;
break;
case Bytecode.INSTR_NEW_BOX_ARGS :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = self.impl.strings[nameIndex];
Map<String, Object> attrs = (ArgumentsMap)operands[sp--];
// look up in original hierarchy not enclosing template (variable group)
// see TestSubtemplates.testEvalSTFromAnotherGroup()
st = self.groupThatCreatedThisInstance.getEmbeddedInstanceOf(this, scope, name);
// get n args and store into st's attr list
storeArgs(scope, attrs, st);
operands[++sp] = st;
break;
case Bytecode.INSTR_SUPER_NEW :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = self.impl.strings[nameIndex];
nargs = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
super_new(scope, name, nargs);
break;
case Bytecode.INSTR_SUPER_NEW_BOX_ARGS :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = self.impl.strings[nameIndex];
attrs = (ArgumentsMap)operands[sp--];
super_new(scope, name, attrs);
break;
case Bytecode.INSTR_STORE_OPTION:
int optionIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
o = operands[sp--]; // value to store
options = (Object[])operands[sp]; // get options
options[optionIndex] = o; // store value into options on stack
break;
case Bytecode.INSTR_STORE_ARG:
nameIndex = getShort(code, ip);
name = self.impl.strings[nameIndex];
ip += Bytecode.OPND_SIZE_IN_BYTES;
o = operands[sp--];
attrs = (ArgumentsMap)operands[sp];
attrs.put(name, o); // leave attrs on stack
break;
case Bytecode.INSTR_WRITE :
o = operands[sp--];
int n1 = writeObjectNoOptions(out, scope, o);
n += n1;
nwline += n1;
break;
case Bytecode.INSTR_WRITE_OPT :
options = (Object[])operands[sp--]; // get options
o = operands[sp--]; // get option to write
int n2 = writeObjectWithOptions(out, scope, o, options);
n += n2;
nwline += n2;
break;
case Bytecode.INSTR_MAP :
st = (ST)operands[sp--]; // get prototype off stack
o = operands[sp--]; // get object to map prototype across
map(scope,o,st);
break;
case Bytecode.INSTR_ROT_MAP :
int nmaps = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
List<ST> templates = new ArrayList<ST>();
for (int i=nmaps-1; i>=0; i--) templates.add((ST)operands[sp-i]);
sp -= nmaps;
o = operands[sp--];
if ( o!=null ) rot_map(scope,o,templates);
break;
case Bytecode.INSTR_ZIP_MAP:
st = (ST)operands[sp--];
nmaps = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
List<Object> exprs = new ObjectList();
for (int i=nmaps-1; i>=0; i--) exprs.add(operands[sp-i]);
sp -= nmaps;
operands[++sp] = zip_map(scope, exprs, st);
break;
case Bytecode.INSTR_BR :
ip = getShort(code, ip);
break;
case Bytecode.INSTR_BRF :
addr = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
o = operands[sp--]; // <if(expr)>...<endif>
if ( !testAttributeTrue(o) ) ip = addr; // jump
break;
case Bytecode.INSTR_OPTIONS :
operands[++sp] = new Object[Compiler.NUM_OPTIONS];
break;
case Bytecode.INSTR_ARGS:
operands[++sp] = new ArgumentsMap();
break;
case Bytecode.INSTR_PASSTHRU :
nameIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
name = self.impl.strings[nameIndex];
attrs = (ArgumentsMap)operands[sp];
passthru(scope, name, attrs);
break;
case Bytecode.INSTR_LIST :
operands[++sp] = new ObjectList();
break;
case Bytecode.INSTR_ADD :
o = operands[sp--]; // pop value
List<Object> list = (ObjectList)operands[sp]; // don't pop list
addToList(scope, list, o);
break;
case Bytecode.INSTR_TOSTR :
// replace with string value; early eval
operands[sp] = toString(out, scope, operands[sp]);
break;
case Bytecode.INSTR_FIRST :
operands[sp] = first(scope, operands[sp]);
break;
case Bytecode.INSTR_LAST :
operands[sp] = last(scope, operands[sp]);
break;
case Bytecode.INSTR_REST :
operands[sp] = rest(scope, operands[sp]);
break;
case Bytecode.INSTR_TRUNC :
operands[sp] = trunc(scope, operands[sp]);
break;
case Bytecode.INSTR_STRIP :
operands[sp] = strip(scope, operands[sp]);
break;
case Bytecode.INSTR_TRIM :
o = operands[sp--];
if ( o.getClass() == String.class ) {
operands[++sp] = ((String)o).trim();
}
else {
errMgr.runTimeError(this, scope, ErrorType.EXPECTING_STRING, "trim", o.getClass().getName());
operands[++sp] = o;
}
break;
case Bytecode.INSTR_LENGTH :
operands[sp] = length(operands[sp]);
break;
case Bytecode.INSTR_STRLEN :
o = operands[sp--];
if ( o.getClass() == String.class ) {
operands[++sp] = ((String)o).length();
}
else {
errMgr.runTimeError(this, scope, ErrorType.EXPECTING_STRING, "strlen", o.getClass().getName());
operands[++sp] = 0;
}
break;
case Bytecode.INSTR_REVERSE :
operands[sp] = reverse(scope, operands[sp]);
break;
case Bytecode.INSTR_NOT :
operands[sp] = !testAttributeTrue(operands[sp]);
break;
case Bytecode.INSTR_OR :
right = operands[sp--];
left = operands[sp--];
operands[++sp] = testAttributeTrue(left) || testAttributeTrue(right);
break;
case Bytecode.INSTR_AND :
right = operands[sp--];
left = operands[sp--];
operands[++sp] = testAttributeTrue(left) && testAttributeTrue(right);
break;
case Bytecode.INSTR_INDENT :
int strIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
indent(out, scope, strIndex);
break;
case Bytecode.INSTR_DEDENT :
out.popIndentation();
break;
case Bytecode.INSTR_NEWLINE :
try {
if ( (prevOpcode==0 && !self.isAnonSubtemplate() && !self.impl.isRegion) ||
prevOpcode==Bytecode.INSTR_NEWLINE ||
prevOpcode==Bytecode.INSTR_INDENT ||
nwline>0 )
{
out.write(Misc.newline);
}
nwline = 0;
}
catch (IOException ioe) {
errMgr.IOError(self, ErrorType.WRITE_IO_ERROR, ioe);
}
break;
case Bytecode.INSTR_NOOP :
break;
case Bytecode.INSTR_POP :
sp--; // throw away top of stack
break;
case Bytecode.INSTR_NULL :
operands[++sp] = null;
break;
case Bytecode.INSTR_TRUE :
operands[++sp] = true;
break;
case Bytecode.INSTR_FALSE :
operands[++sp] = false;
break;
case Bytecode.INSTR_WRITE_STR :
strIndex = getShort(code, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
o = self.impl.strings[strIndex];
n1 = writeObjectNoOptions(out, scope, o);
n += n1;
nwline += n1;
break;
// TODO: generate this optimization
// case Bytecode.INSTR_WRITE_LOCAL:
// valueIndex = getShort(code, ip);
// ip += Bytecode.OPND_SIZE_IN_BYTES;
// o = self.locals[valueIndex];
// if ( o==ST.EMPTY_ATTR ) o = null;
// n1 = writeObjectNoOptions(out, self, o);
// n += n1;
// nwline += n1;
// break;
default :
errMgr.internalError(self, "invalid bytecode @ "+(ip-1)+": "+opcode, null);
self.impl.dump();
}
prevOpcode = opcode;
}
if ( debug ) {
int stop = out.index() - 1;
EvalTemplateEvent e = new EvalTemplateEvent(scope, start, stop);
trackDebugEvent(scope, e);
}
return n;
}
void load_str(ST self, int ip) {
int strIndex = getShort(self.impl.instrs, ip);
ip += Bytecode.OPND_SIZE_IN_BYTES;
operands[++sp] = self.impl.strings[strIndex];
}
// TODO: refactor to remove dup'd code
void super_new(InstanceScope scope, String name, int nargs) {
final ST self = scope.st;
ST st = null;
CompiledST imported = self.impl.nativeGroup.lookupImportedTemplate(name);
if ( imported==null ) {
errMgr.runTimeError(this, scope, ErrorType.NO_IMPORTED_TEMPLATE,
name);
st = self.groupThatCreatedThisInstance.createStringTemplateInternally(new CompiledST());
}
else {
st = imported.nativeGroup.getEmbeddedInstanceOf(this, scope, name);
st.groupThatCreatedThisInstance = group;
}
// get n args and store into st's attr list
storeArgs(scope, nargs, st);
sp -= nargs;
operands[++sp] = st;
}
void super_new(InstanceScope scope, String name, Map<String,Object> attrs) {
final ST self = scope.st;
ST st = null;
CompiledST imported = self.impl.nativeGroup.lookupImportedTemplate(name);
if ( imported==null ) {
errMgr.runTimeError(this, scope, ErrorType.NO_IMPORTED_TEMPLATE,
name);
st = self.groupThatCreatedThisInstance.createStringTemplateInternally(new CompiledST());
}
else {
st = imported.nativeGroup.createStringTemplateInternally(imported);
st.groupThatCreatedThisInstance = group;
}
// get n args and store into st's attr list
storeArgs(scope, attrs, st);
operands[++sp] = st;
}
void passthru(InstanceScope scope, String templateName, Map<String,Object> attrs) {
CompiledST c = group.lookupTemplate(templateName);
if ( c==null ) return; // will get error later
if ( c.formalArguments==null ) return;
for (FormalArgument arg : c.formalArguments.values()) {
// if not already set by user, set to value from outer scope
if ( !attrs.containsKey(arg.name) ) {
//System.out.println("arg "+arg.name+" missing");
try {
Object o = getAttribute(scope, arg.name);
// If the attribute exists but there is no value and
// the formal argument has no default value, make it null.
if ( o==ST.EMPTY_ATTR && arg.defaultValueToken==null ) {
attrs.put(arg.name, null);
}
// Else, the attribute has an existing value, set arg.
else if ( o!=ST.EMPTY_ATTR ) {
attrs.put(arg.name, o);
}
}
catch (STNoSuchAttributeException nsae) {
// if no such attribute exists for arg.name, set parameter
// if no default value
if ( arg.defaultValueToken==null ) {
errMgr.runTimeError(this, scope, ErrorType.NO_SUCH_ATTRIBUTE_PASS_THROUGH, arg.name);
attrs.put(arg.name, null);
}
}
}
}
}
void storeArgs(InstanceScope scope, Map<String,Object> attrs, ST st) {
boolean noSuchAttributeReported = false;
if (attrs != null) {
for (Map.Entry<String, Object> argument : attrs.entrySet()) {
if (!st.impl.hasFormalArgs) {
if (st.impl.formalArguments == null || !st.impl.formalArguments.containsKey(argument.getKey())) {
try {
// we clone the CompiledST to prevent modifying the original
// formalArguments map during interpretation.
st.impl = st.impl.clone();
st.add(argument.getKey(), argument.getValue());
} catch (CloneNotSupportedException ex) {
noSuchAttributeReported = true;
errMgr.runTimeError(this, scope,
ErrorType.NO_SUCH_ATTRIBUTE,
argument.getKey());
}
}
else {
st.rawSetAttribute(argument.getKey(), argument.getValue());
}
}
else {
// don't let it throw an exception in rawSetAttribute
if ( st.impl.formalArguments==null || !st.impl.formalArguments.containsKey(argument.getKey()) ) {
noSuchAttributeReported = true;
errMgr.runTimeError(this, scope,
ErrorType.NO_SUCH_ATTRIBUTE,
argument.getKey());
continue;
}
st.rawSetAttribute(argument.getKey(), argument.getValue());
}
}
}
if (st.impl.hasFormalArgs) {
boolean argumentCountMismatch = false;
Map<String, FormalArgument> formalArguments = st.impl.formalArguments;
if (formalArguments == null) {
formalArguments = Collections.emptyMap();
}
// first make sure that all non-default arguments are specified
// ignore this check if a NO_SUCH_ATTRIBUTE error already occurred
if (!noSuchAttributeReported) {
for (Map.Entry<String, FormalArgument> formalArgument : formalArguments.entrySet()) {
if (formalArgument.getValue().defaultValueToken != null || formalArgument.getValue().defaultValue != null) {
// this argument has a default value, so it doesn't need to appear in attrs
continue;
}
if (attrs == null || !attrs.containsKey(formalArgument.getKey())) {
argumentCountMismatch = true;
break;
}
}
}
// next make sure there aren't too many arguments. note that the names
// of arguments are checked below as they are applied to the template
// instance, so there's no need to do that here.
if (attrs != null && attrs.size() > formalArguments.size()) {
argumentCountMismatch = true;
}
if (argumentCountMismatch) {
int nargs = attrs != null ? attrs.size() : 0;
int nformalArgs = formalArguments.size();
errMgr.runTimeError(this, scope,
ErrorType.ARGUMENT_COUNT_MISMATCH,
nargs,
st.impl.name,
nformalArgs);
}
}
}
void storeArgs(InstanceScope scope, int nargs, ST st) {
if ( nargs>0 && !st.impl.hasFormalArgs && st.impl.formalArguments==null ) {
st.add(ST.IMPLICIT_ARG_NAME, null); // pretend we have "it" arg
}
int nformalArgs = 0;
if ( st.impl.formalArguments!=null ) nformalArgs = st.impl.formalArguments.size();
int firstArg = sp-(nargs-1);
int numToStore = Math.min(nargs, nformalArgs);
if ( st.impl.isAnonSubtemplate ) nformalArgs -= predefinedAnonSubtemplateAttributes.size();
if ( nargs < (nformalArgs-st.impl.numberOfArgsWithDefaultValues) ||
nargs > nformalArgs )
{
errMgr.runTimeError(this, scope,
ErrorType.ARGUMENT_COUNT_MISMATCH,
nargs,
st.impl.name,
nformalArgs);
}
if ( st.impl.formalArguments==null ) return;
Iterator<String> argNames = st.impl.formalArguments.keySet().iterator();
for (int i=0; i<numToStore; i++) {
Object o = operands[firstArg+i]; // value to store
String argName = argNames.next();
st.rawSetAttribute(argName, o);
}
}
protected void indent(STWriter out, InstanceScope scope, int strIndex) {
String indent = scope.st.impl.strings[strIndex];
if ( debug ) {
int start = out.index(); // track char we're about to write
EvalExprEvent e = new IndentEvent(scope,
start, start + indent.length() - 1,
getExprStartChar(scope),
getExprStopChar(scope));
trackDebugEvent(scope, e);
}
out.pushIndentation(indent);
}
/** Write out an expression result that doesn't use expression options.
* E.g., {@code <name>}
*/
protected int writeObjectNoOptions(STWriter out, InstanceScope scope, Object o) {
int start = out.index(); // track char we're about to write
int n = writeObject(out, scope, o, null);
if ( debug ) {
EvalExprEvent e = new EvalExprEvent(scope,
start, out.index() - 1,
getExprStartChar(scope),
getExprStopChar(scope));
trackDebugEvent(scope, e);
}
return n;
}
/** Write out an expression result that uses expression options.
* E.g., {@code <names; separator=", ">}
*/
protected int writeObjectWithOptions(STWriter out, InstanceScope scope, Object o,
Object[] options)
{
int start = out.index(); // track char we're about to write
// precompute all option values (render all the way to strings)
String[] optionStrings = null;
if ( options!=null ) {
optionStrings = new String[options.length];
for (int i=0; i<Compiler.NUM_OPTIONS; i++) {
optionStrings[i] = toString(out, scope, options[i]);
}
}
if ( options!=null && options[Option.ANCHOR.ordinal()]!=null ) {
out.pushAnchorPoint();
}
int n = writeObject(out, scope, o, optionStrings);
if ( options!=null && options[Option.ANCHOR.ordinal()]!=null ) {
out.popAnchorPoint();
}
if ( debug ) {
EvalExprEvent e = new EvalExprEvent(scope,
start, out.index() - 1,
getExprStartChar(scope),
getExprStopChar(scope));
trackDebugEvent(scope, e);
}
return n;
}
/** Generic method to emit text for an object. It differentiates
* between templates, iterable objects, and plain old Java objects (POJOs)
*/
protected int writeObject(STWriter out, InstanceScope scope, Object o, String[] options) {
int n = 0;
if ( o == null ) {
if ( options!=null && options[Option.NULL.ordinal()]!=null ) {
o = options[Option.NULL.ordinal()];
}
else return 0;
}
if ( o instanceof ST ) {
scope = new InstanceScope(scope, (ST)o);
if ( options!=null && options[Option.WRAP.ordinal()]!=null ) {
// if we have a wrap string, then inform writer it
// might need to wrap
try {
out.writeWrap(options[Option.WRAP.ordinal()]);
}
catch (IOException ioe) {
errMgr.IOError(scope.st, ErrorType.WRITE_IO_ERROR, ioe);
}
}
n = exec(out, scope);
}
else {
o = convertAnythingIteratableToIterator(scope, o); // normalize
try {
if ( o instanceof Iterator) n = writeIterator(out, scope, o, options);
else n = writePOJO(out, scope, o, options);
}
catch (IOException ioe) {
errMgr.IOError(scope.st, ErrorType.WRITE_IO_ERROR, ioe, o);
}
}
return n;
}
protected int writeIterator(STWriter out, InstanceScope scope, Object o, String[] options) throws IOException {
if ( o==null ) return 0;
int n = 0;
Iterator<?> it = (Iterator<?>)o;
String separator = null;
if ( options!=null ) separator = options[Option.SEPARATOR.ordinal()];
boolean seenAValue = false;
while ( it.hasNext() ) {
Object iterValue = it.next();
// Emit separator if we're beyond first value
boolean needSeparator = seenAValue &&
separator!=null && // we have a separator and
(iterValue!=null || // either we have a value
options[Option.NULL.ordinal()]!=null); // or no value but null option
if ( needSeparator ) n += out.writeSeparator(separator);
int nw = writeObject(out, scope, iterValue, options);
if ( nw > 0 ) seenAValue = true;
n += nw;
}
return n;
}
protected int writePOJO(STWriter out, InstanceScope scope, Object o, String[] options) throws IOException {
String formatString = null;
if ( options!=null ) formatString = options[Option.FORMAT.ordinal()];
String v = renderObject(scope, formatString, o, o.getClass());
int n;
if ( options!=null && options[Option.WRAP.ordinal()]!=null ) {
n = out.write(v, options[Option.WRAP.ordinal()]);
}
else {
n = out.write(v);
}
return n;
}
private <T> String renderObject(InstanceScope scope, String formatString, Object o, Class<T> attributeType) {
// ask the native group defining the surrounding template for the renderer
AttributeRenderer<? super T> r = scope.st.impl.nativeGroup.getAttributeRenderer(attributeType);
if ( r!=null ) {
return r.toString(attributeType.cast(o), formatString, locale);
} else {
return o.toString();
}
}
protected int getExprStartChar(InstanceScope scope) {
Interval templateLocation = scope.st.impl.sourceMap[scope.ip];
if ( templateLocation!=null ) return templateLocation.a;
return -1;
}
protected int getExprStopChar(InstanceScope scope) {
Interval templateLocation = scope.st.impl.sourceMap[scope.ip];
if ( templateLocation!=null ) return templateLocation.b;
return -1;
}
protected void map(InstanceScope scope, Object attr, final ST st) {
rot_map(scope, attr, Collections.singletonList(st));
}
/**
* Renders expressions of the form {@code <names:a()>} or
* {@code <names:a(),b()>}.
*/
protected void rot_map(InstanceScope scope, Object attr, List<ST> prototypes) {
if ( attr==null ) {
operands[++sp] = null;
return;
}
attr = convertAnythingIteratableToIterator(scope, attr);
if ( attr instanceof Iterator ) {
List<ST> mapped = rot_map_iterator(scope, (Iterator) attr, prototypes);
operands[++sp] = mapped;
}
else { // if only single value, just apply first template to sole value
ST proto = prototypes.get(0);
ST st = group.createStringTemplateInternally(proto);
if ( st!=null ) {
setFirstArgument(scope, st, attr);
if ( st.impl.isAnonSubtemplate ) {
st.rawSetAttribute("i0", 0);
st.rawSetAttribute("i", 1);
}
operands[++sp] = st;
}
else {
operands[++sp] = null;
}
}
}
protected List<ST> rot_map_iterator(InstanceScope scope, Iterator<?> attr, List<ST> prototypes) {
List<ST> mapped = new ArrayList<ST>();
Iterator<?> iter = attr;
int i0 = 0;
int i = 1;
int ti = 0;
while ( iter.hasNext() ) {
Object iterValue = iter.next();
if ( iterValue == null ) { mapped.add(null); continue; }
int templateIndex = ti % prototypes.size(); // rotate through
ti++;
ST proto = prototypes.get(templateIndex);
ST st = group.createStringTemplateInternally(proto);
setFirstArgument(scope, st, iterValue);
if ( st.impl.isAnonSubtemplate ) {
st.rawSetAttribute("i0", i0);
st.rawSetAttribute("i", i);
}
mapped.add(st);
i0++;
i++;
}
return mapped;
}
/**
* Renders expressions of the form {@code <names,phones:{n,p | ...}>} or
* {@code <a,b:t()>}.
*/
// todo: i, i0 not set unless mentioned? map:{k,v | ..}?
protected ST.AttributeList zip_map(InstanceScope scope, List<Object> exprs, ST prototype) {
if ( exprs==null || prototype==null || exprs.size()==0 ) {
return null; // do not apply if missing templates or empty values
}
// make everything iterable
for (int i = 0; i < exprs.size(); i++) {
Object attr = exprs.get(i);
if ( attr!=null ) exprs.set(i, convertAnythingToIterator(scope, attr));
}
// ensure arguments line up
int numExprs = exprs.size();
CompiledST code = prototype.impl;
Map<String, FormalArgument> formalArguments = code.formalArguments;
if ( !code.hasFormalArgs || formalArguments==null ) {
errMgr.runTimeError(this, scope, ErrorType.MISSING_FORMAL_ARGUMENTS);
return null;
}
// todo: track formal args not names for efficient filling of locals
String[] formalArgumentNames = formalArguments.keySet().toArray(new String[formalArguments.size()]);
int nformalArgs = formalArgumentNames.length;
if ( prototype.isAnonSubtemplate() ) nformalArgs -= predefinedAnonSubtemplateAttributes.size();
if ( nformalArgs != numExprs ) {
errMgr.runTimeError(this, scope,
ErrorType.MAP_ARGUMENT_COUNT_MISMATCH,
numExprs,
nformalArgs);
// TODO just fill first n
// truncate arg list to match smaller size
int shorterSize = Math.min(formalArgumentNames.length, numExprs);
numExprs = shorterSize;
String[] newFormalArgumentNames = new String[shorterSize];
System.arraycopy(formalArgumentNames, 0,
newFormalArgumentNames, 0,
shorterSize);
formalArgumentNames = newFormalArgumentNames;
}
// keep walking while at least one attribute has values
ST.AttributeList results = new ST.AttributeList();
int i = 0; // iteration number from 0
while ( true ) {
// get a value for each attribute in list; put into ST instance
int numEmpty = 0;
ST embedded = group.createStringTemplateInternally(prototype);
embedded.rawSetAttribute("i0", i);
embedded.rawSetAttribute("i", i+1);
for (int a = 0; a < numExprs; a++) {
Iterator<?> it = (Iterator<?>) exprs.get(a);
if ( it!=null && it.hasNext() ) {
String argName = formalArgumentNames[a];
Object iteratedValue = it.next();
embedded.rawSetAttribute(argName, iteratedValue);
}
else {
numEmpty++;
}
}
if ( numEmpty==numExprs ) break;
results.add(embedded);
i++;
}
return results;
}
protected void setFirstArgument(InstanceScope scope, ST st, Object attr) {
if ( !st.impl.hasFormalArgs ) {
if ( st.impl.formalArguments==null ) {
st.add(ST.IMPLICIT_ARG_NAME, attr);
return;
}
// else fall thru to set locals[0]
}
if ( st.impl.formalArguments==null ) {
errMgr.runTimeError(this, scope,
ErrorType.ARGUMENT_COUNT_MISMATCH,
1,
st.impl.name,
0);
return;
}
st.locals[0] = attr;
}
protected void addToList(InstanceScope scope, List<Object> list, Object o) {
o = convertAnythingIteratableToIterator(scope, o);
if ( o instanceof Iterator ) {
// copy of elements into our temp list
Iterator<?> it = (Iterator<?>)o;
while (it.hasNext()) list.add(it.next());
}
else {
list.add(o);
}
}
/**
* Return the first attribute if multi-valued, or the attribute itself if
* single-valued.
* <p>
* This method is used for rendering expressions of the form
* {@code <names:first()>}.</p>
*/
public Object first(InstanceScope scope, Object v) {
if ( v==null ) return null;
Object r = v;