decode.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. const (
  293. // 400,000 decode operations is ~500kb of dense object declarations, or ~5kb of dense object declarations with 10000% alias expansion
  294. alias_ratio_range_low = 400000
  295. // 4,000,000 decode operations is ~5MB of dense object declarations, or ~4.5MB of dense object declarations with 10% alias expansion
  296. alias_ratio_range_high = 4000000
  297. // alias_ratio_range is the range over which we scale allowed alias ratios
  298. alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low)
  299. )
  300. func allowedAliasRatio(decodeCount int) float64 {
  301. switch {
  302. case decodeCount <= alias_ratio_range_low:
  303. // allow 99% to come from alias expansion for small-to-medium documents
  304. return 0.99
  305. case decodeCount >= alias_ratio_range_high:
  306. // allow 10% to come from alias expansion for very large documents
  307. return 0.10
  308. default:
  309. // scale smoothly from 99% down to 10% over the range.
  310. // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range.
  311. // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps).
  312. return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range)
  313. }
  314. }
  315. func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
  316. d.decodeCount++
  317. if d.aliasDepth > 0 {
  318. d.aliasCount++
  319. }
  320. if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) {
  321. failf("document contains excessive aliasing")
  322. }
  323. switch n.kind {
  324. case documentNode:
  325. return d.document(n, out)
  326. case aliasNode:
  327. return d.alias(n, out)
  328. }
  329. out, unmarshaled, good := d.prepare(n, out)
  330. if unmarshaled {
  331. return good
  332. }
  333. switch n.kind {
  334. case scalarNode:
  335. good = d.scalar(n, out)
  336. case mappingNode:
  337. good = d.mapping(n, out)
  338. case sequenceNode:
  339. good = d.sequence(n, out)
  340. default:
  341. panic("internal error: unknown node kind: " + strconv.Itoa(n.kind))
  342. }
  343. return good
  344. }
  345. func (d *decoder) document(n *node, out reflect.Value) (good bool) {
  346. if len(n.children) == 1 {
  347. d.doc = n
  348. d.unmarshal(n.children[0], out)
  349. return true
  350. }
  351. return false
  352. }
  353. func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
  354. if d.aliases[n] {
  355. // TODO this could actually be allowed in some circumstances.
  356. failf("anchor '%s' value contains itself", n.value)
  357. }
  358. d.aliases[n] = true
  359. d.aliasDepth++
  360. good = d.unmarshal(n.alias, out)
  361. d.aliasDepth--
  362. delete(d.aliases, n)
  363. return good
  364. }
  365. var zeroValue reflect.Value
  366. func resetMap(out reflect.Value) {
  367. for _, k := range out.MapKeys() {
  368. out.SetMapIndex(k, zeroValue)
  369. }
  370. }
  371. func (d *decoder) scalar(n *node, out reflect.Value) bool {
  372. var tag string
  373. var resolved interface{}
  374. if n.tag == "" && !n.implicit {
  375. tag = yaml_STR_TAG
  376. resolved = n.value
  377. } else {
  378. tag, resolved = resolve(n.tag, n.value)
  379. if tag == yaml_BINARY_TAG {
  380. data, err := base64.StdEncoding.DecodeString(resolved.(string))
  381. if err != nil {
  382. failf("!!binary value contains invalid base64 data")
  383. }
  384. resolved = string(data)
  385. }
  386. }
  387. if resolved == nil {
  388. if out.Kind() == reflect.Map && !out.CanAddr() {
  389. resetMap(out)
  390. } else {
  391. out.Set(reflect.Zero(out.Type()))
  392. }
  393. return true
  394. }
  395. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  396. // We've resolved to exactly the type we want, so use that.
  397. out.Set(resolvedv)
  398. return true
  399. }
  400. // Perhaps we can use the value as a TextUnmarshaler to
  401. // set its value.
  402. if out.CanAddr() {
  403. u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
  404. if ok {
  405. var text []byte
  406. if tag == yaml_BINARY_TAG {
  407. text = []byte(resolved.(string))
  408. } else {
  409. // We let any value be unmarshaled into TextUnmarshaler.
  410. // That might be more lax than we'd like, but the
  411. // TextUnmarshaler itself should bowl out any dubious values.
  412. text = []byte(n.value)
  413. }
  414. err := u.UnmarshalText(text)
  415. if err != nil {
  416. fail(err)
  417. }
  418. return true
  419. }
  420. }
  421. switch out.Kind() {
  422. case reflect.String:
  423. if tag == yaml_BINARY_TAG {
  424. out.SetString(resolved.(string))
  425. return true
  426. }
  427. if resolved != nil {
  428. out.SetString(n.value)
  429. return true
  430. }
  431. case reflect.Interface:
  432. if resolved == nil {
  433. out.Set(reflect.Zero(out.Type()))
  434. } else if tag == yaml_TIMESTAMP_TAG {
  435. // It looks like a timestamp but for backward compatibility
  436. // reasons we set it as a string, so that code that unmarshals
  437. // timestamp-like values into interface{} will continue to
  438. // see a string and not a time.Time.
  439. // TODO(v3) Drop this.
  440. out.Set(reflect.ValueOf(n.value))
  441. } else {
  442. out.Set(reflect.ValueOf(resolved))
  443. }
  444. return true
  445. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  446. switch resolved := resolved.(type) {
  447. case int:
  448. if !out.OverflowInt(int64(resolved)) {
  449. out.SetInt(int64(resolved))
  450. return true
  451. }
  452. case int64:
  453. if !out.OverflowInt(resolved) {
  454. out.SetInt(resolved)
  455. return true
  456. }
  457. case uint64:
  458. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  459. out.SetInt(int64(resolved))
  460. return true
  461. }
  462. case float64:
  463. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  464. out.SetInt(int64(resolved))
  465. return true
  466. }
  467. case string:
  468. if out.Type() == durationType {
  469. d, err := time.ParseDuration(resolved)
  470. if err == nil {
  471. out.SetInt(int64(d))
  472. return true
  473. }
  474. }
  475. }
  476. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  477. switch resolved := resolved.(type) {
  478. case int:
  479. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  480. out.SetUint(uint64(resolved))
  481. return true
  482. }
  483. case int64:
  484. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  485. out.SetUint(uint64(resolved))
  486. return true
  487. }
  488. case uint64:
  489. if !out.OverflowUint(uint64(resolved)) {
  490. out.SetUint(uint64(resolved))
  491. return true
  492. }
  493. case float64:
  494. if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
  495. out.SetUint(uint64(resolved))
  496. return true
  497. }
  498. }
  499. case reflect.Bool:
  500. switch resolved := resolved.(type) {
  501. case bool:
  502. out.SetBool(resolved)
  503. return true
  504. }
  505. case reflect.Float32, reflect.Float64:
  506. switch resolved := resolved.(type) {
  507. case int:
  508. out.SetFloat(float64(resolved))
  509. return true
  510. case int64:
  511. out.SetFloat(float64(resolved))
  512. return true
  513. case uint64:
  514. out.SetFloat(float64(resolved))
  515. return true
  516. case float64:
  517. out.SetFloat(resolved)
  518. return true
  519. }
  520. case reflect.Struct:
  521. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  522. out.Set(resolvedv)
  523. return true
  524. }
  525. case reflect.Ptr:
  526. if out.Type().Elem() == reflect.TypeOf(resolved) {
  527. // TODO DOes this make sense? When is out a Ptr except when decoding a nil value?
  528. elem := reflect.New(out.Type().Elem())
  529. elem.Elem().Set(reflect.ValueOf(resolved))
  530. out.Set(elem)
  531. return true
  532. }
  533. }
  534. d.terror(n, tag, out)
  535. return false
  536. }
  537. func settableValueOf(i interface{}) reflect.Value {
  538. v := reflect.ValueOf(i)
  539. sv := reflect.New(v.Type()).Elem()
  540. sv.Set(v)
  541. return sv
  542. }
  543. func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
  544. l := len(n.children)
  545. var iface reflect.Value
  546. switch out.Kind() {
  547. case reflect.Slice:
  548. out.Set(reflect.MakeSlice(out.Type(), l, l))
  549. case reflect.Array:
  550. if l != out.Len() {
  551. failf("invalid array: want %d elements but got %d", out.Len(), l)
  552. }
  553. case reflect.Interface:
  554. // No type hints. Will have to use a generic sequence.
  555. iface = out
  556. out = settableValueOf(make([]interface{}, l))
  557. default:
  558. d.terror(n, yaml_SEQ_TAG, out)
  559. return false
  560. }
  561. et := out.Type().Elem()
  562. j := 0
  563. for i := 0; i < l; i++ {
  564. e := reflect.New(et).Elem()
  565. if ok := d.unmarshal(n.children[i], e); ok {
  566. out.Index(j).Set(e)
  567. j++
  568. }
  569. }
  570. if out.Kind() != reflect.Array {
  571. out.Set(out.Slice(0, j))
  572. }
  573. if iface.IsValid() {
  574. iface.Set(out)
  575. }
  576. return true
  577. }
  578. func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
  579. switch out.Kind() {
  580. case reflect.Struct:
  581. return d.mappingStruct(n, out)
  582. case reflect.Slice:
  583. return d.mappingSlice(n, out)
  584. case reflect.Map:
  585. // okay
  586. case reflect.Interface:
  587. if d.mapType.Kind() == reflect.Map {
  588. iface := out
  589. out = reflect.MakeMap(d.mapType)
  590. iface.Set(out)
  591. } else {
  592. slicev := reflect.New(d.mapType).Elem()
  593. if !d.mappingSlice(n, slicev) {
  594. return false
  595. }
  596. out.Set(slicev)
  597. return true
  598. }
  599. default:
  600. d.terror(n, yaml_MAP_TAG, out)
  601. return false
  602. }
  603. outt := out.Type()
  604. kt := outt.Key()
  605. et := outt.Elem()
  606. mapType := d.mapType
  607. if outt.Key() == ifaceType && outt.Elem() == ifaceType {
  608. d.mapType = outt
  609. }
  610. if out.IsNil() {
  611. out.Set(reflect.MakeMap(outt))
  612. }
  613. l := len(n.children)
  614. for i := 0; i < l; i += 2 {
  615. if isMerge(n.children[i]) {
  616. d.merge(n.children[i+1], out)
  617. continue
  618. }
  619. k := reflect.New(kt).Elem()
  620. if d.unmarshal(n.children[i], k) {
  621. kkind := k.Kind()
  622. if kkind == reflect.Interface {
  623. kkind = k.Elem().Kind()
  624. }
  625. if kkind == reflect.Map || kkind == reflect.Slice {
  626. failf("invalid map key: %#v", k.Interface())
  627. }
  628. e := reflect.New(et).Elem()
  629. if d.unmarshal(n.children[i+1], e) {
  630. d.setMapIndex(n.children[i+1], out, k, e)
  631. }
  632. }
  633. }
  634. d.mapType = mapType
  635. return true
  636. }
  637. func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) {
  638. if d.strict && out.MapIndex(k) != zeroValue {
  639. d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface()))
  640. return
  641. }
  642. out.SetMapIndex(k, v)
  643. }
  644. func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
  645. outt := out.Type()
  646. if outt.Elem() != mapItemType {
  647. d.terror(n, yaml_MAP_TAG, out)
  648. return false
  649. }
  650. mapType := d.mapType
  651. d.mapType = outt
  652. var slice []MapItem
  653. var l = len(n.children)
  654. for i := 0; i < l; i += 2 {
  655. if isMerge(n.children[i]) {
  656. d.merge(n.children[i+1], out)
  657. continue
  658. }
  659. item := MapItem{}
  660. k := reflect.ValueOf(&item.Key).Elem()
  661. if d.unmarshal(n.children[i], k) {
  662. v := reflect.ValueOf(&item.Value).Elem()
  663. if d.unmarshal(n.children[i+1], v) {
  664. slice = append(slice, item)
  665. }
  666. }
  667. }
  668. out.Set(reflect.ValueOf(slice))
  669. d.mapType = mapType
  670. return true
  671. }
  672. func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
  673. sinfo, err := getStructInfo(out.Type())
  674. if err != nil {
  675. panic(err)
  676. }
  677. name := settableValueOf("")
  678. l := len(n.children)
  679. var inlineMap reflect.Value
  680. var elemType reflect.Type
  681. if sinfo.InlineMap != -1 {
  682. inlineMap = out.Field(sinfo.InlineMap)
  683. inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
  684. elemType = inlineMap.Type().Elem()
  685. }
  686. var doneFields []bool
  687. if d.strict {
  688. doneFields = make([]bool, len(sinfo.FieldsList))
  689. }
  690. for i := 0; i < l; i += 2 {
  691. ni := n.children[i]
  692. if isMerge(ni) {
  693. d.merge(n.children[i+1], out)
  694. continue
  695. }
  696. if !d.unmarshal(ni, name) {
  697. continue
  698. }
  699. if info, ok := sinfo.FieldsMap[name.String()]; ok {
  700. if d.strict {
  701. if doneFields[info.Id] {
  702. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type()))
  703. continue
  704. }
  705. doneFields[info.Id] = true
  706. }
  707. var field reflect.Value
  708. if info.Inline == nil {
  709. field = out.Field(info.Num)
  710. } else {
  711. field = out.FieldByIndex(info.Inline)
  712. }
  713. d.unmarshal(n.children[i+1], field)
  714. } else if sinfo.InlineMap != -1 {
  715. if inlineMap.IsNil() {
  716. inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
  717. }
  718. value := reflect.New(elemType).Elem()
  719. d.unmarshal(n.children[i+1], value)
  720. d.setMapIndex(n.children[i+1], inlineMap, name, value)
  721. } else if d.strict {
  722. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type()))
  723. }
  724. }
  725. return true
  726. }
  727. func failWantMap() {
  728. failf("map merge requires map or sequence of maps as the value")
  729. }
  730. func (d *decoder) merge(n *node, out reflect.Value) {
  731. switch n.kind {
  732. case mappingNode:
  733. d.unmarshal(n, out)
  734. case aliasNode:
  735. an, ok := d.doc.anchors[n.value]
  736. if ok && an.kind != mappingNode {
  737. failWantMap()
  738. }
  739. d.unmarshal(n, out)
  740. case sequenceNode:
  741. // Step backwards as earlier nodes take precedence.
  742. for i := len(n.children) - 1; i >= 0; i-- {
  743. ni := n.children[i]
  744. if ni.kind == aliasNode {
  745. an, ok := d.doc.anchors[ni.value]
  746. if ok && an.kind != mappingNode {
  747. failWantMap()
  748. }
  749. } else if ni.kind != mappingNode {
  750. failWantMap()
  751. }
  752. d.unmarshal(ni, out)
  753. }
  754. default:
  755. failWantMap()
  756. }
  757. }
  758. func isMerge(n *node) bool {
  759. return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG)
  760. }