-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighlight.js
2265 lines (1998 loc) · 72.4 KB
/
highlight.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
/*
Highlight.js 10.4.0 (1166e687)
License: BSD-3-Clause
Copyright (c) 2006-2020, Ivan Sagalaev
*/
var hljs = (function () {
'use strict';
function deepFreeze(obj) {
if (obj instanceof Map) {
obj.clear = obj.delete = obj.set = function () {
throw new Error('map is read-only');
};
} else if (obj instanceof Set) {
obj.add = obj.clear = obj.delete = function () {
throw new Error('set is read-only');
};
}
// Freeze self
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach(function (name) {
var prop = obj[name];
// Freeze prop if it is an object
if (typeof prop == 'object' && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
});
return obj;
}
var deepFreezeEs6 = deepFreeze;
var _default = deepFreeze;
deepFreezeEs6.default = _default;
class Response {
constructor(mode) {
// eslint-disable-next-line no-undefined
if (mode.data === undefined) mode.data = {};
this.data = mode.data;
}
ignoreMatch() {
this.ignore = true;
}
}
/**
* @param {string} value
* @returns {string}
*/
function escapeHTML(value) {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* performs a shallow merge of multiple objects into one
*
* @template T
* @param {T} original
* @param {Record<string,any>[]} objects
* @returns {T} a single new object
*/
function inherit(original, ...objects) {
/** @type Record<string,any> */
const result = Object.create(null);
for (const key in original) {
result[key] = original[key];
}
objects.forEach(function(obj) {
for (const key in obj) {
result[key] = obj[key];
}
});
return /** @type {T} */ (result);
}
/* Stream merging */
/**
* @typedef Event
* @property {'start'|'stop'} event
* @property {number} offset
* @property {Node} node
*/
/**
* @param {Node} node
*/
function tag(node) {
return node.nodeName.toLowerCase();
}
/**
* @param {Node} node
*/
function nodeStream(node) {
/** @type Event[] */
const result = [];
(function _nodeStream(node, offset) {
for (let child = node.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 3) {
offset += child.nodeValue.length;
} else if (child.nodeType === 1) {
result.push({
event: 'start',
offset: offset,
node: child
});
offset = _nodeStream(child, offset);
// Prevent void elements from having an end tag that would actually
// double them in the output. There are more void elements in HTML
// but we list only those realistically expected in code display.
if (!tag(child).match(/br|hr|img|input/)) {
result.push({
event: 'stop',
offset: offset,
node: child
});
}
}
}
return offset;
})(node, 0);
return result;
}
/**
* @param {any} original - the original stream
* @param {any} highlighted - stream of the highlighted source
* @param {string} value - the original source itself
*/
function mergeStreams(original, highlighted, value) {
let processed = 0;
let result = '';
const nodeStack = [];
function selectStream() {
if (!original.length || !highlighted.length) {
return original.length ? original : highlighted;
}
if (original[0].offset !== highlighted[0].offset) {
return (original[0].offset < highlighted[0].offset) ? original : highlighted;
}
/*
To avoid starting the stream just before it should stop the order is
ensured that original always starts first and closes last:
if (event1 == 'start' && event2 == 'start')
return original;
if (event1 == 'start' && event2 == 'stop')
return highlighted;
if (event1 == 'stop' && event2 == 'start')
return original;
if (event1 == 'stop' && event2 == 'stop')
return highlighted;
... which is collapsed to:
*/
return highlighted[0].event === 'start' ? original : highlighted;
}
/**
* @param {Node} node
*/
function open(node) {
/** @param {Attr} attr */
function attributeString(attr) {
return ' ' + attr.nodeName + '="' + escapeHTML(attr.value) + '"';
}
// @ts-ignore
result += '<' + tag(node) + [].map.call(node.attributes, attributeString).join('') + '>';
}
/**
* @param {Node} node
*/
function close(node) {
result += '</' + tag(node) + '>';
}
/**
* @param {Event} event
*/
function render(event) {
(event.event === 'start' ? open : close)(event.node);
}
while (original.length || highlighted.length) {
let stream = selectStream();
result += escapeHTML(value.substring(processed, stream[0].offset));
processed = stream[0].offset;
if (stream === original) {
/*
On any opening or closing tag of the original markup we first close
the entire highlighted node stack, then render the original tag along
with all the following original tags at the same offset and then
reopen all the tags on the highlighted stack.
*/
nodeStack.reverse().forEach(close);
do {
render(stream.splice(0, 1)[0]);
stream = selectStream();
} while (stream === original && stream.length && stream[0].offset === processed);
nodeStack.reverse().forEach(open);
} else {
if (stream[0].event === 'start') {
nodeStack.push(stream[0].node);
} else {
nodeStack.pop();
}
render(stream.splice(0, 1)[0]);
}
}
return result + escapeHTML(value.substr(processed));
}
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
escapeHTML: escapeHTML,
inherit: inherit,
nodeStream: nodeStream,
mergeStreams: mergeStreams
});
/**
* @typedef {object} Renderer
* @property {(text: string) => void} addText
* @property {(node: Node) => void} openNode
* @property {(node: Node) => void} closeNode
* @property {() => string} value
*/
/** @typedef {{kind?: string, sublanguage?: boolean}} Node */
/** @typedef {{walk: (r: Renderer) => void}} Tree */
/** */
const SPAN_CLOSE = '</span>';
/**
* Determines if a node needs to be wrapped in <span>
*
* @param {Node} node */
const emitsWrappingTags = (node) => {
return !!node.kind;
};
/** @type {Renderer} */
class HTMLRenderer {
/**
* Creates a new HTMLRenderer
*
* @param {Tree} parseTree - the parse tree (must support `walk` API)
* @param {{classPrefix: string}} options
*/
constructor(parseTree, options) {
this.buffer = "";
this.classPrefix = options.classPrefix;
parseTree.walk(this);
}
/**
* Adds texts to the output stream
*
* @param {string} text */
addText(text) {
this.buffer += escapeHTML(text);
}
/**
* Adds a node open to the output stream (if needed)
*
* @param {Node} node */
openNode(node) {
if (!emitsWrappingTags(node)) return;
let className = node.kind;
if (!node.sublanguage) {
className = `${this.classPrefix}${className}`;
}
this.span(className);
}
/**
* Adds a node close to the output stream (if needed)
*
* @param {Node} node */
closeNode(node) {
if (!emitsWrappingTags(node)) return;
this.buffer += SPAN_CLOSE;
}
/**
* returns the accumulated buffer
*/
value() {
return this.buffer;
}
// helpers
/**
* Builds a span element
*
* @param {string} className */
span(className) {
this.buffer += `<span class="${className}">`;
}
}
/** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} | string} Node */
/** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} } DataNode */
/** */
class TokenTree {
constructor() {
/** @type DataNode */
this.rootNode = { children: [] };
this.stack = [this.rootNode];
}
get top() {
return this.stack[this.stack.length - 1];
}
get root() { return this.rootNode; }
/** @param {Node} node */
add(node) {
this.top.children.push(node);
}
/** @param {string} kind */
openNode(kind) {
/** @type Node */
const node = { kind, children: [] };
this.add(node);
this.stack.push(node);
}
closeNode() {
if (this.stack.length > 1) {
return this.stack.pop();
}
// eslint-disable-next-line no-undefined
return undefined;
}
closeAllNodes() {
while (this.closeNode());
}
toJSON() {
return JSON.stringify(this.rootNode, null, 4);
}
/**
* @typedef { import("./html_renderer").Renderer } Renderer
* @param {Renderer} builder
*/
walk(builder) {
// this does not
return this.constructor._walk(builder, this.rootNode);
// this works
// return TokenTree._walk(builder, this.rootNode);
}
/**
* @param {Renderer} builder
* @param {Node} node
*/
static _walk(builder, node) {
if (typeof node === "string") {
builder.addText(node);
} else if (node.children) {
builder.openNode(node);
node.children.forEach((child) => this._walk(builder, child));
builder.closeNode(node);
}
return builder;
}
/**
* @param {Node} node
*/
static _collapse(node) {
if (typeof node === "string") return;
if (!node.children) return;
if (node.children.every(el => typeof el === "string")) {
// node.text = node.children.join("");
// delete node.children;
node.children = [node.children.join("")];
} else {
node.children.forEach((child) => {
TokenTree._collapse(child);
});
}
}
}
/**
Currently this is all private API, but this is the minimal API necessary
that an Emitter must implement to fully support the parser.
Minimal interface:
- addKeyword(text, kind)
- addText(text)
- addSublanguage(emitter, subLanguageName)
- finalize()
- openNode(kind)
- closeNode()
- closeAllNodes()
- toHTML()
*/
/**
* @implements {Emitter}
*/
class TokenTreeEmitter extends TokenTree {
/**
* @param {*} options
*/
constructor(options) {
super();
this.options = options;
}
/**
* @param {string} text
* @param {string} kind
*/
addKeyword(text, kind) {
if (text === "") { return; }
this.openNode(kind);
this.addText(text);
this.closeNode();
}
/**
* @param {string} text
*/
addText(text) {
if (text === "") { return; }
this.add(text);
}
/**
* @param {Emitter & {root: DataNode}} emitter
* @param {string} name
*/
addSublanguage(emitter, name) {
/** @type DataNode */
const node = emitter.root;
node.kind = name;
node.sublanguage = true;
this.add(node);
}
toHTML() {
const renderer = new HTMLRenderer(this, this.options);
return renderer.value();
}
finalize() {
return true;
}
}
/**
* @param {string} value
* @returns {RegExp}
* */
function escape(value) {
return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm');
}
/**
* @param {RegExp | string } re
* @returns {string}
*/
function source(re) {
if (!re) return null;
if (typeof re === "string") return re;
return re.source;
}
/**
* @param {...(RegExp | string) } args
* @returns {string}
*/
function concat(...args) {
const joined = args.map((x) => source(x)).join("");
return joined;
}
/**
* @param {RegExp} re
* @returns {number}
*/
function countMatchGroups(re) {
return (new RegExp(re.toString() + '|')).exec('').length - 1;
}
/**
* Does lexeme start with a regular expression match at the beginning
* @param {RegExp} re
* @param {string} lexeme
*/
function startsWith(re, lexeme) {
const match = re && re.exec(lexeme);
return match && match.index === 0;
}
// join logically computes regexps.join(separator), but fixes the
// backreferences so they continue to match.
// it also places each individual regular expression into it's own
// match group, keeping track of the sequencing of those match groups
// is currently an exercise for the caller. :-)
/**
* @param {(string | RegExp)[]} regexps
* @param {string} separator
* @returns {string}
*/
function join(regexps, separator = "|") {
// backreferenceRe matches an open parenthesis or backreference. To avoid
// an incorrect parse, it additionally matches the following:
// - [...] elements, where the meaning of parentheses and escapes change
// - other escape sequences, so we do not misparse escape sequences as
// interesting elements
// - non-matching or lookahead parentheses, which do not capture. These
// follow the '(' with a '?'.
const backreferenceRe = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
let numCaptures = 0;
let ret = '';
for (let i = 0; i < regexps.length; i++) {
numCaptures += 1;
const offset = numCaptures;
let re = source(regexps[i]);
if (i > 0) {
ret += separator;
}
ret += "(";
while (re.length > 0) {
const match = backreferenceRe.exec(re);
if (match == null) {
ret += re;
break;
}
ret += re.substring(0, match.index);
re = re.substring(match.index + match[0].length);
if (match[0][0] === '\\' && match[1]) {
// Adjust the backreference.
ret += '\\' + String(Number(match[1]) + offset);
} else {
ret += match[0];
if (match[0] === '(') {
numCaptures++;
}
}
}
ret += ")";
}
return ret;
}
// Common regexps
const IDENT_RE = '[a-zA-Z]\\w*';
const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
/**
* @param { Partial<Mode> & {binary?: string | RegExp} } opts
*/
const SHEBANG = (opts = {}) => {
const beginShebang = /^#![ ]*\//;
if (opts.binary) {
opts.begin = concat(
beginShebang,
/.*\b/,
opts.binary,
/\b.*/);
}
return inherit({
className: 'meta',
begin: beginShebang,
end: /$/,
relevance: 0,
/** @type {ModeCallback} */
"on:begin": (m, resp) => {
if (m.index !== 0) resp.ignoreMatch();
}
}, opts);
};
// Common modes
const BACKSLASH_ESCAPE = {
begin: '\\\\[\\s\\S]', relevance: 0
};
const APOS_STRING_MODE = {
className: 'string',
begin: '\'',
end: '\'',
illegal: '\\n',
contains: [BACKSLASH_ESCAPE]
};
const QUOTE_STRING_MODE = {
className: 'string',
begin: '"',
end: '"',
illegal: '\\n',
contains: [BACKSLASH_ESCAPE]
};
const PHRASAL_WORDS_MODE = {
begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
};
/**
* Creates a comment mode
*
* @param {string | RegExp} begin
* @param {string | RegExp} end
* @param {Mode | {}} [modeOptions]
* @returns {Partial<Mode>}
*/
const COMMENT = function(begin, end, modeOptions = {}) {
const mode = inherit(
{
className: 'comment',
begin,
end,
contains: []
},
modeOptions
);
mode.contains.push(PHRASAL_WORDS_MODE);
mode.contains.push({
className: 'doctag',
begin: '(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):',
relevance: 0
});
return mode;
};
const C_LINE_COMMENT_MODE = COMMENT('//', '$');
const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
const HASH_COMMENT_MODE = COMMENT('#', '$');
const NUMBER_MODE = {
className: 'number',
begin: NUMBER_RE,
relevance: 0
};
const C_NUMBER_MODE = {
className: 'number',
begin: C_NUMBER_RE,
relevance: 0
};
const BINARY_NUMBER_MODE = {
className: 'number',
begin: BINARY_NUMBER_RE,
relevance: 0
};
const CSS_NUMBER_MODE = {
className: 'number',
begin: NUMBER_RE + '(' +
'%|em|ex|ch|rem' +
'|vw|vh|vmin|vmax' +
'|cm|mm|in|pt|pc|px' +
'|deg|grad|rad|turn' +
'|s|ms' +
'|Hz|kHz' +
'|dpi|dpcm|dppx' +
')?',
relevance: 0
};
const REGEXP_MODE = {
// this outer rule makes sure we actually have a WHOLE regex and not simply
// an expression such as:
//
// 3 / something
//
// (which will then blow up when regex's `illegal` sees the newline)
begin: /(?=\/[^/\n]*\/)/,
contains: [{
className: 'regexp',
begin: /\//,
end: /\/[gimuy]*/,
illegal: /\n/,
contains: [
BACKSLASH_ESCAPE,
{
begin: /\[/,
end: /\]/,
relevance: 0,
contains: [BACKSLASH_ESCAPE]
}
]
}]
};
const TITLE_MODE = {
className: 'title',
begin: IDENT_RE,
relevance: 0
};
const UNDERSCORE_TITLE_MODE = {
className: 'title',
begin: UNDERSCORE_IDENT_RE,
relevance: 0
};
const METHOD_GUARD = {
// excludes method names from keyword processing
begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
relevance: 0
};
/**
* Adds end same as begin mechanics to a mode
*
* Your mode must include at least a single () match group as that first match
* group is what is used for comparison
* @param {Partial<Mode>} mode
*/
const END_SAME_AS_BEGIN = function(mode) {
return Object.assign(mode,
{
/** @type {ModeCallback} */
'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
/** @type {ModeCallback} */
'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
});
};
var MODES = /*#__PURE__*/Object.freeze({
__proto__: null,
IDENT_RE: IDENT_RE,
UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
NUMBER_RE: NUMBER_RE,
C_NUMBER_RE: C_NUMBER_RE,
BINARY_NUMBER_RE: BINARY_NUMBER_RE,
RE_STARTERS_RE: RE_STARTERS_RE,
SHEBANG: SHEBANG,
BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
APOS_STRING_MODE: APOS_STRING_MODE,
QUOTE_STRING_MODE: QUOTE_STRING_MODE,
PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
COMMENT: COMMENT,
C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
HASH_COMMENT_MODE: HASH_COMMENT_MODE,
NUMBER_MODE: NUMBER_MODE,
C_NUMBER_MODE: C_NUMBER_MODE,
BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
CSS_NUMBER_MODE: CSS_NUMBER_MODE,
REGEXP_MODE: REGEXP_MODE,
TITLE_MODE: TITLE_MODE,
UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE,
METHOD_GUARD: METHOD_GUARD,
END_SAME_AS_BEGIN: END_SAME_AS_BEGIN
});
// keywords that should have no default relevance value
const COMMON_KEYWORDS = [
'of',
'and',
'for',
'in',
'not',
'or',
'if',
'then',
'parent', // common variable name
'list', // common variable name
'value' // common variable name
];
// compilation
/**
* Compiles a language definition result
*
* Given the raw result of a language definition (Language), compiles this so
* that it is ready for highlighting code.
* @param {Language} language
* @returns {CompiledLanguage}
*/
function compileLanguage(language) {
/**
* Builds a regex with the case sensativility of the current language
*
* @param {RegExp | string} value
* @param {boolean} [global]
*/
function langRe(value, global) {
return new RegExp(
source(value),
'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')
);
}
/**
Stores multiple regular expressions and allows you to quickly search for
them all in a string simultaneously - returning the first match. It does
this by creating a huge (a|b|c) regex - each individual item wrapped with ()
and joined by `|` - using match groups to track position. When a match is
found checking which position in the array has content allows us to figure
out which of the original regexes / match groups triggered the match.
The match object itself (the result of `Regex.exec`) is returned but also
enhanced by merging in any meta-data that was registered with the regex.
This is how we keep track of which mode matched, and what type of rule
(`illegal`, `begin`, end, etc).
*/
class MultiRegex {
constructor() {
this.matchIndexes = {};
// @ts-ignore
this.regexes = [];
this.matchAt = 1;
this.position = 0;
}
// @ts-ignore
addRule(re, opts) {
opts.position = this.position++;
// @ts-ignore
this.matchIndexes[this.matchAt] = opts;
this.regexes.push([opts, re]);
this.matchAt += countMatchGroups(re) + 1;
}
compile() {
if (this.regexes.length === 0) {
// avoids the need to check length every time exec is called
// @ts-ignore
this.exec = () => null;
}
const terminators = this.regexes.map(el => el[1]);
this.matcherRe = langRe(join(terminators), true);
this.lastIndex = 0;
}
/** @param {string} s */
exec(s) {
this.matcherRe.lastIndex = this.lastIndex;
const match = this.matcherRe.exec(s);
if (!match) { return null; }
// eslint-disable-next-line no-undefined
const i = match.findIndex((el, i) => i > 0 && el !== undefined);
// @ts-ignore
const matchData = this.matchIndexes[i];
// trim off any earlier non-relevant match groups (ie, the other regex
// match groups that make up the multi-matcher)
match.splice(0, i);
return Object.assign(match, matchData);
}
}
/*
Created to solve the key deficiently with MultiRegex - there is no way to
test for multiple matches at a single location. Why would we need to do
that? In the future a more dynamic engine will allow certain matches to be
ignored. An example: if we matched say the 3rd regex in a large group but
decided to ignore it - we'd need to started testing again at the 4th
regex... but MultiRegex itself gives us no real way to do that.
So what this class creates MultiRegexs on the fly for whatever search
position they are needed.
NOTE: These additional MultiRegex objects are created dynamically. For most
grammars most of the time we will never actually need anything more than the
first MultiRegex - so this shouldn't have too much overhead.
Say this is our search group, and we match regex3, but wish to ignore it.
regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0
What we need is a new MultiRegex that only includes the remaining
possibilities:
regex4 | regex5 ' ie, startAt = 3
This class wraps all that complexity up in a simple API... `startAt` decides
where in the array of expressions to start doing the matching. It
auto-increments, so if a match is found at position 2, then startAt will be
set to 3. If the end is reached startAt will return to 0.
MOST of the time the parser will be setting startAt manually to 0.
*/
class ResumableMultiRegex {
constructor() {
// @ts-ignore
this.rules = [];
// @ts-ignore
this.multiRegexes = [];
this.count = 0;
this.lastIndex = 0;
this.regexIndex = 0;
}
// @ts-ignore
getMatcher(index) {
if (this.multiRegexes[index]) return this.multiRegexes[index];
const matcher = new MultiRegex();
this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
matcher.compile();
this.multiRegexes[index] = matcher;
return matcher;
}
resumingScanAtSamePosition() {
return this.regexIndex !== 0;
}
considerAll() {
this.regexIndex = 0;
}
// @ts-ignore
addRule(re, opts) {
this.rules.push([re, opts]);
if (opts.type === "begin") this.count++;
}
/** @param {string} s */
exec(s) {
const m = this.getMatcher(this.regexIndex);
m.lastIndex = this.lastIndex;
let result = m.exec(s);
// The following is because we have no easy way to say "resume scanning at the
// existing position but also skip the current rule ONLY". What happens is
// all prior rules are also skipped which can result in matching the wrong
// thing. Example of matching "booger":
// our matcher is [string, "booger", number]
//
// ....booger....
// if "booger" is ignored then we'd really need a regex to scan from the
// SAME position for only: [string, number] but ignoring "booger" (if it
// was the first match), a simple resume would scan ahead who knows how
// far looking only for "number", ignoring potential string matches (or
// future "booger" matches that might be valid.)
// So what we do: We execute two matchers, one resuming at the same
// position, but the second full matcher starting at the position after:
// /--- resume first regex match here (for [number])
// |/---- full match here for [string, "booger", number]
// vv
// ....booger....
// Which ever results in a match first is then used. So this 3-4 step
// process essentially allows us to say "match at this position, excluding
// a prior rule that was ignored".
//
// 1. Match "booger" first, ignore. Also proves that [string] does non match.
// 2. Resume matching for [number]
// 3. Match at index + 1 for [string, "booger", number]
// 4. If #2 and #3 result in matches, which came first?
if (this.resumingScanAtSamePosition()) {
if (result && result.index === this.lastIndex) ; else { // use the second matcher result
const m2 = this.getMatcher(0);
m2.lastIndex = this.lastIndex + 1;
result = m2.exec(s);
}
}
if (result) {
this.regexIndex += result.position + 1;
if (this.regexIndex === this.count) {
// wrap-around to considering all matches again
this.considerAll();
}
}
return result;