1
2
3
4
5
6
7 package json
8
9 import (
10 "cmp"
11 "errors"
12 "fmt"
13 "io"
14 "reflect"
15 "strconv"
16 "strings"
17 "sync"
18
19 "encoding/json/internal"
20 "encoding/json/internal/jsonflags"
21 "encoding/json/internal/jsonopts"
22 "encoding/json/internal/jsonwire"
23 "encoding/json/jsontext"
24 )
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 var ErrUnknownName = errors.New("unknown object member name")
42
43
44
45 var errAmbiguousName = errors.New("ambiguous object member name")
46
47 const errorPrefix = "json: "
48
49 func isSemanticError(err error) bool {
50 _, ok := err.(*SemanticError)
51 return ok
52 }
53
54 func isSyntacticError(err error) bool {
55 _, ok := err.(*jsontext.SyntacticError)
56 return ok
57 }
58
59
60
61
62
63 func isFatalError(err error, flags jsonflags.Flags) bool {
64 return !flags.Get(jsonflags.ReportErrorsWithLegacySemantics) ||
65 isSyntacticError(err) || export.IsIOError(err)
66 }
67
68
69
70
71
72
73
74
75
76
77 type SemanticError struct {
78 requireKeyedLiterals
79 nonComparable
80
81 action string
82
83
84 ByteOffset int64
85
86
87 JSONPointer jsontext.Pointer
88
89
90 JSONKind jsontext.Kind
91
92
93 JSONValue jsontext.Value
94
95 GoType reflect.Type
96
97
98 Err error
99 }
100
101
102 type coder interface {
103 StackPointer() jsontext.Pointer
104 Options() Options
105 }
106
107
108
109
110
111
112
113
114 func newInvalidFormatError(c coder, t reflect.Type) error {
115 err := fmt.Errorf("invalid format flag %q", c.Options().(*jsonopts.Struct).Format)
116 switch c := c.(type) {
117 case *jsontext.Encoder:
118 err = newMarshalErrorBefore(c, t, err)
119 case *jsontext.Decoder:
120 err = newUnmarshalErrorBeforeWithSkipping(c, t, err)
121 }
122 return err
123 }
124
125
126
127 func newMarshalErrorBefore(e *jsontext.Encoder, t reflect.Type, err error) error {
128 return &SemanticError{action: "marshal", GoType: t, Err: toUnexpectedEOF(err),
129 ByteOffset: e.OutputOffset() + int64(export.Encoder(e).CountNextDelimWhitespace()),
130 JSONPointer: jsontext.Pointer(export.Encoder(e).AppendStackPointer(nil, +1))}
131 }
132
133
134
135
136
137
138
139 func newUnmarshalErrorBefore(d *jsontext.Decoder, t reflect.Type, err error) error {
140 var k jsontext.Kind
141 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
142 k = d.PeekKind()
143 }
144 return &SemanticError{action: "unmarshal", GoType: t, Err: toUnexpectedEOF(err),
145 ByteOffset: d.InputOffset() + int64(export.Decoder(d).CountNextDelimWhitespace()),
146 JSONPointer: jsontext.Pointer(export.Decoder(d).AppendStackPointer(nil, +1)),
147 JSONKind: k}
148 }
149
150
151
152
153 func newUnmarshalErrorBeforeWithSkipping(d *jsontext.Decoder, t reflect.Type, err error) error {
154 err = newUnmarshalErrorBefore(d, t, err)
155 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
156 if err2 := export.Decoder(d).SkipValue(); err2 != nil {
157 return err2
158 }
159 }
160 return err
161 }
162
163
164
165 func newUnmarshalErrorAfter(d *jsontext.Decoder, t reflect.Type, err error) error {
166 tokOrVal := export.Decoder(d).PreviousTokenOrValue()
167 byteOffset := d.InputOffset() - int64(len(tokOrVal))
168 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
169
170 if k := jsontext.Value(tokOrVal).Kind(); k == '[' || k == '{' {
171 byteOffset++
172 } else {
173 byteOffset += int64(len(tokOrVal))
174 }
175 }
176 return &SemanticError{action: "unmarshal", GoType: t, Err: toUnexpectedEOF(err),
177 ByteOffset: byteOffset,
178 JSONPointer: jsontext.Pointer(export.Decoder(d).AppendStackPointer(nil, -1)),
179 JSONKind: jsontext.Value(tokOrVal).Kind()}
180 }
181
182
183
184
185 func newUnmarshalErrorAfterWithValue(d *jsontext.Decoder, t reflect.Type, err error) error {
186 serr := newUnmarshalErrorAfter(d, t, err).(*SemanticError)
187 if serr.JSONKind == '"' || serr.JSONKind == '0' {
188 serr.JSONValue = jsontext.Value(export.Decoder(d).PreviousTokenOrValue()).Clone()
189 }
190 return serr
191 }
192
193
194
195
196 func newUnmarshalErrorAfterWithSkipping(d *jsontext.Decoder, t reflect.Type, err error) error {
197 err = newUnmarshalErrorAfter(d, t, err)
198 if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
199 if err2 := export.Decoder(d).SkipValueRemainder(); err2 != nil {
200 return err2
201 }
202 }
203 return err
204 }
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220 func newSemanticErrorWithPosition(c coder, t reflect.Type, prevDepth int, prevLength int64, err error) error {
221 serr, _ := err.(*SemanticError)
222 if serr == nil {
223 serr = &SemanticError{Err: err}
224 }
225 serr.Err = toUnexpectedEOF(serr.Err)
226 var currDepth int
227 var currLength int64
228 var coderState interface{ AppendStackPointer([]byte, int) []byte }
229 var offset int64
230 switch c := c.(type) {
231 case *jsontext.Encoder:
232 e := export.Encoder(c)
233 serr.action = cmp.Or(serr.action, "marshal")
234 currDepth, currLength = e.Tokens.DepthLength()
235 offset = c.OutputOffset() + int64(export.Encoder(c).CountNextDelimWhitespace())
236 coderState = e
237 case *jsontext.Decoder:
238 d := export.Decoder(c)
239 serr.action = cmp.Or(serr.action, "unmarshal")
240 currDepth, currLength = d.Tokens.DepthLength()
241 tokOrVal := d.PreviousTokenOrValue()
242 offset = c.InputOffset() - int64(len(tokOrVal))
243 if (prevDepth == currDepth && prevLength == currLength) || len(tokOrVal) == 0 {
244
245
246 offset = c.InputOffset() + int64(export.Decoder(c).CountNextDelimWhitespace())
247 }
248 coderState = d
249 }
250 serr.ByteOffset = cmp.Or(serr.ByteOffset, offset)
251 if serr.JSONPointer == "" {
252 where := 0
253 switch {
254 case prevDepth == currDepth && prevLength+0 == currLength:
255 where = +1
256 case prevDepth == currDepth && prevLength+1 == currLength:
257 where = -1
258 }
259 serr.JSONPointer = jsontext.Pointer(coderState.AppendStackPointer(nil, where))
260 }
261 serr.GoType = cmp.Or(serr.GoType, t)
262 return serr
263 }
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305 func collapseSemanticErrors(err error) error {
306 if serr1, ok := err.(*SemanticError); ok {
307 if serr2, ok := serr1.Err.(*SemanticError); ok {
308 serr2.ByteOffset = serr1.ByteOffset + serr2.ByteOffset
309 serr2.JSONPointer = serr1.JSONPointer + serr2.JSONPointer
310 *serr1 = *serr2
311 }
312 }
313 return err
314 }
315
316 func wrapErrUnsupported(err error, what string) error {
317 if errors.Is(err, errors.ErrUnsupported) {
318 return errors.New(what + " may not return errors.ErrUnsupported")
319 }
320 return err
321 }
322
323
324
325
326
327
328
329 var errorModalVerb = sync.OnceValue(func() string {
330 for phrase := range map[string]struct{}{"cannot": {}, "unable to": {}} {
331 return phrase
332 }
333 return ""
334 })
335
336 func (e *SemanticError) Error() string {
337 var sb strings.Builder
338 sb.WriteString(errorPrefix)
339 sb.WriteString(errorModalVerb())
340
341
342 var preposition string
343 switch e.action {
344 case "marshal":
345 sb.WriteString(" marshal")
346 preposition = " from"
347 case "unmarshal":
348 sb.WriteString(" unmarshal")
349 preposition = " into"
350 default:
351 sb.WriteString(" handle")
352 preposition = " with"
353 }
354
355
356 switch e.JSONKind {
357 case 'n':
358 sb.WriteString(" JSON null")
359 case 'f', 't':
360 sb.WriteString(" JSON boolean")
361 case '"':
362 sb.WriteString(" JSON string")
363 case '0':
364 sb.WriteString(" JSON number")
365 case '{', '}':
366 sb.WriteString(" JSON object")
367 case '[', ']':
368 sb.WriteString(" JSON array")
369 default:
370 if e.action == "" {
371 preposition = ""
372 }
373 }
374 if len(e.JSONValue) > 0 && len(e.JSONValue) < 100 {
375 sb.WriteByte(' ')
376 sb.Write(e.JSONValue)
377 }
378
379
380 if e.GoType != nil {
381 typeString := e.GoType.String()
382 if len(typeString) > 100 {
383
384
385
386
387
388 typeString = e.GoType.Kind().String()
389 if e.GoType.Kind() == reflect.Struct && e.GoType.Name() == "" {
390 for i := range e.GoType.NumField() {
391 if pkgPath := e.GoType.Field(i).PkgPath; pkgPath != "" {
392 typeString = pkgPath[strings.LastIndexByte(pkgPath, '/')+len("/"):] + ".struct"
393 break
394 }
395 }
396 }
397 }
398 sb.WriteString(preposition)
399 sb.WriteString(" Go ")
400 sb.WriteString(typeString)
401 }
402
403
404 if e.Err == ErrUnknownName || e.Err == errAmbiguousName {
405 sb.WriteString(": ")
406 sb.WriteString(e.Err.Error())
407 sb.WriteString(" ")
408 sb.WriteString(strconv.Quote(e.JSONPointer.LastToken()))
409 if parent := e.JSONPointer.Parent(); parent != "" {
410 sb.WriteString(" within ")
411 sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(parent), 100)))
412 }
413 return sb.String()
414 }
415
416
417
418 switch serr, _ := e.Err.(*jsontext.SyntacticError); {
419 case e.JSONPointer != "":
420 if serr == nil || !e.JSONPointer.Contains(serr.JSONPointer) {
421 sb.WriteString(" within ")
422 sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(e.JSONPointer), 100)))
423 }
424 case e.ByteOffset > 0:
425 if serr == nil || !(e.ByteOffset <= serr.ByteOffset) {
426 sb.WriteString(" after offset ")
427 sb.WriteString(strconv.FormatInt(e.ByteOffset, 10))
428 }
429 }
430
431
432 if e.Err != nil {
433 errString := e.Err.Error()
434 if isSyntacticError(e.Err) {
435 errString = strings.TrimPrefix(errString, "jsontext: ")
436 }
437 sb.WriteString(": ")
438 sb.WriteString(errString)
439 }
440
441 return sb.String()
442 }
443
444 func (e *SemanticError) Unwrap() error {
445 return e.Err
446 }
447
448 func newDuplicateNameError(ptr jsontext.Pointer, quotedName []byte, offset int64) error {
449 if quotedName != nil {
450 name, _ := jsonwire.AppendUnquote(nil, quotedName)
451 ptr = ptr.AppendToken(string(name))
452 }
453 return &jsontext.SyntacticError{
454 ByteOffset: offset,
455 JSONPointer: ptr,
456 Err: jsontext.ErrDuplicateName,
457 }
458 }
459
460
461
462 func newLegacyMarshalerError(vm maybeAddressableValue, needAddr bool, err error, funcName string) error {
463 if vm.legacyNotAddressable && !needAddr {
464
465 return internal.NewMarshalerError(vm.Interface(), err, funcName)
466 }
467 return internal.NewMarshalerError(vm.ensureAddr().Addr().Interface(), err, funcName)
468 }
469
470
471 func toUnexpectedEOF(err error) error {
472 if err == io.EOF {
473 return io.ErrUnexpectedEOF
474 }
475 return err
476 }
477
View as plain text