| 1 | package operand |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strconv" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | // Constant represents a constant literal. |
| 10 | type Constant interface { |
| 11 | Op |
| 12 | Bytes() int |
| 13 | constant() |
| 14 | } |
| 15 | |
| 16 | //go:generate go run make_const.go -output zconst.go |
| 17 | |
| 18 | // Special cases for floating point string representation. |
| 19 | // |
| 20 | // Issue 387 pointed out that floating point values that happen to be integers |
| 21 | // need to have a decimal point to be parsed correctly. |
| 22 | |
| 23 | // String returns a representation the 32-bit float which is guaranteed to be |
| 24 | // parsed as a floating point constant by the Go assembler. |
| 25 | func (f F32) String() string { return asmfloat(float64(f), 32) } |
| 26 | |
| 27 | // String returns a representation the 64-bit float which is guaranteed to be |
| 28 | // parsed as a floating point constant by the Go assembler. |
| 29 | func (f F64) String() string { return asmfloat(float64(f), 64) } |
| 30 | |
| 31 | // asmfloat represents x as a string such that the assembler scanner will always |
| 32 | // recognize it as a float. Specifically, ensure that when x is an integral |
| 33 | // value, the result will still have a decimal point. |
| 34 | func asmfloat(x float64, bits int) string { |
| 35 | s := strconv.FormatFloat(x, 'f', -1, bits) |
| 36 | if !strings.ContainsRune(s, '.') { |
| 37 | s += ".0" |
| 38 | } |
| 39 | return s |
| 40 | } |
| 41 | |
| 42 | // String is a string constant. |
| 43 | type String string |
| 44 | |
| 45 | // Asm returns an assembly syntax representation of the string s. |
| 46 | func (s String) Asm() string { return fmt.Sprintf("$%q", s) } |
| 47 | |
| 48 | // Bytes returns the length of s. |
| 49 | func (s String) Bytes() int { return len(s) } |
| 50 | |
| 51 | func (s String) constant() {} |
| 52 | |
| 53 | // Imm returns an unsigned integer constant with size guessed from x. |
| 54 | func Imm(x uint64) Constant { |
| 55 | switch { |
| 56 | case uint64(uint8(x)) == x: |
| 57 | return U8(x) |
| 58 | case uint64(uint16(x)) == x: |
| 59 | return U16(x) |
| 60 | case uint64(uint32(x)) == x: |
| 61 | return U32(x) |
| 62 | } |
| 63 | return U64(x) |
| 64 | } |