encode.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package yaml
  2. import (
  3. "encoding"
  4. "fmt"
  5. "io"
  6. "reflect"
  7. "regexp"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. )
  14. type encoder struct {
  15. emitter yaml_emitter_t
  16. event yaml_event_t
  17. out []byte
  18. flow bool
  19. doneInit bool
  20. }
  21. func newEncoder() *encoder {
  22. e := &encoder{}
  23. yaml_emitter_initialize(&e.emitter)
  24. yaml_emitter_set_output_string(&e.emitter, &e.out)
  25. yaml_emitter_set_unicode(&e.emitter, true)
  26. return e
  27. }
  28. func newEncoderWithWriter(w io.Writer) *encoder {
  29. e := &encoder{}
  30. yaml_emitter_initialize(&e.emitter)
  31. yaml_emitter_set_output_writer(&e.emitter, w)
  32. yaml_emitter_set_unicode(&e.emitter, true)
  33. return e
  34. }
  35. func (e *encoder) init() {
  36. if e.doneInit {
  37. return
  38. }
  39. yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)
  40. e.emit()
  41. e.doneInit = true
  42. }
  43. func (e *encoder) finish() {
  44. e.emitter.open_ended = false
  45. yaml_stream_end_event_initialize(&e.event)
  46. e.emit()
  47. }
  48. func (e *encoder) destroy() {
  49. yaml_emitter_delete(&e.emitter)
  50. }
  51. func (e *encoder) emit() {
  52. // This will internally delete the e.event value.
  53. e.must(yaml_emitter_emit(&e.emitter, &e.event))
  54. }
  55. func (e *encoder) must(ok bool) {
  56. if !ok {
  57. msg := e.emitter.problem
  58. if msg == "" {
  59. msg = "unknown problem generating YAML content"
  60. }
  61. failf("%s", msg)
  62. }
  63. }
  64. func (e *encoder) marshalDoc(tag string, in reflect.Value) {
  65. e.init()
  66. var node *Node
  67. if in.IsValid() {
  68. node, _ = in.Interface().(*Node)
  69. }
  70. if node != nil && node.Kind == DocumentNode {
  71. e.nodev(in)
  72. } else {
  73. yaml_document_start_event_initialize(&e.event, nil, nil, true)
  74. e.emit()
  75. e.marshal(tag, in)
  76. yaml_document_end_event_initialize(&e.event, true)
  77. e.emit()
  78. }
  79. }
  80. func (e *encoder) marshal(tag string, in reflect.Value) {
  81. if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() {
  82. e.nilv()
  83. return
  84. }
  85. iface := in.Interface()
  86. switch value := iface.(type) {
  87. case *Node:
  88. e.nodev(in)
  89. return
  90. case time.Time:
  91. e.timev(tag, in)
  92. return
  93. case *time.Time:
  94. e.timev(tag, in.Elem())
  95. return
  96. case time.Duration:
  97. e.stringv(tag, reflect.ValueOf(value.String()))
  98. return
  99. case Marshaler:
  100. v, err := value.MarshalYAML()
  101. if err != nil {
  102. fail(err)
  103. }
  104. if v == nil {
  105. e.nilv()
  106. return
  107. }
  108. in = reflect.ValueOf(v)
  109. case encoding.TextMarshaler:
  110. text, err := value.MarshalText()
  111. if err != nil {
  112. fail(err)
  113. }
  114. in = reflect.ValueOf(string(text))
  115. case nil:
  116. e.nilv()
  117. return
  118. }
  119. switch in.Kind() {
  120. case reflect.Interface:
  121. e.marshal(tag, in.Elem())
  122. case reflect.Map:
  123. e.mapv(tag, in)
  124. case reflect.Ptr:
  125. e.marshal(tag, in.Elem())
  126. case reflect.Struct:
  127. e.structv(tag, in)
  128. case reflect.Slice, reflect.Array:
  129. e.slicev(tag, in)
  130. case reflect.String:
  131. e.stringv(tag, in)
  132. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  133. e.intv(tag, in)
  134. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  135. e.uintv(tag, in)
  136. case reflect.Float32, reflect.Float64:
  137. e.floatv(tag, in)
  138. case reflect.Bool:
  139. e.boolv(tag, in)
  140. default:
  141. panic("cannot marshal type: " + in.Type().String())
  142. }
  143. }
  144. func (e *encoder) mapv(tag string, in reflect.Value) {
  145. e.mappingv(tag, func() {
  146. keys := keyList(in.MapKeys())
  147. sort.Sort(keys)
  148. for _, k := range keys {
  149. e.marshal("", k)
  150. e.marshal("", in.MapIndex(k))
  151. }
  152. })
  153. }
  154. func (e *encoder) structv(tag string, in reflect.Value) {
  155. sinfo, err := getStructInfo(in.Type())
  156. if err != nil {
  157. panic(err)
  158. }
  159. e.mappingv(tag, func() {
  160. for _, info := range sinfo.FieldsList {
  161. var value reflect.Value
  162. if info.Inline == nil {
  163. value = in.Field(info.Num)
  164. } else {
  165. value = in.FieldByIndex(info.Inline)
  166. }
  167. if info.OmitEmpty && isZero(value) {
  168. continue
  169. }
  170. e.marshal("", reflect.ValueOf(info.Key))
  171. e.flow = info.Flow
  172. e.marshal("", value)
  173. }
  174. if sinfo.InlineMap >= 0 {
  175. m := in.Field(sinfo.InlineMap)
  176. if m.Len() > 0 {
  177. e.flow = false
  178. keys := keyList(m.MapKeys())
  179. sort.Sort(keys)
  180. for _, k := range keys {
  181. if _, found := sinfo.FieldsMap[k.String()]; found {
  182. panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String()))
  183. }
  184. e.marshal("", k)
  185. e.flow = false
  186. e.marshal("", m.MapIndex(k))
  187. }
  188. }
  189. }
  190. })
  191. }
  192. func (e *encoder) mappingv(tag string, f func()) {
  193. implicit := tag == ""
  194. style := yaml_BLOCK_MAPPING_STYLE
  195. if e.flow {
  196. e.flow = false
  197. style = yaml_FLOW_MAPPING_STYLE
  198. }
  199. yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)
  200. e.emit()
  201. f()
  202. yaml_mapping_end_event_initialize(&e.event)
  203. e.emit()
  204. }
  205. func (e *encoder) slicev(tag string, in reflect.Value) {
  206. implicit := tag == ""
  207. style := yaml_BLOCK_SEQUENCE_STYLE
  208. if e.flow {
  209. e.flow = false
  210. style = yaml_FLOW_SEQUENCE_STYLE
  211. }
  212. e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
  213. e.emit()
  214. n := in.Len()
  215. for i := 0; i < n; i++ {
  216. e.marshal("", in.Index(i))
  217. }
  218. e.must(yaml_sequence_end_event_initialize(&e.event))
  219. e.emit()
  220. }
  221. // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
  222. //
  223. // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
  224. // in YAML 1.2 and by this package, but these should be marshalled quoted for
  225. // the time being for compatibility with other parsers.
  226. func isBase60Float(s string) (result bool) {
  227. // Fast path.
  228. if s == "" {
  229. return false
  230. }
  231. c := s[0]
  232. if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {
  233. return false
  234. }
  235. // Do the full match.
  236. return base60float.MatchString(s)
  237. }
  238. // From http://yaml.org/type/float.html, except the regular expression there
  239. // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
  240. var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)
  241. func (e *encoder) stringv(tag string, in reflect.Value) {
  242. var style yaml_scalar_style_t
  243. s := in.String()
  244. canUsePlain := true
  245. switch {
  246. case !utf8.ValidString(s):
  247. if tag == yaml_BINARY_TAG {
  248. failf("explicitly tagged !!binary data must be base64-encoded")
  249. }
  250. if tag != "" {
  251. failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
  252. }
  253. // It can't be encoded directly as YAML so use a binary tag
  254. // and encode it as base64.
  255. tag = yaml_BINARY_TAG
  256. s = encodeBase64(s)
  257. case tag == "":
  258. // Check to see if it would resolve to a specific
  259. // tag when encoded unquoted. If it doesn't,
  260. // there's no need to quote it.
  261. rtag, _ := resolve("", s)
  262. canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s)
  263. }
  264. // Note: it's possible for user code to emit invalid YAML
  265. // if they explicitly specify a tag and a string containing
  266. // text that's incompatible with that tag.
  267. switch {
  268. case strings.Contains(s, "\n"):
  269. style = yaml_LITERAL_SCALAR_STYLE
  270. case canUsePlain:
  271. style = yaml_PLAIN_SCALAR_STYLE
  272. default:
  273. style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
  274. }
  275. e.emitScalar(s, "", tag, style, nil, nil, nil)
  276. }
  277. func (e *encoder) boolv(tag string, in reflect.Value) {
  278. var s string
  279. if in.Bool() {
  280. s = "true"
  281. } else {
  282. s = "false"
  283. }
  284. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil)
  285. }
  286. func (e *encoder) intv(tag string, in reflect.Value) {
  287. s := strconv.FormatInt(in.Int(), 10)
  288. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil)
  289. }
  290. func (e *encoder) uintv(tag string, in reflect.Value) {
  291. s := strconv.FormatUint(in.Uint(), 10)
  292. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil)
  293. }
  294. func (e *encoder) timev(tag string, in reflect.Value) {
  295. t := in.Interface().(time.Time)
  296. s := t.Format(time.RFC3339Nano)
  297. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil)
  298. }
  299. func (e *encoder) floatv(tag string, in reflect.Value) {
  300. // Issue #352: When formatting, use the precision of the underlying value
  301. precision := 64
  302. if in.Kind() == reflect.Float32 {
  303. precision = 32
  304. }
  305. s := strconv.FormatFloat(in.Float(), 'g', -1, precision)
  306. switch s {
  307. case "+Inf":
  308. s = ".inf"
  309. case "-Inf":
  310. s = "-.inf"
  311. case "NaN":
  312. s = ".nan"
  313. }
  314. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil)
  315. }
  316. func (e *encoder) nilv() {
  317. e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil)
  318. }
  319. func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, header, inline, footer []byte) {
  320. // TODO Kill this function. Replace all initialize calls by their underlining Go literals.
  321. implicit := tag == ""
  322. e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style))
  323. e.event.header_comment = header
  324. e.event.inline_comment = inline
  325. e.event.footer_comment = footer
  326. e.emit()
  327. }
  328. func (e *encoder) nodev(in reflect.Value) {
  329. e.node(in.Interface().(*Node))
  330. }
  331. func (e *encoder) node(node *Node) {
  332. switch node.Kind {
  333. case DocumentNode:
  334. yaml_document_start_event_initialize(&e.event, nil, nil, true)
  335. e.event.header_comment = []byte(node.Header)
  336. e.emit()
  337. for _, node := range node.Children {
  338. e.node(node)
  339. }
  340. yaml_document_end_event_initialize(&e.event, true)
  341. e.event.footer_comment = []byte(node.Footer)
  342. e.emit()
  343. case SequenceNode:
  344. style := yaml_BLOCK_SEQUENCE_STYLE
  345. if node.Style&FlowStyle != 0 {
  346. style = yaml_FLOW_SEQUENCE_STYLE
  347. }
  348. e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(node.Tag), node.implicit(), style))
  349. e.event.header_comment = []byte(node.Header)
  350. e.emit()
  351. for _, node := range node.Children {
  352. e.node(node)
  353. }
  354. e.must(yaml_sequence_end_event_initialize(&e.event))
  355. e.event.inline_comment = []byte(node.Inline)
  356. e.event.footer_comment = []byte(node.Footer)
  357. e.emit()
  358. case MappingNode:
  359. style := yaml_BLOCK_MAPPING_STYLE
  360. if node.Style&FlowStyle != 0 {
  361. style = yaml_FLOW_MAPPING_STYLE
  362. }
  363. yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(node.Tag), node.implicit(), style)
  364. e.event.header_comment = []byte(node.Header)
  365. e.emit()
  366. for i := 0; i+1 < len(node.Children); i += 2 {
  367. e.node(node.Children[i])
  368. e.node(node.Children[i+1])
  369. }
  370. yaml_mapping_end_event_initialize(&e.event)
  371. e.event.inline_comment = []byte(node.Inline)
  372. e.event.footer_comment = []byte(node.Footer)
  373. e.emit()
  374. case AliasNode:
  375. // TODO This is lacking comment handling. Test and fix.
  376. yaml_alias_event_initialize(&e.event, []byte(node.Value))
  377. e.emit()
  378. case ScalarNode:
  379. style := yaml_PLAIN_SCALAR_STYLE
  380. switch {
  381. case node.Style&DoubleQuotedStyle != 0:
  382. style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
  383. case node.Style&SingleQuotedStyle != 0:
  384. style = yaml_SINGLE_QUOTED_SCALAR_STYLE
  385. case node.Style&LiteralStyle != 0:
  386. style = yaml_LITERAL_SCALAR_STYLE
  387. case node.Style&FoldedStyle != 0:
  388. style = yaml_FOLDED_SCALAR_STYLE
  389. }
  390. if style == yaml_PLAIN_SCALAR_STYLE && strings.Contains(node.Value, "\n") {
  391. style = yaml_LITERAL_SCALAR_STYLE
  392. }
  393. e.emitScalar(node.Value, node.Anchor, node.Tag, style, []byte(node.Header), []byte(node.Inline), []byte(node.Footer))
  394. // TODO Check if binaries are being decoded into node.Value or not.
  395. //switch {
  396. //if !utf8.ValidString(s) {
  397. // if tag == yaml_BINARY_TAG {
  398. // failf("explicitly tagged !!binary data must be base64-encoded")
  399. // }
  400. // if tag != "" {
  401. // failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
  402. // }
  403. // // It can't be encoded directly as YAML so use a binary tag
  404. // // and encode it as base64.
  405. // tag = yaml_BINARY_TAG
  406. // s = encodeBase64(s)
  407. //}
  408. }
  409. }