Skip to content

Commit

Permalink
REPL: introduce a new jupyter notebook based REPL
Browse files Browse the repository at this point in the history
VSCode has introduced a native jupyter notebook API. Wire up a "kernel"
for Swift to provide a native REPL experience within VSCode. This is
primarily a PoC implementation that demonstrates how such an
implementation could work.

The primary limitation in the current implementation is the IO
processing in the LLDB REPL. We can apply a heuristic to capture the
error message (termination on an empty string), but do not have such a
heuristic for the output and currently only capture the first line of
the output, leaving the remaining output in the buffer. Improving the
stream handling would significantly improve the experience.

Co-authored-by: Jeremy Day <[email protected]>
  • Loading branch information
compnerd and z2oh committed Aug 19, 2024
1 parent d801d41 commit 9a0b6b7
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 2 deletions.
10 changes: 9 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@
"no-throw-literal": "warn",
"semi": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/semi": "error"
"@typescript-eslint/semi": "error",
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
]
},
"extends": [
"eslint:recommended",
Expand Down
21 changes: 20 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,11 @@
"command": "swift.runTestsUntilFailure",
"title": "Run Until Failure...",
"category": "Swift"
},
{
"command": "swift.evaluate",
"title": "Evaluate in REPL",
"category": "Swift"
}
],
"configuration": [
Expand Down Expand Up @@ -358,6 +363,15 @@
"default": true,
"markdownDescription": "Controls whether or not the extension will contribute environment variables defined in `Swift: Environment Variables` to the integrated terminal. If this is set to `true` and a custom `Swift: Path` is also set then the swift path is appended to the terminal's `PATH`.",
"order": 15
},
"swift.repl": {
"type": "boolean",
"default": false,
"markdownDescription": "Use the native Swift REPL.",
"order": 16,
"tags": [
"experimental"
]
}
}
},
Expand Down Expand Up @@ -745,6 +759,11 @@
"command": "swift.cleanBuild",
"group": "2_pkg@1",
"when": "swift.hasPackage"
},
{
"command": "swift.evaluate",
"group": "1_file@6",
"when": "editorFocus && editorLangId == swift && config.swift.repl"
}
],
"view/title": [
Expand Down Expand Up @@ -1276,4 +1295,4 @@
"vscode-languageclient": "^9.0.1",
"xml2js": "^0.6.2"
}
}
}
9 changes: 9 additions & 0 deletions src/WorkspaceContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { DebugAdapter } from "./debugger/debugAdapter";
import { SwiftBuildStatus } from "./ui/SwiftBuildStatus";
import { SwiftToolchain } from "./toolchain/toolchain";
import { DiagnosticsManager } from "./DiagnosticsManager";
import { REPL } from "./repl/REPL";

/**
* Context for whole workspace. Holds array of contexts for each workspace folder
Expand All @@ -51,6 +52,7 @@ export class WorkspaceContext implements vscode.Disposable {
public commentCompletionProvider: CommentCompletionProviders;
private lastFocusUri: vscode.Uri | undefined;
private initialisationFinished = false;
private repl: REPL | undefined;

private constructor(
public tempFolder: TemporaryFolder,
Expand Down Expand Up @@ -658,6 +660,13 @@ export class WorkspaceContext implements vscode.Disposable {

private observers: Set<WorkspaceFoldersObserver> = new Set();
private swiftFileObservers: Set<SwiftFileObserver> = new Set();

public getRepl(): REPL {
if (!this.repl) {
this.repl = new REPL(this);
}
return this.repl;
}
}

/** Workspace Folder events */
Expand Down
2 changes: 2 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { captureDiagnostics } from "./commands/captureDiagnostics";
import { reindexProjectRequest } from "./sourcekit-lsp/lspExtensions";
import { TestRunner, TestRunnerTestRunState } from "./TestExplorer/TestRunner";
import { TestKind } from "./TestExplorer/TestKind";
import { evaluateExpression } from "./repl/command";

/**
* References:
Expand Down Expand Up @@ -940,5 +941,6 @@ export function register(ctx: WorkspaceContext): vscode.Disposable[] {
ctx.diagnostics.clear()
),
vscode.commands.registerCommand("swift.captureDiagnostics", () => captureDiagnostics(ctx)),
vscode.commands.registerCommand("swift.evaluate", () => evaluateExpression(ctx)),
];
}
17 changes: 17 additions & 0 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ export interface FolderConfiguration {
readonly disableAutoResolve: boolean;
}

/** REPL configuration */
export interface REPLConfiguration {
/** Enable the native REPL */
readonly enable: boolean;
}

/**
* Type-safe wrapper around configuration settings.
*/
Expand Down Expand Up @@ -154,6 +160,17 @@ const configuration = {
},
};
},

get repl(): REPLConfiguration {
return {
get enable(): boolean {
return vscode.workspace
.getConfiguration("swift.repl")
.get<boolean>("enable", false);
},
};
},

