-
Notifications
You must be signed in to change notification settings - Fork 80
/
const_array.go
103 lines (88 loc) · 2.45 KB
/
const_array.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package constant
import (
"fmt"
"strings"
"github.com/llir/llvm/internal/enc"
"github.com/llir/llvm/ir/types"
)
// --- [ Array constants ] -----------------------------------------------------
// Array is an LLVM IR array constant.
type Array struct {
// Array type.
Typ *types.ArrayType
// Array elements.
Elems []Constant
}
// NewArray returns a new array constant based on the given array type and
// elements. The array type is infered from the type of the elements if t is
// nil.
func NewArray(t *types.ArrayType, elems ...Constant) *Array {
c := &Array{
Elems: elems,
Typ: t,
}
// Compute type.
c.Type()
return c
}
// String returns the LLVM syntax representation of the constant as a type-value
// pair.
func (c *Array) String() string {
return fmt.Sprintf("%s %s", c.Type(), c.Ident())
}
// Type returns the type of the constant.
func (c *Array) Type() types.Type {
// Cache type if not present.
if c.Typ == nil {
elemType := c.Elems[0].Type()
c.Typ = types.NewArray(uint64(len(c.Elems)), elemType)
}
return c.Typ
}
// Ident returns the identifier associated with the constant.
func (c *Array) Ident() string {
// '[' Elems=(TypeConst separator ',')* ']'
buf := &strings.Builder{}
buf.WriteString("[")
for i, elem := range c.Elems {
if i != 0 {
buf.WriteString(", ")
}
buf.WriteString(elem.String())
}
buf.WriteString("]")
return buf.String()
}
// --- [ Character array constants ] -------------------------------------------
// CharArray is an LLVM IR character array constant.
type CharArray struct {
// Array type.
Typ *types.ArrayType
// Character array contents.
X []byte
}
// NewCharArray returns a new character array constant based on the given
// character array contents.
func NewCharArray(x []byte) *CharArray {
typ := types.NewArray(uint64(len(x)), types.I8)
return &CharArray{Typ: typ, X: x}
}
// NewCharArrayFromString returns a new character array constant based on the
// given UTF-8 string contents.
func NewCharArrayFromString(s string) *CharArray {
return NewCharArray([]byte(s))
}
// String returns the LLVM syntax representation of the constant as a type-value
// pair.
func (c *CharArray) String() string {
return fmt.Sprintf("%s %s", c.Type(), c.Ident())
}
// Type returns the type of the constant.
func (c *CharArray) Type() types.Type {
return c.Typ
}
// Ident returns the identifier associated with the constant.
func (c *CharArray) Ident() string {
// 'c' Val=StringLit
return "c" + enc.Quote(c.X)
}