decode.go 14 KB

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