libgo: update to go1.9
[official-gcc.git] / libgo / go / encoding / xml / read.go
blob000d9fbd0ef509bf5ed48871dbce75e6591f0f53
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 package xml
7 import (
8 "bytes"
9 "encoding"
10 "errors"
11 "fmt"
12 "reflect"
13 "strconv"
14 "strings"
17 // BUG(rsc): Mapping between XML elements and data structures is inherently flawed:
18 // an XML element is an order-dependent collection of anonymous
19 // values, while a data structure is an order-independent collection
20 // of named values.
21 // See package json for a textual representation more suitable
22 // to data structures.
24 // Unmarshal parses the XML-encoded data and stores the result in
25 // the value pointed to by v, which must be an arbitrary struct,
26 // slice, or string. Well-formed data that does not fit into v is
27 // discarded.
29 // Because Unmarshal uses the reflect package, it can only assign
30 // to exported (upper case) fields. Unmarshal uses a case-sensitive
31 // comparison to match XML element names to tag values and struct
32 // field names.
34 // Unmarshal maps an XML element to a struct using the following rules.
35 // In the rules, the tag of a field refers to the value associated with the
36 // key 'xml' in the struct field's tag (see the example above).
38 // * If the struct has a field of type []byte or string with tag
39 // ",innerxml", Unmarshal accumulates the raw XML nested inside the
40 // element in that field. The rest of the rules still apply.
42 // * If the struct has a field named XMLName of type Name,
43 // Unmarshal records the element name in that field.
45 // * If the XMLName field has an associated tag of the form
46 // "name" or "namespace-URL name", the XML element must have
47 // the given name (and, optionally, name space) or else Unmarshal
48 // returns an error.
50 // * If the XML element has an attribute whose name matches a
51 // struct field name with an associated tag containing ",attr" or
52 // the explicit name in a struct field tag of the form "name,attr",
53 // Unmarshal records the attribute value in that field.
55 // * If the XML element has an attribute not handled by the previous
56 // rule and the struct has a field with an associated tag containing
57 // ",any,attr", Unmarshal records the attribute value in the first
58 // such field.
60 // * If the XML element contains character data, that data is
61 // accumulated in the first struct field that has tag ",chardata".
62 // The struct field may have type []byte or string.
63 // If there is no such field, the character data is discarded.
65 // * If the XML element contains comments, they are accumulated in
66 // the first struct field that has tag ",comment". The struct
67 // field may have type []byte or string. If there is no such
68 // field, the comments are discarded.
70 // * If the XML element contains a sub-element whose name matches
71 // the prefix of a tag formatted as "a" or "a>b>c", unmarshal
72 // will descend into the XML structure looking for elements with the
73 // given names, and will map the innermost elements to that struct
74 // field. A tag starting with ">" is equivalent to one starting
75 // with the field name followed by ">".
77 // * If the XML element contains a sub-element whose name matches
78 // a struct field's XMLName tag and the struct field has no
79 // explicit name tag as per the previous rule, unmarshal maps
80 // the sub-element to that struct field.
82 // * If the XML element contains a sub-element whose name matches a
83 // field without any mode flags (",attr", ",chardata", etc), Unmarshal
84 // maps the sub-element to that struct field.
86 // * If the XML element contains a sub-element that hasn't matched any
87 // of the above rules and the struct has a field with tag ",any",
88 // unmarshal maps the sub-element to that struct field.
90 // * An anonymous struct field is handled as if the fields of its
91 // value were part of the outer struct.
93 // * A struct field with tag "-" is never unmarshaled into.
95 // Unmarshal maps an XML element to a string or []byte by saving the
96 // concatenation of that element's character data in the string or
97 // []byte. The saved []byte is never nil.
99 // Unmarshal maps an attribute value to a string or []byte by saving
100 // the value in the string or slice.
102 // Unmarshal maps an attribute value to an Attr by saving the attribute,
103 // including its name, in the Attr.
105 // Unmarshal maps an XML element or attribute value to a slice by
106 // extending the length of the slice and mapping the element or attribute
107 // to the newly created value.
109 // Unmarshal maps an XML element or attribute value to a bool by
110 // setting it to the boolean value represented by the string.
112 // Unmarshal maps an XML element or attribute value to an integer or
113 // floating-point field by setting the field to the result of
114 // interpreting the string value in decimal. There is no check for
115 // overflow.
117 // Unmarshal maps an XML element to a Name by recording the element
118 // name.
120 // Unmarshal maps an XML element to a pointer by setting the pointer
121 // to a freshly allocated value and then mapping the element to that value.
123 // A missing element or empty attribute value will be unmarshaled as a zero value.
124 // If the field is a slice, a zero value will be appended to the field. Otherwise, the
125 // field will be set to its zero value.
126 func Unmarshal(data []byte, v interface{}) error {
127 return NewDecoder(bytes.NewReader(data)).Decode(v)
130 // Decode works like Unmarshal, except it reads the decoder
131 // stream to find the start element.
132 func (d *Decoder) Decode(v interface{}) error {
133 return d.DecodeElement(v, nil)
136 // DecodeElement works like Unmarshal except that it takes
137 // a pointer to the start XML element to decode into v.
138 // It is useful when a client reads some raw XML tokens itself
139 // but also wants to defer to Unmarshal for some elements.
140 func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
141 val := reflect.ValueOf(v)
142 if val.Kind() != reflect.Ptr {
143 return errors.New("non-pointer passed to Unmarshal")
145 return d.unmarshal(val.Elem(), start)
148 // An UnmarshalError represents an error in the unmarshaling process.
149 type UnmarshalError string
151 func (e UnmarshalError) Error() string { return string(e) }
153 // Unmarshaler is the interface implemented by objects that can unmarshal
154 // an XML element description of themselves.
156 // UnmarshalXML decodes a single XML element
157 // beginning with the given start element.
158 // If it returns an error, the outer call to Unmarshal stops and
159 // returns that error.
160 // UnmarshalXML must consume exactly one XML element.
161 // One common implementation strategy is to unmarshal into
162 // a separate value with a layout matching the expected XML
163 // using d.DecodeElement, and then to copy the data from
164 // that value into the receiver.
165 // Another common strategy is to use d.Token to process the
166 // XML object one token at a time.
167 // UnmarshalXML may not use d.RawToken.
168 type Unmarshaler interface {
169 UnmarshalXML(d *Decoder, start StartElement) error
172 // UnmarshalerAttr is the interface implemented by objects that can unmarshal
173 // an XML attribute description of themselves.
175 // UnmarshalXMLAttr decodes a single XML attribute.
176 // If it returns an error, the outer call to Unmarshal stops and
177 // returns that error.
178 // UnmarshalXMLAttr is used only for struct fields with the
179 // "attr" option in the field tag.
180 type UnmarshalerAttr interface {
181 UnmarshalXMLAttr(attr Attr) error
184 // receiverType returns the receiver type to use in an expression like "%s.MethodName".
185 func receiverType(val interface{}) string {
186 t := reflect.TypeOf(val)
187 if t.Name() != "" {
188 return t.String()
190 return "(" + t.String() + ")"
193 // unmarshalInterface unmarshals a single XML element into val.
194 // start is the opening tag of the element.
195 func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error {
196 // Record that decoder must stop at end tag corresponding to start.
197 p.pushEOF()
199 p.unmarshalDepth++
200 err := val.UnmarshalXML(p, *start)
201 p.unmarshalDepth--
202 if err != nil {
203 p.popEOF()
204 return err
207 if !p.popEOF() {
208 return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
211 return nil
214 // unmarshalTextInterface unmarshals a single XML element into val.
215 // The chardata contained in the element (but not its children)
216 // is passed to the text unmarshaler.
217 func (p *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler) error {
218 var buf []byte
219 depth := 1
220 for depth > 0 {
221 t, err := p.Token()
222 if err != nil {
223 return err
225 switch t := t.(type) {
226 case CharData:
227 if depth == 1 {
228 buf = append(buf, t...)
230 case StartElement:
231 depth++
232 case EndElement:
233 depth--
236 return val.UnmarshalText(buf)
239 // unmarshalAttr unmarshals a single XML attribute into val.
240 func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error {
241 if val.Kind() == reflect.Ptr {
242 if val.IsNil() {
243 val.Set(reflect.New(val.Type().Elem()))
245 val = val.Elem()
247 if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
248 // This is an unmarshaler with a non-pointer receiver,
249 // so it's likely to be incorrect, but we do what we're told.
250 return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
252 if val.CanAddr() {
253 pv := val.Addr()
254 if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
255 return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
259 // Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
260 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
261 // This is an unmarshaler with a non-pointer receiver,
262 // so it's likely to be incorrect, but we do what we're told.
263 return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
265 if val.CanAddr() {
266 pv := val.Addr()
267 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
268 return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
272 if val.Type().Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
273 // Slice of element values.
274 // Grow slice.
275 n := val.Len()
276 val.Set(reflect.Append(val, reflect.Zero(val.Type().Elem())))
278 // Recur to read element into slice.
279 if err := p.unmarshalAttr(val.Index(n), attr); err != nil {
280 val.SetLen(n)
281 return err
283 return nil
286 if val.Type() == attrType {
287 val.Set(reflect.ValueOf(attr))
288 return nil
291 return copyValue(val, []byte(attr.Value))
294 var (
295 attrType = reflect.TypeOf(Attr{})
296 unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
297 unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem()
298 textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
301 // Unmarshal a single XML element into val.
302 func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
303 // Find start element if we need it.
304 if start == nil {
305 for {
306 tok, err := p.Token()
307 if err != nil {
308 return err
310 if t, ok := tok.(StartElement); ok {
311 start = &t
312 break
317 // Load value from interface, but only if the result will be
318 // usefully addressable.
319 if val.Kind() == reflect.Interface && !val.IsNil() {
320 e := val.Elem()
321 if e.Kind() == reflect.Ptr && !e.IsNil() {
322 val = e
326 if val.Kind() == reflect.Ptr {
327 if val.IsNil() {
328 val.Set(reflect.New(val.Type().Elem()))
330 val = val.Elem()
333 if val.CanInterface() && val.Type().Implements(unmarshalerType) {
334 // This is an unmarshaler with a non-pointer receiver,
335 // so it's likely to be incorrect, but we do what we're told.
336 return p.unmarshalInterface(val.Interface().(Unmarshaler), start)
339 if val.CanAddr() {
340 pv := val.Addr()
341 if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
342 return p.unmarshalInterface(pv.Interface().(Unmarshaler), start)
346 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
347 return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler))
350 if val.CanAddr() {
351 pv := val.Addr()
352 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
353 return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler))
357 var (
358 data []byte
359 saveData reflect.Value
360 comment []byte
361 saveComment reflect.Value
362 saveXML reflect.Value
363 saveXMLIndex int
364 saveXMLData []byte
365 saveAny reflect.Value
366 sv reflect.Value
367 tinfo *typeInfo
368 err error
371 switch v := val; v.Kind() {
372 default:
373 return errors.New("unknown type " + v.Type().String())
375 case reflect.Interface:
376 // TODO: For now, simply ignore the field. In the near
377 // future we may choose to unmarshal the start
378 // element on it, if not nil.
379 return p.Skip()
381 case reflect.Slice:
382 typ := v.Type()
383 if typ.Elem().Kind() == reflect.Uint8 {
384 // []byte
385 saveData = v
386 break
389 // Slice of element values.
390 // Grow slice.
391 n := v.Len()
392 v.Set(reflect.Append(val, reflect.Zero(v.Type().Elem())))
394 // Recur to read element into slice.
395 if err := p.unmarshal(v.Index(n), start); err != nil {
396 v.SetLen(n)
397 return err
399 return nil
401 case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String:
402 saveData = v
404 case reflect.Struct:
405 typ := v.Type()
406 if typ == nameType {
407 v.Set(reflect.ValueOf(start.Name))
408 break
411 sv = v
412 tinfo, err = getTypeInfo(typ)
413 if err != nil {
414 return err
417 // Validate and assign element name.
418 if tinfo.xmlname != nil {
419 finfo := tinfo.xmlname
420 if finfo.name != "" && finfo.name != start.Name.Local {
421 return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
423 if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
424 e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
425 if start.Name.Space == "" {
426 e += "no name space"
427 } else {
428 e += start.Name.Space
430 return UnmarshalError(e)
432 fv := finfo.value(sv)
433 if _, ok := fv.Interface().(Name); ok {
434 fv.Set(reflect.ValueOf(start.Name))
438 // Assign attributes.
439 for _, a := range start.Attr {
440 handled := false
441 any := -1
442 for i := range tinfo.fields {
443 finfo := &tinfo.fields[i]
444 switch finfo.flags & fMode {
445 case fAttr:
446 strv := finfo.value(sv)
447 if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
448 if err := p.unmarshalAttr(strv, a); err != nil {
449 return err
451 handled = true
454 case fAny | fAttr:
455 if any == -1 {
456 any = i
460 if !handled && any >= 0 {
461 finfo := &tinfo.fields[any]
462 strv := finfo.value(sv)
463 if err := p.unmarshalAttr(strv, a); err != nil {
464 return err
469 // Determine whether we need to save character data or comments.
470 for i := range tinfo.fields {
471 finfo := &tinfo.fields[i]
472 switch finfo.flags & fMode {
473 case fCDATA, fCharData:
474 if !saveData.IsValid() {
475 saveData = finfo.value(sv)
478 case fComment:
479 if !saveComment.IsValid() {
480 saveComment = finfo.value(sv)
483 case fAny, fAny | fElement:
484 if !saveAny.IsValid() {
485 saveAny = finfo.value(sv)
488 case fInnerXml:
489 if !saveXML.IsValid() {
490 saveXML = finfo.value(sv)
491 if p.saved == nil {
492 saveXMLIndex = 0
493 p.saved = new(bytes.Buffer)
494 } else {
495 saveXMLIndex = p.savedOffset()
502 // Find end element.
503 // Process sub-elements along the way.
504 Loop:
505 for {
506 var savedOffset int
507 if saveXML.IsValid() {
508 savedOffset = p.savedOffset()
510 tok, err := p.Token()
511 if err != nil {
512 return err
514 switch t := tok.(type) {
515 case StartElement:
516 consumed := false
517 if sv.IsValid() {
518 consumed, err = p.unmarshalPath(tinfo, sv, nil, &t)
519 if err != nil {
520 return err
522 if !consumed && saveAny.IsValid() {
523 consumed = true
524 if err := p.unmarshal(saveAny, &t); err != nil {
525 return err
529 if !consumed {
530 if err := p.Skip(); err != nil {
531 return err
535 case EndElement:
536 if saveXML.IsValid() {
537 saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset]
538 if saveXMLIndex == 0 {
539 p.saved = nil
542 break Loop
544 case CharData:
545 if saveData.IsValid() {
546 data = append(data, t...)
549 case Comment:
550 if saveComment.IsValid() {
551 comment = append(comment, t...)
556 if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
557 if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
558 return err
560 saveData = reflect.Value{}
563 if saveData.IsValid() && saveData.CanAddr() {
564 pv := saveData.Addr()
565 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
566 if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
567 return err
569 saveData = reflect.Value{}
573 if err := copyValue(saveData, data); err != nil {
574 return err
577 switch t := saveComment; t.Kind() {
578 case reflect.String:
579 t.SetString(string(comment))
580 case reflect.Slice:
581 t.Set(reflect.ValueOf(comment))
584 switch t := saveXML; t.Kind() {
585 case reflect.String:
586 t.SetString(string(saveXMLData))
587 case reflect.Slice:
588 if t.Type().Elem().Kind() == reflect.Uint8 {
589 t.Set(reflect.ValueOf(saveXMLData))
593 return nil
596 func copyValue(dst reflect.Value, src []byte) (err error) {
597 dst0 := dst
599 if dst.Kind() == reflect.Ptr {
600 if dst.IsNil() {
601 dst.Set(reflect.New(dst.Type().Elem()))
603 dst = dst.Elem()
606 // Save accumulated data.
607 switch dst.Kind() {
608 case reflect.Invalid:
609 // Probably a comment.
610 default:
611 return errors.New("cannot unmarshal into " + dst0.Type().String())
612 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
613 if len(src) == 0 {
614 dst.SetInt(0)
615 return nil
617 itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits())
618 if err != nil {
619 return err
621 dst.SetInt(itmp)
622 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
623 if len(src) == 0 {
624 dst.SetUint(0)
625 return nil
627 utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits())
628 if err != nil {
629 return err
631 dst.SetUint(utmp)
632 case reflect.Float32, reflect.Float64:
633 if len(src) == 0 {
634 dst.SetFloat(0)
635 return nil
637 ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits())
638 if err != nil {
639 return err
641 dst.SetFloat(ftmp)
642 case reflect.Bool:
643 if len(src) == 0 {
644 dst.SetBool(false)
645 return nil
647 value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
648 if err != nil {
649 return err
651 dst.SetBool(value)
652 case reflect.String:
653 dst.SetString(string(src))
654 case reflect.Slice:
655 if len(src) == 0 {
656 // non-nil to flag presence
657 src = []byte{}
659 dst.SetBytes(src)
661 return nil
664 // unmarshalPath walks down an XML structure looking for wanted
665 // paths, and calls unmarshal on them.
666 // The consumed result tells whether XML elements have been consumed
667 // from the Decoder until start's matching end element, or if it's
668 // still untouched because start is uninteresting for sv's fields.
669 func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
670 recurse := false
671 Loop:
672 for i := range tinfo.fields {
673 finfo := &tinfo.fields[i]
674 if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
675 continue
677 for j := range parents {
678 if parents[j] != finfo.parents[j] {
679 continue Loop
682 if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
683 // It's a perfect match, unmarshal the field.
684 return true, p.unmarshal(finfo.value(sv), start)
686 if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
687 // It's a prefix for the field. Break and recurse
688 // since it's not ok for one field path to be itself
689 // the prefix for another field path.
690 recurse = true
692 // We can reuse the same slice as long as we
693 // don't try to append to it.
694 parents = finfo.parents[:len(parents)+1]
695 break
698 if !recurse {
699 // We have no business with this element.
700 return false, nil
702 // The element is not a perfect match for any field, but one
703 // or more fields have the path to this element as a parent
704 // prefix. Recurse and attempt to match these.
705 for {
706 var tok Token
707 tok, err = p.Token()
708 if err != nil {
709 return true, err
711 switch t := tok.(type) {
712 case StartElement:
713 consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t)
714 if err != nil {
715 return true, err
717 if !consumed2 {
718 if err := p.Skip(); err != nil {
719 return true, err
722 case EndElement:
723 return true, nil
728 // Skip reads tokens until it has consumed the end element
729 // matching the most recent start element already consumed.
730 // It recurs if it encounters a start element, so it can be used to
731 // skip nested structures.
732 // It returns nil if it finds an end element matching the start
733 // element; otherwise it returns an error describing the problem.
734 func (d *Decoder) Skip() error {
735 for {
736 tok, err := d.Token()
737 if err != nil {
738 return err
740 switch tok.(type) {
741 case StartElement:
742 if err := d.Skip(); err != nil {
743 return err
745 case EndElement:
746 return nil