Skip to content

Inlining a function twice in JavaScript drops a variable declaration #9542

In progress

Description

@cknitt

This compiles without error, but the JavaScript throws ReferenceError: k is not defined when it runs:

let main = z => {
  let c = (k, y) => {
    Console.log2("c", y)
    Console.log2("c", y + 1)
    Console.log2("c", y + 2)
    k(y)
  }
  let rec a = n => {
    Console.log2("a", n)
    Console.log2("a", n + 1)
    Console.log2("a", n + 2)
    n > 10 ? b(n) : 0
  }
  and b = n => {
    Console.log2("b", n)
    Console.log2("b", n + 1)
    Console.log2("b", n + 2)
    n > 100 ? a(n - 100) : c(x => x + n, n)
  }
  a(z) + a(z + 1)
}
Console.log(main(20))

The generated a contains:

      } else {
        (x => x + n | 0);
        console.log("c", n);
        console.log("c", n + 1 | 0);
        console.log("c", n + 2 | 0);
        return k(n);
      }

The declaration let k = x => x + n | 0 has become a bare expression, so return k(n) reads an unbound variable. It should print 82.

Cause

The bug is in Js_pass_tailcall_inline, which copies the body of a local function into its single call site when that call is a return f(…). Inlining c into b turns c's parameter k into let k = <function> in b's body. Then b is inlined into a in the same way, and that body is processed a second time. A case for a function declaration at the head of a block looks the variable up in a table of declarations collected before the pass. k didn't exist then, so the case treats the declaration as unused and keeps only its value.

Since when

This is not a regression. It has been in every release since January 2016:

  • The case was already in the first BuckleScript commit (78ffcbd, 2016-01-06, jscomp/js_inline_and_eliminate.ml). There, the table counted uses, so a variable missing from it really was unused.
  • ddd8b4c (2016-01-19) made the table one of declarations, and added the inlining of a returned call, which processes a body a second time. Since then, a missing entry no longer means that the variable is unused.

The shape is rare: the functions must be too big to be inlined earlier, and each must be called once, in a return.

Found by Claude while reviewing optimizer cleanups.

Activity

  1. added theissue type on Dec 5, 2026
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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions