Skip to content
Merged
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
76 changes: 1 addition & 75 deletions src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
CancellationToken,
canUsePropertyAccess,
CaseBlock,
CaseClause,
cast,
CharacterCodes,
ClassElement,
Expand Down Expand Up @@ -43,13 +42,11 @@ import {
createTextSpanFromRange,
Debug,
Declaration,
DefaultClause,
Diagnostics,
diagnosticToString,
displayPart,
EmitHint,
EmitTextWriter,
endsWith,
EntityName,
EnumMember,
escapeSnippetText,
Expand Down Expand Up @@ -140,7 +137,6 @@ import {
isConstructorDeclaration,
isContextualKeyword,
isDeclarationName,
isDefaultClause,
isDeprecatedDeclaration,
isEntityName,
isEnumMember,
Expand Down Expand Up @@ -185,7 +181,6 @@ import {
isKeyword,
isKnownSymbol,
isLabeledStatement,
isLiteralExpression,
isLiteralImportTypeNode,
isMemberName,
isMethodDeclaration,
Expand Down Expand Up @@ -276,6 +271,7 @@ import {
ModuleReference,
moduleResolutionSupportsPackageJsonExportsAndImports,
NamedImportBindings,
newCaseClauseTracker,
Node,
NodeArray,
NodeBuilderFlags,
Expand All @@ -288,7 +284,6 @@ import {
ObjectTypeDeclaration,
or,
ParenthesizedTypeNode,
parseBigInt,
positionBelongsToNode,
positionIsASICandidate,
positionsAreOnSameLine,
Expand Down Expand Up @@ -1105,75 +1100,6 @@ function getExhaustiveCaseSnippets(
return undefined;
}

interface CaseClauseTracker {
addValue(value: string | number): void;
hasValue(value: string | number | PseudoBigInt): boolean;
}

function newCaseClauseTracker(checker: TypeChecker, clauses: readonly (CaseClause | DefaultClause)[]): CaseClauseTracker {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think it makes sense to move this out to a shared space so both completions and stringCompletions can use it - but if you prefer some other solution, let me know.

const existingStrings = new Set<string>();
const existingNumbers = new Set<number>();
const existingBigInts = new Set<string>();

for (const clause of clauses) {
if (!isDefaultClause(clause)) {
if (isLiteralExpression(clause.expression)) {
const expression = clause.expression;
switch (expression.kind) {
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.StringLiteral:
existingStrings.add(expression.text);
break;
case SyntaxKind.NumericLiteral:
existingNumbers.add(parseInt(expression.text));
break;
case SyntaxKind.BigIntLiteral:
const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text);
if (parsedBigInt) {
existingBigInts.add(pseudoBigIntToString(parsedBigInt));
}
break;
}
}
else {
const symbol = checker.getSymbolAtLocation(clause.expression);
if (symbol && symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
const enumValue = checker.getConstantValue(symbol.valueDeclaration);
if (enumValue !== undefined) {
addValue(enumValue);
}
}
}
}
}

return {
addValue,
hasValue,
};

function addValue(value: string | number) {
switch (typeof value) {
case "string":
existingStrings.add(value);
break;
case "number":
existingNumbers.add(value);
}
}

function hasValue(value: string | number | PseudoBigInt): boolean {
switch (typeof value) {
case "string":
return existingStrings.has(value);
case "number":
return existingNumbers.has(value);
case "object":
return existingBigInts.has(pseudoBigIntToString(value));
}
}
}

function typeNodeToExpression(typeNode: TypeNode, languageVersion: ScriptTarget, quotePreference: QuotePreference): Expression | undefined {
switch (typeNode.kind) {
case SyntaxKind.TypeReference:
Expand Down
11 changes: 8 additions & 3 deletions src/services/stringCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
arrayFrom,
CallLikeExpression,
CancellationToken,
CaseClause,
changeExtension,
CharacterCodes,
combinePaths,
Expand Down Expand Up @@ -94,6 +95,7 @@ import {
moduleResolutionUsesNodeModules,
ModuleSpecifierEnding,
moduleSpecifiers,
newCaseClauseTracker,
Node,
normalizePath,
normalizeSlashes,
Expand Down Expand Up @@ -275,7 +277,7 @@ function stringLiteralCompletionDetails(name: string, location: Node, completion
return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
}
case StringLiteralCompletionKind.Types:
return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined;
return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.string, [textPart(name)]) : undefined;
default:
return Debug.assertNever(completion);
}
Expand Down Expand Up @@ -415,12 +417,15 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL
// var y = require("/*completion position*/");
// export * from "/*completion position*/";
return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) };

case SyntaxKind.CaseClause:
const tracker = newCaseClauseTracker(typeChecker, (node.parent as CaseClause).parent.clauses);
const literals = fromContextualType().types.filter(literal => !tracker.hasValue(literal.value));
return { kind: StringLiteralCompletionKind.Types, types: literals, isNewIdentifier: false };
default:
return fromContextualType();
}

function fromContextualType(): StringLiteralCompletion {
function fromContextualType(): StringLiteralCompletionsFromTypes {
// Get completion for string literal from string literal type
// i.e. var x: "hi" | "hello" = "/*completion position*/"
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, ContextFlags.Completions)), isNewIdentifier: false };
Expand Down
79 changes: 79 additions & 0 deletions src/services/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
Debug,
Declaration,
Decorator,
DefaultClause,
defaultMaximumTruncationLength,
DeleteExpression,
Diagnostic,
Expand All @@ -53,6 +54,7 @@ import {
EmitHint,
emptyArray,
EndOfFileToken,
endsWith,
ensureScriptKind,
EqualityOperator,
escapeString,
Expand Down Expand Up @@ -138,10 +140,12 @@ import {
isDeclaration,
isDeclarationName,
isDecorator,
isDefaultClause,
isDeleteExpression,
isElementAccessExpression,
isEntityName,
isEnumDeclaration,
isEnumMember,
isExportAssignment,
isExportDeclaration,
isExportSpecifier,
Expand Down Expand Up @@ -188,6 +192,7 @@ import {
isKeyword,
isLabeledStatement,
isLet,
isLiteralExpression,
isLiteralTypeNode,
isMappedTypeNode,
isModifier,
Expand Down Expand Up @@ -281,13 +286,16 @@ import {
or,
OrganizeImports,
PackageJsonDependencyGroup,
parseBigInt,
pathIsRelative,
PrefixUnaryExpression,
Program,
ProjectPackageJsonInfo,
PropertyAccessExpression,
PropertyAssignment,
PropertyName,
PseudoBigInt,
pseudoBigIntToString,
QualifiedName,
RefactorContext,
Scanner,
Expand Down Expand Up @@ -4037,3 +4045,74 @@ export function jsxModeNeedsExplicitImport(jsx: JsxEmit | undefined) {
export function isSourceFileFromLibrary(program: Program, node: SourceFile) {
return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node);
}

/** @internal */
export interface CaseClauseTracker {
addValue(value: string | number): void;
hasValue(value: string | number | PseudoBigInt): boolean;
}

/** @internal */
export function newCaseClauseTracker(checker: TypeChecker, clauses: readonly (CaseClause | DefaultClause)[]): CaseClauseTracker {
const existingStrings = new Set<string>();
const existingNumbers = new Set<number>();
const existingBigInts = new Set<string>();

for (const clause of clauses) {
if (!isDefaultClause(clause)) {
if (isLiteralExpression(clause.expression)) {
const expression = clause.expression;
switch (expression.kind) {
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.StringLiteral:
existingStrings.add(expression.text);
break;
case SyntaxKind.NumericLiteral:
existingNumbers.add(parseInt(expression.text));
break;
case SyntaxKind.BigIntLiteral:
const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text);
if (parsedBigInt) {
existingBigInts.add(pseudoBigIntToString(parsedBigInt));
}
break;
}
}
else {
const symbol = checker.getSymbolAtLocation(clause.expression);
if (symbol && symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
const enumValue = checker.getConstantValue(symbol.valueDeclaration);
if (enumValue !== undefined) {
addValue(enumValue);
}
}
}
}
}

return {
addValue,
hasValue,
};

function addValue(value: string | number) {
switch (typeof value) {
case "string":
existingStrings.add(value);
break;
case "number":
existingNumbers.add(value);
}
}

function hasValue(value: string | number | PseudoBigInt): boolean {
switch (typeof value) {
case "string":
return existingStrings.has(value);
case "number":
return existingNumbers.has(value);
case "object":
return existingBigInts.has(pseudoBigIntToString(value));
}
}
}
14 changes: 13 additions & 1 deletion tests/cases/fourslash/switchCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@
//// return 1;
//// case /*2*/
//// }
//// declare const f2: 'foo' | 'bar' | 'baz';
//// switch (f2) {
//// case 'bar':
//// return 1;
//// case '/*3*/'
//// }

verify.completions(
{
Expand All @@ -26,5 +32,11 @@ verify.completions(
isNewIdentifierLocation: false,
excludes: "1",
includes: ["2", "3"],
},
{
marker: "3",
isNewIdentifierLocation: false,
includes: ["foo", "baz"],
excludes: "bar",
}
);
);