Backtestsvuerun-20261001-022054#15495

Issue #15495 Merged fix PR #15498 Run 30 Sep 2026 · run-20261001-022054 vuejs/core

[compiler-sfc] Top-level await inside switch case generates invalid code (missing semicolon before rewrite)

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The source changes are functionally identical. Both push `SwitchCase.consequent` onto the scope stack on enter and pop it on leave. That fixes the root cause the issue identifies: the `needsSemi` check only tracked `BlockStatement` bodies. Correctness is therefore equal, and so are scope and craft (A uses `else if` with braces, B uses a separate `if`; neither matters). The difference is in the tests. Patch A adds two snapshot tests through `assertAwaitDetection` plus a regex that checks for `;(` after the preceding call. The broken output `qux()(...)` is syntactically valid, so any parse check would not catch it, but the regex would. Patch A covers the single-await case in a switch, both top-level and nested in an `if`. Patch B goes further. It adds a runtime test that compiles the issue's exact reproduction, extended with two consecutive awaits in one case, and actually executes `setup()`. That test would throw the reported `TypeError` before the fix, so it directly guards the user-visible symptom. It also covers the 'consecutive awaits produce `(...)(...)`' variant that the issue explicitly lists. B's second test checks both directions: a semicolon is prepended after a prior statement and between consecutive awaits, and no semicolon is added when the await is the first statement of a case. Patch B's tests are more thorough and better tied to the reported behavior, so B wins.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

2m 51s10 turns

Wall-clock time in the container

Full test suite

No new failures

3,741 passed · 6 skipped · 3,747 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

50vs 76 merged

Changed lines, ours vs merged

[compiler-sfc] Top-level await inside switch case generates invalid code (missing semicolon before rewrite)

Vue version

3.5.42 — also reproduced on main (5409708)

Link to minimal reproduction

https://play.vuejs.org/#N4IgbgpgTgzglgewHYgFwgMwDoCsWAsATCADQgBmcANhDGqDFAMYD0AggA4dZgCuE9EE2QAXCEhFoQAHjEBbDlQCGYgHwAdJAAIt0gCZwwqqBA5QE0lgaObL8xSogaktmEyhwOIrTAgjeHM5wCghQ3sBaJuRaAL5a5OZyWgDkfBDJmprCSDDeSloAvJEQ5AAUIlD8AJRZyLlaAEaFxWUAjDUuSOS8SEwiiNoAjrwAHqVVWsCaOiwsxf5QOVo9eiVwSBB6WshaHLxQHAi+mjGZSEowAJ698T19A41KUOOT0-P72kQnZ3DRpUo8JRUaqvbQ+ADucBETAAFlpSg1AcCIBMpmCdEwLhAtK1UG8dDphmMOgSCUpwUooY9niTYt8kJY3B4vM5SCA4DA2PdIGgKvwYmRGKw5JSkFgRHRUKBsmIJFJgocwpMtO4II5OBxYvFEik0hkkArQt4NdqEElklh2FwePx9VkTOquKUNVUsHIED0RKVkgBiJRcZIdNkcrn9HmoPkQGICkAILwDSXAaNAA

Steps to reproduce

  1. Open the playground link above (or compile the SFC below with @vue/compiler-sfc).
  2. The component setup() throws TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)).

SFC:

<script setup>
const a = true
const b = 1
function qux() {}
async function bar() { return 42 }
if (a) {
  switch (b) {
    case 1:
      qux()
      await bar()
  }
}
</script>

What is expected?

The compiled setup() should run fine: qux() and await bar() should be two independent statements.

What is actually happening?

The top-level await rewrite in compileScript emits the withAsyncContext wrapper expression without a leading semicolon when the await is inside a switch case that is not the first statement:

async setup(__props, { expose: __expose }) {
  ...
  if (a) {
    switch (b) {
      case 1:
        qux()
        (
  ([__temp,__restore] = _withAsyncContext(() => bar())),
  await __temp,
  __restore()
)
    }
  }
}

