OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [encoding/] [xml/] [read.go] - Blame information for rev 758

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// 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.
4
 
5
package xml
6
 
7
import (
8
        "bytes"
9
        "errors"
10
        "reflect"
11
        "strconv"
12
        "strings"
13
)
14
 
15
// BUG(rsc): Mapping between XML elements and data structures is inherently flawed:
16
// an XML element is an order-dependent collection of anonymous
17
// values, while a data structure is an order-independent collection
18
// of named values.
19
// See package json for a textual representation more suitable
20
// to data structures.
21
 
22
// Unmarshal parses the XML-encoded data and stores the result in
23
// the value pointed to by v, which must be an arbitrary struct,
24
// slice, or string. Well-formed data that does not fit into v is
25
// discarded.
26
//
27
// For example, given these definitions:
28
//
29
//      type Email struct {
30
//              Where string `xml:",attr"`
31
//              Addr  string
32
//      }
33
//
34
//      type Result struct {
35
//              XMLName xml.Name `xml:"result"`
36
//              Name    string
37
//              Phone   string
38
//              Email   []Email
39
//              Groups  []string `xml:"group>value"`
40
//      }
41
//
42
//      result := Result{Name: "name", Phone: "phone", Email: nil}
43
//
44
// unmarshalling the XML input
45
//
46
//      
47
//              
48
//                      gre@example.com
49
//              
50
//              
51
//                      gre@work.com
52
//              
53
//              Grace R. Emlin
54
//              
55
//                      Friends
56
//                      Squash
57
//              
58
//              
123 Main Street
59
//      
60
//
61
// via Unmarshal(data, &result) is equivalent to assigning
62
//
63
//      r = Result{
64
//              xml.Name{Local: "result"},
65
//              "Grace R. Emlin", // name
66
//              "phone",          // no phone given
67
//              []Email{
68
//                      Email{"home", "gre@example.com"},
69
//                      Email{"work", "gre@work.com"},
70
//              },
71
//              []string{"Friends", "Squash"},
72
//      }
73
//
74
// Note that the field r.Phone has not been modified and
75
// that the XML 
element was discarded. Also, the field
76
// Groups was assigned considering the element path provided in the
77
// field tag.
78
//
79
// Because Unmarshal uses the reflect package, it can only assign
80
// to exported (upper case) fields.  Unmarshal uses a case-sensitive
81
// comparison to match XML element names to tag values and struct
82
// field names.
83
//
84
// Unmarshal maps an XML element to a struct using the following rules.
85
// In the rules, the tag of a field refers to the value associated with the
86
// key 'xml' in the struct field's tag (see the example above).
87
//
88
//   * If the struct has a field of type []byte or string with tag
89
//      ",innerxml", Unmarshal accumulates the raw XML nested inside the
90
//      element in that field.  The rest of the rules still apply.
91
//
92
//   * If the struct has a field named XMLName of type xml.Name,
93
//      Unmarshal records the element name in that field.
94
//
95
//   * If the XMLName field has an associated tag of the form
96
//      "name" or "namespace-URL name", the XML element must have
97
//      the given name (and, optionally, name space) or else Unmarshal
98
//      returns an error.
99
//
100
//   * If the XML element has an attribute whose name matches a
101
//      struct field name with an associated tag containing ",attr" or
102
//      the explicit name in a struct field tag of the form "name,attr",
103
//      Unmarshal records the attribute value in that field.
104
//
105
//   * If the XML element contains character data, that data is
106
//      accumulated in the first struct field that has tag "chardata".
107
//      The struct field may have type []byte or string.
108
//      If there is no such field, the character data is discarded.
109
//
110
//   * If the XML element contains comments, they are accumulated in
111
//      the first struct field that has tag ",comments".  The struct
112
//      field may have type []byte or string.  If there is no such
113
//      field, the comments are discarded.
114
//
115
//   * If the XML element contains a sub-element whose name matches
116
//      the prefix of a tag formatted as "a" or "a>b>c", unmarshal
117
//      will descend into the XML structure looking for elements with the
118
//      given names, and will map the innermost elements to that struct
119
//      field. A tag starting with ">" is equivalent to one starting
120
//      with the field name followed by ">".
121
//
122
//   * If the XML element contains a sub-element whose name matches
123
//      a struct field's XMLName tag and the struct field has no
124
//      explicit name tag as per the previous rule, unmarshal maps
125
//      the sub-element to that struct field.
126
//
127
//   * If the XML element contains a sub-element whose name matches a
128
//      field without any mode flags (",attr", ",chardata", etc), Unmarshal
129
//      maps the sub-element to that struct field.
130
//
131
//   * If the XML element contains a sub-element that hasn't matched any
132
//      of the above rules and the struct has a field with tag ",any",
133
//      unmarshal maps the sub-element to that struct field.
134
//
135
//   * A struct field with tag "-" is never unmarshalled into.
136
//
137
// Unmarshal maps an XML element to a string or []byte by saving the
138
// concatenation of that element's character data in the string or
139
// []byte. The saved []byte is never nil.
140
//
141
// Unmarshal maps an attribute value to a string or []byte by saving
142
// the value in the string or slice.
143
//
144
// Unmarshal maps an XML element to a slice by extending the length of
145
// the slice and mapping the element to the newly created value.
146
//
147
// Unmarshal maps an XML element or attribute value to a bool by
148
// setting it to the boolean value represented by the string.
149
//
150
// Unmarshal maps an XML element or attribute value to an integer or
151
// floating-point field by setting the field to the result of
152
// interpreting the string value in decimal.  There is no check for
153
// overflow.
154
//
155
// Unmarshal maps an XML element to an xml.Name by recording the
156
// element name.
157
//
158
// Unmarshal maps an XML element to a pointer by setting the pointer
159
// to a freshly allocated value and then mapping the element to that value.
160
//
161
func Unmarshal(data []byte, v interface{}) error {
162
        return NewDecoder(bytes.NewBuffer(data)).Decode(v)
163
}
164
 
