decode.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package goyaml
  2. import (
  3. "reflect"
  4. "strconv"
  5. )
  6. const (
  7. documentNode = 1 << iota
  8. mappingNode
  9. sequenceNode
  10. scalarNode
  11. aliasNode
  12. )
  13. type node struct {
  14. kind int
  15. line, column int
  16. tag string
  17. value string
  18. implicit bool
  19. children []*node
  20. anchors map[string]*node
  21. }
  22. // ----------------------------------------------------------------------------
  23. // Parser, produces a node tree out of a libyaml event stream.
  24. type parser struct {
  25. parser yaml_parser_t
  26. event yaml_event_t
  27. doc *node
  28. }
  29. func newParser(b []byte) *parser {
  30. p := parser{}
  31. if !yaml_parser_initialize(&p.parser) {
  32. panic("Failed to initialize YAML emitter")
  33. }
  34. if len(b) == 0 {
  35. b = []byte{'\n'}
  36. }
  37. yaml_parser_set_input_string(&p.parser, b)
  38. p.skip()
  39. if p.event.typ != yaml_STREAM_START_EVENT {
  40. panic("Expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
  41. }
  42. p.skip()
  43. return &p
  44. }
  45. func (p *parser) destroy() {
  46. if p.event.typ != yaml_NO_EVENT {
  47. yaml_event_delete(&p.event)
  48. }
  49. yaml_parser_delete(&p.parser)
  50. }
  51. func (p *parser) skip() {
  52. if p.event.typ != yaml_NO_EVENT {
  53. if p.event.typ == yaml_STREAM_END_EVENT {
  54. panic("Attempted to go past the end of stream. Corrupted value?")
  55. }
  56. yaml_event_delete(&p.event)
  57. }
  58. if !yaml_parser_parse(&p.parser, &p.event) {
  59. p.fail()
  60. }
  61. }
  62. func (p *parser) fail() {
  63. var where string
  64. var line int
  65. if p.parser.problem_mark.line != 0 {
  66. line = p.parser.problem_mark.line
  67. } else if p.parser.context_mark.line != 0 {
  68. line = p.parser.context_mark.line
  69. }
  70. if line != 0 {
  71. where = "line " + strconv.Itoa(line) + ": "
  72. }
  73. var msg string
  74. if len(p.parser.problem) > 0 {
  75. msg = p.parser.problem
  76. } else {
  77. msg = "Unknown problem parsing YAML content"
  78. }
  79. panic(where + msg)
  80. }
  81. func (p *parser) anchor(n *node, anchor []byte) {
  82. if anchor != nil {
  83. p.doc.anchors[string(anchor)] = n
  84. }
  85. }
  86. func (p *parser) parse() *node {
  87. switch p.event.typ {
  88. case yaml_SCALAR_EVENT:
  89. return p.scalar()
  90. case yaml_ALIAS_EVENT:
  91. return p.alias()
  92. case yaml_MAPPING_START_EVENT:
  93. return p.mapping()
  94. case yaml_SEQUENCE_START_EVENT:
  95. return p.sequence()
  96. case yaml_DOCUMENT_START_EVENT:
  97. return p.document()
  98. case yaml_STREAM_END_EVENT:
  99. // Happens when attempting to decode an empty buffer.
  100. return nil
  101. default:
  102. panic("Attempted to parse unknown event: " +
  103. strconv.Itoa(int(p.event.typ)))
  104. }
  105. panic("Unreachable")
  106. }
  107. func (p *parser) node(kind int) *node {
  108. return &node{
  109. kind: kind,
  110. line: p.event.start_mark.line,
  111. column: p.event.start_mark.column,
  112. }
  113. }
  114. func (p *parser) document() *node {
  115. n := p.node(documentNode)
  116. n.anchors = make(map[string]*node)
  117. p.doc = n
  118. p.skip()
  119. n.children = append(n.children, p.parse())
  120. if p.event.typ != yaml_DOCUMENT_END_EVENT {
  121. panic("Expected end of document event but got " +
  122. strconv.Itoa(int(p.event.typ)))
  123. }
  124. p.skip()
  125. return n
  126. }
  127. func (p *parser) alias() *node {
  128. n := p.node(aliasNode)
  129. n.value = string(p.event.alias.anchor)
  130. p.skip()
  131. return n
  132. }
  133. func (p *parser) scalar() *node {
  134. scalar := p.event.scalar
  135. n := p.node(scalarNode)
  136. n.value = string(scalar.value)
  137. n.tag = string(scalar.tag)
  138. n.implicit = scalar.plain_implicit
  139. p.anchor(n, scalar.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.sequence_start.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.mapping_start.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. again := true
  192. for again {
  193. again = false
  194. setter, _ := (*out).Interface().(Setter)
  195. if tag != "!!null" || setter != nil {
  196. if pv := (*out); pv.Kind() == reflect.Ptr {
  197. if pv.IsNil() {
  198. *out = reflect.New(pv.Type().Elem()).Elem()
  199. pv.Set((*out).Addr())
  200. } else {
  201. *out = pv.Elem()
  202. }
  203. setter, _ = pv.Interface().(Setter)
  204. again = true
  205. }
  206. }
  207. if setter != nil {
  208. var arg interface{}
  209. *out = reflect.ValueOf(&arg).Elem()
  210. return func() {
  211. *good = setter.SetYAML(tag, arg)
  212. }
  213. }
  214. }
  215. return nil
  216. }
  217. func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
  218. switch n.kind {
  219. case documentNode:
  220. good = d.document(n, out)
  221. case scalarNode:
  222. good = d.scalar(n, out)
  223. case aliasNode:
  224. good = d.alias(n, out)
  225. case mappingNode:
  226. good = d.mapping(n, out)
  227. case sequenceNode:
  228. good = d.sequence(n, out)
  229. default:
  230. panic("Internal error: unknown node kind: " + strconv.Itoa(n.kind))
  231. }
  232. return
  233. }
  234. func (d *decoder) document(n *node, out reflect.Value) (good bool) {
  235. if len(n.children) == 1 {
  236. d.doc = n
  237. d.unmarshal(n.children[0], out)
  238. return true
  239. }
  240. return false
  241. }
  242. func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
  243. an, ok := d.doc.anchors[n.value]
  244. if !ok {
  245. panic("Unknown anchor '" + n.value + "' referenced")
  246. }
  247. if d.aliases[n.value] {
  248. panic("Anchor '" + n.value + "' value contains itself")
  249. }
  250. d.aliases[n.value] = true
  251. good = d.unmarshal(an, out)
  252. delete(d.aliases, n.value)
  253. return good
  254. }
  255. func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
  256. var tag string
  257. var resolved interface{}
  258. if n.tag == "" && !n.implicit {
  259. resolved = n.value
  260. } else {
  261. tag, resolved = resolve(n.tag, n.value)
  262. if set := d.setter(tag, &out, &good); set != nil {
  263. defer set()
  264. }
  265. }
  266. switch out.Kind() {
  267. case reflect.String:
  268. if resolved != nil {
  269. out.SetString(n.value)
  270. good = true
  271. }
  272. case reflect.Interface:
  273. if resolved == nil {
  274. out.Set(reflect.Zero(out.Type()))
  275. } else {
  276. out.Set(reflect.ValueOf(resolved))
  277. }
  278. good = true
  279. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  280. switch resolved := resolved.(type) {
  281. case int:
  282. if !out.OverflowInt(int64(resolved)) {
  283. out.SetInt(int64(resolved))
  284. good = true
  285. }
  286. case int64:
  287. if !out.OverflowInt(resolved) {
  288. out.SetInt(resolved)
  289. good = true
  290. }
  291. }
  292. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  293. switch resolved := resolved.(type) {
  294. case int:
  295. if resolved >= 0 {
  296. out.SetUint(uint64(resolved))
  297. good = true
  298. }
  299. case int64:
  300. if resolved >= 0 {
  301. out.SetUint(uint64(resolved))
  302. good = true
  303. }
  304. }
  305. case reflect.Bool:
  306. switch resolved := resolved.(type) {
  307. case bool:
  308. out.SetBool(resolved)
  309. good = true
  310. }
  311. case reflect.Float32, reflect.Float64:
  312. switch resolved := resolved.(type) {
  313. case float64:
  314. out.SetFloat(resolved)
  315. good = true
  316. }
  317. case reflect.Ptr:
  318. switch resolved.(type) {
  319. case nil:
  320. out.Set(reflect.Zero(out.Type()))
  321. good = true
  322. default:
  323. if out.Type().Elem() == reflect.TypeOf(resolved) {
  324. elem := reflect.New(out.Type().Elem())
  325. elem.Elem().Set(reflect.ValueOf(resolved))
  326. out.Set(elem)
  327. good = true
  328. }
  329. }
  330. }
  331. return good
  332. }
  333. func settableValueOf(i interface{}) reflect.Value {
  334. v := reflect.ValueOf(i)
  335. sv := reflect.New(v.Type()).Elem()
  336. sv.Set(v)
  337. return sv
  338. }
  339. func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
  340. if set := d.setter("!!seq", &out, &good); set != nil {
  341. defer set()
  342. }
  343. var iface reflect.Value
  344. if out.Kind() == reflect.Interface {
  345. // No type hints. Will have to use a generic sequence.
  346. iface = out
  347. out = settableValueOf(make([]interface{}, 0))
  348. }
  349. if out.Kind() != reflect.Slice {
  350. return false
  351. }
  352. et := out.Type().Elem()
  353. l := len(n.children)
  354. for i := 0; i < l; i++ {
  355. e := reflect.New(et).Elem()
  356. if ok := d.unmarshal(n.children[i], e); ok {
  357. out.Set(reflect.Append(out, e))
  358. }
  359. }
  360. if iface.IsValid() {
  361. iface.Set(out)
  362. }
  363. return true
  364. }
  365. func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
  366. if set := d.setter("!!map", &out, &good); set != nil {
  367. defer set()
  368. }
  369. if out.Kind() == reflect.Struct {
  370. return d.mappingStruct(n, out)
  371. }
  372. if out.Kind() == reflect.Interface {
  373. // No type hints. Will have to use a generic map.
  374. iface := out
  375. out = settableValueOf(make(map[interface{}]interface{}))
  376. iface.Set(out)
  377. }
  378. if out.Kind() != reflect.Map {
  379. return false
  380. }
  381. outt := out.Type()
  382. kt := outt.Key()
  383. et := outt.Elem()
  384. if out.IsNil() {
  385. out.Set(reflect.MakeMap(outt))
  386. }
  387. l := len(n.children)
  388. for i := 0; i < l; i += 2 {
  389. k := reflect.New(kt).Elem()
  390. if d.unmarshal(n.children[i], k) {
  391. e := reflect.New(et).Elem()
  392. if d.unmarshal(n.children[i+1], e) {
  393. out.SetMapIndex(k, e)
  394. }
  395. }
  396. }
  397. return true
  398. }
  399. func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
  400. fields, err := getStructFields(out.Type())
  401. if err != nil {
  402. panic(err)
  403. }
  404. name := settableValueOf("")
  405. fieldsMap := fields.Map
  406. l := len(n.children)
  407. for i := 0; i < l; i += 2 {
  408. if !d.unmarshal(n.children[i], name) {
  409. continue
  410. }
  411. if info, ok := fieldsMap[name.String()]; ok {
  412. d.unmarshal(n.children[i+1], out.Field(info.Num))
  413. }
  414. }
  415. return true
  416. }