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