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

View as plain text