-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.ts
More file actions
667 lines (595 loc) · 16.2 KB
/
lexer.ts
File metadata and controls
667 lines (595 loc) · 16.2 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
import { createPoint, createPosition } from "@wdprlib/ast";
import { createToken, type Token, type TokenType } from "./tokens";
/**
* Configuration for the {@link Lexer}.
*
* @group Lexer
*/
export interface LexerOptions {
/**
* When `true` (default), every token carries accurate line/column/offset
* data. Set to `false` to skip position tracking for faster tokenisation
* when source-map information is not needed.
*/
trackPositions?: boolean;
}
/**
* Internal mutable state carried through a single tokenisation pass.
*/
interface LexerState {
source: string;
pos: number;
line: number;
column: number;
lineStart: boolean;
tokens: Token[];
}
/**
* Converts a Wikidot markup source string into a flat array of {@link Token}s.
*
* The lexer is single-pass and greedy: it tries the longest-matching
* multi-character pattern first (e.g. `[[[` before `[[`, `**` before `*`).
* Context-sensitive constructs (line-start headings, blockquote markers)
* are disambiguated via the `lineStart` state flag.
*
* For convenience, use the standalone {@link tokenize} function instead
* of constructing a `Lexer` directly.
*
* @group Lexer
*/
export class Lexer {
private state: LexerState;
private options: Required<LexerOptions>;
// Positions where ]] should be split into ] + ] (for invalid anchor names)
private splitBlockClosePositions: Set<number> = new Set();
constructor(source: string, options: LexerOptions = {}) {
this.options = {
trackPositions: options.trackPositions ?? true,
};
this.state = {
source,
pos: 0,
line: 1,
column: 1,
lineStart: true,
tokens: [],
};
}
/**
* Tokenize the entire source
*/
tokenize(): Token[] {
while (!this.isAtEnd()) {
this.scanToken();
}
this.addToken("EOF", "");
return this.state.tokens;
}
/**
* Check if at end of source
*/
private isAtEnd(): boolean {
return this.state.pos >= this.state.source.length;
}
/**
* Get current character
*/
private current(): string {
return this.state.source[this.state.pos] ?? "";
}
/**
* Check if [[# is followed by an invalid anchor name that closes with ]].
* Valid: [[# valid-name]] where name matches [-_A-Za-z0-9.%]+
* Invalid: [[# name with spaces]] or [[# name$special]]
* When invalid, returns the position of the closing ]] so the lexer can
* emit tokens that allow the inner [# text] to be parsed as a described link.
*/
private findInvalidAnchorNameEnd(): number | null {
const src = this.state.source;
const pos = this.state.pos;
// Must start with [[#
if (src[pos] !== "[" || src[pos + 1] !== "[" || src[pos + 2] !== "#") {
return null;
}
// Must have space after #
if (src[pos + 3] !== " ") {
return null;
}
// Skip spaces after #
let i = pos + 4;
while (i < src.length && src[i] === " ") {
i++;
}
// Scan for invalid characters
let foundInvalid = false;
while (i < src.length) {
const ch = src[i]!;
if (ch === "\n") return null;
if (ch === "]" && src[i + 1] === "]") {
// Reached ]] - if we found invalid chars, this is an invalid anchor name
return foundInvalid ? i : null;
}
const code = ch.charCodeAt(0);
const isValid =
(code >= 48 && code <= 57) || // 0-9
(code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) || // a-z
code === 45 || // -
code === 95 || // _
code === 46 || // .
code === 37; // %
if (!isValid) {
foundInvalid = true;
}
i++;
}
return null;
}
/**
* Check if source matches pattern at current position
*/
private match(pattern: string): boolean {
for (let i = 0; i < pattern.length; i++) {
if (this.state.source[this.state.pos + i] !== pattern[i]) {
return false;
}
}
return true;
}
/**
* Advance position by n characters
*/
private advance(n = 1): string {
let result = "";
for (let i = 0; i < n && !this.isAtEnd(); i++) {
const char = this.current();
result += char;
this.state.pos++;
if (char === "\n") {
this.state.line++;
this.state.column = 1;
this.state.lineStart = true;
} else {
this.state.column++;
if (char !== " " && char !== "\t") {
this.state.lineStart = false;
}
}
}
return result;
}
/**
* Returns the type of the last non-whitespace token, or null if none.
*/
private lastNonWhitespaceTokenType(): TokenType | null {
for (let i = this.state.tokens.length - 1; i >= 0; i--) {
const t = this.state.tokens[i]!;
if (t.type !== "WHITESPACE") return t.type;
}
return null;
}
/**
* Add token
*/
private addToken(type: TokenType, value: string): void {
const startPos = createPoint(
this.state.line,
this.state.column - value.length,
this.state.pos - value.length,
);
const endPos = createPoint(this.state.line, this.state.column, this.state.pos);
const position = this.options.trackPositions
? createPosition(startPos, endPos)
: createPosition(createPoint(0, 0, 0), createPoint(0, 0, 0));
const lineStart =
this.state.tokens.length === 0 ||
this.state.tokens[this.state.tokens.length - 1]?.type === "NEWLINE";
this.state.tokens.push(createToken(type, value, position, lineStart));
}
/**
* Scan a single token
*/
private scanToken(): void {
const char = this.current();
const isLineStart = this.state.lineStart;
// Newline
if (char === "\n") {
this.advance();
this.addToken("NEWLINE", "\n");
return;
}
// Whitespace (non-newline)
if (char === " " || char === "\t") {
let ws = "";
while (!this.isAtEnd() && (this.current() === " " || this.current() === "\t")) {
ws += this.advance();
}
this.addToken("WHITESPACE", ws);
return;
}
// Comment open [!-- (must check before [[[)
if (this.match("[!--")) {
this.advance(4);
this.addToken("COMMENT_OPEN", "[!--");
return;
}
// Link open [[[ (must check before [[)
if (this.match("[[[")) {
this.advance(3);
this.addToken("LINK_OPEN", "[[[");
return;
}
// Block end open [[/
if (this.match("[[/")) {
this.advance(3);
this.addToken("BLOCK_END_OPEN", "[[/");
return;
}
// Block open [[
if (this.match("[[")) {
// Check for invalid anchor name pattern: [[# name-with-spaces]]
// Wikidot's Anchor regex requires [-_A-Za-z0-9.%] only after [[# .
// If [[# is followed by invalid anchor name, decompose into
// TEXT "[" so the inner [# text] is parsed as a described anchor link.
// The closing ]] will also be split: ] (BRACKET_CLOSE) + ] (TEXT).
const invalidEnd = this.findInvalidAnchorNameEnd();
if (invalidEnd !== null) {
this.splitBlockClosePositions.add(invalidEnd);
this.advance(1);
this.addToken("TEXT", "[");
return;
}
this.advance(2);
this.addToken("BLOCK_OPEN", "[[");
return;
}
// Link close ]]] (must check before ]])
if (this.match("]]]")) {
this.advance(3);
this.addToken("LINK_CLOSE", "]]]");
return;
}
// Block close ]]
if (this.match("]]")) {
// For invalid anchor names, split ]] into ] (BRACKET_CLOSE) + ] (TEXT)
if (this.splitBlockClosePositions.has(this.state.pos)) {
this.splitBlockClosePositions.delete(this.state.pos);
this.advance(1);
this.addToken("BRACKET_CLOSE", "]");
this.advance(1);
this.addToken("TEXT", "]");
return;
}
this.advance(2);
this.addToken("BLOCK_CLOSE", "]]");
return;
}
// Raw/escape @@
if (this.match("@@")) {
this.advance(2);
this.addToken("RAW_OPEN", "@@");
return;
}
// Raw block @<
if (this.match("@<")) {
this.advance(2);
this.addToken("RAW_BLOCK_OPEN", "@<");
return;
}
// Raw block close >@
if (this.match(">@")) {
this.advance(2);
this.addToken("RAW_BLOCK_CLOSE", ">@");
return;
}
// Monospace open {{
if (this.match("{{")) {
this.advance(2);
this.addToken("MONO_MARKER", "{{");
return;
}
// Monospace close }}
if (this.match("}}")) {
this.advance(2);
this.addToken("MONO_CLOSE", "}}");
return;
}
// Bold **
if (this.match("**")) {
this.advance(2);
this.addToken("BOLD_MARKER", "**");
return;
}
// Horizontal rule ---- or more (4+ hyphens, check before --)
if (isLineStart && this.match("----")) {
let dashes = "";
while (this.current() === "-") {
dashes += this.advance();
}
this.addToken("HR_MARKER", dashes);
return;
}
// Comment close --] (must check before --)
if (this.match("--]")) {
this.advance(3);
this.addToken("COMMENT_CLOSE", "--]");
return;
}
// Strikethrough -- (Wikidot only uses --)
if (this.match("--")) {
this.advance(2);
this.addToken("STRIKE_MARKER", "--");
return;
}
// Left double angle << (guillemet)
if (this.match("<<")) {
this.advance(2);
this.addToken("LEFT_DOUBLE_ANGLE", "<<");
return;
}
// Clear float ~~~~ or more (at line start only, Wikidot requires 4+)
if (isLineStart && this.match("~~~~")) {
let tildes = "";
while (this.current() === "~") {
tildes += this.advance();
}
// Check for directional clear float
if (this.current() === "<") {
this.advance();
this.addToken("CLEAR_FLOAT_LEFT", `${tildes}<`);
return;
}
if (this.current() === ">") {
this.advance();
this.addToken("CLEAR_FLOAT_RIGHT", `${tildes}>`);
return;
}
this.addToken("CLEAR_FLOAT", `${tildes}`);
return;
}
// Single hyphen (not part of --)
if (char === "-") {
this.advance();
this.addToken("TEXT", "-");
return;
}
// Underline __ (check before single _)
if (this.match("__")) {
this.advance(2);
this.addToken("UNDERLINE_MARKER", "__");
return;
}
// Single underscore _ (for line break)
if (char === "_") {
this.advance();
this.addToken("UNDERSCORE", "_");
return;
}
// Superscript ^^
if (this.match("^^")) {
this.advance(2);
this.addToken("SUPER_MARKER", "^^");
return;
}
// Subscript ,,
if (this.match(",,")) {
this.advance(2);
this.addToken("SUB_MARKER", ",,");
return;
}
// Italic //
if (this.match("//")) {
this.advance(2);
this.addToken("ITALIC_MARKER", "//");
return;
}
// Table markers
// ||~ (header), ||< (left), ||= (center), ||> (right), || (normal)
if (this.match("||~")) {
this.advance(3);
this.addToken("TABLE_HEADER", "||~");
return;
}
if (this.match("||<")) {
this.advance(3);
this.addToken("TABLE_LEFT", "||<");
return;
}
if (this.match("||=")) {
this.advance(3);
this.addToken("TABLE_CENTER", "||=");
return;
}
if (this.match("||>")) {
this.advance(3);
this.addToken("TABLE_RIGHT", "||>");
return;
}
if (this.match("||")) {
this.advance(2);
this.addToken("TABLE_MARKER", "||");
return;
}
// Heading + (at line start)
if (isLineStart && char === "+") {
let plusCount = 0;
while (this.current() === "+") {
plusCount++;
this.advance();
}
this.addToken("HEADING_MARKER", "+".repeat(plusCount));
return;
}
// List bullet * (at line start)
if (isLineStart && char === "*") {
this.advance();
this.addToken("LIST_BULLET", "*");
return;
}
// Color marker ## (check before LIST_NUMBER)
if (this.match("##")) {
this.advance(2);
this.addToken("COLOR_MARKER", "##");
return;
}
// List number # (at line start)
if (isLineStart && char === "#") {
this.advance();
this.addToken("LIST_NUMBER", "#");
return;
}
// Blockquote > or >>> (at line start only for blockquote)
if (char === ">") {
if (isLineStart) {
// At line start: consume all consecutive > as a single blockquote marker
let depth = "";
while (this.current() === ">") {
depth += this.advance();
}
this.addToken("BLOCKQUOTE_MARKER", depth);
return;
}
// Not at line start
if (this.match(">>")) {
// >> not at line start - guillemet
this.advance(2);
this.addToken("RIGHT_DOUBLE_ANGLE", ">>");
return;
}
// Single > not at line start - just text
this.advance();
this.addToken("TEXT", ">");
return;
}
// Bracket anchor [#
if (this.match("[#")) {
this.advance(2);
this.addToken("BRACKET_ANCHOR", "[#");
return;
}
// Bracket star [* (for new tab links)
if (this.match("[*")) {
this.advance(2);
this.addToken("BRACKET_STAR", "[*");
return;
}
// Single characters
if (char === "[") {
this.advance();
this.addToken("BRACKET_OPEN", "[");
return;
}
if (char === "]") {
this.advance();
this.addToken("BRACKET_CLOSE", "]");
return;
}
if (char === "|") {
this.advance();
this.addToken("PIPE", "|");
return;
}
if (char === "=") {
this.advance();
this.addToken("EQUALS", "=");
return;
}
// Quoted string (only after EQUALS for block attribute values)
// In inline context, " is just a text character (typographic quotes)
if (char === '"') {
const lastNonWs = this.lastNonWhitespaceTokenType();
if (lastNonWs === "EQUALS") {
let quoted = this.advance(); // opening "
while (!this.isAtEnd() && this.current() !== '"' && this.current() !== "\n") {
quoted += this.advance();
}
if (this.current() === '"') {
quoted += this.advance(); // closing "
}
this.addToken("QUOTED_STRING", quoted);
return;
}
this.advance();
this.addToken("TEXT", '"');
return;
}
if (char === ":") {
this.advance();
this.addToken("COLON", ":");
return;
}
if (char === "/") {
this.advance();
this.addToken("SLASH", "/");
return;
}
if (char === "*") {
this.advance();
this.addToken("STAR", "*");
return;
}
if (char === "#") {
this.advance();
this.addToken("HASH", "#");
return;
}
if (char === "@") {
this.advance();
this.addToken("AT", "@");
return;
}
if (char === "&") {
this.advance();
this.addToken("AMPERSAND", "&");
return;
}
if (char === "\\") {
this.advance();
this.addToken("BACKSLASH", "\\");
return;
}
// Backslash line break marker (U+E000, inserted by preproc)
if (char.charCodeAt(0) === 0xe000) {
this.advance();
this.addToken("BACKSLASH_BREAK", char);
return;
}
// Identifier: alphanumeric sequence
if (this.isAlphanumeric(char)) {
let ident = "";
while (!this.isAtEnd() && this.isAlphanumeric(this.current())) {
ident += this.advance();
}
this.addToken("IDENTIFIER", ident);
return;
}
// Default: single character as text
const text = this.advance();
this.addToken("TEXT", text);
}
/**
* Check if character is alphanumeric (for identifier tokens)
*/
private isAlphanumeric(char: string): boolean {
const code = char.charCodeAt(0);
return (
(code >= 48 && code <= 57) || // 0-9
(code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) // a-z
);
}
}
/**
* Tokenise a Wikidot markup source string in one call.
*
* Shorthand for `new Lexer(source, options).tokenize()`.
*
* @param source - Raw Wikidot markup
* @param options - Optional lexer configuration
* @returns A flat array of tokens, ending with an `EOF` token
*
* @group Lexer
*/
export function tokenize(source: string, options?: LexerOptions): Token[] {
return new Lexer(source, options).tokenize();
}