encode.go 12 KB

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