decode.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. package yaml
  2. import (
  3. "reflect"
  4. "strconv"
  5. "time"
  6. )
  7. const (
  8. documentNode = 1 << iota
  9. mappingNode
  10. sequenceNode
  11. scalarNode
  12. aliasNode
  13. )
  14. type node struct {
  15. kind int
  16. line, column int
  17. tag string
  18. value string
  19. implicit bool
  20. children []*node
  21. anchors map[string]*node
  22. }
  23. // ----------------------------------------------------------------------------
  24. // Parser, produces a node tree out of a libyaml event stream.
  25. type parser struct {
  26. parser yaml_parser_t
  27. event yaml_event_t
  28. doc *node
  29. }
  30. func newParser(b []byte) *parser {
  31. p := parser{}
  32. if !yaml_parser_initialize(&p.parser) {
  33. panic("Failed to initialize YAML emitter")
  34. }
  35. if len(b) == 0 {
  36. b = []byte{'\n'}
  37. }
  38. yaml_parser_set_input_string(&p.parser, b)
  39. p.skip()
  40. if p.event.typ != yaml_STREAM_START_EVENT {
  41. panic("Expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
  42. }
  43. p.skip()
  44. return &p
  45. }
  46. func (p *parser) destroy() {
  47. if p.event.typ != yaml_NO_EVENT {
  48. yaml_event_delete(&p.event)
  49. }
  50. yaml_parser_delete(&p.parser)
  51. }
  52. func (p *parser) skip() {
  53. if p.event.typ != yaml_NO_EVENT {
  54. if p.event.typ == yaml_STREAM_END_EVENT {
  55. panic("Attempted to go past the end of stream. Corrupted value?")
  56. }
  57. yaml_event_delete(&p.event)
  58. }
  59. if !yaml_parser_parse(&p.parser, &p.event) {
  60. p.fail()
  61. }
  62. }
  63. func (p *parser) fail() {
  64. var where string
  65. var line int
  66. if p.parser.problem_mark.line != 0 {
  67. line = p.parser.problem_mark.line
  68. } else if p.parser.context_mark.line != 0 {
  69. line = p.parser.context_mark.line
  70. }
  71. if line != 0 {
  72. where = "line " + strconv.Itoa(line) + ": "
  73. }
  74. var msg string
  75. if len(p.parser.problem) > 0 {
  76. msg = p.parser.problem
  77. } else {
  78. msg = "Unknown problem parsing YAML content"
  79. }
  80. panic(where + msg)
  81. }
  82. func (p *parser) anchor(n *node, anchor []byte) {
  83. if anchor != nil {
  84. p.doc.anchors[string(anchor)] = n
  85. }
  86. }
  87. func (p *parser) parse() *node {
  88. switch p.event.typ {
  89. case yaml_SCALAR_EVENT:
  90. return p.scalar()
  91. case yaml_ALIAS_EVENT:
  92. return p.alias()
  93. case yaml_MAPPING_START_EVENT:
  94. return p.mapping()
  95. case yaml_SEQUENCE_START_EVENT:
  96. return p.sequence()
  97. case yaml_DOCUMENT_START_EVENT:
  98. return p.document()
  99. case yaml_STREAM_END_EVENT:
  100. // Happens when attempting to decode an empty buffer.
  101. return nil
  102. default:
  103. panic("Attempted to parse unknown event: " +
  104. strconv.Itoa(int(p.event.typ)))
  105. }
  106. panic("Unreachable")
  107. }
  108. func (p *parser) node(kind int) *node {
  109. return &node{
  110. kind: kind,
  111. line: p.event.start_mark.line,
  112. column: p.event.start_mark.column,
  113. }
  114. }
  115. func (p *parser) document() *node {
  116. n := p.node(documentNode)
  117. n.anchors = make(map[string]*node)
  118. p.doc = n
  119. p.skip()
  120. n.children = append(n.children, p.parse())
  121. if p.event.typ != yaml_DOCUMENT_END_EVENT {
  122. panic("Expected end of document event but got " +
  123. strconv.Itoa(int(p.event.typ)))
  124. }
  125. p.skip()
  126. return n
  127. }
  128. func (p *parser) alias() *node {
  129. n := p.node(aliasNode)
  130. n.value = string(p.event.anchor)
  131. p.skip()
  132. return n
  133. }
  134. func (p *parser) scalar() *node {
  135. n := p.node(scalarNode)
  136. n.value = string(p.event.value)
  137. n.tag = string(p.event.tag)
  138. n.implicit = p.event.implicit
  139. p.anchor(n, p.event.anchor)
  140. p.skip()
  141. return n
  142. }
  143. func (p *parser) sequence() *node {
  144. n := p.node(sequenceNode)
  145. p.anchor(n, p.event.anchor)
  146. p.skip()
  147. for p.event.typ != yaml_SEQUENCE_END_EVENT {
  148. n.children = append(n.children, p.parse())
  149. }
  150. p.skip()
  151. return n
  152. }
  153. func (p *parser) mapping() *node {
  154. n := p.node(mappingNode)
  155. p.anchor(n, p.event.anchor)
  156. p.skip()
  157. for p.event.typ != yaml_MAPPING_END_EVENT {
  158. n.children = append(n.children, p.parse(), p.parse())
  159. }
  160. p.skip()
  161. return n
  162. }
  163. // ----------------------------------------------------------------------------
  164. // Decoder, unmarshals a node into a provided value.
  165. type decoder struct {
  166. doc *node
  167. aliases map[string]bool
  168. }
  169. func newDecoder() *decoder {
  170. d := &decoder{}
  171. d.aliases = make(map[string]bool)
  172. return d
  173. }
  174. // d.setter deals with setters and pointer dereferencing and initialization.
  175. //
  176. // It's a slightly convoluted case to handle properly:
  177. //
  178. // - nil pointers should be initialized, unless being set to nil
  179. // - we don't know at this point yet what's the value to SetYAML() with.
  180. // - we can't separate pointer deref/init and setter checking, because
  181. // a setter may be found while going down a pointer chain.
  182. //
  183. // Thus, here is how it takes care of it:
  184. //
  185. // - out is provided as a pointer, so that it can be replaced.
  186. // - when looking at a non-setter ptr, *out=ptr.Elem(), unless tag=!!null
  187. // - when a setter is found, *out=interface{}, and a set() function is
  188. // returned to call SetYAML() with the value of *out once it's defined.
  189. //
  190. func (d *decoder) setter(tag string, out *reflect.Value, good *bool) (set func()) {
  191. if (*out).Kind() != reflect.Ptr && (*out).CanAddr() {
  192. setter, _ := (*out).Addr().Interface().(Setter)
  193. if setter != nil {
  194. var arg interface{}
  195. *out = reflect.ValueOf(&arg).Elem()
  196. return func() {
  197. *good = setter.SetYAML(tag, arg)
  198. }
  199. }
  200. }
  201. again := true
  202. for again {
  203. again = false
  204. setter, _ := (*out).Interface().(Setter)
  205. if tag != "!!null" || setter != nil {
  206. if pv := (*out); pv.Kind() == reflect.Ptr {
  207. if pv.IsNil() {
  208. *out = reflect.New(pv.Type().Elem()).Elem()
  209. pv.Set((*out).Addr())
  210. } else {
  211. *out = pv.Elem()
  212. }
  213. setter, _ = pv.Interface().(Setter)
  214. again = true
  215. }
  216. }
  217. if setter != nil {
  218. var arg interface{}
  219. *out = reflect.ValueOf(&arg).Elem()
  220. return func() {
  221. *good = setter.SetYAML(tag, arg)
  222. }
  223. }
  224. }
  225. return nil
  226. }
  227. func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
  228. switch n.kind {
  229. case documentNode:
  230. good = d.document(n, out)
  231. case scalarNode:
  232. good = d.scalar(n, out)
  233. case aliasNode:
  234. good = d.alias(n, out)
  235. case mappingNode:
  236. good = d.mapping(n, out)
  237. case sequenceNode:
  238. good = d.sequence(n, out)
  239. default:
  240. panic("Internal error: unknown node kind: " + strconv.Itoa(n.kind))
  241. }
  242. return
  243. }
  244. func (d *decoder) document(n *node, out reflect.Value) (good bool) {
  245. if len(n.children) == 1 {
  246. d.doc = n
  247. d.unmarshal(n.children[0], out)
  248. return true
  249. }
  250. return false
  251. }
  252. func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
  253. an, ok := d.doc.anchors[n.value]
  254. if !ok {
  255. panic("Unknown anchor '" + n.value + "' referenced")
  256. }
  257. if d.aliases[n.value] {
  258. panic("Anchor '" + n.value + "' value contains itself")
  259. }
  260. d.aliases[n.value] = true
  261. good = d.unmarshal(an, out)
  262. delete(d.aliases, n.value)
  263. return good
  264. }
  265. var durationType = reflect.TypeOf(time.Duration(0))
  266. func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
  267. var tag string
  268. var resolved interface{}
  269. if n.tag == "" && !n.implicit {
  270. tag = "!!str"
  271. resolved = n.value
  272. } else {
  273. tag, resolved = resolve(n.tag, n.value)
  274. }
  275. if set := d.setter(tag, &out, &good); set != nil {
  276. defer set()
  277. }
  278. switch out.Kind() {
  279. case reflect.String:
  280. if resolved != nil {
  281. out.SetString(n.value)
  282. good = true
  283. }
  284. case reflect.Interface:
  285. if resolved == nil {
  286. out.Set(reflect.Zero(out.Type()))
  287. } else {
  288. out.Set(reflect.ValueOf(resolved))
  289. }
  290. good = true
  291. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  292. switch resolved := resolved.(type) {
  293. case int:
  294. if !out.OverflowInt(int64(resolved)) {
  295. out.SetInt(int64(resolved))
  296. good = true
  297. }
  298. case int64:
  299. if !out.OverflowInt(resolved) {
  300. out.SetInt(resolved)
  301. good = true
  302. }
  303. case float64:
  304. if resolved < 1<<63-1 && !out.OverflowInt(int64(resolved)) {
  305. out.SetInt(int64(resolved))
  306. good = true
  307. }
  308. case string:
  309. if out.Type() == durationType {
  310. d, err := time.ParseDuration(resolved)
  311. if err == nil {
  312. out.SetInt(int64(d))
  313. good = true
  314. }
  315. }
  316. }
  317. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  318. switch resolved := resolved.(type) {
  319. case int:
  320. if resolved >= 0 {
  321. out.SetUint(uint64(resolved))
  322. good = true
  323. }
  324. case int64:
  325. if resolved >= 0 {
  326. out.SetUint(uint64(resolved))
  327. good = true
  328. }
  329. case float64:
  330. if resolved < 1<<64-1 && !out.OverflowUint(uint64(resolved)) {
  331. out.SetUint(uint64(resolved))
  332. good = true
  333. }
  334. }
  335. case reflect.Bool:
  336. switch resolved := resolved.(type) {
  337. case bool:
  338. out.SetBool(resolved)
  339. good = true
  340. }
  341. case reflect.Float32, reflect.Float64:
  342. switch resolved := resolved.(type) {
  343. case int:
  344. out.SetFloat(float64(resolved))
  345. good = true
  346. case int64:
  347. out.SetFloat(float64(resolved))
  348. good = true
  349. case float64:
  350. out.SetFloat(resolved)
  351. good = true
  352. }
  353. case reflect.Ptr:
  354. switch resolved.(type) {
  355. case nil:
  356. out.Set(reflect.Zero(out.Type()))
  357. good = true
  358. default:
  359. if out.Type().Elem() == reflect.TypeOf(resolved) {
  360. elem := reflect.New(out.Type().Elem())
  361. elem.Elem().Set(reflect.ValueOf(resolved))
  362. out.Set(elem)
  363. good = true
  364. }
  365. }
  366. }
  367. return good
  368. }
  369. func settableValueOf(i interface{}) reflect.Value {
  370. v := reflect.ValueOf(i)
  371. sv := reflect.New(v.Type()).Elem()
  372. sv.Set(v)
  373. return sv
  374. }
  375. func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
  376. if set := d.setter("!!seq", &out, &good); set != nil {
  377. defer set()
  378. }
  379. var iface reflect.Value
  380. if out.Kind() == reflect.Interface {
  381. // No type hints. Will have to use a generic sequence.
  382. iface = out
  383. out = settableValueOf(make([]interface{}, 0))
  384. }
  385. if out.Kind() != reflect.Slice {
  386. return false
  387. }
  388. et := out.Type().Elem()
  389. l := len(n.children)
  390. for i := 0; i < l; i++ {
  391. e := reflect.New(et).Elem()
  392. if ok := d.unmarshal(n.children[i], e); ok {
  393. out.Set(reflect.Append(out, e))
  394. }
  395. }
  396. if iface.IsValid() {
  397. iface.Set(out)
  398. }
  399. return true
  400. }
  401. func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
  402. if set := d.setter("!!map", &out, &good); set != nil {
  403. defer set()
  404. }
  405. if out.Kind() == reflect.Struct {
  406. return d.mappingStruct(n, out)
  407. }
  408. if out.Kind() == reflect.Interface {
  409. // No type hints. Will have to use a generic map.
  410. iface := out
  411. out = settableValueOf(make(map[interface{}]interface{}))
  412. iface.Set(out)
  413. }
  414. if out.Kind() != reflect.Map {
  415. return false
  416. }
  417. outt := out.Type()
  418. kt := outt.Key()
  419. et := outt.Elem()
  420. if out.IsNil() {
  421. out.Set(reflect.MakeMap(outt))
  422. }
  423. l := len(n.children)
  424. for i := 0; i < l; i += 2 {
  425. if isMerge(n.children[i]) {
  426. d.merge(n.children[i+1], out)
  427. continue
  428. }
  429. k := reflect.New(kt).Elem()
  430. if d.unmarshal(n.children[i], k) {
  431. e := reflect.New(et).Elem()
  432. if d.unmarshal(n.children[i+1], e) {
  433. out.SetMapIndex(k, e)
  434. }
  435. }
  436. }
  437. return true
  438. }
  439. func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
  440. sinfo, err := getStructInfo(out.Type())
  441. if err != nil {
  442. panic(err)
  443. }
  444. name := settableValueOf("")
  445. l := len(n.children)
  446. for i := 0; i < l; i += 2 {
  447. ni := n.children[i]
  448. if isMerge(ni) {
  449. d.merge(n.children[i+1], out)
  450. continue
  451. }
  452. if !d.unmarshal(ni, name) {
  453. continue
  454. }
  455. if info, ok := sinfo.FieldsMap[name.String()]; ok {
  456. var field reflect.Value
  457. if info.Inline == nil {
  458. field = out.Field(info.Num)
  459. } else {
  460. field = out.FieldByIndex(info.Inline)
  461. }
  462. d.unmarshal(n.children[i+1], field)
  463. }
  464. }
  465. return true
  466. }
  467. func (d *decoder) merge(n *node, out reflect.Value) {
  468. const wantMap = "map merge requires map or sequence of maps as the value"
  469. switch n.kind {
  470. case mappingNode:
  471. d.unmarshal(n, out)
  472. case aliasNode:
  473. an, ok := d.doc.anchors[n.value]
  474. if ok && an.kind != mappingNode {
  475. panic(wantMap)
  476. }
  477. d.unmarshal(n, out)
  478. case sequenceNode:
  479. // Step backwards as earlier nodes take precedence.
  480. for i := len(n.children)-1; i >= 0; i-- {
  481. ni := n.children[i]
  482. if ni.kind == aliasNode {
  483. an, ok := d.doc.anchors[ni.value]
  484. if ok && an.kind != mappingNode {
  485. panic(wantMap)
  486. }
  487. } else if ni.kind != mappingNode {
  488. panic(wantMap)
  489. }
  490. d.unmarshal(ni, out)
  491. }
  492. default:
  493. panic(wantMap)
  494. }
  495. }
  496. func isMerge(n *node) bool {
  497. return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == "!!merge" || n.tag == "tag:yaml.org,2002:merge")
  498. }