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  	"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  // 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: 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: 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: 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  	var currDepth int
   211  	var currLength int64
   212  	var coderState interface{ AppendStackPointer([]byte, int) []byte }
   213  	var offset int64
   214  	switch c := c.(type) {
   215  	case *jsontext.Encoder:
   216  		e := export.Encoder(c)
   217  		serr.action = cmp.Or(serr.action, "marshal")
   218  		currDepth, currLength = e.Tokens.DepthLength()
   219  		offset = c.OutputOffset() + int64(export.Encoder(c).CountNextDelimWhitespace())
   220  		coderState = e
   221  	case *jsontext.Decoder:
   222  		d := export.Decoder(c)
   223  		serr.action = cmp.Or(serr.action, "unmarshal")
   224  		currDepth, currLength = d.Tokens.DepthLength()
   225  		tokOrVal := d.PreviousTokenOrValue()
   226  		offset = c.InputOffset() - int64(len(tokOrVal))
   227  		if (prevDepth == currDepth && prevLength == currLength) || len(tokOrVal) == 0 {
   228  			// If no Read method was called in the user-defined method or
   229  			// if the Peek method was called, then use the offset of the next value.
   230  			offset = c.InputOffset() + int64(export.Decoder(c).CountNextDelimWhitespace())
   231  		}
   232  		coderState = d
   233  	}
   234  	serr.ByteOffset = cmp.Or(serr.ByteOffset, offset)
   235  	if serr.JSONPointer == "" {
   236  		where := 0 // default to ambiguous positioning
   237  		switch {
   238  		case prevDepth == currDepth && prevLength+0 == currLength:
   239  			where = +1
   240  		case prevDepth == currDepth && prevLength+1 == currLength:
   241  			where = -1
   242  		}
   243  		serr.JSONPointer = jsontext.Pointer(coderState.AppendStackPointer(nil, where))
   244  	}
   245  	serr.GoType = cmp.Or(serr.GoType, t)
   246  	return serr
   247  }
   248  
   249  // collapseSemanticErrors collapses double SemanticErrors at the outer levels
   250  // into a single SemanticError by preserving the inner error,
   251  // but prepending the ByteOffset and JSONPointer with the outer error.
   252  //
   253  // For example:
   254  //
   255  //	collapseSemanticErrors(&SemanticError{
   256  //		ByteOffset:  len64(`[0,{"alpha":[0,1,`),
   257  //		JSONPointer: "/1/alpha/2",
   258  //		GoType:      reflect.TypeFor[outerType](),
   259  //		Err: &SemanticError{
   260  //			ByteOffset:  len64(`{"foo":"bar","fizz":[0,`),
   261  //			JSONPointer: "/fizz/1",
   262  //			GoType:      reflect.TypeFor[innerType](),
   263  //			Err:         ...,
   264  //		},
   265  //	})
   266  //
   267  // results in:
   268  //
   269  //	&SemanticError{
   270  //		ByteOffset:  len64(`[0,{"alpha":[0,1,`) + len64(`{"foo":"bar","fizz":[0,`),
   271  //		JSONPointer: "/1/alpha/2" + "/fizz/1",
   272  //		GoType:      reflect.TypeFor[innerType](),
   273  //		Err:         ...,
   274  //	}
   275  //
   276  // This is used to annotate errors returned by user-provided
   277  // v1 MarshalJSON or UnmarshalJSON methods with precise position information
   278  // if they themselves happened to return a SemanticError.
   279  // Since MarshalJSON and UnmarshalJSON are not operating on the root JSON value,
   280  // their positioning must be relative to the nested JSON value
   281  // returned by UnmarshalJSON or passed to MarshalJSON.
   282  // Therefore, we can construct an absolute position by concatenating
   283  // the outer with the inner positions.
   284  //
   285  // Note that we do not use collapseSemanticErrors with user-provided functions
   286  // that take in an [jsontext.Encoder] or [jsontext.Decoder] since they contain
   287  // methods to report position relative to the root JSON value.
   288  // We assume user-constructed errors are correctly precise about position.
   289  func collapseSemanticErrors(err error) error {
   290  	if serr1, ok := err.(*SemanticError); ok {
   291  		if serr2, ok := serr1.Err.(*SemanticError); ok {
   292  			serr2.ByteOffset = serr1.ByteOffset + serr2.ByteOffset
   293  			serr2.JSONPointer = serr1.JSONPointer + serr2.JSONPointer
   294  			*serr1 = *serr2
   295  		}
   296  	}
   297  	return err
   298  }
   299  
   300  // errorModalVerb is a modal verb like "cannot" or "unable to".
   301  //
   302  // Once per process, Hyrum-proof the error message by deliberately
   303  // switching between equivalent renderings of the same error message.
   304  // The randomization is tied to the Hyrum-proofing already applied
   305  // on map iteration in Go.
   306  var errorModalVerb = sync.OnceValue(func() string {
   307  	for phrase := range map[string]struct{}{"cannot": {}, "unable to": {}} {
   308  		return phrase // use whichever phrase we get in the first iteration
   309  	}
   310  	return ""
   311  })
   312  
   313  func (e *SemanticError) Error() string {
   314  	var sb strings.Builder
   315  	sb.WriteString(errorPrefix)
   316  	sb.WriteString(errorModalVerb())
   317  
   318  	// Format action.
   319  	var preposition string
   320  	switch e.action {
   321  	case "marshal":
   322  		sb.WriteString(" marshal")
   323  		preposition = " from"
   324  	case "unmarshal":
   325  		sb.WriteString(" unmarshal")
   326  		preposition = " into"
   327  	default:
   328  		sb.WriteString(" handle")
   329  		preposition = " with"
   330  	}
   331  
   332  	// Format JSON kind.
   333  	switch e.JSONKind {
   334  	case 'n':
   335  		sb.WriteString(" JSON null")
   336  	case 'f', 't':
   337  		sb.WriteString(" JSON boolean")
   338  	case '"':
   339  		sb.WriteString(" JSON string")
   340  	case '0':
   341  		sb.WriteString(" JSON number")
   342  	case '{', '}':
   343  		sb.WriteString(" JSON object")
   344  	case '[', ']':
   345  		sb.WriteString(" JSON array")
   346  	default:
   347  		if e.action == "" {
   348  			preposition = ""
   349  		}
   350  	}
   351  	if len(e.JSONValue) > 0 && len(e.JSONValue) < 100 {
   352  		sb.WriteByte(' ')
   353  		sb.Write(e.JSONValue)
   354  	}
   355  
   356  	// Format Go type.
   357  	if e.GoType != nil {
   358  		typeString := e.GoType.String()
   359  		if len(typeString) > 100 {
   360  			// An excessively long type string most likely occurs for
   361  			// an anonymous struct declaration with many fields.
   362  			// Reduce the noise by just printing the kind,
   363  			// and optionally prepending it with the package name
   364  			// if the struct happens to include an unexported field.
   365  			typeString = e.GoType.Kind().String()
   366  			if e.GoType.Kind() == reflect.Struct && e.GoType.Name() == "" {
   367  				for i := range e.GoType.NumField() {
   368  					if pkgPath := e.GoType.Field(i).PkgPath; pkgPath != "" {
   369  						typeString = pkgPath[strings.LastIndexByte(pkgPath, '/')+len("/"):] + ".struct"
   370  						break
   371  					}
   372  				}
   373  			}
   374  		}
   375  		sb.WriteString(preposition)
   376  		sb.WriteString(" Go ")
   377  		sb.WriteString(typeString)
   378  	}
   379  
   380  	// Special handling for unknown names.
   381  	if e.Err == ErrUnknownName {
   382  		sb.WriteString(": ")
   383  		sb.WriteString(ErrUnknownName.Error())
   384  		sb.WriteString(" ")
   385  		sb.WriteString(strconv.Quote(e.JSONPointer.LastToken()))
   386  		if parent := e.JSONPointer.Parent(); parent != "" {
   387  			sb.WriteString(" within ")
   388  			sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(parent), 100)))
   389  		}
   390  		return sb.String()
   391  	}
   392  
   393  	// Format where.
   394  	// Avoid printing if it overlaps with a wrapped SyntacticError.
   395  	switch serr, _ := e.Err.(*jsontext.SyntacticError); {
   396  	case e.JSONPointer != "":
   397  		if serr == nil || !e.JSONPointer.Contains(serr.JSONPointer) {
   398  			sb.WriteString(" within ")
   399  			sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(e.JSONPointer), 100)))
   400  		}
   401  	case e.ByteOffset > 0:
   402  		if serr == nil || !(e.ByteOffset <= serr.ByteOffset) {
   403  			sb.WriteString(" after offset ")
   404  			sb.WriteString(strconv.FormatInt(e.ByteOffset, 10))
   405  		}
   406  	}
   407  
   408  	// Format underlying error.
   409  	if e.Err != nil {
   410  		errString := e.Err.Error()
   411  		if isSyntacticError(e.Err) {
   412  			errString = strings.TrimPrefix(errString, "jsontext: ")
   413  		}
   414  		sb.WriteString(": ")
   415  		sb.WriteString(errString)
   416  	}
   417  
   418  	return sb.String()
   419  }
   420  
   421  func (e *SemanticError) Unwrap() error {
   422  	return e.Err
   423  }
   424  
   425  func newDuplicateNameError(ptr jsontext.Pointer, quotedName []byte, offset int64) error {
   426  	if quotedName != nil {
   427  		name, _ := jsonwire.AppendUnquote(nil, quotedName)
   428  		ptr = ptr.AppendToken(string(name))
   429  	}
   430  	return &jsontext.SyntacticError{
   431  		ByteOffset:  offset,
   432  		JSONPointer: ptr,
   433  		Err:         jsontext.ErrDuplicateName,
   434  	}
   435  }
   436  

View as plain text