Source file src/encoding/json/v2/errors.go

     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"
    20  	"encoding/json/internal/jsonflags"
    21  	"encoding/json/internal/jsonopts"
    22  	"encoding/json/internal/jsonwire"
    23  	"encoding/json/jsontext"
    24  )
    25  
    26  // ErrUnknownName indicates that a JSON object member could not be
    27  // unmarshaled because the name is not known to the target Go struct.
    28  // This error is directly wrapped within a [SemanticError] when produced.
    29  //
    30  // The name of an unknown JSON object member can be extracted as:
    31  //
    32  //	err := ...
    33  //	serr, ok := errors.AsType[*json.SemanticError](err)
    34  //	if ok && serr.Err == json.ErrUnknownName {
    35  //		ptr := serr.JSONPointer // JSON pointer to unknown name
    36  //		name := ptr.LastToken() // unknown name itself
    37  //		...
    38  //	}
    39  //
    40  // This error is only returned if [RejectUnknownMembers] is true.
    41  var ErrUnknownName = errors.New("unknown object member name")
    42  
    43  // errAmbiguousName indicates a JSON object member could be unmarshal
    44  // into multiple candidate Go struct fields.
    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  // isFatalError reports whether this error must terminate arshaling.
    60  // All errors are considered fatal unless operating under
    61  // [jsonflags.ReportErrorsWithLegacySemantics] in which case only
    62  // syntactic errors and I/O errors are considered fatal.
    63  func isFatalError(err error, flags jsonflags.Flags) bool {
    64  	return !flags.Get(jsonflags.ReportErrorsWithLegacySemantics) ||
    65  		isSyntacticError(err) || export.IsIOError(err)
    66  }
    67  
    68  // SemanticError describes an error determining the meaning
    69  // of JSON data as Go data, or vice versa.
    70  //
    71  // If a [Marshaler], [MarshalerTo], [Unmarshaler], or [UnmarshalerFrom] method
    72  // returns a SemanticError when called by the [json] package,
    73  // then the ByteOffset, JSONPointer, and GoType fields are automatically
    74  // populated by the calling context if they are the zero value.
    75  //
    76  // The contents of this error as produced by this package may change over time.
    77  type SemanticError struct {
    78  	requireKeyedLiterals
    79  	nonComparable
    80  
    81  	action string // either "marshal" or "unmarshal"
    82  
    83  	// ByteOffset indicates that an error occurred at or after this byte offset.
    84  	ByteOffset int64
    85  	// JSONPointer indicates that an error occurred within this JSON value
    86  	// as indicated using the JSON Pointer notation (see RFC 6901).
    87  	JSONPointer jsontext.Pointer
    88  
    89  	// JSONKind is the JSON kind that could not be handled.
    90  	JSONKind jsontext.Kind // may be zero if unknown
    91  	// JSONValue is the JSON number or string that could not be unmarshaled.
    92  	// It is not populated during marshaling.
    93  	JSONValue jsontext.Value // may be nil if irrelevant or unknown
    94  	// GoType is the Go type that could not be handled.
    95  	GoType reflect.Type // may be nil if unknown
    96  
    97  	// Err is the underlying error.
    98  	Err error // may be nil
    99  }
   100  
   101  // coder is implemented by [jsontext.Encoder] or [jsontext.Decoder].
   102  type coder interface {
   103  	StackPointer() jsontext.Pointer
   104  	Options() Options
   105  }
   106  
   107  // newInvalidFormatError constructs a SemanticError because
   108  // the current type t cannot handle the provided options format.
   109  // This function must be called before producing or consuming the next value.
   110  //
   111  // If [jsonflags.ReportErrorsWithLegacySemantics] is specified,
   112  // then this automatically skips the next value when unmarshaling
   113  // to ensure that the value is fully consumed.
   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  // newMarshalErrorBefore wraps err in a SemanticError assuming that e
   126  // is positioned right before the next token or value, which causes an error.
   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  // newUnmarshalErrorBefore wraps err in a SemanticError assuming that d
   134  // is positioned right before the next token or value, which causes an error.
   135  // It does not record the next JSON kind as this error is used to indicate
   136  // the receiving Go value is invalid to unmarshal into (and not a JSON error).
   137  // However, if [jsonflags.ReportErrorsWithLegacySemantics] is specified,
   138  // then it does record the next JSON kind for historical reporting reasons.
   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  // newUnmarshalErrorBeforeWithSkipping is like [newUnmarshalErrorBefore],
   151  // but automatically skips the next value if
   152  // [jsonflags.ReportErrorsWithLegacySemantics] is specified.
   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  // newUnmarshalErrorAfter wraps err in a SemanticError assuming that d
   164  // is positioned right after the previous token or value, which caused an error.
   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  		// NOTE: In v1, the offset pointed to the end of the bad token or value.
   170  		if k := jsontext.Value(tokOrVal).Kind(); k == '[' || k == '{' {
   171  			byteOffset++ // add just the '[' or '{'
   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  // newUnmarshalErrorAfterWithValue wraps err in a SemanticError assuming that d
   183  // is positioned right after the previous token or value, which caused an error.
   184  // It also stores a copy of the last JSON value if it is a string or number.
   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  // newUnmarshalErrorAfterWithSkipping is like [newUnmarshalErrorAfter],
   194  // but automatically skips the remainder of the current value if
   195  // [jsonflags.ReportErrorsWithLegacySemantics] is specified.
   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  // newSemanticErrorWithPosition wraps err in a SemanticError assuming that
   207  // the error occurred at the provided depth, and length.
   208  // If err is already a SemanticError, then position information is only
   209  // injected if it is currently unpopulated.
   210  //
   211  // If the position is unpopulated, it is ambiguous where the error occurred
   212  // in the user code, whether it was before or after the current position.
   213  // For the byte offset, we assume that the error occurred before the last read
   214  // token or value when decoding, or before the next value when encoding.
   215  // For the JSON pointer, we point to the parent object or array unless
   216  // we can be certain that it happened with an object member.
   217  //
   218  // This is used to annotate errors returned by user-provided
   219  // v2 MarshalJSON or UnmarshalJSON methods or functions.
   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  			// If no Read method was called in the user-defined method or
   245  			// if the Peek method was called, then use the offset of the next value.
   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 // default to ambiguous positioning
   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  // collapseSemanticErrors collapses double SemanticErrors at the outer levels
   266  // into a single SemanticError by preserving the inner error,
   267  // but prepending the ByteOffset and JSONPointer with the outer error.
   268  //
   269  // For example:
   270  //
   271  //	collapseSemanticErrors(&SemanticError{
   272  //		ByteOffset:  len64(`[0,{"alpha":[0,1,`),
   273  //		JSONPointer: "/1/alpha/2",
   274  //		GoType:      reflect.TypeFor[outerType](),
   275  //		Err: &SemanticError{
   276  //			ByteOffset:  len64(`{"foo":"bar","fizz":[0,`),
   277  //			JSONPointer: "/fizz/1",
   278  //			GoType:      reflect.TypeFor[innerType](),
   279  //			Err:         ...,
   280  //		},
   281  //	})
   282  //
   283  // results in:
   284  //
   285  //	&SemanticError{
   286  //		ByteOffset:  len64(`[0,{"alpha":[0,1,`) + len64(`{"foo":"bar","fizz":[0,`),
   287  //		JSONPointer: "/1/alpha/2" + "/fizz/1",
   288  //		GoType:      reflect.TypeFor[innerType](),
   289  //		Err:         ...,
   290  //	}
   291  //
   292  // This is used to annotate errors returned by user-provided
   293  // v1 MarshalJSON or UnmarshalJSON methods with precise position information
   294  // if they themselves happened to return a SemanticError.
   295  // Since MarshalJSON and UnmarshalJSON are not operating on the root JSON value,
   296  // their positioning must be relative to the nested JSON value
   297  // returned by UnmarshalJSON or passed to MarshalJSON.
   298  // Therefore, we can construct an absolute position by concatenating
   299  // the outer with the inner positions.
   300  //
   301  // Note that we do not use collapseSemanticErrors with user-provided functions
   302  // that take in an [jsontext.Encoder] or [jsontext.Decoder] since they contain
   303  // methods to report position relative to the root JSON value.
   304  // We assume user-constructed errors are correctly precise about position.
   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  // errorModalVerb is a modal verb like "cannot" or "unable to".
   324  //
   325  // Once per process, Hyrum-proof the error message by deliberately
   326  // switching between equivalent renderings of the same error message.
   327  // The randomization is tied to the Hyrum-proofing already applied
   328  // on map iteration in Go.
   329  var errorModalVerb = sync.OnceValue(func() string {
   330  	for phrase := range map[string]struct{}{"cannot": {}, "unable to": {}} {
   331  		return phrase // use whichever phrase we get in the first iteration
   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  	// Format action.
   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  	// Format JSON kind.
   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  	// Format Go type.
   380  	if e.GoType != nil {
   381  		typeString := e.GoType.String()
   382  		if len(typeString) > 100 {
   383  			// An excessively long type string most likely occurs for
   384  			// an anonymous struct declaration with many fields.
   385  			// Reduce the noise by just printing the kind,
   386  			// and optionally prepending it with the package name
   387  			// if the struct happens to include an unexported field.
   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  	// Special handling for unknown names.
   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  	// Format where.
   417  	// Avoid printing if it overlaps with a wrapped SyntacticError.
   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  	// Format underlying error.
   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  // newLegacyMarshalerError construct a legacy MarshalerError.
   461  // For historical reasons, v1 only wrapped Marshaler errors, but not Unmarshaler errors.
   462  func newLegacyMarshalerError(vm maybeAddressableValue, needAddr bool, err error, funcName string) error {
   463  	if vm.legacyNotAddressable && !needAddr {
   464  		// For historical reasons, the exact reported type depended on addressability.
   465  		return internal.NewMarshalerError(vm.Interface(), err, funcName)
   466  	}
   467  	return internal.NewMarshalerError(vm.ensureAddr().Addr().Interface(), err, funcName)
   468  }
   469  
   470  // toUnexpectedEOF converts [io.EOF] to [io.ErrUnexpectedEOF].
   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