encode.go 11 KB

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