From 9cd7f827f418cf955add8d183c751c4e84498bbe Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Wed, 15 Nov 2023 00:36:35 +0900 Subject: [PATCH] internal/shaderir: bug fix: constants must be truncated correctly in an array Closes #2840 --- internal/shader/expr.go | 28 ++++++++++++++++++- .../shader/testdata/issue2840.expected.vs | 16 +++++++++++ internal/shader/testdata/issue2840.go | 9 ++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 internal/shader/testdata/issue2840.expected.vs create mode 100644 internal/shader/testdata/issue2840.go diff --git a/internal/shader/expr.go b/internal/shader/expr.go index 859718170..abfebae85 100644 --- a/internal/shader/expr.go +++ b/internal/shader/expr.go @@ -854,6 +854,32 @@ func (cs *compileState) parseExpr(block *block, fname string, expr ast.Expr, mar cs.addError(e.Pos(), "multiple-value context is not available at a composite literal") return nil, nil, nil, false } + + expr := exprs[0] + if expr.Const != nil { + switch t.Sub[0].Main { + case shaderir.Bool: + if expr.Const.Kind() != gconstant.Bool { + cs.addError(e.Pos(), fmt.Sprintf("cannot %s to type bool", expr.Const.String())) + } + case shaderir.Int: + if !canTruncateToInteger(expr.Const) { + cs.addError(e.Pos(), fmt.Sprintf("constant %s truncated to integer", expr.Const.String())) + return nil, nil, nil, false + } + expr.Const = gconstant.ToInt(expr.Const) + case shaderir.Float: + if !canTruncateToFloat(expr.Const) { + cs.addError(e.Pos(), fmt.Sprintf("constant %s truncated to float", expr.Const.String())) + return nil, nil, nil, false + } + expr.Const = gconstant.ToFloat(expr.Const) + default: + cs.addError(e.Pos(), fmt.Sprintf("constant %s cannot be used for the array type %s", expr.Const.String(), t.String())) + return nil, nil, nil, false + } + } + stmts = append(stmts, ss...) stmts = append(stmts, shaderir.Stmt{ Type: shaderir.Assign, @@ -871,7 +897,7 @@ func (cs *compileState) parseExpr(block *block, fname string, expr ast.Expr, mar }, }, }, - exprs[0], + expr, }, }) } diff --git a/internal/shader/testdata/issue2840.expected.vs b/internal/shader/testdata/issue2840.expected.vs new file mode 100644 index 000000000..1b4e506ae --- /dev/null +++ b/internal/shader/testdata/issue2840.expected.vs @@ -0,0 +1,16 @@ +float[1] F0(void); +int[1] F1(void); + +float[1] F0(void) { + float l0[1]; + l0[0] = float(0); + (l0)[0] = 1.0; + return l0; +} + +int[1] F1(void) { + int l0[1]; + l0[0] = 0; + (l0)[0] = 1; + return l0; +} diff --git a/internal/shader/testdata/issue2840.go b/internal/shader/testdata/issue2840.go new file mode 100644 index 000000000..1dfe6e827 --- /dev/null +++ b/internal/shader/testdata/issue2840.go @@ -0,0 +1,9 @@ +package main + +func Floats() [1]float { + return [1]float{1} +} + +func Ints() [1]int { + return [1]int{1.0} +}