Skip to content

v3: for x in a[b.len..] evaluates the slice again on every iteration, so a body that changes b.len skips elements #32309

Open

Description

@MARCROCK22

Describe the bug

With the default (V3) compiler, in for x in a[b.len..] the slice is not taken once before the loop: the generated C evaluates array_slice(a, b.len, a.len) again in the loop condition and in the element access of every iteration. When the body changes what the start expression reads (here, it appends to b), the loop skips elements of a.

With a start held in a variable (start := b.len then a[start..]), and with -old-compiler, the loop sees every element. A start that is a function call (a[start()..]) is also evaluated once.

Reproduction Steps

fn main() {
	a := [1, 2, 3]
	mut b := []int{}
	for x in a[b.len..] {
		b << x
	}
	println(b)
	mut c := []int{}
	start := c.len
	for x in a[start..] {
		c << x
	}
	println(c)
}

V_C_ERROR_BUG_REPORT_DISABLED=1 V_MACOS_V3_NO_FALLBACK=1 v run main.v

Expected Behavior

[1, 2, 3]
[1, 2, 3]

as with v -old-compiler run main.v: the range of a for … in is evaluated once, before the first iteration.

Current Behavior

[1, 3]
[1, 2, 3]

The generated C for the first loop:

for (; __for_idx_0 < (array_slice(a, b.len, (a).len)).len; __for_idx_0++) {
	i64 x = *(i64*)(array_get(array_slice(a, b.len, (a).len), __for_idx_0));

After the first iteration b.len is 1, so the slice is [2, 3] and index 1 reads 3; after the second, the slice [3] has length 1 and the loop ends.

Possible Solution

Hoist the sliced array into a temporary before the loop, as is already done when the start is a call.

Additional Information/Context

Found in a linter written in V, where a loop that merged option arrays this way (for option in options[merged.len..] { merged << option }) lost every other option. Taking the slice into a variable first works around it.

V version

V 0.5.2 ba41fa1 (master, 2026-11-13); also 8415951.

Environment details (OS name and version, etc.)

Linux x86_64 (Ubuntu, kernel 6.8), gcc.

Note

You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions