/
NodePatcher.ts
1399 lines (1252 loc) · 44.2 KB
/
NodePatcher.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
import assert from 'assert';
import { SourceType, SourceToken, SourceTokenList, SourceTokenListIndex } from 'coffee-lex';
import { FunctionApplication, NewOp, Node, SoakedFunctionApplication } from 'decaffeinate-parser';
import MagicString from 'magic-string';
import { Options } from '../options';
import { AVOID_IIFES, AVOID_INLINE_ASSIGNMENTS, CLEAN_UP_IMPLICIT_RETURNS, Suggestion } from '../suggestions';
import adjustIndent from '../utils/adjustIndent';
import { logger } from '../utils/debug';
import DecaffeinateContext from '../utils/DecaffeinateContext';
import notNull from '../utils/notNull';
import PatcherError from '../utils/PatchError';
import referencesArguments from '../utils/referencesArguments';
import Scope from '../utils/Scope';
import { isFunction, isSemanticToken } from '../utils/types';
import { PatcherContext, PatchOptions, RepeatableOptions } from './types';
export type AddThisAssignmentCallback = (memberName: string) => string;
export type AddDefaultParamCallback = (assigneeCode: string, initCode: string, assigneeNode: Node) => string;
export interface PatcherClass {
// The "children" arg is some number of NodePatchers, but there doesn't seem
// to be an easy way to have TypeScript understand that.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (context: PatcherContext, ...children: Array<any>): NodePatcher;
patcherClassForChildNode(node: Node, property: string): PatcherClass | null;
patcherClassOverrideForNode(node: Node): PatcherClass | null;
}
export default class NodePatcher {
node: Node;
context: DecaffeinateContext;
editor: MagicString;
options: Options;
addSuggestion: (suggestion: Suggestion) => void;
log: (...args: Array<unknown>) => void;
parent!: NodePatcher | null;
contentStart!: number;
contentEnd!: number;
contentStartTokenIndex!: SourceTokenListIndex;
contentEndTokenIndex!: SourceTokenListIndex;
innerStart!: number;
innerEnd!: number;
innerStartTokenIndex!: SourceTokenListIndex;
innerEndTokenIndex!: SourceTokenListIndex;
outerStart!: number;
outerEnd!: number;
outerStartTokenIndex!: SourceTokenListIndex;
outerEndTokenIndex!: SourceTokenListIndex;
adjustedIndentLevel = 0;
_assignee = false;
_containsYield = false;
_containsAwait = false;
_deferredSuffix = '';
_expression = false;
_hadUnparenthesizedNegation = false;
_implicitlyReturns = false;
_repeatableOptions: RepeatableOptions | null = null;
_repeatCode: string | null = null;
_returns = false;
// Temporary callbacks that can be added for inter-node communication.
addThisAssignmentAtScopeHeader?: AddThisAssignmentCallback;
addDefaultParamAssignmentAtScopeHeader?: AddDefaultParamCallback;
constructor({ node, context, editor, options, addSuggestion }: PatcherContext) {
this.log = logger(this.constructor.name);
this.node = node;
this.context = context;
this.editor = editor;
this.options = options;
this.addSuggestion = addSuggestion;
this.withPrettyErrors(() => this.setupLocationInformation());
}
/**
* Allow patcher classes to override the class used to patch their children.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static patcherClassForChildNode(_node: Node, _property: string): PatcherClass | null {
return null;
}
/**
* Allow patcher classes that would patch a node to chose a different class.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static patcherClassOverrideForNode(_node: Node): PatcherClass | null {
return null;
}
private setupLocationInformation(): void {
const { node, context } = this;
/**
* `contentStart` and `contentEnd` is the exclusive range within the original source that
* composes this patcher's node. For example, here's the contentStart and contentEnd of
* `a + b` in the expression below:
*
* console.log(a + b)
* ^ ^
*/
this.contentStart = node.start;
this.contentEnd = node.end;
if (this.shouldTrimContentRange()) {
this.trimContentRange();
}
const tokens = context.sourceTokens;
const firstSourceTokenIndex = tokens.indexOfTokenStartingAtSourceIndex(this.contentStart);
const lastSourceTokenIndex = tokens.indexOfTokenEndingAtSourceIndex(this.contentEnd);
if (!firstSourceTokenIndex || !lastSourceTokenIndex) {
if (node.type === 'Program') {
// Just an empty program.
return;
}
throw this.error(`cannot find first or last token in ${node.type} node`);
}
this.contentStartTokenIndex = firstSourceTokenIndex;
this.contentEndTokenIndex = lastSourceTokenIndex;
let outerStartTokenIndex = firstSourceTokenIndex;
let outerEndTokenIndex = lastSourceTokenIndex;
let innerStartTokenIndex = firstSourceTokenIndex;
let innerEndTokenIndex = lastSourceTokenIndex;
for (;;) {
const previousSurroundingTokenIndex = tokens.lastIndexOfTokenMatchingPredicate(
isSemanticToken,
outerStartTokenIndex.previous()
);
const nextSurroundingTokenIndex = tokens.indexOfTokenMatchingPredicate(
isSemanticToken,
outerEndTokenIndex.next()
);
if (!previousSurroundingTokenIndex || !nextSurroundingTokenIndex) {
break;
}
const previousSurroundingToken = tokens.tokenAtIndex(previousSurroundingTokenIndex);
const nextSurroundingToken = tokens.tokenAtIndex(nextSurroundingTokenIndex);
if (
!previousSurroundingToken ||
(previousSurroundingToken.type !== SourceType.LPAREN && previousSurroundingToken.type !== SourceType.CALL_START)
) {
break;
}
if (
!nextSurroundingToken ||
(nextSurroundingToken.type !== SourceType.RPAREN && nextSurroundingToken.type !== SourceType.CALL_END)
) {
break;
}
if (innerStartTokenIndex === firstSourceTokenIndex) {
innerStartTokenIndex = previousSurroundingTokenIndex;
}
if (innerEndTokenIndex === lastSourceTokenIndex) {
innerEndTokenIndex = nextSurroundingTokenIndex;
}
outerStartTokenIndex = previousSurroundingTokenIndex;
outerEndTokenIndex = nextSurroundingTokenIndex;
}
this.innerStartTokenIndex = innerStartTokenIndex;
this.innerEndTokenIndex = innerEndTokenIndex;
this.outerStartTokenIndex = outerStartTokenIndex;
this.outerEndTokenIndex = outerEndTokenIndex;
/**
* `innerStart`, `innerEnd`, `outerStart` and `outerEnd` refer to the
* positions around surrounding parentheses. In most nodes they are the same
* as `contentStart` and `contentEnd`. For example:
*
* innerStart
* |
* outerStart | contentStart
* | | |
* ▼ ▼ ▼
* 1 * (( 2 + 3 ))
* ▲ ▲ ▲
* | | |
* contentEnd | outerEnd
* |
* innerEnd
*/
if (innerStartTokenIndex === firstSourceTokenIndex) {
this.innerStart = this.contentStart;
} else {
this.innerStart = notNull(tokens.tokenAtIndex(innerStartTokenIndex)).end;
}
if (innerEndTokenIndex === lastSourceTokenIndex) {
this.innerEnd = this.contentEnd;
} else {
this.innerEnd = notNull(tokens.tokenAtIndex(innerEndTokenIndex)).start;
}
this.outerStart = notNull(tokens.tokenAtIndex(outerStartTokenIndex)).start;
this.outerEnd = notNull(tokens.tokenAtIndex(outerEndTokenIndex)).end;
}
/**
* Called to trim the range of content for this node. Override in subclasses
* to customize its behavior, or override `shouldTrimContentRange` to enable
* or disable it.
*/
trimContentRange(): void {
const context = this.context;
for (;;) {
const startChar = context.source[this.contentStart];
if (startChar === ' ' || startChar === '\t') {
this.contentStart++;
} else {
break;
}
}
for (;;) {
const lastChar = context.source[this.contentEnd - 1];
if (lastChar === ' ' || lastChar === '\t') {
this.contentEnd--;
} else {
break;
}
}
}
/**
* Decides whether to trim the content range of this node.
*/
shouldTrimContentRange(): boolean {
return false;
}
/**
* Called when the patcher tree is complete so we can do any processing that
* requires communication with other patchers.
*/
initialize(): void {
// intentionally left empty
}
/**
* Calls methods on `editor` to transform the source code represented by
* `node` from CoffeeScript to JavaScript. By default this method delegates
* to other patcher methods which can be overridden individually.
*/
patch(options: PatchOptions = {}): void {
this.withPrettyErrors(() => {
if (this._repeatableOptions !== null) {
this._repeatCode = this.patchAsRepeatableExpression(this._repeatableOptions, options);
} else if (this.forcedToPatchAsExpression()) {
this.patchAsForcedExpression(options);
this.commitDeferredSuffix();
} else if (this.willPatchAsExpression()) {
this.patchAsExpression(options);
this.commitDeferredSuffix();
} else {
this.patchAsStatement(options);
this.commitDeferredSuffix();
}
});
}
/**
* Alternative to patch that patches the expression in a way that the result
* can be referenced later, then returns the code to reference it.
*
* This is a shorthand for the simplest use of the repeatable protocol. In
* more advanced cases (such as repeating code that is deep within the AST),
* setRequiresRepeatableExpression can be called before the node is patched
* and getRepeatCode can be called any time after.
*
* The actual implementation for making the node repeatable should be in
* patchAsRepeatableExpression.
*/
patchRepeatable(repeatableOptions: RepeatableOptions = {}): string {
this.setRequiresRepeatableExpression(repeatableOptions);
this.patch();
return this.getRepeatCode();
}
/**
* Patch the given expression and get the underlying generated code. This is
* more robust than calling patch and slice directly, since it also includes
* code inserted at contentStart (which normally isn't picked up by slice
* because it's inserted to the left of the index boundary). To accomplish
* this, we look at the range from contentStart - 1 to contentStart before and
* after patching and include anything new that was added.
*/
patchAndGetCode(options: PatchOptions = {}): string {
return this.captureCodeForPatchOperation(() => this.patch(options));
}
captureCodeForPatchOperation(patchFn: () => void): string {
let sliceStart = this.contentStart > 0 ? this.contentStart - 1 : 0;
// Occasionally, sliceStart will be illegal because it will be in a range
// that has been removed or overwritten. If that's the case, subtract 1 from
// sliceStart until we find something that works.
let beforeCode = null;
while (beforeCode === null) {
try {
beforeCode = this.slice(sliceStart, this.contentStart);
} catch (e) {
// Assume that this is because the index is an invalid start. It looks
// like there isn't a robust way to detect this case exactly, so just
// try a lower start for any error.
sliceStart -= 1;
if (sliceStart < 0) {
throw this.error('Could not find a valid index to slice for patch operation.');
}
}
}
patchFn();
const code = this.slice(sliceStart, this.contentEnd);
let startIndex = 0;
while (startIndex < beforeCode.length && startIndex < code.length && beforeCode[startIndex] === code[startIndex]) {
startIndex++;
}
return code.substr(startIndex);
}
/**
* Catch errors and throw them again annotated with the current node.
*/
withPrettyErrors(body: () => void): void {
try {
body();
} catch (err: unknown) {
assert(err instanceof Error);
if (!PatcherError.detect(err)) {
throw this.error(err.message, this.contentStart, this.contentEnd, err);
} else {
throw err;
}
}
}
/**
* Internal patching method that should patch the current node as an
* expression and also, if necessary, alter it in a way that it can
*
* The return value of this function should be a code snippet that references
* the result of this expression without any further side-effects.
*
* In simple cases, such as identifiers, subclasses can override isRepeatable
* to declare themselves as already repeatable. In more advanced cases,
* subclasses can override this method to provide custom behavior.
*
* This function is also responsible for committing the deferred suffix if
* necessary.
*
* @protected
*/
patchAsRepeatableExpression(repeatableOptions: RepeatableOptions = {}, patchOptions: PatchOptions = {}): string {
if (this.isRepeatable() && !repeatableOptions.forceRepeat) {
return this.captureCodeForPatchOperation(() => {
this.patchAsForcedExpression(patchOptions);
this.commitDeferredSuffix();
});
} else {
this.addSuggestion(AVOID_INLINE_ASSIGNMENTS);
// Can't repeat it, so we assign it to a free variable and return that,
// i.e. `a + b` → `(ref = a + b)`.
if (repeatableOptions.parens) {
this.insert(this.innerStart, '(');
}
const ref = this.claimFreeBinding(repeatableOptions.ref);
this.insert(this.innerStart, `${ref} = `);
this.patchAsForcedExpression(patchOptions);
this.commitDeferredSuffix();
if (repeatableOptions.parens) {
this.insert(this.innerEnd, ')');
}
return ref;
}
}
/**
* Override this to patch the node as an expression.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
patchAsExpression(_options: PatchOptions = {}): void {
throw this.error(`'patchAsExpression' must be overridden in subclasses`);
}
/**
* Override this to patch the node as a statement.
*/
patchAsStatement(options: PatchOptions = {}): void {
const addParens = this.statementShouldAddParens();
if (addParens) {
this.insert(this.outerStart, '(');
}
this.patchAsExpression(options);
if (addParens) {
this.insert(this.outerEnd, ')');
}
}
/**
* Override this to patch the node as an expression that would not normally be
* an expression, often by wrapping it in an immediately invoked function
* expression (IIFE).
*/
patchAsForcedExpression(options: PatchOptions = {}): void {
this.patchAsExpression(options);
}
/**
* Insert content at the specified index.
*/
insert(index: number, content: string): void {
if (typeof index !== 'number') {
throw new Error(`cannot insert ${JSON.stringify(content)} at non-numeric index ${index as number}`);
}
this.log(
'INSERT',
index,
JSON.stringify(content),
'BEFORE',
JSON.stringify(this.context.source.slice(index, index + 8))
);
this.adjustBoundsToInclude(index);
this.editor.appendLeft(index, content);
}
/**
* Insert content at the specified index, before any content normally
* specified with `insert`. Note that this should be used sparingly. In almost
* every case, the correct behavior is to do all patching operations in order
* and always use `insert`. However, in some cases (like a constructor that
* needs the patched contents of the methods below it), we need to do patching
* out of order, so it's ok to use `prependLeft` to ensure that the code ends
* up before the later values.
*/
prependLeft(index: number, content: string): void {
if (typeof index !== 'number') {
throw new Error(`cannot insert ${JSON.stringify(content)} at non-numeric index ${index as number}`);
}
this.log(
'PREPEND LEFT',
index,
JSON.stringify(content),
'BEFORE',
JSON.stringify(this.context.source.slice(index, index + 8))
);
this.adjustBoundsToInclude(index);
this.editor.prependLeft(index, content);
}
allowPatchingOuterBounds(): boolean {
return false;
}
/**
* @protected
*/
getEditingBounds(): [number, number] {
let boundingPatcher = this.getBoundingPatcher();
// When we're a function arg, there isn't a great patcher to use to
// determine our bounds (we're allowed to patch from the previous
// comma/paren to the next comma/paren), so loosen the restriction to the
// entire function.
if (
boundingPatcher.parent &&
(this.isNodeFunctionApplication(boundingPatcher.parent.node) ||
boundingPatcher.parent.node.type === 'ArrayInitialiser')
) {
boundingPatcher = boundingPatcher.parent;
}
if (this.allowPatchingOuterBounds()) {
return [boundingPatcher.outerStart, boundingPatcher.outerEnd];
} else {
return [boundingPatcher.innerStart, boundingPatcher.innerEnd];
}
}
/**
* @protected
*/
isIndexEditable(index: number): boolean {
const [start, end] = this.getEditingBounds();
return index >= start && index <= end;
}
/**
* @protected
*/
assertEditableIndex(index: number): void {
if (!this.isIndexEditable(index)) {
const [start, end] = this.getEditingBounds();
throw this.error(
`cannot edit index ${index} because it is not editable (i.e. outside [${start}, ${end}))`,
start,
end
);
}
}
/**
* When editing outside a node's bounds we expand the bounds to fit, if
* possible. Note that if a node or a node's parent is wrapped in parentheses
* we cannot adjust the bounds beyond the inside of the parentheses.
*/
adjustBoundsToInclude(index: number): void {
this.assertEditableIndex(index);
if (index < this.innerStart) {
this.log('Moving `innerStart` from', this.innerStart, 'to', index);
this.innerStart = index;
}
if (index > this.innerEnd) {
this.log('Moving `innerEnd` from', this.innerEnd, 'to', index);
this.innerEnd = index;
}
if (index < this.outerStart) {
this.log('Moving `outerStart` from', this.outerStart, 'to', index);
this.outerStart = index;
}
if (index > this.outerEnd) {
this.log('Moving `outerEnd` from', this.outerEnd, 'to', index);
this.outerEnd = index;
}
if (this.parent) {
this.parent.adjustBoundsToInclude(index);
}
}
/**
* Replace the content between the start and end indexes with new content.
*/
overwrite(start: number, end: number, content: string): void {
if (typeof start !== 'number' || typeof end !== 'number') {
throw new Error(`cannot overwrite non-numeric range [${start}, ${end}) ` + `with ${JSON.stringify(content)}`);
}
this.log(
'OVERWRITE',
`[${start}, ${end})`,
JSON.stringify(this.context.source.slice(start, end)),
'→',
JSON.stringify(content)
);
this.editor.overwrite(start, end, content);
}
/**
* Remove the content between the start and end indexes.
*/
remove(start: number, end: number): void {
if (typeof start !== 'number' || typeof end !== 'number') {
throw new Error(`cannot remove non-numeric range [${start}, ${end})`);
}
this.log('REMOVE', `[${start}, ${end})`, JSON.stringify(this.context.source.slice(start, end)));
this.editor.remove(start, end);
}
/**
* Moves content in a range to another index.
*/
move(start: number, end: number, index: number): void {
if (typeof start !== 'number' || typeof end !== 'number') {
throw this.error(`cannot remove non-numeric range [${start}, ${end})`);
}
if (typeof index !== 'number') {
throw this.error(`cannot move to non-numeric index: ${index as number}`);
}
this.log(
'MOVE',
`[${start}, ${end}) → ${index}`,
JSON.stringify(this.context.source.slice(start, end)),
'BEFORE',
JSON.stringify(this.context.source.slice(index, index + 8))
);
this.editor.move(start, end, index);
}
/**
* Get the current content between the start and end indexes.
*/
slice(start: number, end: number): string {
// magic-string treats 0 as the end of the string, which we don't want to do.
if (end === 0) {
return '';
}
return this.editor.slice(start, end);
}
/**
* Determines whether this node starts with a string.
*/
startsWith(string: string): boolean {
return this.context.source.slice(this.contentStart, this.contentStart + string.length) === string;
}
/**
* Determines whether this node ends with a string.
*/
endsWith(string: string): boolean {
return this.context.source.slice(this.contentEnd - string.length, this.contentEnd) === string;
}
/**
* Tells us to force this patcher to generate an expression, or else throw.
*/
setRequiresExpression(): void {
this.setExpression(true);
}
/**
* Tells us to try to patch as an expression, returning whether it can.
*/
setExpression(force = false): boolean {
if (force) {
if (!this.canPatchAsExpression()) {
throw this.error(`cannot represent ${this.node.type} as an expression`);
}
} else if (!this.prefersToPatchAsExpression()) {
return false;
}
this._expression = true;
return true;
}
/**
* Override this to express whether the patcher prefers to be represented as
* an expression. By default it's simply an alias for `canPatchAsExpression`.
*/
prefersToPatchAsExpression(): boolean {
return this.canPatchAsExpression();
}
/**
* Override this if a node cannot be represented as an expression.
*/
canPatchAsExpression(): boolean {
return true;
}
/**
* Gets whether this patcher is working on a statement or an expression.
*/
willPatchAsExpression(): boolean {
return this._expression;
}
/**
* Gets whether this patcher was forced to patch its node as an expression.
*/
forcedToPatchAsExpression(): boolean {
return this.willPatchAsExpression() && !this.prefersToPatchAsExpression();
}
/**
* Marks this node as an assignee. Nested assignees, like destructure
* operations, should override this method and propagate it to the children.
*/
setAssignee(): void {
this._assignee = true;
}
/**
* Checks if this node has been marked as an assignee. This is particularly
* useful for distinguishing rest from spread operations.
*/
isAssignee(): boolean {
return this._assignee;
}
/**
* Gets whether this patcher's node implicitly returns.
*/
implicitlyReturns(): boolean {
return this._implicitlyReturns || false;
}
/**
* Causes the node to be returned from its function.
*/
setImplicitlyReturns(): void {
this._implicitlyReturns = true;
}
/**
* Gets the ancestor that will decide the current implicit return behavior.
* That ancestor will then have implicitReturnWillBreak,
* patchImplicitReturnStart, and patchImplicitReturnEnd methods that describe
* how to handle expressions in an implicit return position (usually they are
* just returned, but in the case of loop IIFEs, they will be added to a
* list).
*/
implicitReturnPatcher(): NodePatcher {
if (this.canHandleImplicitReturn()) {
return this;
} else {
return notNull(this.parent).implicitReturnPatcher();
}
}
/**
* Subclasses should return true to declare themselves as the "handler" in an
* implicit return situation.
*/
canHandleImplicitReturn(): boolean {
return false;
}
/**
* Determines whether the current patcher (which has already declared that it
* can be an implicit return patcher) will generate code that stops execution
* in the current block. In the normal case of a return statement, this is
* true, but in loop IIFEs, there might be e.g. an assignment, which means
* that the control flow won't necessarily stop.
*/
implicitReturnWillBreak(): boolean {
return true;
}
/**
* Patch the beginning of an implicitly-returned descendant. Unlike most
* statements, implicitly-returned statements will not have their surrounding
* parens removed, so the implicit return patching may need to remove
* surrounding parens.
*/
patchImplicitReturnStart(patcher: NodePatcher): void {
if (patcher.node.type === 'Break' || patcher.node.type === 'Continue') {
if (patcher.isSurroundedByParentheses()) {
this.remove(patcher.outerStart, patcher.innerStart);
this.remove(patcher.innerEnd, patcher.outerEnd);
}
return;
}
if (isFunction(this.node) && this.isMultiline()) {
this.addSuggestion(CLEAN_UP_IMPLICIT_RETURNS);
}
patcher.setRequiresExpression();
this.insert(patcher.outerStart, 'return ');
}
/**
* Return null to indicate that no empty case code should be generated.
*/
getEmptyImplicitReturnCode(): string | null {
return null;
}
/**
* Patch the end of an implicitly-returned descendant.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
patchImplicitReturnEnd(_patcher: NodePatcher): void {
// Nothing to do.
}
/**
* Gets whether this patcher's node returns explicitly from its function.
*/
explicitlyReturns(): boolean {
return this._returns || false;
}
/**
* Marks this patcher's as containing a node that explicitly returns.
*/
setExplicitlyReturns(): void {
this._returns = true;
if (this.parent) {
this.parent.setExplicitlyReturns();
}
}
/**
* Mark that this node should have the given suffix appended at the end of
* patching. For example, this allows a child node to indicate that this node
* should end with a close-paren, and to do so in a way that respects patching
* order (doesn't add the close-paren too early).
*/
appendDeferredSuffix(suffix: string): void {
this._deferredSuffix += suffix;
}
/**
* Internal method that should be called at the end of patching to actually
* place the deferred suffix in the right place.
*
* @protected
*/
commitDeferredSuffix(): void {
if (this._deferredSuffix) {
this.insert(this.innerEnd, this._deferredSuffix);
}
}
/**
* Determines whether this patcher's node needs a semicolon after it. This
* should be overridden in subclasses as appropriate.
*/
statementNeedsSemicolon(): boolean {
return true;
}
/**
* Determines whether, when appearing as a statement, this patcher's node
* needs to be surrounded by parentheses.
*
* Subclasses should override this and, typically, delegate to their leftmost
* child patcher. Subclasses may return `false` when they will insert text at
* the start of the node.
*/
statementNeedsParens(): boolean {
return false;
}
/**
* Determines whether this patcher's node should add parentheses when used in
* a statement context.
*/
statementShouldAddParens(): boolean {
return this.statementNeedsParens() && !this.isSurroundedByParentheses();
}
/**
* Gets the tokens for the whole program.
*/
getProgramSourceTokens(): SourceTokenList {
return this.context.sourceTokens;
}
/**
* Gets the index of the token starting at a particular source index.
*/
indexOfSourceTokenStartingAtSourceIndex(index: number): SourceTokenListIndex | null {
return this.getProgramSourceTokens().indexOfTokenStartingAtSourceIndex(index);
}
/**
* Gets the index of the token between left and right patchers that matches
* a predicate function.
*/
indexOfSourceTokenBetweenPatchersMatching(
left: NodePatcher,
right: NodePatcher,
predicate: (token: SourceToken) => boolean
): SourceTokenListIndex | null {
return this.indexOfSourceTokenBetweenSourceIndicesMatching(left.outerEnd, right.outerStart, predicate);
}
/**
* Gets the index of the token between source locations that matches a
* predicate function.
*/
indexOfSourceTokenBetweenSourceIndicesMatching(
left: number,
right: number,
predicate: (token: SourceToken) => boolean
): SourceTokenListIndex | null {
const tokenList = this.getProgramSourceTokens();
return tokenList.indexOfTokenMatchingPredicate(
(token) => {
return token.start >= left && token.start <= right && predicate(token);
},
tokenList.indexOfTokenNearSourceIndex(left),
tokenList.indexOfTokenNearSourceIndex(right).next()
);
}
/**
* Gets the token at a particular index.
*/
sourceTokenAtIndex(index: SourceTokenListIndex): SourceToken | null {
return this.getProgramSourceTokens().tokenAtIndex(index);
}
/**
* Gets the source encompassed by the given token.
*/
sourceOfToken(token: SourceToken): string {
return this.context.source.slice(token.start, token.end);
}
/**
* Gets the first token in the content of this node.
*/
firstToken(): SourceToken {
const token = this.sourceTokenAtIndex(this.contentStartTokenIndex);
if (!token) {
throw this.error('Expected to find a first token for node.');
}
return token;
}
/**
* Gets the last token in the content of this node.
*/
lastToken(): SourceToken {
const token = this.sourceTokenAtIndex(this.contentEndTokenIndex);
if (!token) {
throw this.error('Expected to find a last token for node.');
}
return token;
}
/**
* Gets the token after the end of this node, or null if there is none.
*/
nextSemanticToken(): SourceToken | null {
return this.getFirstSemanticToken(this.contentEnd, this.context.source.length);
}
/**
* Gets the original source of this patcher's node.
*/
getOriginalSource(): string {
return this.context.source.slice(this.contentStart, this.contentEnd);
}
/**
* Determines whether this patcher's node spanned multiple lines.
*/
isMultiline(): boolean {
return /\n/.test(this.getOriginalSource());
}
/**
* Gets the patched source of this patcher's node.
*/
getPatchedSource(): string {
return this.slice(this.contentStart, this.contentEnd);
}
/**
* Gets the index of a token after `contentStart` with the matching type, ignoring
* non-semantic types by default.
*/
indexOfSourceTokenAfterSourceTokenIndex(
start: SourceTokenListIndex,
type: SourceType,
predicate: (token: SourceToken) => boolean = isSemanticToken
): SourceTokenListIndex | null {
const index = this.getProgramSourceTokens().indexOfTokenMatchingPredicate(predicate, start.next());
if (!index) {
return null;
}
const token = this.sourceTokenAtIndex(index);
if (!token || token.type !== type) {
return null;
}
return index;
}
/**
* Determines whether this patcher's node is followed by a particular token.
*/
hasSourceTokenAfter(type: SourceType, predicate: (token: SourceToken) => boolean = isSemanticToken): boolean {
return this.indexOfSourceTokenAfterSourceTokenIndex(this.outerEndTokenIndex, type, predicate) !== null;
}
/**
* Determines whether this patcher's node is surrounded by parentheses.
* Also check if these parents are matching, to avoid false positives on things like `(a) && (b)`
*/
isSurroundedByParentheses(): boolean {
// Surrounding parens will extend outer start/end beyond content start/end,
// so only consider parens in that case. If we didn't exit early here, we'd
// get false positives for nodes that start and end with parens without
// actually being surrounded by parens.
if (this.contentStart === this.outerStart && this.contentEnd === this.outerEnd) {
return false;
}
const beforeToken = this.sourceTokenAtIndex(this.outerStartTokenIndex);
const afterToken = this.sourceTokenAtIndex(this.outerEndTokenIndex);
if (!beforeToken || !afterToken) {
return false;
}
let leftTokenType = SourceType.LPAREN;