Skip to content

A for loop reads its upper bound from a local ref on every iteration #9356

Open

Description

@mununki

A for loop evaluates its upper bound once, before the first iteration. When the bound is read from a local ref that the body assigns, the generated JS reads it again on every iteration.

let g = ref(3)

let global = () => {
  let n = ref(0)
  g := 3
  for _ in 0 to g.contents {
    n := n.contents + 1
    g := g.contents - 1
  }
  n.contents
}

let local = () => {
  let n = ref(0)
  let r = ref(3)
  for _ in 0 to r.contents {
    n := n.contents + 1
    r := r.contents - 1
  }
  n.contents
}

Console.log2(global(), local())

Output, on master and on 12.3.1:

// global
for (let _for = 0, _for_finish = g.contents; _for <= _for_finish; ++_for) {

// local
for (let _for = 0; _for <= r; ++_for) {

This prints 4 2. It should print 4 4.

The local ref becomes the variable r, and the loop reads it as its bound without a _finish copy, although the body assigns it.

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