Skip to content
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

Provide snippet completions for @param in JSDoc #53260

Merged
merged 8 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
193 changes: 191 additions & 2 deletions src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
addToSeen,
append,
BinaryExpression,
BindingElement,
BindingPattern,
BreakOrContinueStatement,
CancellationToken,
canUsePropertyAccess,
Expand Down Expand Up @@ -44,6 +46,7 @@ import {
Diagnostics,
diagnosticToString,
displayPart,
DotDotDotToken,
EmitHint,
EmitTextWriter,
EntityName,
Expand Down Expand Up @@ -79,6 +82,7 @@ import {
getEscapedTextOfIdentifierOrLiteral,
getExportInfoMap,
getFormatCodeSettingsForWriting,
getJSDocParameterTags,
getLanguageVariant,
getLeftmostAccessExpression,
getLineAndCharacterOfPosition,
Expand Down Expand Up @@ -343,6 +347,7 @@ import {
tokenToString,
tryCast,
tryGetImportFromModuleSpecifier,
tryGetTextOfPropertyName,
Type,
TypeChecker,
TypeElement,
Expand Down Expand Up @@ -706,10 +711,14 @@ export function getCompletionsAtPosition(
return response;
case CompletionDataKind.JsDocTagName:
// If the current position is a jsDoc tag name, only tag names should be provided for completion
return jsdocCompletionInfo(JsDoc.getJSDocTagNameCompletions());
return jsdocCompletionInfo([
...JsDoc.getJSDocTagNameCompletions(),
...getJSDocParameterCompletions(sourceFile, position, preferences, compilerOptions, /*tagNameOnly*/ true)]);
case CompletionDataKind.JsDocTag:
// If the current position is a jsDoc tag, only tags should be provided for completion
return jsdocCompletionInfo(JsDoc.getJSDocTagCompletions());
return jsdocCompletionInfo([
...JsDoc.getJSDocTagCompletions(),
...getJSDocParameterCompletions(sourceFile, position, preferences, compilerOptions, /*tagNameOnly*/ false)]);
case CompletionDataKind.JsDocParameterName:
return jsdocCompletionInfo(JsDoc.getJSDocParameterNameCompletions(completionData.tag));
case CompletionDataKind.Keywords:
Expand Down Expand Up @@ -826,6 +835,186 @@ function jsdocCompletionInfo(entries: CompletionEntry[]): CompletionInfo {
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries };
}

function getJSDocParameterCompletions(
sourceFile: SourceFile,
position: number,
preferences: UserPreferences,
options: CompilerOptions,
tagNameOnly: boolean): CompletionEntry[] {
const currentToken = getTokenAtPosition(sourceFile, position);
if (!isJSDocTag(currentToken) && !isJSDoc(currentToken)) {
return [];
}
const jsDoc = isJSDoc(currentToken) ? currentToken : currentToken.parent;
if (!isJSDoc(jsDoc)) {
return [];
}
const func = jsDoc.parent;
if (!isFunctionLike(func)) {
return [];
}

const isJs = isSourceFileJS(sourceFile);
const isSnippet = preferences.includeCompletionsWithSnippetText || undefined;
const paramTagCount = jsDoc.tags?.filter(tag => isJSDocParameterTag(tag) && tag.getEnd() <= position).length;
Copy link
Member

Choose a reason for hiding this comment

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

We have a countWhere utility

return mapDefined(func.parameters, param => {
if (getJSDocParameterTags(param).length) {
return undefined; // Parameter is already annotated.
}
if (isIdentifier(param.name)) { // Named parameter
const tabstopCounter = { tabstop: 1 };
const paramName = param.name.text;
let snippetText = getJSDocParamAnnotation(paramName, param.initializer, param.dotDotDotToken, isJs, /*isObject*/ false, /*isSnippet*/ true, tabstopCounter);
let insertText = getJSDocParamAnnotation(paramName, param.initializer, param.dotDotDotToken, isJs, /*isObject*/ false, /*isSnippet*/ false);
if (tagNameOnly) { // Remove `@`
insertText = insertText.slice(1);
snippetText = snippetText.slice(1);
}
return {
name: insertText,
kind: ScriptElementKind.parameterElement,
sortText: SortText.LocationPriority,
insertText: isSnippet ? snippetText : undefined,
isSnippet,
};
}
else if (param.parent.parameters.indexOf(param) === paramTagCount) { // Destructuring parameter; do it positionally
const paramPath = `param${paramTagCount}`;
const insertTextResult =
generateJSDocParamTagsForDestructuring(paramPath, param.name, param.initializer, param.dotDotDotToken, isJs, /*isSnippet*/ false);
const snippetTextResult =
generateJSDocParamTagsForDestructuring(paramPath, param.name, param.initializer, param.dotDotDotToken, isJs, /*isSnippet*/ true);
let insertText = insertTextResult.join(getNewLineCharacter(options) + "* ");
let snippetText = snippetTextResult.join(getNewLineCharacter(options) + "* ");
if (tagNameOnly) { // Remove `@`
insertText = insertText.slice(1);
snippetText = snippetText.slice(1);
}
return {
name: insertText,
kind: ScriptElementKind.parameterElement,
sortText: SortText.LocationPriority,
insertText: isSnippet ? snippetText : undefined,
isSnippet,
};
}
});
}

function generateJSDocParamTagsForDestructuring(
path: string,
pattern: BindingPattern,
initializer: Expression | undefined,
dotDotDotToken: DotDotDotToken | undefined,
isJs: boolean,
isSnippet: boolean): string[] {
if (!isJs) {
return [getJSDocParamAnnotation(path, initializer, dotDotDotToken, isJs, /*isObject*/ false, isSnippet, { tabstop: 1 })];
}
return patternWorker(path, pattern, initializer, dotDotDotToken, { tabstop: 1 });

function patternWorker(
path: string,
pattern: BindingPattern,
initializer: Expression | undefined,
dotDotDotToken: DotDotDotToken | undefined,
counter: TabStopCounter): string[] {
if (isObjectBindingPattern(pattern) && !dotDotDotToken) {
const oldTabstop = counter.tabstop;
const childCounter = { tabstop: oldTabstop };
const rootParam = getJSDocParamAnnotation(path, initializer, dotDotDotToken, isJs, /*isObject*/ true, isSnippet, childCounter);
let childTags: string[] | undefined = [];
for (const element of pattern.elements) {
const elementTags = elementWorker(path, element, childCounter);
if (!elementTags) {
childTags = undefined;
break;
}
else {
childTags.push(...elementTags);
}
}
if (childTags) {
counter.tabstop = childCounter.tabstop;
return [rootParam, ...childTags];
}
}
return [getJSDocParamAnnotation(path, initializer, dotDotDotToken, isJs, /*isObject*/ false, isSnippet, counter)];
}

// Assumes binding element is inside object binding pattern.
// We can't really deeply annotate an array binding pattern.
function elementWorker(path: string, element: BindingElement, counter: TabStopCounter): string[] | undefined {
if ((!element.propertyName && isIdentifier(element.name)) || isIdentifier(element.name)) { // `{ b }` or `{ b: newB }`
const propertyName = element.propertyName ? tryGetTextOfPropertyName(element.propertyName) : element.name.text;
if (!propertyName) {
return undefined;
}
const paramName = `${path}.${propertyName}`;
return [getJSDocParamAnnotation(paramName, element.initializer, element.dotDotDotToken, isJs, /*isObject*/ false, isSnippet, counter)];
}
else if (element.propertyName) { // `{ b: {...} }` or `{ b: [...] }`
const propertyName = tryGetTextOfPropertyName(element.propertyName);
return propertyName
&& patternWorker(`${path}.${propertyName}`, element.name, element.initializer, element.dotDotDotToken, counter);
}
return undefined;
}
}

interface TabStopCounter {
tabstop: number;
}

function getJSDocParamAnnotation(
paramName: string,
initializer: Expression | undefined,
dotDotDotToken: DotDotDotToken | undefined,
isJs: boolean,
isObject: boolean,
isSnippet: boolean,
tabstopCounter?: TabStopCounter) {
if (isSnippet) {
Debug.assertIsDefined(tabstopCounter);
}
if (initializer) {
paramName = getJSDocParamNameWithInitializer(paramName, initializer);
}
if (isSnippet) {
paramName = escapeSnippetText(paramName);
}
if (isJs) {
let type: string;
if (isObject) {
Debug.assert(!dotDotDotToken, `Cannot annotate a rest parameter with type 'Object'.`);
type = "Object";
}
else {
if (isSnippet) {
type = `\${${tabstopCounter!.tabstop++}:*}`;
}
else {
type = "*";
}
}
const dotDotDot = !isObject && dotDotDotToken ? "..." : "";
const description = isSnippet ? `\${${tabstopCounter!.tabstop++}}` : "";
return `@param {${dotDotDot}${type}} ${paramName} ${description}`;
}
else {
const description = isSnippet ? `\${${tabstopCounter!.tabstop++}}` : "";
return `@param ${paramName} ${description}`;
}
}

function getJSDocParamNameWithInitializer(paramName: string, initializer: Expression): string {
const initializerText = initializer.getText().trim();
if (initializerText.includes("\n") || initializerText.length > 80) {
return `[${paramName}]`;
}
return `[${paramName}=${initializerText}]`;
}

function keywordToCompletionEntry(keyword: TokenSyntaxKind) {
return {
name: tokenToString(keyword)!,
Expand Down
Loading