-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathmapCode.ts
324 lines (300 loc) · 9.54 KB
/
mapCode.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import {
Block,
ClassElement,
ClassLikeDeclaration,
createSourceFile,
FileTextChanges,
find,
findAncestor,
findLast,
flatten,
forEach,
formatting,
getTokenAtPosition,
isBlock,
isClassElement,
isClassLike,
isForInOrOfStatement,
isForStatement,
isIfStatement,
isInterfaceDeclaration,
isLabeledStatement,
isNamedDeclaration,
isSourceFile,
isTypeElement,
isWhileStatement,
LanguageServiceHost,
Mutable,
Node,
NodeArray,
or,
some,
SourceFile,
Statement,
SyntaxKind,
textChanges,
TextSpan,
TypeElement,
UserPreferences,
} from "./_namespaces/ts.js";
import { ChangeTracker } from "./textChanges.js";
/** @internal */
export function mapCode(
sourceFile: SourceFile,
contents: string[],
focusLocations: TextSpan[][] | undefined,
host: LanguageServiceHost,
formatContext: formatting.FormatContext,
preferences: UserPreferences,
): FileTextChanges[] {
return textChanges.ChangeTracker.with(
{ host, formatContext, preferences },
changeTracker => {
const parsed = contents.map(c => parse(sourceFile, c));
const flattenedLocations = focusLocations && flatten(focusLocations);
for (const nodes of parsed) {
placeNodeGroup(
sourceFile,
changeTracker,
nodes,
flattenedLocations,
);
}
},
);
}
/**
* Tries to parse something into either "top-level" statements, or into blocks
* of class-context definitions.
*/
function parse(sourceFile: SourceFile, content: string): NodeArray<Node> {
// We're going to speculatively parse different kinds of contexts to see
// which one makes the most sense, and grab the NodeArray from there. Do
// this as lazily as possible.
const nodeKinds = [
{
parse: () =>
createSourceFile(
"__mapcode_content_nodes.ts",
content,
sourceFile.languageVersion,
/*setParentNodes*/ true,
sourceFile.scriptKind,
),
body: (sf: SourceFile) => sf.statements,
},
{
parse: () =>
createSourceFile(
"__mapcode_class_content_nodes.ts",
`class __class {\n${content}\n}`,
sourceFile.languageVersion,
/*setParentNodes*/ true,
sourceFile.scriptKind,
),
body: (cw: SourceFile) => (cw.statements[0] as ClassLikeDeclaration).members,
},
];
const parsedNodes = [];
for (const { parse, body } of nodeKinds) {
const sourceFile = parse();
const bod = body(sourceFile);
if (bod.length && sourceFile.parseDiagnostics.length === 0) {
// If we run into a case with no parse errors, this is likely the right kind.
return bod;
}
// We only want to keep the ones that have some kind of body.
else if (bod.length) {
// Otherwise, we'll need to look at others.
parsedNodes.push({ sourceFile, body: bod });
}
}
// Heuristic: fewer errors = more likely to be the right kind.
parsedNodes.sort(
(a, b) =>
a.sourceFile.parseDiagnostics.length -
b.sourceFile.parseDiagnostics.length,
);
const { body } = parsedNodes[0];
return body;
}
function placeNodeGroup(
originalFile: SourceFile,
changeTracker: ChangeTracker,
changes: NodeArray<Node>,
focusLocations?: TextSpan[],
) {
if (isClassElement(changes[0]) || isTypeElement(changes[0])) {
placeClassNodeGroup(
originalFile,
changeTracker,
changes as NodeArray<ClassElement>,
focusLocations,
);
}
else {
placeStatements(
originalFile,
changeTracker,
changes as NodeArray<Statement>,
focusLocations,
);
}
}
function placeClassNodeGroup(
originalFile: SourceFile,
changeTracker: ChangeTracker,
changes: NodeArray<ClassElement> | NodeArray<TypeElement>,
focusLocations?: TextSpan[],
) {
let classOrInterface;
if (!focusLocations || !focusLocations.length) {
classOrInterface = find(originalFile.statements, or(isClassLike, isInterfaceDeclaration));
}
else {
classOrInterface = forEach(focusLocations, location =>
findAncestor(
getTokenAtPosition(originalFile, location.start),
or(isClassLike, isInterfaceDeclaration),
));
}
if (!classOrInterface) {
// No class? don't insert.
return;
}
const firstMatch = classOrInterface.members.find(member => changes.some(change => matchNode(change, member)));
if (firstMatch) {
// can't be undefined here, since we know we have at least one match.
const lastMatch = findLast(
classOrInterface.members as NodeArray<ClassElement | TypeElement>,
member => changes.some(change => matchNode(change, member)),
)!;
forEach(changes, wipeNode);
changeTracker.replaceNodeRangeWithNodes(
originalFile,
firstMatch,
lastMatch,
changes,
);
return;
}
forEach(changes, wipeNode);
changeTracker.insertNodesAfter(
originalFile,
classOrInterface.members[classOrInterface.members.length - 1],
changes,
);
}
function placeStatements(
originalFile: SourceFile,
changeTracker: ChangeTracker,
changes: NodeArray<Statement>,
focusLocations?: TextSpan[],
) {
if (!focusLocations?.length) {
changeTracker.insertNodesAtEndOfFile(
originalFile,
changes,
/*blankLineBetween*/ false,
);
return;
}
for (const location of focusLocations) {
const scope = findAncestor(
getTokenAtPosition(originalFile, location.start),
(block): block is Block | SourceFile =>
or(isBlock, isSourceFile)(block) &&
some(block.statements, origStmt => changes.some(newStmt => matchNode(newStmt, origStmt))),
);
if (scope) {
const start = scope.statements.find(stmt => changes.some(node => matchNode(node, stmt)));
if (start) {
// Can't be undefined here, since we know we have at least one match.
const end = findLast(scope.statements, stmt => changes.some(node => matchNode(node, stmt)))!;
forEach(changes, wipeNode);
changeTracker.replaceNodeRangeWithNodes(
originalFile,
start,
end,
changes,
);
return;
}
}
}
let scopeStatements: NodeArray<Statement> = originalFile.statements;
for (const location of focusLocations) {
const block = findAncestor(
getTokenAtPosition(originalFile, location.start),
isBlock,
);
if (block) {
scopeStatements = block.statements;
break;
}
}
forEach(changes, wipeNode);
changeTracker.insertNodesAfter(
originalFile,
scopeStatements[scopeStatements.length - 1],
changes,
);
}
function matchNode(a: Node, b: Node): boolean {
if (a.kind !== b.kind) {
return false;
}
if (a.kind === SyntaxKind.Constructor) {
return a.kind === b.kind;
}
if (isNamedDeclaration(a) && isNamedDeclaration(b)) {
return a.name.getText() === b.name.getText();
}
if (isIfStatement(a) && isIfStatement(b)) {
return (
a.expression.getText() === b.expression.getText()
);
}
if (isWhileStatement(a) && isWhileStatement(b)) {
return (
a.expression.getText() ===
b.expression.getText()
);
}
if (isForStatement(a) && isForStatement(b)) {
return (
a.initializer?.getText() ===
b.initializer?.getText() &&
a.incrementor?.getText() ===
b.incrementor?.getText() &&
a.condition?.getText() === b.condition?.getText()
);
}
if (isForInOrOfStatement(a) && isForInOrOfStatement(b)) {
return (
a.expression.getText() ===
b.expression.getText() &&
a.initializer.getText() ===
b.initializer.getText()
);
}
if (isLabeledStatement(a) && isLabeledStatement(b)) {
// If we're actually labeling/naming something, we should be a bit
// more lenient about when we match, so we don't care what the actual
// related statement is: we just replace.
return a.label.getText() === b.label.getText();
}
if (a.getText() === b.getText()) {
return true;
}
return false;
}
function wipeNode(node: Mutable<Node>) {
resetNodePositions(node);
node.parent = undefined!;
}
function resetNodePositions(node: Mutable<Node>) {
node.pos = -1;
node.end = -1;
node.forEachChild(resetNodePositions);
}