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

View as plain text