operand: fix integer float data (#393)

Issue #387 pointed out that integer float data is printed incorrectly, such
that it is not parsed correctly by the Go assembler. Specifically, integer
values need the decimal point, otherwise they will be treated as integers. For
example, 1 must be represented as `$(1.)` or `$(1.0)` to be parsed correctly.

This PR fixes that problem and adds a regression test.  The root of the
problem was that the formatting verb `%#v` does not have the right behavior
for integers. We fix it by deferring to custom `String()` function for the
float operand types.

Fixes #387
Closes #388
This commit is contained in:
Michael McLoughlin
2023-06-11 16:12:59 -07:00
committed by GitHub
parent 9bef88dadc
commit 0d789c8353
9 changed files with 172 additions and 4 deletions

View File

@@ -1,6 +1,10 @@
package operand
import "fmt"
import (
"fmt"
"strconv"
"strings"
)
// Constant represents a constant literal.
type Constant interface {
@@ -11,6 +15,30 @@ type Constant interface {
//go:generate go run make_const.go -output zconst.go
// Special cases for floating point string representation.
//
// Issue 387 pointed out that floating point values that happen to be integers
// need to have a decimal point to be parsed correctly.
// String returns a representation the 32-bit float which is guaranteed to be
// parsed as a floating point constant by the Go assembler.
func (f F32) String() string { return asmfloat(float64(f), 32) }
// String returns a representation the 64-bit float which is guaranteed to be
// parsed as a floating point constant by the Go assembler.
func (f F64) String() string { return asmfloat(float64(f), 64) }
// asmfloat represents x as a string such that the assembler scanner will always
// recognize it as a float. Specifically, ensure that when x is an integral
// value, the result will still have a decimal point.
func asmfloat(x float64, bits int) string {
s := strconv.FormatFloat(x, 'f', -1, bits)
if !strings.ContainsRune(s, '.') {
s += ".0"
}
return s
}
// String is a string constant.
type String string