index.js
40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
'use strict';
var assert = require('assert');
var isExpression = require('is-expression');
var characterParser = require('character-parser');
var error = require('pug-error');
module.exports = lex;
module.exports.Lexer = Lexer;
function lex(str, options) {
var lexer = new Lexer(str, options);
return JSON.parse(JSON.stringify(lexer.getTokens()));
}
/**
* Initialize `Lexer` with the given `str`.
*
* @param {String} str
* @param {String} filename
* @api private
*/
function Lexer(str, options) {
options = options || {};
if (typeof str !== 'string') {
throw new Error('Expected source code to be a string but got "' + (typeof str) + '"')
}
if (typeof options !== 'object') {
throw new Error('Expected "options" to be an object but got "' + (typeof options) + '"')
}
//Strip any UTF-8 BOM off of the start of `str`, if it exists.
str = str.replace(/^\uFEFF/, '');
this.input = str.replace(/\r\n|\r/g, '\n');
this.originalInput = this.input;
this.filename = options.filename;
this.interpolated = options.interpolated || false;
this.lineno = options.startingLine || 1;
this.colno = options.startingColumn || 1;
this.plugins = options.plugins || [];
this.indentStack = [0];
this.indentRe = null;
// If #{}, !{} or #[] syntax is allowed when adding text
this.interpolationAllowed = true;
this.whitespaceRe = /[ \n\t]/;
this.tokens = [];
this.ended = false;
};
/**
* Lexer prototype.
*/
Lexer.prototype = {
constructor: Lexer,
error: function (code, message) {
var err = error(code, message, {line: this.lineno, column: this.colno, filename: this.filename, src: this.originalInput});
throw err;
},
assert: function (value, message) {
if (!value) this.error('ASSERT_FAILED', message);
},
isExpression: function (exp) {
return isExpression(exp, {
throw: true
});
},
assertExpression: function (exp, noThrow) {
//this verifies that a JavaScript expression is valid
try {
this.callLexerFunction('isExpression', exp);
return true;
} catch (ex) {
if (noThrow) return false;
// not coming from acorn
if (!ex.loc) throw ex;
this.incrementLine(ex.loc.line - 1);
this.incrementColumn(ex.loc.column);
var msg = 'Syntax Error: ' + ex.message.replace(/ \([0-9]+:[0-9]+\)$/, '');
this.error('SYNTAX_ERROR', msg);
}
},
assertNestingCorrect: function (exp) {
//this verifies that code is properly nested, but allows
//invalid JavaScript such as the contents of `attributes`
var res = characterParser(exp)
if (res.isNesting()) {
this.error('INCORRECT_NESTING', 'Nesting must match on expression `' + exp + '`')
}
},
/**
* Construct a token with the given `type` and `val`.
*
* @param {String} type
* @param {String} val
* @return {Object}
* @api private
*/
tok: function(type, val){
var res = {
type: type,
loc: {
start: {
line: this.lineno,
column: this.colno
},
filename: this.filename
}
};
if (val !== undefined) res.val = val;
return res;
},
/**
* Set the token's `loc.end` value.
*
* @param {Object} tok
* @returns {Object}
* @api private
*/
tokEnd: function(tok){
tok.loc.end = {
line: this.lineno,
column: this.colno
};
return tok;
},
/**
* Increment `this.lineno` and reset `this.colno`.
*
* @param {Number} increment
* @api private
*/
incrementLine: function(increment){
this.lineno += increment;
if (increment) this.colno = 1;
},
/**
* Increment `this.colno`.
*
* @param {Number} increment
* @api private
*/
incrementColumn: function(increment){
this.colno += increment
},
/**
* Consume the given `len` of input.
*
* @param {Number} len
* @api private
*/
consume: function(len){
this.input = this.input.substr(len);
},
/**
* Scan for `type` with the given `regexp`.
*
* @param {String} type
* @param {RegExp} regexp
* @return {Object}
* @api private
*/
scan: function(regexp, type){
var captures;
if (captures = regexp.exec(this.input)) {
var len = captures[0].length;
var val = captures[1];
var diff = len - (val ? val.length : 0);
var tok = this.tok(type, val);
this.consume(len);
this.incrementColumn(diff);
return tok;
}
},
scanEndOfLine: function (regexp, type) {
var captures;
if (captures = regexp.exec(this.input)) {
var whitespaceLength = 0;
var whitespace;
var tok;
if (whitespace = /^([ ]+)([^ ]*)/.exec(captures[0])) {
whitespaceLength = whitespace[1].length;
this.incrementColumn(whitespaceLength);
}
var newInput = this.input.substr(captures[0].length);
if (newInput[0] === ':') {
this.input = newInput;
tok = this.tok(type, captures[1]);
this.incrementColumn(captures[0].length - whitespaceLength);
return tok;
}
if (/^[ \t]*(\n|$)/.test(newInput)) {
this.input = newInput.substr(/^[ \t]*/.exec(newInput)[0].length);
tok = this.tok(type, captures[1]);
this.incrementColumn(captures[0].length - whitespaceLength);
return tok;
}
}
},
/**
* Return the indexOf `(` or `{` or `[` / `)` or `}` or `]` delimiters.
*
* Make sure that when calling this function, colno is at the character
* immediately before the beginning.
*
* @return {Number}
* @api private
*/
bracketExpression: function(skip){
skip = skip || 0;
var start = this.input[skip];
assert(start === '(' || start === '{' || start === '[',
'The start character should be "(", "{" or "["');
var end = characterParser.BRACKETS[start];
var range;
try {
range = characterParser.parseUntil(this.input, end, {start: skip + 1});
} catch (ex) {
if (ex.index !== undefined) {
var idx = ex.index;
// starting from this.input[skip]
var tmp = this.input.substr(skip).indexOf('\n');
// starting from this.input[0]
var nextNewline = tmp + skip;
var ptr = 0;
while (idx > nextNewline && tmp !== -1) {
this.incrementLine(1);
idx -= nextNewline + 1;
ptr += nextNewline + 1;
tmp = nextNewline = this.input.substr(ptr).indexOf('\n');
};
this.incrementColumn(idx);
}
if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') {
this.error('NO_END_BRACKET', 'The end of the string reached with no closing bracket ' + end + ' found.');
} else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') {
this.error('BRACKET_MISMATCH', ex.message);
}
throw ex;
}
return range;
},
scanIndentation: function() {
var captures, re;
// established regexp
if (this.indentRe) {
captures = this.indentRe.exec(this.input);
// determine regexp
} else {
// tabs
re = /^\n(\t*) */;
captures = re.exec(this.input);
// spaces
if (captures && !captures[1].length) {
re = /^\n( *)/;
captures = re.exec(this.input);
}
// established
if (captures && captures[1].length) this.indentRe = re;
}
return captures;
},
/**
* end-of-source.
*/
eos: function() {
if (this.input.length) return;
if (this.interpolated) {
this.error('NO_END_BRACKET', 'End of line was reached with no closing bracket for interpolation.');
}
for (var i = 0; this.indentStack[i]; i++) {
this.tokens.push(this.tokEnd(this.tok('outdent')));
}
this.tokens.push(this.tokEnd(this.tok('eos')));
this.ended = true;
return true;
},
/**
* Blank line.
*/
blank: function() {
var captures;
if (captures = /^\n[ \t]*\n/.exec(this.input)) {
this.consume(captures[0].length - 1);
this.incrementLine(1);
return true;
}
},
/**
* Comment.
*/
comment: function() {
var captures;
if (captures = /^\/\/(-)?([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('comment', captures[2]);
tok.buffer = '-' != captures[1];
this.interpolationAllowed = tok.buffer;
this.tokens.push(tok);
this.incrementColumn(captures[0].length);
this.tokEnd(tok);
this.callLexerFunction('pipelessText');
return true;
}
},
/**
* Interpolated tag.
*/
interpolation: function() {
if (/^#\{/.test(this.input)) {
var match = this.bracketExpression(1);
this.consume(match.end + 1);
var tok = this.tok('interpolation', match.src);
this.tokens.push(tok);
this.incrementColumn(2); // '#{'
this.assertExpression(match.src);
var splitted = match.src.split('\n');
var lines = splitted.length - 1;
this.incrementLine(lines);
this.incrementColumn(splitted[lines].length + 1); // + 1 → '}'
this.tokEnd(tok);
return true;
}
},
/**
* Tag.
*/
tag: function() {
var captures;
if (captures = /^(\w(?:[-:\w]*\w)?)/.exec(this.input)) {
var tok, name = captures[1], len = captures[0].length;
this.consume(len);
tok = this.tok('tag', name);
this.tokens.push(tok);
this.incrementColumn(len);
this.tokEnd(tok);
return true;
}
},
/**
* Filter.
*/
filter: function(opts) {
var tok = this.scan(/^:([\w\-]+)/, 'filter');
var inInclude = opts && opts.inInclude;
if (tok) {
this.tokens.push(tok);
this.incrementColumn(tok.val.length);
this.tokEnd(tok);
this.callLexerFunction('attrs');
if (!inInclude) {
this.interpolationAllowed = false;
this.callLexerFunction('pipelessText');
}
return true;
}
},
/**
* Doctype.
*/
doctype: function() {
var node = this.scanEndOfLine(/^doctype *([^\n]*)/, 'doctype');
if (node) {
this.tokens.push(this.tokEnd(node));
return true;
}
},
/**
* Id.
*/
id: function() {
var tok = this.scan(/^#([\w-]+)/, 'id');
if (tok) {
this.tokens.push(tok);
this.incrementColumn(tok.val.length);
this.tokEnd(tok);
return true;
}
if (/^#/.test(this.input)) {
this.error('INVALID_ID', '"' + /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] + '" is not a valid ID.');
}
},
/**
* Class.
*/
className: function() {
var tok = this.scan(/^\.([_a-z0-9\-]*[_a-z][_a-z0-9\-]*)/i, 'class');
if (tok) {
this.tokens.push(tok);
this.incrementColumn(tok.val.length);
this.tokEnd(tok);
return true;
}
if (/^\.[_a-z0-9\-]+/i.test(this.input)) {
this.error('INVALID_CLASS_NAME', 'Class names must contain at least one letter or underscore.');
}
if (/^\./.test(this.input)) {
this.error('INVALID_CLASS_NAME', '"' + /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] + '" is not a valid class name. Class names can only contain "_", "-", a-z and 0-9, and must contain at least one of "_", or a-z');
}
},
/**
* Text.
*/
endInterpolation: function () {
if (this.interpolated && this.input[0] === ']') {
this.input = this.input.substr(1);
this.ended = true;
return true;
}
},
addText: function (type, value, prefix, escaped) {
var tok;
if (value + prefix === '') return;
prefix = prefix || '';
escaped = escaped || 0;
var indexOfEnd = this.interpolated ? value.indexOf(']') : -1;
var indexOfStart = this.interpolationAllowed ? value.indexOf('#[') : -1;
var indexOfEscaped = this.interpolationAllowed ? value.indexOf('\\#[') : -1;
var matchOfStringInterp = /(\\)?([#!]){((?:.|\n)*)$/.exec(value);
var indexOfStringInterp = this.interpolationAllowed && matchOfStringInterp ? matchOfStringInterp.index : Infinity;
if (indexOfEnd === -1) indexOfEnd = Infinity;
if (indexOfStart === -1) indexOfStart = Infinity;
if (indexOfEscaped === -1) indexOfEscaped = Infinity;
if (indexOfEscaped !== Infinity && indexOfEscaped < indexOfEnd && indexOfEscaped < indexOfStart && indexOfEscaped < indexOfStringInterp) {
prefix = prefix + value.substring(0, indexOfEscaped) + '#[';
return this.addText(type, value.substring(indexOfEscaped + 3), prefix, escaped + 1);
}
if (indexOfStart !== Infinity && indexOfStart < indexOfEnd && indexOfStart < indexOfEscaped && indexOfStart < indexOfStringInterp) {
tok = this.tok(type, prefix + value.substring(0, indexOfStart));
this.incrementColumn(prefix.length + indexOfStart + escaped);
this.tokens.push(this.tokEnd(tok));
tok = this.tok('start-pug-interpolation');
this.incrementColumn(2);
this.tokens.push(this.tokEnd(tok));
var child = new this.constructor(value.substr(indexOfStart + 2), {
filename: this.filename,
interpolated: true,
startingLine: this.lineno,
startingColumn: this.colno
});
var interpolated;
try {
interpolated = child.getTokens();
} catch (ex) {
if (ex.code && /^PUG:/.test(ex.code)) {
this.colno = ex.column;
this.error(ex.code.substr(4), ex.msg);
}
throw ex;
}
this.colno = child.colno;
this.tokens = this.tokens.concat(interpolated);
tok = this.tok('end-pug-interpolation');
this.incrementColumn(1);
this.tokens.push(this.tokEnd(tok));
this.addText(type, child.input);
return;
}
if (indexOfEnd !== Infinity && indexOfEnd < indexOfStart && indexOfEnd < indexOfEscaped && indexOfEnd < indexOfStringInterp) {
if (prefix + value.substring(0, indexOfEnd)) {
this.addText(type, value.substring(0, indexOfEnd), prefix);
}
this.ended = true;
this.input = value.substr(value.indexOf(']') + 1) + this.input;
return;
}
if (indexOfStringInterp !== Infinity) {
if (matchOfStringInterp[1]) {
prefix = prefix + value.substring(0, indexOfStringInterp) + '#{';
return this.addText(type, value.substring(indexOfStringInterp + 3), prefix, escaped + 1);
}
var before = value.substr(0, indexOfStringInterp);
if (prefix || before) {
before = prefix + before;
tok = this.tok(type, before);
this.incrementColumn(before.length + escaped);
this.tokens.push(this.tokEnd(tok));
}
var rest = matchOfStringInterp[3];
var range;
tok = this.tok('interpolated-code');
this.incrementColumn(2);
try {
range = characterParser.parseUntil(rest, '}');
} catch (ex) {
if (ex.index !== undefined) {
this.incrementColumn(ex.index);
}
if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') {
this.error('NO_END_BRACKET', 'End of line was reached with no closing bracket for interpolation.');
} else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') {
this.error('BRACKET_MISMATCH', ex.message);
} else {
throw ex;
}
}
tok.mustEscape = matchOfStringInterp[2] === '#';
tok.buffer = true;
tok.val = range.src;
this.assertExpression(range.src);
if (range.end + 1 < rest.length) {
rest = rest.substr(range.end + 1);
this.incrementColumn(range.end + 1);
this.tokens.push(this.tokEnd(tok));
this.addText(type, rest);
} else {
this.incrementColumn(rest.length);
this.tokens.push(this.tokEnd(tok));
}
return;
}
value = prefix + value;
tok = this.tok(type, value);
this.incrementColumn(value.length + escaped);
this.tokens.push(this.tokEnd(tok));
},
text: function() {
var tok = this.scan(/^(?:\| ?| )([^\n]+)/, 'text') ||
this.scan(/^( )/, 'text') ||
this.scan(/^\|( ?)/, 'text');
if (tok) {
this.addText('text', tok.val);
return true;
}
},
textHtml: function () {
var tok = this.scan(/^(<[^\n]*)/, 'text-html');
if (tok) {
this.addText('text-html', tok.val);
return true;
}
},
/**
* Dot.
*/
dot: function() {
var tok;
if (tok = this.scanEndOfLine(/^\./, 'dot')) {
this.tokens.push(this.tokEnd(tok));
this.callLexerFunction('pipelessText');
return true;
}
},
/**
* Extends.
*/
"extends": function() {
var tok = this.scan(/^extends?(?= |$|\n)/, 'extends');
if (tok) {
this.tokens.push(this.tokEnd(tok));
if (!this.callLexerFunction('path')) {
this.error('NO_EXTENDS_PATH', 'missing path for extends');
}
return true;
}
if (this.scan(/^extends?\b/)) {
this.error('MALFORMED_EXTENDS', 'malformed extends');
}
},
/**
* Block prepend.
*/
prepend: function() {
var captures;
if (captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input)) {
var name = captures[1].trim();
var comment = '';
if (name.indexOf('//') !== -1) {
comment = '//' + name.split('//').slice(1).join('//');
name = name.split('//')[0].trim();
}
if (!name) return;
var tok = this.tok('block', name);
var len = captures[0].length - comment.length;
while(this.whitespaceRe.test(this.input.charAt(len - 1))) len--;
this.incrementColumn(len);
tok.mode = 'prepend';
this.tokens.push(this.tokEnd(tok));
this.consume(captures[0].length - comment.length);
this.incrementColumn(captures[0].length - comment.length - len);
return true;
}
},
/**
* Block append.
*/
append: function() {
var captures;
if (captures = /^(?:block +)?append +([^\n]+)/.exec(this.input)) {
var name = captures[1].trim();
var comment = '';
if (name.indexOf('//') !== -1) {
comment = '//' + name.split('//').slice(1).join('//');
name = name.split('//')[0].trim();
}
if (!name) return;
var tok = this.tok('block', name);
var len = captures[0].length - comment.length;
while(this.whitespaceRe.test(this.input.charAt(len - 1))) len--;
this.incrementColumn(len);
tok.mode = 'append';
this.tokens.push(this.tokEnd(tok));
this.consume(captures[0].length - comment.length);
this.incrementColumn(captures[0].length - comment.length - len);
return true;
}
},
/**
* Block.
*/
block: function() {
var captures;
if (captures = /^block +([^\n]+)/.exec(this.input)) {
var name = captures[1].trim();
var comment = '';
if (name.indexOf('//') !== -1) {
comment = '//' + name.split('//').slice(1).join('//');
name = name.split('//')[0].trim();
}
if (!name) return;
var tok = this.tok('block', name);
var len = captures[0].length - comment.length;
while(this.whitespaceRe.test(this.input.charAt(len - 1))) len--;
this.incrementColumn(len);
tok.mode = 'replace';
this.tokens.push(this.tokEnd(tok));
this.consume(captures[0].length - comment.length);
this.incrementColumn(captures[0].length - comment.length - len);
return true;
}
},
/**
* Mixin Block.
*/
mixinBlock: function() {
var tok;
if (tok = this.scanEndOfLine(/^block/, 'mixin-block')) {
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* Yield.
*/
'yield': function() {
var tok = this.scanEndOfLine(/^yield/, 'yield');
if (tok) {
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* Include.
*/
include: function() {
var tok = this.scan(/^include(?=:| |$|\n)/, 'include');
if (tok) {
this.tokens.push(this.tokEnd(tok));
while (this.callLexerFunction('filter', { inInclude: true }));
if (!this.callLexerFunction('path')) {
if (/^[^ \n]+/.test(this.input)) {
// if there is more text
this.fail();
} else {
// if not
this.error('NO_INCLUDE_PATH', 'missing path for include');
}
}
return true;
}
if (this.scan(/^include\b/)) {
this.error('MALFORMED_INCLUDE', 'malformed include');
}
},
/**
* Path
*/
path: function() {
var tok = this.scanEndOfLine(/^ ([^\n]+)/, 'path');
if (tok && (tok.val = tok.val.trim())) {
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* Case.
*/
"case": function() {
var tok = this.scanEndOfLine(/^case +([^\n]+)/, 'case');
if (tok) {
this.incrementColumn(-tok.val.length);
this.assertExpression(tok.val);
this.incrementColumn(tok.val.length);
this.tokens.push(this.tokEnd(tok));
return true;
}
if (this.scan(/^case\b/)) {
this.error('NO_CASE_EXPRESSION', 'missing expression for case');
}
},
/**
* When.
*/
when: function() {
var tok = this.scanEndOfLine(/^when +([^:\n]+)/, 'when');
if (tok) {
var parser = characterParser(tok.val);
while (parser.isNesting() || parser.isString()) {
var rest = /:([^:\n]+)/.exec(this.input);
if (!rest) break;
tok.val += rest[0];
this.consume(rest[0].length);
this.incrementColumn(rest[0].length);
parser = characterParser(tok.val);
}
this.incrementColumn(-tok.val.length);
this.assertExpression(tok.val);
this.incrementColumn(tok.val.length);
this.tokens.push(this.tokEnd(tok));
return true;
}
if (this.scan(/^when\b/)) {
this.error('NO_WHEN_EXPRESSION', 'missing expression for when');
}
},
/**
* Default.
*/
"default": function() {
var tok = this.scanEndOfLine(/^default/, 'default');
if (tok) {
this.tokens.push(this.tokEnd(tok));
return true;
}
if (this.scan(/^default\b/)) {
this.error('DEFAULT_WITH_EXPRESSION', 'default should not have an expression');
}
},
/**
* Call mixin.
*/
call: function(){
var tok, captures, increment;
if (captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input)) {
// try to consume simple or interpolated call
if (captures[3]) {
// simple call
increment = captures[0].length;
this.consume(increment);
tok = this.tok('call', captures[3]);
} else {
// interpolated call
var match = this.bracketExpression(2 + captures[1].length);
increment = match.end + 1;
this.consume(increment);
this.assertExpression(match.src);
tok = this.tok('call', '#{'+match.src+'}');
}
this.incrementColumn(increment);
tok.args = null;
// Check for args (not attributes)
if (captures = /^ *\(/.exec(this.input)) {
var range = this.bracketExpression(captures[0].length - 1);
if (!/^\s*[-\w]+ *=/.test(range.src)) { // not attributes
this.incrementColumn(1);
this.consume(range.end + 1);
tok.args = range.src;
this.assertExpression('[' + tok.args + ']');
for (var i = 0; i <= tok.args.length; i++) {
if (tok.args[i] === '\n') {
this.incrementLine(1);
} else {
this.incrementColumn(1);
}
}
}
}
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* Mixin.
*/
mixin: function(){
var captures;
if (captures = /^mixin +([-\w]+)(?: *\((.*)\))? */.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('mixin', captures[1]);
tok.args = captures[2] || null;
this.incrementColumn(captures[0].length);
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* Conditional.
*/
conditional: function() {
var captures;
if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var type = captures[1].replace(/ /g, '-');
var js = captures[2] && captures[2].trim();
// type can be "if", "else-if" and "else"
var tok = this.tok(type, js);
this.incrementColumn(captures[0].length - js.length);
switch (type) {
case 'if':
case 'else-if':
this.assertExpression(js);
break;
case 'unless':
this.assertExpression(js);
tok.val = '!(' + js + ')';
tok.type = 'if';
break;
case 'else':
if (js) {
this.error(
'ELSE_CONDITION',
'`else` cannot have a condition, perhaps you meant `else if`'
);
}
break;
}
this.incrementColumn(js.length);
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* While.
*/
"while": function() {
var captures, tok;
if (captures = /^while +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
this.assertExpression(captures[1]);
tok = this.tok('while', captures[1]);
this.incrementColumn(captures[0].length);
this.tokens.push(this.tokEnd(tok));
return true;
}
if (this.scan(/^while\b/)) {
this.error('NO_WHILE_EXPRESSION', 'missing expression for while');
}
},
/**
* Each.
*/
each: function() {
var captures;
if (captures = /^(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? * in *([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('each', captures[1]);
tok.key = captures[2] || null;
this.incrementColumn(captures[0].length - captures[3].length);
this.assertExpression(captures[3])
tok.code = captures[3];
this.incrementColumn(captures[3].length);
this.tokens.push(this.tokEnd(tok));
return true;
}
if (this.scan(/^(?:each|for)\b/)) {
this.error('MALFORMED_EACH', 'malformed each');
}
if (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +in +([^\n]+)/.exec(this.input)) {
this.error(
'MALFORMED_EACH',
'Pug each and for should no longer be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.'
);
}
},
/**
* Code.
*/
code: function() {
var captures;
if (captures = /^(!?=|-)[ \t]*([^\n]+)/.exec(this.input)) {
var flags = captures[1];
var code = captures[2];
var shortened = 0;
if (this.interpolated) {
var parsed;
try {
parsed = characterParser.parseUntil(code, ']');
} catch (err) {
if (err.index !== undefined) {
this.incrementColumn(captures[0].length - code.length + err.index);
}
if (err.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') {
this.error('NO_END_BRACKET', 'End of line was reached with no closing bracket for interpolation.');
} else if (err.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') {
this.error('BRACKET_MISMATCH', err.message);
} else {
throw err;
}
}
shortened = code.length - parsed.end;
code = parsed.src;
}
var consumed = captures[0].length - shortened;
this.consume(consumed);
var tok = this.tok('code', code);
tok.mustEscape = flags.charAt(0) === '=';
tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '=';
// p #[!= abc] hey
// ^ original colno
// -------------- captures[0]
// -------- captures[2]
// ------ captures[0] - captures[2]
// ^ after colno
// = abc
// ^ original colno
// ------- captures[0]
// --- captures[2]
// ---- captures[0] - captures[2]
// ^ after colno
this.incrementColumn(captures[0].length - captures[2].length);
if (tok.buffer) this.assertExpression(code);
this.tokens.push(tok);
// p #[!= abc] hey
// ^ original colno
// ----- shortened
// --- code
// ^ after colno
// = abc
// ^ original colno
// shortened
// --- code
// ^ after colno
this.incrementColumn(code.length);
this.tokEnd(tok);
return true;
}
},
/**
* Block code.
*/
blockCode: function() {
var tok
if (tok = this.scanEndOfLine(/^-/, 'blockcode')) {
this.tokens.push(this.tokEnd(tok));
this.interpolationAllowed = false;
this.callLexerFunction('pipelessText');
return true;
}
},
/**
* Attribute Name.
*/
attribute: function(str){
var quote = '';
var quoteRe = /['"]/;
var key = '';
var i;
// consume all whitespace before the key
for(i = 0; i < str.length; i++){
if(!this.whitespaceRe.test(str[i])) break;
if(str[i] === '\n'){
this.incrementLine(1);
} else {
this.incrementColumn(1);
}
}
if(i === str.length){
return '';
}
var tok = this.tok('attribute');
// quote?
if(quoteRe.test(str[i])){
quote = str[i];
this.incrementColumn(1);
i++;
}
// start looping through the key
for (; i < str.length; i++) {
if(quote){
if (str[i] === quote) {
this.incrementColumn(1);
i++;
break;
}
} else {
if(this.whitespaceRe.test(str[i]) || str[i] === '!' || str[i] === '=' || str[i] === ',') {
break;
}
}
key += str[i];
if (str[i] === '\n') {
this.incrementLine(1);
} else {
this.incrementColumn(1);
}
}
tok.name = key;
var valueResponse = this.attributeValue(str.substr(i));
if (valueResponse.val) {
tok.val = valueResponse.val;
tok.mustEscape = valueResponse.mustEscape;
} else {
// was a boolean attribute (ex: `input(disabled)`)
tok.val = true;
tok.mustEscape = true;
}
str = valueResponse.remainingSource;
this.tokens.push(this.tokEnd(tok));
for(i = 0; i < str.length; i++){
if(!this.whitespaceRe.test(str[i])) {
break;
}
if(str[i] === '\n'){
this.incrementLine(1);
} else {
this.incrementColumn(1);
}
}
if(str[i] === ','){
this.incrementColumn(1);
i++;
}
return str.substr(i);
},
/**
* Attribute Value.
*/
attributeValue: function(str){
var quoteRe = /['"]/;
var val = '';
var done, i, x;
var escapeAttr = true;
var state = characterParser.defaultState();
var col = this.colno;
var line = this.lineno;
// consume all whitespace before the equals sign
for(i = 0; i < str.length; i++){
if(!this.whitespaceRe.test(str[i])) break;
if(str[i] === '\n'){
line++;
col = 1;
} else {
col++;
}
}
if(i === str.length){
return { remainingSource: str };
}
if(str[i] === '!'){
escapeAttr = false;
col++;
i++;
if (str[i] !== '=') this.error('INVALID_KEY_CHARACTER', 'Unexpected character ' + str[i] + ' expected `=`');
}
if(str[i] !== '='){
// check for anti-pattern `div("foo"bar)`
if (i === 0 && str && !this.whitespaceRe.test(str[0]) && str[0] !== ','){
this.error('INVALID_KEY_CHARACTER', 'Unexpected character ' + str[0] + ' expected `=`');
} else {
return { remainingSource: str };
}
}
this.lineno = line;
this.colno = col + 1;
i++;
// consume all whitespace before the value
for(; i < str.length; i++){
if(!this.whitespaceRe.test(str[i])) break;
if(str[i] === '\n'){
this.incrementLine(1);
} else {
this.incrementColumn(1);
}
}
line = this.lineno;
col = this.colno;
// start looping through the value
for (; i < str.length; i++) {
// if the character is in a string or in parentheses/brackets/braces
if (!(state.isNesting() || state.isString())){
if (this.whitespaceRe.test(str[i])) {
done = false;
// find the first non-whitespace character
for (x = i; x < str.length; x++) {
if (!this.whitespaceRe.test(str[x])) {
// if it is a JavaScript punctuator, then assume that it is
// a part of the value
const isNotPunctuator = !characterParser.isPunctuator(str[x])
const isQuote = quoteRe.test(str[x])
const isColon = str[x] === ':'
const isSpreadOperator = str[x] + str[x + 1] + str[x + 2] === '...'
if ((isNotPunctuator || isQuote || isColon || isSpreadOperator) && this.assertExpression(val, true)) {
done = true;
}
break;
}
}
// if everything else is whitespace, return now so last attribute
// does not include trailing whitespace
if(done || x === str.length){
break;
}
}
// if there's no whitespace and the character is not ',', the
// attribute did not end.
if(str[i] === ',' && this.assertExpression(val, true)){
break;
}
}
state = characterParser.parseChar(str[i], state);
val += str[i];
if (str[i] === '\n') {
line++;
col = 1;
} else {
col++;
}
}
this.assertExpression(val);
this.lineno = line;
this.colno = col;
return { val: val, mustEscape: escapeAttr, remainingSource: str.substr(i) };
},
/**
* Attributes.
*/
attrs: function() {
var tok;
if ('(' == this.input.charAt(0)) {
tok = this.tok('start-attributes');
var index = this.bracketExpression().end;
var str = this.input.substr(1, index-1);
this.incrementColumn(1);
this.tokens.push(this.tokEnd(tok));
this.assertNestingCorrect(str);
this.consume(index + 1);
while(str){
str = this.attribute(str);
}
tok = this.tok('end-attributes');
this.incrementColumn(1);
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* &attributes block
*/
attributesBlock: function () {
if (/^&attributes\b/.test(this.input)) {
var consumed = 11;
this.consume(consumed);
var tok = this.tok('&attributes');
this.incrementColumn(consumed);
var args = this.bracketExpression();
consumed = args.end + 1;
this.consume(consumed);
tok.val = args.src;
this.incrementColumn(consumed);
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* Indent | Outdent | Newline.
*/
indent: function() {
var captures = this.scanIndentation();
var tok;
if (captures) {
var indents = captures[1].length;
this.incrementLine(1);
this.consume(indents + 1);
if (' ' == this.input[0] || '\t' == this.input[0]) {
this.error('INVALID_INDENTATION', 'Invalid indentation, you can use tabs or spaces but not both');
}
// blank line
if ('\n' == this.input[0]) {
this.interpolationAllowed = true;
return this.tokEnd(this.tok('newline'));
}
// outdent
if (indents < this.indentStack[0]) {
var outdent_count = 0;
while (this.indentStack[0] > indents) {
if (this.indentStack[1] < indents) {
this.error('INCONSISTENT_INDENTATION', 'Inconsistent indentation. Expecting either ' + this.indentStack[1] + ' or ' + this.indentStack[0] + ' spaces/tabs.');
}
outdent_count++;
this.indentStack.shift();
}
while(outdent_count--){
this.colno = 1;
tok = this.tok('outdent');
this.colno = this.indentStack[0] + 1;
this.tokens.push(this.tokEnd(tok));
}
// indent
} else if (indents && indents != this.indentStack[0]) {
tok = this.tok('indent', indents);
this.colno = 1 + indents;
this.tokens.push(this.tokEnd(tok));
this.indentStack.unshift(indents);
// newline
} else {
tok = this.tok('newline');
this.colno = 1 + Math.min(this.indentStack[0] || 0, indents);
this.tokens.push(this.tokEnd(tok));
}
this.interpolationAllowed = true;
return true;
}
},
pipelessText: function pipelessText(indents) {
while (this.callLexerFunction('blank'));
var captures = this.scanIndentation();
indents = indents || captures && captures[1].length;
if (indents > this.indentStack[0]) {
this.tokens.push(this.tokEnd(this.tok('start-pipeless-text')));
var tokens = [];
var token_indent = [];
var isMatch;
// Index in this.input. Can't use this.consume because we might need to
// retry lexing the block.
var stringPtr = 0;
do {
// text has `\n` as a prefix
var i = this.input.substr(stringPtr + 1).indexOf('\n');
if (-1 == i) i = this.input.length - stringPtr - 1;
var str = this.input.substr(stringPtr + 1, i);
var lineCaptures = this.indentRe.exec('\n' + str);
var lineIndents = lineCaptures && lineCaptures[1].length;
isMatch = lineIndents >= indents;
token_indent.push(isMatch);
isMatch = isMatch || !str.trim();
if (isMatch) {
// consume test along with `\n` prefix if match
stringPtr += str.length + 1;
tokens.push(str.substr(indents));
} else if (lineIndents > this.indentStack[0]) {
// line is indented less than the first line but is still indented
// need to retry lexing the text block
this.tokens.pop();
return pipelessText.call(this, lineCaptures[1].length);
}
} while((this.input.length - stringPtr) && isMatch);
this.consume(stringPtr);
while (this.input.length === 0 && tokens[tokens.length - 1] === '') tokens.pop();
tokens.forEach(function (token, i) {
var tok;
this.incrementLine(1);
if (i !== 0) tok = this.tok('newline');
if (token_indent[i]) this.incrementColumn(indents);
if (tok) this.tokens.push(this.tokEnd(tok));
this.addText('text', token);
}.bind(this));
this.tokens.push(this.tokEnd(this.tok('end-pipeless-text')));
return true;
}
},
/**
* Slash.
*/
slash: function() {
var tok = this.scan(/^\//, 'slash');
if (tok) {
this.tokens.push(this.tokEnd(tok));
return true;
}
},
/**
* ':'
*/
colon: function() {
var tok = this.scan(/^: +/, ':');
if (tok) {
this.tokens.push(this.tokEnd(tok));
return true;
}
},
fail: function () {
this.error('UNEXPECTED_TEXT', 'unexpected text "' + this.input.substr(0, 5) + '"');
},
callLexerFunction: function (func) {
var rest = [];
for (var i = 1; i < arguments.length; i++) {
rest.push(arguments[i]);
}
var pluginArgs = [this].concat(rest);
for (var i = 0; i < this.plugins.length; i++) {
var plugin = this.plugins[i];
if (plugin[func] && plugin[func].apply(plugin, pluginArgs)) {
return true;
}
}
return this[func].apply(this, rest);
},
/**
* Move to the next token
*
* @api private
*/
advance: function() {
return this.callLexerFunction('blank')
|| this.callLexerFunction('eos')
|| this.callLexerFunction('endInterpolation')
|| this.callLexerFunction('yield')
|| this.callLexerFunction('doctype')
|| this.callLexerFunction('interpolation')
|| this.callLexerFunction('case')
|| this.callLexerFunction('when')
|| this.callLexerFunction('default')
|| this.callLexerFunction('extends')
|| this.callLexerFunction('append')
|| this.callLexerFunction('prepend')
|| this.callLexerFunction('block')
|| this.callLexerFunction('mixinBlock')
|| this.callLexerFunction('include')
|| this.callLexerFunction('mixin')
|| this.callLexerFunction('call')
|| this.callLexerFunction('conditional')
|| this.callLexerFunction('each')
|| this.callLexerFunction('while')
|| this.callLexerFunction('tag')
|| this.callLexerFunction('filter')
|| this.callLexerFunction('blockCode')
|| this.callLexerFunction('code')
|| this.callLexerFunction('id')
|| this.callLexerFunction('dot')
|| this.callLexerFunction('className')
|| this.callLexerFunction('attrs')
|| this.callLexerFunction('attributesBlock')
|| this.callLexerFunction('indent')
|| this.callLexerFunction('text')
|| this.callLexerFunction('textHtml')
|| this.callLexerFunction('comment')
|| this.callLexerFunction('slash')
|| this.callLexerFunction('colon')
|| this.fail();
},
/**
* Return an array of tokens for the current file
*
* @returns {Array.<Token>}
* @api public
*/
getTokens: function () {
while (!this.ended) {
this.callLexerFunction('advance');
}
return this.tokens;
}
};