-
Notifications
You must be signed in to change notification settings - Fork 80
/
const_struct.go
82 lines (74 loc) · 1.71 KB
/
const_struct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package constant
import (
"fmt"
"strings"
"github.com/llir/llvm/ir/types"
)
// --- [ Struct constants ] ----------------------------------------------------
// Struct is an LLVM IR struct constant.
type Struct struct {
// Struct type.
Typ *types.StructType
// Struct fields.
Fields []Constant
}
// NewStruct returns a new struct constant based on the given struct type and
// fields. The struct type is infered from the type of the fields if t is nil.
func NewStruct(t *types.StructType, fields ...Constant) *Struct {
c := &Struct{
Fields: fields,
Typ: t,
}
// Compute type.
c.Type()
return c
}
// String returns the LLVM syntax representation of the constant as a type-value
// pair.
func (c *Struct) String() string {
return fmt.Sprintf("%s %s", c.Type(), c.Ident())
}
// Type returns the type of the constant.
func (c *Struct) Type() types.Type {
// Cache type if not present.
if c.Typ == nil {
var fieldTypes []types.Type
for _, field := range c.Fields {
fieldTypes = append(fieldTypes, field.Type())
}
c.Typ = types.NewStruct(fieldTypes...)
}
return c.Typ
}
// Ident returns the identifier associated with the constant.
func (c *Struct) Ident() string {
// Struct constant.
//
// '{' Fields=(TypeConst separator ',')+? '}'
//
// Packed struct constant.
//
// '<' '{' Fields=(TypeConst separator ',')+? '}' '>'
if len(c.Fields) == 0 {
if c.Typ.Packed {
return "<{}>"
}
return "{}"
}
buf := &strings.Builder{}
if c.Typ.Packed {
buf.WriteString("<")
}
buf.WriteString("{ ")
for i, field := range c.Fields {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(field.String())
}
buf.WriteString(" }")
if c.Typ.Packed {
buf.WriteString(">")
}
return buf.String()
}