-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathpasteEdits.ts
192 lines (182 loc) · 8.53 KB
/
pasteEdits.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import {
CancellationToken,
codefix,
Debug,
fileShouldUseJavaScriptRequire,
findAncestor,
findIndex,
findTokenOnLeftOfPosition,
forEachChild,
formatting,
getNewLineOrDefaultFromHost,
getQuotePreference,
getTokenAtPosition,
isIdentifier,
Program,
rangeContainsPosition,
rangeContainsRange,
SourceFile,
Statement,
SymbolFlags,
textChanges,
TextRange,
UserPreferences,
} from "./_namespaces/ts.js";
import { addTargetFileImports } from "./refactors/helpers.js";
import {
addExportsInOldFile,
getExistingLocals,
getUsageInfo,
} from "./refactors/moveToFile.js";
import {
CodeFixContextBase,
FileTextChanges,
LanguageServiceHost,
PasteEdits,
} from "./types.js";
const fixId = "providePostPasteEdits";
/** @internal */
export function pasteEditsProvider(
targetFile: SourceFile,
pastedText: string[],
pasteLocations: TextRange[],
copiedFrom: { file: SourceFile; range: TextRange[]; } | undefined,
host: LanguageServiceHost,
preferences: UserPreferences,
formatContext: formatting.FormatContext,
cancellationToken: CancellationToken,
): PasteEdits {
const changes: FileTextChanges[] = textChanges.ChangeTracker.with({ host, formatContext, preferences }, changeTracker => pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changeTracker));
return { edits: changes, fixId };
}
interface CopiedFromInfo {
file: SourceFile;
range: TextRange[];
}
function pasteEdits(
targetFile: SourceFile,
pastedText: string[],
pasteLocations: TextRange[],
copiedFrom: CopiedFromInfo | undefined,
host: LanguageServiceHost,
preferences: UserPreferences,
formatContext: formatting.FormatContext,
cancellationToken: CancellationToken,
changes: textChanges.ChangeTracker,
) {
let actualPastedText: string | undefined;
if (pastedText.length !== pasteLocations.length) {
actualPastedText = pastedText.length === 1 ? pastedText[0] : pastedText.join(getNewLineOrDefaultFromHost(formatContext.host, formatContext.options));
}
const statements: Statement[] = [];
let newText = targetFile.text;
for (let i = pasteLocations.length - 1; i >= 0; i--) {
const { pos, end } = pasteLocations[i];
newText = actualPastedText ? newText.slice(0, pos) + actualPastedText + newText.slice(end) : newText.slice(0, pos) + pastedText[i] + newText.slice(end);
}
let importAdder: codefix.ImportAdder;
Debug.checkDefined(host.runWithTemporaryFileUpdate).call(host, targetFile.fileName, newText, (updatedProgram: Program, originalProgram: Program | undefined, updatedFile: SourceFile) => {
importAdder = codefix.createImportAdder(updatedFile, updatedProgram, preferences, host);
if (copiedFrom?.range) {
Debug.assert(copiedFrom.range.length === pastedText.length);
copiedFrom.range.forEach(copy => {
const statementsInSourceFile = copiedFrom.file.statements;
const startNodeIndex = findIndex(statementsInSourceFile, s => s.end > copy.pos);
if (startNodeIndex === -1) return undefined;
let endNodeIndex = findIndex(statementsInSourceFile, s => s.end >= copy.end, startNodeIndex);
/**
* [|console.log(a);
* |]
* console.log(b);
*/
if (endNodeIndex !== -1 && copy.end <= statementsInSourceFile[endNodeIndex].getStart()) {
endNodeIndex--;
}
statements.push(...statementsInSourceFile.slice(startNodeIndex, endNodeIndex === -1 ? statementsInSourceFile.length : endNodeIndex + 1));
});
Debug.assertIsDefined(originalProgram, "no original program found");
const originalProgramTypeChecker = originalProgram.getTypeChecker();
const usageInfoRange = getUsageInfoRangeForPasteEdits(copiedFrom);
const usage = getUsageInfo(copiedFrom.file, statements, originalProgramTypeChecker, getExistingLocals(updatedFile, statements, originalProgramTypeChecker), usageInfoRange);
const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, originalProgram, host, !!copiedFrom.file.commonJsModuleIndicator);
addExportsInOldFile(copiedFrom.file, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax);
addTargetFileImports(copiedFrom.file, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, originalProgramTypeChecker, updatedProgram, importAdder);
}
else {
const context: CodeFixContextBase = {
sourceFile: updatedFile,
program: originalProgram!,
cancellationToken,
host,
preferences,
formatContext,
};
// `updatedRanges` represent the new ranges that account for the offset changes caused by pasting new text and
// `offset` represents by how much the starting position of `pasteLocations` needs to be changed.
//
// We iterate over each updated range to get the node that wholly encloses the updated range.
// For each child of that node, we checked for unresolved identifiers
// within the updated range and try importing it.
let offset = 0;
pasteLocations.forEach((location, i) => {
const oldTextLength = location.end - location.pos;
const textToBePasted = actualPastedText ?? pastedText[i];
const startPos = location.pos + offset;
const endPos = startPos + textToBePasted.length;
const range: TextRange = { pos: startPos, end: endPos };
offset += textToBePasted.length - oldTextLength;
const enclosingNode = findAncestor(
getTokenAtPosition(context.sourceFile, range.pos),
ancestorNode => rangeContainsRange(ancestorNode, range),
);
if (!enclosingNode) return;
forEachChild(enclosingNode, function importUnresolvedIdentifiers(node) {
const isImportCandidate = isIdentifier(node) &&
rangeContainsPosition(range, node.getStart(updatedFile)) &&
!updatedProgram?.getTypeChecker().resolveName(
node.text,
node,
SymbolFlags.All,
/*excludeGlobals*/ false,
);
if (isImportCandidate) {
return importAdder.addImportForUnresolvedIdentifier(
context,
node,
/*useAutoImportProvider*/ true,
);
}
node.forEachChild(importUnresolvedIdentifiers);
});
});
}
importAdder.writeFixes(changes, getQuotePreference(copiedFrom ? copiedFrom.file : targetFile, preferences));
});
/**
* If there are no import fixes, getPasteEdits should return without making any changes to the file.
*/
if (!importAdder!.hasFixes()) {
return;
}
pasteLocations.forEach((paste, i) => {
changes.replaceRangeWithText(
targetFile,
{ pos: paste.pos, end: paste.end },
actualPastedText ?? pastedText[i],
);
});
}
/**
* Adjusts the range for `getUsageInfo` to correctly include identifiers at the edges of the copied text.
*/
function getUsageInfoRangeForPasteEdits({ file: sourceFile, range }: CopiedFromInfo) {
const pos = range[0].pos;
const end = range[range.length - 1].end;
const startToken = getTokenAtPosition(sourceFile, pos);
const endToken = findTokenOnLeftOfPosition(sourceFile, pos) ?? getTokenAtPosition(sourceFile, end);
// Since the range is only used to check identifiers, we do not need to adjust range when the tokens at the edges are not identifiers.
return {
pos: isIdentifier(startToken) && pos <= startToken.getStart(sourceFile) ? startToken.getFullStart() : pos,
end: isIdentifier(endToken) && end === endToken.getEnd() ? textChanges.getAdjustedEndPosition(sourceFile, endToken, {}) : end,
};
}