Debian Codegraph @

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