-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathtwig.expression.js
1395 lines (1224 loc) · 53.2 KB
/
twig.expression.js
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
// ## twig.expression.js
//
// This file handles tokenizing, compiling and parsing expressions.
module.exports = function (Twig) {
'use strict';
function parseParams(state, params, context) {
if (params) {
return Twig.expression.parseAsync.call(state, params, context);
}
return Twig.Promise.resolve(false);
}
/**
* Namespace for expression handling.
*/
Twig.expression = { };
require('./twig.expression.operator')(Twig);
/**
* Reserved word that can't be used as variable names.
*/
Twig.expression.reservedWords = [
'true', 'false', 'null', 'TRUE', 'FALSE', 'NULL', '_context', 'and', 'b-and', 'or', 'b-or', 'b-xor', 'in', 'not in', 'if', 'matches', 'starts', 'ends', 'with'
];
/**
* The type of tokens used in expressions.
*/
Twig.expression.type = {
comma: 'Twig.expression.type.comma',
operator: {
unary: 'Twig.expression.type.operator.unary',
binary: 'Twig.expression.type.operator.binary'
},
string: 'Twig.expression.type.string',
bool: 'Twig.expression.type.bool',
slice: 'Twig.expression.type.slice',
array: {
start: 'Twig.expression.type.array.start',
end: 'Twig.expression.type.array.end'
},
object: {
start: 'Twig.expression.type.object.start',
end: 'Twig.expression.type.object.end'
},
parameter: {
start: 'Twig.expression.type.parameter.start',
end: 'Twig.expression.type.parameter.end'
},
subexpression: {
start: 'Twig.expression.type.subexpression.start',
end: 'Twig.expression.type.subexpression.end'
},
key: {
period: 'Twig.expression.type.key.period',
brackets: 'Twig.expression.type.key.brackets'
},
filter: 'Twig.expression.type.filter',
_function: 'Twig.expression.type._function',
variable: 'Twig.expression.type.variable',
number: 'Twig.expression.type.number',
_null: 'Twig.expression.type.null',
context: 'Twig.expression.type.context',
test: 'Twig.expression.type.test'
};
Twig.expression.set = {
// What can follow an expression (in general)
operations: [
Twig.expression.type.filter,
Twig.expression.type.operator.unary,
Twig.expression.type.operator.binary,
Twig.expression.type.array.end,
Twig.expression.type.object.end,
Twig.expression.type.parameter.end,
Twig.expression.type.subexpression.end,
Twig.expression.type.comma,
Twig.expression.type.test
],
expressions: [
Twig.expression.type._function,
Twig.expression.type.bool,
Twig.expression.type.string,
Twig.expression.type.variable,
Twig.expression.type.number,
Twig.expression.type._null,
Twig.expression.type.context,
Twig.expression.type.parameter.start,
Twig.expression.type.array.start,
Twig.expression.type.object.start,
Twig.expression.type.subexpression.start,
Twig.expression.type.operator.unary
]
};
// Most expressions allow a '.' or '[' after them, so we provide a convenience set
Twig.expression.set.operationsExtended = Twig.expression.set.operations.concat([
Twig.expression.type.key.period,
Twig.expression.type.key.brackets,
Twig.expression.type.slice
]);
// Some commonly used compile and parse functions.
Twig.expression.fn = {
compile: {
push(token, stack, output) {
output.push(token);
},
pushBoth(token, stack, output) {
output.push(token);
stack.push(token);
}
},
parse: {
push(token, stack) {
stack.push(token);
},
pushValue(token, stack) {
stack.push(token.value);
}
}
};
// The regular expressions and compile/parse logic used to match tokens in expressions.
//
// Properties:
//
// type: The type of expression this matches
//
// regex: One or more regular expressions that matche the format of the token.
//
// next: Valid tokens that can occur next in the expression.
//
// Functions:
//
// compile: A function that compiles the raw regular expression match into a token.
//
// parse: A function that parses the compiled token into output.
//
Twig.expression.definitions = [
{
type: Twig.expression.type.test,
regex: /^is\s+(not)?\s*([a-zA-Z_]\w*(\s?(?:as|by))?)/,
next: Twig.expression.set.operations.concat([Twig.expression.type.parameter.start]),
compile(token, stack, output) {
token.filter = token.match[2];
token.modifier = token.match[1];
delete token.match;
delete token.value;
output.push(token);
},
parse(token, stack, context) {
const value = stack.pop();
const state = this;
return parseParams(state, token.params, context)
.then(params => {
const result = Twig.test(token.filter, value, params);
if (token.modifier === 'not') {
stack.push(!result);
} else {
stack.push(result);
}
});
}
},
{
type: Twig.expression.type.comma,
// Match a comma
regex: /^,/,
next: Twig.expression.set.expressions.concat([Twig.expression.type.array.end, Twig.expression.type.object.end]),
compile(token, stack, output) {
let i = stack.length - 1;
let stackToken;
delete token.match;
delete token.value;
// Pop tokens off the stack until the start of the object
for (;i >= 0; i--) {
stackToken = stack.pop();
if (stackToken.type === Twig.expression.type.object.start ||
stackToken.type === Twig.expression.type.parameter.start ||
stackToken.type === Twig.expression.type.array.start) {
stack.push(stackToken);
break;
}
output.push(stackToken);
}
output.push(token);
}
},
{
/**
* Match a number (integer or decimal)
*/
type: Twig.expression.type.number,
// Match a number
regex: /^-?\d+(\.\d+)?/,
next: Twig.expression.set.operations,
compile(token, stack, output) {
token.value = Number(token.value);
output.push(token);
},
parse: Twig.expression.fn.parse.pushValue
},
{
type: Twig.expression.type.operator.binary,
// Match any of ??, ?:, +, *, /, -, %, ~, <=>, <, <=, >, >=, !=, ==, **, ?, :, and, b-and, or, b-or, b-xor, in, not in
// and, or, in, not in, matches, starts with, ends with can be followed by a space or parenthesis
regex: /(^\?\?|^\?:|^(b-and)|^(b-or)|^(b-xor)|^[+\-~%?]|^(<=>)|^[:](?!\d\])|^[!=]==?|^[!<>]=?|^\*\*?|^\/\/?|^(and)[(|\s+]|^(or)[(|\s+]|^(in)[(|\s+]|^(not in)[(|\s+]|^(matches)|^(starts with)|^(ends with)|^\.\.)/,
next: Twig.expression.set.expressions,
transform(match, tokens) {
switch (match[0]) {
case 'and(':
case 'or(':
case 'in(':
case 'not in(':
// Strip off the ( if it exists
tokens[tokens.length - 1].value = match[2];
return match[0];
default:
return '';
}
},
compile(token, stack, output) {
delete token.match;
token.value = token.value.trim();
const {value} = token;
const operator = Twig.expression.operator.lookup(value, token);
Twig.log.trace('Twig.expression.compile: ', 'Operator: ', operator, ' from ', value);
while (stack.length > 0 &&
(stack[stack.length - 1].type === Twig.expression.type.operator.unary || stack[stack.length - 1].type === Twig.expression.type.operator.binary) &&
(
(operator.associativity === Twig.expression.operator.leftToRight &&
operator.precidence >= stack[stack.length - 1].precidence) ||
(operator.associativity === Twig.expression.operator.rightToLeft &&
operator.precidence > stack[stack.length - 1].precidence)
)
) {
const temp = stack.pop();
output.push(temp);
}
if (value === ':') {
// Check if this is a ternary or object key being set
if (stack[stack.length - 1] && stack[stack.length - 1].value === '?') {
// Continue as normal for a ternary
} else {
// This is not a ternary so we push the token to the output where it can be handled
// when the assocated object is closed.
const keyToken = output.pop();
if (keyToken.type === Twig.expression.type.string ||
keyToken.type === Twig.expression.type.variable) {
token.key = keyToken.value;
} else if (keyToken.type === Twig.expression.type.number) {
// Convert integer keys into string keys
token.key = keyToken.value.toString();
} else if (keyToken.expression &&
(keyToken.type === Twig.expression.type.parameter.end ||
keyToken.type === Twig.expression.type.subexpression.end)) {
token.params = keyToken.params;
} else {
throw new Twig.Error('Unexpected value before \':\' of ' + keyToken.type + ' = ' + keyToken.value);
}
output.push(token);
}
} else {
stack.push(operator);
}
},
parse(token, stack, context) {
const state = this;
if (token.key) {
// Handle ternary ':' operator
stack.push(token);
} else if (token.params) {
// Handle "{(expression):value}"
return Twig.expression.parseAsync.call(state, token.params, context)
.then(key => {
token.key = key;
stack.push(token);
// If we're in a loop, we might need token.params later, especially in this form of "(expression):value"
if (!context.loop) {
delete (token.params);
}
});
} else {
Twig.expression.operator.parse(token.value, stack);
}
}
},
{
type: Twig.expression.type.operator.unary,
// Match any of not
regex: /(^not\s+)/,
next: Twig.expression.set.expressions,
compile(token, stack, output) {
delete token.match;
token.value = token.value.trim();
const {value} = token;
const operator = Twig.expression.operator.lookup(value, token);
Twig.log.trace('Twig.expression.compile: ', 'Operator: ', operator, ' from ', value);
while (stack.length > 0 &&
(stack[stack.length - 1].type === Twig.expression.type.operator.unary || stack[stack.length - 1].type === Twig.expression.type.operator.binary) &&
(
(operator.associativity === Twig.expression.operator.leftToRight &&
operator.precidence >= stack[stack.length - 1].precidence) ||
(operator.associativity === Twig.expression.operator.rightToLeft &&
operator.precidence > stack[stack.length - 1].precidence)
)
) {
const temp = stack.pop();
output.push(temp);
}
stack.push(operator);
},
parse(token, stack) {
Twig.expression.operator.parse(token.value, stack);
}
},
{
/**
* Match a string. This is anything between a pair of single or double quotes.
*/
type: Twig.expression.type.string,
// See: http://blog.stevenlevithan.com/archives/match-quoted-string
regex: /^(["'])(?:(?=(\\?))\2[\s\S])*?\1/,
next: Twig.expression.set.operationsExtended,
compile(token, stack, output) {
let {value} = token;
delete token.match;
// Remove the quotes from the string
if (value.slice(0, 1) === '"') {
value = value.replace('\\"', '"');
} else {
value = value.replace('\\\'', '\'');
}
token.value = value.slice(1, -1).replace(/\\n/g, '\n').replace(/\\r/g, '\r');
Twig.log.trace('Twig.expression.compile: ', 'String value: ', token.value);
output.push(token);
},
parse: Twig.expression.fn.parse.pushValue
},
{
/**
* Match a subexpression set start.
*/
type: Twig.expression.type.subexpression.start,
regex: /^\(/,
next: Twig.expression.set.expressions.concat([Twig.expression.type.subexpression.end]),
compile(token, stack, output) {
token.value = '(';
output.push(token);
stack.push(token);
},
parse: Twig.expression.fn.parse.push
},
{
/**
* Match a subexpression set end.
*/
type: Twig.expression.type.subexpression.end,
regex: /^\)/,
next: Twig.expression.set.operationsExtended,
validate(match, tokens) {
// Iterate back through previous tokens to ensure we follow a subexpression start
let i = tokens.length - 1;
let foundSubexpressionStart = false;
let nextSubexpressionStartInvalid = false;
let unclosedParameterCount = 0;
while (!foundSubexpressionStart && i >= 0) {
const token = tokens[i];
foundSubexpressionStart = token.type === Twig.expression.type.subexpression.start;
// If we have previously found a subexpression end, then this subexpression start is the start of
// that subexpression, not the subexpression we are searching for
if (foundSubexpressionStart && nextSubexpressionStartInvalid) {
nextSubexpressionStartInvalid = false;
foundSubexpressionStart = false;
}
// Count parameter tokens to ensure we dont return truthy for a parameter opener
if (token.type === Twig.expression.type.parameter.start) {
unclosedParameterCount++;
} else if (token.type === Twig.expression.type.parameter.end) {
unclosedParameterCount--;
} else if (token.type === Twig.expression.type.subexpression.end) {
nextSubexpressionStartInvalid = true;
}
i--;
}
// If we found unclosed parameters, return false
// If we didnt find subexpression start, return false
// Otherwise return true
return (foundSubexpressionStart && (unclosedParameterCount === 0));
},
compile(token, stack, output) {
// This is basically a copy of parameter end compilation
let stackToken;
const endToken = token;
stackToken = stack.pop();
while (stack.length > 0 && stackToken.type !== Twig.expression.type.subexpression.start) {
output.push(stackToken);
stackToken = stack.pop();
}
// Move contents of parens into preceding filter
const paramStack = [];
while (token.type !== Twig.expression.type.subexpression.start) {
// Add token to arguments stack
paramStack.unshift(token);
token = output.pop();
}
paramStack.unshift(token);
// If the token at the top of the *stack* is a function token, pop it onto the output queue.
// Get the token preceding the parameters
stackToken = stack[stack.length - 1];
if (stackToken === undefined ||
(stackToken.type !== Twig.expression.type._function &&
stackToken.type !== Twig.expression.type.filter &&
stackToken.type !== Twig.expression.type.test &&
stackToken.type !== Twig.expression.type.key.brackets)) {
endToken.expression = true;
// Remove start and end token from stack
paramStack.pop();
paramStack.shift();
endToken.params = paramStack;
output.push(endToken);
} else {
// This should never be hit
endToken.expression = false;
stackToken.params = paramStack;
}
},
parse(token, stack, context) {
const state = this;
if (token.expression) {
return Twig.expression.parseAsync.call(state, token.params, context)
.then(value => {
stack.push(value);
});
}
throw new Twig.Error('Unexpected subexpression end when token is not marked as an expression');
}
},
{
/**
* Match a parameter set start.
*/
type: Twig.expression.type.parameter.start,
regex: /^\(/,
next: Twig.expression.set.expressions.concat([Twig.expression.type.parameter.end]),
validate(match, tokens) {
const lastToken = tokens[tokens.length - 1];
// We can't use the regex to test if we follow a space because expression is trimmed
return lastToken && (!Twig.expression.reservedWords.includes(lastToken.value.trim()));
},
compile: Twig.expression.fn.compile.pushBoth,
parse: Twig.expression.fn.parse.push
},
{
/**
* Match a parameter set end.
*/
type: Twig.expression.type.parameter.end,
regex: /^\)/,
next: Twig.expression.set.operationsExtended,
compile(token, stack, output) {
let stackToken;
const endToken = token;
stackToken = stack.pop();
while (stack.length > 0 && stackToken.type !== Twig.expression.type.parameter.start) {
output.push(stackToken);
stackToken = stack.pop();
}
// Move contents of parens into preceding filter
const paramStack = [];
while (token.type !== Twig.expression.type.parameter.start) {
// Add token to arguments stack
paramStack.unshift(token);
token = output.pop();
}
paramStack.unshift(token);
// Get the token preceding the parameters
token = output[output.length - 1];
if (token === undefined ||
(token.type !== Twig.expression.type._function &&
token.type !== Twig.expression.type.filter &&
token.type !== Twig.expression.type.test &&
token.type !== Twig.expression.type.key.brackets)) {
endToken.expression = true;
// Remove start and end token from stack
paramStack.pop();
paramStack.shift();
endToken.params = paramStack;
output.push(endToken);
} else {
endToken.expression = false;
token.params = paramStack;
}
},
parse(token, stack, context) {
const newArray = [];
let arrayEnded = false;
let value = null;
const state = this;
if (token.expression) {
return Twig.expression.parseAsync.call(state, token.params, context)
.then(value => {
stack.push(value);
});
}
while (stack.length > 0) {
value = stack.pop();
// Push values into the array until the start of the array
if (value && value.type && value.type === Twig.expression.type.parameter.start) {
arrayEnded = true;
break;
}
newArray.unshift(value);
}
if (!arrayEnded) {
throw new Twig.Error('Expected end of parameter set.');
}
stack.push(newArray);
}
},
{
type: Twig.expression.type.slice,
regex: /^\[(-?\w*:-?\w*)\]/,
next: Twig.expression.set.operationsExtended,
compile(token, stack, output) {
const sliceRange = token.match[1].split(':');
// SliceStart can be undefined when we pass parameters to the slice filter later
const sliceStart = sliceRange[0];
const sliceEnd = sliceRange[1];
token.value = 'slice';
token.params = [sliceStart, sliceEnd];
// SliceEnd can't be undefined as the slice filter doesn't check for this, but it does check the length
// of the params array, so just shorten it.
if (!sliceEnd) {
token.params = [sliceStart];
}
output.push(token);
},
parse(token, stack, context) {
const input = stack.pop();
let {params} = token;
const state = this;
if (parseInt(params[0], 10).toString() === params[0]) {
params[0] = parseInt(params[0], 10);
} else {
const value = context[params[0]];
if (state.template.options.strictVariables && value === undefined) {
throw new Twig.Error('Variable "' + params[0] + '" does not exist.');
}
params[0] = value;
}
if (params[1]) {
if (parseInt(params[1], 10).toString() === params[1]) {
params[1] = parseInt(params[1], 10);
} else {
const value = context[params[1]];
if (state.template.options.strictVariables && value === undefined) {
throw new Twig.Error('Variable "' + params[1] + '" does not exist.');
}
if (value === undefined) {
params = [params[0]];
} else {
params[1] = value;
}
}
}
stack.push(Twig.filter.call(state, token.value, input, params));
}
},
{
/**
* Match an array start.
*/
type: Twig.expression.type.array.start,
regex: /^\[/,
next: Twig.expression.set.expressions.concat([Twig.expression.type.array.end]),
compile: Twig.expression.fn.compile.pushBoth,
parse: Twig.expression.fn.parse.push
},
{
/**
* Match an array end.
*/
type: Twig.expression.type.array.end,
regex: /^\]/,
next: Twig.expression.set.operationsExtended,
compile(token, stack, output) {
let i = stack.length - 1;
let stackToken;
// Pop tokens off the stack until the start of the object
for (;i >= 0; i--) {
stackToken = stack.pop();
if (stackToken.type === Twig.expression.type.array.start) {
break;
}
output.push(stackToken);
}
output.push(token);
},
parse(token, stack) {
const newArray = [];
let arrayEnded = false;
let value = null;
while (stack.length > 0) {
value = stack.pop();
// Push values into the array until the start of the array
if (value && value.type && value.type === Twig.expression.type.array.start) {
arrayEnded = true;
break;
}
newArray.unshift(value);
}
if (!arrayEnded) {
throw new Twig.Error('Expected end of array.');
}
stack.push(newArray);
}
},
// Token that represents the start of a hash map '}'
//
// Hash maps take the form:
// { "key": 'value', "another_key": item }
//
// Keys must be quoted (either single or double) and values can be any expression.
{
type: Twig.expression.type.object.start,
regex: /^\{/,
next: Twig.expression.set.expressions.concat([Twig.expression.type.object.end]),
compile: Twig.expression.fn.compile.pushBoth,
parse: Twig.expression.fn.parse.push
},
// Token that represents the end of a Hash Map '}'
//
// This is where the logic for building the internal
// representation of a hash map is defined.
{
type: Twig.expression.type.object.end,
regex: /^\}/,
next: Twig.expression.set.operationsExtended,
compile(token, stack, output) {
let i = stack.length - 1;
let stackToken;
// Pop tokens off the stack until the start of the object
for (;i >= 0; i--) {
stackToken = stack.pop();
if (stackToken && stackToken.type === Twig.expression.type.object.start) {
break;
}
output.push(stackToken);
}
output.push(token);
},
parse(endToken, stack) {
const newObject = {};
let objectEnded = false;
let token = null;
let hasValue = false;
let value = null;
while (stack.length > 0) {
token = stack.pop();
// Push values into the array until the start of the object
if (token && token.type && token.type === Twig.expression.type.object.start) {
objectEnded = true;
break;
}
if (token && token.type && (token.type === Twig.expression.type.operator.binary || token.type === Twig.expression.type.operator.unary) && token.key) {
if (!hasValue) {
throw new Twig.Error('Missing value for key \'' + token.key + '\' in object definition.');
}
newObject[token.key] = value;
// Preserve the order that elements are added to the map
// This is necessary since JavaScript objects don't
// guarantee the order of keys
if (newObject._keys === undefined) {
newObject._keys = [];
}
newObject._keys.unshift(token.key);
// Reset value check
value = null;
hasValue = false;
} else {
hasValue = true;
value = token;
}
}
if (!objectEnded) {
throw new Twig.Error('Unexpected end of object.');
}
stack.push(newObject);
}
},
// Token representing a filter
//
// Filters can follow any expression and take the form:
// expression|filter(optional, args)
//
// Filter parsing is done in the Twig.filters namespace.
{
type: Twig.expression.type.filter,
// Match a | then a letter or _, then any number of letters, numbers, _ or -
regex: /^\|\s?([a-zA-Z_][a-zA-Z0-9_-]*)/,
next: Twig.expression.set.operationsExtended.concat([
Twig.expression.type.parameter.start
]),
compile(token, stack, output) {
token.value = token.match[1];
output.push(token);
},
parse(token, stack, context) {
const input = stack.pop();
const state = this;
return parseParams(state, token.params, context)
.then(params => {
return Twig.filter.call(state, token.value, input, params);
})
.then(value => {
stack.push(value);
});
}
},
{
type: Twig.expression.type._function,
// Match any letter or _, then any number of letters, numbers, _ or - followed by (
regex: /^([a-zA-Z_]\w*)\s*\(/,
next: Twig.expression.type.parameter.start,
validate(match) {
// Make sure this function is not a reserved word
return match[1] && (!Twig.expression.reservedWords.includes(match[1]));
},
transform() {
return '(';
},
compile(token, stack, output) {
const fn = token.match[1];
token.fn = fn;
// Cleanup token
delete token.match;
delete token.value;
output.push(token);
},
parse(token, stack, context) {
const state = this;
const {fn} = token;
let value;
return parseParams(state, token.params, context)
.then(params => {
if (Twig.functions[fn]) {
// Get the function from the built-in functions
value = Twig.functions[fn].apply(state, params);
} else if (typeof context[fn] === 'function') {
// Get the function from the user/context defined functions
value = context[fn](...params);
} else {
throw new Twig.Error(fn + ' function does not exist and is not defined in the context');
}
return value;
})
.then(result => {
stack.push(result);
});
}
},
// Token representing a variable.
//
// Variables can contain letters, numbers, underscores and
// dashes, but must start with a letter or underscore.
//
// Variables are retrieved from the render context and take
// the value of 'undefined' if the given variable doesn't
// exist in the context.
{
type: Twig.expression.type.variable,
// Match any letter or _, then any number of letters, numbers, _ or -
regex: /^[a-zA-Z_]\w*/,
next: Twig.expression.set.operationsExtended.concat([
Twig.expression.type.parameter.start
]),
compile: Twig.expression.fn.compile.push,
validate(match) {
return (!Twig.expression.reservedWords.includes(match[0]));
},
parse(token, stack, context) {
const state = this;
// Get the variable from the context
return Twig.expression.resolveAsync.call(state, context[token.value], context)
.then(value => {
if (state.template.options.strictVariables && value === undefined) {
throw new Twig.Error('Variable "' + token.value + '" does not exist.');
}
stack.push(value);
});
}
},
{
type: Twig.expression.type.key.period,
regex: /^\.(\w+)/,
next: Twig.expression.set.operationsExtended.concat([
Twig.expression.type.parameter.start
]),
compile(token, stack, output) {
token.key = token.match[1];
delete token.match;
delete token.value;
output.push(token);
},
parse(token, stack, context, nextToken) {
const state = this;
const {key} = token;
const object = stack.pop();
let value;
if (object && !Object.prototype.hasOwnProperty.call(object, key) && state.template.options.strictVariables) {
const keys = Object.keys(object);
if (keys.length > 0) {
throw new Twig.Error('Key "' + key + '" for object with keys "' + Object.keys(object).join(', ') + '" does not exist.');
} else {
throw new Twig.Error('Key "' + key + '" does not exist as the object is empty.');
}
}
return parseParams(state, token.params, context)
.then(params => {
if (object === null || object === undefined) {
value = undefined;
} else {
const capitalize = function (value) {
return value.slice(0, 1).toUpperCase() + value.slice(1);
};
// Get the variable from the context
if (typeof object === 'object' && key in object) {
value = object[key];
} else if (object['get' + capitalize(key)]) {
value = object['get' + capitalize(key)];
} else if (object['is' + capitalize(key)]) {
value = object['is' + capitalize(key)];
} else {
value = undefined;
}
}
// When resolving an expression we need to pass nextToken in case the expression is a function
return Twig.expression.resolveAsync.call(state, value, context, params, nextToken, object);
})
.then(result => {
stack.push(result);
});
}
},
{
type: Twig.expression.type.key.brackets,
regex: /^\[([^\]]*)\]/,
next: Twig.expression.set.operationsExtended.concat([
Twig.expression.type.parameter.start
]),
compile(token, stack, output) {
const match = token.match[1];
delete token.value;
delete token.match;
// The expression stack for the key
token.stack = Twig.expression.compile({
value: match
}).stack;
output.push(token);
},
parse(token, stack, context, nextToken) {
// Evaluate key
const state = this;
let params = null;
let object;
let value;
return parseParams(state, token.params, context)
.then(parameters => {
params = parameters;
return Twig.expression.parseAsync.call(state, token.stack, context);
})
.then(key => {
object = stack.pop();
if (object && !Object.prototype.hasOwnProperty.call(object, key) && state.template.options.strictVariables) {
const keys = Object.keys(object);
if (keys.length > 0) {
throw new Twig.Error('Key "' + key + '" for array with keys "' + keys.join(', ') + '" does not exist.');
} else {
throw new Twig.Error('Key "' + key + '" does not exist as the array is empty.');
}
} else if (object === null || object === undefined) {
return null;
}
// Get the variable from the context
if (typeof object === 'object' && key in object) {
value = object[key];
} else {
value = null;
}
// When resolving an expression we need to pass nextToken in case the expression is a function
return Twig.expression.resolveAsync.call(state, value, object, params, nextToken);
})
.then(result => {
stack.push(result);
});
}
},