165
// Decode works like xml.Unmarshal, except it reads the decoder
166
// stream to find the start element.
167
func (d *Decoder) Decode(v interface{}) error {
168
        return d.DecodeElement(v, nil)
169
}
170
 
171
// DecodeElement works like xml.Unmarshal except that it takes
172
// a pointer to the start XML element to decode into v.
173
// It is useful when a client reads some raw XML tokens itself
174
// but also wants to defer to Unmarshal for some elements.
175
func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
176
        val := reflect.ValueOf(v)
177
        if val.Kind() != reflect.Ptr {
178
                return errors.New("non-pointer passed to Unmarshal")
179
        }
180
        return d.unmarshal(val.Elem(), start)
181
}
182
 
183
// An UnmarshalError represents an error in the unmarshalling process.
184
type UnmarshalError string
185
 
186
func (e UnmarshalError) Error() string { return string(e) }
187
 
188
// Unmarshal a single XML element into val.
189
func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
190
        // Find start element if we need it.
191
        if start == nil {
192
                for {
193
                        tok, err := p.Token()
194
                        if err != nil {
195
                                return err
196
                        }
197
                        if t, ok := tok.(StartElement); ok {
198
                                start = &t
199
                                break
200
                        }
201
                }
202
        }
203
 
204
        if pv := val; pv.Kind() == reflect.Ptr {
205
                if pv.IsNil() {
206
                        pv.Set(reflect.New(pv.Type().Elem()))
207
                }
208
                val = pv.Elem()
209
        }
210
 
211
        var (
212
                data         []byte
213
                saveData     reflect.Value
214
                comment      []byte
215
                saveComment  reflect.Value
216
                saveXML      reflect.Value
217
                saveXMLIndex int
218
                saveXMLData  []byte
219
                saveAny      reflect.Value
220
                sv           reflect.Value
221
                tinfo        *typeInfo
222
                err          error
223
        )
224
 
225
        switch v := val; v.Kind() {
226
        default:
227
                return errors.New("unknown type " + v.Type().String())
228
 
229
        case reflect.Interface:
230
                // TODO: For now, simply ignore the field. In the near
231
                //       future we may choose to unmarshal the start
232
                //       element on it, if not nil.
233
                return p.Skip()
234
 
235
        case reflect.Slice:
236
                typ := v.Type()
237
                if typ.Elem().Kind() == reflect.Uint8 {
238
                        // []byte
239
                        saveData = v
240
                        break
241
                }
242
 
243
                // Slice of element values.
244
                // Grow slice.
245
                n := v.Len()
246
                if n >= v.Cap() {
247
                        ncap := 2 * n
248
                        if ncap < 4 {
249
                                ncap = 4
250
                        }
251
                        new := reflect.MakeSlice(typ, n, ncap)
252
                        reflect.Copy(new, v)
253
                        v.Set(new)
254
                }
255
                v.SetLen(n + 1)
256
 
257
                // Recur to read element into slice.
258
                if err := p.unmarshal(v.Index(n), start); err != nil {
259
                        v.SetLen(n)
260
                        return err
261
                }
262
                return nil
263
 
264
        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:
265
                saveData = v
266
 
267
        case reflect.Struct:
268
                typ := v.Type()
269
                if typ == nameType {
270
                        v.Set(reflect.ValueOf(start.Name))
271
                        break
272
                }
273
 
274
                sv = v
275
                tinfo, err = getTypeInfo(typ)
276
                if err != nil {
277
                        return err
278
                }
279
 
280
                // Validate and assign element name.
281
                if tinfo.xmlname != nil {
282
                        finfo := tinfo.xmlname
283
                        if finfo.name != "" && finfo.name != start.Name.Local {
284
                                return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
285
                        }
286
                        if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
287
                                e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
288
                                if start.Name.Space == "" {
289
                                        e += "no name space"
290
                                } else {
291
                                        e += start.Name.Space
292
                                }
293
                                return UnmarshalError(e)
294
                        }
295
                        fv := sv.FieldByIndex(finfo.idx)
296
                        if _, ok := fv.Interface().(Name); ok {
297
                                fv.Set(reflect.ValueOf(start.Name))
298
                        }
299
                }
