Rebase.
[official-gcc.git] / libgo / go / encoding / xml / read.go
blob75b9f2ba1b2ee44fad5e1a72e53058c988364db2
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 xml.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 contains character data, that data is
56 // accumulated in the first struct field that has tag ",chardata".
57 // The struct field may have type []byte or string.
58 // If there is no such field, the character data is discarded.
60 // * If the XML element contains comments, they are accumulated in
61 // the first struct field that has tag ",comment". The struct
62 // field may have type []byte or string. If there is no such
63 // field, the comments are discarded.
65 // * If the XML element contains a sub-element whose name matches
66 // the prefix of a tag formatted as "a" or "a>b>c", unmarshal
67 // will descend into the XML structure looking for elements with the
68 // given names, and will map the innermost elements to that struct
69 // field. A tag starting with ">" is equivalent to one starting
70 // with the field name followed by ">".
72 // * If the XML element contains a sub-element whose name matches
73 // a struct field's XMLName tag and the struct field has no
74 // explicit name tag as per the previous rule, unmarshal maps
75 // the sub-element to that struct field.
77 // * If the XML element contains a sub-element whose name matches a
78 // field without any mode flags (",attr", ",chardata", etc), Unmarshal
79 // maps the sub-element to that struct field.
81 // * If the XML element contains a sub-element that hasn't matched any
82 // of the above rules and the struct has a field with tag ",any",
83 // unmarshal maps the sub-element to that struct field.
85 // * An anonymous struct field is handled as if the fields of its
86 // value were part of the outer struct.
88 // * A struct field with tag "-" is never unmarshalled into.
90 // Unmarshal maps an XML element to a string or []byte by saving the
91 // concatenation of that element's character data in the string or
92 // []byte. The saved []byte is never nil.
94 // Unmarshal maps an attribute value to a string or []byte by saving
95 // the value in the string or slice.
97 // Unmarshal maps an XML element to a slice by extending the length of
98 // the slice and mapping the element to the newly created value.
100 // Unmarshal maps an XML element or attribute value to a bool by
101 // setting it to the boolean value represented by the string.
103 // Unmarshal maps an XML element or attribute value to an integer or
104 // floating-point field by setting the field to the result of
105 // interpreting the string value in decimal. There is no check for
106 // overflow.
108 // Unmarshal maps an XML element to an xml.Name by recording the
109 // element name.
111 // Unmarshal maps an XML element to a pointer by setting the pointer
112 // to a freshly allocated value and then mapping the element to that value.
114 func Unmarshal(data []byte, v interface{}) error {
115 return NewDecoder(bytes.NewReader(data)).Decode(v)
118 // Decode works like xml.Unmarshal, except it reads the decoder
119 // stream to find the start element.
120 func (d *Decoder) Decode(v interface{}) error {
121 return d.DecodeElement(v, nil)
124 // DecodeElement works like xml.Unmarshal except that it takes
125 // a pointer to the start XML element to decode into v.
126 // It is useful when a client reads some raw XML tokens itself
127 // but also wants to defer to Unmarshal for some elements.
128 func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
129 val := reflect.ValueOf(v)
130 if val.Kind() != reflect.Ptr {
131 return errors.New("non-pointer passed to Unmarshal")
133 return d.unmarshal(val.Elem(), start)
136 // An UnmarshalError represents an error in the unmarshalling process.
137 type UnmarshalError string
139 func (e UnmarshalError) Error() string { return string(e) }
141 // Unmarshaler is the interface implemented by objects that can unmarshal
142 // an XML element description of themselves.
144 // UnmarshalXML decodes a single XML element
145 // beginning with the given start element.
146 // If it returns an error, the outer call to Unmarshal stops and
147 // returns that error.
148 // UnmarshalXML must consume exactly one XML element.
149 // One common implementation strategy is to unmarshal into
150 // a separate value with a layout matching the expected XML
151 // using d.DecodeElement, and then to copy the data from
152 // that value into the receiver.
153 // Another common strategy is to use d.Token to process the
154 // XML object one token at a time.
155 // UnmarshalXML may not use d.RawToken.
156 type Unmarshaler interface {
157 UnmarshalXML(d *Decoder, start StartElement) error
160 // UnmarshalerAttr is the interface implemented by objects that can unmarshal
161 // an XML attribute description of themselves.
163 // UnmarshalXMLAttr decodes a single XML attribute.
164 // If it returns an error, the outer call to Unmarshal stops and
165 // returns that error.
166 // UnmarshalXMLAttr is used only for struct fields with the
167 // "attr" option in the field tag.
168 type UnmarshalerAttr interface {
169 UnmarshalXMLAttr(attr Attr) error
172 // receiverType returns the receiver type to use in an expression like "%s.MethodName".
173 func receiverType(val interface{}) string {
174 t := reflect.TypeOf(val)
175 if t.Name() != "" {
176 return t.String()
178 return "(" + t.String() + ")"
181 // unmarshalInterface unmarshals a single XML element into val.
182 // start is the opening tag of the element.
183 func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error {
184 // Record that decoder must stop at end tag corresponding to start.
185 p.pushEOF()
187 p.unmarshalDepth++
188 err := val.UnmarshalXML(p, *start)
189 p.unmarshalDepth--
190 if err != nil {
191 p.popEOF()
192 return err
195 if !p.popEOF() {
196 return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
199 return nil
202 // unmarshalTextInterface unmarshals a single XML element into val.
203 // The chardata contained in the element (but not its children)
204 // is passed to the text unmarshaler.
205 func (p *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler, start *StartElement) error {
206 var buf []byte
207 depth := 1
208 for depth > 0 {
209 t, err := p.Token()
210 if err != nil {
211 return err
213 switch t := t.(type) {
214 case CharData:
215 if depth == 1 {
216 buf = append(buf, t...)
218 case StartElement:
219 depth++
220 case EndElement:
221 depth--
224 return val.UnmarshalText(buf)
227 // unmarshalAttr unmarshals a single XML attribute into val.
228 func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error {
229 if val.Kind() == reflect.Ptr {
230 if val.IsNil() {
231 val.Set(reflect.New(val.Type().Elem()))
233 val = val.Elem()
236 if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
237 // This is an unmarshaler with a non-pointer receiver,
238 // so it's likely to be incorrect, but we do what we're told.
239 return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
241 if val.CanAddr() {
242 pv := val.Addr()
243 if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
244 return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
248 // Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
249 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
250 // This is an unmarshaler with a non-pointer receiver,
251 // so it's likely to be incorrect, but we do what we're told.
252 return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
254 if val.CanAddr() {
255 pv := val.Addr()
256 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
257 return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
261 copyValue(val, []byte(attr.Value))
262 return nil
265 var (
266 unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
267 unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem()
268 textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
271 // Unmarshal a single XML element into val.
272 func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
273 // Find start element if we need it.
274 if start == nil {
275 for {
276 tok, err := p.Token()
277 if err != nil {
278 return err
280 if t, ok := tok.(StartElement); ok {
281 start = &t
282 break
287 // Load value from interface, but only if the result will be
288 // usefully addressable.
289 if val.Kind() == reflect.Interface && !val.IsNil() {
290 e := val.Elem()
291 if e.Kind() == reflect.Ptr && !e.IsNil() {
292 val = e
296 if val.Kind() == reflect.Ptr {
297 if val.IsNil() {
298 val.Set(reflect.New(val.Type().Elem()))
300 val = val.Elem()
303 if val.CanInterface() && val.Type().Implements(unmarshalerType) {
304 // This is an unmarshaler with a non-pointer receiver,
305 // so it's likely to be incorrect, but we do what we're told.
306 return p.unmarshalInterface(val.Interface().(Unmarshaler), start)
309 if val.CanAddr() {
310 pv := val.Addr()
311 if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
312 return p.unmarshalInterface(pv.Interface().(Unmarshaler), start)
316 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
317 return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start)
320 if val.CanAddr() {
321 pv := val.Addr()
322 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
323 return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start)
327 var (
328 data []byte
329 saveData reflect.Value
330 comment []byte
331 saveComment reflect.Value
332 saveXML reflect.Value
333 saveXMLIndex int
334 saveXMLData []byte
335 saveAny reflect.Value
336 sv reflect.Value
337 tinfo *typeInfo
338 err error
341 switch v := val; v.Kind() {
342 default:
343 return errors.New("unknown type " + v.Type().String())
345 case reflect.Interface:
346 // TODO: For now, simply ignore the field. In the near
347 // future we may choose to unmarshal the start
348 // element on it, if not nil.
349 return p.Skip()
351 case reflect.Slice:
352 typ := v.Type()
353 if typ.Elem().Kind() == reflect.Uint8 {
354 // []byte
355 saveData = v
356 break
359 // Slice of element values.
360 // Grow slice.
361 n := v.Len()
362 if n >= v.Cap() {
363 ncap := 2 * n
364 if ncap < 4 {
365 ncap = 4
367 new := reflect.MakeSlice(typ, n, ncap)
368 reflect.Copy(new, v)
369 v.Set(new)
371 v.SetLen(n + 1)
373 // Recur to read element into slice.
374 if err := p.unmarshal(v.Index(n), start); err != nil {
375 v.SetLen(n)
376 return err
378 return nil
380 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:
381 saveData = v
383 case reflect.Struct:
384 typ := v.Type()
385 if typ == nameType {
386 v.Set(reflect.ValueOf(start.Name))
387 break
390 sv = v
391 tinfo, err = getTypeInfo(typ)
392 if err != nil {
393 return err
396 // Validate and assign element name.
397 if tinfo.xmlname != nil {
398 finfo := tinfo.xmlname
399 if finfo.name != "" && finfo.name != start.Name.Local {
400 return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
402 if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
403 e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
404 if start.Name.Space == "" {
405 e += "no name space"
406 } else {
407 e += start.Name.Space
409 return UnmarshalError(e)
411 fv := finfo.value(sv)
412 if _, ok := fv.Interface().(Name); ok {
413 fv.Set(reflect.ValueOf(start.Name))
417 // Assign attributes.
418 // Also, determine whether we need to save character data or comments.
419 for i := range tinfo.fields {
420 finfo := &tinfo.fields[i]
421 switch finfo.flags & fMode {
422 case fAttr:
423 strv := finfo.value(sv)
424 // Look for attribute.
425 for _, a := range start.Attr {
426 if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
427 if err := p.unmarshalAttr(strv, a); err != nil {
428 return err
430 break
434 case fCharData:
435 if !saveData.IsValid() {
436 saveData = finfo.value(sv)
439 case fComment:
440 if !saveComment.IsValid() {
441 saveComment = finfo.value(sv)
444 case fAny, fAny | fElement:
445 if !saveAny.IsValid() {
446 saveAny = finfo.value(sv)
449 case fInnerXml:
450 if !saveXML.IsValid() {
451 saveXML = finfo.value(sv)
452 if p.saved == nil {
453 saveXMLIndex = 0
454 p.saved = new(bytes.Buffer)
455 } else {
456 saveXMLIndex = p.savedOffset()
463 // Find end element.
464 // Process sub-elements along the way.
465 Loop:
466 for {
467 var savedOffset int
468 if saveXML.IsValid() {
469 savedOffset = p.savedOffset()
471 tok, err := p.Token()
472 if err != nil {
473 return err
475 switch t := tok.(type) {
476 case StartElement:
477 consumed := false
478 if sv.IsValid() {
479 consumed, err = p.unmarshalPath(tinfo, sv, nil, &t)
480 if err != nil {
481 return err
483 if !consumed && saveAny.IsValid() {
484 consumed = true
485 if err := p.unmarshal(saveAny, &t); err != nil {
486 return err
490 if !consumed {
491 if err := p.Skip(); err != nil {
492 return err
496 case EndElement:
497 if saveXML.IsValid() {
498 saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset]
499 if saveXMLIndex == 0 {
500 p.saved = nil
503 break Loop
505 case CharData:
506 if saveData.IsValid() {
507 data = append(data, t...)
510 case Comment:
511 if saveComment.IsValid() {
512 comment = append(comment, t...)
517 if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
518 if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
519 return err
521 saveData = reflect.Value{}
524 if saveData.IsValid() && saveData.CanAddr() {
525 pv := saveData.Addr()
526 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
527 if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
528 return err
530 saveData = reflect.Value{}
534 if err := copyValue(saveData, data); err != nil {
535 return err
538 switch t := saveComment; t.Kind() {
539 case reflect.String:
540 t.SetString(string(comment))
541 case reflect.Slice:
542 t.Set(reflect.ValueOf(comment))
545 switch t := saveXML; t.Kind() {
546 case reflect.String:
547 t.SetString(string(saveXMLData))
548 case reflect.Slice:
549 t.Set(reflect.ValueOf(saveXMLData))
552 return nil
555 func copyValue(dst reflect.Value, src []byte) (err error) {
556 dst0 := dst
558 if dst.Kind() == reflect.Ptr {
559 if dst.IsNil() {
560 dst.Set(reflect.New(dst.Type().Elem()))
562 dst = dst.Elem()
565 // Save accumulated data.
566 switch dst.Kind() {
567 case reflect.Invalid:
568 // Probably a comment.
569 default:
570 return errors.New("cannot unmarshal into " + dst0.Type().String())
571 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
572 itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits())
573 if err != nil {
574 return err
576 dst.SetInt(itmp)
577 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
578 utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits())
579 if err != nil {
580 return err
582 dst.SetUint(utmp)
583 case reflect.Float32, reflect.Float64:
584 ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits())
585 if err != nil {
586 return err
588 dst.SetFloat(ftmp)
589 case reflect.Bool:
590 value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
591 if err != nil {
592 return err
594 dst.SetBool(value)
595 case reflect.String:
596 dst.SetString(string(src))
597 case reflect.Slice:
598 if len(src) == 0 {
599 // non-nil to flag presence
600 src = []byte{}
602 dst.SetBytes(src)
604 return nil
607 // unmarshalPath walks down an XML structure looking for wanted
608 // paths, and calls unmarshal on them.
609 // The consumed result tells whether XML elements have been consumed
610 // from the Decoder until start's matching end element, or if it's
611 // still untouched because start is uninteresting for sv's fields.
612 func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
613 recurse := false
614 Loop:
615 for i := range tinfo.fields {
616 finfo := &tinfo.fields[i]
617 if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
618 continue
620 for j := range parents {
621 if parents[j] != finfo.parents[j] {
622 continue Loop
625 if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
626 // It's a perfect match, unmarshal the field.
627 return true, p.unmarshal(finfo.value(sv), start)
629 if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
630 // It's a prefix for the field. Break and recurse
631 // since it's not ok for one field path to be itself
632 // the prefix for another field path.
633 recurse = true
635 // We can reuse the same slice as long as we
636 // don't try to append to it.
637 parents = finfo.parents[:len(parents)+1]
638 break
641 if !recurse {
642 // We have no business with this element.
643 return false, nil
645 // The element is not a perfect match for any field, but one
646 // or more fields have the path to this element as a parent
647 // prefix. Recurse and attempt to match these.
648 for {
649 var tok Token
650 tok, err = p.Token()
651 if err != nil {
652 return true, err
654 switch t := tok.(type) {
655 case StartElement:
656 consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t)
657 if err != nil {
658 return true, err
660 if !consumed2 {
661 if err := p.Skip(); err != nil {
662 return true, err
665 case EndElement:
666 return true, nil
671 // Skip reads tokens until it has consumed the end element
672 // matching the most recent start element already consumed.
673 // It recurs if it encounters a start element, so it can be used to
674 // skip nested structures.
675 // It returns nil if it finds an end element matching the start
676 // element; otherwise it returns an error describing the problem.
677 func (d *Decoder) Skip() error {
678 for {
679 tok, err := d.Token()
680 if err != nil {
681 return err
683 switch tok.(type) {
684 case StartElement:
685 if err := d.Skip(); err != nil {
686 return err
688 case EndElement:
689 return nil