Debian Codegraph @

internal/libyaml/structmeta.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 // Struct metadata extraction for YAML marshaling/unmarshaling.
6 //
7 // This file analyzes Go struct types to build mappings between YAML keys and
8 // struct fields. It parses struct tags like `yaml:"name,omitempty,flow,inline"`
9 // and caches the results for efficient repeated access.
10 //
11 // Used by:
12 // - Constructor: maps YAML keys to struct fields when unmarshaling
13 // - Representer: maps struct fields to YAML keys when marshaling
14 //
15 // Key types:
16 // - structInfo: cached metadata about a struct type
17 // - fieldInfo: metadata about a single struct field
18 // - getStructInfo(): analyzes a struct type and returns cached metadata
19
20 package libyaml
21
22 import (
23 "errors"
24 "fmt"
25 "reflect"
26 "strings"
27 "sync"
28 )
29
30 // structInfo holds cached information about a struct's YAML-relevant fields.
31 type structInfo struct {
32 FieldsMap map[string]fieldInfo
33 FieldsList []fieldInfo
34
35 // InlineMap is the number of the field in the struct that
36 // contains an ,inline map, or -1 if there's none.
37 InlineMap int
38
39 // InlineConstructors holds indexes to inlined fields that
40 // contain constructor values.
41 InlineConstructors [][]int
42 }
43
44 // fieldInfo holds information about a single struct field.
45 type fieldInfo struct {
46 Key string
47 Num int
48 OmitEmpty bool
49 Flow bool
50 // Id holds the unique field identifier, so we can cheaply
51 // check for field duplicates without maintaining an extra map.
52 Id int
53
54 // Inline holds the field index if the field is part of an inlined struct.
55 Inline []int
56 }
57
58 // structMap caches struct reflection information.
59 // fieldMapMutex protects access to structMap.
60 // constructorType holds the [reflect.Type] for the constructor interface.
61 var (
62 structMap = make(map[reflect.Type]*structInfo)
63 fieldMapMutex sync.RWMutex
64 constructorType reflect.Type
65 )
66
67 // constructor interface is defined here to detect types that implement
68 // UnmarshalYAML during struct reflection.
69 type constructor interface {
70 UnmarshalYAML(value *Node) error
71 }
72
73 // init initializes the constructorType variable with the [reflect.Type] of constructor interface.
74 func init() {
75 var v constructor
76 constructorType = reflect.ValueOf(&v).Elem().Type()
77 }
78
79 // hasConstructYAMLMethod checks if a type has an UnmarshalYAML method
80 // that takes a *Node from an allowlisted v3 yaml package. This detects
81 // v3 backward-compatible Unmarshaler implementations whose Node type
82 // can't be checked via interface assertion from this package.
83 func hasConstructYAMLMethod(t reflect.Type) bool {
84 method, found := t.MethodByName("UnmarshalYAML")
85 if !found {
86 return false
87 }
88
89 // Check signature: func(*T) UnmarshalYAML(*Node) error
90 mtype := method.Type
91 if mtype.NumIn() != 2 || mtype.NumOut() != 1 {
92 return false
93 }
94
95 // First param is receiver (already checked by MethodByName)
96 // Second param should be a pointer to a Node-like struct
97 paramType := mtype.In(1)
98 if paramType.Kind() != reflect.Ptr {
99 return false
100 }
101
102 elemType := paramType.Elem()
103 if elemType.Kind() != reflect.Struct || elemType.Name() != "Node" || !isYAMLNodePkg(elemType.PkgPath()) {
104 return false
105 }
106
107 // Return type should be error
108 retType := mtype.Out(0)
109 if retType.Kind() != reflect.Interface || retType.Name() != "error" {
110 return false
111 }
112
113 return true
114 }
115
116 func isYAMLNodePkg(pkg string) bool {
117 switch pkg {
118 case "gopkg.in/yaml.v3", "go.yaml.in/yaml/v3":
119 return true
120 }
121 return false
122 }
123
124 // getStructInfo returns cached information about a struct type's fields.
125 // It parses struct tags and builds a map of field names to field info.
126 func getStructInfo(st reflect.Type) (*structInfo, error) {
127 fieldMapMutex.RLock()
128 sinfo, found := structMap[st]
129 fieldMapMutex.RUnlock()
130 if found {
131 return sinfo, nil
132 }
133
134 n := st.NumField()
135 fieldsMap := make(map[string]fieldInfo)
136 fieldsList := make([]fieldInfo, 0, n)
137 inlineMap := -1
138 inlineConstructors := [][]int(nil)
139 for i := 0; i != n; i++ {
140 field := st.Field(i)
141 if field.PkgPath != "" && !field.Anonymous {
142 continue // Private field
143 }
144
145 info := fieldInfo{Num: i}
146
147 tag := field.Tag.Get("yaml")
148 if tag == "" && !strings.Contains(string(field.Tag), ":") {
149 tag = string(field.Tag)
150 }
151 if tag == "-" {
152 continue
153 }
154
155 inline := false
156 fields := strings.Split(tag, ",")
157 if len(fields) > 1 {
158 for _, flag := range fields[1:] {
159 switch flag {
160 case "omitempty":
161 info.OmitEmpty = true
162 case "flow":
163 info.Flow = true
164 case "inline":
165 inline = true
166 default:
167 return nil, fmt.Errorf("unsupported flag %q in tag %q of type %s", flag, tag, st)
168 }
169 }
170 tag = fields[0]
171 }
172
173 if inline {
174 switch field.Type.Kind() {
175 case reflect.Map:
176 if inlineMap >= 0 {
177 return nil, errors.New("multiple ,inline maps in struct " + st.String())
178 }
179 if field.Type.Key() != reflect.TypeOf("") {
180 return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String())
181 }
182 inlineMap = info.Num
183 case reflect.Struct, reflect.Pointer:
184 ftype := field.Type
185 for ftype.Kind() == reflect.Pointer {
186 ftype = ftype.Elem()
187 }
188 if ftype.Kind() != reflect.Struct {
189 return nil, errors.New("option ,inline may only be used on a struct or map field")
190 }
191 // Check for both libyaml.constructor and yaml.Unmarshaler (by method name)
192 if reflect.PointerTo(ftype).Implements(constructorType) || hasConstructYAMLMethod(reflect.PointerTo(ftype)) {
193 inlineConstructors = append(inlineConstructors, []int{i})
194 } else {
195 sinfo, err := getStructInfo(ftype)
196 if err != nil {
197 return nil, err
198 }
199 for _, index := range sinfo.InlineConstructors {
200 inlineConstructors = append(inlineConstructors, append([]int{i}, index...))
201 }
202 for _, finfo := range sinfo.FieldsList {
203 if _, found := fieldsMap[finfo.Key]; found {
204 msg := "duplicated key '" + finfo.Key + "' in struct " + st.String()
205 return nil, errors.New(msg)
206 }
207 if finfo.Inline == nil {
208 finfo.Inline = []int{i, finfo.Num}
209 } else {
210 finfo.Inline = append([]int{i}, finfo.Inline...)
211 }
212 finfo.Id = len(fieldsList)
213 fieldsMap[finfo.Key] = finfo
214 fieldsList = append(fieldsList, finfo)
215 }
216 }
217 default:
218 return nil, errors.New("option ,inline may only be used on a struct or map field")
219 }
220 continue
221 }
222
223 if tag != "" {
224 info.Key = tag
225 } else {
226 info.Key = strings.ToLower(field.Name)
227 }
228
229 if _, found = fieldsMap[info.Key]; found {
230 msg := "duplicated key '" + info.Key + "' in struct " + st.String()
231 return nil, errors.New(msg)
232 }
233
234 info.Id = len(fieldsList)
235 fieldsList = append(fieldsList, info)
236 fieldsMap[info.Key] = info
237 }
238
239 sinfo = &structInfo{
240 FieldsMap: fieldsMap,
241 FieldsList: fieldsList,
242 InlineMap: inlineMap,
243 InlineConstructors: inlineConstructors,
244 }
245
246 fieldMapMutex.Lock()
247 structMap[st] = sinfo
248 fieldMapMutex.Unlock()
249 return sinfo, nil
250 }