Source file src/encoding/json/v2/arshal_funcs.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  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"reflect"
    14  	"sync"
    15  
    16  	"encoding/json/internal/jsonflags"
    17  	"encoding/json/internal/jsonopts"
    18  	"encoding/json/jsontext"
    19  )
    20  
    21  var errUnsupportedMutation = errors.New("unsupported calls must not read or write any tokens")
    22  var errNonSingularValue = errors.New("must read or write exactly one value")
    23  
    24  // Marshalers is a list of functions that may override the marshal behavior
    25  // of specific types. Populate [WithMarshalers] to use it with
    26  // [Marshal], [MarshalWrite], or [MarshalEncode].
    27  // A nil *Marshalers is equivalent to an empty list.
    28  // There are no exported fields or methods on Marshalers.
    29  type Marshalers = typedMarshalers
    30  
    31  // JoinMarshalers constructs a flattened list of marshal functions.
    32  // If multiple functions in the list are applicable for a value of a given type,
    33  // then those earlier in the list take precedence over those that come later.
    34  // If a function returns [errors.ErrUnsupported],
    35  // then the next applicable function is called,
    36  // otherwise the default marshaling behavior is used.
    37  //
    38  // For example:
    39  //
    40  //	m1 := JoinMarshalers(f1, f2)
    41  //	m2 := JoinMarshalers(f0, m1, f3)     // equivalent to m3
    42  //	m3 := JoinMarshalers(f0, f1, f2, f3) // equivalent to m2
    43  func JoinMarshalers(ms ...*Marshalers) *Marshalers {
    44  	return newMarshalers(ms...)
    45  }
    46  
    47  // Unmarshalers is a list of functions that may override the unmarshal behavior
    48  // of specific types. Populate [WithUnmarshalers] to use it with
    49  // [Unmarshal], [UnmarshalRead], or [UnmarshalDecode].
    50  // A nil *Unmarshalers is equivalent to an empty list.
    51  // There are no exported fields or methods on Unmarshalers.
    52  type Unmarshalers = typedUnmarshalers
    53  
    54  // JoinUnmarshalers constructs a flattened list of unmarshal functions.
    55  // If multiple functions in the list are applicable for a value of a given type,
    56  // then those earlier in the list take precedence over those that come later.
    57  // If a function returns [errors.ErrUnsupported],
    58  // then the next applicable function is called,
    59  // otherwise the default unmarshaling behavior is used.
    60  //
    61  // For example:
    62  //
    63  //	u1 := JoinUnmarshalers(f1, f2)
    64  //	u2 := JoinUnmarshalers(f0, u1, f3)     // equivalent to u3
    65  //	u3 := JoinUnmarshalers(f0, f1, f2, f3) // equivalent to u2
    66  func JoinUnmarshalers(us ...*Unmarshalers) *Unmarshalers {
    67  	return newUnmarshalers(us...)
    68  }
    69  
    70  type typedMarshalers = typedArshalers[jsontext.Encoder, maybeAddressableValue]
    71  type typedUnmarshalers = typedArshalers[jsontext.Decoder, alwaysAddressableValue]
    72  type typedArshalers[Coder, Value any] struct {
    73  	nonComparable
    74  
    75  	fncVals  []typedArshaler[Coder, Value]
    76  	fncCache sync.Map // map[reflect.Type]arshaler
    77  
    78  	// fromAny reports whether any of Go types used to represent arbitrary JSON
    79  	// (i.e., any, bool, string, float64, map[string]any, or []any) matches
    80  	// any of the provided type-specific arshalers.
    81  	//
    82  	// This bit of information is needed in arshal_default.go to determine
    83  	// whether to use the specialized logic in arshal_any.go to handle
    84  	// the any interface type. The logic in arshal_any.go does not support
    85  	// type-specific arshal functions, so we must avoid using that logic
    86  	// if this is true.
    87  	fromAny bool
    88  }
    89  type typedMarshaler = typedArshaler[jsontext.Encoder, maybeAddressableValue]
    90  type typedUnmarshaler = typedArshaler[jsontext.Decoder, alwaysAddressableValue]
    91  type typedArshaler[Coder, Value any] struct {
    92  	typ     reflect.Type
    93  	fnc     func(*Coder, Value, *jsonopts.Struct) error
    94  	maySkip bool
    95  }
    96  
    97  func newMarshalers(ms ...*Marshalers) *Marshalers       { return newTypedArshalers(ms...) }
    98  func newUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newTypedArshalers(us...) }
    99  func newTypedArshalers[Coder, Value any](as ...*typedArshalers[Coder, Value]) *typedArshalers[Coder, Value] {
   100  	var a typedArshalers[Coder, Value]
   101  	for _, a2 := range as {
   102  		if a2 != nil {
   103  			a.fncVals = append(a.fncVals, a2.fncVals...)
   104  			a.fromAny = a.fromAny || a2.fromAny
   105  		}
   106  	}
   107  	if len(a.fncVals) == 0 {
   108  		return nil
   109  	}
   110  	return &a
   111  }
   112  
   113  func (a *typedArshalers[Coder, Value]) lookup(fnc func(*Coder, Value, *jsonopts.Struct) error, t reflect.Type) (func(*Coder, Value, *jsonopts.Struct) error, bool) {
   114  	if a == nil {
   115  		return fnc, false
   116  	}
   117  	if v, ok := a.fncCache.Load(t); ok {
   118  		if v == nil {
   119  			return fnc, false
   120  		}
   121  		return v.(func(*Coder, Value, *jsonopts.Struct) error), true
   122  	}
   123  
   124  	// Collect a list of arshalers that can be called for this type.
   125  	// This list may be longer than 1 since some arshalers can be skipped.
   126  	var fncs []func(*Coder, Value, *jsonopts.Struct) error
   127  	for _, fncVal := range a.fncVals {
   128  		if !castableTo(t, fncVal.typ) {
   129  			continue
   130  		}
   131  		fncs = append(fncs, fncVal.fnc)
   132  		if !fncVal.maySkip {
   133  			break // subsequent arshalers will never be called
   134  		}
   135  	}
   136  
   137  	if len(fncs) == 0 {
   138  		a.fncCache.Store(t, nil) // nil to indicate that no funcs found
   139  		return fnc, false
   140  	}
   141  
   142  	// Construct an arshaler that may call every applicable arshaler.
   143  	fncDefault := fnc
   144  	fnc = func(c *Coder, v Value, o *jsonopts.Struct) error {
   145  		for _, fnc := range fncs {
   146  			if err := fnc(c, v, o); !errors.Is(err, errors.ErrUnsupported) {
   147  				return err // may be nil or non-nil
   148  			}
   149  		}
   150  		return fncDefault(c, v, o)
   151  	}
   152  
   153  	// Use the first stored so duplicate work can be garbage collected.
   154  	v, _ := a.fncCache.LoadOrStore(t, fnc)
   155  	return v.(func(*Coder, Value, *jsonopts.Struct) error), true
   156  }
   157  
   158  // MarshalFunc constructs a type-specific marshaler that
   159  // specifies how to marshal values of type T.
   160  // T can be any type except a named pointer.
   161  // The function is always provided with a non-nil pointer value
   162  // if T is an interface or pointer type.
   163  //
   164  // Implementations must follow the requirements of [Marshaler].
   165  //
   166  // Implementations must not retain the value of T.
   167  func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers {
   168  	t := reflect.TypeFor[T]()
   169  	assertCastableTo(t, true)
   170  	typFnc := typedMarshaler{
   171  		typ: t,
   172  		fnc: func(enc *jsontext.Encoder, vm maybeAddressableValue, mo *jsonopts.Struct) error {
   173  			va := vm.ensureAddr()
   174  			v, _ := reflect.TypeAssert[T](va.castTo(t))
   175  			val, err := fn(v)
   176  			if err != nil {
   177  				err = wrapErrUnsupported(err, "marshal function of type func(T) ([]byte, error)")
   178  				if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
   179  					return newLegacyMarshalerError(vm, true, err, "MarshalFunc")
   180  				}
   181  				err = newMarshalErrorBefore(enc, t, err)
   182  				return collapseSemanticErrors(err)
   183  			}
   184  			if err := enc.WriteValue(val); err != nil {
   185  				if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
   186  					return newLegacyMarshalerError(vm, true, err, "MarshalFunc")
   187  				}
   188  				if isSyntacticError(err) {
   189  					err = newMarshalErrorBefore(enc, t, err)
   190  				}
   191  				return err
   192  			}
   193  			return nil
   194  		},
   195  	}
   196  	return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)}
   197  }
   198  
   199  // MarshalToFunc constructs a type-specific marshaler that
   200  // specifies how to marshal values of type T.
   201  // T can be any type except a named pointer.
   202  // The function is always provided with a non-nil pointer value
   203  // if T is an interface or pointer type.
   204  //
   205  // Implementations must follow the requirements of [MarshalerTo].
   206  //
   207  // Implementations must not retain the pointer to [jsontext.Encoder] or the
   208  // value of T.
   209  func MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers {
   210  	t := reflect.TypeFor[T]()
   211  	assertCastableTo(t, true)
   212  	typFnc := typedMarshaler{
   213  		typ: t,
   214  		fnc: func(enc *jsontext.Encoder, vm maybeAddressableValue, mo *jsonopts.Struct) error {
   215  			va := vm.ensureAddr()
   216  			xe := export.Encoder(enc)
   217  			prevDepth, prevLength := xe.Tokens.DepthLength()
   218  			xe.Flags.Set(jsonflags.WithinArshalCall | 1)
   219  			v, _ := reflect.TypeAssert[T](va.castTo(t))
   220  			err := fn(enc, v)
   221  			xe.Flags.Set(jsonflags.WithinArshalCall | 0)
   222  			currDepth, currLength := xe.Tokens.DepthLength()
   223  			if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) {
   224  				err = errNonSingularValue
   225  			}
   226  			if err != nil {
   227  				if errors.Is(err, errors.ErrUnsupported) {
   228  					if prevDepth == currDepth && prevLength == currLength {
   229  						return err // forward [errors.ErrUnsupported]
   230  					}
   231  					err = errUnsupportedMutation
   232  				}
   233  				if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
   234  					return newLegacyMarshalerError(vm, true, err, "MarshalToFunc")
   235  				}
   236  				if !export.IsIOError(err) {
   237  					err = newSemanticErrorWithPosition(enc, t, prevDepth, prevLength, err)
   238  				}
   239  				return err
   240  			}
   241  			return nil
   242  		},
   243  		maySkip: true,
   244  	}
   245  	return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)}
   246  }
   247  
   248  // UnmarshalFunc constructs a type-specific unmarshaler that
   249  // specifies how to unmarshal values of type T.
   250  // T must be an unnamed pointer or an interface type.
   251  // The function is always provided with a non-nil pointer value.
   252  //
   253  // Implementations must follow the requirements of [Unmarshaler].
   254  //
   255  // Implementations must not retain the value of T.
   256  func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers {
   257  	t := reflect.TypeFor[T]()
   258  	assertCastableTo(t, false)
   259  	typFnc := typedUnmarshaler{
   260  		typ: t,
   261  		fnc: func(dec *jsontext.Decoder, va alwaysAddressableValue, uo *jsonopts.Struct) error {
   262  			val, err := dec.ReadValue()
   263  			if err != nil {
   264  				return err // must be a syntactic or I/O error
   265  			}
   266  			v, _ := reflect.TypeAssert[T](va.castTo(t))
   267  			err = fn(val, v)
   268  			if err != nil {
   269  				err = wrapErrUnsupported(err, "unmarshal function of type func([]byte, T) error")
   270  				if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
   271  					return err // unlike marshal, never wrapped
   272  				}
   273  				err = newUnmarshalErrorAfter(dec, t, err)
   274  				return collapseSemanticErrors(err)
   275  			}
   276  			return nil
   277  		},
   278  	}
   279  	return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)}
   280  }
   281  
   282  // UnmarshalFromFunc constructs a type-specific unmarshaler that
   283  // specifies how to unmarshal values of type T.
   284  // T must be an unnamed pointer or an interface type.
   285  // The function is always provided with a non-nil pointer value.
   286  //
   287  // Implementations must follow the requirements of [UnmarshalerFrom].
   288  //
   289  // Implementations must not retain the pointer to [jsontext.Decoder] or the
   290  // value of T.
   291  func UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers {
   292  	t := reflect.TypeFor[T]()
   293  	assertCastableTo(t, false)
   294  	typFnc := typedUnmarshaler{
   295  		typ: t,
   296  		fnc: func(dec *jsontext.Decoder, va alwaysAddressableValue, uo *jsonopts.Struct) error {
   297  			xd := export.Decoder(dec)
   298  			prevDepth, prevLength := xd.Tokens.DepthLength()
   299  			if prevDepth == 1 && xd.AtEOF() {
   300  				return io.EOF // check EOF early to avoid fn reporting an EOF
   301  			}
   302  			xd.Flags.Set(jsonflags.WithinArshalCall | 1)
   303  			v, _ := reflect.TypeAssert[T](va.castTo(t))
   304  			err := fn(dec, v)
   305  			xd.Flags.Set(jsonflags.WithinArshalCall | 0)
   306  			currDepth, currLength := xd.Tokens.DepthLength()
   307  			if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) {
   308  				err = errNonSingularValue
   309  			}
   310  			if err != nil {
   311  				if errors.Is(err, errors.ErrUnsupported) {
   312  					if prevDepth == currDepth && prevLength == currLength {
   313  						return err // forward [errors.ErrUnsupported]
   314  					}
   315  					err = errUnsupportedMutation
   316  				}
   317  				if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) {
   318  					if err2 := xd.SkipUntil(prevDepth, prevLength+1); err2 != nil {
   319  						return err2
   320  					}
   321  					return err // unlike marshal, never wrapped
   322  				}
   323  				if !isSyntacticError(err) && !export.IsIOError(err) {
   324  					err = newSemanticErrorWithPosition(dec, t, prevDepth, prevLength, err)
   325  				}
   326  				return err
   327  			}
   328  			return nil
   329  		},
   330  		maySkip: true,
   331  	}
   332  	return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)}
   333  }
   334  
   335  // assertCastableTo asserts that "to" is a valid type to be casted to.
   336  // These are the Go types that type-specific arshalers may operate upon.
   337  //
   338  // Let AllTypes be the universal set of all possible Go types.
   339  // This function generally asserts that:
   340  //
   341  //	len([from for from in AllTypes if castableTo(from, to)]) > 0
   342  //
   343  // otherwise it panics.
   344  //
   345  // As a special-case if marshal is false, then we forbid any non-pointer or
   346  // non-interface type since it is almost always a bug trying to unmarshal
   347  // into something where the end-user caller did not pass in an addressable value
   348  // since they will not observe the mutations.
   349  func assertCastableTo(to reflect.Type, marshal bool) {
   350  	switch to.Kind() {
   351  	case reflect.Interface:
   352  		return
   353  	case reflect.Pointer:
   354  		// Only allow unnamed pointers to be consistent with the fact that
   355  		// taking the address of a value produces an unnamed pointer type.
   356  		if to.Name() == "" {
   357  			return
   358  		}
   359  	default:
   360  		// Technically, non-pointer types are permissible for unmarshal.
   361  		// However, they are often a bug since the receiver would be immutable.
   362  		// Thus, only allow them for marshaling.
   363  		if marshal {
   364  			return
   365  		}
   366  	}
   367  	if marshal {
   368  		panic(fmt.Sprintf("input type %v must be an interface type, an unnamed pointer type, or a non-pointer type", to))
   369  	} else {
   370  		panic(fmt.Sprintf("input type %v must be an interface type or an unnamed pointer type", to))
   371  	}
   372  }
   373  
   374  // castableTo checks whether values of type "from" can be casted to type "to".
   375  // Nil pointer or interface "from" values are never considered castable.
   376  //
   377  // This function must be kept in sync with addressableValue.castTo.
   378  func castableTo(from, to reflect.Type) bool {
   379  	switch to.Kind() {
   380  	case reflect.Interface:
   381  		// TODO: This breaks when ordinary interfaces can have type sets
   382  		// since interfaces now exist where only the value form of a type (T)
   383  		// implements the interface, but not the pointer variant (*T).
   384  		// See https://go.dev/issue/45346.
   385  		return reflect.PointerTo(from).Implements(to)
   386  	case reflect.Pointer:
   387  		// Common case for unmarshaling.
   388  		// From must be a concrete or interface type.
   389  		return reflect.PointerTo(from) == to
   390  	default:
   391  		// Common case for marshaling.
   392  		// From must be a concrete type.
   393  		return from == to
   394  	}
   395  }
   396  
   397  // castTo casts va to the specified type.
   398  // If the type is an interface, then the underlying type will always
   399  // be a non-nil pointer to a concrete type.
   400  //
   401  // Requirement: castableTo(va.Type(), to) must hold.
   402  func (va alwaysAddressableValue) castTo(to reflect.Type) reflect.Value {
   403  	switch to.Kind() {
   404  	case reflect.Interface:
   405  		return va.Addr().Convert(to)
   406  	case reflect.Pointer:
   407  		return va.Addr()
   408  	default:
   409  		return va.Value
   410  	}
   411  }
   412  
   413  // castableToFromAny reports whether "to" can be casted to from any
   414  // of the dynamic types used to represent arbitrary JSON.
   415  func castableToFromAny(to reflect.Type) bool {
   416  	for _, from := range []reflect.Type{anyType, boolType, stringType, float64Type, mapStringAnyType, sliceAnyType} {
   417  		if castableTo(from, to) {
   418  			return true
   419  		}
   420  	}
   421  	return false
   422  }
   423  

View as plain text