Skip to content

NimVM reuses default-value sequences, differing from Nim and from NimVM with explicit defaults #20985

Closed
@jrfondren

Description

@jrfondren

Description

The following program with identical code blocks (but for let v. const) results in a != b. This isn't the case when the group and groups variables are explicitly initialized to @[].

let a = block:
  var groups: seq[seq[int]]
  for i in 0 ..< 3:
    var group: seq[int]
    for j in 0 ..< 3:
      group.add j
    groups.add group
  groups

const b = block:
  var groups: seq[seq[int]]
  for i in 0 ..< 3:
    var group: seq[int]
    for j in 0 ..< 3:
      group.add j
    groups.add group
  groups

echo a
echo b

Nim Version

Nim Compiler Version 1.6.10 [Linux: amd64]

and:

Nim Compiler Version 1.7.3 [Linux: amd64]
Compiled at 2022-12-01
Copyright (c) 2006-2022 by Andreas Rumpf

git hash: b36f511

Current Output

@[@[0, 1, 2], @[0, 1, 2], @[0, 1, 2]]
@[@[0, 1, 2], @[0, 1, 2, 0, 1, 2], @[0, 1, 2, 0, 1, 2, 0, 1, 2]]

Expected Output

@[@[0, 1, 2], @[0, 1, 2], @[0, 1, 2]]
@[@[0, 1, 2], @[0, 1, 2], @[0, 1, 2]]

Possible Solution

No response

Additional Information

Workaround: don't trust https://nim-lang.org/docs/manual.html#statements-and-expressions-var-statement in const blocks:

let a = block:
  var groups: seq[seq[int]] = @[]
  for i in 0 ..< 3:
    var group: seq[int] = @[]
    for j in 0 ..< 3:
      group.add j
    groups.add group
  groups

const b = block:
  var groups: seq[seq[int]] = @[]
  for i in 0 ..< 3:
    var group: seq[int] = @[]
    for j in 0 ..< 3:
      group.add j
    groups.add group
  groups

echo a
echo b

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