Debian Codegraph @

path.go

raw
1 // Copyright 2015-2019 Brett Vickers.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package etree
6
7 import (
8 "iter"
9 "strconv"
10 "strings"
11 )
12
13 /*
14 A Path is a string that represents a search path through an etree starting
15 from the document root or an arbitrary element. Paths are used with the
16 Element object's Find* methods to locate and return desired elements.
17
18 A Path consists of a series of slash-separated "selectors", each of which may
19 be modified by one or more bracket-enclosed "filters". Selectors are used to
20 traverse the etree from element to element, while filters are used to narrow
21 the list of candidate elements at each node.
22
23 Although etree Path strings are structurally and behaviorally similar to XPath
24 strings (https://www.w3.org/TR/1999/REC-xpath-19991116/), they have a more
25 limited set of selectors and filtering options.
26
27 The following selectors are supported by etree paths:
28
29 . Select the current element.
30 .. Select the parent of the current element.
31 * Select all child elements of the current element.
32 / Select the root element when used at the start of a path.
33 // Select all descendants of the current element.
34 tag Select all child elements with a name matching the tag.
35
36 The following basic filters are supported:
37
38 [@attrib] Keep elements with an attribute named attrib.
39 [@attrib='val'] Keep elements with an attribute named attrib and value matching val.
40 [tag] Keep elements with a child element named tag.
41 [tag='val'] Keep elements with a child element named tag and text matching val.
42 [n] Keep the n-th element, where n is a numeric index starting from 1.
43
44 The following function-based filters are supported:
45
46 [text()] Keep elements with non-empty text.
47 [text()='val'] Keep elements whose text matches val.
48 [local-name()='val'] Keep elements whose un-prefixed tag matches val.
49 [name()='val'] Keep elements whose full tag exactly matches val.
50 [namespace-prefix()] Keep elements with non-empty namespace prefixes.
51 [namespace-prefix()='val'] Keep elements whose namespace prefix matches val.
52 [namespace-uri()] Keep elements with non-empty namespace URIs.
53 [namespace-uri()='val'] Keep elements whose namespace URI matches val.
54
55 Below are some examples of etree path strings.
56
57 Select the bookstore child element of the root element:
58
59 /bookstore
60
61 Beginning from the root element, select the title elements of all descendant
62 book elements having a 'category' attribute of 'WEB':
63
64 //book[@category='WEB']/title
65
66 Beginning from the current element, select the first descendant book element
67 with a title child element containing the text 'Great Expectations':
68
69 .//book[title='Great Expectations'][1]
70
71 Beginning from the current element, select all child elements of book elements
72 with an attribute 'language' set to 'english':
73
74 ./book/*[@language='english']
75
76 Beginning from the current element, select all child elements of book elements
77 containing the text 'special':
78
79 ./book/*[text()='special']
80
81 Beginning from the current element, select all descendant book elements whose
82 title child element has a 'language' attribute of 'french':
83
84 .//book/title[@language='french']/..
85
86 Beginning from the current element, select all descendant book elements
87 belonging to the http://www.w3.org/TR/html4/ namespace:
88
89 .//book[namespace-uri()='http://www.w3.org/TR/html4/']
90 */
91 type Path struct {
92 segments []segment
93 }
94
95 // ErrPath is returned by path functions when an invalid etree path is provided.
96 type ErrPath string
97
98 // Error returns the string describing a path error.
99 func (err ErrPath) Error() string {
100 return "etree: " + string(err)
101 }
102
103 // CompilePath creates an optimized version of an XPath-like string that
104 // can be used to query elements in an element tree.
105 func CompilePath(path string) (Path, error) {
106 var comp compiler
107 segments := comp.parsePath(path)
108 if comp.err != ErrPath("") {
109 return Path{nil}, comp.err
110 }
111 return Path{segments}, nil
112 }
113
114 // MustCompilePath creates an optimized version of an XPath-like string that
115 // can be used to query elements in an element tree. Panics if an error
116 // occurs. Use this function to create Paths when you know the path is
117 // valid (i.e., if it's hard-coded).
118 func MustCompilePath(path string) Path {
119 p, err := CompilePath(path)
120 if err != nil {
121 panic(err)
122 }
123 return p
124 }
125
126 // traverse follows the path from the element e, yielding elements that match
127 // the path's selectors and filters using iterators.
128 func (p Path) traverse(e *Element) iter.Seq[*Element] {
129 pather := newPather()
130 return func(yield func(*Element) bool) {
131 pather.queue.add(node{e, p.segments})
132 for pather.queue.len() > 0 {
133 if cont := pather.eval(pather.queue.remove(), yield); !cont {
134 return
135 }
136 }
137 }
138 }
139
140 // A segment is a portion of a path between "/" characters.
141 // It contains one selector and zero or more [filters].
142 type segment struct {
143 sel selector
144 filters []filter
145 }
146
147 func (seg *segment) apply(e *Element, p *pather) {
148 seg.sel.apply(e, p)
149 for _, f := range seg.filters {
150 f.apply(p)
151 }
152 }
153
154 // A selector selects XML elements for consideration by the
155 // path traversal.
156 type selector interface {
157 apply(e *Element, p *pather)
158 }
159
160 // A filter pares down a list of candidate XML elements based
161 // on a path filter in [brackets].
162 type filter interface {
163 apply(p *pather)
164 }
165
166 // A node represents an element and the remaining path segments that
167 // should be applied against it by the pather.
168 type node struct {
169 e *Element
170 segments []segment
171 }
172
173 // A pather is helper object that traverses an element tree using
174 // a Path object. It collects and deduplicates all elements matching
175 // the path query.
176 type pather struct {
177 queue queue[node]
178 results []*Element
179 inResults map[*Element]bool
180 candidates []*Element
181 scratch []*Element // used by filters
182 }
183
184 // newPather creates a new pather instance.
185 func newPather() *pather {
186 return &pather{
187 results: make([]*Element, 0),
188 inResults: make(map[*Element]bool),
189 candidates: make([]*Element, 0),
190 scratch: make([]*Element, 0),
191 }
192 }
193
194 // eval evaluates the current path node by applying the remaining path's
195 // selector rules against the node's element, yielding results via iterator.
196 // Returns false if early termination is requested.
197 func (p *pather) eval(n node, yield func(*Element) bool) bool {
198 p.candidates = p.candidates[:0]
199 seg, remain := n.segments[0], n.segments[1:]
200 seg.apply(n.e, p)
201
202 if len(remain) == 0 {
203 for _, c := range p.candidates {
204 if in := p.inResults[c]; !in {
205 p.inResults[c] = true
206 if !yield(c) {
207 return false
208 }
209 }
210 }
211 } else {
212 for _, c := range p.candidates {
213 p.queue.add(node{c, remain})
214 }
215 }
216 return true
217 }
218
219 // A compiler generates a compiled path from a path string.
220 type compiler struct {
221 err ErrPath
222 }
223
224 // parsePath parses an XPath-like string describing a path
225 // through an element tree and returns a slice of segment
226 // descriptors.
227 func (c *compiler) parsePath(path string) []segment {
228 // If path ends with //, fix it
229 if strings.HasSuffix(path, "//") {
230 path += "*"
231 }
232
233 var segments []segment
234
235 // Check for an absolute path
236 if strings.HasPrefix(path, "/") {
237 segments = append(segments, segment{new(selectRoot), []filter{}})
238 path = path[1:]
239 }
240
241 // Split path into segments
242 for _, s := range splitPath(path) {
243 segments = append(segments, c.parseSegment(s))
244 if c.err != ErrPath("") {
245 break
246 }
247 }
248 return segments
249 }
250
251 func splitPath(path string) []string {
252 var pieces []string
253 start := 0
254 inquote := false
255 var quote byte
256 for i := 0; i+1 <= len(path); i++ {
257 if !inquote {
258 if path[i] == '\'' || path[i] == '"' {
259 inquote, quote = true, path[i]
260 } else if path[i] == '/' {
261 pieces = append(pieces, path[start:i])
262 start = i + 1
263 }
264 } else if path[i] == quote {
265 inquote = false
266 }
267 }
268 return append(pieces, path[start:])
269 }
270
271 // parseSegment parses a path segment between / characters.
272 func (c *compiler) parseSegment(path string) segment {
273 pieces := strings.Split(path, "[")
274 seg := segment{
275 sel: c.parseSelector(pieces[0]),
276 filters: []filter{},
277 }
278 for i := 1; i < len(pieces); i++ {
279 fpath := pieces[i]
280 if len(fpath) == 0 || fpath[len(fpath)-1] != ']' {
281 c.err = ErrPath("path has invalid filter [brackets].")
282 break
283 }
284 filter := c.parseFilter(fpath[:len(fpath)-1])
285 if c.err != ErrPath("") {
286 break
287 }
288 seg.filters = append(seg.filters, filter)
289 }
290 return seg
291 }
292
293 // parseSelector parses a selector at the start of a path segment.
294 func (c *compiler) parseSelector(path string) selector {
295 switch path {
296 case ".":
297 return new(selectSelf)
298 case "..":
299 return new(selectParent)
300 case "*":
301 return new(selectChildren)
302 case "":
303 return new(selectDescendants)
304 default:
305 return newSelectChildrenByTag(path)
306 }
307 }
308
309 var fnTable = map[string]func(e *Element) string{
310 "local-name": (*Element).name,
311 "name": (*Element).FullTag,
312 "namespace-prefix": (*Element).namespacePrefix,
313 "namespace-uri": (*Element).NamespaceURI,
314 "text": (*Element).Text,
315 }
316
317 // parseFilter parses a path filter contained within [brackets].
318 func (c *compiler) parseFilter(path string) filter {
319 if len(path) == 0 {
320 c.err = ErrPath("path contains an empty filter expression.")
321 return nil
322 }
323
324 // Filter contains [@attr='val'], [@attr="val"], [fn()='val'],
325 // [fn()="val"], [tag='val'] or [tag="val"]?
326 eqindex := strings.IndexByte(path, '=')
327 if eqindex == 0 {
328 c.err = ErrPath("path contains a filter expression with no key.")
329 return nil
330 }
331 if eqindex > 0 && eqindex+1 < len(path) {
332 quote := path[eqindex+1]
333 if quote == '\'' || quote == '"' {
334 rindex := nextIndex(path, quote, eqindex+2)
335 if rindex != len(path)-1 {
336 c.err = ErrPath("path has mismatched filter quotes.")
337 return nil
338 }
339
340 key := path[:eqindex]
341 value := path[eqindex+2 : rindex]
342
343 switch {
344 case key[0] == '@':
345 if len(key) == 1 {
346 c.err = ErrPath("path contains a filter expression with no key.")
347 return nil
348 }
349 return newFilterAttrVal(key[1:], value)
350 case strings.HasSuffix(key, "()"):
351 name := key[:len(key)-2]
352 if fn, ok := fnTable[name]; ok {
353 return newFilterFuncVal(fn, value)
354 }
355 c.err = ErrPath("path has unknown function " + name)
356 return nil
357 default:
358 return newFilterChildText(key, value)
359 }
360 }
361 }
362
363 // Filter contains [@attr], [N], [tag] or [fn()]
364 switch {
365 case path[0] == '@':
366 return newFilterAttr(path[1:])
367 case strings.HasSuffix(path, "()"):
368 name := path[:len(path)-2]
369 if fn, ok := fnTable[name]; ok {
370 return newFilterFunc(fn)
371 }
372 c.err = ErrPath("path has unknown function " + name)
373 return nil
374 case isInteger(path):
375 pos, _ := strconv.Atoi(path)
376 switch {
377 case pos > 0:
378 return newFilterPos(pos - 1)
379 default:
380 return newFilterPos(pos)
381 }
382 default:
383 return newFilterChild(path)
384 }
385 }
386
387 // selectSelf selects the current element into the candidate list.
388 type selectSelf struct{}
389
390 func (s *selectSelf) apply(e *Element, p *pather) {
391 p.candidates = append(p.candidates, e)
392 }
393
394 // selectRoot selects the element's root node.
395 type selectRoot struct{}
396
397 func (s *selectRoot) apply(e *Element, p *pather) {
398 root := e
399 for root.parent != nil {
400 root = root.parent
401 }
402 p.candidates = append(p.candidates, root)
403 }
404
405 // selectParent selects the element's parent into the candidate list.
406 type selectParent struct{}
407
408 func (s *selectParent) apply(e *Element, p *pather) {
409 if e.parent != nil {
410 p.candidates = append(p.candidates, e.parent)
411 }
412 }
413
414 // selectChildren selects the element's child elements into the
415 // candidate list.
416 type selectChildren struct{}
417
418 func (s *selectChildren) apply(e *Element, p *pather) {
419 for _, c := range e.Child {
420 if c, ok := c.(*Element); ok {
421 p.candidates = append(p.candidates, c)
422 }
423 }
424 }
425
426 // selectDescendants selects all descendant child elements
427 // of the element into the candidate list.
428 type selectDescendants struct{}
429
430 func (s *selectDescendants) apply(e *Element, p *pather) {
431 var queue queue[*Element]
432 for queue.add(e); queue.len() > 0; {
433 e := queue.remove()
434 p.candidates = append(p.candidates, e)
435 for _, c := range e.Child {
436 if c, ok := c.(*Element); ok {
437 queue.add(c)
438 }
439 }
440 }
441 }
442
443 // selectChildrenByTag selects into the candidate list all child
444 // elements of the element having the specified tag.
445 type selectChildrenByTag struct {
446 space, tag string
447 }
448
449 func newSelectChildrenByTag(path string) *selectChildrenByTag {
450 s, l := spaceDecompose(path)
451 return &selectChildrenByTag{s, l}
452 }
453
454 func (s *selectChildrenByTag) apply(e *Element, p *pather) {
455 for _, c := range e.Child {
456 if c, ok := c.(*Element); ok && spaceMatch(s.space, c.Space) && s.tag == c.Tag {
457 p.candidates = append(p.candidates, c)
458 }
459 }
460 }
461
462 // filterPos filters the candidate list, keeping only the
463 // candidate at the specified index.
464 type filterPos struct {
465 index int
466 }
467
468 func newFilterPos(pos int) *filterPos {
469 return &filterPos{pos}
470 }
471
472 func (f *filterPos) apply(p *pather) {
473 if f.index >= 0 {
474 if f.index < len(p.candidates) {
475 p.scratch = append(p.scratch, p.candidates[f.index])
476 }
477 } else {
478 if i := len(p.candidates) + f.index; i >= 0 {
479 p.scratch = append(p.scratch, p.candidates[i])
480 }
481 }
482 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
483 }
484
485 // filterAttr filters the candidate list for elements having
486 // the specified attribute.
487 type filterAttr struct {
488 space, key string
489 }
490
491 func newFilterAttr(str string) *filterAttr {
492 s, l := spaceDecompose(str)
493 return &filterAttr{s, l}
494 }
495
496 func (f *filterAttr) apply(p *pather) {
497 for _, c := range p.candidates {
498 for _, a := range c.Attr {
499 if spaceMatch(f.space, a.Space) && f.key == a.Key {
500 p.scratch = append(p.scratch, c)
501 break
502 }
503 }
504 }
505 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
506 }
507
508 // filterAttrVal filters the candidate list for elements having
509 // the specified attribute with the specified value.
510 type filterAttrVal struct {
511 space, key, val string
512 }
513
514 func newFilterAttrVal(str, value string) *filterAttrVal {
515 s, l := spaceDecompose(str)
516 return &filterAttrVal{s, l, value}
517 }
518
519 func (f *filterAttrVal) apply(p *pather) {
520 for _, c := range p.candidates {
521 for _, a := range c.Attr {
522 if spaceMatch(f.space, a.Space) && f.key == a.Key && f.val == a.Value {
523 p.scratch = append(p.scratch, c)
524 break
525 }
526 }
527 }
528 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
529 }
530
531 // filterFunc filters the candidate list for elements satisfying a custom
532 // boolean function.
533 type filterFunc struct {
534 fn func(e *Element) string
535 }
536
537 func newFilterFunc(fn func(e *Element) string) *filterFunc {
538 return &filterFunc{fn}
539 }
540
541 func (f *filterFunc) apply(p *pather) {
542 for _, c := range p.candidates {
543 if f.fn(c) != "" {
544 p.scratch = append(p.scratch, c)
545 }
546 }
547 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
548 }
549
550 // filterFuncVal filters the candidate list for elements containing a value
551 // matching the result of a custom function.
552 type filterFuncVal struct {
553 fn func(e *Element) string
554 val string
555 }
556
557 func newFilterFuncVal(fn func(e *Element) string, value string) *filterFuncVal {
558 return &filterFuncVal{fn, value}
559 }
560
561 func (f *filterFuncVal) apply(p *pather) {
562 for _, c := range p.candidates {
563 if f.fn(c) == f.val {
564 p.scratch = append(p.scratch, c)
565 }
566 }
567 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
568 }
569
570 // filterChild filters the candidate list for elements having
571 // a child element with the specified tag.
572 type filterChild struct {
573 space, tag string
574 }
575
576 func newFilterChild(str string) *filterChild {
577 s, l := spaceDecompose(str)
578 return &filterChild{s, l}
579 }
580
581 func (f *filterChild) apply(p *pather) {
582 for _, c := range p.candidates {
583 for _, cc := range c.Child {
584 if cc, ok := cc.(*Element); ok &&
585 spaceMatch(f.space, cc.Space) &&
586 f.tag == cc.Tag {
587 p.scratch = append(p.scratch, c)
588 }
589 }
590 }
591 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
592 }
593
594 // filterChildText filters the candidate list for elements having
595 // a child element with the specified tag and text.
596 type filterChildText struct {
597 space, tag, text string
598 }
599
600 func newFilterChildText(str, text string) *filterChildText {
601 s, l := spaceDecompose(str)
602 return &filterChildText{s, l, text}
603 }
604
605 func (f *filterChildText) apply(p *pather) {
606 for _, c := range p.candidates {
607 for _, cc := range c.Child {
608 if cc, ok := cc.(*Element); ok &&
609 spaceMatch(f.space, cc.Space) &&
610 f.tag == cc.Tag &&
611 f.text == cc.Text() {
612 p.scratch = append(p.scratch, c)
613 }
614 }
615 }
616 p.candidates, p.scratch = p.scratch, p.candidates[0:0]
617 }