300
 
301
                // Assign attributes.
302
                // Also, determine whether we need to save character data or comments.
303
                for i := range tinfo.fields {
304
                        finfo := &tinfo.fields[i]
305
                        switch finfo.flags & fMode {
306
                        case fAttr:
307
                                strv := sv.FieldByIndex(finfo.idx)
308
                                // Look for attribute.
309
                                for _, a := range start.Attr {
310
                                        if a.Name.Local == finfo.name {
311
                                                copyValue(strv, []byte(a.Value))
312
                                                break
313
                                        }
314
                                }
315
 
316
                        case fCharData:
317
                                if !saveData.IsValid() {
318
                                        saveData = sv.FieldByIndex(finfo.idx)
319
                                }
320
 
321
                        case fComment:
322
                                if !saveComment.IsValid() {
323
                                        saveComment = sv.FieldByIndex(finfo.idx)
324
                                }
325
 
326
                        case fAny:
327
                                if !saveAny.IsValid() {
328
                                        saveAny = sv.FieldByIndex(finfo.idx)
329
                                }
330
 
331
                        case fInnerXml:
332
                                if !saveXML.IsValid() {
333
                                        saveXML = sv.FieldByIndex(finfo.idx)
334
                                        if p.saved == nil {
335
                                                saveXMLIndex = 0
336
                                                p.saved = new(bytes.Buffer)
337
                                        } else {
338
                                                saveXMLIndex = p.savedOffset()
339
                                        }
340
                                }
341
                        }
342
                }
343
        }
344
 
345
        // Find end element.
346
        // Process sub-elements along the way.
347
Loop:
348
        for {
349
                var savedOffset int
350
                if saveXML.IsValid() {
351
                        savedOffset = p.savedOffset()
352
                }
353
                tok, err := p.Token()
354
                if err != nil {
355
                        return err
356
                }
357
                switch t := tok.(type) {
358
                case StartElement:
359
                        consumed := false
360
                        if sv.IsValid() {
361
                                consumed, err = p.unmarshalPath(tinfo, sv, nil, &t)
362
                                if err != nil {
363
                                        return err
364
                                }
365
                                if !consumed && saveAny.IsValid() {
366
                                        consumed = true
367
                                        if err := p.unmarshal(saveAny, &t); err != nil {
368
                                                return err
369
                                        }
370
                                }
371
                        }
372
                        if !consumed {
373
                                if err := p.Skip(); err != nil {
374
                                        return err
375
                                }
376
                        }
377
 
378
                case EndElement:
379
                        if saveXML.IsValid() {
380
                                saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset]
381
                                if saveXMLIndex == 0 {
382
                                        p.saved = nil
383
                                }
384
                        }
385
                        break Loop
386
 
387
                case CharData:
388
                        if saveData.IsValid() {
389
                                data = append(data, t...)
390
                        }
391
 
392
                case Comment:
393
                        if saveComment.IsValid() {
394
                                comment = append(comment, t...)
395
                        }
396
                }
397
        }
398
 
399
        if err := copyValue(saveData, data); err != nil {
400
                return err
401
        }
402
 
403
        switch t := saveComment; t.Kind() {
404
        case reflect.String:
405
                t.SetString(string(comment))
406
        case reflect.Slice:
407
                t.Set(reflect.ValueOf(comment))
408
        }
409
 
410
        switch t := saveXML; t.Kind() {
411
        case reflect.String:
412
                t.SetString(string(saveXMLData))
413
        case reflect.Slice:
414
                t.Set(reflect.ValueOf(saveXMLData))
415
        }
