decode.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. package yaml
  2. import (
  3. "encoding"
  4. "encoding/base64"
  5. "fmt"
  6. "io"
  7. "math"
  8. "reflect"
  9. "strconv"
  10. "time"
  11. )
  12. const (
  13. documentNode = 1 << iota
  14. mappingNode
  15. sequenceNode
  16. scalarNode
  17. aliasNode
  18. )
  19. type node struct {
  20. kind int
  21. line, column int
  22. tag string
  23. // For an alias node, alias holds the resolved alias.
  24. alias *node
  25. value string
  26. implicit bool
  27. children []*node
  28. anchors map[string]*node
  29. }
  30. // ----------------------------------------------------------------------------
  31. // Parser, produces a node tree out of a libyaml event stream.
  32. type parser struct {
  33. parser yaml_parser_t
  34. event yaml_event_t
  35. doc *node
  36. doneInit bool
  37. }
  38. func newParser(b []byte) *parser {
  39. p := parser{}
  40. if !yaml_parser_initialize(&p.parser) {
  41. panic("failed to initialize YAML emitter")
  42. }
  43. if len(b) == 0 {
  44. b = []byte{'\n'}
  45. }
  46. yaml_parser_set_input_string(&p.parser, b)
  47. return &p
  48. }
  49. func newParserFromReader(r io.Reader) *parser {
  50. p := parser{}
  51. if !yaml_parser_initialize(&p.parser) {
  52. panic("failed to initialize YAML emitter")
  53. }
  54. yaml_parser_set_input_reader(&p.parser, r)
  55. return &p
  56. }
  57. func (p *parser) init() {
  58. if p.doneInit {
  59. return
  60. }
  61. p.expect(yaml_STREAM_START_EVENT)
  62. p.doneInit = true
  63. }
  64. func (p *parser) destroy() {
  65. if p.event.typ != yaml_NO_EVENT {
  66. yaml_event_delete(&p.event)
  67. }
  68. yaml_parser_delete(&p.parser)
  69. }
  70. // expect consumes an event from the event stream and
  71. // checks that it's of the expected type.
  72. func (p *parser) expect(e yaml_event_type_t) {
  73. if p.event.typ == yaml_NO_EVENT {
  74. if !yaml_parser_parse(&p.parser, &p.event) {
  75. p.fail()
  76. }
  77. }
  78. if p.event.typ == yaml_STREAM_END_EVENT {
  79. failf("attempted to go past the end of stream; corrupted value?")
  80. }
  81. if p.event.typ != e {
  82. p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ)
  83. p.fail()
  84. }
  85. yaml_event_delete(&p.event)
  86. p.event.typ = yaml_NO_EVENT
  87. }
  88. // peek peeks at the next event in the event stream,
  89. // puts the results into p.event and returns the event type.
  90. func (p *parser) peek() yaml_event_type_t {
  91. if p.event.typ != yaml_NO_EVENT {
  92. return p.event.typ
  93. }
  94. if !yaml_parser_parse(&p.parser, &p.event) {
  95. p.fail()
  96. }
  97. return p.event.typ
  98. }
  99. func (p *parser) fail() {
  100. var where string
  101. var line int
  102. if p.parser.problem_mark.line != 0 {
  103. line = p.parser.problem_mark.line
  104. } else if p.parser.context_mark.line != 0 {
  105. line = p.parser.context_mark.line
  106. }
  107. if line != 0 {
  108. where = "line " + strconv.Itoa(line) + ": "
  109. }
  110. var msg string
  111. if len(p.parser.problem) > 0 {
  112. msg = p.parser.problem
  113. } else {
  114. msg = "unknown problem parsing YAML content"
  115. }
  116. failf("%s%s", where, msg)
  117. }
  118. func (p *parser) anchor(n *node, anchor []byte) {
  119. if anchor != nil {
  120. p.doc.anchors[string(anchor)] = n
  121. }
  122. }
  123. func (p *parser) parse() *node {
  124. p.init()
  125. switch p.peek() {
  126. case yaml_SCALAR_EVENT:
  127. return p.scalar()
  128. case yaml_ALIAS_EVENT:
  129. return p.alias()
  130. case yaml_MAPPING_START_EVENT:
  131. return p.mapping()
  132. case yaml_SEQUENCE_START_EVENT:
  133. return p.sequence()
  134. case yaml_DOCUMENT_START_EVENT:
  135. return p.document()
  136. case yaml_STREAM_END_EVENT:
  137. // Happens when attempting to decode an empty buffer.
  138. return nil
  139. default:
  140. panic("attempted to parse unknown event: " + p.event.typ.String())
  141. }
  142. }
  143. func (p *parser) node(kind int) *node {
  144. return &node{
  145. kind: kind,
  146. line: p.event.start_mark.line,
  147. column: p.event.start_mark.column,
  148. }
  149. }
  150. func (p *parser) document() *node {
  151. n := p.node(documentNode)
  152. n.anchors = make(map[string]*node)
  153. p.doc = n
  154. p.expect(yaml_DOCUMENT_START_EVENT)
  155. n.children = append(n.children, p.parse())
  156. p.expect(yaml_DOCUMENT_END_EVENT)
  157. return n
  158. }
  159. func (p *parser) alias() *node {
  160. n := p.node(aliasNode)
  161. n.value = string(p.event.anchor)
  162. n.alias = p.doc.anchors[n.value]
  163. if n.alias == nil {
  164. failf("unknown anchor '%s' referenced", n.value)
  165. }
  166. p.expect(yaml_ALIAS_EVENT)
  167. return n
  168. }
  169. func (p *parser) scalar() *node {
  170. n := p.node(scalarNode)
  171. n.value = string(p.event.value)
  172. n.tag = string(p.event.tag)
  173. n.implicit = p.event.implicit
  174. p.anchor(n, p.event.anchor)
  175. p.expect(yaml_SCALAR_EVENT)
  176. return n
  177. }
  178. func (p *parser) sequence() *node {
  179. n := p.node(sequenceNode)
  180. p.anchor(n, p.event.anchor)
  181. p.expect(yaml_SEQUENCE_START_EVENT)
  182. for p.peek() != yaml_SEQUENCE_END_EVENT {
  183. n.children = append(n.children, p.parse())
  184. }
  185. p.expect(yaml_SEQUENCE_END_EVENT)
  186. return n
  187. }
  188. func (p *parser) mapping() *node {
  189. n := p.node(mappingNode)
  190. p.anchor(n, p.event.anchor)
  191. p.expect(yaml_MAPPING_START_EVENT)
  192. for p.peek() != yaml_MAPPING_END_EVENT {
  193. n.children = append(n.children, p.parse(), p.parse())
  194. }
  195. p.expect(yaml_MAPPING_END_EVENT)
  196. return n
  197. }
  198. // ----------------------------------------------------------------------------
  199. // Decoder, unmarshals a node into a provided value.
  200. type decoder struct {
  201. doc *node
  202. aliases map[*node]bool
  203. mapType reflect.Type
  204. terrors []string
  205. strict bool
  206. }
  207. var (
  208. mapItemType = reflect.TypeOf(MapItem{})
  209. durationType = reflect.TypeOf(time.Duration(0))
  210. defaultMapType = reflect.TypeOf(map[interface{}]interface{}{})
  211. ifaceType = defaultMapType.Elem()
  212. timeType = reflect.TypeOf(time.Time{})
  213. ptrTimeType = reflect.TypeOf(&time.Time{})
  214. )
  215. func newDecoder(strict bool) *decoder {
  216. d := &decoder{mapType: defaultMapType, strict: strict}
  217. d.aliases = make(map[*node]bool)
  218. return d
  219. }
  220. func (d *decoder) terror(n *node, tag string, out reflect.Value) {
  221. if n.tag != "" {
  222. tag = n.tag
  223. }
  224. value := n.value
  225. if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG {
  226. if len(value) > 10 {
  227. value = " `" + value[:7] + "...`"
  228. } else {
  229. value = " `" + value + "`"
  230. }
  231. }
  232. d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type()))
  233. }
  234. func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) {
  235. terrlen := len(d.terrors)
  236. err := u.UnmarshalYAML(func(v interface{}) (err error) {
  237. defer handleErr(&err)
  238. d.unmarshal(n, reflect.ValueOf(v))
  239. if len(d.terrors) > terrlen {
  240. issues := d.terrors[terrlen:]
  241. d.terrors = d.terrors[:terrlen]
  242. return &TypeError{issues}
  243. }
  244. return nil
  245. })
  246. if e, ok := err.(*TypeError); ok {
  247. d.terrors = append(d.terrors, e.Errors...)
  248. return false
  249. }
  250. if err != nil {
  251. fail(err)
  252. }
  253. return true
  254. }
  255. // d.prepare initializes and dereferences pointers and calls UnmarshalYAML
  256. // if a value is found to implement it.
  257. // It returns the initialized and dereferenced out value, whether
  258. // unmarshalling was already done by UnmarshalYAML, and if so whether
  259. // its types unmarshalled appropriately.
  260. //
  261. // If n holds a null value, prepare returns before doing anything.
  262. func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
  263. if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) {
  264. return out, false, false
  265. }
  266. again := true
  267. for again {
  268. again = false
  269. if out.Kind() == reflect.Ptr {
  270. if out.IsNil() {
  271. out.Set(reflect.New(out.Type().Elem()))
  272. }
  273. out = out.Elem()
  274. again = true
  275. }
  276. if out.CanAddr() {
  277. if u, ok := out.Addr().Interface().(Unmarshaler); ok {
  278. good = d.callUnmarshaler(n, u)
  279. return out, true, good
  280. }
  281. }
  282. }
  283. return out, false, false
  284. }
  285. func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
  286. switch n.kind {
  287. case documentNode:
  288. return d.document(n, out)
  289. case aliasNode:
  290. return d.alias(n, out)
  291. }
  292. out, unmarshaled, good := d.prepare(n, out)
  293. if unmarshaled {
  294. return good
  295. }
  296. switch n.kind {
  297. case scalarNode:
  298. good = d.scalar(n, out)
  299. case mappingNode:
  300. good = d.mapping(n, out)
  301. case sequenceNode:
  302. good = d.sequence(n, out)
  303. default:
  304. panic("internal error: unknown node kind: " + strconv.Itoa(n.kind))
  305. }
  306. return good
  307. }
  308. func (d *decoder) document(n *node, out reflect.Value) (good bool) {
  309. if len(n.children) == 1 {
  310. d.doc = n
  311. d.unmarshal(n.children[0], out)
  312. return true
  313. }
  314. return false
  315. }
  316. func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
  317. if d.aliases[n] {
  318. // TODO this could actually be allowed in some circumstances.
  319. failf("anchor '%s' value contains itself", n.value)
  320. }
  321. d.aliases[n] = true
  322. good = d.unmarshal(n.alias, out)
  323. delete(d.aliases, n)
  324. return good
  325. }
  326. var zeroValue reflect.Value
  327. func resetMap(out reflect.Value) {
  328. for _, k := range out.MapKeys() {
  329. out.SetMapIndex(k, zeroValue)
  330. }
  331. }
  332. func (d *decoder) scalar(n *node, out reflect.Value) bool {
  333. var tag string
  334. var resolved interface{}
  335. if n.tag == "" && !n.implicit {
  336. tag = yaml_STR_TAG
  337. resolved = n.value
  338. } else {
  339. tag, resolved = resolve(n.tag, n.value)
  340. if tag == yaml_BINARY_TAG {
  341. data, err := base64.StdEncoding.DecodeString(resolved.(string))
  342. if err != nil {
  343. failf("!!binary value contains invalid base64 data")
  344. }
  345. resolved = string(data)
  346. }
  347. }
  348. if resolved == nil {
  349. if out.Kind() == reflect.Map && !out.CanAddr() {
  350. resetMap(out)
  351. } else {
  352. out.Set(reflect.Zero(out.Type()))
  353. }
  354. return true
  355. }
  356. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  357. // We've resolved to exactly the type we want, so use that.
  358. out.Set(resolvedv)
  359. return true
  360. }
  361. // Perhaps we can use the value as a TextUnmarshaler to
  362. // set its value.
  363. if out.CanAddr() {
  364. u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
  365. if ok {
  366. var text []byte
  367. if tag == yaml_BINARY_TAG {
  368. text = []byte(resolved.(string))
  369. } else {
  370. // We let any value be unmarshaled into TextUnmarshaler.
  371. // That might be more lax than we'd like, but the
  372. // TextUnmarshaler itself should bowl out any dubious values.
  373. text = []byte(n.value)
  374. }
  375. err := u.UnmarshalText(text)
  376. if err != nil {
  377. fail(err)
  378. }
  379. return true
  380. }
  381. }
  382. switch out.Kind() {
  383. case reflect.String:
  384. if tag == yaml_BINARY_TAG {
  385. out.SetString(resolved.(string))
  386. return true
  387. }
  388. if resolved != nil {
  389. out.SetString(n.value)
  390. return true
  391. }
  392. case reflect.Interface:
  393. if resolved == nil {
  394. out.Set(reflect.Zero(out.Type()))
  395. } else if tag == yaml_TIMESTAMP_TAG {
  396. // It looks like a timestamp but for backward compatibility
  397. // reasons we set it as a string, so that code that unmarshals
  398. // timestamp-like values into interface{} will continue to
  399. // see a string and not a time.Time.
  400. out.Set(reflect.ValueOf(n.value))
  401. } else {
  402. out.Set(reflect.ValueOf(resolved))
  403. }
  404. return true
  405. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  406. switch resolved := resolved.(type) {
  407. case int:
  408. if !out.OverflowInt(int64(resolved)) {
  409. out.SetInt(int64(resolved))
  410. return true
  411. }
  412. case int64:
  413. if !out.OverflowInt(resolved) {
  414. out.SetInt(resolved)
  415. return true
  416. }
  417. case uint64:
  418. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  419. out.SetInt(int64(resolved))
  420. return true
  421. }
  422. case float64:
  423. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  424. out.SetInt(int64(resolved))
  425. return true
  426. }
  427. case string:
  428. if out.Type() == durationType {
  429. d, err := time.ParseDuration(resolved)
  430. if err == nil {
  431. out.SetInt(int64(d))
  432. return true
  433. }
  434. }
  435. }
  436. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  437. switch resolved := resolved.(type) {
  438. case int:
  439. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  440. out.SetUint(uint64(resolved))
  441. return true
  442. }
  443. case int64:
  444. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  445. out.SetUint(uint64(resolved))
  446. return true
  447. }
  448. case uint64:
  449. if !out.OverflowUint(uint64(resolved)) {
  450. out.SetUint(uint64(resolved))
  451. return true
  452. }
  453. case float64:
  454. if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
  455. out.SetUint(uint64(resolved))
  456. return true
  457. }
  458. }
  459. case reflect.Bool:
  460. switch resolved := resolved.(type) {
  461. case bool:
  462. out.SetBool(resolved)
  463. return true
  464. }
  465. case reflect.Float32, reflect.Float64:
  466. switch resolved := resolved.(type) {
  467. case int:
  468. out.SetFloat(float64(resolved))
  469. return true
  470. case int64:
  471. out.SetFloat(float64(resolved))
  472. return true
  473. case uint64:
  474. out.SetFloat(float64(resolved))
  475. return true
  476. case float64:
  477. out.SetFloat(resolved)
  478. return true
  479. }
  480. case reflect.Struct:
  481. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  482. out.Set(resolvedv)
  483. return true
  484. }
  485. case reflect.Ptr:
  486. if out.Type().Elem() == reflect.TypeOf(resolved) {
  487. // TODO DOes this make sense? When is out a Ptr except when decoding a nil value?
  488. elem := reflect.New(out.Type().Elem())
  489. elem.Elem().Set(reflect.ValueOf(resolved))
  490. out.Set(elem)
  491. return true
  492. }
  493. }
  494. d.terror(n, tag, out)
  495. return false
  496. }
  497. func settableValueOf(i interface{}) reflect.Value {
  498. v := reflect.ValueOf(i)
  499. sv := reflect.New(v.Type()).Elem()
  500. sv.Set(v)
  501. return sv
  502. }
  503. func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
  504. l := len(n.children)
  505. var iface reflect.Value
  506. switch out.Kind() {
  507. case reflect.Slice:
  508. out.Set(reflect.MakeSlice(out.Type(), l, l))
  509. case reflect.Interface:
  510. // No type hints. Will have to use a generic sequence.
  511. iface = out
  512. out = settableValueOf(make([]interface{}, l))
  513. default:
  514. d.terror(n, yaml_SEQ_TAG, out)
  515. return false
  516. }
  517. et := out.Type().Elem()
  518. j := 0
  519. for i := 0; i < l; i++ {
  520. e := reflect.New(et).Elem()
  521. if ok := d.unmarshal(n.children[i], e); ok {
  522. out.Index(j).Set(e)
  523. j++
  524. }
  525. }
  526. out.Set(out.Slice(0, j))
  527. if iface.IsValid() {
  528. iface.Set(out)
  529. }
  530. return true
  531. }
  532. func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
  533. switch out.Kind() {
  534. case reflect.Struct:
  535. return d.mappingStruct(n, out)
  536. case reflect.Slice:
  537. return d.mappingSlice(n, out)
  538. case reflect.Map:
  539. // okay
  540. case reflect.Interface:
  541. if d.mapType.Kind() == reflect.Map {
  542. iface := out
  543. out = reflect.MakeMap(d.mapType)
  544. iface.Set(out)
  545. } else {
  546. slicev := reflect.New(d.mapType).Elem()
  547. if !d.mappingSlice(n, slicev) {
  548. return false
  549. }
  550. out.Set(slicev)
  551. return true
  552. }
  553. default:
  554. d.terror(n, yaml_MAP_TAG, out)
  555. return false
  556. }
  557. outt := out.Type()
  558. kt := outt.Key()
  559. et := outt.Elem()
  560. mapType := d.mapType
  561. if outt.Key() == ifaceType && outt.Elem() == ifaceType {
  562. d.mapType = outt
  563. }
  564. if out.IsNil() {
  565. out.Set(reflect.MakeMap(outt))
  566. }
  567. l := len(n.children)
  568. for i := 0; i < l; i += 2 {
  569. if isMerge(n.children[i]) {
  570. d.merge(n.children[i+1], out)
  571. continue
  572. }
  573. k := reflect.New(kt).Elem()
  574. if d.unmarshal(n.children[i], k) {
  575. kkind := k.Kind()
  576. if kkind == reflect.Interface {
  577. kkind = k.Elem().Kind()
  578. }
  579. if kkind == reflect.Map || kkind == reflect.Slice {
  580. failf("invalid map key: %#v", k.Interface())
  581. }
  582. e := reflect.New(et).Elem()
  583. if d.unmarshal(n.children[i+1], e) {
  584. d.setMapIndex(n.children[i+1], out, k, e)
  585. }
  586. }
  587. }
  588. d.mapType = mapType
  589. return true
  590. }
  591. func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) {
  592. if d.strict && out.MapIndex(k) != zeroValue {
  593. d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface()))
  594. return
  595. }
  596. out.SetMapIndex(k, v)
  597. }
  598. func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
  599. outt := out.Type()
  600. if outt.Elem() != mapItemType {
  601. d.terror(n, yaml_MAP_TAG, out)
  602. return false
  603. }
  604. mapType := d.mapType
  605. d.mapType = outt
  606. var slice []MapItem
  607. var l = len(n.children)
  608. for i := 0; i < l; i += 2 {
  609. if isMerge(n.children[i]) {
  610. d.merge(n.children[i+1], out)
  611. continue
  612. }
  613. item := MapItem{}
  614. k := reflect.ValueOf(&item.Key).Elem()
  615. if d.unmarshal(n.children[i], k) {
  616. v := reflect.ValueOf(&item.Value).Elem()
  617. if d.unmarshal(n.children[i+1], v) {
  618. slice = append(slice, item)
  619. }
  620. }
  621. }
  622. out.Set(reflect.ValueOf(slice))
  623. d.mapType = mapType
  624. return true
  625. }
  626. func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
  627. sinfo, err := getStructInfo(out.Type())
  628. if err != nil {
  629. panic(err)
  630. }
  631. name := settableValueOf("")
  632. l := len(n.children)
  633. var inlineMap reflect.Value
  634. var elemType reflect.Type
  635. if sinfo.InlineMap != -1 {
  636. inlineMap = out.Field(sinfo.InlineMap)
  637. inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
  638. elemType = inlineMap.Type().Elem()
  639. }
  640. var doneFields []bool
  641. if d.strict {
  642. doneFields = make([]bool, len(sinfo.FieldsList))
  643. }
  644. for i := 0; i < l; i += 2 {
  645. ni := n.children[i]
  646. if isMerge(ni) {
  647. d.merge(n.children[i+1], out)
  648. continue
  649. }
  650. if !d.unmarshal(ni, name) {
  651. continue
  652. }
  653. if info, ok := sinfo.FieldsMap[name.String()]; ok {
  654. if d.strict {
  655. if doneFields[info.Id] {
  656. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type()))
  657. continue
  658. }
  659. doneFields[info.Id] = true
  660. }
  661. var field reflect.Value
  662. if info.Inline == nil {
  663. field = out.Field(info.Num)
  664. } else {
  665. field = out.FieldByIndex(info.Inline)
  666. }
  667. d.unmarshal(n.children[i+1], field)
  668. } else if sinfo.InlineMap != -1 {
  669. if inlineMap.IsNil() {
  670. inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
  671. }
  672. value := reflect.New(elemType).Elem()
  673. d.unmarshal(n.children[i+1], value)
  674. d.setMapIndex(n.children[i+1], inlineMap, name, value)
  675. } else if d.strict {
  676. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type()))
  677. }
  678. }
  679. return true
  680. }
  681. func failWantMap() {
  682. failf("map merge requires map or sequence of maps as the value")
  683. }
  684. func (d *decoder) merge(n *node, out reflect.Value) {
  685. switch n.kind {
  686. case mappingNode:
  687. d.unmarshal(n, out)
  688. case aliasNode:
  689. an, ok := d.doc.anchors[n.value]
  690. if ok && an.kind != mappingNode {
  691. failWantMap()
  692. }
  693. d.unmarshal(n, out)
  694. case sequenceNode:
  695. // Step backwards as earlier nodes take precedence.
  696. for i := len(n.children) - 1; i >= 0; i-- {
  697. ni := n.children[i]
  698. if ni.kind == aliasNode {
  699. an, ok := d.doc.anchors[ni.value]
  700. if ok && an.kind != mappingNode {
  701. failWantMap()
  702. }
  703. } else if ni.kind != mappingNode {
  704. failWantMap()
  705. }
  706. d.unmarshal(ni, out)
  707. }
  708. default:
  709. failWantMap()
  710. }
  711. }
  712. func isMerge(n *node) bool {
  713. return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG)
  714. }