Because the next line starts with (, ASI does not insert a semicolon, so the two lines are parsed as a single call expression qux()(...). bar() is never awaited in the intended way and the runtime throws TypeError: object is not iterable.

The same code inside a plain block (not a switch) is compiled correctly with a leading ;:

if (a) {
  qux()
  ;(
  ([__temp,__restore] = _withAsyncContext(() => bar())),
  await __temp,
  __restore()
)
}

Additional comments

Root cause: in packages/compiler-sfc/src/compileScript.ts, the scope stack used to decide whether the rewrite needs a semicolon only pushes/pops on BlockStatement. A switch statement's SwitchCase.consequent statement list is not tracked, so needsSemi is misjudged as false for await expressions inside case branches (unless the await happens to be the very first statement of the case).

Related variants also affected:

  • Two consecutive top-level awaits inside one case produce (...)(...) back-to-back (second one also parsed as a call of the first result).
  • Any await that follows an expression statement inside a case branch.

No prior issue found for this.

The two patches

Our patch+49 −1
packages/compiler-sfc/__tests__/compileScript.spec.tsindex a1cc885cd..785fcbc06 100644@@ -1045,6 +1045,50 @@ describe('SFC compile <script setup>', () => {       )((getAwaitable: () => unknown) => [getAwaitable(), () => {}])       await expect(component.setup({}, { expose() {} })).resolves.toEqual({})     })++    test('await statements in switch case should be separated', async () => {+      const { content } = compile(+        `<script setup>+        const a = true+        const b = 1+        function qux() {}+        async function bar() { return 42 }+        if (a) {+          switch (b) {+            case 1:+              qux()+              await bar()+              await bar()+          }+        }+        </script>`,+        { genDefaultAs: '_sfc_' },+      )+      const component = new Function(+        '_withAsyncContext',+        `${content.replace(/^import .*\n/, '')};return _sfc_`,+      )((getAwaitable: () => unknown) => [getAwaitable(), () => {}])+      const setupResult = await component.setup({}, { expose() {} })+      expect(Object.keys(setupResult)).toEqual(['a', 'b', 'qux', 'bar'])+    })++    test('switch case statements', () => {+      // should prepend semicolon to awaits following other statements+      const { content: code } = compile(+        `<script setup>switch (b) { case 1: foo()\nawait 1\nawait 2 }</script>`,+      )+      expect(code).toMatch(`let __temp, __restore`)+      expect(code).toMatch(`async setup(`)+      expect(code).toMatch(`foo()\n;(`)+      expect(code).toMatch(`__restore()\n)\n;(`)+      // should NOT prepend semicolon to the first statement of a case+      const { content: code2 } = compile(+        `<script setup>switch (b) { case 1: await 1\nawait 2 }</script>`,+      )+      expect(code2).toMatch(`case 1: (`)+      expect(code2).not.toMatch(`case 1: ;(`)+      expect(code2).toMatch(`__restore()\n)\n;(`)+    })   })    describe('errors', () => {packages/compiler-sfc/src/compileScript.tsindex 901196235..cf7f2f658 100644@@ -647,6 +647,9 @@ export function compileScript(           if (child.type === 'BlockStatement') {             scope.push(child.body)           }+          if (child.type === 'SwitchCase') {+            scope.push(child.consequent)+          }           if (child.type === 'AwaitExpression') {             hasAwait = true             // if the await expression is an expression statement and@@ -670,7 +673,8 @@ export function compileScript(           }         },         leave(node: Node) {-          if (node.type === 'BlockStatement') scope.pop()+          if (node.type === 'BlockStatement' || node.type === 'SwitchCase')+            scope.pop()         },       })     } 
Merged fix · PR #15498+75 −1
packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snapindex 795f0ae88..c718e7690 100644@@ -206,6 +206,54 @@ return { n, get x() { return x } } })" `; +exports[`SFC compile <script setup> > async/await detection > await in switch case 1`] = `+"import { withAsyncContext as _withAsyncContext } from 'vue'++export default {+  async setup(__props, { expose: __expose }) {+  __expose();++let __temp, __restore+switch (a) {+        case 1:+          foo()+          ;(+  ([__temp,__restore] = _withAsyncContext(() => bar())),+  await __temp,+  __restore()+)+      }+return {  }+}++}"+`;++exports[`SFC compile <script setup> > async/await detection > await in switch case nested in a block 1`] = `+"import { withAsyncContext as _withAsyncContext } from 'vue'++export default {+  async setup(__props, { expose: __expose }) {+  __expose();++let __temp, __restore+if (a) {+        switch (b) {+          case 1:+            qux()+            ;(+  ([__temp,__restore] = _withAsyncContext(() => bar())),+  await __temp,+  __restore()+)+        }+      }+return {  }+}++}"+`;+ exports[`SFC compile <script setup> > async/await detection > expression statement 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' packages/compiler-sfc/__tests__/compileScript.spec.tsindex a1cc885cd..caaae92b4 100644@@ -960,6 +960,28 @@ describe('SFC compile <script setup>', () => {       assertAwaitDetection(`if (ok) { await foo } else { await bar }`)     }) +    // #15495+    test('await in switch case', () => {+      const code = assertAwaitDetection(`switch (a) {+        case 1:+          foo()+          await bar()+      }`)+      expect(code).toMatch(/foo\(\)\s*;\(/)+    })++    // #15495+    test('await in switch case nested in a block', () => {+      const code = assertAwaitDetection(`if (a) {+        switch (b) {+          case 1:+            qux()+            await bar()+        }+      }`)+      expect(code).toMatch(/qux\(\)\s*;\(/)+    })+     test('multiple `if` nested statements', () => {       assertAwaitDetection(`if (ok) {         let a = 'foo'packages/compiler-sfc/src/compileScript.tsindex 901196235..3c070a0e0 100644@@ -646,6 +646,8 @@ export function compileScript(           }           if (child.type === 'BlockStatement') {             scope.push(child.body)+          } else if (child.type === 'SwitchCase') {+            scope.push(child.consequent)           }           if (child.type === 'AwaitExpression') {             hasAwait = true@@ -670,7 +672,9 @@ export function compileScript(           }         },         leave(node: Node) {-          if (node.type === 'BlockStatement') scope.pop()+          if (node.type === 'BlockStatement' || node.type === 'SwitchCase') {+            scope.pop()+          }         },       })     } 