416
 
417
        return nil
418
}
419
 
420
func copyValue(dst reflect.Value, src []byte) (err error) {
421
        // Helper functions for integer and unsigned integer conversions
422
        var itmp int64
423
        getInt64 := func() bool {
424
                itmp, err = strconv.ParseInt(string(src), 10, 64)
425
                // TODO: should check sizes
426
                return err == nil
427
        }
428
        var utmp uint64
429
        getUint64 := func() bool {
430
                utmp, err = strconv.ParseUint(string(src), 10, 64)
431
                // TODO: check for overflow?
432
                return err == nil
433
        }
434
        var ftmp float64
435
        getFloat64 := func() bool {
436
                ftmp, err = strconv.ParseFloat(string(src), 64)
437
                // TODO: check for overflow?
438
                return err == nil
439
        }
440
 
441
        // Save accumulated data.
442
        switch t := dst; t.Kind() {
443
        case reflect.Invalid:
444
                // Probably a comment.
445
        default:
446
                return errors.New("cannot happen: unknown type " + t.Type().String())
447
        case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
448
                if !getInt64() {
449
                        return err
450
                }
451
                t.SetInt(itmp)
452
        case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
453
                if !getUint64() {
454
                        return err
455
                }
456
                t.SetUint(utmp)
457
        case reflect.Float32, reflect.Float64:
458
                if !getFloat64() {
459
                        return err
460
                }
461
                t.SetFloat(ftmp)
462
        case reflect.Bool:
463
                value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
464
                if err != nil {
465
                        return err
466
                }
467
                t.SetBool(value)
468
        case reflect.String:
469
                t.SetString(string(src))
470
        case reflect.Slice:
471
                if len(src) == 0 {
472
                        // non-nil to flag presence
473
                        src = []byte{}
474
                }
475
                t.SetBytes(src)
476
        }
477
        return nil
478
}
479
 
480
// unmarshalPath walks down an XML structure looking for wanted
481
// paths, and calls unmarshal on them.
482
// The consumed result tells whether XML elements have been consumed
483
// from the Decoder until start's matching end element, or if it's
484
// still untouched because start is uninteresting for sv's fields.
485
func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
486
        recurse := false
487
Loop:
488
        for i := range tinfo.fields {
489
                finfo := &tinfo.fields[i]
490
                if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) {
491
                        continue
492
                }
493
                for j := range parents {
494
                        if parents[j] != finfo.parents[j] {
495
                                continue Loop
496
                        }
497
                }
498
                if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
499
                        // It's a perfect match, unmarshal the field.
500
                        return true, p.unmarshal(sv.FieldByIndex(finfo.idx), start)
501
                }
502
                if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
503
                        // It's a prefix for the field. Break and recurse
504
                        // since it's not ok for one field path to be itself
505
                        // the prefix for another field path.
506
                        recurse = true
507
 
508
                        // We can reuse the same slice as long as we
509
                        // don't try to append to it.
510
                        parents = finfo.parents[:len(parents)+1]
511
                        break
512
                }
513
        }
514
        if !recurse {
515
                // We have no business with this element.
516
                return false, nil
517
        }
518
        // The element is not a perfect match for any field, but one
519
        // or more fields have the path to this element as a parent
520
        // prefix. Recurse and attempt to match these.
521
        for {
522
                var tok Token
523
                tok, err = p.Token()
524
                if err != nil {
525
                        return true, err
526
                }
527
                switch t := tok.(type) {
528
                case StartElement:
529
                        consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t)
530
                        if err != nil {
531
                                return true, err
532
                        }
533
                        if !consumed2 {
534
                                if err := p.Skip(); err != nil {
535
                                        return true, err
536
                                }
537
                        }
538
                case EndElement:
539
                        return true, nil
540
                }
541
        }
542
        panic("unreachable")
543
}
544
 
545
// Skip reads tokens until it has consumed the end element
546
// matching the most recent start element already consumed.
547
// It recurs if it encounters a start element, so it can be used to
548
// skip nested structures.
549
// It returns nil if it finds an end element matching the start
550
// element; otherwise it returns an error describing the problem.
551
func (d *Decoder) Skip() error {
552
        for {
553
                tok, err := d.Token()
554
                if err != nil {
555
                        return err
556
                }
557
                switch tok.(type) {
558
                case StartElement:
559
                        if err := d.Skip(); err != nil {
560
                                return err
561
                        }
562
                case EndElement:
563
                        return nil
564
                }
565
        }
566
        panic("unreachable")
567
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.