Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions examples/negative-indices.ilo
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
-- Negative indices on slice-shaped builtins count from the end of the
-- list or text, matching Python semantics already in place for `at xs i`.
--
-- slc xs s e accepts negative s and e. `slc xs -1 (len xs)` is the
-- last element as a 1-element list; `slc xs 0 -1` drops
-- the last element; bounds clamp, never wrap.
-- take n xs with n<0 keeps all but the last |n|. Equivalent to
-- Python's xs[:n]. `take -1 [10,20,30]` is [10,20].
-- drop n xs with n<0 keeps only the last |n|. Equivalent to
-- Python's xs[n:]. `drop -1 [10,20,30]` is [30].
--
-- Closes the quant-trader fencepost (`@i 1..np` loops produce np-1 results,
-- so the equity curve ends at length np; `at eq np` errored, and the
-- workaround was `npm=- np 1`). With negative indices everywhere, the same
-- pattern is `slc eq 0 -1` — no separate binding, no off-by-one risk.

last-element xs:L n>L n;slc xs -1 (len xs)
drop-last xs:L n>L n;slc xs 0 -1
keep-last-two xs:L n>L n;slc xs -2 (len xs)
all-but-last xs:L n>L n;take -1 xs
only-last-two xs:L n>L n;drop -2 xs
trim-edges s:t>t;slc s 1 -1

-- run: last-element [10,20,30,40,50]
-- out: [50]
-- run: drop-last [10,20,30,40,50]
-- out: [10, 20, 30, 40]
-- run: keep-last-two [10,20,30,40,50]
-- out: [40, 50]
-- run: all-but-last [10,20,30,40,50]
-- out: [10, 20, 30, 40]
-- run: only-last-two [10,20,30,40,50]
-- out: [40, 50]
-- run: trim-edges "(quoted)"
-- out: quoted
128 changes: 128 additions & 0 deletions src/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,57 @@ pub(crate) fn char_at_signed(s: &str, raw_idx: i64) -> CharAtResult {
}
}

/// Resolve a Python-style signed slice bound against `len`.
///
/// - `raw >= 0`: clamp to `[0, len]`.
/// - `raw < 0`: treat as `len + raw`, then clamp to `[0, len]`. So `-1` on a
/// length-5 list becomes index `4` (the last element); `-5` becomes `0`;
/// `-99` clamps to `0`.
///
/// Returned index is always in `[0, len]`, so callers can use it directly
/// as a slice bound without further checks. Matches the semantics already
/// applied to `at`'s negative index handling (`adjusted = if i < 0 { i + len }
/// else { i }`) — see `Builtin::At` in the tree-walker and `OP_AT` in the VM.
#[inline]
pub(crate) fn resolve_slice_bound(raw: i64, len: usize) -> usize {
let len_i = len as i64;
let adjusted = if raw < 0 { raw + len_i } else { raw };
adjusted.clamp(0, len_i) as usize
}

/// Resolve `take n xs` against `len`, returning the prefix length to retain.
///
/// - `n >= 0`: take the first `min(n, len)` elements.
/// - `n < 0`: take all but the last `|n|`. Equivalent to Python's `xs[:n]`.
/// `take -1 [1,2,3]` returns `[1,2]`; `take -len xs` returns `[]`; `n` more
/// negative than `-len` clamps to `0` (empty).
#[inline]
pub(crate) fn resolve_take_count(n: i64, len: usize) -> usize {
if n >= 0 {
(n as usize).min(len)
} else {
let adjusted = (len as i64) + n;
adjusted.max(0) as usize
}
}

