Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ jobs:
linux_pre_build_command: . .github/workflows/scripts/setup-linux.sh
linux_build_command: ./scripts/test.sh
# Windows
windows_exclude_swift_versions: '[{"swift_version": "5.9"}, {"swift_version": "6.0"}, {"swift_version": "6.1"}, {"swift_version": "nightly-6.1"}, {"swift_version": "nightly-6.2"}, {"swift_version": "nightly"}]'
windows_exclude_swift_versions: '[{"swift_version": "5.9"}, {"swift_version": "6.0"}, {"swift_version": "6.1"}, {"swift_version": "6.2"}, {"swift_version": "nightly-6.1"}, {"swift_version": "nightly-6.2"}, {"swift_version": "nightly"}]'
windows_env_vars: |
CI=1
VSCODE_VERSION=insiders
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1527,6 +1527,11 @@
"command": "swift.coverAllTests",
"when": "view == projectPanel && viewItem == 'test_runnable'",
"group": "inline@3"
},
{
"command": "swift.play",
"when": "view == projectPanel && viewItem == 'playground'",
"group": "inline@1"
}
]
},
Expand Down
49 changes: 47 additions & 2 deletions src/FolderContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { TestRunProxy } from "./TestExplorer/TestRunner";
import { FolderOperation, WorkspaceContext } from "./WorkspaceContext";
import configuration from "./configuration";
import { SwiftLogger } from "./logging/SwiftLogger";
import { PlaygroundProvider } from "./playgrounds/PlaygroundProvider";
import { TaskQueue } from "./tasks/TaskQueue";
import { SwiftToolchain } from "./toolchain/toolchain";
import { showToolchainError } from "./ui/ToolchainSelection";
Expand All @@ -35,6 +36,7 @@ export class FolderContext implements vscode.Disposable {
public taskQueue: TaskQueue;
public testExplorer?: TestExplorer;
public resolvedTestExplorer: Promise<TestExplorer>;
public playgroundProvider?: PlaygroundProvider;
private testExplorerResolver?: (testExplorer: TestExplorer) => void;
private packageWatcher: PackageWatcher;
private testRunManager: TestRunManager;
Expand Down Expand Up @@ -247,7 +249,7 @@ export class FolderContext implements vscode.Disposable {
return this.testExplorer;
}

/** Create Test explorer for this folder */
/** Remove Test explorer from this folder */
removeTestExplorer() {
this.testExplorer?.dispose();
this.testExplorer = undefined;
Expand All @@ -260,11 +262,35 @@ export class FolderContext implements vscode.Disposable {
}
}

/** Return if package folder has a test explorer */
/** Return `true` if package folder has a test explorer */
hasTestExplorer() {
return this.testExplorer !== undefined;
}

/** Create Playground provider for this folder */
addPlaygroundProvider() {
if (!this.playgroundProvider) {
this.playgroundProvider = new PlaygroundProvider(this);
}
return this.playgroundProvider;
}

/** Refresh the tests in the test explorer for this folder */
async refreshPlaygroundProvider() {
await this.playgroundProvider?.fetch();
}

/** Remove playground provider from this folder */
removePlaygroundProvider() {
this.playgroundProvider?.dispose();
this.playgroundProvider = undefined;
}

/** Return `true` if package folder has a playground provider */
hasPlaygroundProvider() {
return this.testExplorer !== undefined;
}

static uriName(uri: vscode.Uri): string {
return path.basename(uri.fsPath);
}
Expand Down Expand Up @@ -335,6 +361,25 @@ export class FolderContext implements vscode.Disposable {
void this.testExplorer.getDocumentTests(this, uri, symbols);
}
}

/**
* Called whenever we have new document CodeLens
*/
onDocumentCodeLens(
document: vscode.TextDocument,
codeLens: vscode.CodeLens[] | null | undefined
) {
const uri = document?.uri;
if (
this.playgroundProvider &&
codeLens &&
uri &&
uri.scheme === "file" &&
isPathInsidePath(uri.fsPath, this.folder.fsPath)
) {
void this.playgroundProvider.onDocumentCodeLens(document, codeLens);
}
}
}

