github.com/llir/llvm@v0.3.6/ir/constant/const_array.go (about) 1 package constant 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/llir/llvm/internal/enc" 8 "github.com/llir/llvm/ir/types" 9 ) 10 11 // --- [ Array constants ] ----------------------------------------------------- 12 13 // Array is an LLVM IR array constant. 14 type Array struct { 15 // Array type. 16 Typ *types.ArrayType 17 // Array elements. 18 Elems []Constant 19 } 20 21 // NewArray returns a new array constant based on the given array type and 22 // elements. The array type is infered from the type of the elements if t is 23 // nil. 24 func NewArray(t *types.ArrayType, elems ...Constant) *Array { 25 c := &Array{ 26 Elems: elems, 27 Typ: t, 28 } 29 // Compute type. 30 c.Type() 31 return c 32 } 33 34 // String returns the LLVM syntax representation of the constant as a type-value 35 // pair. 36 func (c *Array) String() string { 37 return fmt.Sprintf("%s %s", c.Type(), c.Ident()) 38 } 39 40 // Type returns the type of the constant. 41 func (c *Array) Type() types.Type { 42 // Cache type if not present. 43 if c.Typ == nil { 44 elemType := c.Elems[0].Type() 45 c.Typ = types.NewArray(uint64(len(c.Elems)), elemType) 46 } 47 return c.Typ 48 } 49 50 // Ident returns the identifier associated with the constant. 51 func (c *Array) Ident() string { 52 // '[' Elems=(TypeConst separator ',')* ']' 53 buf := &strings.Builder{} 54 buf.WriteString("[") 55 for i, elem := range c.Elems { 56 if i != 0 { 57 buf.WriteString(", ") 58 } 59 buf.WriteString(elem.String()) 60 } 61 buf.WriteString("]") 62 return buf.String() 63 } 64 65 // --- [ Character array constants ] ------------------------------------------- 66 67 // CharArray is an LLVM IR character array constant. 68 type CharArray struct { 69 // Array type. 70 Typ *types.ArrayType 71 // Character array contents. 72 X []byte 73 } 74 75 // NewCharArray returns a new character array constant based on the given 76 // character array contents. 77 func NewCharArray(x []byte) *CharArray { 78 typ := types.NewArray(uint64(len(x)), types.I8) 79 return &CharArray{Typ: typ, X: x} 80 } 81 82 // NewCharArrayFromString returns a new character array constant based on the 83 // given UTF-8 string contents. 84 func NewCharArrayFromString(s string) *CharArray { 85 return NewCharArray([]byte(s)) 86 } 87 88 // String returns the LLVM syntax representation of the constant as a type-value 89 // pair. 90 func (c *CharArray) String() string { 91 return fmt.Sprintf("%s %s", c.Type(), c.Ident()) 92 } 93 94 // Type returns the type of the constant. 95 func (c *CharArray) Type() types.Type { 96 return c.Typ 97 } 98 99 // Ident returns the identifier associated with the constant. 100 func (c *CharArray) Ident() string { 101 // 'c' Val=StringLit 102 return "c" + enc.Quote(c.X) 103 }