/** Files and directories to exclude from the code coverage. */
get excludeFromCodeCoverage(): string[] {
return vscode.workspace
Expand Down
212 changes: 212 additions & 0 deletions src/repl/REPL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2022 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import {
Disposable,
NotebookController,
NotebookDocument,
NotebookCellOutput,
NotebookCellOutputItem,
notebooks,
workspace,
NotebookEditor,
ViewColumn,
TabInputNotebook,
commands,
window,
NotebookControllerAffinity,
NotebookCellData,
NotebookEdit,
WorkspaceEdit,
} from "vscode";
import { ChildProcess, spawn } from "child_process";
import { createInterface, Interface } from "readline";
import { WorkspaceContext } from "../WorkspaceContext";
import { NotebookCellKind } from "vscode-languageclient";

export interface ExecutionResult {
status: boolean;
output: string | undefined;
}

export interface IREPL {
execute(code: string): Promise<ExecutionResult | undefined>;
interrupt(): void;
}

class REPLConnection implements IREPL {
private stdout: Interface;
private stderr: Interface;

constructor(private repl: ChildProcess) {
this.stdout = createInterface({ input: repl.stdout as NodeJS.ReadableStream });
this.stderr = createInterface({ input: repl.stderr as NodeJS.ReadableStream });
this.stdout.on("line", line => {
console.log(`=> ${line}`);
});
this.stderr.on("line", line => {
console.log(`=> ${line}`);
});
}

public async execute(code: string): Promise<ExecutionResult | undefined> {
if (!code.endsWith("\n")) {
code += "\n";
}
if (!this.repl.stdin?.write(code)) {
return Promise.resolve({ status: false, output: undefined });
}
return new Promise((resolve, _reject) => {
this.stdout.on("line", line => {
return resolve({ status: true, output: line });
});

const lines: string[] = [];
this.stderr.on("line", line => {
lines.push(line);
if (!line) {
return resolve({ status: false, output: lines.join("\n") });
}
});
});
}

public interrupt(): void {
this.repl.stdin?.write(":q");
}
}

export class REPL implements Disposable {
private repl: REPLConnection;
private controller: NotebookController;
private document: NotebookDocument | undefined;
private listener: Disposable | undefined;

constructor(workspace: WorkspaceContext) {
const repl = spawn(workspace.toolchain.getToolchainExecutable("swift"), ["repl"]);
repl.on("exit", (code, _signal) => {
console.error(`repl exited with code ${code}`);
});
repl.on("error", error => {
console.error(`repl error: ${error}`);
});

this.repl = new REPLConnection(repl);

this.controller = notebooks.createNotebookController(
"SwiftREPL",
"interactive",
"Swift REPL"
);
this.controller.supportedLanguages = ["swift"];
this.controller.supportsExecutionOrder = true;
this.controller.description = "Swift REPL";
this.controller.interruptHandler = async () => {
this.repl.interrupt();
};
this.controller.executeHandler = async (cells, _notebook, controller) => {
for (const cell of cells) {
const execution = controller.createNotebookCellExecution(cell);
execution.start(Date.now());

const result = await this.repl.execute(cell.document.getText());
if (result?.output) {
execution.replaceOutput([
new NotebookCellOutput([
NotebookCellOutputItem.text(result.output, "text/plain"),
]),
]);
}

execution.end(result?.status);
}
};

this.watchNotebookClose();
}

dispose(): void {
this.controller.dispose();
this.listener?.dispose();
}

private watchNotebookClose() {
this.listener = workspace.onDidCloseNotebookDocument(notebook => {
if (notebook.uri.toString() === this.document?.uri.toString()) {
this.document = undefined;
}
});
}

private getNotebookColumn(): ViewColumn | undefined {
const uri = this.document?.uri.toString();
return window.tabGroups.all.flatMap(group => {
return group.tabs.flatMap(tab => {
if (tab.label === "Swift REPL") {
if ((tab.input as TabInputNotebook)?.uri.toString() === uri) {
return tab.group.viewColumn;
}
}
return undefined;
});
})?.[0];
}

public async evaluate(code: string): Promise<void> {
let editor: NotebookEditor | undefined;
if (this.document) {
const column = this.getNotebookColumn() ?? ViewColumn.Beside;
editor = await window.showNotebookDocument(this.document!, { viewColumn: column });
} else {
const notebook = (await commands.executeCommand(
"interactive.open",
{
preserveFocus: true,
viewColumn: ViewColumn.Beside,
},
undefined,
this.controller.id,
"Swift REPL"
)) as { notebookEditor: NotebookEditor };
editor = notebook.notebookEditor;
this.document = editor.notebook;
}

if (this.document) {
this.controller.updateNotebookAffinity(
this.document,
NotebookControllerAffinity.Default
);

await commands.executeCommand("notebook.selectKernel", {
notebookEdtior: this.document,
id: this.controller.id,
extension: "sswg.swift-lang",
});

const edit = new WorkspaceEdit();
edit.set(this.document.uri, [
NotebookEdit.insertCells(this.document.cellCount, [
new NotebookCellData(NotebookCellKind.Code, code, "swift"),
]),
]);
workspace.applyEdit(edit);

commands.executeCommand("notebook.cell.execute", {
ranges: [{ start: this.document.cellCount, end: this.document.cellCount + 1 }],
document: this.document.uri,
});
}
}
}
30 changes: 30 additions & 0 deletions src/repl/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2022 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import { window } from "vscode";
import { WorkspaceContext } from "../WorkspaceContext";

export async function evaluateExpression(context: WorkspaceContext): Promise<void> {
const editor = window.activeTextEditor;

// const multiline = !editor?.selection.isSingleLine ?? false;
// const complete = true; // TODO(compnerd) determine if the input is complete
const code = editor?.document.lineAt(editor?.selection.start.line).text;
if (!code) {
return;
}

const repl = context.getRepl();
await repl.evaluate(code);
}

0 comments on commit 9a0b6b7

Please sign in to comment.