forked from denoland/std
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_parse_sync.ts
More file actions
1471 lines (1319 loc) · 45.4 KB
/
Copy path_parse_sync.ts
File metadata and controls
1471 lines (1319 loc) · 45.4 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
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
/**
* Internal synchronous XML parser for non-streaming use.
*
* This module provides a high-performance single-pass parser that directly
* builds the XML tree without intermediate tokens or events. It is used by
* the `parse()` function for parsing complete XML strings.
*
* For streaming parsing, use {@linkcode parseXmlStream} from `parse_stream.ts`.
*
* @module
*/
import type {
ParseOptions,
XmlCDataNode,
XmlCommentNode,
XmlDeclarationEvent,
XmlDocument,
XmlElement,
XmlName,
XmlNode,
XmlTextNode,
} from "./types.ts";
import { XmlSyntaxError } from "./types.ts";
import { decodeEntities } from "./_entities.ts";
import {
isIllegalXmlLiteralChar,
isReservedPiTarget,
LINE_ENDING_REGEXP,
parseName,
validateNamespaceBinding,
validatePubidLiteral,
validateQName,
validateXmlDeclaration,
WHITESPACE_ONLY_REGEXP,
XML_NAMESPACE,
} from "./_common.ts";
import { isNameChar, isNameStartChar } from "./_name_chars.ts";
// Character codes for hot path optimization
const CC_LT = 60; // <
const CC_GT = 62; // >
const CC_SLASH = 47; // /
const CC_BANG = 33; // !
const CC_QUESTION = 63; // ?
const CC_EQ = 61; // =
const CC_DQUOTE = 34; // "
const CC_SQUOTE = 39; // '
const CC_LBRACKET = 91; // [
const CC_RBRACKET = 93; // ]
const CC_DASH = 45; // -
// Character codes for DTD parsing (cold path)
const CC_HASH = 35; // #
const CC_PERCENT = 37; // %
const CC_LPAREN = 40; // (
const CC_RPAREN = 41; // )
const CC_STAR = 42; // *
const CC_PLUS = 43; // +
const CC_COMMA = 44; // ,
const CC_SEMICOLON = 59; // ;
const CC_PIPE = 124; // |
/** Internal mutable type for building the tree. */
type MutableElement = {
type: "element";
name: XmlName;
attributes: Record<string, string>;
children: XmlNode[];
};
/**
* Synchronous single-pass XML parser.
*
* Directly builds the XML tree without intermediate tokens or events,
* providing significant performance improvements over the streaming parser
* for non-streaming use cases.
*
* Uses lazy position tracking: line/column are only computed when an error
* occurs, eliminating tracking overhead during successful parsing.
*
* @returns The parsed document.
* @throws {XmlSyntaxError} If the XML is malformed.
*/
export function parseSync(xml: string, options?: ParseOptions): XmlDocument {
const ignoreWhitespace = options?.ignoreWhitespace ?? false;
const ignoreComments = options?.ignoreComments ?? false;
const trackPosition = options?.trackPosition ?? true;
const disallowDoctype = options?.disallowDoctype ?? true;
const maxDepth = options?.maxDepth ?? Infinity;
const maxAttributes = options?.maxAttributes ?? Infinity;
const xml11 = options?.xmlVersion === "1.1";
// Normalize line endings (XML 1.0 §2.11 / XML 1.1 §2.11)
const version = xml11 ? "1.1" : "1.0";
const needsNormalization = xml11
? xml.includes("\r") || xml.includes("\x85") || xml.includes("\u2028")
: xml.includes("\r");
const input = needsNormalization
? xml.replace(LINE_ENDING_REGEXP[version], "\n")
: xml;
const len = input.length;
function isIllegalLiteralChar(code: number): boolean {
return isIllegalXmlLiteralChar(code, xml11);
}
// Parser state - only track position offset, not line/column
let pos = 0;
// Tree building state
const stack: MutableElement[] = [];
let root: MutableElement | undefined;
let declaration: XmlDeclarationEvent | undefined;
let rootClosed = false; // Track whether root element has been closed
// Namespace tracking (lazy initialization for performance)
// Only created when first namespace prefix is encountered
// Using object wrapper to avoid TypeScript control flow narrowing issues with error()
const ns: { bindings: Map<string, string> | null } = { bindings: null };
// Stack of namespace bindings per element scope (array of [prefix, previousUri] tuples)
// Used to restore bindings when element closes
const nsStack: Array<Array<[string, string | undefined]>> = [];
// Reusable empty array to avoid allocations for elements without namespace bindings
const EMPTY_NS_SCOPE: Array<[string, string | undefined]> = [];
/** Get or create namespace bindings map with xml prefix pre-bound */
function getNsBindings(): Map<string, string> {
if (!ns.bindings) {
ns.bindings = new Map([["xml", XML_NAMESPACE]]);
}
return ns.bindings;
}
// Note: We do NOT expand custom entities from DTD.
// We only support the 5 predefined XML entities: lt, gt, amp, apos, quot.
// External entities (SYSTEM/PUBLIC) are also not supported.
/**
* Compute line and column from offset on-demand (lazy position tracking).
* Only called when an error occurs, avoiding overhead during successful parsing.
*/
function computePosition(offset: number): {
line: number;
column: number;
offset: number;
} {
if (!trackPosition) {
return { line: 0, column: 0, offset: 0 };
}
let line = 1;
let lastNlPos = -1;
let searchStart = 0;
while (true) {
const nlPos = input.indexOf("\n", searchStart);
if (nlPos === -1 || nlPos >= offset) break;
line++;
lastNlPos = nlPos;
searchStart = nlPos + 1;
}
return {
line,
column: offset - lastNlPos,
offset,
};
}
function error(message: string): never {
throw new XmlSyntaxError(message, computePosition(pos));
}
function errorUnterminated(message: string): never {
pos = len;
error(message);
}
function skipWhitespace(): void {
while (pos < len) {
const code = input.charCodeAt(pos);
if (code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d) {
pos++;
} else {
break;
}
}
}
function isWhitespace(code: number): boolean {
return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
}
// ===========================================================================
// DTD PARSING
// ===========================================================================
/**
* Parse DTD internal subset with validation.
* Validates whitespace requirements per XML 1.0 spec.
*/
function parseDTDInternalSubset(): void {
while (pos < len) {
const code = input.charCodeAt(pos);
if (code === CC_RBRACKET) {
pos++;
return; // End of internal subset
}
if (isWhitespace(code)) {
// Batch-skip whitespace for better performance
skipWhitespace();
continue;
}
if (code === CC_LT) {
pos++;
if (pos >= len) {
error("Unexpected end of input in DTD");
}
const nextCode = input.charCodeAt(pos);
if (nextCode === CC_BANG) {
pos++;
parseDTDMarkupDeclaration();
} else if (nextCode === CC_QUESTION) {
pos++;
// Processing instruction in DTD
while (pos < len) {
if (
input.charCodeAt(pos) === CC_QUESTION &&
pos + 1 < len &&
input.charCodeAt(pos + 1) === CC_GT
) {
pos += 2;
break;
}
pos++;
}
} else {
error(`Unexpected character '${input[pos]}' after '<' in DTD`);
}
continue;
}
if (code === CC_LBRACKET) {
// Conditional sections are not allowed in internal subset
error(
"Conditional sections (INCLUDE/IGNORE) are not allowed in internal DTD subset",
);
}
// Parameter entity reference: %name;
// These are valid in internal subset and must be skipped
if (code === CC_PERCENT) {
pos++;
while (pos < len) {
const c = input.charCodeAt(pos);
if (c === CC_SEMICOLON) {
pos++;
break;
}
// Name characters
if (
(c >= 97 && c <= 122) || // a-z
(c >= 65 && c <= 90) || // A-Z
(c >= 48 && c <= 57) || // 0-9
c === 95 || c === 58 || c === 46 || c === 45 || // _ : . -
(c > 127 && isNameChar(c))
) {
pos++;
continue;
}
error("Invalid character in parameter entity reference");
}
continue;
}
error(`Unexpected character '${input[pos]}' in DTD internal subset`);
}
error("Unterminated DTD internal subset");
}
/**
* Parse a DTD markup declaration (<!ENTITY, <!ELEMENT, <!ATTLIST, <!NOTATION, or comment).
*/
function parseDTDMarkupDeclaration(): void {
if (pos >= len) {
error("Unexpected end of input in DTD declaration");
}
// Check for comment
if (input.charCodeAt(pos) === CC_DASH) {
pos++;
if (pos >= len || input.charCodeAt(pos) !== CC_DASH) {
error("Expected '--' to start comment in DTD");
}
pos++;
// Skip comment content
while (pos < len) {
if (
input.charCodeAt(pos) === CC_DASH &&
pos + 1 < len &&
input.charCodeAt(pos + 1) === CC_DASH
) {
pos += 2;
if (pos >= len || input.charCodeAt(pos) !== CC_GT) {
error("Cannot use '--' within XML comments (XML 1.0 §2.5)");
}
pos++;
return;
}
pos++;
}
error("Unterminated comment in DTD");
}
// Read declaration keyword (ENTITY, ELEMENT, ATTLIST, NOTATION)
const kwStart = pos;
while (
pos < len &&
((input.charCodeAt(pos) >= 65 && input.charCodeAt(pos) <= 90) || // A-Z
(input.charCodeAt(pos) >= 97 && input.charCodeAt(pos) <= 122)) // a-z
) {
pos++;
}
const keyword = input.slice(kwStart, pos);
if (
keyword !== "ENTITY" && keyword !== "ELEMENT" &&
keyword !== "ATTLIST" && keyword !== "NOTATION"
) {
error(`Unknown DTD declaration type '<!${keyword}'`);
}
// Must have whitespace after keyword
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error(`Missing whitespace after '<!${keyword}'`);
}
// For ENTITY declarations, extract the entity name and value
if (keyword === "ENTITY") {
parseEntityDeclaration();
} else {
// Parse the rest of the declaration with whitespace validation
parseDTDDeclarationContent();
}
}
/**
* Parse and validate an ENTITY declaration syntax.
*
* We do NOT expand custom entities from DTD
* We only support the 5 predefined XML entities (lt, gt, amp, apos, quot).
* External entities (SYSTEM/PUBLIC) are also not supported.
*
* This function validates syntax but does not store entity definitions.
*
* EntityDecl ::= GEDecl | PEDecl
* GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
* PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
* EntityDef ::= EntityValue | (ExternalID NDataDecl?)
* PEDef ::= EntityValue | ExternalID
* ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral
* NDataDecl ::= S 'NDATA' S Name
*/
function parseEntityDeclaration(): void {
// Skip whitespace after ENTITY keyword (already validated by caller)
skipWhitespace();
// Check for parameter entity marker '%'
const isParameterEntity = input.charCodeAt(pos) === CC_PERCENT;
if (isParameterEntity) {
pos++;
// Must have whitespace after '%'
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error("Missing whitespace after '%' in parameter entity declaration");
}
skipWhitespace();
}
// Read entity name
const name = readName();
if (name === "") {
error("Missing entity name in ENTITY declaration");
}
// Must have whitespace after name
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error("Missing whitespace after entity name");
}
skipWhitespace();
// Determine entity definition type
const code = input.charCodeAt(pos);
if (code === CC_DQUOTE || code === CC_SQUOTE) {
// EntityValue - internal entity
parseQuotedLiteral();
// Check for SGML-style comment (-- after quoted value)
skipWhitespace();
if (
pos + 1 < len &&
input.charCodeAt(pos) === CC_DASH &&
input.charCodeAt(pos + 1) === CC_DASH
) {
error(
"SGML-style comments (--) are not allowed in XML declarations",
);
}
} else {
// ExternalID - SYSTEM or PUBLIC
const kwStart = pos;
while (
pos < len &&
((input.charCodeAt(pos) >= 65 && input.charCodeAt(pos) <= 90) || // A-Z
(input.charCodeAt(pos) >= 97 && input.charCodeAt(pos) <= 122)) // a-z
) {
pos++;
}
const keyword = input.slice(kwStart, pos);
const keywordUpper = keyword.toUpperCase();
// Check for case-sensitivity - must be uppercase
if (keywordUpper === "SYSTEM" && keyword !== "SYSTEM") {
error(`'${keyword}' must be uppercase 'SYSTEM'`);
} else if (keywordUpper === "PUBLIC" && keyword !== "PUBLIC") {
error(`'${keyword}' must be uppercase 'PUBLIC'`);
}
if (keyword === "SYSTEM") {
// SYSTEM S SystemLiteral
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error("Missing whitespace after SYSTEM keyword");
}
skipWhitespace();
parseQuotedLiteral();
} else if (keyword === "PUBLIC") {
// PUBLIC S PubidLiteral S SystemLiteral
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error("Missing whitespace after PUBLIC keyword");
}
skipWhitespace();
parseQuotedLiteral(true); // PubidLiteral - validate characters
// Must have whitespace before SystemLiteral
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error(
"PUBLIC identifier requires both public ID and system ID literals",
);
}
skipWhitespace();
// SystemLiteral is required after PUBLIC
const nextCode = input.charCodeAt(pos);
if (nextCode !== CC_DQUOTE && nextCode !== CC_SQUOTE) {
error(
"PUBLIC identifier requires both public ID and system ID literals",
);
}
parseQuotedLiteral();
} else {
error(
`Expected SYSTEM, PUBLIC, or quoted string in ENTITY declaration, got '${
keyword || input[pos]
}'`,
);
}
// Check for NDATA declaration (only for general entities, not parameter entities)
skipWhitespace();
if (pos < len && input.charCodeAt(pos) !== CC_GT) {
// Check if we're about to see NDATA
if (
pos + 4 < len &&
input.startsWith("NDATA", pos)
) {
if (isParameterEntity) {
error("Parameter entities cannot have NDATA declarations");
}
pos += 5; // Skip NDATA
// Must have whitespace after NDATA
if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
error("Missing whitespace after NDATA keyword");
}
skipWhitespace();
// Read notation name
const notationName = readName();
if (notationName === "") {
error("Missing notation name after NDATA");
}
} else if (input.charCodeAt(pos) !== CC_GT) {
// If not NDATA and not '>', check for missing whitespace before NDATA
// This handles case like "foo.eps"NDATA (missing space)
const remaining = input.slice(pos, Math.min(pos + 10, len));
if (remaining.includes("NDATA")) {
error("Missing whitespace before NDATA keyword");
}
error(`Unexpected content '${input[pos]}' in ENTITY declaration`);
}
}
}
// Skip optional trailing whitespace and expect '>'
skipWhitespace();
if (pos >= len || input.charCodeAt(pos) !== CC_GT) {
error("Unterminated ENTITY declaration");
}
pos++;
}
/**
* Parse a quoted literal (single or double quoted).
* @param validatePubid If true, validate as PubidLiteral per XML 1.0 §2.3
*/
function parseQuotedLiteral(validatePubid = false): void {
const quote = input.charCodeAt(pos);
if (quote !== CC_DQUOTE && quote !== CC_SQUOTE) {
error("Expected quoted string");
}
const quoteChar = String.fromCharCode(quote);
pos++;
const valueStart = pos;
while (pos < len && input.charCodeAt(pos) !== quote) {
pos++;
}
if (pos >= len) {
error("Unterminated quoted string");
}
if (validatePubid) {
const pubidError = validatePubidLiteral(
input.slice(valueStart, pos),
quoteChar,
);
if (pubidError) error(pubidError);
}
pos++;
}
/**
* Parse DTD declaration content with whitespace validation.
* Validates that quoted strings and parenthesized groups have proper whitespace.
*/
function parseDTDDeclarationContent(): void {
let sawWhitespace = true; // Start true since we just saw whitespace after keyword
let parenDepth = 0;
while (pos < len) {
const code = input.charCodeAt(pos);
if (code === CC_GT && parenDepth === 0) {
pos++;
return; // End of declaration
}
if (isWhitespace(code)) {
sawWhitespace = true;
pos++;
continue;
}
if (code === CC_DQUOTE || code === CC_SQUOTE) {
// Quoted string - must have whitespace before (unless inside parens)
if (!sawWhitespace && parenDepth === 0) {
error("Missing whitespace before quoted string in DTD declaration");
}
const quote = code;
pos++;
while (pos < len && input.charCodeAt(pos) !== quote) {
pos++;
}
if (pos >= len) {
error("Unterminated string in DTD declaration");
}
pos++;
sawWhitespace = false;
continue;
}
// Opening paren - must have whitespace before FIRST paren only
// Nested parens like ((a|b)) are valid without whitespace between them
if (code === CC_LPAREN) {
if (!sawWhitespace && parenDepth === 0) {
error("Missing whitespace before '(' in DTD declaration");
}
parenDepth++;
sawWhitespace = false;
pos++;
continue;
}
if (code === CC_RPAREN) {
if (parenDepth === 0) {
error("Unexpected ')' in DTD declaration");
}
parenDepth--;
sawWhitespace = false;
pos++;
continue;
}
// Choice operator per §3.2.1: choice ::= '(' S? cp ( S? '|' S? cp )+ S? ')'
if (code === CC_PIPE) {
sawWhitespace = false;
pos++;
continue;
}
// Sequence operator per §3.2.1: seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
if (code === CC_COMMA) {
sawWhitespace = false;
pos++;
continue;
}
// #PCDATA, #IMPLIED, #REQUIRED, #FIXED keywords
if (code === CC_HASH) {
if (!sawWhitespace && parenDepth === 0) {
error("Missing whitespace before '#' in DTD declaration");
}
sawWhitespace = false;
pos++;
continue;
}
// Parameter entity reference
if (code === CC_PERCENT) {
sawWhitespace = false;
pos++;
continue;
}
// End of parameter entity reference
if (code === CC_SEMICOLON) {
sawWhitespace = false;
pos++;
continue;
}
// Name characters
if (
(code >= 97 && code <= 122) || // a-z
(code >= 65 && code <= 90) || // A-Z
(code >= 48 && code <= 57) || // 0-9
code === 95 || // _
code === 58 || // :
code === 46 || // .
code === 45 || // -
(code > 127 && isNameChar(code))
) {
sawWhitespace = false;
pos++;
continue;
}
if (code === CC_LBRACKET || code === CC_RBRACKET) {
sawWhitespace = false;
pos++;
continue;
}
// Content model operators per §3.2.1: cp ::= (Name | choice | seq) ('?' | '*' | '+')?
if (code === CC_STAR || code === CC_PLUS || code === CC_QUESTION) {
sawWhitespace = false;
pos++;
continue;
}
error(
`Unexpected character '${input[pos]}' in DTD declaration`,
);
}
error("Unterminated DTD declaration");
}
// ===========================================================================
// NAME AND VALUE READING
// ===========================================================================
function readName(): string {
const start = pos;
// First character must be NameStartChar
if (pos < len) {
const firstCode = input.charCodeAt(pos);
// Fast ASCII NameStartChar check
if (
(firstCode >= 97 && firstCode <= 122) || // a-z
(firstCode >= 65 && firstCode <= 90) || // A-Z
firstCode === 95 || // _
firstCode === 58 // :
) {
pos++;
} else if (firstCode > 127) {
// Non-ASCII: use codePointAt for proper surrogate pair handling
// Astral plane characters (U+10000+) are represented as surrogate pairs
const codePoint = input.codePointAt(pos)!;
if (isNameStartChar(codePoint)) {
// Advance by 1 for BMP chars, 2 for astral plane (surrogate pairs)
pos += codePoint > 0xFFFF ? 2 : 1;
} else {
// Not a valid name start character
return "";
}
} else {
// Not a valid name start character
return "";
}
}
// Remaining characters: NameChar
while (pos < len) {
const code = input.charCodeAt(pos);
// Fast ASCII NameChar check (inline for performance)
if (
(code >= 97 && code <= 122) || // a-z
(code >= 65 && code <= 90) || // A-Z
(code >= 48 && code <= 57) || // 0-9
code === 95 || // _
code === 58 || // :
code === 46 || // .
code === 45 // -
) {
pos++;
continue;
}
// Non-ASCII: use codePointAt for proper surrogate pair handling
if (code > 127) {
const codePoint = input.codePointAt(pos)!;
if (isNameChar(codePoint)) {
// Advance by 1 for BMP chars, 2 for astral plane (surrogate pairs)
pos += codePoint > 0xFFFF ? 2 : 1;
continue;
}
}
break;
}
return input.slice(start, pos);
}
function readQuotedValue(): string {
const quoteCode = input.charCodeAt(pos);
if (quoteCode !== CC_DQUOTE && quoteCode !== CC_SQUOTE) {
error("Expected quote to start attribute value");
}
const quoteChar = input[pos]!;
const start = pos + 1;
const closeIdx = input.indexOf(quoteChar, start);
if (closeIdx === -1) {
pos = len;
error("Unterminated attribute value");
}
const raw = input.slice(start, closeIdx);
// Validate: '<' not allowed in attribute values (XML 1.0 §3.1)
if (raw.includes("<")) {
// Find exact position for error reporting
pos = start + raw.indexOf("<");
error("Cannot use '<' in attribute value");
}
pos = closeIdx + 1;
// Normalize whitespace (§3.3.3) and decode entities
return decodeEntities(raw.replace(/[\t\n]/g, " "), xml11);
}
function readText(): string {
const start = pos;
const idx = input.indexOf("<", pos);
const end = idx === -1 ? len : idx;
for (let i = start; i < end; i++) {
const code = input.charCodeAt(i);
if (isIllegalLiteralChar(code)) {
pos = i;
error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
}`,
);
}
}
pos = end;
// Slice text once (reused for ]]> check and entity decoding)
const text = input.slice(start, end);
// XML 1.0 §2.4: "]]>" is not allowed in text content
if (text.includes("]]>")) {
pos = start + text.indexOf("]]>");
error("Cannot use ']]>' in text content (XML 1.0 §2.4)");
}
return decodeEntities(text, xml11);
}
function addNode(node: XmlTextNode | XmlCDataNode | XmlCommentNode): void {
if (stack.length > 0) {
stack[stack.length - 1]!.children.push(node);
}
}
// ===========================================================================
// MAIN PARSING LOOP
// ===========================================================================
while (pos < len) {
// Handle text content first (early continue)
if (input.charCodeAt(pos) !== CC_LT) {
const textStart = pos;
const text = readText();
const textEnd = pos;
// XML 1.0 §2.8: Prolog and epilog only allow Misc, where:
// Misc ::= Comment | PI | S
// S is LITERAL whitespace only, not character/entity references
const outsideRoot = !root || rootClosed;
if (outsideRoot) {
// Check raw text for any entity/character references
const rawText = input.slice(textStart, textEnd);
if (rawText.includes("&")) {
pos = textStart + rawText.indexOf("&");
error(
"Cannot use character/entity references in prolog/epilog (XML 1.0 §2.8)",
);
}
// Check for non-whitespace content
if (!WHITESPACE_ONLY_REGEXP.test(text)) {
pos = textStart;
if (!root) {
error(
"Cannot have content before the root element (XML 1.0 §2.8)",
);
} else {
error(
"Cannot have content after the root element (XML 1.0 §2.8)",
);
}
}
}
if (!(ignoreWhitespace && WHITESPACE_ONLY_REGEXP.test(text))) {
addNode({ type: "text", text });
}
continue;
}
pos++;
if (pos >= len) {
error("Unexpected end of input after '<'");
}
const code = input.charCodeAt(pos);
// End tag: </name>
if (code === CC_SLASH) {
pos++;
const name = readName();
if (name === "") {
error("Invalid character in end tag name");
}
skipWhitespace();
if (input.charCodeAt(pos) !== CC_GT) {
error("Expected '>' in end tag");
}
pos++;
const expected = stack.pop();
if (!expected) {
error(`Unexpected closing tag </${name}>`);
}
// Compare raw strings directly - equivalent to comparing prefix+local
// since XmlName.raw preserves the exact input to parseName()
if (expected.name.raw !== name) {
error(
`Mismatched closing tag: expected </${expected.name.raw}> but found </${name}>`,
);
}
// Restore namespace bindings from this element's scope
const elementBindings = nsStack.pop();
if (elementBindings && ns.bindings) {
const bindings = ns.bindings; // Capture for TypeScript narrowing
for (const [prefix, previousUri] of elementBindings) {
if (previousUri === undefined) {
bindings.delete(prefix);
} else {
bindings.set(prefix, previousUri);
}
}
}
// Track when root element closes
if (stack.length === 0 && root) {
rootClosed = true;
}
continue;
}
// Comment, CDATA, or DOCTYPE
if (code === CC_BANG) {
pos++;
// Comment: <!--...-->
if (
pos + 1 < len &&
input.charCodeAt(pos) === CC_DASH &&
input.charCodeAt(pos + 1) === CC_DASH
) {
pos += 2; // Skip '--'
const start = pos;
const endIdx = input.indexOf("-->", pos);
if (endIdx === -1) errorUnterminated("Unterminated comment");
const content = input.slice(start, endIdx);
// XML 1.0 §2.5: "--" is not permitted within comments
// Also, a single "-" cannot appear immediately before "-->"
// (grammar: Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->')
if (content.includes("--")) {
pos = start + content.indexOf("--");
error("Cannot use '--' within comments (XML 1.0 §2.5)");
}
// Check trailing dash before --> (e.g., "<!--->" or "<!-- comment --->")
if (
content.length > 0 &&
content.charCodeAt(content.length - 1) === CC_DASH
) {
pos = endIdx - 1; // Point to the trailing dash
error("Cannot use '-' immediately before '-->' (XML 1.0 §2.5)");
}
for (let i = start; i < endIdx; i++) {
const charCode = input.charCodeAt(i);
if (isIllegalLiteralChar(charCode)) {
pos = i;
error(
`Illegal XML character U+${
charCode.toString(16).toUpperCase().padStart(4, "0")
}`,
);
}
}
if (!ignoreComments) {
addNode({ type: "comment", text: content });
}
pos = endIdx + 3;
continue;
}
// CDATA: <![CDATA[...]]>
if (pos + 6 < len && input.startsWith("[CDATA[", pos)) {
// XML 1.0 §2.8: CDATA sections are only allowed within elements
if (!root) {
pos -= 2; // Point back to '<!'
error(
"Cannot have CDATA section before the root element (XML 1.0 §2.8)",
);
}
if (rootClosed) {
pos -= 2; // Point back to '<!'
error(
"Cannot have CDATA section after the root element (XML 1.0 §2.8)",
);
}
pos += 7; // Skip '[CDATA['
const start = pos;
const endIdx = input.indexOf("]]>", pos);
if (endIdx === -1) errorUnterminated("Unterminated CDATA section");
for (let i = start; i < endIdx; i++) {
const charCode = input.charCodeAt(i);
if (isIllegalLiteralChar(charCode)) {
pos = i;
error(
`Illegal XML character U+${
charCode.toString(16).toUpperCase().padStart(4, "0")
}`,
);
}
}
addNode({ type: "cdata", text: input.slice(start, endIdx) });
pos = endIdx + 3;
continue;
}
// DOCTYPE: <!DOCTYPE...>
if (pos + 6 < len && input.startsWith("DOCTYPE", pos)) {