Debian Codegraph @

internal/libyaml/constructor.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 // Constructor stage: Converts YAML nodes to Go values.
6 // Handles type resolution, custom unmarshalers, and struct field mapping.
7
8 package libyaml
9
10 import (
11 "encoding"
12 "encoding/base64"
13 "fmt"
14 "math"
15 "reflect"
16 "time"
17 )
18
19 // --------------------------------------------------------------------------
20 // Types and Interfaces
21
22 // legacyConstructor is the old-style unmarshaler interface.
23 // It's kept for backwards compatibility.
24 type legacyConstructor interface {
25 UnmarshalYAML(construct func(any) error) error
26 }
27
28 // constructorAdapter is an interface that wraps the root package's Unmarshaler
29 // interface.
30 // This allows the constructor to call constructors that expect *yaml.Node
31 // instead of *libyaml.Node.
32 type constructorAdapter interface {
33 CallRootConstructor(n *Node) error
34 }
35
36 // ScalarConstructFunc is the signature for tag-specific scalar constructor
37 // functions.
38 // Each function handles construction of a specific YAML tag to various Go
39 // types.
40 type ScalarConstructFunc func(c *Constructor, n *Node, resolved any, out reflect.Value) bool
41
42 // Constructor state
43 type Constructor struct {
44 doc *Node
45 aliases map[*Node]bool
46 TypeErrors []*LoadError
47
48 stringMapType reflect.Type
49 generalMapType reflect.Type
50
51 KnownFields bool
52 UniqueKeys bool
53 constructCount int
54 aliasCount int
55 aliasDepth int
56 aliasCheck func(aliasCount, constructCount int) error
57
58 mergedFields map[any]bool
59 }
60
61 // NewConstructor creates a new Constructor initialized with the provided
62 // options.
63 func NewConstructor(opts *Options) *Constructor {
64 return &Constructor{
65 stringMapType: stringMapType,
66 generalMapType: generalMapType,
67 KnownFields: opts.KnownFields,
68 UniqueKeys: opts.UniqueKeys,
69 aliases: make(map[*Node]bool),
70 aliasCheck: opts.AliasCheck,
71 }
72 }
73
74 // --------------------------------------------------------------------------
75 // Main Entry Point
76
77 // Construct converts a YAML node into the Go value represented by out.
78 // It dispatches to the appropriate handler based on the node kind and
79 // handles alias expansion, custom unmarshalers, and type resolution.
80 // Returns true if the construction was successful.
81 func (c *Constructor) Construct(n *Node, out reflect.Value) (good bool) {
82 c.constructCount++
83 if c.aliasDepth > 0 {
84 c.aliasCount++
85 }
86 if c.aliasCheck != nil {
87 if err := c.aliasCheck(c.aliasCount, c.constructCount); err != nil {
88 Fail(formatConstructorError(err, Mark{Line: n.Line, Column: n.Column}))
89 }
90 }
91 if out.Type() == nodeType {
92 out.Set(reflect.ValueOf(n).Elem())
93 return true
94 }
95
96 switch n.Kind {
97 case DocumentNode:
98 return c.document(n, out)
99 case AliasNode:
100 return c.alias(n, out)
101 }
102
103 out, constructed, good := c.prepare(n, out)
104 if constructed {
105 return good
106 }
107
108 // When out type implements [encoding.TextUnmarshaler], ensure the node
109 // is a scalar. Otherwise, for example, constructing a YAML mapping
110 // into a struct having no exported fields, but implementing
111 // TextUnmarshaler would silently succeed, but do nothing.
112 //
113 // Note that this matches the behavior of both encoding/json and
114 // encoding/json/v2.
115 if n.Kind != ScalarNode && isTextUnmarshaler(out) {
116 err := fmt.Errorf("cannot construct %s into %s (TextUnmarshaler)", shortTag(n.Tag), out.Type())
117 c.TypeErrors = append(c.TypeErrors,
118 formatConstructorError(err, Mark{Line: n.Line, Column: n.Column}))
119 return false
120 }
121
122 switch n.Kind {
123 case ScalarNode:
124 good = c.scalar(n, out)
125 case MappingNode:
126 good = c.mapping(n, out)
127 case SequenceNode:
128 good = c.sequence(n, out)
129 case 0:
130 if n.IsZero() {
131 return c.null(out)
132 }
133 fallthrough
134 default:
135 Fail(formatConstructorError(
136 fmt.Errorf("cannot construct node with unknown kind: '%d'", n.Kind),
137 Mark{Line: n.Line, Column: n.Column},
138 ))
139 }
140 return good
141 }
142
143 // --------------------------------------------------------------------------
144 // Package-level Variables and Constants
145 var (
146 nodeType = reflect.TypeOf(Node{})
147 durationType = reflect.TypeOf(time.Duration(0))
148 stringMapType = reflect.TypeOf(map[string]any{})
149 generalMapType = reflect.TypeOf(map[any]any{})
150 ifaceType = generalMapType.Elem()
151 )
152
153 // scalarConstructors maps YAML scalar tags to their constructor functions.
154 var scalarConstructors = map[string]ScalarConstructFunc{
155 strTag: (*Constructor).constructStr,
156 intTag: (*Constructor).constructInt,
157 boolTag: (*Constructor).constructBool,
158 floatTag: (*Constructor).constructFloat,
159 nullTag: (*Constructor).constructNull,
160 timestampTag: (*Constructor).constructTimestamp,
161 binaryTag: (*Constructor).constructBinary,
162 mergeTag: (*Constructor).constructMerge,
163 }
164
165 // --------------------------------------------------------------------------
166 // Scalar tag constructors
167
168 // constructStr constructs a !!str tagged value into various Go types.
169 func (c *Constructor) constructStr(n *Node, resolved any, out reflect.Value) bool {
170 switch out.Kind() {
171 case reflect.String:
172 out.SetString(n.Value)
173 return true
174 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
175 // Handle time.Duration parsing from strings like "3s", "1m",
176 // etc.
177 if out.Type() == durationType {
178 d, err := time.ParseDuration(n.Value)
179 if err == nil {
180 out.SetInt(int64(d))
181 return true
182 }
183 }
184 case reflect.Bool:
185 // YAML 1.1 compatibility: allow string values like "y", "on",
186 // "Off" as bools
187 switch n.Value {
188 case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON":
189 out.SetBool(true)
190 return true
191 case "n", "N", "no", "No", "NO", "off", "Off", "OFF":
192 out.SetBool(false)
193 return true
194 }
195 case reflect.Interface:
196 out.Set(reflect.ValueOf(resolved))
197 return true
198 }
199 c.tagError(n, strTag, out)
200 return false
201 }
202
203 // constructInt constructs a !!int tagged value into various Go types.
204 func (c *Constructor) constructInt(n *Node, resolved any, out reflect.Value) bool {
205 switch out.Kind() {
206 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
207 isDuration := out.Type() == durationType
208
209 switch resolved := resolved.(type) {
210 case int:
211 if !isDuration && !out.OverflowInt(int64(resolved)) {
212 out.SetInt(int64(resolved))
213 return true
214 } else if isDuration && resolved == 0 {
215 out.SetInt(0)
216 return true
217 }
218 case int64:
219 if !isDuration && !out.OverflowInt(resolved) {
220 out.SetInt(resolved)
221 return true
222 }
223 case uint64:
224 if !isDuration && resolved <= math.MaxInt64 {
225 intVal := int64(resolved)
226 if !out.OverflowInt(intVal) {
227 out.SetInt(intVal)
228 return true
229 }
230 }
231 case float64:
232 if !isDuration && resolved >= math.MinInt64 && resolved <= math.MaxInt64 {
233 intVal := int64(resolved)
234 // Verify conversion is lossless (handles
235 // floating-point precision)
236 if float64(intVal) == resolved && !out.OverflowInt(intVal) {
237 out.SetInt(intVal)
238 return true
239 }
240 }
241 case string:
242 if out.Type() == durationType {
243 d, err := time.ParseDuration(resolved)
244 if err == nil {
245 out.SetInt(int64(d))
246 return true
247 }
248 }
249 }
250 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
251 switch resolved := resolved.(type) {
252 case int:
253 if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
254 out.SetUint(uint64(resolved))
255 return true
256 }
257 case int64:
258 if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
259 out.SetUint(uint64(resolved))
260 return true
261 }
262 case uint64:
263 if !out.OverflowUint(resolved) {
264 out.SetUint(resolved)
265 return true
266 }
267 case float64:
268 if resolved >= 0 && resolved <= math.MaxUint64 {
269 uintVal := uint64(resolved)
270 // Verify conversion is lossless (handles
271 // floating-point precision)
272 if float64(uintVal) == resolved && !out.OverflowUint(uintVal) {
273 out.SetUint(uintVal)
274 return true
275 }
276 }
277 }
278 case reflect.Float32, reflect.Float64:
279 // Allow int to float conversion
280 switch resolved := resolved.(type) {
281 case int:
282 out.SetFloat(float64(resolved))
283 return true
284 case int64:
285 out.SetFloat(float64(resolved))
286 return true
287 case uint64:
288 out.SetFloat(float64(resolved))
289 return true
290 }
291 case reflect.String:
292 // Allow int to string conversion
293 out.SetString(n.Value)
294 return true
295 case reflect.Interface:
296 out.Set(reflect.ValueOf(resolved))
297 return true
298 }
299 c.tagError(n, intTag, out)
300 return false
301 }
302
303 // constructBool constructs a !!bool tagged value into various Go types.
304 func (c *Constructor) constructBool(n *Node, resolved any, out reflect.Value) bool {
305 switch out.Kind() {
306 case reflect.Bool:
307 switch resolved := resolved.(type) {
308 case bool:
309 out.SetBool(resolved)
310 return true
311 case string:
312 // This offers some compatibility with the 1.1 spec
313 // (https://yaml.org/type/bool.html).
314 // It only works if explicitly attempting to construct
315 // into a typed bool value.
316 switch resolved {
317 case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON":
318 out.SetBool(true)
319 return true
320 case "n", "N", "no", "No", "NO", "off", "Off", "OFF":
321 out.SetBool(false)
322 return true
323 }
324 }
325 case reflect.String:
326 // Allow bool to be constructed as string (e.g., true -> "true")
327 out.SetString(n.Value)
328 return true
329 case reflect.Interface:
330 out.Set(reflect.ValueOf(resolved))
331 return true
332 }
333 c.tagError(n, boolTag, out)
334 return false
335 }
336
337 // constructFloat constructs a !!float tagged value into various Go types.
338 func (c *Constructor) constructFloat(n *Node, resolved any, out reflect.Value) bool {
339 switch out.Kind() {
340 case reflect.Float32, reflect.Float64:
341 switch resolved := resolved.(type) {
342 case int:
343 out.SetFloat(float64(resolved))
344 return true
345 case int64:
346 out.SetFloat(float64(resolved))
347 return true
348 case uint64:
349 out.SetFloat(float64(resolved))
350 return true
351 case float64:
352 out.SetFloat(resolved)
353 return true
354 }
355 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
356 // Allow float to int conversion if lossless
357 if fval, ok := resolved.(float64); ok {
358 if fval >= math.MinInt64 && fval <= math.MaxInt64 {
359 intVal := int64(fval)
360 if float64(intVal) == fval && !out.OverflowInt(intVal) {
361 out.SetInt(intVal)
362 return true
363 }
364 }
365 }
366 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
367 // Allow float to uint conversion if lossless
368 if fval, ok := resolved.(float64); ok {
369 if fval >= 0 && fval <= math.MaxUint64 {
370 uintVal := uint64(fval)
371 if float64(uintVal) == fval && !out.OverflowUint(uintVal) {
372 out.SetUint(uintVal)
373 return true
374 }
375 }
376 }
377 case reflect.String:
378 out.SetString(n.Value)
379 return true
380 case reflect.Interface:
381 out.Set(reflect.ValueOf(resolved))
382 return true
383 }
384 c.tagError(n, floatTag, out)
385 return false
386 }
387
388 // constructTimestamp constructs a !!timestamp tagged value into various Go
389 // types.
390 func (c *Constructor) constructTimestamp(n *Node, resolved any, out reflect.Value) bool {
391 switch out.Kind() {
392 case reflect.Struct:
393 if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
394 out.Set(resolvedv)
395 return true
396 }
397 case reflect.Interface:
398 out.Set(reflect.ValueOf(resolved))
399 return true
400 }
401 c.tagError(n, timestampTag, out)
402 return false
403 }
404
405 // constructBinary constructs a !!binary tagged value into various Go types.
406 func (c *Constructor) constructBinary(n *Node, resolved any, out reflect.Value) bool {
407 switch out.Kind() {
408 case reflect.String:
409 out.SetString(resolved.(string))
410 return true
411 case reflect.Slice:
412 // allow decoding !!binary-tagged value into []byte specifically
413 if out.Type().Elem().Kind() == reflect.Uint8 {
414 out.SetBytes([]byte(resolved.(string)))
415 return true
416 }
417 case reflect.Interface:
418 out.Set(reflect.ValueOf(resolved))
419 return true
420 }
421 c.tagError(n, binaryTag, out)
422 return false
423 }
424
425 // constructNull constructs a !!null tagged value into various Go types.
426 func (c *Constructor) constructNull(n *Node, resolved any, out reflect.Value) bool {
427 return c.null(out)
428 }
429
430 // constructMerge handles !!merge tagged keys.
431 // Merge keys are directives, not values, so construction always fails.
432 // They are handled specially by the mapping() function.
433 func (c *Constructor) constructMerge(n *Node, resolved any, out reflect.Value) bool {
434 return false
435 }
436
437 // --------------------------------------------------------------------------
438 // Node Kind Handlers
439
440 // document constructs a DocumentNode by processing its single content node.
441 func (c *Constructor) document(n *Node, out reflect.Value) (good bool) {
442 if len(n.Content) == 1 {
443 c.doc = n
444 c.Construct(n.Content[0], out)
445 return true
446 }
447 return false
448 }
449
450 // alias constructs an AliasNode by following the alias reference and
451 // tracking alias depth to detect circular references.
452 func (c *Constructor) alias(n *Node, out reflect.Value) (good bool) {
453 if c.aliases[n] {
454 // TODO this could actually be allowed in some circumstances.
455 Fail(formatComposerError(
456 fmt.Sprintf("anchor '%s' value contains itself", n.Value),
457 Mark{Line: n.Line, Column: n.Column},
458 ))
459 }
460 c.aliases[n] = true
461 c.aliasDepth++
462 good = c.Construct(n.Alias, out)
463 c.aliasDepth--
464 delete(c.aliases, n)
465 return good
466 }
467
468 // scalar constructs a ScalarNode by resolving its tag and value, then
469 // dispatching to the appropriate tag-specific constructor or using
470 // TextUnmarshaler if available.
471 func (c *Constructor) scalar(n *Node, out reflect.Value) bool {
472 // Resolve the tag and value
473 var tag string
474 var resolved any
475 if n.indicatedString() {
476 tag = strTag
477 resolved = n.Value
478 } else {
479 tag, resolved = resolve(n.Tag, n.Value)
480 if tag == binaryTag {
481 data, err := base64.StdEncoding.DecodeString(resolved.(string))
482 if err != nil {
483 Fail(formatConstructorError(
484 fmt.Errorf("!!binary value contains invalid base64 data"),
485 Mark{Line: n.Line, Column: n.Column},
486 ))
487 }
488 resolved = string(data)
489 }
490 }
491
492 // Handle null
493 if resolved == nil {
494 return c.null(out)
495 }
496
497 // Fast path: exact type match
498 if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
499 out.Set(resolvedv)
500 return true
501 }
502
503 // Handle TextUnmarshaler interface
504 if out.CanAddr() {
505 u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
506 if ok {
507 var text []byte
508 if tag == binaryTag {
509 text = []byte(resolved.(string))
510 } else {
511 text = []byte(n.Value)
512 }
513 err := u.UnmarshalText(text)
514 if err != nil {
515 c.TypeErrors = append(c.TypeErrors, formatConstructorError(err, Mark{Line: n.Line, Column: n.Column}))
516 return false
517 }
518 return true
519 }
520 }
521
522 // Dispatch to tag-specific constructor
523 if constructor, ok := scalarConstructors[tag]; ok {
524 return constructor(c, n, resolved, out)
525 }
526
527 // Unknown tag - try some fallback behaviors
528 switch out.Kind() {
529 case reflect.Interface:
530 // For interface{} targets, accept any resolved value
531 out.Set(reflect.ValueOf(resolved))
532 return true
533 case reflect.Struct:
534 // For struct targets with matching types, try direct assignment
535 if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
536 out.Set(resolvedv)
537 return true
538 }
539 }
540
541 // No constructor and no fallback worked
542 c.tagError(n, tag, out)
543 return false
544 }
545
546 // sequence constructs a SequenceNode into a Go slice, array, or interface.
547 func (c *Constructor) sequence(n *Node, out reflect.Value) (good bool) {
548 l := len(n.Content)
549
550 var iface reflect.Value
551 switch out.Kind() {
552 case reflect.Slice:
553 out.Set(reflect.MakeSlice(out.Type(), l, l))
554 case reflect.Array:
555 if l != out.Len() {
556 Fail(formatConstructorError(
557 fmt.Errorf("invalid array: want %d elements but got %d", out.Len(), l),
558 Mark{Line: n.Line, Column: n.Column},
559 ))
560 }
561 case reflect.Interface:
562 // No type hints. Will have to use a generic sequence.
563 iface = out
564 out = settableValueOf(make([]any, l))
565 default:
566 c.tagError(n, seqTag, out)
567 return false
568 }
569 et := out.Type().Elem()
570
571 j := 0
572 for i := 0; i < l; i++ {
573 e := reflect.New(et).Elem()
574 if ok := c.Construct(n.Content[i], e); ok {
575 out.Index(j).Set(e)
576 j++
577 }
578 }
579 if out.Kind() != reflect.Array {
580 out.Set(out.Slice(0, j))
581 }
582 if iface.IsValid() {
583 iface.Set(out)
584 }
585 return true
586 }
587
588 // mapping constructs a MappingNode into a Go map, struct, or interface.
589 // It handles key uniqueness checking, merge keys, and type-appropriate
590 // map construction (string-keyed vs general).
591 func (c *Constructor) mapping(n *Node, out reflect.Value) (good bool) {
592 l := len(n.Content)
593 if c.UniqueKeys {
594 nerrs := len(c.TypeErrors)
595 for i := 0; i < l; i += 2 {
596 ni := n.Content[i]
597 for j := i + 2; j < l; j += 2 {
598 nj := n.Content[j]
599 if ni.Kind == nj.Kind && ni.Value == nj.Value {
600 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
601 fmt.Errorf("mapping key %#v already defined at line %d", nj.Value, ni.Line),
602 Mark{Line: nj.Line, Column: nj.Column},
603 ))
604 }
605 }
606 }
607 if len(c.TypeErrors) > nerrs {
608 return false
609 }
610 }
611 switch out.Kind() {
612 case reflect.Struct:
613 return c.mappingStruct(n, out)
614 case reflect.Map:
615 // okay
616 case reflect.Interface:
617 iface := out
618 if isStringMap(n) {
619 out = reflect.MakeMap(c.stringMapType)
620 } else {
621 out = reflect.MakeMap(c.generalMapType)
622 }
623 iface.Set(out)
624 default:
625 c.tagError(n, mapTag, out)
626 return false
627 }
628
629 outt := out.Type()
630 kt := outt.Key()
631 et := outt.Elem()
632
633 stringMapType := c.stringMapType
634 generalMapType := c.generalMapType
635 if outt.Elem() == ifaceType {
636 if outt.Key().Kind() == reflect.String {
637 c.stringMapType = outt
638 } else if outt.Key() == ifaceType {
639 c.generalMapType = outt
640 }
641 }
642
643 mergedFields := c.mergedFields
644 c.mergedFields = nil
645
646 var mergeNode *Node
647
648 mapIsNew := false
649 if out.IsNil() {
650 out.Set(reflect.MakeMap(outt))
651 mapIsNew = true
652 }
653 for i := 0; i < l; i += 2 {
654 if isMerge(n.Content[i]) {
655 mergeNode = n.Content[i+1]
656 continue
657 }
658 k := reflect.New(kt).Elem()
659 if c.Construct(n.Content[i], k) {
660 if mergedFields != nil {
661 ki := k.Interface()
662 if c.getPossiblyUnhashableKey(mergedFields, ki, n.Content[i]) {
663 continue
664 }
665 c.setPossiblyUnhashableKey(mergedFields, ki, true, n.Content[i])
666 }
667 kkind := k.Kind()
668 if kkind == reflect.Interface {
669 kkind = k.Elem().Kind()
670 }
671 if kkind == reflect.Map || kkind == reflect.Slice {
672 Fail(formatConstructorError(
673 fmt.Errorf("cannot use '%#v' as a map key; try decoding into yaml.Node", k.Interface()),
674 Mark{Line: n.Content[i].Line, Column: n.Content[i].Column},
675 ))
676 }
677 e := reflect.New(et).Elem()
678 if c.Construct(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) {
679 out.SetMapIndex(k, e)
680 }
681 }
682 }
683
684 c.mergedFields = mergedFields
685 if mergeNode != nil {
686 c.merge(n, mergeNode, out)
687 }
688
689 c.stringMapType = stringMapType
690 c.generalMapType = generalMapType
691 return true
692 }
693
694 // --------------------------------------------------------------------------
695 // Mapping/Struct Support
696
697 // mappingStruct constructs a MappingNode into a struct value.
698 // It handles field matching by name, inline fields, inline maps, merge keys,
699 // and enforces known fields and unique keys when configured.
700 func (c *Constructor) mappingStruct(n *Node, out reflect.Value) (good bool) {
701 sinfo, err := getStructInfo(out.Type())
702 if err != nil {
703 panic(err)
704 }
705
706 var inlineMap reflect.Value
707 var elemType reflect.Type
708 if sinfo.InlineMap != -1 {
709 inlineMap = out.Field(sinfo.InlineMap)
710 elemType = inlineMap.Type().Elem()
711 }
712
713 for _, index := range sinfo.InlineConstructors {
714 field := c.fieldByIndex(n, out, index)
715 c.prepare(n, field)
716 }
717
718 mergedFields := c.mergedFields
719 c.mergedFields = nil
720 var mergeNode *Node
721 var doneFields []bool
722 if c.UniqueKeys {
723 doneFields = make([]bool, len(sinfo.FieldsList))
724 }
725 name := settableValueOf("")
726 l := len(n.Content)
727 for i := 0; i < l; i += 2 {
728 ni := n.Content[i]
729 if isMerge(ni) {
730 mergeNode = n.Content[i+1]
731 continue
732 }
733 if !c.Construct(ni, name) {
734 continue
735 }
736 sname := name.String()
737 if mergedFields != nil {
738 if mergedFields[sname] {
739 continue
740 }
741 mergedFields[sname] = true
742 }
743 if info, ok := sinfo.FieldsMap[sname]; ok {
744 if c.UniqueKeys {
745 if doneFields[info.Id] {
746 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
747 fmt.Errorf("field %s already set in type %s", name.String(), out.Type()),
748 Mark{Line: ni.Line, Column: ni.Column},
749 ))
750 continue
751 }
752 doneFields[info.Id] = true
753 }
754 var field reflect.Value
755 if info.Inline == nil {
756 field = out.Field(info.Num)
757 } else {
758 field = c.fieldByIndex(n, out, info.Inline)
759 }
760 c.Construct(n.Content[i+1], field)
761 } else if sinfo.InlineMap != -1 {
762 if inlineMap.IsNil() {
763 inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
764 }
765 value := reflect.New(elemType).Elem()
766 c.Construct(n.Content[i+1], value)
767 inlineMap.SetMapIndex(name, value)
768 } else if c.KnownFields {
769 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
770 fmt.Errorf("field %s not found in type %s", name.String(), out.Type()),
771 Mark{Line: ni.Line, Column: ni.Column},
772 ))
773 }
774 }
775
776 c.mergedFields = mergedFields
777 if mergeNode != nil {
778 c.merge(n, mergeNode, out)
779 }
780 return true
781 }
782
783 // merge processes a merge key (<<) by constructing the merge value into out.
784 // The merge value can be a single mapping, an alias to a mapping, or a
785 // sequence of mappings.
786 // Fields from the parent mapping take precedence over merged fields.
787 func (c *Constructor) merge(parent *Node, merge *Node, out reflect.Value) {
788 mergedFields := c.mergedFields
789 if mergedFields == nil {
790 c.mergedFields = make(map[any]bool)
791 for i := 0; i < len(parent.Content); i += 2 {
792 k := reflect.New(ifaceType).Elem()
793 if c.Construct(parent.Content[i], k) {
794 c.setPossiblyUnhashableKey(c.mergedFields, k.Interface(), true, parent.Content[i])
795 }
796 }
797 }
798
799 switch merge.Kind {
800 case MappingNode:
801 c.Construct(merge, out)
802 case AliasNode:
803 if merge.Alias != nil && merge.Alias.Kind != MappingNode {
804 failWantMap(merge.Alias)
805 }
806 c.Construct(merge, out)
807 case SequenceNode:
808 for i := 0; i < len(merge.Content); i++ {
809 ni := merge.Content[i]
810 if ni.Kind == AliasNode {
811 if ni.Alias != nil && ni.Alias.Kind != MappingNode {
812 failWantMap(ni.Alias)
813 }
814 } else if ni.Kind != MappingNode {
815 failWantMap(ni)
816 }
817 c.Construct(ni, out)
818 }
819 default:
820 failWantMap(merge)
821 }
822
823 c.mergedFields = mergedFields
824 }
825
826 // isStringMap checks if a MappingNode has only string or merge keys.
827 // This determines whether to use map[string]any or map[any]any when
828 // constructing into an interface{}.
829 func isStringMap(n *Node) bool {
830 if n.Kind != MappingNode {
831 return false
832 }
833 l := len(n.Content)
834 for i := 0; i < l; i += 2 {
835 shortTag := n.Content[i].ShortTag()
836 if shortTag != strTag && shortTag != mergeTag {
837 return false
838 }
839 }
840 return true
841 }
842
843 // isMerge checks if a node is a merge key (!!merge tag).
844 func isMerge(n *Node) bool {
845 return n.Kind == ScalarNode && shortTag(n.Tag) == mergeTag
846 }
847
848 // failWantMap panics with an error message for invalid merge key values.
849 func failWantMap(n *Node) {
850 Fail(formatConstructorError(
851 fmt.Errorf("map merge requires map or sequence of maps as the value"),
852 Mark{Line: n.Line, Column: n.Column},
853 ))
854 }
855
856 // --------------------------------------------------------------------------
857 // Utility Methods
858
859 // prepare initializes and dereferences pointers and calls UnmarshalYAML
860 // if a value is found to implement it.
861 // It returns the initialized and dereferenced out value, whether
862 // construction was already done by UnmarshalYAML, and if so whether
863 // its types constructed appropriately.
864 //
865 // If n holds a null value, prepare returns before doing anything.
866 func (c *Constructor) prepare(n *Node, out reflect.Value) (newout reflect.Value, constructed, good bool) {
867 if n.ShortTag() == nullTag {
868 return out, false, false
869 }
870 again := true
871 for again {
872 again = false
873 if out.Kind() == reflect.Pointer {
874 if out.IsNil() {
875 out.Set(reflect.New(out.Type().Elem()))
876 }
877 out = out.Elem()
878 again = true
879 }
880 if out.CanAddr() {
881 // Try yaml.Unmarshaler (from root package) first
882 if called, good := c.tryCallYAMLConstructor(n, out); called {
883 return out, true, good
884 }
885
886 outi := out.Addr().Interface()
887 // Check for libyaml.constructor
888 if u, ok := outi.(constructor); ok {
889 good = c.callConstructor(n, u)
890 return out, true, good
891 }
892 if u, ok := outi.(legacyConstructor); ok {
893 good = c.callLegacyConstructor(n, u)
894 return out, true, good
895 }
896 }
897 }
898 return out, false, false
899 }
900
901 // fieldByIndex returns the struct field at the given index path, initializing
902 // any nil pointers along the way.
903 func (c *Constructor) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) {
904 if n.ShortTag() == nullTag {
905 return reflect.Value{}
906 }
907 for _, num := range index {
908 for {
909 if v.Kind() == reflect.Pointer {
910 if v.IsNil() {
911 v.Set(reflect.New(v.Type().Elem()))
912 }
913 v = v.Elem()
914 continue
915 }
916 break
917 }
918 v = v.Field(num)
919 }
920 return v
921 }
922
923 // tryCallYAMLConstructor checks if the value has an UnmarshalYAML method that
924 // takes a *Node from an allowlisted v3 yaml package and calls it if found.
925 // This handles backward compatibility with types that implement the v3
926 // yaml.Unmarshaler interface instead of the native libyaml.constructor.
927 func (c *Constructor) tryCallYAMLConstructor(n *Node, out reflect.Value) (called bool, good bool) {
928 if !out.CanAddr() {
929 return false, false
930 }
931
932 addr := out.Addr()
933 // Check for UnmarshalYAML method
934 method := addr.MethodByName("UnmarshalYAML")
935 if !method.IsValid() {
936 return false, false
937 }
938
939 // Check method signature: func(*yaml.Node) error
940 mtype := method.Type()
941 if mtype.NumIn() != 1 || mtype.NumOut() != 1 {
942 return false, false
943 }
944
945 // Check if parameter is a pointer to a Node-like struct
946 paramType := mtype.In(0)
947 if paramType.Kind() != reflect.Ptr {
948 return false, false
949 }
950
951 elemType := paramType.Elem()
952 if elemType.Kind() != reflect.Struct {
953 return false, false
954 }
955
956 // Only accept *Node from allowlisted v3 yaml packages whose Node type
957 // is assumed to have a compatible memory layout with libyaml.Node.
958 // The unsafe pointer cast below is only safe for these packages.
959 if elemType.Name() != "Node" || !isYAMLNodePkg(elemType.PkgPath()) {
960 return false, false
961 }
962
963 // Return type must be error
964 retType := mtype.Out(0)
965 if retType.Kind() != reflect.Interface || retType.Name() != "error" {
966 return false, false
967 }
968
969 // Call the method with a converted node.
970 // The allowlisted v3 packages define their own Node type that is
971 // assumed to have a compatible memory layout with libyaml.Node.
972 nodeValue := reflect.NewAt(elemType, reflect.ValueOf(n).UnsafePointer())
973
974 results := method.Call([]reflect.Value{nodeValue})
975 err := results[0].Interface()
976
977 if err == nil {
978 return true, true
979 }
980
981 switch e := err.(type) {
982 case *LoadErrors:
983 c.TypeErrors = append(c.TypeErrors, e.Errors...)
984 return true, false
985 default:
986 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
987 err.(error),
988 Mark{Line: n.Line, Column: n.Column},
989 ))
990 return true, false
991 }
992 }
993
994 // callConstructor invokes the UnmarshalYAML method on a value implementing
995 // the constructor interface, handling errors appropriately.
996 func (c *Constructor) callConstructor(n *Node, u constructor) (good bool) {
997 err := u.UnmarshalYAML(n)
998 switch e := err.(type) {
999 case nil:
1000 return true
1001 case *LoadErrors:
1002 c.TypeErrors = append(c.TypeErrors, e.Errors...)
1003 return false
1004 default:
1005 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
1006 err,
1007 Mark{Line: n.Line, Column: n.Column},
1008 ))
1009 return false
1010 }
1011 }
1012
1013 // callLegacyConstructor invokes the UnmarshalYAML method on a value
1014 // implementing the old-style legacyConstructor interface.
1015 func (c *Constructor) callLegacyConstructor(n *Node, u legacyConstructor) (good bool) {
1016 terrlen := len(c.TypeErrors)
1017 err := u.UnmarshalYAML(func(v any) (err error) {
1018 defer handleErr(&err)
1019 c.Construct(n, reflect.ValueOf(v))
1020 if len(c.TypeErrors) > terrlen {
1021 issues := c.TypeErrors[terrlen:]
1022 c.TypeErrors = c.TypeErrors[:terrlen]
1023 return &LoadErrors{issues}
1024 }
1025 return nil
1026 })
1027 switch e := err.(type) {
1028 case nil:
1029 return true
1030 case *LoadErrors:
1031 c.TypeErrors = append(c.TypeErrors, e.Errors...)
1032 return false
1033 default:
1034 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
1035 err,
1036 Mark{Line: n.Line, Column: n.Column},
1037 ))
1038 return false
1039 }
1040 }
1041
1042 // tagError records a type construction error indicating that a node with a
1043 // given tag cannot be constructed into the target type.
1044 func (c *Constructor) tagError(n *Node, tag string, out reflect.Value) {
1045 if n.Tag != "" {
1046 tag = n.Tag
1047 }
1048 value := n.Value
1049 if tag != seqTag && tag != mapTag {
1050 if len(value) > 10 {
1051 value = " `" + value[:7] + "...`"
1052 } else {
1053 value = " `" + value + "`"
1054 }
1055 }
1056 c.TypeErrors = append(c.TypeErrors, formatConstructorError(
1057 fmt.Errorf("cannot construct %s%s into %s", shortTag(tag), value, out.Type()),
1058 Mark{Line: n.Line, Column: n.Column},
1059 ))
1060 }
1061
1062 // null constructs a null value by setting the target to its zero value.
1063 // Only works for nillable types (interface, pointer, map, slice).
1064 func (c *Constructor) null(out reflect.Value) bool {
1065 if out.CanAddr() {
1066 switch out.Kind() {
1067 case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice:
1068 out.Set(reflect.Zero(out.Type()))
1069 return true
1070 }
1071 }
1072 return false
1073 }
1074
1075 // isTextUnmarshaler checks if a value implements [encoding.TextUnmarshaler].
1076 // It dereferences pointers to check the underlying type.
1077 func isTextUnmarshaler(out reflect.Value) bool {
1078 // Dereference pointers to check the underlying type,
1079 // similar to how prepare() handles Constructor checks.
1080 for out.Kind() == reflect.Pointer {
1081 if out.IsNil() {
1082 // Create a new instance to check the type
1083 out = reflect.New(out.Type().Elem()).Elem()
1084 } else {
1085 out = out.Elem()
1086 }
1087 }
1088 if out.CanAddr() {
1089 _, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
1090 return ok
1091 }
1092 return false
1093 }
1094
1095 // settableValueOf returns a settable [reflect.Value] for the given value.
1096 func settableValueOf(i any) reflect.Value {
1097 v := reflect.ValueOf(i)
1098 sv := reflect.New(v.Type()).Elem()
1099 sv.Set(v)
1100 return sv
1101 }
1102
1103 // setPossiblyUnhashableKey sets a map key, recovering from panics if the key
1104 // type is unhashable.
1105 func (c *Constructor) setPossiblyUnhashableKey(m map[any]bool, key any, value bool, n *Node) {
1106 defer func() {
1107 if err := recover(); err != nil {
1108 Fail(formatConstructorError(
1109 fmt.Errorf("%v", err),
1110 Mark{Line: n.Line, Column: n.Column},
1111 ))
1112 }
1113 }()
1114 m[key] = value
1115 }
1116
1117 // getPossiblyUnhashableKey gets a map key value, recovering from panics if
1118 // the key type is unhashable.
1119 func (c *Constructor) getPossiblyUnhashableKey(m map[any]bool, key any, n *Node) bool {
1120 defer func() {
1121 if err := recover(); err != nil {
1122 Fail(formatConstructorError(
1123 fmt.Errorf("%v", err),
1124 Mark{Line: n.Line, Column: n.Column},
1125 ))
1126 }
1127 }()
1128 return m[key]
1129 }
1130
1131 // formatConstructorError creates a LoadError for constructor-stage errors.
1132 func formatConstructorError(err error, mark Mark) *LoadError {
1133 return &LoadError{
1134 Stage: ConstructorStage,
1135 Mark: mark,
1136 Message: err.Error(),
1137 err: err,
1138 }
1139 }
1140
1141 // formatConstructorErrorContext creates a LoadError with both context and
1142 // problem information for constructor-stage errors.
1143 func formatConstructorErrorContext(context string, contextMark Mark, err error, mark Mark) *LoadError {
1144 return &LoadError{
1145 Stage: ConstructorStage,
1146 ContextMark: contextMark,
1147 ContextMsg: context,
1148 Mark: mark,
1149 Message: err.Error(),
1150 err: err,
1151 }
1152 }