decode.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. mergeTagType = reflect.TypeOf(MergeTag)
  215. )
  216. func newDecoder(strict bool) *decoder {
  217. d := &decoder{mapType: defaultMapType, strict: strict}
  218. d.aliases = make(map[*node]bool)
  219. return d
  220. }
  221. func (d *decoder) terror(n *node, tag string, out reflect.Value) {
  222. if n.tag != "" {
  223. tag = n.tag
  224. }
  225. value := n.value
  226. if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG {
  227. if len(value) > 10 {
  228. value = " `" + value[:7] + "...`"
  229. } else {
  230. value = " `" + value + "`"
  231. }
  232. }
  233. d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type()))
  234. }
  235. func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) {
  236. terrlen := len(d.terrors)
  237. err := u.UnmarshalYAML(func(v interface{}) (err error) {
  238. defer handleErr(&err)
  239. d.unmarshal(n, reflect.ValueOf(v))
  240. if len(d.terrors) > terrlen {
  241. issues := d.terrors[terrlen:]
  242. d.terrors = d.terrors[:terrlen]
  243. return &TypeError{issues}
  244. }
  245. return nil
  246. })
  247. if e, ok := err.(*TypeError); ok {
  248. d.terrors = append(d.terrors, e.Errors...)
  249. return false
  250. }
  251. if err != nil {
  252. fail(err)
  253. }
  254. return true
  255. }
  256. // d.prepare initializes and dereferences pointers and calls UnmarshalYAML
  257. // if a value is found to implement it.
  258. // It returns the initialized and dereferenced out value, whether
  259. // unmarshalling was already done by UnmarshalYAML, and if so whether
  260. // its types unmarshalled appropriately.
  261. //
  262. // If n holds a null value, prepare returns before doing anything.
  263. func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
  264. if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) {
  265. return out, false, false
  266. }
  267. again := true
  268. for again {
  269. again = false
  270. if out.Kind() == reflect.Ptr {
  271. if out.IsNil() {
  272. out.Set(reflect.New(out.Type().Elem()))
  273. }
  274. out = out.Elem()
  275. again = true
  276. }
  277. if out.CanAddr() {
  278. if u, ok := out.Addr().Interface().(Unmarshaler); ok {
  279. good = d.callUnmarshaler(n, u)
  280. return out, true, good
  281. }
  282. }
  283. }
  284. return out, false, false
  285. }
  286. func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
  287. switch n.kind {
  288. case documentNode:
  289. return d.document(n, out)
  290. case aliasNode:
  291. return d.alias(n, out)
  292. }
  293. out, unmarshaled, good := d.prepare(n, out)
  294. if unmarshaled {
  295. return good
  296. }
  297. switch n.kind {
  298. case scalarNode:
  299. good = d.scalar(n, out)
  300. case mappingNode:
  301. good = d.mapping(n, out)
  302. case sequenceNode:
  303. good = d.sequence(n, out)
  304. default:
  305. panic("internal error: unknown node kind: " + strconv.Itoa(n.kind))
  306. }
  307. return good
  308. }
  309. func (d *decoder) document(n *node, out reflect.Value) (good bool) {
  310. if len(n.children) == 1 {
  311. d.doc = n
  312. d.unmarshal(n.children[0], out)
  313. return true
  314. }
  315. return false
  316. }
  317. func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
  318. if d.aliases[n] {
  319. // TODO this could actually be allowed in some circumstances.
  320. failf("anchor '%s' value contains itself", n.value)
  321. }
  322. d.aliases[n] = true
  323. good = d.unmarshal(n.alias, out)
  324. delete(d.aliases, n)
  325. return good
  326. }
  327. var zeroValue reflect.Value
  328. func resetMap(out reflect.Value) {
  329. for _, k := range out.MapKeys() {
  330. out.SetMapIndex(k, zeroValue)
  331. }
  332. }
  333. func (d *decoder) scalar(n *node, out reflect.Value) bool {
  334. var tag string
  335. var resolved interface{}
  336. if n.tag == "" && !n.implicit {
  337. tag = yaml_STR_TAG
  338. resolved = n.value
  339. } else {
  340. tag, resolved = resolve(n.tag, n.value)
  341. if tag == yaml_BINARY_TAG {
  342. data, err := base64.StdEncoding.DecodeString(resolved.(string))
  343. if err != nil {
  344. failf("!!binary value contains invalid base64 data")
  345. }
  346. resolved = string(data)
  347. }
  348. }
  349. if resolved == nil {
  350. if out.Kind() == reflect.Map && !out.CanAddr() {
  351. resetMap(out)
  352. } else {
  353. out.Set(reflect.Zero(out.Type()))
  354. }
  355. return true
  356. }
  357. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  358. // We've resolved to exactly the type we want, so use that.
  359. out.Set(resolvedv)
  360. return true
  361. }
  362. // Perhaps we can use the value as a TextUnmarshaler to
  363. // set its value.
  364. if out.CanAddr() {
  365. u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
  366. if ok {
  367. var text []byte
  368. if tag == yaml_BINARY_TAG {
  369. text = []byte(resolved.(string))
  370. } else {
  371. // We let any value be unmarshaled into TextUnmarshaler.
  372. // That might be more lax than we'd like, but the
  373. // TextUnmarshaler itself should bowl out any dubious values.
  374. text = []byte(n.value)
  375. }
  376. err := u.UnmarshalText(text)
  377. if err != nil {
  378. fail(err)
  379. }
  380. return true
  381. }
  382. }
  383. switch out.Kind() {
  384. case reflect.String:
  385. if tag == yaml_BINARY_TAG {
  386. out.SetString(resolved.(string))
  387. return true
  388. }
  389. if resolved != nil {
  390. out.SetString(n.value)
  391. return true
  392. }
  393. case reflect.Interface:
  394. if resolved == nil {
  395. out.Set(reflect.Zero(out.Type()))
  396. } else if tag == yaml_TIMESTAMP_TAG {
  397. // It looks like a timestamp but for backward compatibility
  398. // reasons we set it as a string, so that code that unmarshals
  399. // timestamp-like values into interface{} will continue to
  400. // see a string and not a time.Time.
  401. out.Set(reflect.ValueOf(n.value))
  402. } else {
  403. out.Set(reflect.ValueOf(resolved))
  404. }
  405. return true
  406. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  407. switch resolved := resolved.(type) {
  408. case int:
  409. if !out.OverflowInt(int64(resolved)) {
  410. out.SetInt(int64(resolved))
  411. return true
  412. }
  413. case int64:
  414. if !out.OverflowInt(resolved) {
  415. out.SetInt(resolved)
  416. return true
  417. }
  418. case uint64:
  419. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  420. out.SetInt(int64(resolved))
  421. return true
  422. }
  423. case float64:
  424. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  425. out.SetInt(int64(resolved))
  426. return true
  427. }
  428. case string:
  429. if out.Type() == durationType {
  430. d, err := time.ParseDuration(resolved)
  431. if err == nil {
  432. out.SetInt(int64(d))
  433. return true
  434. }
  435. }
  436. }
  437. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  438. switch resolved := resolved.(type) {
  439. case int:
  440. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  441. out.SetUint(uint64(resolved))
  442. return true
  443. }
  444. case int64:
  445. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  446. out.SetUint(uint64(resolved))
  447. return true
  448. }
  449. case uint64:
  450. if !out.OverflowUint(uint64(resolved)) {
  451. out.SetUint(uint64(resolved))
  452. return true
  453. }
  454. case float64:
  455. if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
  456. out.SetUint(uint64(resolved))
  457. return true
  458. }
  459. }
  460. case reflect.Bool:
  461. switch resolved := resolved.(type) {
  462. case bool:
  463. out.SetBool(resolved)
  464. return true
  465. }
  466. case reflect.Float32, reflect.Float64:
  467. switch resolved := resolved.(type) {
  468. case int:
  469. out.SetFloat(float64(resolved))
  470. return true
  471. case int64:
  472. out.SetFloat(float64(resolved))
  473. return true
  474. case uint64:
  475. out.SetFloat(float64(resolved))
  476. return true
  477. case float64:
  478. out.SetFloat(resolved)
  479. return true
  480. }
  481. case reflect.Struct:
  482. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  483. out.Set(resolvedv)
  484. return true
  485. }
  486. case reflect.Ptr:
  487. if out.Type().Elem() == reflect.TypeOf(resolved) {
  488. // TODO DOes this make sense? When is out a Ptr except when decoding a nil value?
  489. elem := reflect.New(out.Type().Elem())
  490. elem.Elem().Set(reflect.ValueOf(resolved))
  491. out.Set(elem)
  492. return true
  493. }
  494. }
  495. d.terror(n, tag, out)
  496. return false
  497. }
  498. func settableValueOf(i interface{}) reflect.Value {
  499. v := reflect.ValueOf(i)
  500. sv := reflect.New(v.Type()).Elem()
  501. sv.Set(v)
  502. return sv
  503. }
  504. func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
  505. l := len(n.children)
  506. var iface reflect.Value
  507. switch out.Kind() {
  508. case reflect.Slice:
  509. out.Set(reflect.MakeSlice(out.Type(), l, l))
  510. case reflect.Interface:
  511. // No type hints. Will have to use a generic sequence.
  512. iface = out
  513. out = settableValueOf(make([]interface{}, l))
  514. default:
  515. d.terror(n, yaml_SEQ_TAG, out)
  516. return false
  517. }
  518. et := out.Type().Elem()
  519. j := 0
  520. for i := 0; i < l; i++ {
  521. e := reflect.New(et).Elem()
  522. if ok := d.unmarshal(n.children[i], e); ok {
  523. out.Index(j).Set(e)
  524. j++
  525. }
  526. }
  527. out.Set(out.Slice(0, j))
  528. if iface.IsValid() {
  529. iface.Set(out)
  530. }
  531. return true
  532. }
  533. func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
  534. switch out.Kind() {
  535. case reflect.Struct:
  536. return d.mappingStruct(n, out)
  537. case reflect.Slice:
  538. return d.mappingSlice(n, out)
  539. case reflect.Map:
  540. // okay
  541. case reflect.Interface:
  542. if d.mapType.Kind() == reflect.Map {
  543. iface := out
  544. out = reflect.MakeMap(d.mapType)
  545. iface.Set(out)
  546. } else {
  547. slicev := reflect.New(d.mapType).Elem()
  548. if !d.mappingSlice(n, slicev) {
  549. return false
  550. }
  551. out.Set(slicev)
  552. return true
  553. }
  554. default:
  555. d.terror(n, yaml_MAP_TAG, out)
  556. return false
  557. }
  558. outt := out.Type()
  559. kt := outt.Key()
  560. et := outt.Elem()
  561. mapType := d.mapType
  562. if outt.Key() == ifaceType && outt.Elem() == ifaceType {
  563. d.mapType = outt
  564. }
  565. if out.IsNil() {
  566. out.Set(reflect.MakeMap(outt))
  567. }
  568. l := len(n.children)
  569. for i := 0; i < l; i += 2 {
  570. if isMerge(n.children[i]) {
  571. d.merge(n.children[i+1], out)
  572. continue
  573. }
  574. k := reflect.New(kt).Elem()
  575. if d.unmarshal(n.children[i], k) {
  576. kkind := k.Kind()
  577. if kkind == reflect.Interface {
  578. kkind = k.Elem().Kind()
  579. }
  580. if kkind == reflect.Map || kkind == reflect.Slice {
  581. failf("invalid map key: %#v", k.Interface())
  582. }
  583. e := reflect.New(et).Elem()
  584. if d.unmarshal(n.children[i+1], e) {
  585. d.setMapIndex(n.children[i+1], out, k, e)
  586. }
  587. }
  588. }
  589. d.mapType = mapType
  590. return true
  591. }
  592. func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) {
  593. if d.strict && out.MapIndex(k) != zeroValue {
  594. d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface()))
  595. return
  596. }
  597. out.SetMapIndex(k, v)
  598. }
  599. func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
  600. outt := out.Type()
  601. if outt.Elem() != mapItemType {
  602. d.terror(n, yaml_MAP_TAG, out)
  603. return false
  604. }
  605. mapType := d.mapType
  606. d.mapType = outt
  607. var slice []MapItem
  608. var l = len(n.children)
  609. for i := 0; i < l; i += 2 {
  610. if isMerge(n.children[i]) {
  611. d.merge(n.children[i+1], out)
  612. continue
  613. }
  614. item := MapItem{}
  615. k := reflect.ValueOf(&item.Key).Elem()
  616. if d.unmarshal(n.children[i], k) {
  617. v := reflect.ValueOf(&item.Value).Elem()
  618. if d.unmarshal(n.children[i+1], v) {
  619. slice = append(slice, item)
  620. }
  621. }
  622. }
  623. out.Set(reflect.ValueOf(slice))
  624. d.mapType = mapType
  625. return true
  626. }
  627. func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
  628. sinfo, err := getStructInfo(out.Type())
  629. if err != nil {
  630. panic(err)
  631. }
  632. name := settableValueOf("")
  633. l := len(n.children)
  634. var inlineMap reflect.Value
  635. var elemType reflect.Type
  636. if sinfo.InlineMap != -1 {
  637. inlineMap = out.Field(sinfo.InlineMap)
  638. inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
  639. elemType = inlineMap.Type().Elem()
  640. }
  641. var doneFields []bool
  642. if d.strict {
  643. doneFields = make([]bool, len(sinfo.FieldsList))
  644. }
  645. for i := 0; i < l; i += 2 {
  646. ni := n.children[i]
  647. if isMerge(ni) {
  648. d.merge(n.children[i+1], out)
  649. continue
  650. }
  651. if !d.unmarshal(ni, name) {
  652. continue
  653. }
  654. if info, ok := sinfo.FieldsMap[name.String()]; ok {
  655. if d.strict {
  656. if doneFields[info.Id] {
  657. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type()))
  658. continue
  659. }
  660. doneFields[info.Id] = true
  661. }
  662. var field reflect.Value
  663. if info.Inline == nil {
  664. field = out.Field(info.Num)
  665. } else {
  666. field = out.FieldByIndex(info.Inline)
  667. }
  668. d.unmarshal(n.children[i+1], field)
  669. } else if sinfo.InlineMap != -1 {
  670. if inlineMap.IsNil() {
  671. inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
  672. }
  673. value := reflect.New(elemType).Elem()
  674. d.unmarshal(n.children[i+1], value)
  675. d.setMapIndex(n.children[i+1], inlineMap, name, value)
  676. } else if d.strict {
  677. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type()))
  678. }
  679. }
  680. return true
  681. }
  682. func failWantMap() {
  683. failf("map merge requires map or sequence of maps as the value")
  684. }
  685. func (d *decoder) merge(n *node, out reflect.Value) {
  686. switch n.kind {
  687. case mappingNode:
  688. d.unmarshal(n, out)
  689. case aliasNode:
  690. an, ok := d.doc.anchors[n.value]
  691. if ok && an.kind != mappingNode {
  692. failWantMap()
  693. }
  694. d.unmarshal(n, out)
  695. case sequenceNode:
  696. // Step backwards as earlier nodes take precedence.
  697. for i := len(n.children) - 1; i >= 0; i-- {
  698. ni := n.children[i]
  699. if ni.kind == aliasNode {
  700. an, ok := d.doc.anchors[ni.value]
  701. if ok && an.kind != mappingNode {
  702. failWantMap()
  703. }
  704. } else if ni.kind != mappingNode {
  705. failWantMap()
  706. }
  707. d.unmarshal(ni, out)
  708. }
  709. default:
  710. failWantMap()
  711. }
  712. }
  713. func isMerge(n *node) bool {
  714. // Quick test so we avoid the overhead of calling resolve
  715. // unless we're pretty sure it can be a merge node.
  716. if n.kind != scalarNode || n.value != "<<" {
  717. return false
  718. }
  719. _, v := resolve(n.tag, n.value)
  720. return v == MergeTag
  721. }