Debian Codegraph @

gotypes/components.go

raw symbols SCIP
1 package gotypes
2
3 import (
4 "errors"
5 "fmt"
6 "go/token"
7 "go/types"
8 "strconv"
9
10 "github.com/mmcloughlin/avo/operand"
11 "github.com/mmcloughlin/avo/reg"
12 )
13
14 // Sizes provides type sizes used by the standard Go compiler on amd64.
15 var Sizes = types.SizesFor("gc", "amd64")
16
17 // PointerSize is the size of a pointer on amd64.
18 var PointerSize = Sizes.Sizeof(types.Typ[types.UnsafePointer])
19
20 // Basic represents a primitive/basic type at a given memory address.
21 type Basic struct {
22 Addr operand.Mem
23 Type *types.Basic
24 }
25
26 // Component provides access to sub-components of a Go type.
27 type Component interface {
28 // When the component has no further sub-components, Resolve will return a
29 // reference to the components type and memory address. If there was an error
30 // during any previous calls to Component methods, they will be returned at
31 // resolution time.
32 Resolve() (*Basic, error)
33 Dereference(r reg.Register) Component // dereference a pointer
34 Base() Component // base pointer of a string or slice
35 Len() Component // length of a string or slice
36 Cap() Component // capacity of a slice
37 Real() Component // real part of a complex value
38 Imag() Component // imaginary part of a complex value
39 Index(int) Component // index into an array
40 Field(string) Component // access a struct field
41 }
42
43 // componenterr is an error that also provides a null implementation of the
44 // Component interface. This enables us to return an error from Component
45 // methods whilst also allowing method chaining to continue.
46 type componenterr string
47
48 func errorf(format string, args ...any) Component {
49 return componenterr(fmt.Sprintf(format, args...))
50 }
51
52 func (c componenterr) Error() string { return string(c) }
53 func (c componenterr) Resolve() (*Basic, error) { return nil, c }
54 func (c componenterr) Dereference(r reg.Register) Component { return c }
55 func (c componenterr) Base() Component { return c }
56 func (c componenterr) Len() Component { return c }
57 func (c componenterr) Cap() Component { return c }
58 func (c componenterr) Real() Component { return c }
59 func (c componenterr) Imag() Component { return c }
60 func (c componenterr) Index(int) Component { return c }
61 func (c componenterr) Field(string) Component { return c }
62
63 type component struct {
64 typ types.Type
65 addr operand.Mem
66 }
67
68 // NewComponent builds a component for the named type at the given address.
69 func NewComponent(t types.Type, addr operand.Mem) Component {
70 return &component{
71 typ: t,
72 addr: addr,
73 }
74 }
75
76 func (c *component) Resolve() (*Basic, error) {
77 b := toprimitive(c.typ)
78 if b == nil {
79 return nil, errors.New("component is not primitive")
80 }
81 return &Basic{
82 Addr: c.addr,
83 Type: b,
84 }, nil
85 }
86
87 func (c *component) Dereference(r reg.Register) Component {
88 p, ok := c.typ.Underlying().(*types.Pointer)
89 if !ok {
90 return errorf("not pointer type")
91 }
92 return NewComponent(p.Elem(), operand.Mem{Base: r})
93 }
94
95 // Reference: https://github.com/golang/go/blob/50bd1c4d4eb4fac8ddeb5f063c099daccfb71b26/src/reflect/value.go#L1800-L1804
96 //
97 // type SliceHeader struct {
98 // Data uintptr
99 // Len int
100 // Cap int
101 // }
102 var slicehdroffsets = Sizes.Offsetsof([]*types.Var{
103 types.NewField(token.NoPos, nil, "Data", types.Typ[types.Uintptr], false),
104 types.NewField(token.NoPos, nil, "Len", types.Typ[types.Int], false),
105 types.NewField(token.NoPos, nil, "Cap", types.Typ[types.Int], false),
106 })
107
108 func (c *component) Base() Component {
109 if !isslice(c.typ) && !isstring(c.typ) {
110 return errorf("only slices and strings have base pointers")
111 }
112 return c.sub("_base", int(slicehdroffsets[0]), types.Typ[types.Uintptr])
113 }
114
115 func (c *component) Len() Component {
116 if !isslice(c.typ) && !isstring(c.typ) {
117 return errorf("only slices and strings have length fields")
118 }
119 return c.sub("_len", int(slicehdroffsets[1]), types.Typ[types.Int])
120 }
121
122 func (c *component) Cap() Component {
123 if !isslice(c.typ) {
124 return errorf("only slices have capacity fields")
125 }
126 return c.sub("_cap", int(slicehdroffsets[2]), types.Typ[types.Int])
127 }
128
129 func (c *component) Real() Component {
130 if !iscomplex(c.typ) {
131 return errorf("only complex types have real values")
132 }
133 f := complextofloat(c.typ)
134 return c.sub("_real", 0, f)
135 }
136
137 func (c *component) Imag() Component {
138 if !iscomplex(c.typ) {
139 return errorf("only complex types have imaginary values")
140 }
141 f := complextofloat(c.typ)
142 return c.sub("_imag", int(Sizes.Sizeof(f)), f)
143 }
144
145 func (c *component) Index(i int) Component {
146 a, ok := c.typ.Underlying().(*types.Array)
147 if !ok {
148 return errorf("not array type")
149 }
150 if int64(i) >= a.Len() {
151 return errorf("array index out of bounds")
152 }
153 // Reference: https://github.com/golang/tools/blob/bcd4e47d02889ebbc25c9f4bf3d27e4124b0bf9d/go/analysis/passes/asmdecl/asmdecl.go#L482-L494
154 //
155 // case asmArray:
156 // tu := t.Underlying().(*types.Array)
157 // elem := tu.Elem()
158 // // Calculate offset of each element array.
159 // fields := []*types.Var{
160 // types.NewVar(token.NoPos, nil, "fake0", elem),
161 // types.NewVar(token.NoPos, nil, "fake1", elem),
162 // }
163 // offsets := arch.sizes.Offsetsof(fields)
164 // elemoff := int(offsets[1])
165 // for i := 0; i < int(tu.Len()); i++ {
166 // cc = appendComponentsRecursive(arch, elem, cc, suffix+"_"+strconv.Itoa(i), i*elemoff)
167 // }
168 //
169 elem := a.Elem()
170 elemsize := int(Sizes.Sizeof(types.NewArray(elem, 2)) - Sizes.Sizeof(types.NewArray(elem, 1)))
171 return c.sub("_"+strconv.Itoa(i), i*elemsize, elem)
172 }
173
174 func (c *component) Field(n string) Component {
175 s, ok := c.typ.Underlying().(*types.Struct)
176 if !ok {
177 return errorf("not struct type")
178 }
179 // Reference: https://github.com/golang/tools/blob/13ba8ad772dfbf0f451b5dd0679e9c5605afc05d/go/analysis/passes/asmdecl/asmdecl.go#L471-L480
180 //
181 // case asmStruct:
182 // tu := t.Underlying().(*types.Struct)
183 // fields := make([]*types.Var, tu.NumFields())
184 // for i := 0; i < tu.NumFields(); i++ {
185 // fields[i] = tu.Field(i)
186 // }
187 // offsets := arch.sizes.Offsetsof(fields)
188 // for i, f := range fields {
189 // cc = appendComponentsRecursive(arch, f.Type(), cc, suffix+"_"+f.Name(), off+int(offsets[i]))
190 // }
191 //
192 fields := make([]*types.Var, s.NumFields())
193 for i := 0; i < s.NumFields(); i++ {
194 fields[i] = s.Field(i)
195 }
196 offsets := Sizes.Offsetsof(fields)
197 for i, f := range fields {
198 if f.Name() == n {
199 return c.sub("_"+n, int(offsets[i]), f.Type())
200 }
201 }
202 return errorf("struct does not have field '%s'", n)
203 }
204
205 func (c *component) sub(suffix string, offset int, t types.Type) *component {
206 s := *c
207 if s.addr.Symbol.Name != "" {
208 s.addr.Symbol.Name += suffix
209 }
210 s.addr = s.addr.Offset(offset)
211 s.typ = t
212 return &s
213 }
214
215 func isslice(t types.Type) bool {
216 _, ok := t.Underlying().(*types.Slice)
217 return ok
218 }
219
220 func isstring(t types.Type) bool {
221 b, ok := t.Underlying().(*types.Basic)
222 return ok && b.Kind() == types.String
223 }
224
225 func iscomplex(t types.Type) bool {
226 b, ok := t.Underlying().(*types.Basic)
227 return ok && (b.Info()&types.IsComplex) != 0
228 }
229
230 func complextofloat(t types.Type) types.Type {
231 switch Sizes.Sizeof(t) {
232 case 16:
233 return types.Typ[types.Float64]
234 case 8:
235 return types.Typ[types.Float32]
236 }
237 panic("bad")
238 }
239
240 // toprimitive determines whether t is primitive (cannot be reduced into
241 // components). If it is, it returns the basic type for t, otherwise returns
242 // nil.
243 func toprimitive(t types.Type) *types.Basic {
244 switch b := t.(type) {
245 case *types.Basic:
246 if (b.Info() & (types.IsString | types.IsComplex)) == 0 {
247 return b
248 }
249 case *types.Pointer:
250 return types.Typ[types.Uintptr]
251 }
252 return nil
253 }