forked from decaffeinate/decaffeinate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NodePatcher.js
1022 lines (902 loc) · 29.2 KB
/
NodePatcher.js
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 PatcherError from '../utils/PatchError.js';
import adjustIndent from '../utils/adjustIndent.js';
import repeat from 'repeating';
import type { SourceType, SourceToken, SourceTokenListIndex, Editor, Node, ParseContext, SourceTokenList } from './types.js';
import { CALL_START, CALL_END, LPAREN, RPAREN } from 'coffee-lex';
import { isSemanticToken } from '../utils/types.js';
import { logger } from '../utils/debug.js';
export default class NodePatcher {
node: Node;
context: ParseContext;
editor: Editor;
log: (...args: Array<any>) => void;
parent: ?NodePatcher;
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: number = 0;
constructor(node: Node, context: ParseContext, editor: Editor) {
this.log = logger(this.constructor.name);
this.node = node;
this.context = context;
this.editor = editor;
this.withPrettyErrors(() => this.setupLocationInformation());
}
/**
* Allow patcher classes to override the class used to patch their children.
*/
static patcherClassForChildNode(/* node: Node, property: string */): ?Class<NodePatcher> {
return null;
}
/**
* Allow patcher classes that would patch a node to chose a different class.
*/
static patcherClassOverrideForNode(node: Node): ?Class<NodePatcher> { // eslint-disable-line no-unused-vars
return null;
}
/**
* @private
*/
setupLocationInformation() {
let { node, context } = this;
if (node.virtual) {
return;
}
/**
* `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.range[0];
this.contentEnd = node.range[1];
if (this.shouldTrimContentRange()) {
this.trimContentRange();
}
let tokens = context.sourceTokens;
let firstSourceTokenIndex = tokens.indexOfTokenStartingAtSourceIndex(this.contentStart);
let 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 (;;) {
let previousSurroundingTokenIndex = tokens.lastIndexOfTokenMatchingPredicate(
isSemanticToken,
outerStartTokenIndex.previous()
);
let nextSurroundingTokenIndex = tokens.indexOfTokenMatchingPredicate(
isSemanticToken,
outerEndTokenIndex.next()
);
if (!previousSurroundingTokenIndex || !nextSurroundingTokenIndex) {
break;
}
let previousSurroundingToken = tokens.tokenAtIndex(previousSurroundingTokenIndex);
let nextSurroundingToken = tokens.tokenAtIndex(nextSurroundingTokenIndex);
if (!previousSurroundingToken || (previousSurroundingToken.type !== LPAREN && previousSurroundingToken.type !== CALL_START)) {
break;
}
if (!nextSurroundingToken || (nextSurroundingToken.type !== RPAREN && nextSurroundingToken.type !== 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 = tokens.tokenAtIndex(innerStartTokenIndex).end;
}
if (innerEndTokenIndex === lastSourceTokenIndex) {
this.innerEnd = this.contentEnd;
} else {
this.innerEnd = tokens.tokenAtIndex(innerEndTokenIndex).start;
}
this.outerStart = tokens.tokenAtIndex(outerStartTokenIndex).start;
this.outerEnd = 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() {
let context = this.context;
for (;;) {
let startChar = context.source[this.contentStart];
if (startChar === ' ' || startChar === '\t') {
this.contentStart++;
} else {
break;
}
}
for (;;) {
let 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() {
return false;
}
/**
* Called when the patcher tree is complete so we can do any processing that
* requires communication with other patchers.
*/
initialize() {}
/**
* 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={}) {
this.withPrettyErrors(() => {
if (this.forcedToPatchAsExpression()) {
this.patchAsForcedExpression(options);
} else if (this.willPatchAsExpression()) {
this.patchAsExpression(options);
} else {
this.patchAsStatement(options);
}
});
}
/**
* 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={}) {
let sliceStart = this.contentStart > 0 ? this.contentStart - 1 : 0;
let beforeCode = this.slice(sliceStart, this.contentStart);
this.patch(options);
let 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) {
try {
body();
} catch (err) {
if (!PatcherError.detect(err)) {
throw this.error(
err.message,
this.contentStart,
this.contentEnd,
err
);
} else {
throw err;
}
}
}
/**
* Override this to patch the node as an expression.
*/
patchAsExpression() {
throw this.error(`'patchAsExpression' must be overridden in subclasses`);
}
/**
* Override this to patch the node as a statement.
*/
patchAsStatement(options={}) {
let 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() {
this.patchAsExpression();
}
/**
* Insert content at the specified index.
*/
insert(index: number, content: string) {
if (typeof index !== 'number') {
throw new Error(
`cannot insert ${JSON.stringify(content)} at non-numeric index ${index}`
);
}
this.log(
'INSERT RIGHT',
index,
JSON.stringify(content),
'BEFORE',
JSON.stringify(this.context.source.slice(index, index + 8))
);
this.adjustBoundsToInclude(index);
this.editor.appendLeft(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 = boundingPatcher.parent;
}
if (this.allowPatchingOuterBounds()) {
return [boundingPatcher.outerStart, boundingPatcher.outerEnd];
} else {
return [boundingPatcher.innerStart, boundingPatcher.innerEnd];
}
}
/**
* @protected
*/
isIndexEditable(index: number): boolean {
let [ start, end ] = this.getEditingBounds();
return index >= start && index <= end;
}
/**
* @protected
*/
assertEditableIndex(index: number) {
if (!this.isIndexEditable(index)) {
let [ 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.
*
* @private
*/
adjustBoundsToInclude(index: number) {
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) {
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) {
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) {
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}`
);
}
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 {
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() {
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();
}
/**
* Gets whether this patcher's node implicitly returns.
*/
implicitlyReturns(): boolean {
return this._implicitlyReturns || false;
}
/**
* Causes the node to be returned from its function.
*/
setImplicitlyReturns() {
this._implicitlyReturns = true;
}
/**
* Gets the ancestor that can make implicit returns explicit. Classes that
* override this method should override `implicitReturnWillBreak`.
*/
implicitReturnPatcher(): NodePatcher {
return this.parent.implicitReturnPatcher();
}
/**
* Patch the beginning of an implicitly-returned descendant.
*/
patchImplicitReturnStart(patcher: NodePatcher) {
patcher.setRequiresExpression();
this.insert(patcher.outerStart, 'return ');
}
/**
* Determines whether the implicit return code will stop execution of
* statements in the current block. Classes that override this method should
* also override `implicitReturnPatcher`.
*/
implicitReturnWillBreak(): boolean {
return this.parent.implicitReturnWillBreak();
}
/**
* Patch the end of an implicitly-returned descendant.
*/
patchImplicitReturnEnd(patcher: NodePatcher) { // eslint-disable-line no-unused-vars
// 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() {
this._returns = true;
if (this.parent) {
this.parent.setExplicitlyReturns();
}
}
/**
* 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 {
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 {
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 {
return this.getProgramSourceTokens().indexOfTokenMatchingPredicate(token => {
return (
token.start >= left &&
token.start <= right &&
predicate(token)
);
});
}
/**
* Gets the token at a particular index.
*/
sourceTokenAtIndex(index: SourceTokenListIndex): ?SourceToken {
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 last token in the content of this node.
*/
lastToken() {
return this.sourceTokenAtIndex(this.contentEndTokenIndex);
}
/**
* 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 !this.node.virtual && /\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 {
let index = this.getProgramSourceTokens()
.indexOfTokenMatchingPredicate(predicate, start.next());
if (!index) {
return null;
}
let 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 {
let beforeToken = this.sourceTokenAtIndex(this.outerStartTokenIndex);
let afterToken = this.sourceTokenAtIndex(this.outerEndTokenIndex);
if (!beforeToken || !afterToken) {
return false;
}
let leftTokenType = LPAREN;
let rightTokenType = RPAREN;
if (beforeToken.type === LPAREN && afterToken.type === RPAREN) {
// nothing
} else if (beforeToken.type === CALL_START && afterToken.type === CALL_END) {
leftTokenType = CALL_START;
rightTokenType = CALL_END;
} else {
return false;
}
let parenRange = this.getProgramSourceTokens()
.rangeOfMatchingTokensContainingTokenIndex(
leftTokenType,
rightTokenType,
this.outerStartTokenIndex
);
if (!parenRange) return false;
let rparenIndex = parenRange[1].previous();
let rparen = this.sourceTokenAtIndex(rparenIndex);
return rparen === afterToken;
}
surroundInParens() {
if (!this.isSurroundedByParentheses()) {
this.insert(this.outerStart, '(');
this.insert(this.outerEnd, ')');
}
}
getBoundingPatcher(): ?NodePatcher {
if (this.isSurroundedByParentheses()) {
return this;
} else if (this.parent) {
if (this.isNodeFunctionApplication(this.parent.node) &&
this.parent.node.arguments.some(arg => arg === this.node)) {
return this;
}
return this.parent.getBoundingPatcher();
} else {
return this;
}
}
isNodeFunctionApplication(node) {
return node.type === 'FunctionApplication' ||
node.type === 'SoakedFunctionApplication' ||
node.type === 'NewOp';
}
/**
* Determines whether this patcher's node can be negated without prepending
* a `!`, which turns it into a unary operator node.
*/
canHandleNegationInternally(): boolean {
return false;
}
/**
* Negates this patcher's node when patching.
*/
negate() {
this.insert(this.outerStart, '!');
}
/**
* Gets the indent string for the line that starts this patcher's node.
*/
getIndent(offset: number=0): string {
return adjustIndent(
this.context.source,
this.contentStart,
this.getAdjustedIndentLevel() + offset
);
}
/**
* Force the indentation level of this node, adjusting it forward or backward
* if necessary. This also sets the "adjusted indent" level, so that later
* calls to getIndent will return this value.
*/
setIndent(indentStr: string) {
let currentIndent = this.getIndent();
let indentLength = this.getProgramIndentString().length;
let currentIndentLevel = currentIndent.length / indentLength;
let desiredIndentLevel = indentStr.length / indentLength;
this.indent(desiredIndentLevel - currentIndentLevel);
}
/**
* Get the amount the adjusted indent level differs from the original level.
*/
getAdjustedIndentLevel(): number {
return (
this.adjustedIndentLevel +
(this.parent ? this.parent.getAdjustedIndentLevel() : 0)
);
}
/**
* Gets the indent string used for each indent in this program.
*/
getProgramIndentString(): string {
return this.parent.getProgramIndentString();
}
/**
* Indent this node a number of times. To unindent, pass a negative number.
*
* Note that because this method inserts indents immediately before the first
* non-whitespace character of each line in the node's source, it should be
* called *before* any other editing is done to the node's source to ensure
* that strings inserted before child nodes appear after the indent, not
* before.
*/
indent(offset: number=1) {
if (offset === 0) {
return;
}
this.adjustedIndentLevel += offset;
let indentString = this.getProgramIndentString();
let indentToChange = repeat(indentString, Math.abs(offset));
let start = this.outerStart;
let end = this.outerEnd;
let { source } = this.context;
// See if there are already non-whitespace characters before the start. If
// so, skip the start to the next line, since we don't want to put
// indentation in the middle of a line.
for (let i = start - 1; i >= 0 && source[i] !== '\n'; i--) {
if (source[i] !== '\t' && source[i] !== ' ') {
while (start < end && source[start] !== '\n') {
start++;
}
break;
}
}
let hasIndentedThisLine = false;
for (let i = start; i < end; i++) {
switch (source[i]) {
case '\n':
hasIndentedThisLine = false;
break;
case ' ':
case '\t':
break;
default:
if (!hasIndentedThisLine) {
if (offset > 0) {
this.insert(i, indentToChange);
} else if (source.slice(i - indentToChange.length, i) === indentToChange) {
this.remove(i - indentToChange.length, i);
} else {
throw this.error(
`cannot unindent line by ${offset} without enough indent`,
i - indentToChange.length,
i
);
}
hasIndentedThisLine = true;
}
break;
}
}
}
/**
* Gets the index ending the line following this patcher's node.
*
* @private
*/
getEndOfLine(): number {
let { source } = this.context;
for (let i = this.outerEnd - '\n'.length; i < source.length; i++) {
if (source[i] === '\n') {
return i;
}
}
return source.length;
}
/**
* Appends the given content on a new line after the end of the current line.
*/
appendLineAfter(content: string, indentOffset: number=0) {
let boundingPatcher = this.getBoundingPatcher();
let endOfLine = this.getEndOfLine();
this.insert(
Math.min(endOfLine, boundingPatcher.innerEnd),
`\n${this.getIndent(indentOffset)}${content}`
);
}
/**
* Appends the given content at the end of the current line.
*/
appendToEndOfLine(content: string) {
let boundingPatcher = this.getBoundingPatcher();
let endOfLine = this.getEndOfLine();
this.insert(Math.min(endOfLine, boundingPatcher.innerEnd), content);
}
/**
* Generate an error referring to a particular section of the source.
*/
error(message: string, start: number=this.contentStart, end: number=this.contentEnd, error: ?Error=null): PatcherError {
let patcherError = new PatcherError(message, this.context.source, start, end, error);
if (error) { patcherError.stack = error.stack; }
return patcherError;
}
/**
* Register a helper to be reused in several places.
*/
registerHelper(name: string, code: string): string {
return this.parent.registerHelper(name, code);
}
/**
* Determines whether this node can be repeated without side-effects. Most
* nodes are not repeatable, so that is the default. Subclasses should
* override this to indicate whether they are repeatable without any changes.
*/
isRepeatable(): boolean {
return false;
}
/**
* Alter this node to enable it to be repeated without side-effects. Though
* a default implementation is provided, subclasses should override this to
* provide a more appropriate version for their particular node type.
*/
makeRepeatable(parens: boolean, ref: ?string=null): string {
if (this.isRepeatable()) {
// If we can repeat it, just return the original source.
return this.getOriginalSource();
} else {
// Can't repeat it, so we assign it to a free variable and return that,
// i.e. `a + b` → `(ref = a + b)`.
if (parens) {
this.insert(this.innerStart, '(');
}
ref = this.claimFreeBinding(ref);
this.insert(this.innerStart, `${ref} = `);
if (parens) {
this.insert(this.innerEnd, ')');
}
return ref;
}
}
/**
* Claim a binding that is unique in the current scope.