forked from marko-js/htmljs-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.js
2808 lines (2372 loc) · 107 KB
/
Parser.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
'use strict';
var BaseParser = require('./BaseParser');
var operators = require('./operators');
var notifyUtil = require('./notify-util');
var complain = require('complain');
var charProps = require('char-props');
function isWhitespaceCode(code) {
// For all practical purposes, the space character (32) and all the
// control characters below it are whitespace. We simplify this
// condition for performance reasons.
// NOTE: This might be slightly non-conforming.
return (code <= 32);
}
var NUMBER_REGEX = /^[\-\+]?\d*(?:\.\d+)?(?:e[\-\+]?\d+)?$/;
/**
* Takes a string expression such as `"foo"` or `'foo "bar"'`
* and returns the literal String value.
*/
function evaluateStringExpression(expression, pos, notifyError) {
// We could just use eval(expression) to get the literal String value,
// but there is a small chance we could be introducing a security threat
// by accidently running malicous code. Instead, we will use
// JSON.parse(expression). JSON.parse() only allows strings
// that use double quotes so we have to do extra processing if
// we detect that the String uses single quotes
if (expression.charAt(0) === "'") {
expression = expression.substring(1, expression.length - 1);
// Make sure there are no unescaped double quotes in the string expression...
expression = expression.replace(/\\\\|\\[']|\\["]|["]/g, function(match) {
if (match === "\\'"){
// Don't escape single quotes since we are using double quotes
return "'";
} else if (match === '"'){
// Return an escaped double quote if we encounter an
// unescaped double quote
return '\\"';
} else {
// Return the escape sequence
return match;
}
});
expression = '"' + expression + '"';
}
try {
return JSON.parse(expression);
} catch(e) {
notifyError(pos,
'INVALID_STRING',
'Invalid string (' + expression + '): ' + e);
}
}
function peek(array) {
var len = array.length;
if (!len) {
return undefined;
}
return array[len - 1];
}
const MODE_HTML = 1;
const MODE_CONCISE = 2;
const CODE_BACK_SLASH = 92;
const CODE_FORWARD_SLASH = 47;
const CODE_OPEN_ANGLE_BRACKET = 60;
const CODE_CLOSE_ANGLE_BRACKET = 62;
const CODE_EXCLAMATION = 33;
const CODE_QUESTION = 63;
const CODE_OPEN_SQUARE_BRACKET = 91;
const CODE_CLOSE_SQUARE_BRACKET = 93;
const CODE_EQUAL = 61;
const CODE_SINGLE_QUOTE = 39;
const CODE_DOUBLE_QUOTE = 34;
const CODE_BACKTICK = 96;
const CODE_OPEN_PAREN = 40;
const CODE_CLOSE_PAREN = 41;
const CODE_OPEN_CURLY_BRACE = 123;
const CODE_CLOSE_CURLY_BRACE = 125;
const CODE_ASTERISK = 42;
const CODE_HYPHEN = 45;
const CODE_HTML_BLOCK_DELIMITER = CODE_HYPHEN;
const CODE_DOLLAR = 36;
const CODE_PERCENT = 37;
const CODE_PERIOD = 46;
const CODE_COMMA = 44;
const CODE_SEMICOLON = 59;
const CODE_NUMBER_SIGN = 35;
const BODY_PARSED_TEXT = 1; // Body of a tag is treated as text, but placeholders will be parsed
const BODY_STATIC_TEXT = 2;// Body of a tag is treated as text and placeholders will *not* be parsed
const EMPTY_ATTRIBUTES = [];
const htmlTags = require('./html-tags');
class Parser extends BaseParser {
constructor(listeners, options) {
super(options);
var parser = this;
function outputDeprecationWarning(message) {
var srcCharProps = charProps(parser.src);
var line = srcCharProps.lineAt(parser.pos);
var column = srcCharProps.columnAt(parser.pos);
var filename = parser.filename;
var location = (filename || '(unknown file)') + ':' + line + ':' + column;
complain(message, { location: location });
}
var notifiers = notifyUtil.createNotifiers(parser, listeners);
this.notifiers = notifiers;
var defaultMode = options && options.concise === false ? MODE_HTML : MODE_CONCISE;
var userIsOpenTagOnly = options && options.isOpenTagOnly;
var ignorePlaceholders = options && options.ignorePlaceholders;
var legacyCompatibility = options.legacyCompatibility === true;
var currentOpenTag; // Used to reference the current open tag that is being parsed
var currentAttribute; // Used to reference the current attribute that is being parsed
var closeTagName; // Used to keep track of the current close tag name as it is being parsed
var closeTagPos; // Used to keep track of the position of the current closing tag
var expectedCloseTagName; // Used to figure out when a text block has been ended (HTML tags are ignored)
var text; // Used to buffer text that is found within the body of a tag
var withinOpenTag;// Set to true if the parser is within the open tag
var blockStack; // Used to keep track of HTML tags and HTML blocks
var partStack; // Used to keep track of parts such as CDATA, expressions, declarations, etc.
var currentPart; // The current part at the top of the part stack
var indent; // Used to build the indent for the current concise line
var isConcise; // Set to true if parser is currently in concise mode
var isWithinSingleLineHtmlBlock; // Set to true if the current block is for a single line HTML block
var htmlBlockDelimiter; // Current delimiter for multiline HTML blocks nested within a concise tag. e.g. "--"
var htmlBlockIndent; // Used to hold the indentation for a delimited, multiline HTML block
var beginMixedMode; // Used as a flag to mark that the next HTML block should enter the parser into HTML mode
var endingMixedModeAtEOL; // Used as a flag to record that the next EOL to exit HTML mode and go back to concise
var placeholderDepth; // Used as an easy way to know if an exptression is within a placeholder
var textParseMode = 'html';
this.reset = function() {
BaseParser.prototype.reset.call(this);
text = '';
currentOpenTag = undefined;
currentAttribute = undefined;
closeTagName = undefined;
closeTagPos = undefined;
expectedCloseTagName = undefined;
withinOpenTag = false;
blockStack = [];
partStack = [];
currentPart = undefined;
indent = '';
isConcise = defaultMode === MODE_CONCISE;
isWithinSingleLineHtmlBlock = false;
htmlBlockDelimiter = null;
htmlBlockIndent = null;
beginMixedMode = false;
endingMixedModeAtEOL = false;
placeholderDepth = 0;
};
this.reset();
/**
* This function is called to determine if a tag is an "open only tag". Open only tags such as <img>
* are immediately closed.
* @param {String} tagName The name of the tag (e.g. "img")
*/
function isOpenTagOnly(tagName) {
tagName = tagName.toLowerCase();
var openTagOnly = userIsOpenTagOnly && userIsOpenTagOnly(tagName);
if (openTagOnly == null) {
openTagOnly = htmlTags.isOpenTagOnly(tagName);
}
return openTagOnly;
}
/**
* Clear out any buffered body text and notify any listeners
*/
function endText(txt) {
if (arguments.length === 0) {
txt = text;
}
notifiers.notifyText(txt, textParseMode);
// always clear text buffer...
text = '';
}
function openTagEOL() {
if (isConcise && !currentOpenTag.withinAttrGroup) {
// In concise mode we always end the open tag
finishOpenTag();
}
}
/**
* This function is used to enter into "HTML" parsing mode instead
* of concise HTML. We push a block on to the stack so that we know when
* return back to the previous parsing mode and to ensure that all
* tags within a block are properly closed.
*/
function beginHtmlBlock(delimiter) {
htmlBlockIndent = indent;
htmlBlockDelimiter = delimiter;
var parent = peek(blockStack);
blockStack.push({
type: 'html',
delimiter: delimiter,
indent: indent
});
if (parent && parent.body) {
if (parent.body === BODY_PARSED_TEXT) {
parser.enterState(STATE_PARSED_TEXT_CONTENT);
} else if (parent.body === BODY_STATIC_TEXT) {
parser.enterState(STATE_STATIC_TEXT_CONTENT);
} else {
throw new Error('Illegal value for parent.body: ' + parent.body);
}
} else {
return parser.enterState(STATE_HTML_CONTENT);
}
}
/**
* This method gets called when we are in non-concise mode
* and we are exiting out of non-concise mode.
*/
function endHtmlBlock() {
// End any text
endText();
// Make sure all tags in this HTML block are closed
for (let i=blockStack.length-1; i>=0; i--) {
var curBlock = blockStack[i];
if (curBlock.type === 'html') {
// Remove the HTML block from the stack since it has ended
blockStack.pop();
// We have reached the point where the HTML block started
// so we can stop
break;
} else {
// The current block is for an HTML tag and it still open. When a tag is tag is closed
// it is removed from the stack
notifyError(curBlock.pos,
'MISSING_END_TAG',
'Missing ending "' + curBlock.tagName + '" tag');
return;
}
}
// Resert variables associated with parsing an HTML block
htmlBlockIndent = null;
htmlBlockDelimiter = null;
isWithinSingleLineHtmlBlock = false;
if (parser.state !== STATE_CONCISE_HTML_CONTENT) {
parser.enterState(STATE_CONCISE_HTML_CONTENT);
}
}
/**
* This function gets called when we reach EOF outside of a tag.
*/
function htmlEOF() {
endText();
while(blockStack.length) {
var curBlock = peek(blockStack);
if (curBlock.type === 'tag') {
if (curBlock.concise) {
closeTag(curBlock.expectedCloseTagName);
} else {
// We found an unclosed tag on the stack that is not for a concise tag. That means
// there is a problem with the template because all open tags should have a closing
// tag
//
// NOTE: We have already closed tags that are open tag only or self-closed
notifyError(curBlock.pos,
'MISSING_END_TAG',
'Missing ending "' + curBlock.tagName + '" tag');
return;
}
} else if (curBlock.type === 'html') {
// We reached the end of file while still within a single line HTML block. That's okay
// though since we know the line is completely. We'll continue ending all open concise tags.
blockStack.pop();
} else {
// There is a bug in our parser...
throw new Error('Illegal state. There should not be any non-concise tags on the stack when in concise mode');
}
}
}
function openTagEOF() {
if (isConcise) {
if (currentOpenTag.withinAttrGroup) {
notifyError(currentOpenTag.pos,
'MALFORMED_OPEN_TAG',
'EOF reached while within an attribute group (e.g. "[ ... ]").');
return;
}
// If we reach EOF inside an open tag when in concise-mode
// then we just end the tag and all other open tags on the stack
finishOpenTag();
htmlEOF();
} else {
// Otherwise, in non-concise mode we consider this malformed input
// since the end '>' was not found.
notifyError(currentOpenTag.pos,
'MALFORMED_OPEN_TAG',
'EOF reached while parsing open tag');
}
}
var notifyCDATA = notifiers.notifyCDATA;
var notifyComment = notifiers.notifyComment;
var notifyOpenTag = notifiers.notifyOpenTag;
var notifyOpenTagName = notifiers.notifyOpenTagName;
var notifyCloseTag = notifiers.notifyCloseTag;
var notifyDocumentType = notifiers.notifyDocumentType;
var notifyDeclaration = notifiers.notifyDeclaration;
var notifyPlaceholder = notifiers.notifyPlaceholder;
var notifyScriptlet = notifiers.notifyScriptlet;
function notifyError(pos, errorCode, message) {
parser.end();
notifiers.notifyError(pos, errorCode, message);
}
function beginAttribute() {
currentAttribute = {};
if (currentOpenTag.attributes === EMPTY_ATTRIBUTES) {
currentOpenTag.attributes = [currentAttribute];
} else {
currentOpenTag.attributes.push(currentAttribute);
}
parser.enterState(STATE_ATTRIBUTE_NAME);
return currentAttribute;
}
function endAttribute() {
currentAttribute = null;
if (parser.state !== STATE_WITHIN_OPEN_TAG) {
parser.enterState(STATE_WITHIN_OPEN_TAG);
}
}
function beginOpenTag() {
endText();
var tagInfo = {
type: 'tag',
tagName: '',
tagNameParts: null,
attributes: [],
argument: undefined,
pos: parser.pos,
indent: indent,
nestedIndent: null, // This will get set when we know what hte nested indent is
concise: isConcise
};
withinOpenTag = true;
if (beginMixedMode) {
tagInfo.beginMixedMode = true;
beginMixedMode = false;
}
blockStack.push(tagInfo);
currentOpenTag = tagInfo;
parser.enterState(STATE_TAG_NAME);
return currentOpenTag;
}
function finishOpenTag(selfClosed) {
var tagName = currentOpenTag.tagName;
var attributes = currentOpenTag.attributes;
if (currentOpenTag.requiresCommas && attributes.length > 1) {
for(let i = 0; i < attributes.length-1; i++) {
if(!attributes[i].endedWithComma) {
var parseOptions = currentOpenTag.parseOptions;
if (!parseOptions || parseOptions.relaxRequireCommas !== true) {
notifyError(attributes[i].pos,
'COMMAS_REQUIRED',
'if commas are used, they must be used to separate all attributes for a tag');
}
}
}
}
if (currentOpenTag.hasUnenclosedWhitespace && attributes.length > 1) {
for(let i = 0; i < attributes.length-1; i++) {
if(!attributes[i].endedWithComma) {
notifyError(attributes[i].pos,
'COMMAS_REQUIRED',
'commas are required to separate all attributes when using complex attribute values with un-enclosed whitespace');
}
}
}
currentOpenTag.expectedCloseTagName = expectedCloseTagName =
parser.substring(currentOpenTag.tagNameStart, currentOpenTag.tagNameEnd);
var openTagOnly = currentOpenTag.openTagOnly = isOpenTagOnly(tagName);
var endPos = parser.pos;
if (!isConcise) {
if (selfClosed) {
endPos += 2; // Skip past '/>'
} else {
endPos += 1;
}
}
if (currentOpenTag.tagNameParts) {
currentOpenTag.tagNameExpression = currentOpenTag.tagNameParts.join('+');
}
currentOpenTag.endPos = endPos;
currentOpenTag.selfClosed = selfClosed === true;
if (!currentOpenTag.tagName) {
tagName = currentOpenTag.tagName = 'div';
}
var origState = parser.state;
notifyOpenTag(currentOpenTag);
var shouldClose = false;
if (selfClosed) {
shouldClose = true;
} else if (openTagOnly) {
if (!isConcise) {
// Only close the tag if we are not in concise mode. In concise mode
// we want to keep the tag on the stack to make sure nothing is nested below it
shouldClose = true;
}
}
if (shouldClose) {
closeTag(expectedCloseTagName);
}
withinOpenTag = false;
if (shouldClose) {
if (isConcise) {
parser.enterConciseHtmlContentState();
} else {
parser.enterHtmlContentState();
}
} else {
// Did the parser stay in the same state after
// notifying listeners about openTag?
if (parser.state === origState) {
// The listener didn't transition the parser to a new state
// so we use some simple rules to find the appropriate state.
if (tagName === 'script') {
parser.enterJsContentState();
} else if (tagName === 'style') {
parser.enterCssContentState();
} else {
if (isConcise) {
parser.enterConciseHtmlContentState();
} else {
parser.enterHtmlContentState();
}
}
}
}
// We need to record the "expected close tag name" if we transition into
// either STATE_STATIC_TEXT_CONTENT or STATE_PARSED_TEXT_CONTENT
currentOpenTag = undefined;
}
function closeTag(tagName, pos, endPos) {
if (!tagName) {
throw new Error('Illegal state. Invalid tag name');
}
var lastTag = blockStack.length ? blockStack.pop() : undefined;
if (pos == null && closeTagPos != null) {
pos = closeTagPos;
endPos = parser.pos + 1;
}
if (!lastTag || lastTag.type !== 'tag') {
return notifyError(pos,
'EXTRA_CLOSING_TAG',
'The closing "' + tagName + '" tag was not expected');
}
if (!lastTag || (lastTag.expectedCloseTagName !== tagName && lastTag.tagName !== tagName)) {
return notifyError(pos,
'MISMATCHED_CLOSING_TAG',
'The closing "' + tagName + '" tag does not match the corresponding opening "' + lastTag.expectedCloseTagName + '" tag');
}
tagName = lastTag.tagName;
notifyCloseTag(tagName, pos, endPos);
if (lastTag.beginMixedMode) {
endingMixedModeAtEOL = true;
}
closeTagName = null;
closeTagPos = null;
lastTag = peek(blockStack);
expectedCloseTagName = lastTag && lastTag.expectedCloseTagName;
}
function beginPart() {
currentPart = {
pos: parser.pos,
parentState: parser.state
};
partStack.push(currentPart);
return currentPart;
}
function endPart() {
var last = partStack.pop();
parser.endPos = parser.pos;
parser.enterState(last.parentState);
currentPart = partStack.length ? peek(partStack) : undefined;
return last;
}
// Expression
function beginExpression(endAfterGroup) {
var expression = beginPart();
expression.value = '';
expression.groupStack = [];
expression.endAfterGroup = endAfterGroup === true;
expression.isStringLiteral = null;
parser.enterState(STATE_EXPRESSION);
return expression;
}
function endExpression() {
var expression = endPart();
// Probably shouldn't do this, but it makes it easier to test!
if(expression.parentState === STATE_ATTRIBUTE_VALUE && expression.hasUnenclosedWhitespace) {
expression.value = '('+expression.value+')';
}
expression.parentState.expression(expression);
}
// --------------------------
// String
function beginString(quoteChar, quoteCharCode) {
var string = beginPart();
string.stringParts = [];
string.currentText = '';
string.quoteChar = quoteChar;
string.quoteCharCode = quoteCharCode;
string.isStringLiteral = true;
parser.enterState(STATE_STRING);
return string;
}
function endString() {
var string = endPart();
string.parentState.string(string);
}
// --------------------------
// Template String
function beginTemplateString() {
var templateString = beginPart();
templateString.value = '`';
parser.enterState(STATE_TEMPLATE_STRING);
return templateString;
}
function endTemplateString() {
var templateString = endPart();
templateString.parentState.templateString(templateString);
}
// --------------------------
// Scriptlet
function beginScriptlet() {
endText();
var scriptlet = beginPart();
scriptlet.value = '';
scriptlet.quoteCharCode = null;
parser.enterState(STATE_SCRIPTLET);
return scriptlet;
}
function endScriptlet(endPos) {
var scriptlet = endPart();
scriptlet.endPos = endPos;
notifyScriptlet(scriptlet);
}
// --------------------------
// DTD
function beginDocumentType() {
endText();
var documentType = beginPart();
documentType.value = '';
parser.enterState(STATE_DTD);
return documentType;
}
function endDocumentType() {
var documentType = endPart();
notifyDocumentType(documentType);
}
// --------------------------
// Declaration
function beginDeclaration() {
endText();
var declaration = beginPart();
declaration.value = '';
parser.enterState(STATE_DECLARATION);
return declaration;
}
function endDeclaration() {
var declaration = endPart();
notifyDeclaration(declaration);
}
// --------------------------
// CDATA
function beginCDATA() {
endText();
var cdata = beginPart();
cdata.value = '';
parser.enterState(STATE_CDATA);
return cdata;
}
function endCDATA() {
var cdata = endPart();
notifyCDATA(cdata.value, cdata.pos, parser.pos + 3);
}
// --------------------------
// JavaScript Comments
function beginLineComment() {
var comment = beginPart();
comment.value = '';
comment.type = 'line';
parser.enterState(STATE_JS_COMMENT_LINE);
return comment;
}
function beginBlockComment() {
var comment = beginPart();
comment.value = '';
comment.type = 'block';
parser.enterState(STATE_JS_COMMENT_BLOCK);
return comment;
}
function endJavaScriptComment() {
var comment = endPart();
comment.rawValue = comment.type === 'line' ?
'//' + comment.value :
'/*' + comment.value + '*/';
comment.parentState.comment(comment);
}
// --------------------------
// HTML Comment
function beginHtmlComment() {
endText();
var comment = beginPart();
comment.value = '';
parser.enterState(STATE_HTML_COMMENT);
return comment;
}
function endHtmlComment() {
var comment = endPart();
comment.endPos = parser.pos + 3;
notifyComment(comment);
}
// --------------------------
// Trailing whitespace
function beginCheckTrailingWhitespace(handler) {
var part = beginPart();
part.handler = handler;
if (typeof handler !== 'function') {
throw new Error('Invalid handler');
}
parser.enterState(STATE_CHECK_TRAILING_WHITESPACE);
}
function endCheckTrailingWhitespace(err, eof) {
var part = endPart();
part.handler(err, eof);
}
function handleTrailingWhitespaceJavaScriptComment(err) {
if (err) {
// This is a non-whitespace! We don't allow non-whitespace
// after matching two or more hyphens. This is user error...
notifyError(parser.pos,
'INVALID_CHARACTER',
'A non-whitespace of "' + err.ch + '" was found after a JavaScript block comment.');
}
return;
}
function handleTrailingWhitespaceMultilineHtmlBlcok(err, eof) {
if (err) {
// This is a non-whitespace! We don't allow non-whitespace
// after matching two or more hyphens. This is user error...
notifyError(parser.pos,
'INVALID_CHARACTER',
'A non-whitespace of "' + err.ch + '" was found on the same line as the ending delimiter ("' + htmlBlockDelimiter + '") for a multiline HTML block');
return;
}
endHtmlBlock();
if (eof) {
htmlEOF();
}
return;
}
// --------------------------
// Placeholder
function beginPlaceholder(escape, withinTagName) {
var placeholder = beginPart();
placeholder.value = '';
placeholder.escape = escape !== false;
placeholder.type = 'placeholder';
placeholder.withinBody = withinOpenTag !== true;
placeholder.withinAttribute = currentAttribute != null;
placeholder.withinString = placeholder.parentState === STATE_STRING;
placeholder.withinOpenTag = withinOpenTag === true && currentAttribute == null;
placeholder.withinTagName = withinTagName;
placeholderDepth++;
parser.enterState(STATE_PLACEHOLDER);
return placeholder;
}
function endPlaceholder() {
var placeholder = endPart();
placeholderDepth--;
var newExpression = notifyPlaceholder(placeholder);
placeholder.value = newExpression;
placeholder.parentState.placeholder(placeholder);
}
// --------------------------
// Placeholder
function beginTagNameShorthand(escape, withinTagName) {
var shorthand = beginPart();
shorthand.currentPart = null;
shorthand.hasId = false;
shorthand.beginPart = function(type) {
shorthand.currentPart = {
type: type,
stringParts: [],
text: '',
_endText() {
if (this.text) {
this.stringParts.push(JSON.stringify(this.text));
}
this.text = '';
},
addPlaceholder(placeholder) {
this._endText();
this.stringParts.push('(' + placeholder.value + ')');
},
end() {
this._endText();
var expression = this.stringParts.join('+');
if (type === 'id') {
currentOpenTag.shorthandId = {
value: expression
};
} else if (type === 'class') {
if (!currentOpenTag.shorthandClassNames) {
currentOpenTag.shorthandClassNames = [];
}
currentOpenTag.shorthandClassNames.push({
value: expression
});
}
}
};
};
parser.enterState(STATE_TAG_NAME_SHORTHAND);
return shorthand;
}
function endTagNameShorthand() {
var shorthand = endPart();
if (shorthand.currentPart) {
shorthand.currentPart.end();
}
parser.enterState(STATE_WITHIN_OPEN_TAG);
}
// --------------------------
function getAndRemoveArgument(expression) {
let start = expression.lastLeftParenPos;
if (start != null) {
// The tag has an argument that we need to slice off
let end = expression.lastRightParenPos;
if (end === expression.value.length - 1) {
var argument = {
value: expression.value.substring(start+1, end),
pos: expression.pos + start,
endPos: expression.pos + end + 1
};
// Chop off the argument from the expression
expression.value = expression.value.substring(0, start);
// Fix the end position for the expression
expression.endPos = expression.pos + expression.value.length;
return argument;
}
}
return undefined;
}
// --------------------------
function checkForPlaceholder(ch, code) {
if (code === CODE_DOLLAR) {
var nextCode = parser.lookAtCharCodeAhead(1);
if (nextCode === CODE_OPEN_CURLY_BRACE) {
// We expect to start a placeholder at the first curly brace (the next character)
beginPlaceholder(true);
return true;
} else if (nextCode === CODE_EXCLAMATION) {
var afterExclamationCode = parser.lookAtCharCodeAhead(2);
if (afterExclamationCode === CODE_OPEN_CURLY_BRACE) {
// We expect to start a placeholder at the first curly brace so skip
// past the exclamation point
beginPlaceholder(false);
parser.skip(1);
return true;
}
}
}
return false;
}
function checkForEscapedPlaceholder(ch, code) {
// Look for \${ and \$!{
if (code === CODE_BACK_SLASH) {
if (parser.lookAtCharCodeAhead(1) === CODE_DOLLAR) {
if (parser.lookAtCharCodeAhead(2) === CODE_OPEN_CURLY_BRACE) {
return true;
} else if (parser.lookAtCharCodeAhead(2) === CODE_EXCLAMATION) {
if (parser.lookAtCharCodeAhead(3) === CODE_OPEN_CURLY_BRACE) {
return true;
}
}
}
}
return false;
}
function checkForEscapedEscapedPlaceholder(ch, code) {
// Look for \\${ and \\$!{
if (code === CODE_BACK_SLASH) {
if (parser.lookAtCharCodeAhead(1) === CODE_BACK_SLASH) {
if (parser.lookAtCharCodeAhead(2) === CODE_DOLLAR) {
if (parser.lookAtCharCodeAhead(3) === CODE_OPEN_CURLY_BRACE) {
return true;
} else if (parser.lookAtCharCodeAhead(3) === CODE_EXCLAMATION) {
if (parser.lookAtCharCodeAhead(4) === CODE_OPEN_CURLY_BRACE) {
return true;
}
}
}
}
}
return false;
}
function lookPastWhitespaceFor(str, start) {
var ahead = start == null ? 1 : start;
while(isWhitespaceCode(parser.lookAtCharCodeAhead(ahead))) ahead++;
return !!parser.lookAheadFor(str, parser.pos+ahead);
}
function getNextIndent() {
var match = /[^\n]*\n(\s+)/.exec(parser.substring(parser.pos));
if(match) {
var whitespace = match[1].split(/\n/g);
return whitespace[whitespace.length-1];
}
}
function onlyWhitespaceRemainsOnLine(offset) {
offset = offset == null ? 1 : offset;
return /^\s*\n/.test(parser.substring(parser.pos+offset));
}
function consumeWhitespace() {
var ahead = 1;
var whitespace = '';
while(isWhitespaceCode(parser.lookAtCharCodeAhead(ahead))) {
whitespace += parser.lookAtCharAhead(ahead++);
}
parser.skip(whitespace.length);
return whitespace;
}
function checkForClosingTag() {
// Look ahead to see if we found the closing tag that will
// take us out of the EXPRESSION state...
var lookAhead = '/' + expectedCloseTagName + '>';
var match = parser.lookAheadFor(lookAhead);
if (match) {
endText();
closeTag(expectedCloseTagName, parser.pos, parser.pos + 1 + lookAhead.length);
parser.skip(match.length);
parser.enterState(STATE_HTML_CONTENT);
return true;
}
return false;
}