encode.go 11 KB

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