Debian Codegraph @

internal/libyaml/node.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 // Node types and constants for YAML tree representation.
6 // Defines Kind, Style, and Node structure for intermediate YAML representation.
7
8 package libyaml
9
10 import (
11 "reflect"
12 "strings"
13 "unicode"
14 "unicode/utf8"
15 )
16
17 // Tag constants for YAML types
18 const (
19 nullTag = "!!null"
20 boolTag = "!!bool"
21 strTag = "!!str"
22 intTag = "!!int"
23 floatTag = "!!float"
24 timestampTag = "!!timestamp"
25 seqTag = "!!seq"
26 mapTag = "!!map"
27 binaryTag = "!!binary"
28 mergeTag = "!!merge"
29 )
30
31 // longTagPrefix is the standard YAML tag prefix for core types.
32 const longTagPrefix = "tag:yaml.org,2002:"
33
34 // longTags maps short tags to their long form representations.
35 // shortTags maps long tags to their short form representations.
36 var (
37 longTags = make(map[string]string)
38 shortTags = make(map[string]string)
39 )
40
41 // init initializes the tag conversion maps.
42 func init() {
43 for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} {
44 ltag := longTag(stag)
45 longTags[stag] = ltag
46 shortTags[ltag] = stag
47 }
48 }
49
50 // shortTag converts a long-form tag to its short form (e.g., "tag:yaml.org,2002:str" to "!!str").
51 func shortTag(tag string) string {
52 if strings.HasPrefix(tag, longTagPrefix) {
53 if stag, ok := shortTags[tag]; ok {
54 return stag
55 }
56 return "!!" + tag[len(longTagPrefix):]
57 }
58 return tag
59 }
60
61 // longTag converts a short-form tag to its long form (e.g., "!!str" to "tag:yaml.org,2002:str").
62 func longTag(tag string) string {
63 if strings.HasPrefix(tag, "!!") {
64 if ltag, ok := longTags[tag]; ok {
65 return ltag
66 }
67 return longTagPrefix + tag[2:]
68 }
69 return tag
70 }
71
72 // Kind represents the type of YAML node
73 type Kind uint32
74
75 // Kind constants define the different types of YAML nodes.
76 const (
77 DocumentNode Kind = 1 << iota
78 SequenceNode
79 MappingNode
80 ScalarNode
81 AliasNode
82 StreamNode
83 )
84
85 // Style represents the formatting style of a YAML node
86 type Style uint32
87
88 // Style constants define different formatting styles for YAML nodes.
89 const (
90 TaggedStyle Style = 1 << iota
91 DoubleQuotedStyle
92 SingleQuotedStyle
93 LiteralStyle
94 FoldedStyle
95 FlowStyle
96 )
97
98 // StreamVersionDirective represents a YAML %YAML version directive for stream nodes.
99 type StreamVersionDirective struct {
100 Major int
101 Minor int
102 }
103
104 // StreamTagDirective represents a YAML %TAG directive for stream nodes.
105 type StreamTagDirective struct {
106 Handle string
107 Prefix string
108 }
109
110 // Stream holds stream-level metadata for StreamNode.
111 // This includes encoding, version directive, and tag directives.
112 type Stream struct {
113 Encoding Encoding
114 Version *StreamVersionDirective
115 TagDirectives []StreamTagDirective
116 }
117
118 // Node represents an element in the YAML document hierarchy. While documents
119 // are typically encoded and decoded into higher level types, such as structs
120 // and maps, Node is an intermediate representation that allows detailed
121 // control over the content being decoded or encoded.
122 //
123 // It's worth noting that although Node offers access into details such as
124 // line numbers, columns, and comments, the content when re-encoded will not
125 // have its original textual representation preserved. An effort is made to
126 // render the data pleasantly, and to preserve comments near the data they
127 // describe, though.
128 //
129 // Values that make use of the Node type interact with the yaml package in the
130 // same way any other type would do, by encoding and decoding yaml data
131 // directly or indirectly into them.
132 //
133 // For example:
134 //
135 // var person struct {
136 // Name string
137 // Address yaml.Node
138 // }
139 // err := yaml.Unmarshal(data, &person)
140 //
141 // Or by itself:
142 //
143 // var person Node
144 // err := yaml.Unmarshal(data, &person)
145 type Node struct {
146 // Kind defines whether the node is a document, a mapping, a sequence,
147 // a scalar value, or an alias to another node. The specific data type of
148 // scalar nodes may be obtained via the ShortTag and LongTag methods.
149 Kind Kind
150
151 // Style allows customizing the appearance of the node in the tree.
152 Style Style
153
154 // Tag holds the YAML tag defining the data type for the value.
155 // When decoding, this field will always be set to the resolved tag,
156 // even when it wasn't explicitly provided in the YAML content.
157 // When encoding, if this field is unset the value type will be
158 // implied from the node properties, and if it is set, it will only
159 // be serialized into the representation if TaggedStyle is used or
160 // the implicit tag diverges from the provided one.
161 Tag string
162
163 // Value holds the unescaped and unquoted representation of the value.
164 Value string
165
166 // Anchor holds the anchor name for this node, which allows aliases to point to it.
167 Anchor string
168
169 // Alias holds the node that this alias points to. Only valid when Kind is AliasNode.
170 Alias *Node
171
172 // Content holds contained nodes for documents, mappings, and sequences.
173 Content []*Node
174
175 // HeadComment holds any comments in the lines preceding the node and
176 // not separated by an empty line.
177 HeadComment string
178
179 // LineComment holds any comments at the end of the line where the node is in.
180 LineComment string
181
182 // FootComment holds any comments following the node and before empty lines.
183 FootComment string
184
185 // Line and Column hold the node position in the decoded YAML text.
186 // These fields are not respected when encoding the node.
187 Line int
188 Column int
189
190 // Stream holds stream metadata (non-nil only when Kind == StreamNode).
191 Stream *Stream
192 }
193
194 // IsZero returns whether the node has all of its fields unset.
195 func (n *Node) IsZero() bool {
196 return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil &&
197 n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 &&
198 n.Stream == nil
199 }
200
201 // LongTag returns the long form of the tag that indicates the data type for
202 // the node. If the Tag field isn't explicitly defined, one will be computed
203 // based on the node properties.
204 func (n *Node) LongTag() string {
205 return longTag(n.ShortTag())
206 }
207
208 // ShortTag returns the short form of the YAML tag that indicates data type for
209 // the node. If the Tag field isn't explicitly defined, one will be computed
210 // based on the node properties.
211 func (n *Node) ShortTag() string {
212 if n.indicatedString() {
213 return strTag
214 }
215 if n.Tag == "" || n.Tag == "!" {
216 switch n.Kind {
217 case MappingNode:
218 return mapTag
219 case SequenceNode:
220 return seqTag
221 case AliasNode:
222 if n.Alias != nil {
223 return n.Alias.ShortTag()
224 }
225 case ScalarNode:
226 return strTag
227 case 0:
228 // Special case to make the zero value convenient.
229 if n.IsZero() {
230 return nullTag
231 }
232 }
233 return ""
234 }
235 return shortTag(n.Tag)
236 }
237
238 // indicatedString returns true if the node's style explicitly indicates a string type.
239 func (n *Node) indicatedString() bool {
240 return n.Kind == ScalarNode &&
241 (shortTag(n.Tag) == strTag ||
242 (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0)
243 }
244
245 // shouldUseLiteralStyle determines if a string should use literal style.
246 // It returns true if the string contains newlines AND meets additional criteria:
247 // - is at least 2 characters long
248 // - contains at least one non-whitespace character
249 func shouldUseLiteralStyle(s string) bool {
250 if !strings.Contains(s, "\n") || len(s) < 2 {
251 return false
252 }
253 // Must contain at least one non-whitespace character
254 for _, r := range s {
255 if !unicode.IsSpace(r) {
256 return true
257 }
258 }
259 return false
260 }
261
262 // SetString is a convenience function that sets the node to a string value
263 // and defines its style in a pleasant way depending on its content.
264 func (n *Node) SetString(s string) {
265 n.Kind = ScalarNode
266 if utf8.ValidString(s) {
267 n.Value = s
268 n.Tag = strTag
269 } else {
270 n.Value = encodeBase64(s)
271 n.Tag = binaryTag
272 }
273 if shouldUseLiteralStyle(n.Value) {
274 n.Style = LiteralStyle
275 }
276 }
277
278 // Decode decodes the node and stores its data into the value pointed to by v.
279 //
280 // See the documentation for Unmarshal for details about the
281 // conversion of YAML into a Go value.
282 func (n *Node) Decode(v any) (err error) {
283 d := NewConstructor(DefaultOptions)
284 defer handleErr(&err)
285 out := reflect.ValueOf(v)
286 if out.Kind() == reflect.Pointer && !out.IsNil() {
287 out = out.Elem()
288 }
289 d.Construct(n, out)
290 if len(d.TypeErrors) > 0 {
291 return &LoadErrors{Errors: d.TypeErrors}
292 }
293 return nil
294 }
295
296 // Load decodes the node and stores its data into the value pointed to by v,
297 // applying the given options.
298 //
299 // This method is useful when you need to preserve options like WithKnownFields()
300 // inside custom UnmarshalYAML implementations.
301 //
302 // Maps and pointers (to a struct, string, int, etc) are accepted as v
303 // values. If an internal pointer within a struct is not initialized,
304 // the yaml package will initialize it if necessary. The v parameter
305 // must not be nil.
306 //
307 // See the documentation of the package-level Load function for details
308 // about YAML to Go conversion and tag options.
309 func (n *Node) Load(v any, opts ...Option) (err error) {
310 defer handleErr(&err)
311 o, err := ApplyOptions(opts...)
312 if err != nil {
313 return err
314 }
315 d := NewConstructor(o)
316 out := reflect.ValueOf(v)
317 if out.Kind() == reflect.Pointer && !out.IsNil() {
318 out = out.Elem()
319 }
320 d.Construct(n, out)
321 if len(d.TypeErrors) > 0 {
322 return &LoadErrors{Errors: d.TypeErrors}
323 }
324 return nil
325 }
326
327 // Encode encodes value v and stores its representation in n.
328 //
329 // See the documentation for Marshal for details about the
330 // conversion of Go values into YAML.
331 func (n *Node) Encode(v any) (err error) {
332 defer handleErr(&err)
333 // Use the 3-stage dump pipeline with round-trip to preserve styles
334 r := NewRepresenter(DefaultOptions)
335 node := r.Represent("", reflect.ValueOf(v))
336 d := NewDesolver(DefaultOptions)
337 d.Desolve(node)
338 s := NewSerializer(nil, DefaultOptions)
339 var out []byte
340 s.Emitter.SetOutputString(&out)
341 s.Serialize(node)
342 s.Finish()
343 // Parse back to get styles
344 p := NewComposer(out, nil)
345 p.Textless = true
346 defer p.Destroy()
347 doc := p.Compose()
348 NewResolver(nil).Resolve(doc)
349 *n = *doc.Content[0]
350 return nil
351 }
352
353 // Dump encodes value v and stores its representation in n,
354 // applying the given options.
355 //
356 // This method is useful when you need to apply specific encoding options
357 // while building Node trees programmatically.
358 //
359 // See the documentation for Marshal for details about the
360 // conversion of Go values into YAML.
361 func (n *Node) Dump(v any, opts ...Option) (err error) {
362 defer handleErr(&err)
363 o, err := ApplyOptions(opts...)
364 if err != nil {
365 return err
366 }
367 // Use the 3-stage dump pipeline with round-trip to preserve styles
368 r := NewRepresenter(o)
369 node := r.Represent("", reflect.ValueOf(v))
370 d := NewDesolver(o)
371 d.Desolve(node)
372 s := NewSerializer(nil, o)
373 var out []byte
374 s.Emitter.SetOutputString(&out)
375 s.Serialize(node)
376 s.Finish()
377 // Parse back to get styles
378 p := NewComposer(out, nil)
379 p.Textless = true
380 defer p.Destroy()
381 doc := p.Compose()
382 NewResolver(nil).Resolve(doc)
383 *n = *doc.Content[0]
384 return nil
385 }
386
387 // Marshaler interface may be implemented by types to customize their
388 // behavior when being marshaled into a YAML document.
389 type Marshaler interface {
390 MarshalYAML() (any, error)
391 }
392
393 // Unmarshaler is the interface implemented by types that can unmarshal
394 // a YAML description of themselves.
395 type Unmarshaler interface {
396 UnmarshalYAML(node *Node) error
397 }
398
399 // IsZeroer is used to check whether an object is zero to determine whether
400 // it should be omitted when marshaling with the ,omitempty flag. One notable
401 // implementation is [time.Time].
402 type IsZeroer interface {
403 IsZero() bool
404 }
405
406 // FromYAMLNode is a new interface that types can implement to customize
407 // their unmarshaling behavior. It receives a Node directly and modifies
408 // the receiver in place.
409 // This is the preferred interface for new code.
410 //
411 // Note: This interface is reserved for the v4 API and is not yet fully
412 // integrated into the current implementation.
413 type FromYAMLNode interface {
414 FromYAMLNode(*Node) error
415 }
416
417 // ToYAMLNode is a new interface that types can implement to customize
418 // their marshaling behavior. It returns a Node directly.
419 // This is the preferred interface for new code.
420 //
421 // Note: This interface is reserved for the v4 API and is not yet fully
422 // integrated into the current implementation.
423 type ToYAMLNode interface {
424 ToYAMLNode() (*Node, error)
425 }
426
427 // isZero reports whether v represents the zero value for its type.
428 // If v implements the IsZeroer interface, IsZero() is called.
429 // Otherwise, zero is determined by checking type-specific conditions.
430 // This is used to determine omitempty behavior when marshaling.
431 func isZero(v reflect.Value) bool {
432 kind := v.Kind()
433 if z, ok := v.Interface().(IsZeroer); ok {
434 if (kind == reflect.Pointer || kind == reflect.Interface) && v.IsNil() {
435 return true
436 }
437 return z.IsZero()
438 }
439 switch kind {
440 case reflect.String:
441 return len(v.String()) == 0
442 case reflect.Interface, reflect.Pointer:
443 return v.IsNil()
444 case reflect.Slice:
445 return v.Len() == 0
446 case reflect.Map:
447 return v.Len() == 0
448 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
449 return v.Int() == 0
450 case reflect.Float32, reflect.Float64:
451 return v.Float() == 0
452 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
453 return v.Uint() == 0
454 case reflect.Bool:
455 return !v.Bool()
456 case reflect.Struct:
457 vt := v.Type()
458 for i := v.NumField() - 1; i >= 0; i-- {
459 if vt.Field(i).PkgPath != "" {
460 continue // Private field
461 }
462 if !isZero(v.Field(i)) {
463 return false
464 }
465 }
466 return true
467 }
468 return false
469 }