Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/errors.go

raw
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package json
6
7 import (
8 "cmp"
9 "errors"
10 "fmt"
11 "reflect"
12 "strconv"
13 "strings"
14 "sync"
15
16 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
17 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts"
18 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
19 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
20 )
21
22 // ErrUnknownName indicates that a JSON object member could not be
23 // unmarshaled because the name is not known to the target Go struct.
24 // This error is directly wrapped within a [SemanticError] when produced.
25 //
26 // The name of an unknown JSON object member can be extracted as:
27 //
28 // err := ...
29 // var serr json.SemanticError
30 // if errors.As(err, &serr) && serr.Err == json.ErrUnknownName {
31 // ptr := serr.JSONPointer // JSON pointer to unknown name
32 // name := ptr.LastToken() // unknown name itself
33 // ...
34 // }
35 //
36 // This error is only returned if [RejectUnknownMembers] is true.
37 var ErrUnknownName = errors.New("unknown object member name")
38
39 const errorPrefix = "json: "
40
41 func isSemanticError(err error) bool {
42 _, ok := err.(*SemanticError)
43 return ok
44 }
45
46 func isSyntacticError(err error) bool {
47 _, ok := err.(*jsontext.SyntacticError)
48 return ok
49 }
50
51 // isFatalError reports whether this error must terminate asharling.
52 // All errors are considered fatal unless operating under
53 // [jsonflags.ReportErrorsWithLegacySemantics] in which case only
54 // syntactic errors and I/O errors are considered fatal.
55 func isFatalError(err error, flags jsonflags.Flags) bool {
56 return !flags.Get(jsonflags.ReportErrorsWithLegacySemantics) ||
57 isSyntacticError(err) || export.IsIOError(err)
58 }
59
60 // SemanticError describes an error determining the meaning
61 // of JSON data as Go data or vice-versa.
62 //
63 // The contents of this error as produced by this package may change over time.
64 type SemanticError struct {
65 requireKeyedLiterals
66 nonComparable
67
68 action string // either "marshal" or "unmarshal"
69
70 // ByteOffset indicates that an error occurred after this byte offset.
71 ByteOffset int64
72 // JSONPointer indicates that an error occurred within this JSON value
73 // as indicated using the JSON Pointer notation (see RFC 6901).
74 JSONPointer jsontext.Pointer
75
76 // JSONKind is the JSON kind that could not be handled.
77 JSONKind jsontext.Kind // may be zero if unknown
78 // JSONValue is the JSON number or string that could not be unmarshaled.
79 // It is not populated during marshaling.
80 JSONValue jsontext.Value // may be nil if irrelevant or unknown
81 // GoType is the Go type that could not be handled.
82 GoType reflect.Type // may be nil if unknown
83
84 // Err is the underlying error.
85 Err error // may be nil
86 }
87
88 // coder is implemented by [jsontext.Encoder] or [jsontext.Decoder].
89 type coder interface {
90 StackPointer() jsontext.Pointer
91 Options() Options
92 }
93
94 // newInvalidFormatError wraps err in a SemanticError because
95 // the current type t cannot handle the provided options format.
96 // This error must be called before producing or consuming the next value.
97 //
98 // If [jsonflags.ReportErrorsWithLegacySemantics] is specified,
99 // then this automatically skips the next value when unmarshaling
100 // to ensure that the value is fully consumed.
101 func newInvalidFormatError(c coder, t reflect.Type) error {
102 err := fmt.Errorf("invalid format flag %q", c.Options().(*jsonopts.Struct).Format)
103 switch c := c.(type) {
104 case *jsontext.Encoder:
105 err = newMarshalErrorBefore(c, t, err)
106 case *jsontext.Decoder:
107 err = newUnmarshalErrorBeforeWithSkipping(c, t, err)
108 }
109 return err
110 }
111
112 // newMarshalErrorBefore wraps err in a SemanticError assuming that e
113 // is positioned right before the next token or value, which causes an error.
114 func newMarshalErrorBefore(e *jsontext.Encoder, t reflect.Type, err error) error {
115 return &SemanticError{action: "marshal", GoType: t, Err: err,
116 ByteOffset: e.OutputOffset() + int64(export.Encoder(e).CountNextDelimWhitespace()),
117 JSONPointer: jsontext.Pointer(export.Encoder(e).AppendStackPointer(nil, +1))}
118 }
119
120 // newUnmarshalErrorBefore wraps err in a SemanticError assuming that d
121 // is positioned right before the next token or value, which causes an error.
122 // It does not record the next JSON kind as this error is used to indicate
123 // the receiving Go value is invalid to unmarshal into (and not a JSON error).
124 // However, if [jsonflags.ReportErrorsWithLegacySemantics] is specified,
125 // then it does record the next JSON kind for historical reporting reasons.
126 func newUnmarshalErrorBefore(d *jsontext.Decoder, t reflect.Type, err error) error {
127 var k jsontext.Kind
128 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
129 k = d.PeekKind()
130 }
131 return &SemanticError{action: "unmarshal", GoType: t, Err: err,
132 ByteOffset: d.InputOffset() + int64(export.Decoder(d).CountNextDelimWhitespace()),
133 JSONPointer: jsontext.Pointer(export.Decoder(d).AppendStackPointer(nil, +1)),
134 JSONKind: k}
135 }
136
137 // newUnmarshalErrorBeforeWithSkipping is like [newUnmarshalErrorBefore],
138 // but automatically skips the next value if
139 // [jsonflags.ReportErrorsWithLegacySemantics] is specified.
140 func newUnmarshalErrorBeforeWithSkipping(d *jsontext.Decoder, t reflect.Type, err error) error {
141 err = newUnmarshalErrorBefore(d, t, err)
142 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
143 if err2 := export.Decoder(d).SkipValue(); err2 != nil {
144 return err2
145 }
146 }
147 return err
148 }
149
150 // newUnmarshalErrorAfter wraps err in a SemanticError assuming that d
151 // is positioned right after the previous token or value, which caused an error.
152 func newUnmarshalErrorAfter(d *jsontext.Decoder, t reflect.Type, err error) error {
153 tokOrVal := export.Decoder(d).PreviousTokenOrValue()
154 return &SemanticError{action: "unmarshal", GoType: t, Err: err,
155 ByteOffset: d.InputOffset() - int64(len(tokOrVal)),
156 JSONPointer: jsontext.Pointer(export.Decoder(d).AppendStackPointer(nil, -1)),
157 JSONKind: jsontext.Value(tokOrVal).Kind()}
158 }
159
160 // newUnmarshalErrorAfter wraps err in a SemanticError assuming that d
161 // is positioned right after the previous token or value, which caused an error.
162 // It also stores a copy of the last JSON value if it is a string or number.
163 func newUnmarshalErrorAfterWithValue(d *jsontext.Decoder, t reflect.Type, err error) error {
164 serr := newUnmarshalErrorAfter(d, t, err).(*SemanticError)
165 if serr.JSONKind == '"' || serr.JSONKind == '0' {
166 serr.JSONValue = jsontext.Value(export.Decoder(d).PreviousTokenOrValue()).Clone()
167 }
168 return serr
169 }
170
171 // newUnmarshalErrorAfterWithSkipping is like [newUnmarshalErrorAfter],
172 // but automatically skips the remainder of the current value if
173 // [jsonflags.ReportErrorsWithLegacySemantics] is specified.
174 func newUnmarshalErrorAfterWithSkipping(d *jsontext.Decoder, t reflect.Type, err error) error {
175 err = newUnmarshalErrorAfter(d, t, err)
176 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
177 if err2 := export.Decoder(d).SkipValueRemainder(); err2 != nil {
178 return err2
179 }
180 }
181 return err
182 }
183
184 // newSemanticErrorWithPosition wraps err in a SemanticError assuming that
185 // the error occurred at the provided depth, and length.
186 // If err is already a SemanticError, then position information is only
187 // injected if it is currently unpopulated.
188 //
189 // If the position is unpopulated, it is ambiguous where the error occurred
190 // in the user code, whether it was before or after the current position.
191 // For the byte offset, we assume that the error occurred before the last read
192 // token or value when decoding, or before the next value when encoding.
193 // For the JSON pointer, we point to the parent object or array unless
194 // we can be certain that it happened with an object member.
195 //
196 // This is used to annotate errors returned by user-provided
197 // v2 MarshalJSON or UnmarshalJSON methods or functions.
198 func newSemanticErrorWithPosition(c coder, t reflect.Type, prevDepth int, prevLength int64, err error) error {
199 serr, _ := err.(*SemanticError)
200 if serr == nil {
201 serr = &SemanticError{Err: err}
202 }
203 var currDepth int
204 var currLength int64
205 var coderState interface{ AppendStackPointer([]byte, int) []byte }
206 var offset int64
207 switch c := c.(type) {
208 case *jsontext.Encoder:
209 e := export.Encoder(c)
210 serr.action = cmp.Or(serr.action, "marshal")
211 currDepth, currLength = e.Tokens.DepthLength()
212 offset = c.OutputOffset() + int64(export.Encoder(c).CountNextDelimWhitespace())
213 coderState = e
214 case *jsontext.Decoder:
215 d := export.Decoder(c)
216 serr.action = cmp.Or(serr.action, "unmarshal")
217 currDepth, currLength = d.Tokens.DepthLength()
218 tokOrVal := d.PreviousTokenOrValue()
219 offset = c.InputOffset() - int64(len(tokOrVal))
220 if (prevDepth == currDepth && prevLength == currLength) || len(tokOrVal) == 0 {
221 // If no Read method was called in the user-defined method or
222 // if the Peek method was called, then use the offset of the next value.
223 offset = c.InputOffset() + int64(export.Decoder(c).CountNextDelimWhitespace())
224 }
225 coderState = d
226 }
227 serr.ByteOffset = cmp.Or(serr.ByteOffset, offset)
228 if serr.JSONPointer == "" {
229 where := 0 // default to ambiguous positioning
230 switch {
231 case prevDepth == currDepth && prevLength+0 == currLength:
232 where = +1
233 case prevDepth == currDepth && prevLength+1 == currLength:
234 where = -1
235 }
236 serr.JSONPointer = jsontext.Pointer(coderState.AppendStackPointer(nil, where))
237 }
238 serr.GoType = cmp.Or(serr.GoType, t)
239 return serr
240 }
241
242 // collapseSemanticErrors collapses double SemanticErrors at the outer levels
243 // into a single SemanticError by preserving the inner error,
244 // but prepending the ByteOffset and JSONPointer with the outer error.
245 //
246 // For example:
247 //
248 // collapseSemanticErrors(&SemanticError{
249 // ByteOffset: len64(`[0,{"alpha":[0,1,`),
250 // JSONPointer: "/1/alpha/2",
251 // GoType: reflect.TypeFor[outerType](),
252 // Err: &SemanticError{
253 // ByteOffset: len64(`{"foo":"bar","fizz":[0,`),
254 // JSONPointer: "/fizz/1",
255 // GoType: reflect.TypeFor[innerType](),
256 // Err: ...,
257 // },
258 // })
259 //
260 // results in:
261 //
262 // &SemanticError{
263 // ByteOffset: len64(`[0,{"alpha":[0,1,`) + len64(`{"foo":"bar","fizz":[0,`),
264 // JSONPointer: "/1/alpha/2" + "/fizz/1",
265 // GoType: reflect.TypeFor[innerType](),
266 // Err: ...,
267 // }
268 //
269 // This is used to annotate errors returned by user-provided
270 // v1 MarshalJSON or UnmarshalJSON methods with precise position information
271 // if they themselves happened to return a SemanticError.
272 // Since MarshalJSON and UnmarshalJSON are not operating on the root JSON value,
273 // their positioning must be relative to the nested JSON value
274 // returned by UnmarshalJSON or passed to MarshalJSON.
275 // Therefore, we can construct an absolute position by concatenating
276 // the outer with the inner positions.
277 //
278 // Note that we do not use collapseSemanticErrors with user-provided functions
279 // that take in an [jsontext.Encoder] or [jsontext.Decoder] since they contain
280 // methods to report position relative to the root JSON value.
281 // We assume user-constructed errors are correctly precise about position.
282 func collapseSemanticErrors(err error) error {
283 if serr1, ok := err.(*SemanticError); ok {
284 if serr2, ok := serr1.Err.(*SemanticError); ok {
285 serr2.ByteOffset = serr1.ByteOffset + serr2.ByteOffset
286 serr2.JSONPointer = serr1.JSONPointer + serr2.JSONPointer
287 *serr1 = *serr2
288 }
289 }
290 return err
291 }
292
293 // errorModalVerb is a modal verb like "cannot" or "unable to".
294 //
295 // Once per process, Hyrum-proof the error message by deliberately
296 // switching between equivalent renderings of the same error message.
297 // The randomization is tied to the Hyrum-proofing already applied
298 // on map iteration in Go.
299 var errorModalVerb = sync.OnceValue(func() string {
300 for phrase := range map[string]struct{}{"cannot": {}, "unable to": {}} {
301 return phrase // use whichever phrase we get in the first iteration
302 }
303 return ""
304 })
305
306 func (e *SemanticError) Error() string {
307 var sb strings.Builder
308 sb.WriteString(errorPrefix)
309 sb.WriteString(errorModalVerb())
310
311 // Format action.
312 var preposition string
313 switch e.action {
314 case "marshal":
315 sb.WriteString(" marshal")
316 preposition = " from"
317 case "unmarshal":
318 sb.WriteString(" unmarshal")
319 preposition = " into"
320 default:
321 sb.WriteString(" handle")
322 preposition = " with"
323 }
324
325 // Format JSON kind.
326 switch e.JSONKind {
327 case 'n':
328 sb.WriteString(" JSON null")
329 case 'f', 't':
330 sb.WriteString(" JSON boolean")
331 case '"':
332 sb.WriteString(" JSON string")
333 case '0':
334 sb.WriteString(" JSON number")
335 case '{', '}':
336 sb.WriteString(" JSON object")
337 case '[', ']':
338 sb.WriteString(" JSON array")
339 default:
340 if e.action == "" {
341 preposition = ""
342 }
343 }
344 if len(e.JSONValue) > 0 && len(e.JSONValue) < 100 {
345 sb.WriteByte(' ')
346 sb.Write(e.JSONValue)
347 }
348
349 // Format Go type.
350 if e.GoType != nil {
351 typeString := e.GoType.String()
352 if len(typeString) > 100 {
353 // An excessively long type string most likely occurs for
354 // an anonymous struct declaration with many fields.
355 // Reduce the noise by just printing the kind,
356 // and optionally prepending it with the package name
357 // if the struct happens to include an unexported field.
358 typeString = e.GoType.Kind().String()
359 if e.GoType.Kind() == reflect.Struct && e.GoType.Name() == "" {
360 for i := range e.GoType.NumField() {
361 if pkgPath := e.GoType.Field(i).PkgPath; pkgPath != "" {
362 typeString = pkgPath[strings.LastIndexByte(pkgPath, '/')+len("/"):] + ".struct"
363 break
364 }
365 }
366 }
367 }
368 sb.WriteString(preposition)
369 sb.WriteString(" Go ")
370 sb.WriteString(typeString)
371 }
372
373 // Special handling for unknown names.
374 if e.Err == ErrUnknownName {
375 sb.WriteString(": ")
376 sb.WriteString(ErrUnknownName.Error())
377 sb.WriteString(" ")
378 sb.WriteString(strconv.Quote(e.JSONPointer.LastToken()))
379 if parent := e.JSONPointer.Parent(); parent != "" {
380 sb.WriteString(" within ")
381 sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(parent), 100)))
382 }
383 return sb.String()
384 }
385
386 // Format where.
387 // Avoid printing if it overlaps with a wrapped SyntacticError.
388 switch serr, _ := e.Err.(*jsontext.SyntacticError); {
389 case e.JSONPointer != "":
390 if serr == nil || !e.JSONPointer.Contains(serr.JSONPointer) {
391 sb.WriteString(" within ")
392 sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(e.JSONPointer), 100)))
393 }
394 case e.ByteOffset > 0:
395 if serr == nil || !(e.ByteOffset <= serr.ByteOffset) {
396 sb.WriteString(" after offset ")
397 sb.WriteString(strconv.FormatInt(e.ByteOffset, 10))
398 }
399 }
400
401 // Format underlying error.
402 if e.Err != nil {
403 errString := e.Err.Error()
404 if isSyntacticError(e.Err) {
405 errString = strings.TrimPrefix(errString, "jsontext: ")
406 }
407 sb.WriteString(": ")
408 sb.WriteString(errString)
409 }
410
411 return sb.String()
412 }
413
414 func (e *SemanticError) Unwrap() error {
415 return e.Err
416 }
417
418 func newDuplicateNameError(ptr jsontext.Pointer, quotedName []byte, offset int64) error {
419 if quotedName != nil {
420 name, _ := jsonwire.AppendUnquote(nil, quotedName)
421 ptr = ptr.AppendToken(string(name))
422 }
423 return &jsontext.SyntacticError{
424 ByteOffset: offset,
425 JSONPointer: ptr,
426 Err: jsontext.ErrDuplicateName,
427 }
428 }