export interface EditedPackage {
Expand Down
3 changes: 3 additions & 0 deletions src/WorkspaceContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ export class WorkspaceContext implements vscode.Disposable {
onDocumentSymbols: (folder, document, symbols) => {
folder.onDocumentSymbols(document, symbols);
},
onDocumentCodeLens: (folder, document, codelens) => {
folder.onDocumentCodeLens(document, codelens);
},
});
this.tasks = new TaskManager(this);
this.diagnostics = new DiagnosticsManager(this);
Expand Down
8 changes: 6 additions & 2 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { switchPlatform } from "./commands/switchPlatform";
import { extractTestItemsAndCount, runTestMultipleTimes } from "./commands/testMultipleTimes";
import { SwiftLogger } from "./logging/SwiftLogger";
import { SwiftToolchain } from "./toolchain/toolchain";
import { PackageNode } from "./ui/ProjectPanelProvider";
import { PackageNode, PlaygroundNode } from "./ui/ProjectPanelProvider";
import { showToolchainSelectionQuickPick } from "./ui/ToolchainSelection";

/**
Expand Down Expand Up @@ -153,7 +153,11 @@ export function register(ctx: WorkspaceContext): vscode.Disposable[] {
if (!folder || !target) {
return false;
}
return await runPlayground(folder, ctx.tasks, target);
return await runPlayground(
folder,
ctx.tasks,
PlaygroundNode.isPlaygroundNode(target) ? target.playground : target
);
}),
vscode.commands.registerCommand(Commands.CLEAN_BUILD, async () => await cleanBuild(ctx)),
vscode.commands.registerCommand(
Expand Down
2 changes: 2 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { registerDebugger } from "./debugger/debugAdapterFactory";
import * as debug from "./debugger/launch";
import { SwiftLogger } from "./logging/SwiftLogger";
import { SwiftLoggerFactory } from "./logging/SwiftLoggerFactory";
import { PlaygroundProvider } from "./playgrounds/PlaygroundProvider";
import { SwiftEnvironmentVariablesManager, SwiftTerminalProfileProvider } from "./terminal";
import { SelectedXcodeWatcher } from "./toolchain/SelectedXcodeWatcher";
import { checkForSwiftlyInstallation } from "./toolchain/swiftly";
Expand Down Expand Up @@ -159,6 +160,7 @@ export async function activate(context: vscode.ExtensionContext): Promise<Api> {
// observer that will resolve package and build launch configurations
context.subscriptions.push(workspaceContext.onDidChangeFolders(handleFolderEvent(logger)));
context.subscriptions.push(TestExplorer.observeFolders(workspaceContext));
context.subscriptions.push(PlaygroundProvider.observeFolders(workspaceContext));

context.subscriptions.push(registerSourceKitSchemaWatcher(workspaceContext));
const subscriptionsElapsed = Date.now() - subscriptionsStartTime;
Expand Down
57 changes: 57 additions & 0 deletions src/playgrounds/LSPPlaygroundsDiscovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2025 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 { checkExperimentalCapability } from "../sourcekit-lsp/LanguageClientManager";
import { LanguageClientManager } from "../sourcekit-lsp/LanguageClientManager";
import { Playground, WorkspacePlaygroundsRequest } from "../sourcekit-lsp/extensions";
import { Version } from "../utilities/version";

export { Playground };

/**
* Uses document symbol request to keep a running copy of all the test methods
* in a file. When a file is saved it checks to see if any new methods have been
* added, or if any methods have been removed and edits the test items based on
* these results.
*/
export class LSPPlaygroundsDiscovery {
constructor(private languageClient: LanguageClientManager) {}

private get toolchainVersion(): Version {
return this.languageClient.folderContext.toolchain.swiftVersion;
}

/**
* Return list of workspace playgrounds
*/
async getWorkspacePlaygrounds(): Promise<Playground[]> {
return await this.languageClient.useLanguageClient(async (client, token) => {
// Only use the lsp for this request if it supports the
// workspace/playgrounds method.
if (checkExperimentalCapability(client, WorkspacePlaygroundsRequest.method, 1)) {
return await client.sendRequest(WorkspacePlaygroundsRequest.type, token);
} else {
throw new Error(`${WorkspacePlaygroundsRequest.method} requests not supported`);
}
});
}

async supportsPlaygrounds(): Promise<boolean> {
if (this.toolchainVersion.isLessThan(new Version(6, 3, 0))) {
return false;
}
return await this.languageClient.useLanguageClient(async client => {
return checkExperimentalCapability(client, WorkspacePlaygroundsRequest.method, 1);
});
}
}
145 changes: 145 additions & 0 deletions src/playgrounds/PlaygroundProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2025 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 * as vscode from "vscode";

import { FolderContext } from "../FolderContext";
import { FolderOperation, WorkspaceContext } from "../WorkspaceContext";
import { SwiftLogger } from "../logging/SwiftLogger";
import { LSPPlaygroundsDiscovery, Playground } from "./LSPPlaygroundsDiscovery";

export { Playground };

export interface PlaygroundChangeEvent {
uri: string;
playgrounds: Playground[];
}

