cmd/cloner, cmd/viewer: handle named map/slice types with Clone/View methods
The cloner and viewer code generators didn't handle named types
with basic underlying types (map/slice) that have their own Clone
or View methods. For example, a type like:
type Map map[string]any
func (m Map) Clone() Map { ... }
func (m Map) View() MapView { ... }
When used as a struct field, the cloner would descend into the
underlying map[string]any and fail because it can't clone the any
(interface{}) value type. Similarly, the viewer would try to create
a MapFnOf view and fail.
Fix the cloner to check for a Clone method on the named type
before falling through to the underlying type handling.
Fix the viewer to check for a View method on named map/slice types,
so the type author can provide a purpose-built safe view that
doesn't leak raw any values. Named map/slice types without a View
method fall through to normal handling, which correctly rejects
types like map[string]any as unsupported.
Updates tailscale/corp#39502 (needed by tailscale/corp#39594)
Change-Id: Iaef0192a221e02b4b8e409c99ef8398090327744
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
committed by
Brad Fitzpatrick
parent
5a899e406d
commit
86f42ea87b
@@ -282,6 +282,22 @@ func genView(buf *bytes.Buffer, it *codegen.ImportTracker, typ *types.Named, fie
|
||||
writeTemplateWithComment("valueField", fname)
|
||||
continue
|
||||
}
|
||||
// Named map/slice types whose element type is opaque (e.g. any)
|
||||
// can't be safely wrapped in views.Map/views.Slice because the
|
||||
// accessor would leak the raw element. If the type provides its
|
||||
// own View() method the author can return a purpose-built safe
|
||||
// view; use it. Otherwise fall through to the normal handling,
|
||||
// which will reject the type as unsupported.
|
||||
if named, _ := codegen.NamedTypeOf(fieldType); named != nil {
|
||||
switch fieldType.Underlying().(type) {
|
||||
case *types.Map, *types.Slice:
|
||||
if viewType := viewTypeForValueType(fieldType); viewType != nil {
|
||||
args.FieldViewName = it.QualifiedName(viewType)
|
||||
writeTemplateWithComment("viewField", fname)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
switch underlying := fieldType.Underlying().(type) {
|
||||
case *types.Slice:
|
||||
slice := underlying
|
||||
|
||||
Reference in New Issue
Block a user