Debian Codegraph @

encode.go

raw symbols SCIP
1 package yaml
2
3 import (
4 "context"
5 "encoding"
6 "fmt"
7 "io"
8 "math"
9 "reflect"
10 "sort"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/goccy/go-yaml/ast"
16 "github.com/goccy/go-yaml/internal/errors"
17 "github.com/goccy/go-yaml/parser"
18 "github.com/goccy/go-yaml/printer"
19 "github.com/goccy/go-yaml/token"
20 )
21
22 const (
23 // DefaultIndentSpaces default number of space for indent
24 DefaultIndentSpaces = 2
25 )
26
27 // Encoder writes YAML values to an output stream.
28 type Encoder struct {
29 writer io.Writer
30 opts []EncodeOption
31 singleQuote bool
32 isFlowStyle bool
33 isJSONStyle bool
34 useJSONMarshaler bool
35 enableSmartAnchor bool
36 aliasRefToName map[uintptr]string
37 anchorRefToName map[uintptr]string
38 anchorNameMap map[string]struct{}
39 anchorCallback func(*ast.AnchorNode, interface{}) error
40 customMarshalerMap map[reflect.Type]func(context.Context, interface{}) ([]byte, error)
41 omitZero bool
42 omitEmpty bool
43 autoInt bool
44 useLiteralStyleIfMultiline bool
45 commentMap map[*Path][]*Comment
46 written bool
47
48 line int
49 column int
50 offset int
51 indentNum int
52 indentLevel int
53 indentSequence bool
54 }
55
56 // NewEncoder returns a new encoder that writes to w.
57 // The Encoder should be closed after use to flush all data to w.
58 func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder {
59 return &Encoder{
60 writer: w,
61 opts: opts,
62 customMarshalerMap: map[reflect.Type]func(context.Context, interface{}) ([]byte, error){},
63 line: 1,
64 column: 1,
65 offset: 0,
66 indentNum: DefaultIndentSpaces,
67 anchorRefToName: make(map[uintptr]string),
68 anchorNameMap: make(map[string]struct{}),
69 aliasRefToName: make(map[uintptr]string),
70 }
71 }
72
73 // Close closes the encoder by writing any remaining data.
74 // It does not write a stream terminating string "...".
75 func (e *Encoder) Close() error {
76 return nil
77 }
78
79 // Encode writes the YAML encoding of v to the stream.
80 // If multiple items are encoded to the stream,
81 // the second and subsequent document will be preceded with a "---" document separator,
82 // but the first will not.
83 //
84 // See the documentation for Marshal for details about the conversion of Go values to YAML.
85 func (e *Encoder) Encode(v interface{}) error {
86 return e.EncodeContext(context.Background(), v)
87 }
88
89 // EncodeContext writes the YAML encoding of v to the stream with context.Context.
90 func (e *Encoder) EncodeContext(ctx context.Context, v interface{}) error {
91 node, err := e.EncodeToNodeContext(ctx, v)
92 if err != nil {
93 return err
94 }
95 if err := e.setCommentByCommentMap(node); err != nil {
96 return err
97 }
98 if !e.written {
99 e.written = true
100 } else {
101 // write document separator
102 _, _ = e.writer.Write([]byte("---\n"))
103 }
104 var p printer.Printer
105 _, _ = e.writer.Write(p.PrintNode(node))
106 return nil
107 }
108
109 // EncodeToNode convert v to ast.Node.
110 func (e *Encoder) EncodeToNode(v interface{}) (ast.Node, error) {
111 return e.EncodeToNodeContext(context.Background(), v)
112 }
113
114 // EncodeToNodeContext convert v to ast.Node with context.Context.
115 func (e *Encoder) EncodeToNodeContext(ctx context.Context, v interface{}) (ast.Node, error) {
116 for _, opt := range e.opts {
117 if err := opt(e); err != nil {
118 return nil, err
119 }
120 }
121 if e.enableSmartAnchor {
122 // during the first encoding, store all mappings between alias addresses and their names.
123 if _, err := e.encodeValue(ctx, reflect.ValueOf(v), 1); err != nil {
124 return nil, err
125 }
126 e.clearSmartAnchorRef()
127 }
128 node, err := e.encodeValue(ctx, reflect.ValueOf(v), 1)
129 if err != nil {
130 return nil, err
131 }
132 return node, nil
133 }
134
135 func (e *Encoder) setCommentByCommentMap(node ast.Node) error {
136 if e.commentMap == nil {
137 return nil
138 }
139 for path, comments := range e.commentMap {
140 n, err := path.FilterNode(node)
141 if err != nil {
142 return err
143 }
144 if n == nil {
145 continue
146 }
147 for _, comment := range comments {
148 commentTokens := []*token.Token{}
149 for _, text := range comment.Texts {
150 commentTokens = append(commentTokens, token.New(text, text, nil))
151 }
152 commentGroup := ast.CommentGroup(commentTokens)
153 switch comment.Position {
154 case CommentHeadPosition:
155 if err := e.setHeadComment(node, n, commentGroup); err != nil {
156 return err
157 }
158 case CommentLinePosition:
159 if err := e.setLineComment(node, n, commentGroup); err != nil {
160 return err
161 }
162 case CommentFootPosition:
163 if err := e.setFootComment(node, n, commentGroup); err != nil {
164 return err
165 }
166 default:
167 return ErrUnknownCommentPositionType
168 }
169 }
170 }
171 return nil
172 }
173
174 func (e *Encoder) setHeadComment(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error {
175 parent := ast.Parent(node, filtered)
176 if parent == nil {
177 return ErrUnsupportedHeadPositionType(node)
178 }
179 switch p := parent.(type) {
180 case *ast.MappingValueNode:
181 if err := p.SetComment(comment); err != nil {
182 return err
183 }
184 case *ast.MappingNode:
185 if err := p.SetComment(comment); err != nil {
186 return err
187 }
188 case *ast.SequenceNode:
189 if len(p.ValueHeadComments) == 0 {
190 p.ValueHeadComments = make([]*ast.CommentGroupNode, len(p.Values))
191 }
192 var foundIdx int
193 for idx, v := range p.Values {
194 if v == filtered {
195 foundIdx = idx
196 break
197 }
198 }
199 p.ValueHeadComments[foundIdx] = comment
200 default:
201 return ErrUnsupportedHeadPositionType(node)
202 }
203 return nil
204 }
205
206 func (e *Encoder) setLineComment(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error {
207 switch filtered.(type) {
208 case *ast.MappingValueNode, *ast.SequenceNode:
209 // Line comment cannot be set for mapping value node.
210 // It should probably be set for the parent map node
211 if err := e.setLineCommentToParentMapNode(node, filtered, comment); err != nil {
212 return err
213 }
214 default:
215 if err := filtered.SetComment(comment); err != nil {
216 return err
217 }
218 }
219 return nil
220 }
221
222 func (e *Encoder) setLineCommentToParentMapNode(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error {
223 parent := ast.Parent(node, filtered)
224 if parent == nil {
225 return ErrUnsupportedLinePositionType(node)
226 }
227 switch p := parent.(type) {
228 case *ast.MappingValueNode:
229 if err := p.Key.SetComment(comment); err != nil {
230 return err
231 }
232 case *ast.MappingNode:
233 if err := p.SetComment(comment); err != nil {
234 return err
235 }
236 default:
237 return ErrUnsupportedLinePositionType(parent)
238 }
239 return nil
240 }
241
242 func (e *Encoder) setFootComment(node ast.Node, filtered ast.Node, comment *ast.CommentGroupNode) error {
243 parent := ast.Parent(node, filtered)
244 if parent == nil {
245 return ErrUnsupportedFootPositionType(node)
246 }
247 switch n := parent.(type) {
248 case *ast.MappingValueNode:
249 n.FootComment = comment
250 case *ast.MappingNode:
251 n.FootComment = comment
252 case *ast.SequenceNode:
253 n.FootComment = comment
254 default:
255 return ErrUnsupportedFootPositionType(n)
256 }
257 return nil
258 }
259
260 func (e *Encoder) encodeDocument(doc []byte) (ast.Node, error) {
261 f, err := parser.ParseBytes(doc, 0)
262 if err != nil {
263 return nil, err
264 }
265 for _, docNode := range f.Docs {
266 if docNode.Body != nil {
267 return docNode.Body, nil
268 }
269 }
270 return nil, nil
271 }
272
273 func (e *Encoder) isInvalidValue(v reflect.Value) bool {
274 if !v.IsValid() {
275 return true
276 }
277 kind := v.Type().Kind()
278 if kind == reflect.Ptr && v.IsNil() {
279 return true
280 }
281 if kind == reflect.Interface && v.IsNil() {
282 return true
283 }
284 return false
285 }
286
287 type jsonMarshaler interface {
288 MarshalJSON() ([]byte, error)
289 }
290
291 func (e *Encoder) existsTypeInCustomMarshalerMap(t reflect.Type) bool {
292 if _, exists := e.customMarshalerMap[t]; exists {
293 return true
294 }
295
296 globalCustomMarshalerMu.Lock()
297 defer globalCustomMarshalerMu.Unlock()
298 if _, exists := globalCustomMarshalerMap[t]; exists {
299 return true
300 }
301 return false
302 }
303
304 func (e *Encoder) marshalerFromCustomMarshalerMap(t reflect.Type) (func(context.Context, interface{}) ([]byte, error), bool) {
305 if marshaler, exists := e.customMarshalerMap[t]; exists {
306 return marshaler, exists
307 }
308
309 globalCustomMarshalerMu.Lock()
310 defer globalCustomMarshalerMu.Unlock()
311 if marshaler, exists := globalCustomMarshalerMap[t]; exists {
312 return marshaler, exists
313 }
314 return nil, false
315 }
316
317 func (e *Encoder) canEncodeByMarshaler(v reflect.Value) bool {
318 if !v.CanInterface() {
319 return false
320 }
321 if e.existsTypeInCustomMarshalerMap(v.Type()) {
322 return true
323 }
324 iface := v.Interface()
325 switch iface.(type) {
326 case BytesMarshalerContext:
327 return true
328 case BytesMarshaler:
329 return true
330 case InterfaceMarshalerContext:
331 return true
332 case InterfaceMarshaler:
333 return true
334 case time.Time, *time.Time:
335 return true
336 case time.Duration:
337 return true
338 case encoding.TextMarshaler:
339 return true
340 case jsonMarshaler:
341 return e.useJSONMarshaler
342 }
343 return false
344 }
345
346 func (e *Encoder) encodeByMarshaler(ctx context.Context, v reflect.Value, column int) (ast.Node, error) {
347 iface := v.Interface()
348
349 if marshaler, exists := e.marshalerFromCustomMarshalerMap(v.Type()); exists {
350 doc, err := marshaler(ctx, iface)
351 if err != nil {
352 return nil, err
353 }
354 node, err := e.encodeDocument(doc)
355 if err != nil {
356 return nil, err
357 }
358 return node, nil
359 }
360
361 if marshaler, ok := iface.(BytesMarshalerContext); ok {
362 doc, err := marshaler.MarshalYAML(ctx)
363 if err != nil {
364 return nil, err
365 }
366 node, err := e.encodeDocument(doc)
367 if err != nil {
368 return nil, err
369 }
370 return node, nil
371 }
372
373 if marshaler, ok := iface.(BytesMarshaler); ok {
374 doc, err := marshaler.MarshalYAML()
375 if err != nil {
376 return nil, err
377 }
378 node, err := e.encodeDocument(doc)
379 if err != nil {
380 return nil, err
381 }
382 return node, nil
383 }
384
385 if marshaler, ok := iface.(InterfaceMarshalerContext); ok {
386 marshalV, err := marshaler.MarshalYAML(ctx)
387 if err != nil {
388 return nil, err
389 }
390 return e.encodeValue(ctx, reflect.ValueOf(marshalV), column)
391 }
392
393 if marshaler, ok := iface.(InterfaceMarshaler); ok {
394 marshalV, err := marshaler.MarshalYAML()
395 if err != nil {
396 return nil, err
397 }
398 return e.encodeValue(ctx, reflect.ValueOf(marshalV), column)
399 }
400
401 if t, ok := iface.(time.Time); ok {
402 return e.encodeTime(t, column), nil
403 }
404 // Handle *time.Time explicitly since it implements TextMarshaler and shouldn't be treated as plain text
405 if t, ok := iface.(*time.Time); ok && t != nil {
406 return e.encodeTime(*t, column), nil
407 }
408
409 if t, ok := iface.(time.Duration); ok {
410 return e.encodeDuration(t, column), nil
411 }
412
413 if marshaler, ok := iface.(encoding.TextMarshaler); ok {
414 text, err := marshaler.MarshalText()
415 if err != nil {
416 return nil, err
417 }
418 node := e.encodeString(string(text), column)
419 return node, nil
420 }
421
422 if e.useJSONMarshaler {
423 if marshaler, ok := iface.(jsonMarshaler); ok {
424 jsonBytes, err := marshaler.MarshalJSON()
425 if err != nil {
426 return nil, err
427 }
428 doc, err := JSONToYAML(jsonBytes)
429 if err != nil {
430 return nil, err
431 }
432 node, err := e.encodeDocument(doc)
433 if err != nil {
434 return nil, err
435 }
436 return node, nil
437 }
438 }
439
440 return nil, errors.New("does not implemented Marshaler")
441 }
442
443 func (e *Encoder) encodeValue(ctx context.Context, v reflect.Value, column int) (ast.Node, error) {
444 if e.isInvalidValue(v) {
445 return e.encodeNil(), nil
446 }
447 if e.canEncodeByMarshaler(v) {
448 node, err := e.encodeByMarshaler(ctx, v, column)
449 if err != nil {
450 return nil, err
451 }
452 return node, nil
453 }
454 switch v.Type().Kind() {
455 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
456 return e.encodeInt(v.Int()), nil
457 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
458 return e.encodeUint(v.Uint()), nil
459 case reflect.Float32:
460 return e.encodeFloat(v.Float(), 32), nil
461 case reflect.Float64:
462 return e.encodeFloat(v.Float(), 64), nil
463 case reflect.Ptr:
464 if value := e.encodePtrAnchor(v, column); value != nil {
465 return value, nil
466 }
467 return e.encodeValue(ctx, v.Elem(), column)
468 case reflect.Interface:
469 return e.encodeValue(ctx, v.Elem(), column)
470 case reflect.String:
471 return e.encodeString(v.String(), column), nil
472 case reflect.Bool:
473 return e.encodeBool(v.Bool()), nil
474 case reflect.Slice:
475 if mapSlice, ok := v.Interface().(MapSlice); ok {
476 return e.encodeMapSlice(ctx, mapSlice, column)
477 }
478 if value := e.encodePtrAnchor(v, column); value != nil {
479 return value, nil
480 }
481 return e.encodeSlice(ctx, v)
482 case reflect.Array:
483 return e.encodeArray(ctx, v)
484 case reflect.Struct:
485 if v.CanInterface() {
486 if mapItem, ok := v.Interface().(MapItem); ok {
487 return e.encodeMapItem(ctx, mapItem, column)
488 }
489 if t, ok := v.Interface().(time.Time); ok {
490 return e.encodeTime(t, column), nil
491 }
492 }
493 return e.encodeStruct(ctx, v, column)
494 case reflect.Map:
495 if value := e.encodePtrAnchor(v, column); value != nil {
496 return value, nil
497 }
498 return e.encodeMap(ctx, v, column)
499 default:
500 return nil, fmt.Errorf("unknown value type %s", v.Type().String())
501 }
502 }
503
504 func (e *Encoder) encodePtrAnchor(v reflect.Value, column int) ast.Node {
505 anchorName, exists := e.getAnchor(v.Pointer())
506 if !exists {
507 return nil
508 }
509 aliasName := anchorName
510 alias := ast.Alias(token.New("*", "*", e.pos(column)))
511 alias.Value = ast.String(token.New(aliasName, aliasName, e.pos(column)))
512 e.setSmartAlias(aliasName, v.Pointer())
513 return alias
514 }
515
516 func (e *Encoder) pos(column int) *token.Position {
517 return &token.Position{
518 Line: e.line,
519 Column: column,
520 Offset: e.offset,
521 IndentNum: e.indentNum,
522 IndentLevel: e.indentLevel,
523 }
524 }
525
526 func (e *Encoder) encodeNil() *ast.NullNode {
527 value := "null"
528 return ast.Null(token.New(value, value, e.pos(e.column)))
529 }
530
531 func (e *Encoder) encodeInt(v int64) *ast.IntegerNode {
532 value := strconv.FormatInt(v, 10)
533 return ast.Integer(token.New(value, value, e.pos(e.column)))
534 }
535
536 func (e *Encoder) encodeUint(v uint64) *ast.IntegerNode {
537 value := strconv.FormatUint(v, 10)
538 return ast.Integer(token.New(value, value, e.pos(e.column)))
539 }
540
541 func (e *Encoder) encodeFloat(v float64, bitSize int) ast.Node {
542 if v == math.Inf(0) {
543 value := ".inf"
544 return ast.Infinity(token.New(value, value, e.pos(e.column)))
545 } else if v == math.Inf(-1) {
546 value := "-.inf"
547 return ast.Infinity(token.New(value, value, e.pos(e.column)))
548 } else if math.IsNaN(v) {
549 value := ".nan"
550 return ast.Nan(token.New(value, value, e.pos(e.column)))
551 }
552 value := strconv.FormatFloat(v, 'g', -1, bitSize)
553 if !strings.Contains(value, ".") && !strings.Contains(value, "e") {
554 if e.autoInt {
555 return ast.Integer(token.New(value, value, e.pos(e.column)))
556 }
557 // append x.0 suffix to keep float value context
558 value = fmt.Sprintf("%s.0", value)
559 }
560 return ast.Float(token.New(value, value, e.pos(e.column)))
561 }
562
563 func (e *Encoder) isNeedQuoted(v string) bool {
564 if e.isJSONStyle {
565 return true
566 }
567 if e.useLiteralStyleIfMultiline && strings.ContainsAny(v, "\n\r") {
568 return false
569 }
570 if e.isFlowStyle && strings.ContainsAny(v, `]},'"`) {
571 return true
572 }
573 if e.isFlowStyle {
574 for i := 0; i < len(v); i++ {
575 if v[i] != ':' {
576 continue
577 }
578 if i+1 < len(v) && v[i+1] == '/' {
579 continue
580 }
581 return true
582 }
583 }
584 if token.IsNeedQuoted(v) {
585 return true
586 }
587 return false
588 }
589
590 func (e *Encoder) encodeString(v string, column int) *ast.StringNode {
591 if e.isNeedQuoted(v) {
592 if e.singleQuote {
593 v = quoteWith(v, '\'')
594 } else {
595 v = strconv.Quote(v)
596 }
597 }
598 return ast.String(token.New(v, v, e.pos(column)))
599 }
600
601 func (e *Encoder) encodeBool(v bool) *ast.BoolNode {
602 value := strconv.FormatBool(v)
603 return ast.Bool(token.New(value, value, e.pos(e.column)))
604 }
605
606 func (e *Encoder) encodeSlice(ctx context.Context, value reflect.Value) (*ast.SequenceNode, error) {
607 if e.indentSequence {
608 e.column += e.indentNum
609 defer func() { e.column -= e.indentNum }()
610 }
611 column := e.column
612 sequence := ast.Sequence(token.New("-", "-", e.pos(column)), e.isFlowStyle)
613 for i := 0; i < value.Len(); i++ {
614 node, err := e.encodeValue(ctx, value.Index(i), column)
615 if err != nil {
616 return nil, err
617 }
618 sequence.Values = append(sequence.Values, node)
619 }
620 return sequence, nil
621 }
622
623 func (e *Encoder) encodeArray(ctx context.Context, value reflect.Value) (*ast.SequenceNode, error) {
624 if e.indentSequence {
625 e.column += e.indentNum
626 defer func() { e.column -= e.indentNum }()
627 }
628 column := e.column
629 sequence := ast.Sequence(token.New("-", "-", e.pos(column)), e.isFlowStyle)
630 for i := 0; i < value.Len(); i++ {
631 node, err := e.encodeValue(ctx, value.Index(i), column)
632 if err != nil {
633 return nil, err
634 }
635 sequence.Values = append(sequence.Values, node)
636 }
637 return sequence, nil
638 }
639
640 func (e *Encoder) encodeMapItem(ctx context.Context, item MapItem, column int) (*ast.MappingValueNode, error) {
641 k := reflect.ValueOf(item.Key)
642 v := reflect.ValueOf(item.Value)
643 value, err := e.encodeValue(ctx, v, column)
644 if err != nil {
645 return nil, err
646 }
647 if e.isMapNode(value) {
648 value.AddColumn(e.indentNum)
649 }
650 if e.isTagAndMapNode(value) {
651 value.AddColumn(e.indentNum)
652 }
653 return ast.MappingValue(
654 token.New("", "", e.pos(column)),
655 e.encodeString(k.Interface().(string), column),
656 value,
657 ), nil
658 }
659
660 func (e *Encoder) encodeMapSlice(ctx context.Context, value MapSlice, column int) (*ast.MappingNode, error) {
661 node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle)
662 for _, item := range value {
663 encoded, err := e.encodeMapItem(ctx, item, column)
664 if err != nil {
665 return nil, err
666 }
667 node.Values = append(node.Values, encoded)
668 }
669 return node, nil
670 }
671
672 func (e *Encoder) isMapNode(node ast.Node) bool {
673 _, ok := node.(ast.MapNode)
674 return ok
675 }
676
677 func (e *Encoder) isTagAndMapNode(node ast.Node) bool {
678 tn, ok := node.(*ast.TagNode)
679 return ok && e.isMapNode(tn.Value)
680 }
681
682 func (e *Encoder) encodeMap(ctx context.Context, value reflect.Value, column int) (ast.Node, error) {
683 node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle)
684 keys := make([]interface{}, len(value.MapKeys()))
685 for i, k := range value.MapKeys() {
686 keys[i] = k.Interface()
687 }
688 sort.Slice(keys, func(i, j int) bool {
689 return fmt.Sprint(keys[i]) < fmt.Sprint(keys[j])
690 })
691 for _, key := range keys {
692 k := reflect.ValueOf(key)
693 v := value.MapIndex(k)
694 encoded, err := e.encodeValue(ctx, v, column)
695 if err != nil {
696 return nil, err
697 }
698 if e.isMapNode(encoded) {
699 encoded.AddColumn(e.indentNum)
700 }
701 if e.isTagAndMapNode(encoded) {
702 encoded.AddColumn(e.indentNum)
703 }
704 keyText := fmt.Sprint(key)
705 vRef := e.toPointer(v)
706
707 // during the second encoding, an anchor is assigned if it is found to be used by an alias.
708 if aliasName, exists := e.getSmartAlias(vRef); exists {
709 anchorName := aliasName
710 anchorNode := ast.Anchor(token.New("&", "&", e.pos(column)))
711 anchorNode.Name = ast.String(token.New(anchorName, anchorName, e.pos(column)))
712 anchorNode.Value = encoded
713 encoded = anchorNode
714 }
715 node.Values = append(node.Values, ast.MappingValue(
716 nil,
717 e.encodeString(keyText, column),
718 encoded,
719 ))
720 e.setSmartAnchor(vRef, keyText)
721 }
722 return node, nil
723 }
724
725 // IsZeroer is used to check whether an object is zero to determine
726 // whether it should be omitted when marshaling with the omitempty flag.
727 // One notable implementation is time.Time.
728 type IsZeroer interface {
729 IsZero() bool
730 }
731
732 func (e *Encoder) isOmittedByOmitZero(v reflect.Value) bool {
733 kind := v.Kind()
734 if z, ok := v.Interface().(IsZeroer); ok {
735 if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() {
736 return true
737 }
738 return z.IsZero()
739 }
740 switch kind {
741 case reflect.String:
742 return len(v.String()) == 0
743 case reflect.Interface, reflect.Ptr, reflect.Slice, reflect.Map:
744 return v.IsNil()
745 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
746 return v.Int() == 0
747 case reflect.Float32, reflect.Float64:
748 return v.Float() == 0
749 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
750 return v.Uint() == 0
751 case reflect.Bool:
752 return !v.Bool()
753 case reflect.Struct:
754 vt := v.Type()
755 for i := v.NumField() - 1; i >= 0; i-- {
756 if vt.Field(i).PkgPath != "" {
757 continue // private field
758 }
759 if !e.isOmittedByOmitZero(v.Field(i)) {
760 return false
761 }
762 }
763 return true
764 }
765 return false
766 }
767
768 func (e *Encoder) isOmittedByOmitEmptyOption(v reflect.Value) bool {
769 switch v.Kind() {
770 case reflect.String:
771 return len(v.String()) == 0
772 case reflect.Interface, reflect.Ptr:
773 return v.IsNil()
774 case reflect.Slice, reflect.Map:
775 return v.Len() == 0
776 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
777 return v.Int() == 0
778 case reflect.Float32, reflect.Float64:
779 return v.Float() == 0
780 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
781 return v.Uint() == 0
782 case reflect.Bool:
783 return !v.Bool()
784 }
785 return false
786 }
787
788 // The current implementation of the omitempty tag combines the functionality of encoding/json's omitempty and omitzero tags.
789 // This stems from a historical decision to respect the implementation of gopkg.in/yaml.v2, but it has caused confusion,
790 // so we are working to integrate it into the functionality of encoding/json. (However, this will take some time.)
791 // In the current implementation, in addition to the exclusion conditions of omitempty,
792 // if a type implements IsZero, that implementation will be used.
793 // Furthermore, for non-pointer structs, if all fields are eligible for exclusion,
794 // the struct itself will also be excluded. These behaviors are originally the functionality of omitzero.
795 func (e *Encoder) isOmittedByOmitEmptyTag(v reflect.Value) bool {
796 kind := v.Kind()
797 if z, ok := v.Interface().(IsZeroer); ok {
798 if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() {
799 return true
800 }
801 return z.IsZero()
802 }
803 switch kind {
804 case reflect.String:
805 return len(v.String()) == 0
806 case reflect.Interface, reflect.Ptr:
807 return v.IsNil()
808 case reflect.Slice, reflect.Map:
809 return v.Len() == 0
810 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
811 return v.Int() == 0
812 case reflect.Float32, reflect.Float64:
813 return v.Float() == 0
814 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
815 return v.Uint() == 0
816 case reflect.Bool:
817 return !v.Bool()
818 case reflect.Struct:
819 vt := v.Type()
820 for i := v.NumField() - 1; i >= 0; i-- {
821 if vt.Field(i).PkgPath != "" {
822 continue // private field
823 }
824 if !e.isOmittedByOmitEmptyTag(v.Field(i)) {
825 return false
826 }
827 }
828 return true
829 }
830 return false
831 }
832
833 func (e *Encoder) encodeTime(v time.Time, column int) *ast.StringNode {
834 value := v.Format(time.RFC3339Nano)
835 if e.isJSONStyle {
836 value = strconv.Quote(value)
837 }
838 return ast.String(token.New(value, value, e.pos(column)))
839 }
840
841 func (e *Encoder) encodeDuration(v time.Duration, column int) *ast.StringNode {
842 value := v.String()
843 if e.isJSONStyle {
844 value = strconv.Quote(value)
845 }
846 return ast.String(token.New(value, value, e.pos(column)))
847 }
848
849 func (e *Encoder) encodeAnchor(anchorName string, value ast.Node, fieldValue reflect.Value, column int) (*ast.AnchorNode, error) {
850 anchorNode := ast.Anchor(token.New("&", "&", e.pos(column)))
851 anchorNode.Name = ast.String(token.New(anchorName, anchorName, e.pos(column)))
852 anchorNode.Value = value
853 if e.anchorCallback != nil {
854 if err := e.anchorCallback(anchorNode, fieldValue.Interface()); err != nil {
855 return nil, err
856 }
857 if snode, ok := anchorNode.Name.(*ast.StringNode); ok {
858 anchorName = snode.Value
859 }
860 }
861 if fieldValue.Kind() == reflect.Ptr {
862 e.setAnchor(fieldValue.Pointer(), anchorName)
863 }
864 return anchorNode, nil
865 }
866
867 func (e *Encoder) encodeStruct(ctx context.Context, value reflect.Value, column int) (ast.Node, error) {
868 node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle)
869 structType := value.Type()
870 fieldMap, err := structFieldMap(structType)
871 if err != nil {
872 return nil, err
873 }
874 hasInlineAnchorField := false
875 var inlineAnchorValue reflect.Value
876 for i := 0; i < value.NumField(); i++ {
877 field := structType.Field(i)
878 if isIgnoredStructField(field) {
879 continue
880 }
881 fieldValue := value.FieldByName(field.Name)
882 sf := fieldMap[field.Name]
883 if (e.omitZero || sf.IsOmitZero) && e.isOmittedByOmitZero(fieldValue) {
884 // omit encoding by omitzero tag or OmitZero option.
885 continue
886 }
887 if e.omitEmpty && e.isOmittedByOmitEmptyOption(fieldValue) {
888 // omit encoding by OmitEmpty option.
889 continue
890 }
891 if sf.IsOmitEmpty && e.isOmittedByOmitEmptyTag(fieldValue) {
892 // omit encoding by omitempty tag.
893 continue
894 }
895 ve := e
896 if !e.isFlowStyle && sf.IsFlow {
897 ve = &Encoder{}
898 *ve = *e
899 ve.isFlowStyle = true
900 }
901 encoded, err := ve.encodeValue(ctx, fieldValue, column)
902 if err != nil {
903 return nil, err
904 }
905 if e.isMapNode(encoded) {
906 encoded.AddColumn(e.indentNum)
907 }
908 var key ast.MapKeyNode = e.encodeString(sf.RenderName, column)
909 switch {
910 case encoded.Type() == ast.AliasType:
911 if aliasName := sf.AliasName; aliasName != "" {
912 alias, ok := encoded.(*ast.AliasNode)
913 if !ok {
914 return nil, errors.ErrUnexpectedNodeType(encoded.Type(), ast.AliasType, encoded.GetToken())
915 }
916 got := alias.Value.String()
917 if aliasName != got {
918 return nil, fmt.Errorf("expected alias name is %q but got %q", aliasName, got)
919 }
920 }
921 if sf.IsInline {
922 // if both used alias and inline, output `<<: *alias`
923 key = ast.MergeKey(token.New("<<", "<<", e.pos(column)))
924 }
925 case sf.AnchorName != "":
926 anchorNode, err := e.encodeAnchor(sf.AnchorName, encoded, fieldValue, column)
927 if err != nil {
928 return nil, err
929 }
930 encoded = anchorNode
931 case sf.IsInline:
932 isAutoAnchor := sf.IsAutoAnchor
933 if !hasInlineAnchorField {
934 hasInlineAnchorField = isAutoAnchor
935 }
936 if isAutoAnchor {
937 inlineAnchorValue = fieldValue
938 }
939 mapNode, ok := encoded.(ast.MapNode)
940 if !ok {
941 // if an inline field is null, skip encoding it
942 if _, ok := encoded.(*ast.NullNode); ok {
943 continue
944 }
945 return nil, errors.New("inline value is must be map or struct type")
946 }
947 mapIter := mapNode.MapRange()
948 for mapIter.Next() {
949 mapKey := mapIter.Key()
950 mapValue := mapIter.Value()
951 keyName := mapKey.GetToken().Value
952 if fieldMap.isIncludedRenderName(keyName) {
953 // if declared the same key name, skip encoding this field
954 continue
955 }
956 mapKey.AddColumn(-e.indentNum)
957 mapValue.AddColumn(-e.indentNum)
958 node.Values = append(node.Values, ast.MappingValue(nil, mapKey, mapValue))
959 }
960 continue
961 case sf.IsAutoAnchor:
962 anchorNode, err := e.encodeAnchor(sf.RenderName, encoded, fieldValue, column)
963 if err != nil {
964 return nil, err
965 }
966 encoded = anchorNode
967 }
968 node.Values = append(node.Values, ast.MappingValue(nil, key, encoded))
969 }
970 if hasInlineAnchorField {
971 node.AddColumn(e.indentNum)
972 anchorName := "anchor"
973 anchorNode := ast.Anchor(token.New("&", "&", e.pos(column)))
974 anchorNode.Name = ast.String(token.New(anchorName, anchorName, e.pos(column)))
975 anchorNode.Value = node
976 if e.anchorCallback != nil {
977 if err := e.anchorCallback(anchorNode, value.Addr().Interface()); err != nil {
978 return nil, err
979 }
980 if snode, ok := anchorNode.Name.(*ast.StringNode); ok {
981 anchorName = snode.Value
982 }
983 }
984 if inlineAnchorValue.Kind() == reflect.Ptr {
985 e.setAnchor(inlineAnchorValue.Pointer(), anchorName)
986 }
987 return anchorNode, nil
988 }
989 return node, nil
990 }
991
992 func (e *Encoder) toPointer(v reflect.Value) uintptr {
993 if e.isInvalidValue(v) {
994 return 0
995 }
996
997 switch v.Type().Kind() {
998 case reflect.Ptr:
999 return v.Pointer()
1000 case reflect.Interface:
1001 return e.toPointer(v.Elem())
1002 case reflect.Slice:
1003 return v.Pointer()
1004 case reflect.Map:
1005 return v.Pointer()
1006 }
1007 return 0
1008 }
1009
1010 func (e *Encoder) clearSmartAnchorRef() {
1011 if !e.enableSmartAnchor {
1012 return
1013 }
1014 e.anchorRefToName = make(map[uintptr]string)
1015 e.anchorNameMap = make(map[string]struct{})
1016 }
1017
1018 func (e *Encoder) setSmartAnchor(ptr uintptr, name string) {
1019 if !e.enableSmartAnchor {
1020 return
1021 }
1022 e.setAnchor(ptr, e.generateAnchorName(name))
1023 }
1024
1025 func (e *Encoder) setAnchor(ptr uintptr, name string) {
1026 if ptr == 0 {
1027 return
1028 }
1029 if name == "" {
1030 return
1031 }
1032 e.anchorRefToName[ptr] = name
1033 e.anchorNameMap[name] = struct{}{}
1034 }
1035
1036 func (e *Encoder) generateAnchorName(base string) string {
1037 if _, exists := e.anchorNameMap[base]; !exists {
1038 return base
1039 }
1040 for i := 1; i < 100; i++ {
1041 name := base + strconv.Itoa(i)
1042 if _, exists := e.anchorNameMap[name]; exists {
1043 continue
1044 }
1045 return name
1046 }
1047 return ""
1048 }
1049
1050 func (e *Encoder) getAnchor(ref uintptr) (string, bool) {
1051 anchorName, exists := e.anchorRefToName[ref]
1052 return anchorName, exists
1053 }
1054
1055 func (e *Encoder) setSmartAlias(name string, ref uintptr) {
1056 if !e.enableSmartAnchor {
1057 return
1058 }
1059 e.aliasRefToName[ref] = name
1060 }
1061
1062 func (e *Encoder) getSmartAlias(ref uintptr) (string, bool) {
1063 if !e.enableSmartAnchor {
1064 return "", false
1065 }
1066 aliasName, exists := e.aliasRefToName[ref]
1067 return aliasName, exists
1068 }