Skip to content

Merge remote-tracking branch 'origin/main' into fix-string-completions-from-infer #54668

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

Closed
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
29 changes: 23 additions & 6 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1650,12 +1650,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
getFullyQualifiedName,
getResolvedSignature: (node, candidatesOutArray, argumentCount) =>
getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.Normal),
getResolvedSignatureForStringLiteralCompletions: (call, editingArgument, candidatesOutArray, checkMode = CheckMode.IsForStringLiteralArgumentCompletions) => {
if (checkMode & CheckMode.IsForStringLiteralArgumentCompletions) {
return runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ undefined, checkMode & ~CheckMode.IsForStringLiteralArgumentCompletions));
}
return runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ undefined, checkMode & ~CheckMode.IsForStringLiteralArgumentCompletions));
},
getCandidateSignaturesForStringLiteralCompletions,
getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) =>
runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.IsForSignatureHelp)),
getExpandedParameters,
Expand Down Expand Up @@ -1836,6 +1831,28 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
typeHasCallOrConstructSignatures,
};

function getCandidateSignaturesForStringLiteralCompletions(call: CallLikeExpression, editingArgument: Node) {
const candidatesSet = new Set<Signature>();
const candidates: Signature[] = [];

// first, get candidates when inference is blocked from the source node.
runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(call, candidates, /*argumentCount*/ undefined, CheckMode.IsForStringLiteralArgumentCompletions));
for (const candidate of candidates) {
candidatesSet.add(candidate);
}

// reset candidates for second pass
candidates.length = 0;

// next, get candidates where the source node is considered for inference.
runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(call, candidates, /*argumentCount*/ undefined, CheckMode.IsForStringLiteralArgumentCompletions));
for (const candidate of candidates) {
candidatesSet.add(candidate);
}

return arrayFrom(candidatesSet);
}

function runWithoutResolvedSignatureCaching<T>(node: Node | undefined, fn: () => T): T {
const cachedSignatures = [];
while (node) {
Expand Down
3 changes: 1 addition & 2 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
BaseNodeFactory,
CheckMode,
CreateSourceFileOptions,
EmitHelperFactory,
GetCanonicalFileName,
Expand Down Expand Up @@ -5081,7 +5080,7 @@ export interface TypeChecker {
*/
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
/** @internal */ getResolvedSignatureForSignatureHelp(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
/** @internal */ getResolvedSignatureForStringLiteralCompletions(call: CallLikeExpression, editingArgument: Node, candidatesOutArray: Signature[], checkMode?: CheckMode): Signature | undefined;
/** @internal */ getCandidateSignaturesForStringLiteralCompletions(call: CallLikeExpression, editingArgument: Node): Signature[];
/** @internal */ getExpandedParameters(sig: Signature): readonly (readonly Symbol[])[];
/** @internal */ hasEffectiveRestParameter(sig: Signature): boolean;
/** @internal */ containsArgumentsReference(declaration: SignatureDeclaration): boolean;
Expand Down
9 changes: 3 additions & 6 deletions src/services/stringCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
CaseClause,
changeExtension,
CharacterCodes,
CheckMode,
combinePaths,
comparePaths,
comparePatternKeys,
Expand Down Expand Up @@ -117,7 +116,6 @@ import {
ScriptElementKind,
ScriptElementKindModifier,
ScriptTarget,
Signature,
signatureHasRestParameter,
SignatureHelp,
singleElementArray,
Expand Down Expand Up @@ -390,7 +388,7 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL
// Get string literal completions from specialized signatures of the target
// i.e. declare function f(a: 'A');
// f("/*completion position*/")
return argumentInfo && (getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker, CheckMode.Normal)) || fromContextualType(ContextFlags.None);
return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(ContextFlags.None);
}
// falls through (is `require("")` or `require(""` or `import("")`)

Expand Down Expand Up @@ -481,12 +479,11 @@ function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current:
type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined);
}

function getStringLiteralCompletionsFromSignature(call: CallLikeExpression, arg: StringLiteralLike, argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker, checkMode = CheckMode.IsForStringLiteralArgumentCompletions): StringLiteralCompletionsFromTypes | undefined {
function getStringLiteralCompletionsFromSignature(call: CallLikeExpression, arg: StringLiteralLike, argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes | undefined {
let isNewIdentifier = false;
const uniques = new Map<string, true>();
const candidates: Signature[] = [];
const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg;
checker.getResolvedSignatureForStringLiteralCompletions(call, editingArgument, candidates, checkMode);
const candidates = checker.getCandidateSignaturesForStringLiteralCompletions(call, editingArgument);
const types = flatMap(candidates, candidate => {
if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return;
let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/// <reference path="fourslash.ts" />

// repro from https://github.com/microsoft/TypeScript/issues/49680

//// type PathOf<T, K extends string, P extends string = ""> =
//// K extends `${infer U}.${infer V}`
//// ? U extends keyof T ? PathOf<T[U], V, `${P}${U}.`> : `${P}${keyof T & (string | number)}`
//// : K extends keyof T ? `${P}${K}` : `${P}${keyof T & (string | number)}`;
////
//// declare function consumer<K extends string>(path: PathOf<{a: string, b: {c: string}}, K>) : number;
////
//// consumer('b./*ts*/')

verify.completions({ marker: ["ts"], exact: ["a", "b", "b.c"] });
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/// <reference path="fourslash.ts" />

// @strict: true

// repro from https://github.com/microsoft/TypeScript/issues/53997

//// type keyword = "foo" | "bar" | "baz"
////
//// type validateString<s> = s extends keyword
//// ? s
//// : s extends `${infer left extends keyword}|${infer right}`
//// ? right extends keyword
//// ? s
//// : `${left}|${keyword}`
//// : keyword
////
//// type isUnknown<t> = unknown extends t
//// ? [t] extends [{}]
//// ? false
//// : true
//// : false
////
//// type validate<def> = def extends string
//// ? validateString<def>
//// : isUnknown<def> extends true
//// ? keyword
//// : {
//// [k in keyof def]: validate<def[k]>
//// }
//// const parse = <def>(def: validate<def>) => def
//// const shallowExpression = parse("foo|/*ts*/")
//// const nestedExpression = parse({ prop: "foo|/*ts2*/" })

verify.completions({ marker: ["ts"], exact: ["foo|foo", "foo|bar", "foo|baz"] });
verify.completions({ marker: ["ts2"], exact: ["foo|foo", "foo|bar", "foo|baz"] });
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/// <reference path="fourslash.ts" />

// repro from https://github.com/microsoft/TypeScript/issues/49680#issuecomment-1249191842

//// declare function pick<T extends object, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K>;
//// declare function pick2<T extends object, K extends (keyof T)[]>(obj: T, ...keys: K): Pick<T, K[number]>;
////
//// const obj = { aaa: 1, bbb: '2', ccc: true };
////
//// pick(obj, 'aaa', '/*ts1*/');
//// pick2(obj, 'aaa', '/*ts2*/');

// repro from https://github.com/microsoft/TypeScript/issues/49680#issuecomment-1273677941

//// class Q<T> {
//// public select<Keys extends keyof T>(...args: Keys[]) {}
//// }
//// new Q<{ id: string; name: string }>().select("name", "/*ts3*/");

verify.completions({ marker: ["ts1", "ts2"], exact: ["aaa", "bbb", "ccc"] });
verify.completions({ marker: ["ts3"], exact: ["name", "id"] });