8000 inferFromUsage codefix now emits JSDoc in JS files by sandersn · Pull Request #27610 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content

inferFromUsage codefix now emits JSDoc in JS files #27610

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 24 commits into from
Oct 9, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
1bc0cd1
Now adding @type to variable declarations, at least
sandersn Sep 28, 2018
e34bf54
Improve @param output and add test
sandersn Sep 28, 2018
0f4a800
Add some js/inferFromUsage tests and fixes
sandersn Oct 1, 2018
be3577c
Fix @typedef refactor
sandersn Oct 2, 2018
bf5529b
Emit JSDoc optional parameters
sandersn Oct 2, 2018
4ee4d69
Get rest of existing tests working
sandersn Oct 3, 2018
9ae4a99
Merge branch 'master' into js/infer-from-usage
sandersn Oct 4, 2018
09ae612
Merge branch 'master' into js/infer-from-usage
sandersn Oct 4, 2018
e99220f
Merge branch 'master' into js/infer-from-usage
sandersn Oct 5, 2018
ae062b2
Correct location of comments
sandersn Oct 5, 2018
69dec3f
Handle @param blocks
sandersn Oct 5, 2018
b469d9f
Re-add isGet/SetAccessor -- it is part of the API
sandersn Oct 5, 2018
56bcf3f
Move isSet/GetAccessor back to the original location
sandersn Oct 5, 2018
84b08c0
Merge branch 'master' into js/infer-from-usage
sandersn Oct 5, 2018
a3aae7b
Oh no I missed a newline and a space
sandersn Oct 5, 2018
d22961a
Switch to an object type
sandersn Oct 5, 2018
3cc99ea
A lot of cleanup
sandersn Oct 5, 2018
31db1ce
Move and delegate to annotateJSDocParameters
sandersn Oct 8, 2018
6b0be8b
Merge branch 'master' into js/infer-from-usage
sandersn Oct 8, 2018
edcb30d
Address PR comments
sandersn Oct 8, 2018
d129e32
Lint: newline problems!!!!
sandersn Oct 8, 2018
e3cf787
Switch another call to getNonformattedText
sandersn Oct 9, 2018
bc32d3c
Merge branch 'master' into js/infer-from-usage
sandersn Oct 9, 2018
5066880
Update baseline missed after merge
sandersn Oct 9, 2018
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
Prev Previous commit
Next Next commit
Handle @param blocks
1. Format multiple params nicely in a single-multiline block.
2. Generate only params that haven't already been documented. Existing
documentation is not touched.
  • Loading branch information
sandersn committed Oct 5, 2018
commit 69dec3f7ad975ff94a0587e3ce8593f4f36a6d18
40 changes: 33 additions & 7 deletions src/services/codefixes/inferFromUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,25 +165,51 @@ namespace ts.codefix {
return;
}

zipWith<ParameterDeclaration, [Type | undefined, boolean], void>(containingFunction.parameters, types, (parameter, [type, isOptionalParameter]) => {
if (!(parameter.type || isInJSFile(parameter) && getJSDocType(parameter)) && !parameter.initializer) {
annotate(changes, sourceFile, parameter, type, program, isOptionalParameter);
if (isInJSFile(containingFunction)) {
annotateJSDocParameters(changes, sourceFile, containingFunction.parameters, types, program);
}
else {
zipWith<ParameterDeclaration, [Type | undefined, boolean], void>(containingFunction.parameters, types, (parameter, typair) => {
if (!parameter.type && !parameter.initializer) {
annotate(changes, sourceFile, parameter, typair[0], program);
}
});
}
}

function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, params: NodeArray<ParameterDeclaration>, types: [Type | undefined, boolean][], program: Program): void {
const triples = [];
for (let i = 0; i < params.length; i++) {
const param = params[i];
const [t, opt] = types[i];
const typeNode = t && getTypeNodeIfAccessible(t, param, program.getTypeChecker());
if (!(param.type || isInJSFile(param) && getJSDocType(param)) && !param.initializer && typeNode) {
triples.push([param, typeNode, opt] as [ParameterDeclaration, TypeNode, boolean]);
}
});
}
changes.tryInsertJSDocParams(sourceFile, triples);
}

function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, cancellationToken: CancellationToken): void {
const param = firstOrUndefined(setAccessorDeclaration.parameters);
if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) {
const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) ||
inferTypeForVariableFromUsage(param.name, program, cancellationToken);
annotate(changes, sourceFile, param, type, program);
if (isInJSFile(setAccessorDeclaration)) {
const typeNode = type && getTypeNodeIfAccessible(type, param, program.getTypeChecker());
if (typeNode) {
changes.tryInsertJSDocParams(sourceFile, [[param, typeNode, /*isOptionalParameter*/ false]]);
}
}
else {
annotate(changes, sourceFile, param, type, program);
}
}
}

