-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnode.go
More file actions
859 lines (753 loc) · 24.3 KB
/
Copy pathnode.go
File metadata and controls
859 lines (753 loc) · 24.3 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
package helium
import (
"bytes"
"errors"
"fmt"
"slices"
"github.com/lestrrat-go/pdebug"
)
// AsNode performs a safe type assertion on a [Node], returning the
// concrete type T and true if the assertion succeeds, or the zero value
// of T and false otherwise.
//
// if elem, ok := helium.AsNode[*helium.Element](node); ok {
// // use elem
// }
func AsNode[T Node](n Node) (T, bool) {
if n == nil {
var zero T
return zero, false
}
if v, ok := n.(T); ok {
return v, true
}
var zero T
return zero, false
}
// Node is a read-only view of an XML document tree node (libxml2: xmlNode).
type Node interface {
baseDocNode() *docnode // prevents external implementation
Content() []byte
FirstChild() Node
LastChild() Node
Line() int
Name() string
NextSibling() Node
OwnerDocument() *Document
Parent() Node
PrevSibling() Node
Type() ElementType
}
// MutableNode extends Node with tree-mutation operations.
type MutableNode interface {
Node
AddChild(Node) error
AddSibling(Node) error
// AppendText appends text content to this node (libxml2: xmlNodeAddContent).
AppendText([]byte) error
Replace(...Node) error
SetLine(int)
SetNextSibling(Node)
SetOwnerDocument(doc *Document)
SetParent(Node)
SetPrevSibling(Node)
SetTreeDoc(doc *Document)
}
// docnode is responsible for handling the basic tree-ish operations
type docnode struct {
name string
etype ElementType
firstChild Node
lastChild Node
parent Node
next Node
prev Node
doc *Document
line int
entityBaseURI string // non-empty when this node originates from an external parsed entity
}
// node represents a node in a XML tree.
type node struct {
docnode
// private interface{}
content []byte
properties *Attribute
ns *Namespace
nsDefs []*Namespace
qname string // cached qualified name (prefix:local or just local)
}
type ElementType int
const (
ElementNode ElementType = iota + 1
AttributeNode
TextNode
CDATASectionNode
EntityRefNode
EntityNode
ProcessingInstructionNode
CommentNode
DocumentNode
DocumentTypeNode
DocumentFragNode
NotationNode
HTMLDocumentNode
DTDNode
ElementDeclNode
AttributeDeclNode
EntityDeclNode
NamespaceDeclNode
XIncludeStartNode
XIncludeEndNode
// NamespaceNode represents a namespace declaration (does not exist in libxml2).
NamespaceNode
)
const _ElementType_name = "ElementNodeAttributeNodeTextNodeCDATASectionNodeEntityRefNodeEntityNodeProcessingInstructionNodeCommentNodeDocumentNodeDocumentTypeNodeDocumentFragNodeNotationNodeHTMLDocumentNodeDTDNodeElementDeclNodeAttributeDeclNodeEntityDeclNodeNamespaceDeclNodeXIncludeStartNodeXIncludeEndNodeNamespaceNode"
var _ElementType_index = [...]uint16{0, 11, 24, 32, 48, 61, 71, 96, 107, 119, 135, 151, 163, 179, 186, 201, 218, 232, 249, 266, 281, 294}
func (i ElementType) String() string {
i -= 1
if i < 0 || i >= ElementType(len(_ElementType_index)-1) {
return fmt.Sprintf("ElementType(%d)", i+1)
}
return _ElementType_name[_ElementType_index[i]:_ElementType_index[i+1]]
}
// NamespaceContainer is an interface for nodes that carry namespace declarations.
type NamespaceContainer interface {
Namespaces() []*Namespace
}
// Namespacer is an interface for things that have a namespace
// prefix and URI.
type Namespacer interface {
Namespace() *Namespace
Namespaces() []*Namespace
Prefix() string
URI() string
LocalName() string
}
// because docnode contains links to other nodes, one tends to want to make
// methods for docnodes that cover the rest of the Node types. However,
// this cannot be done because the way Go does method reuse -- by delegation.
// For example, a method that changes the parent's point to the current node would
// be bad:
//
// func (n *docnode) MakeMeYourParent(cur Node) {
// cur.SetParent(n)
// }
//
// Wait, you just passed a pointer to the docnode, not the container node
// such as Element, Text, Comment, etc.
//
// So basically the deal is: if you need methods that may mutate the current
// node AND the operand node, DO NOT implement it for docnode. That includes
// things like AddSibling, or AddChild.
func (n *docnode) baseDocNode() *docnode {
return n
}
func setFirstChild(n MutableNode, cur Node) {
n.baseDocNode().firstChild = cur
}
func setLastChild(n MutableNode, cur Node) {
n.baseDocNode().lastChild = cur
}
func (n *docnode) SetOwnerDocument(doc *Document) {
n.doc = doc
}
func (n docnode) OwnerDocument() *Document {
return n.doc
}
func (n docnode) Parent() Node {
return n.parent
}
func (n docnode) Content() []byte {
b := bytes.Buffer{}
for e := n.firstChild; e != nil; e = e.NextSibling() {
_, _ = b.Write(e.Content())
}
return b.Bytes()
}
func appendText(n MutableNode, b []byte) error {
// Fast path: if last child is already a text node, append directly
// without allocating a new Text node.
if last := n.LastChild(); last != nil {
if t, ok := AsNode[*Text](last); ok {
return t.AppendText(b)
}
}
// Use slab allocator when the node belongs to a document.
if doc := n.OwnerDocument(); doc != nil {
t := doc.CreateText(b)
return n.AddChild(t)
}
t := newText(b)
return n.AddChild(t)
}
// NodeWalker visits nodes during tree traversal.
type NodeWalker interface {
Visit(Node) error
}
// NodeWalkerFunc is an adapter to allow use of ordinary functions as NodeWalker.
// Similar to http.HandlerFunc.
type NodeWalkerFunc func(Node) error
func (f NodeWalkerFunc) Visit(n Node) error {
return f(n)
}
// Walk performs a depth-first traversal of the node tree rooted at n,
// calling w.Visit for each node. There is no direct libxml2 equivalent; callers
// typically write manual tree traversal loops in C.
func Walk(n Node, w NodeWalker) error {
if n == nil {
return errors.New("nil node")
}
type walkFrame struct {
node Node
entered bool
activeChild Node
}
stack := []walkFrame{{node: n}}
for len(stack) > 0 {
top := &stack[len(stack)-1]
if !top.entered {
if err := w.Visit(top.node); err != nil {
return err
}
top.entered = true
top.activeChild = top.node.FirstChild()
continue
}
if top.activeChild == nil {
stack = stack[:len(stack)-1]
if len(stack) > 0 {
parent := &stack[len(stack)-1]
parent.activeChild = parent.activeChild.NextSibling()
}
continue
}
stack = append(stack, walkFrame{node: top.activeChild})
}
return nil
}
func (n docnode) LocalName() string {
return n.name
}
func (n docnode) Name() string {
return n.name
}
func (n docnode) Type() ElementType {
return n.etype
}
func (n docnode) Line() int {
return n.line
}
func (n *docnode) SetLine(line int) {
n.line = line
}
func (n docnode) FirstChild() Node {
return n.firstChild
}
func (n docnode) LastChild() Node {
return n.lastChild
}
// wouldCreateCycle reports whether installing cur under parent would create a
// cycle. That happens when cur is the parent itself or an ancestor of the
// parent: making it a descendant would put a node below itself. Walking
// parent's ancestor chain (inclusive of parent) and looking for cur covers
// both cases, including the self-insertion case when cur == parent.
func wouldCreateCycle(parent, cur Node) bool {
cdn := cur.baseDocNode()
for anc := parent; anc != nil; anc = anc.Parent() {
if anc.baseDocNode() == cdn {
return true
}
}
return false
}
// addChildPreflight runs the shared self/cycle guard and auto-unlink that every
// AddChild path must perform before relinking. It returns a non-nil error when
// the operation must be rejected; on success cur is detached from any previous
// position and safe to splice in. Leaf AddChild overrides (Text, Comment, ...)
// reuse this so their content-merge fast paths cannot bypass the guard: a node
// must not be merged into itself, and an already-linked incoming node must be
// unlinked from its old parent first.
func addChildPreflight(n MutableNode, cur Node) error {
cdn := cur.baseDocNode()
// Cycle guard: a node may not be inserted into itself, nor into one of
// its own descendants (which would make an ancestor a descendant of
// itself). This also catches the self-insertion case when n == cur.
if wouldCreateCycle(n, cur) {
return errors.New("cannot add a node as a child of itself or one of its descendants")
}
// Detach cur from its current parent/sibling chain before relinking, so a
// node that already lives elsewhere in a tree cannot remain in two places.
// unlinkNode works for every sealed node type, including non-MutableNode
// nodes such as NamespaceNodeWrapper, so the detach can never be silently
// skipped and leave stale old-parent links behind.
if cdn.parent != nil || cdn.prev != nil || cdn.next != nil {
unlinkNode(cur)
}
return nil
}
func addChild(n MutableNode, cur Node) error {
// Reject a nil or typed-nil operand BEFORE any baseDocNode() dereference so
// the call returns ErrNilNode instead of panicking and leaves the tree
// untouched.
if isNilNode(cur) {
return ErrNilNode
}
pdn := n.baseDocNode()
cdn := cur.baseDocNode()
if err := addChildPreflight(n, cur); err != nil {
return err
}
l := pdn.lastChild
if l == nil {
if pdebug.Enabled {
pdebug.Printf("LastChild is nil, setting firstChild and lastChild")
}
pdn.firstChild = cur
pdn.lastChild = cur
cdn.parent = n
return nil
}
ldn := l.baseDocNode()
curType := cdn.etype
// Fast path: when lastChild has no next sibling (the normal case),
// link directly without virtual dispatch through AddSibling.
if ldn.next == nil && (curType != TextNode || ldn.etype != TextNode) {
ldn.next = cur
cdn.prev = l
cdn.parent = n
pdn.lastChild = cur
return nil
}
// AddSibling handles setting the parent, and the
// lastChild pointer (also merges adjacent text nodes)
if err := l.(MutableNode).AddSibling(cur); err != nil { //nolint:forcetypeassert
return err
}
// If the last child was a text node, keep the old LastChild
if curType == TextNode && ldn.etype == TextNode {
pdn.lastChild = l
}
return nil
}
func (n docnode) NextSibling() Node {
if n.next == nil {
return nil
}
return n.next
}
func (n docnode) PrevSibling() Node {
return n.prev
}
// addSiblingPreflight runs the shared self/cycle guard and auto-unlink that
// every AddSibling path must perform before relinking. It returns a non-nil
// error when the operation must be rejected; on success cur is detached from
// any previous position and safe to splice in. Text.AddSibling reuses this so
// its text-merge fast path cannot bypass the guard.
func addSiblingPreflight(n MutableNode, cur Node) error {
cdn := cur.baseDocNode()
// Cycle guard: a sibling of n is installed under n's parent, so the same
// self/ancestor rule that protects addChild applies here against the
// effective insertion parent. This also rejects cur == n (a node cannot be
// its own sibling) since n is its parent's child.
if cur.baseDocNode() == n.baseDocNode() || wouldCreateCycle(n.Parent(), cur) {
return errors.New("cannot add a node as a sibling of itself or one of its descendants")
}
// Detach cur from its current parent/sibling chain before relinking, so a
// node that already lives elsewhere in a tree cannot remain in two places.
// unlinkNode works for every sealed node type, including non-MutableNode
// nodes such as NamespaceNodeWrapper, so the detach can never be silently
// skipped and leave stale old-parent links behind.
if cdn.parent != nil || cdn.prev != nil || cdn.next != nil {
unlinkNode(cur)
}
return nil
}
func addSibling(n MutableNode, cur Node) error {
// Reject a nil or typed-nil operand BEFORE any baseDocNode() dereference so
// the call returns ErrNilNode instead of panicking and leaves the tree
// untouched.
if isNilNode(cur) {
return ErrNilNode
}
cdn := cur.baseDocNode()
ndn := n.baseDocNode()
// Attribute-list semantics: attributes USUALLY live in the owning Element's
// properties linked list, NOT in the parent's child list. When n is such a
// property attribute, a new sibling must itself be an attribute and the splice
// must stay within the attribute chain, never touching firstChild/lastChild.
//
// But an *Attribute with an *Element parent is not guaranteed to live in that
// element's properties chain: public paths (elem.AddChild(attr), a generic
// Replace(attr)) can place it in the normal child list instead. Only use
// property-list logic when the anchor is genuinely reachable from
// ownerElem.properties; otherwise fall through to the generic child-list path.
if nAttr, ok := n.(*Attribute); ok {
if ownerElem, ok := ndn.parent.(*Element); ok && ownerElem.hasAttributeInProperties(nAttr) {
// Reject a non-attribute operand BEFORE the preflight unlink so a
// rejected call leaves cur's old tree position untouched.
if _, ok := cur.(*Attribute); !ok {
return errors.New("cannot add a non-attribute node as a sibling of an attribute")
}
if err := addSiblingPreflight(n, cur); err != nil {
return err
}
// Splice cur in only within the attribute sibling chain. Walk to the
// tail attribute and append. Never touch parent.firstChild/lastChild:
// attributes are not in the owner element's child list.
iter := Node(n)
for iter.NextSibling() != nil {
iter = iter.NextSibling()
}
idn := iter.baseDocNode()
idn.next = cur
cdn.prev = iter
cdn.parent = ownerElem
return nil
}
}
if err := addSiblingPreflight(n, cur); err != nil {
return err
}
iter := Node(n)
for iter != nil {
if iter.NextSibling() == nil {
idn := iter.baseDocNode()
idn.next = cur
cdn.prev = iter
parent := iter.Parent()
cdn.parent = parent
if parent != nil {
parent.baseDocNode().lastChild = cur
}
return nil
}
iter = iter.NextSibling()
}
return errors.New("cannot add sibling to nil node")
}
func (n *docnode) SetPrevSibling(cur Node) {
n.prev = cur
}
func (n *docnode) SetNextSibling(cur Node) {
n.next = cur
}
func (n *docnode) SetParent(cur Node) {
n.parent = cur
}
// UnlinkNode detaches a node from its parent and sibling chain.
// After unlinking, the node has no parent, prev, or next pointers.
func UnlinkNode(n MutableNode) {
if n == nil {
return
}
unlinkNode(n)
}
// unlinkNode detaches any [Node] from its parent and sibling chain, operating
// purely through baseDocNode() pointers. It works for every sealed node type,
// including those that are NOT MutableNode (e.g. NamespaceNodeWrapper), so any
// already-linked incoming node can be safely detached before relinking without
// a MutableNode type assertion that would silently skip or panic.
func unlinkNode(n Node) {
if n == nil {
return
}
ndn := n.baseDocNode()
// Attributes are USUALLY stored in the owning Element's properties linked
// list, NOT in the parent's child list. Detach via spliceOutAttribute so the
// Element.properties head is repaired and the attribute sibling chain is
// patched, without ever touching the parent's firstChild/lastChild. But an
// attribute with an *Element parent is not guaranteed to be a property:
// public paths (elem.AddChild(attr), a generic Replace(attr)) can place it in
// the normal child list instead. Confirm it is actually reachable from
// elem.properties before using property-list logic; otherwise fall through to
// the generic child-list unlink below.
if attr, ok := n.(*Attribute); ok {
if elem, ok := ndn.parent.(*Element); ok && elem.hasAttributeInProperties(attr) {
elem.spliceOutAttribute(attr)
return
}
}
if parent := ndn.parent; parent != nil {
pdn := parent.baseDocNode()
if pdn.firstChild != nil && pdn.firstChild.baseDocNode() == ndn {
pdn.firstChild = ndn.next
}
if pdn.lastChild != nil && pdn.lastChild.baseDocNode() == ndn {
pdn.lastChild = ndn.prev
}
}
if prev := ndn.prev; prev != nil {
prev.baseDocNode().next = ndn.next
}
if next := ndn.next; next != nil {
next.baseDocNode().prev = ndn.prev
}
ndn.parent = nil
ndn.prev = nil
ndn.next = nil
}
func replaceNode(n MutableNode, nodes ...Node) error {
if len(nodes) == 0 {
return nil
}
// Reject a nil or typed-nil replacement operand BEFORE any baseDocNode()
// dereference so the call returns ErrNilNode instead of panicking and
// leaves the tree untouched. Validate every operand, not just the first.
if slices.ContainsFunc(nodes, isNilNode) {
return ErrNilNode
}
cur := nodes[0]
cdn := cur.baseDocNode()
ndn := n.baseDocNode()
// Attribute-list semantics: attributes USUALLY live in the owning Element's
// properties linked list, NOT in the parent's child list. When n is such a
// property attribute, every replacement must itself be an attribute, and the
// Element.properties head must be repaired instead of firstChild/lastChild.
// Reject a mixed/non-attribute replacement before any unlink/splice so a
// rejected call leaves the tree untouched.
//
// But an *Attribute with an *Element parent is not guaranteed to live in that
// element's properties chain: public paths (elem.AddChild(attr), a generic
// Replace(attr)) can place it in the normal child list instead. Only use
// property-list logic when the attribute is genuinely reachable from
// ownerElem.properties; otherwise fall back to the generic child-list splice
// so firstChild/lastChild are repaired.
nAttr, nIsAttr := n.(*Attribute)
ownerElem, _ := ndn.parent.(*Element)
attrList := nIsAttr && ownerElem != nil && ownerElem.hasAttributeInProperties(nAttr)
if attrList {
for _, nn := range nodes {
if nn.baseDocNode() == ndn {
continue
}
if _, ok := nn.(*Attribute); !ok {
return errors.New("cannot replace an attribute with a non-attribute node")
}
}
}
// Duplicate-operand guard: the same node cannot appear twice among the
// replacements. Splicing it into two positions of the new sibling chain
// would corrupt its prev/next links (e.g. b.prev == b). Reject before any
// unlink/splice so a rejected call leaves the tree untouched.
seen := make(map[*docnode]struct{}, len(nodes))
for _, nn := range nodes {
dn := nn.baseDocNode()
if _, dup := seen[dn]; dup {
return errors.New("cannot replace a node with duplicate replacement operands")
}
seen[dn] = struct{}{}
}
// Cycle guard: each replacement node takes n's place under n's parent, so
// installing the parent (or any ancestor of it) below itself would create a
// cycle. Reject before any unlink/splice so a rejected call leaves the tree
// untouched. n itself is exempt: when n is among the replacements it stays
// live in place (handled below as replacedIsInserted).
parent := ndn.parent
for _, nn := range nodes {
if nn.baseDocNode() == ndn {
continue
}
if wouldCreateCycle(parent, nn) {
return errors.New("cannot replace a node with one of its own ancestors")
}
}
// A replacement node may already be linked into the tree (e.g. replacing a
// node with its own sibling). Detach every replacement node from its current
// position before splicing so it cannot remain in n's neighbor chain and
// create a self-loop. Skip n itself: when n is among the replacements it
// stays live in place (handled below as replacedIsInserted).
for _, nn := range nodes {
if nn.baseDocNode() == ndn {
continue
}
// unlinkNode handles every sealed node type, so a non-MutableNode
// replacement (e.g. NamespaceNodeWrapper) is detached safely instead of
// panicking on a MutableNode force-cast.
unlinkNode(nn)
}
// Capture n's following sibling AFTER detaching replacement nodes so it
// always points at a node that survives the splice.
afterN := ndn.next
// Patch first replacement into n's position
if ndn.prev != nil {
cdn.prev = ndn.prev
ndn.prev.baseDocNode().next = cur
}
if parent != nil {
if attrList {
// n is the owner Element's first attribute when properties points at
// it; move the head to the first replacement attribute. Never touch
// firstChild/lastChild: attributes are not in the child list. cur is
// guaranteed an *Attribute here: the attribute-only check above rejected
// any non-attribute replacement when n is an attribute.
if curAttr, ok := cur.(*Attribute); ok && ownerElem.properties == n {
ownerElem.properties = curAttr
}
}
if !attrList {
pdn := parent.baseDocNode()
if pdn.firstChild == n {
pdn.firstChild = cur
}
if pdn.lastChild == n {
pdn.lastChild = cur
}
}
cdn.parent = parent
}
// Determine the true last replacement node. Operate on baseDocNode() links
// directly rather than through MutableNode setters so a non-MutableNode
// replacement (e.g. NamespaceNodeWrapper) is spliced safely instead of
// panicking on a force-cast.
last := cur
ldn := cdn
for i := 1; i < len(nodes); i++ {
c := nodes[i]
cn := c.baseDocNode()
cn.parent = ldn.parent
cn.prev = last
ldn.next = c
last = c
ldn = cn
}
// Link last replacement to whatever followed n
ldn.next = afterN
if afterN != nil {
afterN.baseDocNode().prev = last
}
// Update parent's lastChild if n was the last child and we added more nodes.
// Skip for the attribute-list case: attributes are not in the child list, so
// the parent's lastChild must never be retargeted at an attribute.
if !attrList && afterN == nil && len(nodes) > 1 {
if parent := cdn.parent; parent != nil {
parent.baseDocNode().lastChild = last
}
}
// The replaced node is logically removed from the tree. Clear its own
// parent/sibling links so a stale handle cannot rewrite the spliced-in
// replacement (e.g. via a later UnlinkNode or Replace). Skip this when the
// replaced node is itself one of the inserted nodes (e.g. self-replacement),
// since it remains live in the tree and clearing its links would corrupt it.
replacedIsInserted := false
for _, nn := range nodes {
if nn.baseDocNode() == ndn {
replacedIsInserted = true
break
}
}
if !replacedIsInserted {
ndn.parent = nil
ndn.prev = nil
ndn.next = nil
}
return nil
}
func (n node) Namespace() *Namespace {
return n.ns
}
func (n node) Namespaces() []*Namespace {
return n.nsDefs
}
// RemoveNamespaceByPrefix removes a namespace declaration with the given prefix.
// Returns true if a declaration was removed.
func (n *node) RemoveNamespaceByPrefix(prefix string) bool {
for i, ns := range n.nsDefs {
if ns.Prefix() == prefix {
n.nsDefs = append(n.nsDefs[:i], n.nsDefs[i+1:]...)
return true
}
}
return false
}
// DeclareNamespace declares a namespace on this node without making it the
// node's active namespace (libxml2: xmlNewNs).
func (n *node) DeclareNamespace(prefix, uri string) error {
ns, err := n.doc.CreateNamespace(prefix, uri)
if err != nil {
return err
}
n.nsDefs = append(n.nsDefs, ns)
return nil
}
// SetActiveNamespace declares a namespace and sets it as this node's active
// namespace (libxml2: xmlSetNs).
func (n *node) SetActiveNamespace(prefix, uri string) error {
ns, err := n.doc.CreateNamespace(prefix, uri)
if err != nil {
return err
}
n.ns = ns
n.invalidateQName()
return nil
}
// SetNs sets the node's active namespace to an existing Namespace object
// without creating a new declaration.
func (n *node) SetNs(ns *Namespace) {
n.ns = ns
n.invalidateQName()
}
func (n node) Prefix() string {
if ns := n.ns; ns != nil {
return ns.Prefix()
}
return ""
}
func (n node) URI() string {
if ns := n.ns; ns != nil {
return ns.URI()
}
return ""
}
func (n *node) Name() string {
if n.qname != "" {
return n.qname
}
if ns := n.ns; ns != nil && ns.Prefix() != "" {
n.qname = ns.Prefix() + ":" + n.name
return n.qname
}
return n.name
}
func (n *node) invalidateQName() {
n.qname = ""
}
func setListDoc(n Node, doc *Document) {
if isNilNode(n) || n.Type() == NamespaceDeclNode {
return
}
for cur := n; cur != nil; cur = cur.NextSibling() {
if cur.OwnerDocument() == doc {
continue
}
// A non-MutableNode node (e.g. NamespaceNodeWrapper) cannot recurse
// through SetTreeDoc; set its document directly via baseDocNode(),
// mirroring unlinkNode's force-cast-free approach. MutableNode nodes
// still go through SetTreeDoc so their children are walked too.
if mn, ok := cur.(MutableNode); ok {
mn.SetTreeDoc(doc)
continue
}
cur.baseDocNode().doc = doc
}
}
func setTreeDoc(n MutableNode, doc *Document) {
if n == nil || n.Type() == NamespaceDeclNode {
return
}
if n.OwnerDocument() == doc {
return
}
if e, ok := AsNode[*Element](n); ok {
for prop := e.properties; prop != nil; prop = prop.NextAttribute() {
// if prop.atype == XML_ATTRIBUTE_ID; xmlRemoveID(tree->doc, prop)
prop.doc = doc
if child := prop.firstChild; child != nil {
setListDoc(child, doc)
}
}
}
if child := n.FirstChild(); child != nil {
setListDoc(child, doc)
}
n.SetOwnerDocument(doc)
}