Debian Codegraph @

internal/libyaml/resolver.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 // Tag resolution for YAML scalars.
6 // Determines implicit types (int, float, bool, null, timestamp) from untagged
7 // scalar values.
8
9 package libyaml
10
11 import (
12 "encoding/base64"
13 "fmt"
14 "math"
15 "regexp"
16 "strconv"
17 "strings"
18 "time"
19 )
20
21 // resolveMapItem holds a resolved value and its YAML tag for exact string
22 // matches in the resolution table.
23 type resolveMapItem struct {
24 value any
25 tag string
26 }
27
28 // Resolver handles tag resolution for YAML nodes.
29 type Resolver struct {
30 opts *Options
31 }
32
33 // NewResolver creates a new Resolver with the given options.
34 func NewResolver(opts *Options) *Resolver {
35 return &Resolver{opts: opts}
36 }
37
38 // Resolve walks the node tree and resolves tags for untagged nodes.
39 // This is called after composition to:
40 // - Default quoted scalars to !!str
41 // - Default sequences to !!seq
42 // - Default mappings to !!map
43 // - Resolve plain scalars to implicit types (int, float, bool, null, timestamp)
44 func (r *Resolver) Resolve(n *Node) {
45 if n == nil {
46 return
47 }
48
49 switch n.Kind {
50 case ScalarNode:
51 if n.Tag == "" {
52 if n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 {
53 // Quoted scalars default to !!str without value resolution
54 n.Tag = strTag
55 } else {
56 // Plain scalars: resolve type from value
57 n.Tag, _ = resolve("", n.Value)
58 }
59 }
60
61 case SequenceNode:
62 if n.Tag == "" {
63 n.Tag = seqTag
64 }
65 for _, child := range n.Content {
66 r.Resolve(child)
67 }
68
69 case MappingNode:
70 if n.Tag == "" {
71 n.Tag = mapTag
72 }
73 for _, child := range n.Content {
74 r.Resolve(child)
75 }
76
77 case DocumentNode:
78 for _, child := range n.Content {
79 r.Resolve(child)
80 }
81
82 case AliasNode:
83 // Alias nodes point to already-resolved nodes
84 }
85 }
86
87 // resolve determines the YAML tag and Go value for a scalar string.
88 // It takes a tag hint and the scalar string value, and returns the resolved
89 // tag and the corresponding Go value (int, float, bool, [time.Time], etc.).
90 // If the tag is already specified and non-resolvable, it returns the input
91 // unchanged.
92 func resolve(tag string, in string) (rtag string, out any) {
93 tag = shortTag(tag)
94 if !resolvableTag(tag) {
95 return tag, in
96 }
97
98 defer func() {
99 switch tag {
100 case "", rtag, strTag, binaryTag:
101 return
102 case floatTag:
103 if rtag == intTag {
104 switch v := out.(type) {
105 case int64:
106 rtag = floatTag
107 out = float64(v)
108 return
109 case int:
110 rtag = floatTag
111 out = float64(v)
112 return
113 }
114 }
115 }
116 Fail(formatResolverError(
117 fmt.Sprintf("cannot construct %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)),
118 Mark{},
119 ))
120 }()
121
122 // Any data is accepted as a !!str or !!binary.
123 // Otherwise, the prefix is enough of a hint about what it might be.
124 hint := byte('N')
125 if in != "" {
126 hint = resolveTable[in[0]]
127 }
128 if hint != 0 && tag != strTag && tag != binaryTag {
129 // Handle things we can lookup in a map.
130 if item, ok := resolveMap[in]; ok {
131 return item.tag, item.value
132 }
133
134 // Base 60 floats are a bad idea, were dropped in YAML 1.2, and
135 // are purposefully unsupported here. They're still quoted on
136 // the way out for compatibility with other parser, though.
137
138 switch hint {
139 case 'M':
140 // We've already checked the map above.
141
142 case '.':
143 // Not in the map, so maybe a normal float.
144 floatv, err := strconv.ParseFloat(in, 64)
145 if err == nil {
146 return floatTag, floatv
147 }
148
149 case 'D', 'S':
150 // Int, float, or timestamp.
151 // Only try values as a timestamp if the value is
152 // unquoted or there's an explicit !!timestamp tag.
153 if tag == "" || tag == timestampTag {
154 t, ok := parseTimestamp(in)
155 if ok {
156 return timestampTag, t
157 }
158 }
159
160 plain := strings.ReplaceAll(in, "_", "")
161 intv, err := strconv.ParseInt(plain, 0, 64)
162 if err == nil {
163 if intv == int64(int(intv)) {
164 return intTag, int(intv)
165 } else {
166 return intTag, intv
167 }
168 }
169 uintv, err := strconv.ParseUint(plain, 0, 64)
170 if err == nil {
171 return intTag, uintv
172 }
173 if yamlStyleFloat.MatchString(plain) {
174 floatv, err := strconv.ParseFloat(plain, 64)
175 if err == nil {
176 return floatTag, floatv
177 }
178 }
179 default:
180 panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")")
181 }
182 }
183 return strTag, in
184 }
185
186 // resolveTable provides a fast lookup table for initial character-based
187 // classification during tag resolution.
188 // resolveMap maps specific scalar strings to their resolved values and tags.
189 var (
190 resolveTable = make([]byte, 256)
191 resolveMap = make(map[string]resolveMapItem)
192 )
193
194 // negativeZero represents -0.0 for YAML encoding/decoding
195 // this is needed because Go constants cannot express -0.0
196 // https://staticcheck.dev/docs/checks/#SA4026
197 var negativeZero = math.Copysign(0.0, -1.0)
198
199 // yamlStyleFloat matches floating-point numbers in YAML style (including
200 // scientific notation and numbers starting with a dot).
201 var yamlStyleFloat = regexp.MustCompile(`^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?$`)
202
203 // allowedTimestampFormats lists the timestamp formats supported by the
204 // resolver.
205 // This is a subset of the formats allowed by the regular expression
206 // defined at http://yaml.org/type/timestamp.html.
207 var allowedTimestampFormats = []string{
208 "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields.
209 "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t".
210 "2006-1-2 15:4:5.999999999", // space separated with no time zone
211 "2006-1-2", // date only
212 // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5"
213 // from the set of examples.
214 }
215
216 // init initializes the resolveTable with character class mappings for tag resolution.
217 func init() {
218 t := resolveTable
219 t[int('+')] = 'S' // Sign
220 t[int('-')] = 'S'
221 for _, c := range "0123456789" {
222 t[int(c)] = 'D' // Digit
223 }
224 for _, c := range "yYnNtTfFoO~<" { // < for merge key <<
225 t[int(c)] = 'M' // In map
226 }
227 t[int('.')] = '.' // Float (potentially in map)
228
229 resolveMapList := []struct {
230 v any
231 tag string
232 l []string
233 }{
234 {true, boolTag, []string{"true", "True", "TRUE"}},
235 {false, boolTag, []string{"false", "False", "FALSE"}},
236 {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}},
237 {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}},
238 {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}},
239 {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}},
240 {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}},
241 {negativeZero, floatTag, []string{"-0", "-0.0"}},
242 {"<<", mergeTag, []string{"<<"}},
243 }
244
245 m := resolveMap
246 for _, item := range resolveMapList {
247 for _, s := range item.l {
248 m[s] = resolveMapItem{item.v, item.tag}
249 }
250 }
251 }
252
253 // resolvableTag checks if a tag can be automatically resolved from a scalar
254 // value.
255 func resolvableTag(tag string) bool {
256 switch tag {
257 case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag:
258 return true
259 }
260 return false
261 }
262
263 // encodeBase64 encodes s as base64 that is broken up into multiple lines
264 // as appropriate for the resulting length.
265 func encodeBase64(s string) string {
266 const lineLen = 70
267 encLen := base64.StdEncoding.EncodedLen(len(s))
268 lines := encLen/lineLen + 1
269 buf := make([]byte, encLen*2+lines)
270 in := buf[0:encLen]
271 out := buf[encLen:]
272 base64.StdEncoding.Encode(in, []byte(s))
273 k := 0
274 for i := 0; i < len(in); i += lineLen {
275 j := i + lineLen
276 if j > len(in) {
277 j = len(in)
278 }
279 k += copy(out[k:], in[i:j])
280 if lines > 1 {
281 out[k] = '\n'
282 k++
283 }
284 }
285 return string(out[:k])
286 }
287
288 // parseTimestamp parses s as a timestamp string and
289 // returns the timestamp and reports whether it succeeded.
290 // Timestamp formats are defined at http://yaml.org/type/timestamp.html
291 func parseTimestamp(s string) (time.Time, bool) {
292 // TODO write code to check all the formats supported by
293 // http://yaml.org/type/timestamp.html instead of using time.Parse.
294
295 // Quick check: all date formats start with YYYY-.
296 i := 0
297 for ; i < len(s); i++ {
298 if c := s[i]; c < '0' || c > '9' {
299 break
300 }
301 }
302 if i != 4 || i == len(s) || s[i] != '-' {
303 return time.Time{}, false
304 }
305 for _, format := range allowedTimestampFormats {
306 if t, err := time.Parse(format, s); err == nil {
307 return t, true
308 }
309 }
310 return time.Time{}, false
311 }
312
313 // formatResolverError creates a LoadError for resolver-stage errors.
314 func formatResolverError(message string, mark Mark) *LoadError {
315 return &LoadError{
316 Stage: ResolverStage,
317 Mark: mark,
318 Message: message,
319 }
320 }
321
322 // formatResolverErrorContext creates a LoadError with both context and
323 // problem information for resolver-stage errors.
324 func formatResolverErrorContext(context string, contextMark Mark, message string, mark Mark) *LoadError {
325 return &LoadError{
326 Stage: ResolverStage,
327 ContextMark: contextMark,
328 ContextMsg: context,
329 Mark: mark,
330 Message: message,
331 }
332 }