From 178bd780550d27ef6f0c6640ceafa4cc74f43c16 Mon Sep 17 00:00:00 2001 From: Mine Starks <16928427+minestarks@users.noreply.github.com> Date: Tue, 26 Nov 2024 07:58:14 -0800 Subject: [PATCH] VS Code extension throws on launch if Q# notebook cell is open (#2044) **Repro** 1. Create a notebook like so - with one cell with language set to "Q#" but no `%%qsharp` magic ![image](https://github.com/user-attachments/assets/944aca1e-96f2-4660-9ada-30e6d9e50b66) 2. Save this notebook, and launch VS Code with only this notebook open Exception: ``` 2024-11-25 12:23:42.755 [error] ReferenceError: Cannot access 'defaultLanguageId' before initialization at updateQSharpCellLanguages (http://localhost:3000/static/devextensions/out/extension.js#vscode-extension:40620:57) at eval (http://localhost:3000/static/devextensions/out/extension.js#vscode-extension:40577:7) at Array.forEach () at registerQSharpNotebookHandlers (http://localhost:3000/static/devextensions/out/extension.js#vscode-extension:40575:40) at activate (http://localhost:3000/static/devextensions/out/extension.js#vscode-extension:40979:33) at async F1.n (http://localhost:3000/static/build/out/vs/workbench/api/worker/extensionHostWorkerMain.js:113:4450) at async F1.m (http://localhost:3000/static/build/out/vs/workbench/api/worker/extensionHostWorkerMain.js:113:4413) at async F1.l (http://localhost:3000/static/build/out/vs/workbench/api/worker/extensionHostWorkerMain.js:113:3869) ``` -------- The bug comes down to this sort of pattern causing an exception in JavaScript: ```js foo(); // ReferenceError: Cannot access 'x' before initialization let x = 1; function foo() { x } ``` Fix is to declare `defaultLanguageId` at the global scope so that initialization is guaranteed before the function that closes over it is ever called. --- vscode/src/notebook.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vscode/src/notebook.ts b/vscode/src/notebook.ts index 065bddf1ea..2d370b0be9 100644 --- a/vscode/src/notebook.ts +++ b/vscode/src/notebook.ts @@ -11,6 +11,7 @@ import { notebookTemplate } from "./notebookTemplate.js"; const qsharpCellMagic = "%%qsharp"; const jupyterNotebookType = "jupyter-notebook"; const qsharpConfigMimeType = "application/x.qsharp-config"; +let defaultLanguageId: string | undefined; /** * Sets up handlers to detect Q# code cells in Jupyter notebooks and set the language to Q#. @@ -53,8 +54,6 @@ export function registerQSharpNotebookHandlers() { }), ); - let defaultLanguageId: string | undefined; - function updateQSharpCellLanguages(cells: vscode.NotebookCell[]) { for (const cell of cells) { // If this is a code cell that starts with %%qsharp, and language wasn't already set to Q#, set it.