/**
* Uses document symbol request to keep a running copy of all the test methods
* in a file. When a file is saved it checks to see if any new methods have been
* added, or if any methods have been removed and edits the test items based on
* these results.
*/
export class PlaygroundProvider implements vscode.Disposable {
private fetchPromise: Promise<Playground[]> | undefined;
private documentPlaygrounds: Map<string, Playground[]> = new Map();
private didChangePlaygroundsEmitter: vscode.EventEmitter<PlaygroundChangeEvent> =
new vscode.EventEmitter();

constructor(private folderContext: FolderContext) {}

private get lspPlaygroundDiscovery(): LSPPlaygroundsDiscovery {
return new LSPPlaygroundsDiscovery(this.folderContext.languageClientManager);
}

private get logger(): SwiftLogger {
return this.folderContext.workspaceContext.logger;
}

/**
* Create folder observer that creates a PlaygroundProvider when a folder is added and
* discovers available playgrounds when the folder is in focus
* @param workspaceContext Workspace context for extension
* @returns Observer disposable
*/
public static observeFolders(workspaceContext: WorkspaceContext): vscode.Disposable {
return workspaceContext.onDidChangeFolders(({ folder, operation }) => {
switch (operation) {
case FolderOperation.add:
case FolderOperation.packageUpdated:
if (folder) {
void this.setupPlaygroundProviderForFolder(folder);
}
break;
}
});
}

private static async setupPlaygroundProviderForFolder(folder: FolderContext) {
if (!folder.hasPlaygroundProvider()) {
folder.addPlaygroundProvider();
}
await folder.refreshPlaygroundProvider();
}

/**
* Fetch the full list of playgrounds
*/
async getWorkspacePlaygrounds(): Promise<Playground[]> {
if (this.fetchPromise) {
return await this.fetchPromise;
}
return Array.from(this.documentPlaygrounds.values()).flatMap(v => v);
}

onDocumentCodeLens(
document: vscode.TextDocument,
codeLens: vscode.CodeLens[] | null | undefined
) {
const playgrounds: Playground[] = (
codeLens?.map(c => (c.command?.arguments ?? [])[0]) ?? []
)
.filter(p => !!p)
// Convert from LSP TextDocumentPlayground to Playground
.map(p => ({
...p,
range: undefined,
location: new vscode.Location(document.uri, p.range),
}));
const uri = document.uri.toString();
if (playgrounds.length > 0) {
this.documentPlaygrounds.set(uri, playgrounds);
this.didChangePlaygroundsEmitter.fire({ uri, playgrounds });
} else {
if (this.documentPlaygrounds.delete(uri)) {
this.didChangePlaygroundsEmitter.fire({ uri, playgrounds: [] });
}
}
}

onDidChangePlaygrounds: vscode.Event<PlaygroundChangeEvent> =
this.didChangePlaygroundsEmitter.event;

async fetch() {
if (!(await this.lspPlaygroundDiscovery.supportsPlaygrounds())) {
this.logger.debug(
`Fetching playgrounds not supported by the language server`,
this.folderContext.name
);
return;
}
this.fetchPromise = this.lspPlaygroundDiscovery.getWorkspacePlaygrounds();
try {
const playgrounds = await this.fetchPromise;
this.documentPlaygrounds.clear();
for (const playground of playgrounds) {
const uri = playground.location.uri;
this.documentPlaygrounds.set(
uri,
(this.documentPlaygrounds.get(uri) ?? []).concat(playground)
);
}
} catch (error) {
this.logger.error(
`Failed to fetch workspace playgrounds: ${error}`,
this.folderContext.name
);
}
this.fetchPromise = undefined;
}

dispose() {
this.documentPlaygrounds.clear();
}
}
6 changes: 5 additions & 1 deletion src/sourcekit-lsp/LanguageClientConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ export function lspClientOptions(
documentSymbolWatcher?: (
document: vscode.TextDocument,
symbols: vscode.DocumentSymbol[]
) => void
) => void,
documentCodeLensWatcher?: (document: vscode.TextDocument, codeLens: vscode.CodeLens[]) => void
): LanguageClientOptions {
return {
documentSelector: LanguagerClientDocumentSelectors.sourcekitLSPDocumentTypes(),
Expand Down Expand Up @@ -247,6 +248,9 @@ export function lspClientOptions(
},
provideCodeLenses: async (document, token, next) => {
const result = await next(document, token);
if (documentCodeLensWatcher && result) {
documentCodeLensWatcher(document, result);
}
return result?.map(codelens => {
switch (codelens.command?.command) {
case "swift.run":
Expand Down
Loading