decode.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package goyaml
  2. // #cgo LDFLAGS: -lm -lpthread
  3. // #cgo windows LDFLAGS: -L. -lyaml
  4. // #cgo windows CFLAGS: -DYAML_DECLARE_STATIC=1
  5. // #cgo CFLAGS: -I. -DHAVE_CONFIG_H=1
  6. //
  7. // #include "helpers.h"
  8. import "C"
  9. import (
  10. "reflect"
  11. "strconv"
  12. "unsafe"
  13. )
  14. const (
  15. documentNode = 1 << iota
  16. mappingNode
  17. sequenceNode
  18. scalarNode
  19. aliasNode
  20. )
  21. type node struct {
  22. kind int
  23. line, column int
  24. tag string
  25. value string
  26. implicit bool
  27. children []*node
  28. anchors map[string]*node
  29. }
  30. func stry(s *C.yaml_char_t) string {
  31. return C.GoString((*C.char)(unsafe.Pointer(s)))
  32. }
  33. // ----------------------------------------------------------------------------
  34. // Parser, produces a node tree out of a libyaml event stream.
  35. type parser struct {
  36. parser C.yaml_parser_t
  37. event C.yaml_event_t
  38. doc *node
  39. }
  40. func newParser(b []byte) *parser {
  41. p := parser{}
  42. if C.yaml_parser_initialize(&p.parser) == 0 {
  43. panic("Failed to initialize YAML emitter")
  44. }
  45. if len(b) == 0 {
  46. b = []byte{'\n'}
  47. }
  48. // How unsafe is this really? Will this break if the GC becomes compacting?
  49. // Probably not, otherwise that would likely break &parse below as well.
  50. input := (*C.uchar)(unsafe.Pointer(&b[0]))
  51. C.yaml_parser_set_input_string(&p.parser, input, (C.size_t)(len(b)))
  52. p.skip()
  53. if p.event._type != C.YAML_STREAM_START_EVENT {
  54. panic("Expected stream start event, got " +
  55. strconv.Itoa(int(p.event._type)))
  56. }
  57. p.skip()
  58. return &p
  59. }
  60. func (p *parser) destroy() {
  61. if p.event._type != C.YAML_NO_EVENT {
  62. C.yaml_event_delete(&p.event)
  63. }
  64. C.yaml_parser_delete(&p.parser)
  65. }
  66. func (p *parser) skip() {
  67. if p.event._type != C.YAML_NO_EVENT {
  68. if p.event._type == C.YAML_STREAM_END_EVENT {
  69. panic("Attempted to go past the end of stream. Corrupted value?")
  70. }
  71. C.yaml_event_delete(&p.event)
  72. }
  73. if C.yaml_parser_parse(&p.parser, &p.event) == 0 {
  74. p.fail()
  75. }
  76. }
  77. func (p *parser) fail() {
  78. var where string
  79. var line int
  80. if p.parser.problem_mark.line != 0 {
  81. line = int(C.int(p.parser.problem_mark.line))
  82. } else if p.parser.context_mark.line != 0 {
  83. line = int(C.int(p.parser.context_mark.line))
  84. }
  85. if line != 0 {
  86. where = "line " + strconv.Itoa(line) + ": "
  87. }
  88. var msg string
  89. if p.parser.problem != nil {
  90. msg = C.GoString(p.parser.problem)
  91. } else {
  92. msg = "Unknown problem parsing YAML content"
  93. }
  94. panic(where + msg)
  95. }
  96. func (p *parser) anchor(n *node, anchor *C.yaml_char_t) {
  97. if anchor != nil {
  98. p.doc.anchors[stry(anchor)] = n
  99. }
  100. }
  101. func (p *parser) parse() *node {
  102. switch p.event._type {
  103. case C.YAML_SCALAR_EVENT:
  104. return p.scalar()
  105. case C.YAML_ALIAS_EVENT:
  106. return p.alias()
  107. case C.YAML_MAPPING_START_EVENT:
  108. return p.mapping()
  109. case C.YAML_SEQUENCE_START_EVENT:
  110. return p.sequence()
  111. case C.YAML_DOCUMENT_START_EVENT:
  112. return p.document()
  113. case C.YAML_STREAM_END_EVENT:
  114. // Happens when attempting to decode an empty buffer.
  115. return nil
  116. default:
  117. panic("Attempted to parse unknown event: " +
  118. strconv.Itoa(int(p.event._type)))
  119. }
  120. panic("Unreachable")
  121. }
  122. func (p *parser) node(kind int) *node {
  123. return &node{kind: kind,
  124. line: int(C.int(p.event.start_mark.line)),
  125. column: int(C.int(p.event.start_mark.column))}
  126. }
  127. func (p *parser) document() *node {
  128. n := p.node(documentNode)
  129. n.anchors = make(map[string]*node)
  130. p.doc = n
  131. p.skip()
  132. n.children = append(n.children, p.parse())
  133. if p.event._type != C.YAML_DOCUMENT_END_EVENT {
  134. panic("Expected end of document event but got " +
  135. strconv.Itoa(int(p.event._type)))
  136. }
  137. p.skip()
  138. return n
  139. }
  140. func (p *parser) alias() *node {
  141. alias := C.event_alias(&p.event)
  142. n := p.node(aliasNode)
  143. n.value = stry(alias.anchor)
  144. p.skip()
  145. return n
  146. }
  147. func (p *parser) scalar() *node {
  148. scalar := C.event_scalar(&p.event)
  149. n := p.node(scalarNode)
  150. n.value = stry(scalar.value)
  151. n.tag = stry(scalar.tag)
  152. n.implicit = (scalar.plain_implicit != 0)
  153. p.anchor(n, scalar.anchor)
  154. p.skip()
  155. return n
  156. }
  157. func (p *parser) sequence() *node {
  158. n := p.node(sequenceNode)
  159. p.anchor(n, C.event_sequence_start(&p.event).anchor)
  160. p.skip()
  161. for p.event._type != C.YAML_SEQUENCE_END_EVENT {
  162. n.children = append(n.children, p.parse())
  163. }
  164. p.skip()
  165. return n
  166. }
  167. func (p *parser) mapping() *node {
  168. n := p.node(mappingNode)
  169. p.anchor(n, C.event_mapping_start(&p.event).anchor)
  170. p.skip()
  171. for p.event._type != C.YAML_MAPPING_END_EVENT {
  172. n.children = append(n.children, p.parse(), p.parse())
  173. }
  174. p.skip()
  175. return n
  176. }
  177. // ----------------------------------------------------------------------------
  178. // Decoder, unmarshals a node into a provided value.
  179. type decoder struct {
  180. doc *node
  181. aliases map[string]bool
  182. }
  183. func newDecoder() *decoder {
  184. d := &decoder{}
  185. d.aliases = make(map[string]bool)
  186. return d
  187. }
  188. // d.setter deals with setters and pointer dereferencing and initialization.
  189. //
  190. // It's a slightly convoluted case to handle properly:
  191. //
  192. // - nil pointers should be initialized, unless being set to nil
  193. // - we don't know at this point yet what's the value to SetYAML() with.
  194. // - we can't separate pointer deref/init and setter checking, because
  195. // a setter may be found while going down a pointer chain.
  196. //
  197. // Thus, here is how it takes care of it:
  198. //
  199. // - out is provided as a pointer, so that it can be replaced.
  200. // - when looking at a non-setter ptr, *out=ptr.Elem(), unless tag=!!null
  201. // - when a setter is found, *out=interface{}, and a set() function is
  202. // returned to call SetYAML() with the value of *out once it's defined.
  203. //
  204. func (d *decoder) setter(tag string, out *reflect.Value, good *bool) (set func()) {
  205. again := true
  206. for again {
  207. again = false
  208. setter, _ := (*out).Interface().(Setter)
  209. if tag != "!!null" || setter != nil {
  210. if pv := (*out); pv.Kind() == reflect.Ptr {
  211. if pv.IsNil() {
  212. *out = reflect.New(pv.Type().Elem()).Elem()
  213. pv.Set((*out).Addr())
  214. } else {
  215. *out = pv.Elem()
  216. }
  217. setter, _ = pv.Interface().(Setter)
  218. again = true
  219. }
  220. }
  221. if setter != nil {
  222. var arg interface{}
  223. *out = reflect.ValueOf(&arg).Elem()
  224. return func() {
  225. *good = setter.SetYAML(tag, arg)
  226. }
  227. }
  228. }
  229. return nil
  230. }
  231. func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
  232. switch n.kind {
  233. case documentNode:
  234. good = d.document(n, out)
  235. case scalarNode:
  236. good = d.scalar(n, out)
  237. case aliasNode:
  238. good = d.alias(n, out)
  239. case mappingNode:
  240. good = d.mapping(n, out)
  241. case sequenceNode:
  242. good = d.sequence(n, out)
  243. default:
  244. panic("Internal error: unknown node kind: " + strconv.Itoa(n.kind))
  245. }
  246. return
  247. }
  248. func (d *decoder) document(n *node, out reflect.Value) (good bool) {
  249. if len(n.children) == 1 {
  250. d.doc = n
  251. d.unmarshal(n.children[0], out)
  252. return true
  253. }
  254. return false
  255. }
  256. func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
  257. an, ok := d.doc.anchors[n.value]
  258. if !ok {
  259. panic("Unknown anchor '" + n.value + "' referenced")
  260. }
  261. if d.aliases[n.value] {
  262. panic("Anchor '" + n.value + "' value contains itself")
  263. }
  264. d.aliases[n.value] = true
  265. good = d.unmarshal(an, out)
  266. delete(d.aliases, n.value)
  267. return good
  268. }
  269. func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
  270. var tag string
  271. var resolved interface{}
  272. if n.tag == "" && !n.implicit {
  273. resolved = n.value
  274. } else {
  275. tag, resolved = resolve(n.tag, n.value)
  276. if set := d.setter(tag, &out, &good); set != nil {
  277. defer set()
  278. }
  279. }
  280. switch out.Kind() {
  281. case reflect.String:
  282. out.SetString(n.value)
  283. good = true
  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. }
  304. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  305. switch resolved := resolved.(type) {
  306. case int:
  307. if resolved >= 0 {
  308. out.SetUint(uint64(resolved))
  309. good = true
  310. }
  311. case int64:
  312. if resolved >= 0 {
  313. out.SetUint(uint64(resolved))
  314. good = true
  315. }
  316. }
  317. case reflect.Bool:
  318. switch resolved := resolved.(type) {
  319. case bool:
  320. out.SetBool(resolved)
  321. good = true
  322. }
  323. case reflect.Float32, reflect.Float64:
  324. switch resolved := resolved.(type) {
  325. case float64:
  326. out.SetFloat(resolved)
  327. good = true
  328. }
  329. case reflect.Ptr:
  330. switch resolved.(type) {
  331. case nil:
  332. out.Set(reflect.Zero(out.Type()))
  333. good = true
  334. }
  335. }
  336. return good
  337. }
  338. func settableValueOf(i interface{}) reflect.Value {
  339. v := reflect.ValueOf(i)
  340. sv := reflect.New(v.Type()).Elem()
  341. sv.Set(v)
  342. return sv
  343. }
  344. func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
  345. if set := d.setter("!!seq", &out, &good); set != nil {
  346. defer set()
  347. }
  348. var iface reflect.Value
  349. if out.Kind() == reflect.Interface {
  350. // No type hints. Will have to use a generic sequence.
  351. iface = out
  352. out = settableValueOf(make([]interface{}, 0))
  353. }
  354. if out.Kind() != reflect.Slice {
  355. return false
  356. }
  357. et := out.Type().Elem()
  358. l := len(n.children)
  359. for i := 0; i < l; i++ {
  360. e := reflect.New(et).Elem()
  361. if ok := d.unmarshal(n.children[i], e); ok {
  362. out.Set(reflect.Append(out, e))
  363. }
  364. }
  365. if iface.IsValid() {
  366. iface.Set(out)
  367. }
  368. return true
  369. }
  370. func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
  371. if set := d.setter("!!map", &out, &good); set != nil {
  372. defer set()
  373. }
  374. if out.Kind() == reflect.Struct {
  375. return d.mappingStruct(n, out)
  376. }
  377. if out.Kind() == reflect.Interface {
  378. // No type hints. Will have to use a generic map.
  379. iface := out
  380. out = settableValueOf(make(map[interface{}]interface{}))
  381. iface.Set(out)
  382. }
  383. if out.Kind() != reflect.Map {
  384. return false
  385. }
  386. outt := out.Type()
  387. kt := outt.Key()
  388. et := outt.Elem()
  389. if out.IsNil() {
  390. out.Set(reflect.MakeMap(outt))
  391. }
  392. l := len(n.children)
  393. for i := 0; i < l; i += 2 {
  394. k := reflect.New(kt).Elem()
  395. if d.unmarshal(n.children[i], k) {
  396. e := reflect.New(et).Elem()
  397. if d.unmarshal(n.children[i+1], e) {
  398. out.SetMapIndex(k, e)
  399. }
  400. }
  401. }
  402. return true
  403. }
  404. func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
  405. fields, err := getStructFields(out.Type())
  406. if err != nil {
  407. panic(err)
  408. }
  409. name := settableValueOf("")
  410. fieldsMap := fields.Map
  411. l := len(n.children)
  412. for i := 0; i < l; i += 2 {
  413. if !d.unmarshal(n.children[i], name) {
  414. continue
  415. }
  416. if info, ok := fieldsMap[name.String()]; ok {
  417. d.unmarshal(n.children[i+1], out.Field(info.Num))
  418. }
  419. }
  420. return true
  421. }