Skip to content

Add CopilotRelated command #59963

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Sep 26, 2024
Merged
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
1 change: 1 addition & 0 deletions src/harness/client.ts
Original file line number Diff line number Diff line change
@@ -800,6 +800,7 @@ export class SessionClient implements LanguageService {
}

mapCode: typeof notImplemented = notImplemented;
getImports: typeof notImplemented = notImplemented;

private createFileLocationOrRangeRequestArgs(positionOrRange: number | TextRange, fileName: string): protocol.FileLocationOrRangeRequestArgs {
return typeof positionOrRange === "number"
22 changes: 22 additions & 0 deletions src/harness/fourslashImpl.ts
Original file line number Diff line number Diff line change
@@ -4631,6 +4631,28 @@ ${changes.join("\n// ---\n")}
${after}`;
this.baseline("mapCode", baseline, ".mapCode.ts");
}

public verifyGetImports(fileName: string, expectedImports: string[]): void {
const actualImports = this.languageService.getImports(fileName);
if (actualImports.length !== expectedImports.length) {
throw new Error(`Expected ${expectedImports.length} imports for ${fileName}, got ${actualImports.length}
Expected:
${expectedImports}
Actual:
${actualImports}
`);
}
for (let i = 0; i < expectedImports.length; i++) {
if (actualImports[i] !== expectedImports[i]) {
throw new Error(`Expected at ${fileName} index ${i}: ${expectedImports[i]}, got ${actualImports[i]}
Expected:
${expectedImports}
Actual:
${actualImports}
`);
}
}
}
}

function updateTextRangeForTextChanges({ pos, end }: ts.TextRange, textChanges: readonly ts.TextChange[]): ts.TextRange {
9 changes: 9 additions & 0 deletions src/harness/fourslashInterfaceImpl.ts
Original file line number Diff line number Diff line change
@@ -257,6 +257,10 @@ export class VerifyNegatable {
public baselineMapCode(ranges: FourSlash.Range[][], changes: string[] = []): void {
this.state.baselineMapCode(ranges, changes);
}

public getImports(fileName: string, imports: string[]): void {
return this.state.verifyGetImports(fileName, imports);
}
}

export interface CompletionsResult {
@@ -2039,3 +2043,8 @@ export interface RenameOptions {
readonly providePrefixAndSuffixTextForRename?: boolean;
readonly quotePreference?: "auto" | "double" | "single";
}

export interface VerifyGetImportsOptions {
fileName: string;
imports: string[];
}
13 changes: 13 additions & 0 deletions src/server/protocol.ts
Original file line number Diff line number Diff line change
@@ -201,6 +201,7 @@ export const enum CommandTypes {
ProvideInlayHints = "provideInlayHints",
WatchChange = "watchChange",
MapCode = "mapCode",
CopilotRelated = "copilotRelated",
}

/**
@@ -2391,6 +2392,18 @@ export interface MapCodeResponse extends Response {
body: readonly FileCodeEdits[];
}

export interface CopilotRelatedRequest extends FileRequest {
command: CommandTypes.CopilotRelated;
arguments: FileRequestArgs;
}

export interface CopilotRelatedItems {
relatedFiles: readonly string[];
}

export interface CopilotRelatedResponse extends Response {
body: CopilotRelatedItems;
}
/**
* Synchronous request for semantic diagnostics of one file.
*/
13 changes: 12 additions & 1 deletion src/server/session.ts
Original file line number Diff line number Diff line change
@@ -937,6 +937,7 @@ const invalidPartialSemanticModeCommands: readonly protocol.CommandTypes[] = [
protocol.CommandTypes.ProvideCallHierarchyIncomingCalls,
protocol.CommandTypes.ProvideCallHierarchyOutgoingCalls,
protocol.CommandTypes.GetPasteEdits,
protocol.CommandTypes.CopilotRelated,
];

const invalidSyntacticModeCommands: readonly protocol.CommandTypes[] = [
@@ -2029,7 +2030,6 @@ export class Session<TMessage = string> implements EventSender {
};
});
}

private mapCode(args: protocol.MapCodeRequestArgs): protocol.FileCodeEdits[] {
const formatOptions = this.getHostFormatOptions();
const preferences = this.getHostPreferences();
@@ -2050,6 +2050,14 @@ export class Session<TMessage = string> implements EventSender {
return this.mapTextChangesToCodeEdits(changes);
}

private getCopilotRelatedInfo(args: protocol.FileRequestArgs): protocol.CopilotRelatedItems {
const { file, project } = this.getFileAndProject(args);

return {
relatedFiles: project.getLanguageService().getImports(file),
};
}

private setCompilerOptionsForInferredProjects(args: protocol.SetCompilerOptionsForInferredProjectsArgs): void {
this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath);
}
@@ -3783,6 +3791,9 @@ export class Session<TMessage = string> implements EventSender {
[protocol.CommandTypes.MapCode]: (request: protocol.MapCodeRequest) => {
return this.requiredResponse(this.mapCode(request.arguments));
},
[protocol.CommandTypes.CopilotRelated]: (request: protocol.CopilotRelatedRequest) => {
return this.requiredResponse(this.getCopilotRelatedInfo(request.arguments));
},
}));

public addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void {
16 changes: 16 additions & 0 deletions src/services/services.ts
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ import {
__String,
ApplicableRefactorInfo,
ApplyCodeActionCommandResult,
arrayFrom,
AssignmentDeclarationKind,
BaseType,
BinaryExpression,
@@ -233,6 +234,7 @@ import {
Node,
NodeArray,
NodeFlags,
nodeIsSynthesized,
noop,
normalizePath,
normalizeSpans,
@@ -1593,6 +1595,7 @@ const invalidOperationsInPartialSemanticMode: readonly (keyof LanguageService)[]
"provideInlayHints",
"getSupportedCodeFixes",
"getPasteEdits",
"getImports",
];

const invalidOperationsInSyntacticMode: readonly (keyof LanguageService)[] = [
@@ -3345,6 +3348,18 @@ export function createLanguageService(
);
}

function getImports(fileName: string): readonly string[] {
synchronizeHostData();
const file = getValidSourceFile(fileName);
let imports: Set<string> | undefined;
for (const specifier of file.imports) {
if (nodeIsSynthesized(specifier)) continue;
const name = program.getResolvedModuleFromModuleSpecifier(specifier, file)?.resolvedModule?.resolvedFileName;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it may happen that we have resolvedFileName = say "module.js" but its not part of program. Is this ok to send back that file name ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, files that are not part of the program are fine; we don't expect to get information from Typescript about them -- they are fine if they exist on disk.

if (name) (imports ??= new Set()).add(name);
}
return imports ? arrayFrom(imports) : emptyArray;
}

const ls: LanguageService = {
dispose,
cleanupSemanticCache,
@@ -3418,6 +3433,7 @@ export function createLanguageService(
getSupportedCodeFixes,
getPasteEdits,
mapCode,
getImports,
};

switch (languageServiceMode) {
1 change: 1 addition & 0 deletions src/services/types.ts
Original file line number Diff line number Diff line change
@@ -697,6 +697,7 @@ export interface LanguageService {
getSupportedCodeFixes(fileName?: string): readonly string[];

/** @internal */ mapCode(fileName: string, contents: string[], focusLocations: TextSpan[][] | undefined, formatOptions: FormatCodeSettings, preferences: UserPreferences): readonly FileTextChanges[];
/** @internal */ getImports(fileName: string): readonly string[];

dispose(): void;
getPasteEdits(
12 changes: 12 additions & 0 deletions tests/baselines/reference/api/typescript.d.ts
Original file line number Diff line number Diff line change
@@ -122,6 +122,7 @@ declare namespace ts {
ProvideInlayHints = "provideInlayHints",
WatchChange = "watchChange",
MapCode = "mapCode",
CopilotRelated = "copilotRelated",
}
/**
* A TypeScript Server message
@@ -1816,6 +1817,16 @@ declare namespace ts {
export interface MapCodeResponse extends Response {
body: readonly FileCodeEdits[];
}
export interface CopilotRelatedRequest extends FileRequest {
command: CommandTypes.CopilotRelated;
arguments: FileRequestArgs;
}
export interface CopilotRelatedItems {
relatedFiles: readonly string[];
}
export interface CopilotRelatedResponse extends Response {
body: CopilotRelatedItems;
}
/**
* Synchronous request for semantic diagnostics of one file.
*/
@@ -3500,6 +3511,7 @@ declare namespace ts {
private getDocumentHighlights;
private provideInlayHints;
private mapCode;
private getCopilotRelatedInfo;
private setCompilerOptionsForInferredProjects;
private getProjectInfo;
private getProjectInfoWorker;
1 change: 1 addition & 0 deletions tests/cases/fourslash/fourslash.ts
Original file line number Diff line number Diff line change
@@ -467,6 +467,7 @@ declare namespace FourSlashInterface {
}
}): void;
baselineMapCode(ranges: Range[][], changes: string[]): void;
getImports(fileName: string, imports: string[]): void;
}
class edit {
caretPosition(): Marker;
16 changes: 16 additions & 0 deletions tests/cases/fourslash/getImportsDuplicate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
///<reference path="fourslash.ts"/>

// @Filename: /first.ts
//// export function foo() {
//// return 1;
//// }
//// export function bar() {
//// return 2;
//// }

// @Filename: /index.ts
//// import { foo } from "./first";
//// import { bar } from './first';
//// console.log(foo() + bar())

verify.getImports('/index.ts', ['/first.ts'])
12 changes: 12 additions & 0 deletions tests/cases/fourslash/getImportsDynamic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
///<reference path="fourslash.ts"/>

// @Filename: /first.ts
//// export function foo() {
//// return 1;
//// }
// @Filename: /index.ts
//// let bar: typeof import('./first').foo = function bar() {
//// return 2;
//// }

verify.getImports('/index.ts', ['/first.ts'])
108 changes: 108 additions & 0 deletions tests/cases/fourslash/getImportsJSXFactory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
///<reference path="fourslash.ts"/>

// @strict: true
// @jsx: react-jsx
// @jsxImportSource: preact
// @filename: /node_modules/preact/index.d.ts
//// type Defaultize<Props, Defaults> =
//// // Distribute over unions
//// Props extends any // Make any properties included in Default optional
//// ? Partial<Pick<Props, Extract<keyof Props, keyof Defaults>>> &
//// // Include the remaining properties from Props
//// Pick<Props, Exclude<keyof Props, keyof Defaults>>
//// : never;
//// export namespace JSXInternal {
//// interface HTMLAttributes<T = {}> { }
//// interface SVGAttributes<T = {}> { }
//// type LibraryManagedAttributes<Component, Props> = Component extends {
//// defaultProps: infer Defaults;
//// }
//// ? Defaultize<Props, Defaults>
//// : Props;
////
//// interface IntrinsicAttributes {
//// key?: any;
//// }
////
//// interface Element extends VNode<any> { }
////
//// interface ElementClass extends Component<any, any> { }
////
//// interface ElementAttributesProperty {
//// props: any;
//// }
////
//// interface ElementChildrenAttribute {
//// children: any;
//// }
////
//// interface IntrinsicElements {
//// div: HTMLAttributes;
//// }
//// }
//// export const Fragment: unique symbol;
//// export type ComponentType<T = {}> = {};
//// export type ComponentChild = {};
//// export type ComponentChildren = {};
//// export type VNode<T = {}> = {};
//// export type Attributes = {};
//// export type Component<T = {}, U = {}> = {};
// @filename: /node_modules/preact/jsx-runtime/index.d.ts
//// export { Fragment } from '..';
//// import {
//// ComponentType,
//// ComponentChild,
//// ComponentChildren,
//// VNode,
//// Attributes
//// } from '..';
//// import { JSXInternal } from '..';
////
//// export function jsx(
//// type: string,
//// props: JSXInternal.HTMLAttributes &
//// JSXInternal.SVGAttributes &
//// Record<string, any> & { children?: ComponentChild },
//// key?: string
//// ): VNode<any>;
//// export function jsx<P>(
//// type: ComponentType<P>,
//// props: Attributes & P & { children?: ComponentChild },
//// key?: string
//// ): VNode<any>;
////
////
//// export function jsxs(
//// type: string,
//// props: JSXInternal.HTMLAttributes &
//// JSXInternal.SVGAttributes &
//// Record<string, any> & { children?: ComponentChild[] },
//// key?: string
//// ): VNode<any>;
//// export function jsxs<P>(
//// type: ComponentType<P>,
//// props: Attributes & P & { children?: ComponentChild[] },
//// key?: string
//// ): VNode<any>;
////
////
//// export function jsxDEV(
//// type: string,
//// props: JSXInternal.HTMLAttributes &
//// JSXInternal.SVGAttributes &
//// Record<string, any> & { children?: ComponentChildren },
//// key?: string
//// ): VNode<any>;
//// export function jsxDEV<P>(
//// type: ComponentType<P>,
//// props: Attributes & P & { children?: ComponentChildren },
//// key?: string
//// ): VNode<any>;
////
//// export import JSX = JSXInternal;
////
// @filename: /index.tsx
//// export const Comp = () => <div></div>;

verify.noErrors()
verify.getImports('/index.tsx', [])
12 changes: 12 additions & 0 deletions tests/cases/fourslash/getImportsNone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
///<reference path="fourslash.ts"/>

// @Filename: /index.ts
//// function foo() {
//// return 1;
//// }
//// function bar() {
//// return 2;
//// }
////

verify.getImports('/index.ts', [])
14 changes: 14 additions & 0 deletions tests/cases/fourslash/getImportsOne.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
///<reference path="fourslash.ts"/>

// @Filename: /first.ts
//// export function foo() {
//// return 1;
//// }
// @Filename: /index.ts
//// import { foo } from "./first";
//// function bar() {
//// return 2;
//// }
////

verify.getImports('/index.ts', ['/first.ts'])
15 changes: 15 additions & 0 deletions tests/cases/fourslash/getImportsOneJs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
///<reference path="fourslash.ts"/>

// @checkJs: true
// @Filename: /first.ts
//// export function foo() {
//// return 1;
//// }
// @Filename: /index.js
//// const { foo } = require("./first");
//// function bar() {
//// return 2;
//// }
////

verify.getImports('/index.js', ['/first.ts'])
15 changes: 15 additions & 0 deletions tests/cases/fourslash/getImportsReexport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
///<reference path="fourslash.ts"/>

// @Filename: /first.ts
//// export function foo() {
//// return 1;
//// }
// @Filename: /index.ts
//// export { foo } from "./first";
//// function bar() {
//// return 2;
//// }
////


verify.getImports('/index.ts', ['/first.ts'])
19 changes: 19 additions & 0 deletions tests/cases/fourslash/getImportsTslib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
///<reference path="fourslash.ts"/>

// @importHelpers: true
// @target: es2015
// @lib: es2015
// @module: commonjs
// @Filename: /node_modules/tslib/index.d.ts
//// export function __awaiter(...args: any): any;
// @Filename: /first.ts
//// export function foo() {
//// return 2
//// }
// @Filename: /index.ts
//// export async function importer() {
//// const mod = await import("./first");
//// }

verify.noErrors()
verify.getImports('/index.ts', ['/first.ts'])