/
extractSymbol.ts
2051 lines (1835 loc) · 103 KB
/
extractSymbol.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @internal */
namespace ts.refactor.extractSymbol {
const refactorName = "Extract Symbol";
const extractConstantAction = {
name: "Extract Constant",
description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
kind: "refactor.extract.constant",
};
const extractFunctionAction = {
name: "Extract Function",
description: getLocaleSpecificMessage(Diagnostics.Extract_function),
kind: "refactor.extract.function",
};
registerRefactor(refactorName, {
kinds: [
extractConstantAction.kind,
extractFunctionAction.kind
],
getEditsForAction: getRefactorEditsToExtractSymbol,
getAvailableActions: getRefactorActionsToExtractSymbol,
});
/**
* Compute the associated code actions
* Exported for tests.
*/
export function getRefactorActionsToExtractSymbol(context: RefactorContext): readonly ApplicableRefactorInfo[] {
const requestedRefactor = context.kind;
const rangeToExtract = getRangeToExtract(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked");
const targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) {
return emptyArray;
}
const errors = [];
if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
errors.push({
name: refactorName,
description: extractFunctionAction.description,
actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }]
});
}
if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
errors.push({
name: refactorName,
description: extractConstantAction.description,
actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }]
});
}
return errors;
}
const extractions = getPossibleExtractions(targetRange, context);
if (extractions === undefined) {
// No extractions possible
return emptyArray;
}
const functionActions: RefactorActionInfo[] = [];
const usedFunctionNames = new Map<string, boolean>();
let innermostErrorFunctionAction: RefactorActionInfo | undefined;
const constantActions: RefactorActionInfo[] = [];
const usedConstantNames = new Map<string, boolean>();
let innermostErrorConstantAction: RefactorActionInfo | undefined;
let i = 0;
for (const { functionExtraction, constantExtraction } of extractions) {
const description = functionExtraction.description;
if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) {
if (functionExtraction.errors.length === 0) {
// Don't issue refactorings with duplicated names.
// Scopes come back in "innermost first" order, so extractions will
// preferentially go into nearer scopes
if (!usedFunctionNames.has(description)) {
usedFunctionNames.set(description, true);
functionActions.push({
description,
name: `function_scope_${i}`,
kind: extractFunctionAction.kind
});
}
}
else if (!innermostErrorFunctionAction) {
innermostErrorFunctionAction = {
description,
name: `function_scope_${i}`,
notApplicableReason: getStringError(functionExtraction.errors),
kind: extractFunctionAction.kind
};
}
}
if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) {
if (constantExtraction.errors.length === 0) {
// Don't issue refactorings with duplicated names.
// Scopes come back in "innermost first" order, so extractions will
// preferentially go into nearer scopes
const description = constantExtraction.description;
if (!usedConstantNames.has(description)) {
usedConstantNames.set(description, true);
constantActions.push({
description,
name: `constant_scope_${i}`,
kind: extractConstantAction.kind
});
}
}
else if (!innermostErrorConstantAction) {
innermostErrorConstantAction = {
description,
name: `constant_scope_${i}`,
notApplicableReason: getStringError(constantExtraction.errors),
kind: extractConstantAction.kind
};
}
}
// *do* increment i anyway because we'll look for the i-th scope
// later when actually doing the refactoring if the user requests it
i++;
}
const infos: ApplicableRefactorInfo[] = [];
if (functionActions.length) {
infos.push({
name: refactorName,
description: getLocaleSpecificMessage(Diagnostics.Extract_function),
actions: functionActions,
});
}
else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) {
infos.push({
name: refactorName,
description: getLocaleSpecificMessage(Diagnostics.Extract_function),
actions: [ innermostErrorFunctionAction ]
});
}
if (constantActions.length) {
infos.push({
name: refactorName,
description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
actions: constantActions
});
}
else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) {
infos.push({
name: refactorName,
description: getLocaleSpecificMessage(Diagnostics.Extract_constant),
actions: [ innermostErrorConstantAction ]
});
}
return infos.length ? infos : emptyArray;
function getStringError(errors: readonly Diagnostic[]) {
let error = errors[0].messageText;
if (typeof error !== "string") {
error = error.messageText;
}
return error;
}
}
/* Exported for tests */
export function getRefactorEditsToExtractSymbol(context: RefactorContext, actionName: string): RefactorEditInfo | undefined {
const rangeToExtract = getRangeToExtract(context.file, getRefactorContextSpan(context));
const targetRange = rangeToExtract.targetRange!; // TODO:GH#18217
const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
const index = +parsedFunctionIndexMatch[1];
Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index");
return getFunctionExtractionAtIndex(targetRange, context, index);
}
const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName);
if (parsedConstantIndexMatch) {
const index = +parsedConstantIndexMatch[1];
Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index");
return getConstantExtractionAtIndex(targetRange, context, index);
}
Debug.fail("Unrecognized action name");
}
// Move these into diagnostic messages if they become user-facing
export namespace Messages {
function createMessage(message: string): DiagnosticMessage {
return { message, code: 0, category: DiagnosticCategory.Message, key: message };
}
export const cannotExtractRange: DiagnosticMessage = createMessage("Cannot extract range.");
export const cannotExtractImport: DiagnosticMessage = createMessage("Cannot extract import statement.");
export const cannotExtractSuper: DiagnosticMessage = createMessage("Cannot extract super call.");
export const cannotExtractJSDoc: DiagnosticMessage = createMessage("Cannot extract JSDoc.");
export const cannotExtractEmpty: DiagnosticMessage = createMessage("Cannot extract empty range.");
export const expressionExpected: DiagnosticMessage = createMessage("expression expected.");
export const uselessConstantType: DiagnosticMessage = createMessage("No reason to extract constant of type.");
export const statementOrExpressionExpected: DiagnosticMessage = createMessage("Statement or expression expected.");
export const cannotExtractRangeContainingConditionalBreakOrContinueStatements: DiagnosticMessage = createMessage("Cannot extract range containing conditional break or continue statements.");
export const cannotExtractRangeContainingConditionalReturnStatement: DiagnosticMessage = createMessage("Cannot extract range containing conditional return statement.");
export const cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange: DiagnosticMessage = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
export const cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators: DiagnosticMessage = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
export const typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
export const functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
export const cannotExtractIdentifier = createMessage("Select more than a single identifier.");
export const cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
export const cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
export const cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
export const cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
export const cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
export const cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
export const cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
export const cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method");
}
enum RangeFacts {
None = 0,
HasReturn = 1 << 0,
IsGenerator = 1 << 1,
IsAsyncFunction = 1 << 2,
UsesThis = 1 << 3,
UsesThisInFunction = 1 << 4,
/**
* The range is in a function which needs the 'static' modifier in a class
*/
InStaticRegion = 1 << 5,
}
/**
* Represents an expression or a list of statements that should be extracted with some extra information
*/
interface TargetRange {
readonly range: Expression | Statement[];
readonly facts: RangeFacts;
/**
* If `this` is referring to a function instead of class, we need to retrieve its type.
*/
readonly thisNode: Node | undefined;
}
/**
* Result of 'getRangeToExtract' operation: contains either a range or a list of errors
*/
type RangeToExtract = {
readonly targetRange?: never;
readonly errors: readonly Diagnostic[];
} | {
readonly targetRange: TargetRange;
readonly errors?: never;
};
/*
* Scopes that can store newly extracted method
*/
type Scope = FunctionLikeDeclaration | SourceFile | ModuleBlock | ClassLikeDeclaration;
/**
* getRangeToExtract takes a span inside a text file and returns either an expression or an array
* of statements representing the minimum set of nodes needed to extract the entire span. This
* process may fail, in which case a set of errors is returned instead. These errors are shown to
* users if they have the provideRefactorNotApplicableReason option set.
*/
// exported only for tests
export function getRangeToExtract(sourceFile: SourceFile, span: TextSpan, invoked = true): RangeToExtract {
const { length } = span;
if (length === 0 && !invoked) {
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] };
}
const cursorRequest = length === 0 && invoked;
const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start);
const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span));
/* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for
refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the
searched span to cover a real node range making it more likely that something useful will show up. */
const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span;
// Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
// This may fail (e.g. you select two statements in the root of a source file)
const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan);
// Do the same for the ending position
const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan);
// We'll modify these flags as we walk the tree to collect data
// about what things need to be done as part of the extraction.
let rangeFacts = RangeFacts.None;
let thisNode: Node | undefined;
if (!start || !end) {
// cannot find either start or end node
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
}
if (start.flags & NodeFlags.JSDoc) {
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] };
}
if (start.parent !== end.parent) {
// start and end nodes belong to different subtrees
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
}
if (start !== end) {
// start and end should be statements and parent should be either block or a source file
if (!isBlockLike(start.parent)) {
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
}
const statements: Statement[] = [];
for (const statement of start.parent.statements) {
if (statement === start || statements.length) {
const errors = checkNode(statement);
if (errors) {
return { errors };
}
statements.push(statement);
}
if (statement === end) {
break;
}
}
if (!statements.length) {
// https://github.com/Microsoft/TypeScript/issues/20559
// Ranges like [|case 1: break;|] will fail to populate `statements` because
// they will never find `start` in `start.parent.statements`.
// Consider: We could support ranges like [|case 1:|] by refining them to just
// the expression.
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
}
return { targetRange: { range: statements, facts: rangeFacts, thisNode } };
}
if (isReturnStatement(start) && !start.expression) {
// Makes no sense to extract an expression-less return statement.
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
}
// We have a single node (start)
const node = refineNode(start);
const errors = checkRootNode(node) || checkNode(node);
if (errors) {
return { errors };
}
return { targetRange: { range: getStatementOrExpressionRange(node)!, facts: rangeFacts, thisNode } }; // TODO: GH#18217
/**
* Attempt to refine the extraction node (generally, by shrinking it) to produce better results.
* @param node The unrefined extraction node.
*/
function refineNode(node: Node): Node {
if (isReturnStatement(node)) {
if (node.expression) {
return node.expression;
}
}
else if (isVariableStatement(node) || isVariableDeclarationList(node)) {
const declarations = isVariableStatement(node) ? node.declarationList.declarations : node.declarations;
let numInitializers = 0;
let lastInitializer: Expression | undefined;
for (const declaration of declarations) {
if (declaration.initializer) {
numInitializers++;
lastInitializer = declaration.initializer;
}
}
if (numInitializers === 1) {
return lastInitializer!;
}
// No special handling if there are multiple initializers.
}
else if (isVariableDeclaration(node)) {
if (node.initializer) {
return node.initializer;
}
}
return node;
}
function checkRootNode(node: Node): Diagnostic[] | undefined {
if (isIdentifier(isExpressionStatement(node) ? node.expression : node)) {
return [createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
}
return undefined;
}
function checkForStaticContext(nodeToCheck: Node, containingClass: Node) {
let current: Node = nodeToCheck;
while (current !== containingClass) {
if (current.kind === SyntaxKind.PropertyDeclaration) {
if (isStatic(current)) {
rangeFacts |= RangeFacts.InStaticRegion;
}
break;
}
else if (current.kind === SyntaxKind.Parameter) {
const ctorOrMethod = getContainingFunction(current)!;
if (ctorOrMethod.kind === SyntaxKind.Constructor) {
rangeFacts |= RangeFacts.InStaticRegion;
}
break;
}
else if (current.kind === SyntaxKind.MethodDeclaration) {
if (isStatic(current)) {
rangeFacts |= RangeFacts.InStaticRegion;
}
}
current = current.parent;
}
}
// Verifies whether we can actually extract this node or not.
function checkNode(nodeToCheck: Node): Diagnostic[] | undefined {
const enum PermittedJumps {
None = 0,
Break = 1 << 0,
Continue = 1 << 1,
Return = 1 << 2
}
// We believe it's true because the node is from the (unmodified) tree.
Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)");
// For understanding how skipTrivia functioned:
Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)");
if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) {
return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
}
if (nodeToCheck.flags & NodeFlags.Ambient) {
return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
}
// If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)
const containingClass = getContainingClass(nodeToCheck);
if (containingClass) {
checkForStaticContext(nodeToCheck, containingClass);
}
let errors: Diagnostic[] | undefined;
let permittedJumps = PermittedJumps.Return;
let seenLabels: __String[];
visit(nodeToCheck);
if (rangeFacts & RangeFacts.UsesThis) {
const container = getThisContainer(nodeToCheck, /** includeArrowFunctions */ false);
if (
container.kind === SyntaxKind.FunctionDeclaration ||
(container.kind === SyntaxKind.MethodDeclaration && container.parent.kind === SyntaxKind.ObjectLiteralExpression) ||
container.kind === SyntaxKind.FunctionExpression
) {
rangeFacts |= RangeFacts.UsesThisInFunction;
}
}
return errors;
function visit(node: Node) {
if (errors) {
// already found an error - can stop now
return true;
}
if (isDeclaration(node)) {
const declaringNode = (node.kind === SyntaxKind.VariableDeclaration) ? node.parent.parent : node;
if (hasSyntacticModifier(declaringNode, ModifierFlags.Export)) {
// TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)
// Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!
// Also TODO: GH#19956
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
return true;
}
}
// Some things can't be extracted in certain situations
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractImport));
return true;
case SyntaxKind.ExportAssignment:
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
return true;
case SyntaxKind.SuperKeyword:
// For a super *constructor call*, we have to be extracting the entire class,
// but a super *method call* simply implies a 'this' reference
if (node.parent.kind === SyntaxKind.CallExpression) {
// Super constructor call
const containingClass = getContainingClass(node);
if (containingClass === undefined || containingClass.pos < span.start || containingClass.end >= (span.start + span.length)) {
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractSuper));
return true;
}
}
else {
rangeFacts |= RangeFacts.UsesThis;
thisNode = node;
}
break;
case SyntaxKind.ArrowFunction:
// check if arrow function uses this
forEachChild(node, function check(n) {
if (isThis(n)) {
rangeFacts |= RangeFacts.UsesThis;
thisNode = node;
}
else if (isClassLike(n) || (isFunctionLike(n) && !isArrowFunction(n))) {
return false;
}
else {
forEachChild(n, check);
}
});
// falls through
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
if (isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
// You cannot extract global declarations
(errors ||= []).push(createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
}
// falls through
case SyntaxKind.ClassExpression:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
// do not dive into functions or classes
return false;
}
const savedPermittedJumps = permittedJumps;
switch (node.kind) {
case SyntaxKind.IfStatement:
permittedJumps &= ~PermittedJumps.Return;
break;
case SyntaxKind.TryStatement:
// forbid all jumps inside try blocks
permittedJumps = PermittedJumps.None;
break;
case SyntaxKind.Block:
if (node.parent && node.parent.kind === SyntaxKind.TryStatement && (node.parent as TryStatement).finallyBlock === node) {
// allow unconditional returns from finally blocks
permittedJumps = PermittedJumps.Return;
}
break;
case SyntaxKind.DefaultClause:
case SyntaxKind.CaseClause:
// allow unlabeled break inside case clauses
permittedJumps |= PermittedJumps.Break;
break;
default:
if (isIterationStatement(node, /*lookInLabeledStatements*/ false)) {
// allow unlabeled break/continue inside loops
permittedJumps |= PermittedJumps.Break | PermittedJumps.Continue;
}
break;
}
switch (node.kind) {
case SyntaxKind.ThisType:
case SyntaxKind.ThisKeyword:
rangeFacts |= RangeFacts.UsesThis;
thisNode = node;
break;
case SyntaxKind.LabeledStatement: {
const label = (node as LabeledStatement).label;
(seenLabels || (seenLabels = [])).push(label.escapedText);
forEachChild(node, visit);
seenLabels.pop();
break;
}
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement: {
const label = (node as BreakStatement | ContinueStatement).label;
if (label) {
if (!contains(seenLabels, label.escapedText)) {
// attempts to jump to label that is not in range to be extracted
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
}
}
else {
if (!(permittedJumps & (node.kind === SyntaxKind.BreakStatement ? PermittedJumps.Break : PermittedJumps.Continue))) {
// attempt to break or continue in a forbidden context
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
}
}
break;
}
case SyntaxKind.AwaitExpression:
rangeFacts |= RangeFacts.IsAsyncFunction;
break;
case SyntaxKind.YieldExpression:
rangeFacts |= RangeFacts.IsGenerator;
break;
case SyntaxKind.ReturnStatement:
if (permittedJumps & PermittedJumps.Return) {
rangeFacts |= RangeFacts.HasReturn;
}
else {
(errors ||= []).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement));
}
break;
default:
forEachChild(node, visit);
break;
}
permittedJumps = savedPermittedJumps;
}
}
}
/**
* Includes the final semicolon so that the span covers statements in cases where it would otherwise
* only cover the declaration list.
*/
function getAdjustedSpanFromNodes(startNode: Node, endNode: Node, sourceFile: SourceFile): TextSpan {
const start = startNode.getStart(sourceFile);
let end = endNode.getEnd();
if (sourceFile.text.charCodeAt(end) === CharacterCodes.semicolon) {
end++;
}
return { start, length: end - start };
}
function getStatementOrExpressionRange(node: Node): Statement[] | Expression | undefined {
if (isStatement(node)) {
return [node];
}
if (isExpressionNode(node)) {
// If our selection is the expression in an ExpressionStatement, expand
// the selection to include the enclosing Statement (this stops us
// from trying to care about the return value of the extracted function
// and eliminates double semicolon insertion in certain scenarios)
return isExpressionStatement(node.parent) ? [node.parent] : node as Expression;
}
if (isStringLiteralJsxAttribute(node)) {
return node;
}
return undefined;
}
function isScope(node: Node): node is Scope {
return isArrowFunction(node) ? isFunctionBody(node.body) :
isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node);
}
/**
* Computes possible places we could extract the function into. For example,
* you may be able to extract into a class method *or* local closure *or* namespace function,
* depending on what's in the extracted body.
*/
function collectEnclosingScopes(range: TargetRange): Scope[] {
let current: Node = isReadonlyArray(range.range) ? first(range.range) : range.range;
if (range.facts & RangeFacts.UsesThis && !(range.facts & RangeFacts.UsesThisInFunction)) {
// if range uses this as keyword or as type inside the class then it can only be extracted to a method of the containing class
const containingClass = getContainingClass(current);
if (containingClass) {
const containingFunction = findAncestor(current, isFunctionLikeDeclaration);
return containingFunction
? [containingFunction, containingClass]
: [containingClass];
}
}
const scopes: Scope[] = [];
while (true) {
current = current.parent;
// A function parameter's initializer is actually in the outer scope, not the function declaration
if (current.kind === SyntaxKind.Parameter) {
// Skip all the way to the outer scope of the function that declared this parameter
current = findAncestor(current, parent => isFunctionLikeDeclaration(parent))!.parent;
}
// We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of.
// Walk up to the closest parent of a place where we can logically put a sibling:
// * Function declaration
// * Class declaration or expression
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
if (current.kind === SyntaxKind.SourceFile) {
return scopes;
}
}
}
}
function getFunctionExtractionAtIndex(targetRange: TargetRange, context: RefactorContext, requestedChangesIndex: number): RefactorEditInfo {
const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
context.cancellationToken!.throwIfCancellationRequested(); // TODO: GH#18217
return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context);
}
function getConstantExtractionAtIndex(targetRange: TargetRange, context: RefactorContext, requestedChangesIndex: number): RefactorEditInfo {
const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context);
Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?");
Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?");
context.cancellationToken!.throwIfCancellationRequested();
const expression = isExpression(target)
? target
: (target.statements[0] as ExpressionStatement).expression;
return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context);
}
interface Extraction {
readonly description: string;
readonly errors: readonly Diagnostic[];
}
interface ScopeExtractions {
readonly functionExtraction: Extraction;
readonly constantExtraction: Extraction;
}
/**
* Given a piece of text to extract ('targetRange'), computes a list of possible extractions.
* Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes
* or an error explaining why we can't extract into that scope.
*/
function getPossibleExtractions(targetRange: TargetRange, context: RefactorContext): readonly ScopeExtractions[] | undefined {
const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context);
// Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547
const extractions = scopes.map((scope, i): ScopeExtractions => {
const functionDescriptionPart = getDescriptionForFunctionInScope(scope);
const constantDescriptionPart = getDescriptionForConstantInScope(scope);
const scopeDescription = isFunctionLikeDeclaration(scope)
? getDescriptionForFunctionLikeDeclaration(scope)
: isClassLike(scope)
? getDescriptionForClassLikeDeclaration(scope)
: getDescriptionForModuleLikeDeclaration(scope);
let functionDescription: string;
let constantDescription: string;
if (scopeDescription === SpecialScope.Global) {
functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]);
constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]);
}
else if (scopeDescription === SpecialScope.Module) {
functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]);
constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]);
}
else {
functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]);
constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]);
}
// Customize the phrasing for the innermost scope to increase clarity.
if (i === 0 && !isClassLike(scope)) {
constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]);
}
return {
functionExtraction: {
description: functionDescription,
errors: functionErrorsPerScope[i],
},
constantExtraction: {
description: constantDescription,
errors: constantErrorsPerScope[i],
},
};
});
return extractions;
}
function getPossibleExtractionsWorker(targetRange: TargetRange, context: RefactorContext): { readonly scopes: Scope[], readonly readsAndWrites: ReadsAndWrites } {
const { file: sourceFile } = context;
const scopes = collectEnclosingScopes(targetRange);
const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile);
const readsAndWrites = collectReadsAndWrites(
targetRange,
scopes,
enclosingTextRange,
sourceFile,
context.program.getTypeChecker(),
context.cancellationToken!);
return { scopes, readsAndWrites };
}
function getDescriptionForFunctionInScope(scope: Scope): string {
return isFunctionLikeDeclaration(scope)
? "inner function"
: isClassLike(scope)
? "method"
: "function";
}
function getDescriptionForConstantInScope(scope: Scope): string {
return isClassLike(scope)
? "readonly field"
: "constant";
}
function getDescriptionForFunctionLikeDeclaration(scope: FunctionLikeDeclaration): string {
switch (scope.kind) {
case SyntaxKind.Constructor:
return "constructor";
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
return scope.name
? `function '${scope.name.text}'`
: ANONYMOUS;
case SyntaxKind.ArrowFunction:
return "arrow function";
case SyntaxKind.MethodDeclaration:
return `method '${scope.name.getText()}'`;
case SyntaxKind.GetAccessor:
return `'get ${scope.name.getText()}'`;
case SyntaxKind.SetAccessor:
return `'set ${scope.name.getText()}'`;
default:
throw Debug.assertNever(scope, `Unexpected scope kind ${(scope as FunctionLikeDeclaration).kind}`);
}
}
function getDescriptionForClassLikeDeclaration(scope: ClassLikeDeclaration): string {
return scope.kind === SyntaxKind.ClassDeclaration
? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration"
: scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression";
}
function getDescriptionForModuleLikeDeclaration(scope: SourceFile | ModuleBlock): string | SpecialScope {
return scope.kind === SyntaxKind.ModuleBlock
? `namespace '${scope.parent.name.getText()}'`
: scope.externalModuleIndicator ? SpecialScope.Module : SpecialScope.Global;
}
const enum SpecialScope {
Module,
Global,
}
/**
* Result of 'extractRange' operation for a specific scope.
* Stores either a list of changes that should be applied to extract a range or a list of errors
*/
function extractFunctionInScope(
node: Statement | Expression | Block,
scope: Scope,
{ usages: usagesInScope, typeParameterUsages, substitutions }: ScopeUsages,
exposedVariableDeclarations: readonly VariableDeclaration[],
range: TargetRange,
context: RefactorContext): RefactorEditInfo {
const checker = context.program.getTypeChecker();
const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions());
const importAdder = codefix.createImportAdder(context.file, context.program, context.preferences, context.host);
// Make a unique name for the extracted function
const file = scope.getSourceFile();
const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file);
const isJS = isInJSFile(scope);
const functionName = factory.createIdentifier(functionNameText);
let returnType: TypeNode | undefined;
const parameters: ParameterDeclaration[] = [];
const callArguments: Identifier[] = [];
let writes: UsageEntry[] | undefined;
usagesInScope.forEach((usage, name) => {
let typeNode: TypeNode | undefined;
if (!isJS) {
let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node);
// Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
type = checker.getBaseTypeOfLiteralType(type);
typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, NodeBuilderFlags.NoTruncation);
}
const paramDecl = factory.createParameterDeclaration(
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
/*name*/ name,
/*questionToken*/ undefined,
typeNode
);
parameters.push(paramDecl);
if (usage.usage === Usage.Write) {
(writes || (writes = [])).push(usage);
}
callArguments.push(factory.createIdentifier(name));
});
const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values()).map(type => ({ type, declaration: getFirstDeclaration(type) }));
const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder);
const typeParameters: readonly TypeParameterDeclaration[] | undefined = sortedTypeParametersAndDeclarations.length === 0
? undefined
: sortedTypeParametersAndDeclarations.map(t => t.declaration as TypeParameterDeclaration);
// Strictly speaking, we should check whether each name actually binds to the appropriate type
// parameter. In cases of shadowing, they may not.
const callTypeArguments: readonly TypeNode[] | undefined = typeParameters !== undefined
? typeParameters.map(decl => factory.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined))
: undefined;
// Provide explicit return types for contextually-typed functions
// to avoid problems when there are literal types present
if (isExpression(node) && !isJS) {
const contextualType = checker.getContextualType(node);
returnType = checker.typeToTypeNode(contextualType!, scope, NodeBuilderFlags.NoTruncation); // TODO: GH#18217
}
const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn));
suppressLeadingAndTrailingTrivia(body);
let newFunction: MethodDeclaration | FunctionDeclaration;
const callThis = !!(range.facts & RangeFacts.UsesThisInFunction);
if (isClassLike(scope)) {
// always create private method in TypeScript files
const modifiers: Modifier[] = isJS ? [] : [factory.createModifier(SyntaxKind.PrivateKeyword)];
if (range.facts & RangeFacts.InStaticRegion) {
modifiers.push(factory.createModifier(SyntaxKind.StaticKeyword));
}
if (range.facts & RangeFacts.IsAsyncFunction) {
modifiers.push(factory.createModifier(SyntaxKind.AsyncKeyword));
}
newFunction = factory.createMethodDeclaration(
modifiers.length ? modifiers : undefined,
range.facts & RangeFacts.IsGenerator ? factory.createToken(SyntaxKind.AsteriskToken) : undefined,
functionName,
/*questionToken*/ undefined,
typeParameters,
parameters,
returnType,
body
);
}
else {
if (callThis) {
parameters.unshift(
factory.createParameterDeclaration(
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
/*name*/ "this",
/*questionToken*/ undefined,
checker.typeToTypeNode(
checker.getTypeAtLocation(range.thisNode!),
scope,
NodeBuilderFlags.NoTruncation
),
/*initializer*/ undefined,
)
);
}
newFunction = factory.createFunctionDeclaration(
range.facts & RangeFacts.IsAsyncFunction ? [factory.createToken(SyntaxKind.AsyncKeyword)] : undefined,
range.facts & RangeFacts.IsGenerator ? factory.createToken(SyntaxKind.AsteriskToken) : undefined,
functionName,
typeParameters,
parameters,
returnType,
body
);
}
const changeTracker = textChanges.ChangeTracker.fromContext(context);
const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end;
const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope);
if (nodeToInsertBefore) {
changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true);
}
else {
changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction);
}
importAdder.writeFixes(changeTracker);
const newNodes: Node[] = [];
// replace range with function call
const called = getCalledExpression(scope, range, functionNameText);
if (callThis) {
callArguments.unshift(factory.createIdentifier("this"));
}
let call: Expression = factory.createCallExpression(
callThis ? factory.createPropertyAccessExpression(
called,
"call"
) : called,
callTypeArguments, // Note that no attempt is made to take advantage of type argument inference
callArguments);
if (range.facts & RangeFacts.IsGenerator) {
call = factory.createYieldExpression(factory.createToken(SyntaxKind.AsteriskToken), call);
}
if (range.facts & RangeFacts.IsAsyncFunction) {
call = factory.createAwaitExpression(call);