function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program, isOptionalParameter?: boolean): void {
function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program): void {
const typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker());
if (typeNode) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode, isOptionalParameter);
if (typeNode) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
}

function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, checker: TypeChecker): TypeNode | undefined {
Expand Down
32 changes: 20 additions & 12 deletions src/services/textChanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,10 +365,24 @@ namespace ts.textChanges {
this.replaceRangeWithText(sourceFile, createRange(pos), text);
}

public tryInsertJSDocParams(sourceFile: SourceFile, annotations: [ParameterDe 8000 claration, TypeNode, boolean][]) {
const parent = annotations[0][0].parent;
const indent = getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character;
let commentText = "\n";
for (const [node, type, isOptionalParameter] of annotations) {
if (isIdentifier(node.name)) {
const printed = createPrinter().printNode(EmitHint.Unspecified, type, sourceFile);
commentText += this.printJSDocParameter(indent, printed, node.name, isOptionalParameter);
}
}
commentText += " ".repeat(indent + 1);
this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText, CommentKind.Jsdoc);
}

/** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
public tryInsertTypeAnnotation(sourceFile: SourceFile, topNode: TypeAnnotatable, type: TypeNode, isOptionalParameter?: boolean): void {
public tryInsertTypeAnnotation(sourceFile: SourceFile, topNode: TypeAnnotatable, type: TypeNode): void {
if (isInJSFile(sourceFile) && topNode.kind !== SyntaxKind.PropertySignature) {
return this.tryInsertJSDocType(sourceFile, topNode, type, isOptionalParameter);
return this.tryInsertJSDocType(sourceFile, topNode, type);
}
const node = topNode as SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration | PropertySignature;
let endNode: Node | undefined;
Expand All @@ -391,16 +405,10 @@ namespace ts.textChanges {
* TODO: Might need to only disallow node from being a parameterdecl, propertydecl, propertysig
* (or correctly handle parameterdecl by walking up and adding a param, at least)
*/
public tryInsertJSDocType(sourceFile: SourceFile, node: Node, type: TypeNode, isOptionalParameter: boolean | undefined): void {
// TODO: Parameter code needs to be MUCH smarter (multiple parameters are ugly, etc)
// TODO: Parameter probably shouldn't need to manually unescape its text
public tryInsertJSDocType(sourceFile: SourceFile, node: Node, type: TypeNode): void {
Copy link
Member

Choose a reason for hiding this comment

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

tryInsertJSDocType [](start = 15, length = 18)

I feel like I'm missing something obvious, but why "try"?

const printed = createPrinter().printNode(EmitHint.Unspecified, type, sourceFile);
Copy link

Choose a reason for hiding this comment

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

Think this could also use getNonformattedText.

let commentText;
if (isParameter(node) && isIdentifier(node.name)) {
commentText = this.printJSDocParameter(printed, node.name, isOptionalParameter);
node = node.parent;
}
else if (isGetAccessorDeclaration(node)) {
if (isGetAccessorDeclaration(node)) {
commentText = ` @return {${printed}} `;
}
else {
Expand All @@ -411,12 +419,12 @@ namespace ts.textChanges {
// this.replaceRangeWithText <-- SOMEDAY, when we support existing ones
}

private printJSDocParameter(printed: string, name: Identifier, isOptionalParameter: boolean | undefined) {
private printJSDocParameter(indent: number, printed: string, name: Identifier, isOptionalParameter: boolean | undefined) {
let printName = unescapeLeadingUnderscores(name.escapedText);
if (isOptionalParameter) {
printName = `[${printName}]`;
}
return ` @param {${printed}} ${printName} `;
return " ".repeat(indent) + ` * @param {${printed}} ${printName}\n`;
}

public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: ReadonlyArray<TypeParameterDeclaration>): void {
Expand Down
4 changes: 3 additions & 1 deletion tests/cases/fourslash/codeFixInferFromUsageCallJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ verify.codeFixAll({
fixId: "inferFromUsage",
fixAllDescription: "Infer all types from usage",
newFileContent:
`/** @param {() => void} b */
`/**
* @param {() => void} b
*/
function wat(b) {
b();
}`});
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@


verify.fileAfterCodeFix(
`/** @param {number} a */
/** @param {string} b */
/** @param {{ a: number; }} c */
/** @param {{ shouldNotBeHere: number; }} d */
/** @param {(string | number)[]} d */
`/**
* @param {number} a
* @param {string} b
* @param {{ a: number; }} c
* @param {{ shouldNotBeHere: number; }} d
* @param {(string | number)[]} d
*/
function f(a, b, c, d, e = 0, ...d ) {
}
f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string");`, undefined, 6);
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
////}

verify.fileAfterCodeFix(
`/** @param {number[]} a */
`/**
* @param {number[]} a
*/
function f(a) {
return a[0] + 1;
}`, undefined, 2);
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
////f(1);

verify.fileAfterCodeFix(
`/** @param {number} [a] */
`/**
* @param {number} [a]
*/
function f(a) {
a;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// <reference path='fourslash.ts' />

// @allowJs: true
// @checkJs: true
// @noImplicitAny: true
// @strictNullChecks: true
// @Filename: important.js
/////**
//// * @param {*} y
//// */
////function f(x, y, z) {
//// return x
////}
////f(1, 2, 3)

verify.fileAfterCodeFix(
`
/**
* @param {*} y
*/
/**
* @param {number} x
* @param {number} z
*/
function f(x, y, z) {
return x
}
f(1, 2, 3)
`, undefined, 2);
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
////}

verify.fileAfterCodeFix(
`/** @param {{ b: { c: any; }; }} a */
/** @param {{ n: () => number; }} m */
/** @param {{ y: { z: number[]; }; }} x */
`/**
* @param {{ b: { c: any; }; }} a
* @param {{ n: () => number; }} m
* @param {{ y: { z: number[]; }; }} x
*/
function foo(a, m, x) {
a.b.c;

Expand Down
4 changes: 3 additions & 1 deletion tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@

verify.fileAfterCodeFix(
`/** @param {number} a */
/** @param {(string | boolean)[]} rest */
/**
Copy link

Choose a reason for hiding this comment

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

Could you file this as a bug? We should combine comments, not add a new one.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll file it after merging the PR since the bug depends on being able to emit JSDoc in the first place.

I personally think the current approach is a good compromise and that we'll rarely have to generate partial JSDoc. The bigger lack is untyped JSDoc:

/** @param x Just a description, no type */
function f(x) {
    return x * x
}

* @param {(string | boolean)[]} rest
*/
function f(a, ...rest){
a; rest;
}
Expand Down
4 changes: 3 additions & 1 deletion tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@

verify.fileAfterCodeFix(
`/** @param {number} a */
/** @param {number[]} rest */
/**
* @param {number[]} rest
*/
function f(a, ...rest){
a;
rest.push(22);
Expand Down
4 changes: 3 additions & 1 deletion tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@

verify.fileAfterCodeFix(
`/** @param {number} a */
/** @param {string[]} rest */
/**
* @param {string[]} rest
*/
function f(a: number, ...rest){
a; rest;
}
Expand Down
4 changes: 3 additions & 1 deletion tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
verify.fileAfterCodeFix(
`
class C {
/** @param {number} v */
/**
* @param {number} v
*/
set x(v) {
v;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ verify.codeFix({
description: "Infer type of 'x' from usage",
newFileContent:
`export class C {
/** @param {Promise<typeof import("/a")>} val */
/**
* @param {Promise<typeof import("/a")>} val
Copy link

Choose a reason for hiding this comment

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

I think this should be "./a" when we synthesize the import. Doesn't look so bad in this example but in a real example this might import from /home/myname/projects/typescript/someproject/src/components/a.

Copy link
Member Author

Choose a reason for hiding this comment

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

Wow, nice catch. I asked Wesley and he said that getTypeNodeIfAccessible needs to provide more members to the symbol tracker host (from Program and LanguageServiceHost). It sounds fairly simple, but it's not related to this change, so I'll put it in a separate PR.

*/
set x(val) { val; }
method() { this.x = import("./a"); }
}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

verify.fileAfterCodeFix(
`
class C {/** @param {number} x */
class C {/**
* @param {number} x
*/
m(x) {return x;}}
var c = new C()
c.m(1)`, undefined, 2);
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ verify.codeFix({
index: 2,
description: "Infer parameter types from usage",
newFileContent:
`/** @param {{ [x: string]: any; }} a */
`/**
* @param {{ [x: string]: any; }} a
*/
function f(a) {
return a['hi'];
}`,
Expand Down
10 changes: 7 additions & 3 deletions tests/cases/fourslash/codeFixInferFromUsage_allJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,18 @@ verify.codeFixAll({
fixId: "inferFromUsage",
fixAllDescription: "Infer all types from usage",
newFileContent:
`/** @param {number} x */
/** @param {string} y */
`/**
* @param {number} x
* @param {string} y
*/
function f(x, y) {
x += 0;
y += "";
}

/** @param {number} z */
/**
* @param {number} z
*/
function g(z) {
return z * 2;
}
Expand Down
0