|
| 1 | +/* @internal */ |
| 2 | +namespace ts.codefix { |
| 3 | + const fixId = "fixAwaitInSyncFunction"; |
| 4 | + const errorCodes = [ |
| 5 | + Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, |
| 6 | + Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, |
| 7 | + ]; |
| 8 | + registerCodeFix({ |
| 9 | + errorCodes, |
| 10 | + getCodeActions(context) { |
| 11 | + const { sourceFile, span } = context; |
| 12 | + const node = getNode(sourceFile, span.start); |
| 13 | + if (!node) return undefined; |
| 14 | + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, node)); |
| 15 | + return [{ description: getLocaleSpecificMessage(Diagnostics.Convert_to_async), changes, fixId }]; |
| 16 | + }, |
| 17 | + fixIds: [fixId], |
| 18 | + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => |
| 19 | + doChange(changes, context.sourceFile, getNode(diag.file, diag.start!))), |
| 20 | + }); |
| 21 | + |
| 22 | + function getNode(sourceFile: SourceFile, pos: number): FunctionLikeDeclaration { |
| 23 | + const token = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); |
| 24 | + const containingFunction = getContainingFunction(token); |
| 25 | + if (!isFunctionLikeDeclaration(containingFunction) || |
| 26 | + isConstructorDeclaration(containingFunction) || |
| 27 | + isGetAccessorDeclaration(containingFunction) || |
| 28 | + isSetAccessorDeclaration(containingFunction)) return; |
| 29 | + return containingFunction; |
| 30 | + } |
| 31 | + |
| 32 | + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, decl: FunctionLikeDeclaration) { |
| 33 | + const asyncToken = createToken(SyntaxKind.AsyncKeyword); |
| 34 | + const modifiers = decl.modifiers ? decl.modifiers.concat(asyncToken) : createNodeArray([asyncToken]); |
| 35 | + let changed; |
| 36 | + switch (decl.kind) { |
| 37 | + case SyntaxKind.MethodDeclaration: |
| 38 | + changed = createMethod(decl.decorators, modifiers, decl.asteriskToken, decl.name, decl.questionToken, decl.typeParameters, decl.parameters, decl.type, decl.body); |
| 39 | + break; |
| 40 | + case SyntaxKind.FunctionExpression: |
| 41 | + changed = createFunctionExpression(modifiers, decl.asteriskToken, decl.name, decl.typeParameters, decl.parameters, decl.type, decl.body); |
| 42 | + break; |
| 43 | + case SyntaxKind.FunctionDeclaration: |
| 44 | + changed = createFunctionDeclaration(decl.decorators, modifiers, decl.asteriskToken, decl.name, decl.typeParameters, decl.parameters, decl.type, decl.body); |
| 45 | + break; |
| 46 | + case SyntaxKind.ArrowFunction: |
| 47 | + changed = createArrowFunction(modifiers, decl.typeParameters, decl.parameters, decl.type, decl.equalsGreaterThanToken, decl.body); |
| 48 | + break; |
| 49 | + } |
| 50 | + changes.replaceNode(sourceFile, decl, changed); |
| 51 | + } |
| 52 | +} |
0 commit comments