What the agent reported

A top-level await inside a switch case now gets its leading ;, so qux() and await bar() compile as two separate statements. Two new tests failed before the change and pass after it, and the whole packages/compiler-sfc suite passes. The changes are left uncommitted.

What was wrong: In packages/compiler-sfc/src/compileScript.ts, the code that rewrites top-level awaits decides whether to add a ; by tracking a stack of statement lists. It only added a list when it entered a BlockStatement (a { ... } block). The statements under a case label are a separate list that never got added. So an await inside a case was checked against the enclosing block's list, nothing matched, and no ; was added. The result was qux()\n(...), which JavaScript reads as calling the result of qux(), plus (...)(...) for two awaits in a row.

The change (compileScript.ts, about 6 lines): when the walk enters a case (or default), its statement list is added to the stack, and removed when it leaves, just like a block. The existing rule then applies unchanged: the first statement in a case gets no ;, later ones do.

Tests added (packages/compiler-sfc/__tests__/compileScript.spec.ts, after the #15465 test):

  • await statements in switch case should be separated: compiles the exact SFC from the report, with a second await bar() added, then runs the generated setup() and checks it returns the bindings a, b, qux, bar.
  • Before the fix it threw TypeError: qux(...) is not a function, not the reported "object is not iterable". The cause is the same mis-parse; the message differs only because qux returns undefined here.
  • switch case statements: checks the generated text.
  • foo()\n;( is present.
  • Consecutive awaits are separated (__restore()\n)\n;().
  • An await that is the first statement of a case is not given a ; (case 1: ( is present, case 1: ;( is absent).
  • It checks the output with plain string matches instead of the usual helper, because that helper uses snapshots and ./bt-test doesn't write new ones.

Results:

  • Before the fix: the two new tests failed and the other 90 in compileScript.spec.ts passed.
  • After the fix: all 19 test files in packages/compiler-sfc passed (474 passed, 1 skipped). No existing tests or snapshots were changed.
  • Review: a reviewer found the fix minimal and correct. They traced through these cases and found them handled correctly, but the tests don't cover them:
  • a case x: { ... } body in braces
  • default:
  • case await x:
  • switch (await x)

Requirements from the report:

  1. Reported scenario (qux() then await bar() in a case runs without error): fixed; covered by the runtime test.
  2. Two consecutive awaits in one case: fixed; covered by both tests (__restore()\n)\n;( and the runtime run with two await bar()).
  3. Any await after an expression statement in a case: fixed; covered by the foo()\n;( check.
  4. An await as the first statement of a case stays correct: kept as before; covered by the case 1: ( and not case 1: ;( checks.
  5. Root cause (SwitchCase bodies not tracked): addressed directly in compileScript.ts.