Debian Codegraph @

internal/typesinternal/zerovalue.go

raw symbols SCIP
1 // Copyright 2024 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 package typesinternal
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/token"
11 "go/types"
12 "strings"
13 )
14
15 // ZeroString returns the string representation of the zero value for any type t.
16 // The boolean result indicates whether the type is or contains an invalid type
17 // or a non-basic (constraint) interface type.
18 //
19 // Even for invalid input types, ZeroString may return a partially correct
20 // string representation. The caller should use the returned isValid boolean
21 // to determine the validity of the expression.
22 //
23 // When assigning to a wider type (such as 'any'), it's the caller's
24 // responsibility to handle any necessary type conversions.
25 //
26 // This string can be used on the right-hand side of an assignment where the
27 // left-hand side has that explicit type.
28 // References to named types are qualified by an appropriate (optional)
29 // qualifier function.
30 // Exception: This does not apply to tuples. Their string representation is
31 // informational only and cannot be used in an assignment.
32 //
33 // See [ZeroExpr] for a variant that returns an [ast.Expr].
34 func ZeroString(t types.Type, qual types.Qualifier) (_ string, isValid bool) {
35 switch t := t.(type) {
36 case *types.Basic:
37 switch {
38 case t.Info()&types.IsBoolean != 0:
39 return "false", true
40 case t.Info()&types.IsNumeric != 0:
41 return "0", true
42 case t.Info()&types.IsString != 0:
43 return `""`, true
44 case t.Kind() == types.UnsafePointer:
45 fallthrough
46 case t.Kind() == types.UntypedNil:
47 return "nil", true
48 case t.Kind() == types.Invalid:
49 return "invalid", false
50 default:
51 panic(fmt.Sprintf("ZeroString for unexpected type %v", t))
52 }
53
54 case *types.Pointer, *types.Slice, *types.Chan, *types.Map, *types.Signature:
55 return "nil", true
56
57 case *types.Interface:
58 if !t.IsMethodSet() {
59 return "invalid", false
60 }
61 return "nil", true
62
63 case *types.Named:
64 switch under := t.Underlying().(type) {
65 case *types.Struct, *types.Array:
66 return types.TypeString(t, qual) + "{}", true
67 default:
68 return ZeroString(under, qual)
69 }
70
71 case *types.Alias:
72 switch t.Underlying().(type) {
73 case *types.Struct, *types.Array:
74 return types.TypeString(t, qual) + "{}", true
75 default:
76 // A type parameter can have alias but alias type's underlying type
77 // can never be a type parameter.
78 // Use types.Unalias to preserve the info of type parameter instead
79 // of call Underlying() going right through and get the underlying
80 // type of the type parameter which is always an interface.
81 return ZeroString(types.Unalias(t), qual)
82 }
83
84 case *types.Array, *types.Struct:
85 return types.TypeString(t, qual) + "{}", true
86
87 case *types.TypeParam:
88 // Assumes func new is not shadowed.
89 return "*new(" + types.TypeString(t, qual) + ")", true
90
91 case *types.Tuple:
92 // Tuples are not normal values.
93 // We are currently format as "(t[0], ..., t[n])". Could be something else.
94 isValid := true
95 components := make([]string, t.Len())
96 for i := 0; i < t.Len(); i++ {
97 comp, ok := ZeroString(t.At(i).Type(), qual)
98
99 components[i] = comp
100 isValid = isValid && ok
101 }
102 return "(" + strings.Join(components, ", ") + ")", isValid
103
104 case *types.Union:
105 // Variables of these types cannot be created, so it makes
106 // no sense to ask for their zero value.
107 panic(fmt.Sprintf("invalid type for a variable: %v", t))
108
109 default:
110 panic(t) // unreachable.
111 }
112 }
113
114 // ZeroExpr returns the ast.Expr representation of the zero value for any type t.
115 // The boolean result indicates whether the type is or contains an invalid type
116 // or a non-basic (constraint) interface type.
117 //
118 // Even for invalid input types, ZeroExpr may return a partially correct ast.Expr
119 // representation. The caller should use the returned isValid boolean to determine
120 // the validity of the expression.
121 //
122 // This function is designed for types suitable for variables and should not be
123 // used with Tuple or Union types.References to named types are qualified by an
124 // appropriate (optional) qualifier function.
125 //
126 // See [ZeroString] for a variant that returns a string.
127 func ZeroExpr(t types.Type, qual types.Qualifier) (_ ast.Expr, isValid bool) {
128 switch t := t.(type) {
129 case *types.Basic:
130 switch {
131 case t.Info()&types.IsBoolean != 0:
132 return &ast.Ident{Name: "false"}, true
133 case t.Info()&types.IsNumeric != 0:
134 return &ast.BasicLit{Kind: token.INT, Value: "0"}, true
135 case t.Info()&types.IsString != 0:
136 return &ast.BasicLit{Kind: token.STRING, Value: `""`}, true
137 case t.Kind() == types.UnsafePointer:
138 fallthrough
139 case t.Kind() == types.UntypedNil:
140 return ast.NewIdent("nil"), true
141 case t.Kind() == types.Invalid:
142 return &ast.BasicLit{Kind: token.STRING, Value: `"invalid"`}, false
143 default:
144 panic(fmt.Sprintf("ZeroExpr for unexpected type %v", t))
145 }
146
147 case *types.Pointer, *types.Slice, *types.Chan, *types.Map, *types.Signature:
148 return ast.NewIdent("nil"), true
149
150 case *types.Interface:
151 if !t.IsMethodSet() {
152 return &ast.BasicLit{Kind: token.STRING, Value: `"invalid"`}, false
153 }
154 return ast.NewIdent("nil"), true
155
156 case *types.Named:
157 switch under := t.Underlying().(type) {
158 case *types.Struct, *types.Array:
159 return &ast.CompositeLit{
160 Type: TypeExpr(t, qual),
161 }, true
162 default:
163 return ZeroExpr(under, qual)
164 }
165
166 case *types.Alias:
167 switch t.Underlying().(type) {
168 case *types.Struct, *types.Array:
169 return &ast.CompositeLit{
170 Type: TypeExpr(t, qual),
171 }, true
172 default:
173 return ZeroExpr(types.Unalias(t), qual)
174 }
175
176 case *types.Array, *types.Struct:
177 return &ast.CompositeLit{
178 Type: TypeExpr(t, qual),
179 }, true
180
181 case *types.TypeParam:
182 return &ast.StarExpr{ // *new(T)
183 X: &ast.CallExpr{
184 // Assumes func new is not shadowed.
185 Fun: ast.NewIdent("new"),
186 Args: []ast.Expr{
187 ast.NewIdent(t.Obj().Name()),
188 },
189 },
190 }, true
191
192 case *types.Tuple:
193 // Unlike ZeroString, there is no ast.Expr can express tuple by
194 // "(t[0], ..., t[n])".
195 panic(fmt.Sprintf("invalid type for a variable: %v", t))
196
197 case *types.Union:
198 // Variables of these types cannot be created, so it makes
199 // no sense to ask for their zero value.
200 panic(fmt.Sprintf("invalid type for a variable: %v", t))
201
202 default:
203 panic(t) // unreachable.
204 }
205 }
206
207 // TypeExpr returns syntax for the specified type. References to named types
208 // are qualified by an appropriate (optional) qualifier function.
209 // It may panic for types such as Tuple or Union.
210 //
211 // See also https://go.dev/issues/75604, which will provide a robust
212 // Type-to-valid-Go-syntax formatter.
213 func TypeExpr(t types.Type, qual types.Qualifier) ast.Expr {
214 switch t := t.(type) {
215 case *types.Basic:
216 switch t.Kind() {
217 case types.UnsafePointer:
218 return &ast.SelectorExpr{X: ast.NewIdent(qual(types.NewPackage("unsafe", "unsafe"))), Sel: ast.NewIdent("Pointer")}
219 default:
220 return ast.NewIdent(t.Name())
221 }
222
223 case *types.Pointer:
224 return &ast.UnaryExpr{
225 Op: token.MUL,
226 X: TypeExpr(t.Elem(), qual),
227 }
228
229 case *types.Array:
230 return &ast.ArrayType{
231 Len: &ast.BasicLit{
232 Kind: token.INT,
233 Value: fmt.Sprintf("%d", t.Len()),
234 },
235 Elt: TypeExpr(t.Elem(), qual),
236 }
237
238 case *types.Slice:
239 return &ast.ArrayType{
240 Elt: TypeExpr(t.Elem(), qual),
241 }
242
243 case *types.Map:
244 return &ast.MapType{
245 Key: TypeExpr(t.Key(), qual),
246 Value: TypeExpr(t.Elem(), qual),
247 }
248
249 case *types.Chan:
250 dir := ast.ChanDir(t.Dir())
251 if t.Dir() == types.SendRecv {
252 dir = ast.SEND | ast.RECV
253 }
254 return &ast.ChanType{
255 Dir: dir,
256 Value: TypeExpr(t.Elem(), qual),
257 }
258
259 case *types.Signature:
260 var params []*ast.Field
261 for v := range t.Params().Variables() {
262 params = append(params, &ast.Field{
263 Type: TypeExpr(v.Type(), qual),
264 Names: []*ast.Ident{
265 {
266 Name: v.Name(),
267 },
268 },
269 })
270 }
271 if t.Variadic() {
272 last := params[len(params)-1]
273 last.Type = &ast.Ellipsis{Elt: last.Type.(*ast.ArrayType).Elt}
274 }
275 var returns []*ast.Field
276 for v := range t.Results().Variables() {
277 returns = append(returns, &ast.Field{
278 Type: TypeExpr(v.Type(), qual),
279 })
280 }
281 return &ast.FuncType{
282 Params: &ast.FieldList{
283 List: params,
284 },
285 Results: &ast.FieldList{
286 List: returns,
287 },
288 }
289
290 case *types.TypeParam:
291 pkgName := qual(t.Obj().Pkg())
292 if pkgName == "" || t.Obj().Pkg() == nil {
293 return ast.NewIdent(t.Obj().Name())
294 }
295 return &ast.SelectorExpr{
296 X: ast.NewIdent(pkgName),
297 Sel: ast.NewIdent(t.Obj().Name()),
298 }
299
300 // types.TypeParam also implements interface NamedOrAlias. To differentiate,
301 // case TypeParam need to be present before case NamedOrAlias.
302 // TODO(hxjiang): remove this comment once TypeArgs() is added to interface
303 // NamedOrAlias.
304 case NamedOrAlias:
305 var expr ast.Expr = ast.NewIdent(t.Obj().Name())
306 if pkgName := qual(t.Obj().Pkg()); pkgName != "." && pkgName != "" {
307 expr = &ast.SelectorExpr{
308 X: ast.NewIdent(pkgName),
309 Sel: expr.(*ast.Ident),
310 }
311 }
312
313 // TODO(hxjiang): call t.TypeArgs after adding method TypeArgs() to
314 // typesinternal.NamedOrAlias.
315 if hasTypeArgs, ok := t.(interface{ TypeArgs() *types.TypeList }); ok {
316 if typeArgs := hasTypeArgs.TypeArgs(); typeArgs != nil && typeArgs.Len() > 0 {
317 var indices []ast.Expr
318 for t0 := range typeArgs.Types() {
319 indices = append(indices, TypeExpr(t0, qual))
320 }
321 expr = &ast.IndexListExpr{
322 X: expr,
323 Indices: indices,
324 }
325 }
326 }
327
328 return expr
329
330 case *types.Struct:
331 return ast.NewIdent(t.String())
332
333 case *types.Interface:
334 return ast.NewIdent(t.String())
335
336 case *types.Union:
337 if t.Len() == 0 {
338 panic("Union type should have at least one term")
339 }
340 // Same as go/ast, the return expression will put last term in the
341 // Y field at topmost level of BinaryExpr.
342 // For union of type "float32 | float64 | int64", the structure looks
343 // similar to:
344 // {
345 // X: {
346 // X: float32,
347 // Op: |
348 // Y: float64,
349 // }
350 // Op: |,
351 // Y: int64,
352 // }
353 var union ast.Expr
354 for i := range t.Len() {
355 term := t.Term(i)
356 termExpr := TypeExpr(term.Type(), qual)
357 if term.Tilde() {
358 termExpr = &ast.UnaryExpr{
359 Op: token.TILDE,
360 X: termExpr,
361 }
362 }
363 if i == 0 {
364 union = termExpr
365 } else {
366 union = &ast.BinaryExpr{
367 X: union,
368 Op: token.OR,
369 Y: termExpr,
370 }
371 }
372 }
373 return union
374
375 case *types.Tuple:
376 panic("invalid input type types.Tuple")
377
378 default:
379 panic("unreachable")
380 }
381 }