feat: allow Range objects as list subscript operator arguments

Extend the list subscript operator to accept Range arguments in addition to plain numbers. When a Range is provided, the operator returns a new list containing the elements within that range, supporting inclusive (..) and exclusive (...) bounds, negative indices that count from the end, and automatic reversal for backwards ranges. Added validation functions for integer values and range bounds, with dedicated error messages for non-integer range endpoints and out-of-bounds conditions. Updated the test suite with comprehensive range subscript tests and removed the old test that only checked for non-numeric subscripts.
This commit is contained in:
Bob Nystrom
2014-01-30 17:12:44 +00:00
parent 1464007327
commit 1607b6d2dd
13 changed files with 133 additions and 28 deletions
-2
View File
@@ -1,2 +0,0 @@
var a = [1, 2, 3]
a["2"] // expect runtime error: Subscript must be a number.
+31
View File
@@ -0,0 +1,31 @@
// Returns lists.
var list = ["a", "b", "c", "d", "e"]
IO.print(list[0..0]) // expect: [a]
IO.print(list[1...1]) // expect: []
IO.print(list[1..2]) // expect: [b, c]
IO.print(list[1...2]) // expect: [b]
IO.print(list[2..4]) // expect: [c, d, e]
IO.print(list[2...5]) // expect: [c, d, e]
// A backwards range reverses.
IO.print(list[3..1]) // expect: [d, c, b]
IO.print(list[3...1]) // expect: [d, c]
IO.print(list[3...3]) // expect: []
// Negative ranges index from the end.
IO.print(list[-5..-2]) // expect: [a, b, c, d]
IO.print(list[-5...-2]) // expect: [a, b, c]
IO.print(list[-3..-5]) // expect: [c, b, a]
IO.print(list[-3...-6]) // expect: [c, b, a]
// Half-negative ranges are treated like the negative value is fixed before
// walking the range.
IO.print(list[-5..3]) // expect: [a, b, c, d]
IO.print(list[-3...5]) // expect: [c, d, e]
IO.print(list[-2..1]) // expect: [d, c, b]
IO.print(list[-2...0]) // expect: [d, c, b]
IO.print(list[1..-2]) // expect: [b, c, d]
IO.print(list[2...-1]) // expect: [c, d]
IO.print(list[4..-5]) // expect: [e, d, c, b, a]
IO.print(list[3...-6]) // expect: [d, c, b, a]
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[1.5..2] // expect runtime error: Range start must be an integer.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[3..2] // expect runtime error: Range start out of bounds.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[-4..2] // expect runtime error: Range start out of bounds.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[1...4] // expect runtime error: Range end out of bounds.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[0...-5] // expect runtime error: Range end out of bounds.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[1..2.5] // expect runtime error: Range end must be an integer.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[1..3] // expect runtime error: Range end out of bounds.
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a[0..-4] // expect runtime error: Range end out of bounds.
+2
View File
@@ -0,0 +1,2 @@
var a = [1, 2, 3]
a["2"] // expect runtime error: Subscript must be a number or a range.