-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathparser.go
More file actions
811 lines (741 loc) · 23.4 KB
/
Copy pathparser.go
File metadata and controls
811 lines (741 loc) · 23.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
package helium
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/lestrrat-go/helium/internal/iofs"
"github.com/lestrrat-go/helium/push"
"github.com/lestrrat-go/helium/sax"
"github.com/lestrrat-go/pdebug"
)
// pseudoRootName is the internal element name used for the synthetic root
// wrapping fragment content during entity/external-subset parsing.
const pseudoRootName = "pseudoroot"
type stopFuncKey struct{}
// StopParser tells the parser to stop at the next opportunity. Call this
// from any SAX callback to abort parsing early. The parse functions will
// return the partial document built so far with a nil error.
func StopParser(ctx context.Context) {
if ctx == nil {
return
}
if fn, _ := ctx.Value(stopFuncKey{}).(func()); fn != nil {
fn()
}
}
// parserConfig holds the mutable configuration behind a Parser.
type parserConfig struct {
sax sax.SAX2Handler
charBufferSize int
options parseOption
baseURI string
catalog CatalogResolver
fsys fs.FS
maxDepth int
maxExtDTDSize int
errorHandler ErrorHandler
}
// Parser holds configuration for XML parsing (libxml2: xmlParserCtxt).
// It uses clone-on-write semantics: each builder method returns
// a new Parser sharing the underlying config until mutation.
type Parser struct {
cfg *parserConfig
}
// NewParser creates a new Parser with default settings.
func NewParser() Parser {
return Parser{cfg: &parserConfig{
sax: NewTreeBuilder(),
fsys: iofs.PermissiveRoot{},
}}
}
func (p Parser) clone() Parser {
cp := *p.cfg
return Parser{cfg: &cp}
}
// --- Flag methods (each sets/clears the corresponding bit) ---
// RecoverOnError controls whether the parser attempts to recover from
// well-formedness errors and returns a partial document.
// libxml2: XML_PARSE_RECOVER
// Default: false
func (p Parser) RecoverOnError(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseRecover)
return p
}
p.cfg.options.Set(parseRecover)
return p
}
// SubstituteEntities controls whether entity references are replaced
// with their substitution text during parsing.
// libxml2: XML_PARSE_NOENT
// Default: false
func (p Parser) SubstituteEntities(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNoEnt)
return p
}
p.cfg.options.Set(parseNoEnt)
return p
}
// LoadExternalDTD controls whether the parser loads the external DTD subset.
// libxml2: XML_PARSE_DTDLOAD
// Default: false
func (p Parser) LoadExternalDTD(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseDTDLoad)
return p
}
p.cfg.options.Set(parseDTDLoad)
return p
}
// DefaultDTDAttributes controls whether the parser adds default attributes
// defined in the DTD. When set to true, also enables LoadExternalDTD.
// libxml2: XML_PARSE_DTDATTR
// Default: false
func (p Parser) DefaultDTDAttributes(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseDTDAttr)
return p
}
p.cfg.options.Set(parseDTDAttr)
p.cfg.options.Set(parseDTDLoad)
return p
}
// ValidateDTD controls whether the parser validates the document against
// its DTD after parsing. When set to true, also enables LoadExternalDTD.
// libxml2: XML_PARSE_DTDVALID
// Default: false
func (p Parser) ValidateDTD(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseDTDValid)
return p
}
p.cfg.options.Set(parseDTDValid)
p.cfg.options.Set(parseDTDLoad)
return p
}
// SuppressErrors controls whether error reports from the parser are
// suppressed. When true, the SAX error callback is not invoked.
// libxml2: XML_PARSE_NOERROR
// Default: false
func (p Parser) SuppressErrors(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNoError)
return p
}
p.cfg.options.Set(parseNoError)
return p
}
// SuppressWarnings controls whether warning reports from the parser are
// suppressed. When true, the SAX warning callback is not invoked.
// libxml2: XML_PARSE_NOWARNING
// Default: false
func (p Parser) SuppressWarnings(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNoWarning)
return p
}
p.cfg.options.Set(parseNoWarning)
return p
}
// PedanticErrors controls whether the parser reports pedantic warnings
// for minor specification violations.
// libxml2: XML_PARSE_PEDANTIC
// Default: false
func (p Parser) PedanticErrors(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parsePedantic)
return p
}
p.cfg.options.Set(parsePedantic)
return p
}
// StripBlanks controls whether whitespace-only text nodes are removed
// from the resulting DOM tree.
// libxml2: XML_PARSE_NOBLANKS
// Default: false
func (p Parser) StripBlanks(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNoBlanks)
return p
}
p.cfg.options.Set(parseNoBlanks)
return p
}
// ProcessXInclude controls whether XInclude substitution is performed
// during parsing.
// libxml2: XML_PARSE_XINCLUDE
// Default: false
func (p Parser) ProcessXInclude(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseXInclude)
return p
}
p.cfg.options.Set(parseXInclude)
return p
}
// AllowNetwork controls whether the parser is allowed to fetch resources
// over the network (e.g. external DTDs, entities). When set to false,
// all network access is forbidden.
// libxml2: XML_PARSE_NONET (note: semantics are inverted — libxml2 sets
// this flag to *forbid* network access, whereas AllowNetwork(true)
// *permits* it)
// Default: true (network access is allowed)
func (p Parser) AllowNetwork(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Set(parseNoNet)
return p
}
p.cfg.options.Clear(parseNoNet)
return p
}
// CleanNamespaces controls whether redundant namespace declarations are
// removed from the resulting DOM tree.
// libxml2: XML_PARSE_NSCLEAN
// Default: false
func (p Parser) CleanNamespaces(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNsClean)
return p
}
p.cfg.options.Set(parseNsClean)
return p
}
// MergeCDATA controls whether CDATA sections are merged into adjacent
// text nodes instead of being represented as separate CDATA nodes.
// libxml2: XML_PARSE_NOCDATA
// Default: false
func (p Parser) MergeCDATA(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNoCDATA)
return p
}
p.cfg.options.Set(parseNoCDATA)
return p
}
// XIncludeNodes controls whether XINCLUDE START/END marker nodes are
// generated in the DOM tree during XInclude processing.
// libxml2: XML_PARSE_NOXINCNODE (note: semantics are inverted — libxml2
// sets this flag to *suppress* marker nodes, whereas XIncludeNodes(false)
// suppresses them)
// Default: true (marker nodes are generated)
func (p Parser) XIncludeNodes(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Set(parseNoXIncNode)
return p
}
p.cfg.options.Clear(parseNoXIncNode)
return p
}
// CompactTextNodes controls whether the parser compacts small text nodes
// to reduce memory usage.
// libxml2: XML_PARSE_COMPACT
// Default: false
func (p Parser) CompactTextNodes(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseCompact)
return p
}
p.cfg.options.Set(parseCompact)
return p
}
// FixBaseURIs controls whether xml:base URIs are fixed up during
// XInclude processing. When set to false, xml:base attributes are
// not adjusted on included content.
// libxml2: XML_PARSE_NOBASEFIX (note: semantics are inverted — libxml2
// sets this flag to *disable* fixup, whereas FixBaseURIs(false)
// disables it)
// Default: true (xml:base URIs are fixed up)
func (p Parser) FixBaseURIs(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Set(parseNoBaseFix)
return p
}
p.cfg.options.Clear(parseNoBaseFix)
return p
}
// RelaxLimits controls whether hardcoded parser limits (name length,
// entity expansion) are relaxed. Use with caution — disabling limits
// may expose the parser to denial-of-service attacks.
// libxml2: XML_PARSE_HUGE
// Default: false
func (p Parser) RelaxLimits(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseHuge)
return p
}
p.cfg.options.Set(parseHuge)
return p
}
// IgnoreEncoding controls whether the parser ignores the encoding
// declaration inside the document and uses the transport-level encoding
// instead.
// libxml2: XML_PARSE_IGNORE_ENC
// Default: false
func (p Parser) IgnoreEncoding(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseIgnoreEnc)
return p
}
p.cfg.options.Set(parseIgnoreEnc)
return p
}
// BigLineNumbers controls whether large line numbers are stored in the
// text PSVI field, allowing line numbers above 65535.
// libxml2: XML_PARSE_BIG_LINES
// Default: false
func (p Parser) BigLineNumbers(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseBigLines)
return p
}
p.cfg.options.Set(parseBigLines)
return p
}
// BlockXXE controls whether loading of external entities and DTDs is
// blocked, preventing XML External Entity (XXE) attacks.
// libxml2: XML_PARSE_NOXXE
// Default: false
func (p Parser) BlockXXE(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseNoXXE)
return p
}
p.cfg.options.Set(parseNoXXE)
return p
}
// ReuseDict controls whether the parser reuses the context dictionary
// for interned strings. When set to false, a fresh dictionary is used.
// libxml2: XML_PARSE_NODICT (note: semantics are inverted — libxml2
// sets this flag to *disable* dictionary reuse, whereas ReuseDict(false)
// disables it)
// Default: true (dictionary is reused)
func (p Parser) ReuseDict(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Set(parseNoDict)
return p
}
p.cfg.options.Clear(parseNoDict)
return p
}
// SkipIDs controls whether ID attribute interning is skipped during
// parsing. When true, the parser does not build the ID table.
// libxml2: XML_PARSE_SKIP_IDS
// Default: false
func (p Parser) SkipIDs(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseSkipIDs)
return p
}
p.cfg.options.Set(parseSkipIDs)
return p
}
// LenientXMLDecl relaxes XML declaration parsing so that the version,
// encoding, and standalone pseudo-attributes may appear in any order.
// Per the XML spec (section 2.8) the order MUST be version, encoding,
// standalone, but some real-world producers emit them differently.
// This is a helium extension not present in libxml2.
// Default: false
func (p Parser) LenientXMLDecl(v bool) Parser {
p = p.clone()
if !v {
p.cfg.options.Clear(parseLenientXMLDecl)
return p
}
p.cfg.options.Set(parseLenientXMLDecl)
return p
}
// --- Non-flag configuration ---
// SAXHandler sets the SAX2 event handler for parsing.
func (p Parser) SAXHandler(s sax.SAX2Handler) Parser {
p = p.clone()
p.cfg.sax = s
return p
}
// BaseURI sets the document's base URI, used for resolving relative
// references such as external DTD system identifiers.
func (p Parser) BaseURI(uri string) Parser {
p = p.clone()
p.cfg.baseURI = uri
return p
}
// CharBufferSize sets the maximum number of bytes delivered in a single
// Characters or IgnorableWhitespace SAX callback. When size <= 0 (the
// default), all character data is delivered in one call. When size > 0,
// data longer than size bytes is split into chunks of at most size bytes,
// always respecting UTF-8 character boundaries.
func (p Parser) CharBufferSize(size int) Parser {
p = p.clone()
p.cfg.charBufferSize = size
return p
}
// MaxDepth sets the maximum element nesting depth allowed during parsing.
// When depth is greater than zero, the parser returns an error if the input
// document contains elements nested deeper than this limit. A value of zero
// (the default) means no limit is enforced.
func (p Parser) MaxDepth(depth int) Parser {
p = p.clone()
p.cfg.maxDepth = depth
return p
}
// MaxExternalDTDBytes sets the maximum number of bytes read from an external
// DTD subset (see [LoadExternalDTD], [ValidateDTD], [DefaultDTDAttributes]).
// The cap is enforced against the actual number of bytes read, guarding
// against hostile or pathological sources (e.g. /dev/zero) that could
// otherwise exhaust memory before any entity or parse limits apply. A value
// less than or equal to zero (the default) means [MaxExternalDTDSize] (10 MiB)
// is used.
func (p Parser) MaxExternalDTDBytes(n int) Parser {
p = p.clone()
p.cfg.maxExtDTDSize = n
return p
}
// Catalog sets an XML Catalog for resolving external entity identifiers
// (public/system IDs) during parsing. When set, the parser consults the
// catalog before attempting to load external DTDs and entities.
func (p Parser) Catalog(c CatalogResolver) Parser {
p = p.clone()
p.cfg.catalog = c
return p
}
// FS sets the [fs.FS] used to load external resources referenced by the
// document — external DTDs ([LoadExternalDTD]) and external entities
// resolved through [TreeBuilder.ResolveEntity]. A nil value restores the
// default, which opens any path supplied to the parser via [os.Open].
//
// Note: the names handed to the FS are built with [filepath.Join] against
// the document's base URI, so they may be absolute and may use
// OS-specific separators on Windows. FS implementations that enforce
// [fs.ValidPath] (notably [os.DirFS] and [testing/fstest.MapFS]) will
// reject those names. Sandboxing the loader behind such an FS requires
// path normalization that is not yet performed by this package; for now,
// supply an FS implementation that accepts OS-style names.
func (p Parser) FS(fsys fs.FS) Parser {
p = p.clone()
if fsys == nil {
fsys = iofs.PermissiveRoot{}
}
p.cfg.fsys = fsys
return p
}
// ErrorHandler sets the handler for validation errors produced during
// DTD validation ([ValidateDTD]). When set, individual errors are delivered
// to the handler as they occur. The returned error from Parse is
// [ErrDTDValidationFailed] on failure.
func (p Parser) ErrorHandler(h ErrorHandler) Parser {
p = p.clone()
p.cfg.errorHandler = h
return p
}
func (p Parser) closeHandler() {
if p.cfg != nil && p.cfg.errorHandler != nil {
if cl, ok := p.cfg.errorHandler.(io.Closer); ok {
_ = cl.Close()
}
}
}
// --- Terminal methods ---
// Parse parses XML from a byte slice and returns the resulting Document
// (libxml2: xmlParseDoc / xmlParseMemory).
//
// When [ValidateDTD] is enabled and the document fails validation, the
// returned error is [ErrDTDValidationFailed] and the document is still
// returned. Individual validation errors are delivered to the [ErrorHandler]
// configured via [Parser.ErrorHandler].
//
// Cancellation: if ctx is cancelled or its deadline is exceeded, Parse aborts
// and returns the context error (matched by [errors.Is] against
// [context.Canceled] / [context.DeadlineExceeded]) with a nil Document — never
// a partial tree. Because Parse reads from an in-memory byte slice there is no
// blocking read, so cancellation is always observed promptly: the parser checks
// the context between parse steps and between cursor refills.
func (p Parser) Parse(ctx context.Context, b []byte) (*Document, error) { //nolint:contextcheck
if ctx == nil {
ctx = context.Background()
}
if pdebug.Enabled {
g := pdebug.IPrintf("=== START Parser.Parse ===")
defer g.IRelease("=== END Parser.Parse ===")
}
pctx := &parserCtx{rawInput: b, baseURI: p.cfg.baseURI}
if err := pctx.init(p.cfg, bytes.NewReader(b)); err != nil {
return nil, err
}
defer func() {
if err := pctx.release(); err != nil {
// Log error but don't override the main return error
if pdebug.Enabled {
pdebug.Printf("ctx.release() failed: %s", err)
}
}
}()
if err := pctx.parseDocument(ctx); err != nil {
if errors.Is(err, errParserStopped) {
return pctx.doc, nil
}
// A cancelled or timed-out parse is not a recoverable parse error:
// return the context error with a nil document, never a partial tree.
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if p.cfg.options.IsSet(parseRecover) {
// ParseRecover: return the partial document along with the error
return pctx.doc, err
}
return nil, err
}
// DTD validation: run post-parse document validation when requested.
if p.cfg.options.IsSet(parseDTDValid) && pctx.doc != nil {
handler := p.cfg.errorHandler
if handler == nil {
handler = NilErrorHandler{}
}
err := validateDocument(ctx, pctx.doc, handler)
p.closeHandler()
if err != nil {
return pctx.doc, err
}
}
return pctx.doc, nil
}
// ParseReader parses XML from an io.Reader and returns the resulting Document
// (libxml2: xmlReadIO).
// This is identical to [Parse] but reads from a stream instead of a byte slice.
// EBCDIC encoding detection is not supported when parsing from a reader.
// See [Parse] for DTD validation error handling.
//
// Cancellation: context cancellation and deadlines are observed BETWEEN read
// operations and parse steps. The parser checks ctx before each cursor refill
// (read from r) and between parse steps, so a cancelled or timed-out context is
// honored as soon as the parser regains control, returning the context error
// (matched by [errors.Is] against [context.Canceled] /
// [context.DeadlineExceeded]) with a nil Document.
//
// A reader already blocked inside its own Read call cannot be interrupted
// generically: Go provides no way to unblock a Read in progress. Such a read is
// only interruptible if r itself honors the context or a deadline — for example
// a reader that sets a read deadline when ctx.Done() fires, or that returns from
// Read with an error on cancellation. If r can block indefinitely (e.g. a slow
// or never-returning network reader), wrap it so its Read observes ctx, or pass
// the already-read bytes to [Parse] instead.
func (p Parser) ParseReader(ctx context.Context, r io.Reader) (*Document, error) { //nolint:contextcheck
if ctx == nil {
ctx = context.Background()
}
if pdebug.Enabled {
g := pdebug.IPrintf("=== START Parser.ParseReader ===")
defer g.IRelease("=== END Parser.ParseReader ===")
}
pctx := &parserCtx{baseURI: p.cfg.baseURI}
if err := pctx.init(p.cfg, r); err != nil {
return nil, err
}
defer func() {
if err := pctx.release(); err != nil {
if pdebug.Enabled {
pdebug.Printf("ctx.release() failed: %s", err)
}
}
}()
if err := pctx.parseDocument(ctx); err != nil {
if errors.Is(err, errParserStopped) {
return pctx.doc, nil
}
// A cancelled or timed-out parse is not a recoverable parse error:
// return the context error with a nil document, never a partial tree.
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if p.cfg.options.IsSet(parseRecover) {
return pctx.doc, err
}
return nil, err
}
if p.cfg.options.IsSet(parseDTDValid) && pctx.doc != nil {
handler := p.cfg.errorHandler
if handler == nil {
handler = NilErrorHandler{}
}
err := validateDocument(ctx, pctx.doc, handler)
p.closeHandler()
if err != nil {
return pctx.doc, err
}
}
return pctx.doc, nil
}
// ParseFile reads and parses an XML file. The document's URL is set to the
// absolute path of the file, and the file path is used as the base URI for
// relative URI resolution during parsing.
func (p Parser) ParseFile(ctx context.Context, path string) (*Document, error) {
data, err := os.ReadFile(path) //nolint:gosec // path is caller-supplied
if err != nil {
return nil, fmt.Errorf("helium: failed to read %q: %w", path, err)
}
abs, err := filepath.Abs(path)
if err != nil {
return nil, fmt.Errorf("helium: failed to resolve path %q: %w", path, err)
}
doc, err := p.BaseURI(abs).Parse(ctx, data)
if err != nil {
return nil, err
}
doc.SetURL(abs)
return doc, nil
}
// ParseInNodeContext parses an XML fragment in the context of an existing
// node. The node provides in-scope namespace declarations and document-level
// DTD/entity context. Returns the first node of the parsed fragment list
// (siblings linked via NextSibling). The returned nodes are not attached
// to any parent.
func (p Parser) ParseInNodeContext(ctx context.Context, node Node, data []byte) (Node, error) { //nolint:contextcheck
if ctx == nil {
ctx = context.Background()
}
if pdebug.Enabled {
g := pdebug.IPrintf("=== START Parser.ParseInNodeContext ===")
defer g.IRelease("=== END Parser.ParseInNodeContext ===")
}
if node == nil {
return nil, errors.New("node must not be nil")
}
// Walk up to the nearest element or document node.
var ctxElem *Element
var doc *Document
cur := node
for cur != nil {
switch v := cur.(type) {
case *Document:
doc = v
goto found
case *Element:
ctxElem = v
doc = v.doc
goto found
}
cur = cur.Parent()
}
return nil, errors.New("no element or document context found")
found:
if doc == nil {
doc = NewDocument("1.0", "", StandaloneImplicitNo)
}
newctx := &parserCtx{}
if err := newctx.init(p.cfg, bytes.NewReader(data)); err != nil {
return nil, err
}
defer func() {
if err := newctx.release(); err != nil {
if pdebug.Enabled {
pdebug.Printf("newctx.release() failed: %s", err)
}
}
}()
// Save the document's children and restore them afterward.
fc := doc.FirstChild()
lc := doc.LastChild()
setFirstChild(doc, nil)
setLastChild(doc, nil)
defer func() {
setFirstChild(doc, fc)
setLastChild(doc, lc)
}()
newctx.doc = doc
// Push in-scope namespaces from the context element into the parser's
// namespace stack so that the fragment can resolve prefixed names.
if ctxElem != nil {
nsList := collectInScopeNamespaces(ctxElem)
for _, ns := range nsList {
newctx.pushNS(ns.Prefix(), ns.URI())
}
}
// Create pseudoroot element, push to node stack.
newRoot := doc.CreateElement(pseudoRootName)
newctx.pushNodeEntry(nodeEntry{local: pseudoRootName, qname: pseudoRootName})
newctx.elem = newRoot
if err := doc.AddChild(newRoot); err != nil {
return nil, err
}
if err := newctx.switchEncoding(); err != nil {
return nil, err
}
innerCtx := withParserCtx(ctx, newctx)
innerCtx = sax.WithDocumentLocator(innerCtx, newctx)
innerCtx = context.WithValue(innerCtx, stopFuncKey{}, newctx.stop)
if err := newctx.parseContent(innerCtx); err != nil {
// errParserStopped is a benign stop (helium.StopParser); any other
// error, including context cancellation, propagates with a nil result.
if !errors.Is(err, errParserStopped) {
return nil, err
}
}
// Extract children from pseudoroot.
if child := doc.FirstChild(); child != nil {
if grandchild := child.FirstChild(); grandchild != nil {
for e := grandchild; e != nil; e = e.NextSibling() {
e.(MutableNode).SetTreeDoc(doc) //nolint:forcetypeassert
e.baseDocNode().parent = nil
}
return grandchild, nil
}
}
return nil, nil //nolint:nilnil
}
// collectInScopeNamespaces walks up from elem collecting all namespace
// declarations. Inner declarations shadow outer ones (closer to elem wins).
func collectInScopeNamespaces(elem *Element) []*Namespace {
seen := map[string]bool{}
var result []*Namespace
var cur Node = elem
for cur != nil {
if e, ok := cur.(*Element); ok {
for _, ns := range e.Namespaces() {
if !seen[ns.Prefix()] {
seen[ns.Prefix()] = true
result = append(result, ns)
}
}
}
cur = cur.Parent()
}
return result
}
// PushParser provides an incremental XML parsing interface
// (libxml2: xmlParserCtxt in push mode).
// Data is pushed via Push or Write, and the parser processes tokens as
// they become available in a background goroutine. Call [PushParser.Close]
// to signal end-of-input and retrieve the parsed Document.
type PushParser = push.Parser[*Document]
// NewPushParser creates a PushParser using the given Parser's configuration.
// The parser runs in a background goroutine, reading from the internal
// stream as data is pushed.
func (p Parser) NewPushParser(ctx context.Context) *PushParser {
return push.New[*Document](ctx, p)
}