Debian Codegraph @

internal/libyaml/representer.go

raw symbols SCIP
1 // Copyright 2011-2019 Canonical Ltd
2 // Copyright 2025 The go-yaml Project Contributors
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Representer stage: Converts Go values to YAML nodes.
6 // Handles representing from Go types to the intermediate node representation.
7
8 package libyaml
9
10 import (
11 "encoding"
12 "reflect"
13 "regexp"
14 "sort"
15 "strconv"
16 "strings"
17 "time"
18 "unicode"
19 "unicode/utf8"
20 )
21
22 // keyList is a sortable slice of reflect.Values used for sorting map keys
23 // in a natural order (numeric, then lexicographic).
24 type keyList []reflect.Value
25
26 // Representer converts Go values to YAML node trees with configurable
27 // formatting options.
28 type Representer struct {
29 flow bool
30 Indent int
31 lineWidth int
32 explicitStart bool
33 explicitEnd bool
34 flowSimpleCollections bool
35 quotePreference QuoteStyle
36 }
37
38 // NewRepresenter creates a new YAML representer with the given options.
39 func NewRepresenter(opts *Options) *Representer {
40 return &Representer{
41 Indent: opts.Indent,
42 lineWidth: opts.LineWidth,
43 explicitStart: opts.ExplicitStart,
44 explicitEnd: opts.ExplicitEnd,
45 flowSimpleCollections: opts.FlowSimpleCollections,
46 quotePreference: opts.QuotePreference,
47 }
48 }
49
50 // Represent converts a Go value to a YAML node tree.
51 // This is the primary method for the Representer stage in the dump pipeline.
52 func (r *Representer) Represent(tag string, in reflect.Value) *Node {
53 var node *Node
54 if in.IsValid() {
55 node, _ = in.Interface().(*Node)
56 }
57 if node != nil && node.Kind == DocumentNode {
58 // Already a document node, return as-is
59 return node
60 } else {
61 // Wrap the represented value in a document node
62 contentNode := r.represent(tag, in)
63 return &Node{
64 Kind: DocumentNode,
65 Content: []*Node{contentNode},
66 }
67 }
68 }
69
70 // From http://yaml.org/type/float.html, except the regular expression there
71 // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
72 var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)
73
74 // represent is the core conversion method that handles the actual
75 // type-specific conversion from Go values to YAML nodes.
76 func (r *Representer) represent(tag string, in reflect.Value) *Node {
77 tag = shortTag(tag)
78 if !in.IsValid() || in.Kind() == reflect.Pointer && in.IsNil() {
79 return r.nilv()
80 }
81 iface := in.Interface()
82 switch value := iface.(type) {
83 case *Node:
84 return r.nodev(in)
85 case Node:
86 if !in.CanAddr() {
87 n := reflect.New(in.Type()).Elem()
88 n.Set(in)
89 in = n
90 }
91 return r.nodev(in.Addr())
92 case time.Time:
93 return r.timev(tag, in)
94 case *time.Time:
95 return r.timev(tag, in.Elem())
96 case time.Duration:
97 return r.stringv(tag, reflect.ValueOf(value.String()))
98 case Marshaler:
99 v, err := value.MarshalYAML()
100 if err != nil {
101 failDump(RepresenterStage, err)
102 }
103 if v == nil {
104 return r.nilv()
105 }
106 return r.represent(tag, reflect.ValueOf(v))
107 case encoding.TextMarshaler:
108 text, err := value.MarshalText()
109 if err != nil {
110 failDump(RepresenterStage, err)
111 }
112 in = reflect.ValueOf(string(text))
113 case nil:
114 return r.nilv()
115 }
116 switch in.Kind() {
117 case reflect.Interface:
118 return r.represent(tag, in.Elem())
119 case reflect.Map:
120 return r.mapv(tag, in)
121 case reflect.Pointer:
122 return r.represent(tag, in.Elem())
123 case reflect.Struct:
124 return r.structv(tag, in)
125 case reflect.Slice, reflect.Array:
126 return r.slicev(tag, in)
127 case reflect.String:
128 return r.stringv(tag, in)
129 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
130 return r.intv(tag, in)
131 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
132 return r.uintv(tag, in)
133 case reflect.Float32, reflect.Float64:
134 return r.floatv(tag, in)
135 case reflect.Bool:
136 return r.boolv(tag, in)
137 default:
138 failDumpf(RepresenterStage, "cannot represent type: %s", in.Type().String())
139 return nil // unreachable; failDumpf always panics
140 }
141 }
142
143 // mapv converts a Go map to a YAML mapping node with sorted keys.
144 func (r *Representer) mapv(tag string, in reflect.Value) *Node {
145 if tag == "" {
146 tag = mapTag
147 }
148 var style Style
149 if r.flow {
150 r.flow = false
151 style = FlowStyle
152 }
153
154 keys := keyList(in.MapKeys())
155 sort.Sort(keys)
156 content := make([]*Node, 0, len(keys)*2)
157 for _, k := range keys {
158 content = append(content, r.represent("", k))
159 content = append(content, r.represent("", in.MapIndex(k)))
160 }
161
162 return &Node{
163 Kind: MappingNode,
164 Tag: tag,
165 Content: content,
166 Style: style,
167 }
168 }
169
170 // structv converts a Go struct to a YAML mapping node, handling field tags,
171 // omitempty, inline fields, and inline maps.
172 func (r *Representer) structv(tag string, in reflect.Value) *Node {
173 sinfo, err := getStructInfo(in.Type())
174 if err != nil {
175 failDump(RepresenterStage, err)
176 }
177
178 if tag == "" {
179 tag = mapTag
180 }
181 var style Style
182 if r.flow {
183 r.flow = false
184 style = FlowStyle
185 }
186
187 content := make([]*Node, 0)
188 for _, info := range sinfo.FieldsList {
189 var value reflect.Value
190 if info.Inline == nil {
191 value = in.Field(info.Num)
192 } else {
193 value = r.fieldByIndex(in, info.Inline)
194 if !value.IsValid() {
195 continue
196 }
197 }
198 if info.OmitEmpty && isZero(value) {
199 continue
200 }
201 content = append(content, r.represent("", reflect.ValueOf(info.Key)))
202 r.flow = info.Flow
203 content = append(content, r.represent("", value))
204 }
205 if sinfo.InlineMap >= 0 {
206 m := in.Field(sinfo.InlineMap)
207 if m.Len() > 0 {
208 r.flow = false
209 keys := keyList(m.MapKeys())
210 sort.Sort(keys)
211 for _, k := range keys {
212 if _, found := sinfo.FieldsMap[k.String()]; found {
213 failDumpf(RepresenterStage, "cannot have key %q in inlined map: conflicts with struct field", k.String())
214 }
215 content = append(content, r.represent("", k))
216 r.flow = false
217 content = append(content, r.represent("", m.MapIndex(k)))
218 }
219 }
220 }
221
222 return &Node{
223 Kind: MappingNode,
224 Tag: tag,
225 Content: content,
226 Style: style,
227 }
228 }
229
230 // slicev converts a Go slice or array to a YAML sequence node.
231 func (r *Representer) slicev(tag string, in reflect.Value) *Node {
232 if tag == "" {
233 tag = seqTag
234 }
235 var style Style
236 if r.flow {
237 r.flow = false
238 style = FlowStyle
239 }
240
241 n := in.Len()
242 content := make([]*Node, n)
243 for i := 0; i < n; i++ {
244 content[i] = r.represent("", in.Index(i))
245 }
246
247 return &Node{
248 Kind: SequenceNode,
249 Tag: tag,
250 Content: content,
251 Style: style,
252 }
253 }
254
255 // stringv converts a Go string to a YAML scalar node, handling quoting,
256 // binary data (base64 encoding), and special string values.
257 func (r *Representer) stringv(tag string, in reflect.Value) *Node {
258 var style Style
259 s := in.String()
260 needsQuoting := false
261
262 switch {
263 case !utf8.ValidString(s):
264 if tag == binaryTag {
265 failDumpf(RepresenterStage, "explicitly tagged !!binary data must be base64-encoded")
266 }
267 if tag != "" {
268 failDumpf(RepresenterStage, "cannot represent invalid UTF-8 data as %s", shortTag(tag))
269 }
270 // It can't be represented directly as YAML so use a binary tag
271 // and represent it as base64.
272 tag = binaryTag
273 s = encodeBase64(s)
274 case tag == "":
275 tag = strTag
276 // Check if this string needs quoting for compatibility
277 // even though it would resolve as !!str
278 needsQuoting = isBase60Float(s) || isOldBool(s) || looksLikeMerge(s)
279 }
280
281 // Set the style based on content
282 switch {
283 case strings.Contains(s, "\n"):
284 if r.flow || !shouldUseLiteralStyle(s) {
285 style = DoubleQuotedStyle
286 } else {
287 style = LiteralStyle
288 }
289 case needsQuoting:
290 // Force quoting for YAML 1.1 compatibility values
291 style = SingleQuotedStyle
292 default:
293 // Plain style by default - Desolver will add quotes if type mismatch
294 style = 0
295 }
296
297 return &Node{
298 Kind: ScalarNode,
299 Tag: tag,
300 Value: s,
301 Style: style,
302 }
303 }
304
305 // boolv converts a Go bool to a YAML scalar node.
306 func (r *Representer) boolv(tag string, in reflect.Value) *Node {
307 var s string
308 if in.Bool() {
309 s = "true"
310 } else {
311 s = "false"
312 }
313 if tag == "" {
314 tag = boolTag
315 }
316 return &Node{
317 Kind: ScalarNode,
318 Tag: tag,
319 Value: s,
320 }
321 }
322
323 // intv converts a Go signed integer to a YAML scalar node.
324 func (r *Representer) intv(tag string, in reflect.Value) *Node {
325 s := strconv.FormatInt(in.Int(), 10)
326 if tag == "" {
327 tag = intTag
328 }
329 return &Node{
330 Kind: ScalarNode,
331 Tag: tag,
332 Value: s,
333 }
334 }
335
336 // uintv converts a Go unsigned integer to a YAML scalar node.
337 func (r *Representer) uintv(tag string, in reflect.Value) *Node {
338 s := strconv.FormatUint(in.Uint(), 10)
339 if tag == "" {
340 tag = intTag
341 }
342 return &Node{
343 Kind: ScalarNode,
344 Tag: tag,
345 Value: s,
346 }
347 }
348
349 // timev converts a Go [time.Time] to a YAML scalar node in RFC3339Nano format.
350 func (r *Representer) timev(tag string, in reflect.Value) *Node {
351 t := in.Interface().(time.Time)
352 s := t.Format(time.RFC3339Nano)
353 if tag == "" {
354 tag = timestampTag
355 }
356 return &Node{
357 Kind: ScalarNode,
358 Tag: tag,
359 Value: s,
360 }
361 }
362
363 // floatv converts a Go float to a YAML scalar node, handling special values
364 // like infinity and NaN.
365 func (r *Representer) floatv(tag string, in reflect.Value) *Node {
366 // Issue #352: When formatting, use the precision of the underlying value
367 precision := 64
368 if in.Kind() == reflect.Float32 {
369 precision = 32
370 }
371
372 s := strconv.FormatFloat(in.Float(), 'g', -1, precision)
373 switch s {
374 case "+Inf":
375 s = ".inf"
376 case "-Inf":
377 s = "-.inf"
378 case "NaN":
379 s = ".nan"
380 }
381 if tag == "" {
382 tag = floatTag
383 }
384 return &Node{
385 Kind: ScalarNode,
386 Tag: tag,
387 Value: s,
388 }
389 }
390
391 // nilv creates a YAML null node.
392 func (r *Representer) nilv() *Node {
393 return &Node{
394 Kind: ScalarNode,
395 Tag: nullTag,
396 Value: "null",
397 }
398 }
399
400 // nodev returns a node value as-is without conversion.
401 func (r *Representer) nodev(in reflect.Value) *Node {
402 // Return the node as-is - no conversion needed
403 return in.Interface().(*Node)
404 }
405
406 // Len returns the number of keys in the list.
407 func (l keyList) Len() int { return len(l) }
408
409 // Swap exchanges the positions of two keys in the list.
410 func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
411
412 // Less implements a natural sort order for map keys: numeric values sort
413 // numerically, strings sort with natural number ordering, and mixed types
414 // sort by kind.
415 func (l keyList) Less(i, j int) bool {
416 a := l[i]
417 b := l[j]
418 ak := a.Kind()
419 bk := b.Kind()
420 for (ak == reflect.Interface || ak == reflect.Pointer) && !a.IsNil() {
421 a = a.Elem()
422 ak = a.Kind()
423 }
424 for (bk == reflect.Interface || bk == reflect.Pointer) && !b.IsNil() {
425 b = b.Elem()
426 bk = b.Kind()
427 }
428 af, aok := keyFloat(a)
429 bf, bok := keyFloat(b)
430 if aok && bok {
431 if af != bf {
432 return af < bf
433 }
434 if ak != bk {
435 return ak < bk
436 }
437 return numLess(a, b)
438 }
439 if ak != reflect.String || bk != reflect.String {
440 return ak < bk
441 }
442 ar, br := []rune(a.String()), []rune(b.String())
443 digits := false
444 for i := 0; i < len(ar) && i < len(br); i++ {
445 if ar[i] == br[i] {
446 digits = unicode.IsDigit(ar[i])
447 continue
448 }
449 al := unicode.IsLetter(ar[i])
450 bl := unicode.IsLetter(br[i])
451 if al && bl {
452 return ar[i] < br[i]
453 }
454 if al || bl {
455 if digits {
456 return al
457 } else {
458 return bl
459 }
460 }
461 var ai, bi int
462 var an, bn int64
463 if ar[i] == '0' || br[i] == '0' {
464 for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- {
465 if ar[j] != '0' {
466 an = 1
467 bn = 1
468 break
469 }
470 }
471 }
472 for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ {
473 an = an*10 + int64(ar[ai]-'0')
474 }
475 for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ {
476 bn = bn*10 + int64(br[bi]-'0')
477 }
478 if an != bn {
479 return an < bn
480 }
481 if ai != bi {
482 return ai < bi
483 }
484 return ar[i] < br[i]
485 }
486 return len(ar) < len(br)
487 }
488
489 // keyFloat returns a float value for v if it is a number/bool
490 // and whether it is a number/bool or not.
491 func keyFloat(v reflect.Value) (f float64, ok bool) {
492 switch v.Kind() {
493 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
494 return float64(v.Int()), true
495 case reflect.Float32, reflect.Float64:
496 return v.Float(), true
497 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
498 return float64(v.Uint()), true
499 case reflect.Bool:
500 if v.Bool() {
501 return 1, true
502 }
503 return 0, true
504 }
505 return 0, false
506 }
507
508 // numLess returns whether a < b.
509 // a and b must necessarily have the same kind.
510 func numLess(a, b reflect.Value) bool {
511 switch a.Kind() {
512 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
513 return a.Int() < b.Int()
514 case reflect.Float32, reflect.Float64:
515 return a.Float() < b.Float()
516 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
517 return a.Uint() < b.Uint()
518 case reflect.Bool:
519 return !a.Bool() && b.Bool()
520 }
521 panic("not a number")
522 }
523
524 // fieldByIndex navigates through struct fields using the given index path,
525 // dereferencing pointers as needed.
526 func (r *Representer) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) {
527 for _, num := range index {
528 for {
529 if v.Kind() == reflect.Pointer {
530 if v.IsNil() {
531 return reflect.Value{}
532 }
533 v = v.Elem()
534 continue
535 }
536 break
537 }
538 v = v.Field(num)
539 }
540 return v
541 }
542
543 // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
544 //
545 // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
546 // in YAML 1.2 and by this package, but these should be represented quoted for
547 // the time being for compatibility with other parsers.
548 func isBase60Float(s string) (result bool) {
549 // Fast path.
550 if s == "" {
551 return false
552 }
553 c := s[0]
554 if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {
555 return false
556 }
557 // Do the full match.
558 return base60float.MatchString(s)
559 }
560
561 // isOldBool returns whether s is bool notation as defined in YAML 1.1.
562 //
563 // We continue to force strings that YAML 1.1 would interpret as booleans to be
564 // rendered as quotes strings so that the represented output valid for YAML 1.1
565 // parsing.
566 func isOldBool(s string) (result bool) {
567 switch s {
568 case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON",
569 "n", "N", "no", "No", "NO", "off", "Off", "OFF":
570 return true
571 default:
572 return false
573 }
574 }
575
576 // looksLikeMerge returns true if the given string is the merge indicator "<<".
577 //
578 // When encoding a scalar with this exact value, it must be quoted to prevent it
579 // from being interpreted as a merge indicator during decoding.
580 func looksLikeMerge(s string) (result bool) {
581 return s == "<<"
582 }