decode.go 18 KB

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