/// Resolve `drop n xs` against `len`, returning the prefix length to skip.
///
/// - `n >= 0`: skip the first `min(n, len)` elements.
/// - `n < 0`: keep only the last `|n|`, i.e. skip the leading `len - |n|`.
/// Equivalent to Python's `xs[n:]`. `drop -1 [1,2,3]` returns `[3]`;
/// `drop -len xs` returns the full list; `n` more negative than `-len`
/// clamps to `0` (returns the full list).
#[inline]
pub(crate) fn resolve_drop_count(n: i64, len: usize) -> usize {
if n >= 0 {
(n as usize).min(len)
} else {
let adjusted = (len as i64) + n;
adjusted.max(0) as usize
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -684,6 +735,83 @@ mod tests {
assert_eq!(Builtin::from_name(""), None);
}

#[test]
fn resolve_slice_bound_positive_and_clamps() {
// Within range: returned as-is.
assert_eq!(resolve_slice_bound(0, 5), 0);
assert_eq!(resolve_slice_bound(3, 5), 3);
assert_eq!(resolve_slice_bound(5, 5), 5);
// Past len: clamps up to len (matches existing slc behaviour).
assert_eq!(resolve_slice_bound(99, 5), 5);
}

#[test]
fn resolve_slice_bound_negative_python_style() {
// -1 is the last index; -len is 0; beyond -len clamps to 0.
assert_eq!(resolve_slice_bound(-1, 5), 4);
assert_eq!(resolve_slice_bound(-5, 5), 0);
assert_eq!(resolve_slice_bound(-99, 5), 0);
}

#[test]
fn resolve_slice_bound_empty_list() {
// len=0 makes every bound clamp to 0 — slc of an empty list always
// returns empty, never errors. The fencepost-trap case in the
// quant-trader run.
assert_eq!(resolve_slice_bound(0, 0), 0);
assert_eq!(resolve_slice_bound(-1, 0), 0);
assert_eq!(resolve_slice_bound(99, 0), 0);
}

#[test]
fn resolve_take_count_positive() {
assert_eq!(resolve_take_count(0, 5), 0);
assert_eq!(resolve_take_count(3, 5), 3);
assert_eq!(resolve_take_count(5, 5), 5);
assert_eq!(resolve_take_count(99, 5), 5);
}

#[test]
fn resolve_take_count_negative_drops_tail() {
// `take -k xs` == `xs[:-k]` — keep all but the last |k|.
assert_eq!(resolve_take_count(-1, 5), 4);
assert_eq!(resolve_take_count(-4, 5), 1);
assert_eq!(resolve_take_count(-5, 5), 0);
// Beyond -len clamps to 0 (empty), matching Python's `xs[:-99]`.
assert_eq!(resolve_take_count(-99, 5), 0);
}

#[test]
fn resolve_drop_count_positive() {
assert_eq!(resolve_drop_count(0, 5), 0);
assert_eq!(resolve_drop_count(3, 5), 3);
assert_eq!(resolve_drop_count(5, 5), 5);
assert_eq!(resolve_drop_count(99, 5), 5);
}

#[test]
fn resolve_drop_count_negative_keeps_tail() {
// `drop -k xs` == `xs[-k:]` — discard all but the last |k|.
// Returned value is the *prefix length to skip*.
assert_eq!(resolve_drop_count(-1, 5), 4); // skip 4, keep last 1
assert_eq!(resolve_drop_count(-4, 5), 1); // skip 1, keep last 4
assert_eq!(resolve_drop_count(-5, 5), 0); // skip 0, keep all
// Beyond -len clamps to 0 (keep everything), matching Python `xs[-99:]`.
assert_eq!(resolve_drop_count(-99, 5), 0);
}

#[test]
fn resolve_take_drop_empty_list() {
// Every count against len=0 must clamp to 0 — take/drop of empty
// never errors, irrespective of sign.
assert_eq!(resolve_take_count(0, 0), 0);
assert_eq!(resolve_take_count(-3, 0), 0);
assert_eq!(resolve_take_count(3, 0), 0);
assert_eq!(resolve_drop_count(0, 0), 0);
assert_eq!(resolve_drop_count(-3, 0), 0);
assert_eq!(resolve_drop_count(3, 0), 0);
}

#[test]
fn tag_round_trips_for_every_builtin() {
// Anchor for the OP_CALL_BUILTIN_TREE bridge: every builtin must
Expand Down
65 changes: 39 additions & 26 deletions src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1726,17 +1726,36 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
};
}
if builtin == Some(Builtin::Slc) && args.len() == 3 {
let start = match &args[1] {
Value::Number(n) => *n as usize,
// Both bounds accept negative integers Python-style:
// `slc xs -1 0` is empty, `slc xs 0 -1` drops the last element,
// `slc xs -2 (len xs)` returns the last two elements.
let start_raw = match &args[1] {
Value::Number(n) => {
if n.fract() != 0.0 {
return Err(RuntimeError::new(
"ILO-R009",
"slc: start index must be an integer".to_string(),
));
}
*n as i64
}
other => {
return Err(RuntimeError::new(
"ILO-R009",
format!("slc: start index must be a number, got {:?}", other),
));
}
};
let end = match &args[2] {
Value::Number(n) => *n as usize,
let end_raw = match &args[2] {
Value::Number(n) => {
if n.fract() != 0.0 {
return Err(RuntimeError::new(
"ILO-R009",
"slc: end index must be an integer".to_string(),
));
}
*n as i64
}
other => {
return Err(RuntimeError::new(
"ILO-R009",
Expand All @@ -1746,14 +1765,16 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
};
return match &args[0] {
Value::List(items) => {
let end = end.min(items.len());
let start = start.min(end);
let len = items.len();
let end = crate::builtins::resolve_slice_bound(end_raw, len);
let start = crate::builtins::resolve_slice_bound(start_raw, len).min(end);
Ok(Value::List(items[start..end].to_vec()))
}
Value::Text(s) => {
let chars: Vec<char> = s.chars().collect();
let end = end.min(chars.len());
let start = start.min(end);
let len = chars.len();
let end = crate::builtins::resolve_slice_bound(end_raw, len);
let start = crate::builtins::resolve_slice_bound(start_raw, len).min(end);
Ok(Value::Text(chars[start..end].iter().collect()))
}
other => Err(RuntimeError::new(
Expand All @@ -1763,6 +1784,8 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
};
}
if builtin == Some(Builtin::Take) && args.len() == 2 {
// Negative `n` means "all but the last |n|" (Python `xs[:n]`):
// `take -1 [1,2,3]` returns `[1,2]`.
let n = match &args[0] {
Value::Number(n) => {
if n.fract() != 0.0 {
Expand All @@ -1771,13 +1794,7 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
"take: count must be an integer".to_string(),
));
}
if *n < 0.0 {
return Err(RuntimeError::new(
"ILO-R009",
"take: count must be a non-negative integer".to_string(),
));
}
*n as usize
*n as i64
}
other => {
return Err(RuntimeError::new(
Expand All @@ -1788,12 +1805,12 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
};
return match &args[1] {
Value::List(items) => {
let end = n.min(items.len());
let end = crate::builtins::resolve_take_count(n, items.len());
Ok(Value::List(items[..end].to_vec()))
}
Value::Text(s) => {
let chars: Vec<char> = s.chars().collect();
let end = n.min(chars.len());
let end = crate::builtins::resolve_take_count(n, chars.len());
Ok(Value::Text(chars[..end].iter().collect()))
}
other => Err(RuntimeError::new(
Expand All @@ -1803,6 +1820,8 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
};
}
if builtin == Some(Builtin::Drop) && args.len() == 2 {
// Negative `n` means "keep only the last |n|" (Python `xs[n:]`):
// `drop -1 [1,2,3]` returns `[3]`.
let n = match &args[0] {
Value::Number(n) => {
if n.fract() != 0.0 {
Expand All @@ -1811,13 +1830,7 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
"drop: count must be an integer".to_string(),
));
}
if *n < 0.0 {
return Err(RuntimeError::new(
"ILO-R009",
"drop: count must be a non-negative integer".to_string(),
));
}
*n as usize
*n as i64
}
other => {
return Err(RuntimeError::new(
Expand All @@ -1828,12 +1841,12 @@ fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
};
return match &args[1] {
Value::List(items) => {
let start = n.min(items.len());
let start = crate::builtins::resolve_drop_count(n, items.len());
Ok(Value::List(items[start..].to_vec()))
}
Value::Text(s) => {
let chars: Vec<char> = s.chars().collect();
let start = n.min(chars.len());
let start = crate::builtins::resolve_drop_count(n, chars.len());
Ok(Value::Text(chars[start..].iter().collect()))
}
other => Err(RuntimeError::new(
Expand Down
Loading
Loading