14 documentNode = 1 << iota
28 anchors map[string]*node
31 // ----------------------------------------------------------------------------
32 // Parser, produces a node tree out of a libyaml event stream.
40 func newParser(b []byte) *parser {
42 if !yaml_parser_initialize(&p.parser) {
43 panic("failed to initialize YAML emitter")
50 yaml_parser_set_input_string(&p.parser, b)
53 if p.event.typ != yaml_STREAM_START_EVENT {
54 panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
60 func (p *parser) destroy() {
61 if p.event.typ != yaml_NO_EVENT {
62 yaml_event_delete(&p.event)
64 yaml_parser_delete(&p.parser)
67 func (p *parser) skip() {
68 if p.event.typ != yaml_NO_EVENT {
69 if p.event.typ == yaml_STREAM_END_EVENT {
70 failf("attempted to go past the end of stream; corrupted value?")
72 yaml_event_delete(&p.event)
74 if !yaml_parser_parse(&p.parser, &p.event) {
79 func (p *parser) fail() {
82 if p.parser.problem_mark.line != 0 {
83 line = p.parser.problem_mark.line
84 } else if p.parser.context_mark.line != 0 {
85 line = p.parser.context_mark.line
88 where = "line " + strconv.Itoa(line) + ": "
91 if len(p.parser.problem) > 0 {
92 msg = p.parser.problem
94 msg = "unknown problem parsing YAML content"
96 failf("%s%s", where, msg)
99 func (p *parser) anchor(n *node, anchor []byte) {
101 p.doc.anchors[string(anchor)] = n
105 func (p *parser) parse() *node {
107 case yaml_SCALAR_EVENT:
109 case yaml_ALIAS_EVENT:
111 case yaml_MAPPING_START_EVENT:
113 case yaml_SEQUENCE_START_EVENT:
115 case yaml_DOCUMENT_START_EVENT:
117 case yaml_STREAM_END_EVENT:
118 // Happens when attempting to decode an empty buffer.
121 panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ)))
125 func (p *parser) node(kind int) *node {
128 line: p.event.start_mark.line,
129 column: p.event.start_mark.column,
133 func (p *parser) document() *node {
134 n := p.node(documentNode)
135 n.anchors = make(map[string]*node)
138 n.children = append(n.children, p.parse())
139 if p.event.typ != yaml_DOCUMENT_END_EVENT {
140 panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ)))
146 func (p *parser) alias() *node {
147 n := p.node(aliasNode)
148 n.value = string(p.event.anchor)
153 func (p *parser) scalar() *node {
154 n := p.node(scalarNode)
155 n.value = string(p.event.value)
156 n.tag = string(p.event.tag)
157 n.implicit = p.event.implicit
158 p.anchor(n, p.event.anchor)
163 func (p *parser) sequence() *node {
164 n := p.node(sequenceNode)
165 p.anchor(n, p.event.anchor)
167 for p.event.typ != yaml_SEQUENCE_END_EVENT {
168 n.children = append(n.children, p.parse())
174 func (p *parser) mapping() *node {
175 n := p.node(mappingNode)
176 p.anchor(n, p.event.anchor)
178 for p.event.typ != yaml_MAPPING_END_EVENT {
179 n.children = append(n.children, p.parse(), p.parse())
185 // ----------------------------------------------------------------------------
186 // Decoder, unmarshals a node into a provided value.
188 type decoder struct {
190 aliases map[string]bool
196 mapItemType = reflect.TypeOf(MapItem{})
197 durationType = reflect.TypeOf(time.Duration(0))
198 defaultMapType = reflect.TypeOf(map[interface{}]interface{}{})
199 ifaceType = defaultMapType.Elem()
202 func newDecoder() *decoder {
203 d := &decoder{mapType: defaultMapType}
204 d.aliases = make(map[string]bool)
208 func (d *decoder) terror(n *node, tag string, out reflect.Value) {
213 if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG {
215 value = " `" + value[:7] + "...`"
217 value = " `" + value + "`"
220 d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type()))
223 func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) {
224 terrlen := len(d.terrors)
225 err := u.UnmarshalYAML(func(v interface{}) (err error) {
226 defer handleErr(&err)
227 d.unmarshal(n, reflect.ValueOf(v))
228 if len(d.terrors) > terrlen {
229 issues := d.terrors[terrlen:]
230 d.terrors = d.terrors[:terrlen]
231 return &TypeError{issues}
235 if e, ok := err.(*TypeError); ok {
236 d.terrors = append(d.terrors, e.Errors...)
245 // d.prepare initializes and dereferences pointers and calls UnmarshalYAML
246 // if a value is found to implement it.
247 // It returns the initialized and dereferenced out value, whether
248 // unmarshalling was already done by UnmarshalYAML, and if so whether
249 // its types unmarshalled appropriately.
251 // If n holds a null value, prepare returns before doing anything.
252 func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
253 if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "" && n.implicit) {
254 return out, false, false
259 if out.Kind() == reflect.Ptr {
261 out.Set(reflect.New(out.Type().Elem()))
267 if u, ok := out.Addr().Interface().(Unmarshaler); ok {
268 good = d.callUnmarshaler(n, u)
269 return out, true, good
273 return out, false, false
276 func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
279 return d.document(n, out)
281 return d.alias(n, out)
283 out, unmarshaled, good := d.prepare(n, out)
289 good = d.scalar(n, out)
291 good = d.mapping(n, out)
293 good = d.sequence(n, out)
295 panic("internal error: unknown node kind: " + strconv.Itoa(n.kind))
300 func (d *decoder) document(n *node, out reflect.Value) (good bool) {
301 if len(n.children) == 1 {
303 d.unmarshal(n.children[0], out)
309 func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
310 an, ok := d.doc.anchors[n.value]
312 failf("unknown anchor '%s' referenced", n.value)
314 if d.aliases[n.value] {
315 failf("anchor '%s' value contains itself", n.value)
317 d.aliases[n.value] = true
318 good = d.unmarshal(an, out)
319 delete(d.aliases, n.value)
323 var zeroValue reflect.Value
325 func resetMap(out reflect.Value) {
326 for _, k := range out.MapKeys() {
327 out.SetMapIndex(k, zeroValue)
331 func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
333 var resolved interface{}
334 if n.tag == "" && !n.implicit {
338 tag, resolved = resolve(n.tag, n.value)
339 if tag == yaml_BINARY_TAG {
340 data, err := base64.StdEncoding.DecodeString(resolved.(string))
342 failf("!!binary value contains invalid base64 data")
344 resolved = string(data)
348 if out.Kind() == reflect.Map && !out.CanAddr() {
351 out.Set(reflect.Zero(out.Type()))
355 if s, ok := resolved.(string); ok && out.CanAddr() {
356 if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok {
357 err := u.UnmarshalText([]byte(s))
366 if tag == yaml_BINARY_TAG {
367 out.SetString(resolved.(string))
369 } else if resolved != nil {
370 out.SetString(n.value)
373 case reflect.Interface:
375 out.Set(reflect.Zero(out.Type()))
377 out.Set(reflect.ValueOf(resolved))
380 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
381 switch resolved := resolved.(type) {
383 if !out.OverflowInt(int64(resolved)) {
384 out.SetInt(int64(resolved))
388 if !out.OverflowInt(resolved) {
393 if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
394 out.SetInt(int64(resolved))
398 if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
399 out.SetInt(int64(resolved))
403 if out.Type() == durationType {
404 d, err := time.ParseDuration(resolved)
411 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
412 switch resolved := resolved.(type) {
414 if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
415 out.SetUint(uint64(resolved))
419 if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
420 out.SetUint(uint64(resolved))
424 if !out.OverflowUint(uint64(resolved)) {
425 out.SetUint(uint64(resolved))
429 if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
430 out.SetUint(uint64(resolved))
435 switch resolved := resolved.(type) {
437 out.SetBool(resolved)
440 case reflect.Float32, reflect.Float64:
441 switch resolved := resolved.(type) {
443 out.SetFloat(float64(resolved))
446 out.SetFloat(float64(resolved))
449 out.SetFloat(float64(resolved))
452 out.SetFloat(resolved)
456 if out.Type().Elem() == reflect.TypeOf(resolved) {
457 // TODO DOes this make sense? When is out a Ptr except when decoding a nil value?
458 elem := reflect.New(out.Type().Elem())
459 elem.Elem().Set(reflect.ValueOf(resolved))
465 d.terror(n, tag, out)
470 func settableValueOf(i interface{}) reflect.Value {
471 v := reflect.ValueOf(i)
472 sv := reflect.New(v.Type()).Elem()
477 func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
480 var iface reflect.Value
483 out.Set(reflect.MakeSlice(out.Type(), l, l))
484 case reflect.Interface:
485 // No type hints. Will have to use a generic sequence.
487 out = settableValueOf(make([]interface{}, l))
489 d.terror(n, yaml_SEQ_TAG, out)
492 et := out.Type().Elem()
495 for i := 0; i < l; i++ {
496 e := reflect.New(et).Elem()
497 if ok := d.unmarshal(n.children[i], e); ok {
502 out.Set(out.Slice(0, j))
509 func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
512 return d.mappingStruct(n, out)
514 return d.mappingSlice(n, out)
517 case reflect.Interface:
518 if d.mapType.Kind() == reflect.Map {
520 out = reflect.MakeMap(d.mapType)
523 slicev := reflect.New(d.mapType).Elem()
524 if !d.mappingSlice(n, slicev) {
531 d.terror(n, yaml_MAP_TAG, out)
539 if outt.Key() == ifaceType && outt.Elem() == ifaceType {
544 out.Set(reflect.MakeMap(outt))
547 for i := 0; i < l; i += 2 {
548 if isMerge(n.children[i]) {
549 d.merge(n.children[i+1], out)
552 k := reflect.New(kt).Elem()
553 if d.unmarshal(n.children[i], k) {
555 if kkind == reflect.Interface {
556 kkind = k.Elem().Kind()
558 if kkind == reflect.Map || kkind == reflect.Slice {
559 failf("invalid map key: %#v", k.Interface())
561 e := reflect.New(et).Elem()
562 if d.unmarshal(n.children[i+1], e) {
563 out.SetMapIndex(k, e)
571 func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
573 if outt.Elem() != mapItemType {
574 d.terror(n, yaml_MAP_TAG, out)
582 var l = len(n.children)
583 for i := 0; i < l; i += 2 {
584 if isMerge(n.children[i]) {
585 d.merge(n.children[i+1], out)
589 k := reflect.ValueOf(&item.Key).Elem()
590 if d.unmarshal(n.children[i], k) {
591 v := reflect.ValueOf(&item.Value).Elem()
592 if d.unmarshal(n.children[i+1], v) {
593 slice = append(slice, item)
597 out.Set(reflect.ValueOf(slice))
602 func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
603 sinfo, err := getStructInfo(out.Type())
607 name := settableValueOf("")
610 var inlineMap reflect.Value
611 var elemType reflect.Type
612 if sinfo.InlineMap != -1 {
613 inlineMap = out.Field(sinfo.InlineMap)
614 inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
615 elemType = inlineMap.Type().Elem()
618 for i := 0; i < l; i += 2 {
621 d.merge(n.children[i+1], out)
624 if !d.unmarshal(ni, name) {
627 if info, ok := sinfo.FieldsMap[name.String()]; ok {
628 var field reflect.Value
629 if info.Inline == nil {
630 field = out.Field(info.Num)
632 field = out.FieldByIndex(info.Inline)
634 d.unmarshal(n.children[i+1], field)
635 } else if sinfo.InlineMap != -1 {
636 if inlineMap.IsNil() {
637 inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
639 value := reflect.New(elemType).Elem()
640 d.unmarshal(n.children[i+1], value)
641 inlineMap.SetMapIndex(name, value)
648 failf("map merge requires map or sequence of maps as the value")
651 func (d *decoder) merge(n *node, out reflect.Value) {
656 an, ok := d.doc.anchors[n.value]
657 if ok && an.kind != mappingNode {
662 // Step backwards as earlier nodes take precedence.
663 for i := len(n.children) - 1; i >= 0; i-- {
665 if ni.kind == aliasNode {
666 an, ok := d.doc.anchors[ni.value]
667 if ok && an.kind != mappingNode {
670 } else if ni.kind != mappingNode {
680 func isMerge(n *node) bool {
681 return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG)