compiler: compare slice against nil

This commit is contained in:
Ayke van Laethem
2018-10-20 17:22:51 +02:00
parent 3f05490846
commit da89464a63
3 changed files with 17 additions and 0 deletions
+13
View File
@@ -2863,6 +2863,19 @@ func (c *Compiler) parseBinOp(frame *Frame, binop *ssa.BinOp) (llvm.Value, error
default:
return llvm.Value{}, errors.New("todo: binop on pointer: " + binop.Op.String())
}
case *types.Slice:
// Slices are in general not comparable, but can be compared against
// nil. Assume at least one of them is nil to make the code easier.
xPtr := c.builder.CreateExtractValue(x, 0, "")
yPtr := c.builder.CreateExtractValue(y, 0, "")
switch binop.Op {
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, xPtr, yPtr, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, xPtr, yPtr, ""), nil
default:
return llvm.Value{}, errors.New("todo: binop on slice: " + binop.Op.String())
}
default:
return llvm.Value{}, errors.New("unknown binop type: " + binop.X.Type().String())
}
+2
View File
@@ -4,6 +4,7 @@ func main() {
l := 5
foo := []int{1, 2, 4, 5}
bar := make([]int, l-2, l)
println("foo is nil?", foo == nil, nil == foo)
printslice("foo", foo)
printslice("bar", bar)
printslice("foo[1:2]", foo[1:2])
@@ -15,6 +16,7 @@ func main() {
// append
var grow []int
println("slice is nil?", grow == nil, nil == grow)
printslice("grow", grow)
grow = append(grow, 42)
printslice("grow", grow)
+2
View File
@@ -1,9 +1,11 @@
foo is nil? false false
foo: len=4 cap=4 data: 1 2 4 5
bar: len=3 cap=5 data: 0 0 0
foo[1:2]: len=1 cap=3 data: 2
sum foo: 12
copy foo -> bar: 3
bar: len=3 cap=5 data: 1 2 4
slice is nil? true true
grow: len=0 cap=0 data:
grow: len=1 cap=1 data: 42
grow: len=3 cap=4 data: 42 -1 -2