-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcxMemberOrderingRule.ts
More file actions
1027 lines (740 loc) · 29.4 KB
/
cxMemberOrderingRule.ts
File metadata and controls
1027 lines (740 loc) · 29.4 KB
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 * as Lint from 'tslint';
import { hasModifier } from 'tsutils';
import * as ts from 'typescript';
import { showWarningOnce } from './helpers/error';
import { flatMap, mapDefined } from './helpers/utils';
/* tslint:disable */
/**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const OPTION_ORDER = 'order';
const OPTION_ALPHABETIZE = 'alphabetize';
enum MemberKind {
publicDecoratedField,
publicDecoratedGetter,
publicDecoratedMethod,
publicDecoratedSetter,
protectedDecoratedField,
protectedDecoratedGetter,
protectedDecoratedMethod,
protectedDecoratedSetter,
privateDecoratedField,
privateDecoratedGetter,
privateDecoratedMethod,
privateDecoratedSetter,
publicAbstractField,
publicAbstractGetter,
publicAbstractMethod,
publicAbstractSetter,
protectedAbstractField,
protectedAbstractGetter,
protectedAbstractMethod,
protectedAbstractSetter,
privateAbstractField,
privateAbstractGetter,
privateAbstractMethod,
privateAbstractSetter,
publicReadonlyField,
protectedReadonlyField,
privateReadonlyField,
publicStaticField,
publicStaticGetter,
publicStaticMethod,
publicStaticSetter,
protectedStaticField,
protectedStaticGetter,
protectedStaticMethod,
protectedStaticSetter,
privateStaticField,
privateStaticGetter,
privateStaticMethod,
privateStaticSetter,
publicInstanceField,
publicInstanceGetter,
publicInstanceSetter,
protectedInstanceField,
protectedInstanceGetter,
protectedInstanceSetter,
privateInstanceField,
privateInstanceGetter,
privateInstanceSetter,
publicConstructor,
protectedConstructor,
privateConstructor,
ngInstanceMethod,
publicInstanceMethod,
protectedInstanceMethod,
privateInstanceMethod
}
const PRESETS = new Map<string, MemberCategoryJson[]>([
[
'fields-first', [
'public-static-field',
'protected-static-field',
'private-static-field',
'public-instance-field',
'protected-instance-field',
'private-instance-field',
'constructor',
'public-static-method',
'protected-static-method',
'private-static-method',
'public-instance-method',
'protected-instance-method',
'private-instance-method'
]
],
[
'instance-sandwich', [
'public-static-field',
'protected-static-field',
'private-static-field',
'public-instance-field',
'protected-instance-field',
'private-instance-field',
'constructor',
'public-instance-method',
'protected-instance-method',
'private-instance-method',
'public-static-method',
'protected-static-method',
'private-static-method'
]
],
[
'statics-first', [
'public-static-field',
'public-static-method',
'protected-static-field',
'protected-static-method',
'private-static-field',
'private-static-method',
'public-instance-field',
'protected-instance-field',
'private-instance-field',
'constructor',
'public-instance-method',
'protected-instance-method',
'private-instance-method'
]
]
]);
const PRESET_NAMES = Array.from(PRESETS.keys());
const allMemberKindNames = mapDefined(Object.keys(MemberKind), (key) => {
const mk = (MemberKind as any)[key];
return typeof mk === 'number' ? MemberKind[mk].replace(/[A-Z]/g, (cap) => `-${cap.toLowerCase()}`) : undefined;
});
const namesMarkdown = (names: string[]): string => {
return names.map((name) => {
return `* \`${name}\``;
}).join('\n ');
};
const optionsDescription = Lint.Utils.dedent`
One argument, which is an object, must be provided. It should contain an \`order\` property.
The \`order\` property should have a value of one of the following strings:
${namesMarkdown(PRESET_NAMES)}
Alternatively, the value for \`order\` may be an array consisting of the following strings:
${namesMarkdown(allMemberKindNames)}
You can also omit the access modifier to refer to 'public-', 'protected-',
and 'private-' all at once; for example, 'static-field'.
You can also make your own categories by using an object instead of a string:
{
'name': 'static non-private',
'kinds': [
'public-static-field',
'protected-static-field',
'public-static-method',
'protected-static-method'
]
}
The '${OPTION_ALPHABETIZE}' option will enforce that members within the same
category should be alphabetically sorted by name.`;
export class Rule extends Lint.Rules.AbstractRule {
public static metadata: Lint.IRuleMetadata = {
ruleName: 'member-ordering',
description: 'Enforces member ordering.',
hasFix: true,
rationale: Lint.Utils.dedent`
A consistent ordering for class members can make classes easier to read, navigate, and edit.
A common opposite practice to \`member-ordering\` is to keep related groups of classes together.
Instead of creating classes with multiple separate groups, consider splitting class responsibilities
apart across multiple single-responsibility classes.
`,
optionsDescription,
options: {
type: 'object',
properties: {
order: {
oneOf: [
{
type: 'string',
enum: PRESET_NAMES
},
{
type: 'array',
items: {
type: 'string',
enum: allMemberKindNames
},
maxLength: 13
}
]
}
},
additionalProperties: false
},
optionExamples: [
[true, { order: 'fields-first' }],
[true, {
order: [
'public-static-field',
'public-instance-field',
'public-constructor',
'private-static-field',
'private-instance-field',
'private-constructor',
'public-instance-method',
'protected-instance-method',
'private-instance-method'
]
}],
[true, {
order: [
{
name: 'static non-private',
kinds: [
'public-static-field',
'protected-static-field',
'public-static-method',
'protected-static-method'
]
},
'constructor'
]
}]
],
type: 'typescript',
typescriptOnly: false
};
public static FAILURE_STRING_ALPHABETIZE (prevName: string, curName: string) {
const show = (s: string) => {
return s === '' ? 'Computed property' : `'${s}'`;
};
return `${show(curName)} should come alphabetically before ${show(prevName)}`;
}
public apply (sourceFile: ts.SourceFile): Lint.RuleFailure[] {
let options: Options;
try {
options = parseOptions(this.ruleArguments);
} catch (e) {
showWarningOnce(`Warning: ${this.ruleName} - ${(e as Error).stack}`);
return [];
}
return this.applyWithWalker(new MemberOrderingWalker(sourceFile, this.ruleName, options));
}
}
class MemberOrderingWalker extends Lint.AbstractWalker<Options> {
private readonly fixes: Array<[Lint.RuleFailure, Lint.Replacement]> = [];
public walk (sourceFile: ts.SourceFile) {
const cb = (node: ts.Node) => {
// NB: iterate through children first!
ts.forEachChild(node, cb);
switch (node.kind) {
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.ClassExpression:
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.TypeLiteral:
this.checkMembers(
(node as ts.ClassLikeDeclaration | ts.InterfaceDeclaration | ts.TypeLiteralNode).members
);
}
};
ts.forEachChild(sourceFile, cb);
// assign Replacements which have not been merged into surrounding ones to their RuleFailures.
this.fixes.forEach(([failure, replacement]) => {
(failure.getFix() as Lint.Replacement[]).push(replacement);
});
}
/**
* Check wether the passed members adhere to the configured order. If not, RuleFailures are generated and a single
* Lint.Replacement is generated, which replaces the entire NodeArray with a correctly sorted one. The Replacement
* is not immediately added to a RuleFailure, as incorrectly sorted nodes can be nested (e.g. a class declaration
* in a method implementation), but instead temporarily stored in `this.fixes`. Nested Replacements are manually
* merged, as TSLint doesn't handle overlapping ones. For this reason it is important that the recursion happens
* before the checkMembers call in this.walk().
*/
private checkMembers (members: ts.NodeArray<Member>) {
let prevRank = -1;
let prevName: string | undefined;
let failureExists = false;
for (const member of members) {
const rank = this.memberRank(member);
if (rank === -1) {
// no explicit ordering for this kind of node specified, so continue
continue;
}
if (rank < prevRank) {
const nodeType = this.rankName(rank);
const prevNodeType = this.rankName(prevRank);
const lowerRank = this.findLowerRank(members, rank);
const locationHint = lowerRank !== -1
? `after ${this.rankName(lowerRank)}s`
: 'at the beginning of the class/interface';
const errorLine1 = `Declaration of ${nodeType} not allowed after declaration of ${prevNodeType}. `
+ `Instead, this should come ${locationHint}.`;
// add empty array as fix so we can add a replacement later. (fix itself is readonly)
this.addFailureAtNode(member, errorLine1, []);
failureExists = true;
} else {
if (this.options.alphabetize && member.name !== undefined) {
if (rank !== prevRank) {
// No alphabetical ordering between different ranks
prevName = undefined;
}
const curName = decoratedNameString(member);
if (prevName !== undefined && caseInsensitiveLess(curName, prevName)) {
this.addFailureAtNode(
member.name,
Rule.FAILURE_STRING_ALPHABETIZE(this.findLowerName(members, rank, curName), curName), []);
failureExists = true;
} else {
prevName = curName;
}
}
// keep track of last good node
prevRank = rank;
}
}
if (failureExists) {
const sortedMemberIndexes = members.map((_, i) => {
return i;
}).sort((ai, bi) => {
const a = members[ai];
const b = members[bi];
// first, sort by member rank
const rankDiff = this.memberRank(a) - this.memberRank(b);
if (rankDiff !== 0) {
return rankDiff;
}
// then lexicographically if alphabetize == true
if (this.options.alphabetize && a.name !== undefined && b.name !== undefined) {
const aName = decoratedNameString(a);
const bName = decoratedNameString(b);
const nameDiff = aName.localeCompare(bName);
if (nameDiff !== 0) {
return nameDiff;
}
}
// finally, sort by position in original NodeArray so the sort remains stable.
return ai - bi;
});
const splits = getSplitIndexes(members, this.sourceFile.text);
const sortedMembersText = sortedMemberIndexes.map((i) => {
const start = splits[i];
const end = splits[i + 1];
let nodeText = this.sourceFile.text.substring(start, end);
while (true) {
// check if there are previous fixes which we need to merge into this one
// if yes, remove it from the list so that we do not return overlapping Replacements
const fixIndex = arrayFindLastIndex(
this.fixes,
([, r]) => {
return r.start >= start && r.start + r.length <= end;
}
);
if (fixIndex === -1) {
break;
}
const fix = this.fixes.splice(fixIndex, 1)[0];
const [, replacement] = fix;
nodeText = applyReplacementOffset(nodeText, replacement, start);
}
return nodeText;
});
// instead of assigning the fix immediately to the last failure, we temporarily store it in `this.fixes`,
// in case a containing node needs to be fixed too. We only 'add' the fix to the last failure, although
// it fixes all failures in this NodeArray, as TSLint doesn't handle duplicate Replacements.
this.fixes.push([
arrayLast(this.failures),
Lint.Replacement.replaceFromTo(splits[0], arrayLast(splits), sortedMembersText.join(''))
]);
}
}
/** Finds the lowest name higher than 'targetName'. */
private findLowerName (members: ReadonlyArray<Member>, targetRank: Rank, targetName: string): string {
for (const member of members) {
if (member.name === undefined || this.memberRank(member) !== targetRank) {
continue;
}
const name = decoratedNameString(member);
if (caseInsensitiveLess(targetName, name)) {
return name;
}
}
throw new Error('Expected to find a name');
}
/** Finds the highest existing rank lower than `targetRank`. */
private findLowerRank (members: ReadonlyArray<Member>, targetRank: Rank): Rank | -1 {
let max: Rank | -1 = -1;
for (const member of members) {
const rank = this.memberRank(member);
if (rank !== -1 && rank < targetRank) {
max = Math.max(max, rank);
}
}
return max;
}
private memberRank (member: Member): Rank | -1 {
const optionName = getMemberKind(member);
if (optionName === undefined) {
return -1;
}
return this.options.order.findIndex((category) => {
return category.has(optionName);
});
}
private rankName (rank: Rank): string {
return this.options.order[rank].name;
}
}
const caseInsensitiveLess = (a: string, b: string) => {
return a.toLowerCase() < b.toLowerCase();
};
const memberKindForConstructor = (access: Access): MemberKind => {
return (MemberKind as any)[`${access}Constructor`] as MemberKind;
};
type AllowedMembers = 'Decorated' | 'Abstract' | 'Getter' | 'Readonly' | 'Setter' | 'Static' | 'Instance';
type AllowedKinds = 'Method' | 'Field' | 'Getter' | 'Setter';
const memberKindForMethodOrField = (access: Access, membership: AllowedMembers, kind: AllowedKinds): MemberKind => {
return (MemberKind as any)[access + membership + kind] as MemberKind;
};
const allAccess: Access[] = ['public', 'protected', 'private'];
const getMembership = (member: Member): AllowedMembers => {
if (member.decorators && member.decorators.length) {
return 'Decorated';
}
if (hasModifier(member.modifiers, ts.SyntaxKind.AbstractKeyword)) {
return 'Abstract';
}
if (hasModifier(member.modifiers, ts.SyntaxKind.StaticKeyword)) {
return 'Static';
}
if (hasModifier(member.modifiers, ts.SyntaxKind.ReadonlyKeyword)) {
return 'Readonly';
}
return 'Instance';
};
const memberKindFromName = (name: string): MemberKind[] => {
const kind = (MemberKind as any)[Lint.Utils.camelize(name)];
const addModifier = (modifier: string) => {
const modifiedKind = (MemberKind as any)[Lint.Utils.camelize(`${modifier}-${name}`)];
if (typeof modifiedKind !== 'number') {
throw new Error(`Bad member kind: ${name}`);
}
return modifiedKind;
};
return typeof kind === 'number' ? [kind as MemberKind] : allAccess.map(addModifier);
};
const getMemberKind = (member: Member): MemberKind | undefined => {
const accessLevel = hasModifier(member.modifiers, ts.SyntaxKind.PrivateKeyword) ? 'private'
: hasModifier(member.modifiers, ts.SyntaxKind.ProtectedKeyword) ? 'protected'
: 'public';
const accessor = (type: 'Getter' | 'Setter') => {
const membership = getMembership(member);
return memberKindForMethodOrField(accessLevel, membership, type);
};
const methodOrField = (isMethod: boolean) => {
if (isMethod && testForNg()) {
return MemberKind.ngInstanceMethod;
}
const methodOrField = isMethod ? 'Method' : 'Field';
const membership = getMembership(member);
return memberKindForMethodOrField(accessLevel, membership, methodOrField);
};
const testForNg = () => {
return member.name != null && nameString(member.name).startsWith('ng');
};
switch (member.kind) {
case ts.SyntaxKind.Constructor:
case ts.SyntaxKind.ConstructSignature:
return memberKindForConstructor(accessLevel);
case ts.SyntaxKind.GetAccessor:
return accessor('Getter');
case ts.SyntaxKind.SetAccessor:
return accessor('Setter');
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.PropertySignature:
return methodOrField(isFunctionLiteral((member as ts.PropertyDeclaration).initializer));
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.MethodSignature:
return methodOrField(true);
default:
return undefined;
}
};
type MemberCategoryJson = { name: string; kinds: string[] } | string;
class MemberCategory {
constructor (readonly name: string, private readonly kinds: Set<MemberKind>) {}
public has (kind: MemberKind) {
return this.kinds.has(kind);
}
}
type Member = ts.TypeElement | ts.ClassElement;
type Rank = number;
type Access = 'public' | 'protected' | 'private';
interface Options {
order: MemberCategory[];
alphabetize: boolean;
}
const parseOptions = (options: any[]): Options => {
const { order: orderJson, alphabetize } = getOptionsJson(options);
const order = orderJson.map((cat) => {
return typeof cat === 'string'
? new MemberCategory(cat.replace(/-/g, ' '), new Set(memberKindFromName(cat)))
: new MemberCategory(cat.name, new Set(flatMap(cat.kinds, memberKindFromName)));
});
return { order, alphabetize };
};
const getOptionsJson = (allOptions: any[]): { order: MemberCategoryJson[]; alphabetize: boolean } => {
if (allOptions === undefined || allOptions.length === 0 || allOptions[0] === undefined) {
throw new Error('Got empty options');
}
const firstOption = allOptions[0] as { order: MemberCategoryJson[] | string; alphabetize?: boolean } | string;
if (typeof firstOption !== 'object') {
// Undocumented direct string option. Deprecate eventually.
// presume allOptions to be string[]
return { order: convertFromOldStyleOptions(allOptions), alphabetize: false };
}
return {
alphabetize: firstOption[OPTION_ALPHABETIZE] === true,
order: categoryFromOption(firstOption[OPTION_ORDER])
};
};
const categoryFromOption = (orderOption: MemberCategoryJson[] | string): MemberCategoryJson[] => {
if (Array.isArray(orderOption)) {
return orderOption;
}
const preset = PRESETS.get(orderOption);
if (preset === undefined) {
throw new Error(`Bad order: ${JSON.stringify(orderOption)}`);
}
return preset;
};
/**
* Convert from undocumented old-style options.
* This is designed to mimic the old behavior and should be removed eventually.
*/
const convertFromOldStyleOptions = (options: string[]): MemberCategoryJson[] => {
const hasOption = (x: string): boolean => {
return options.indexOf(x) !== -1;
};
let categories: NameAndKinds[] = [{ name: 'member', kinds: allMemberKindNames }];
if (hasOption('variables-before-functions')) {
categories = splitOldStyleOptions(categories, (kind) => kind.includes('field'), 'field', 'method');
}
if (hasOption('static-before-instance')) {
categories = splitOldStyleOptions(categories, (kind) => kind.includes('static'), 'static', 'instance');
}
if (hasOption('public-before-private')) {
// 'protected' is considered public
categories = splitOldStyleOptions(categories, (kind) => !kind.includes('private'), 'public', 'private');
}
return categories;
};
interface NameAndKinds { name: string; kinds: string[]; }
const splitOldStyleOptions = (
categories: NameAndKinds[], filter: (name: string) => boolean, a: string, b: string
): NameAndKinds[] => {
const newCategories: NameAndKinds[] = [];
for (const cat of categories) {
const yes = []; const no = [];
for (const kind of cat.kinds) {
if (filter(kind)) {
yes.push(kind);
} else {
no.push(kind);
}
}
const augmentName = (s: string) => {
if (a === 'field') {
// Replace 'member' with 'field'/'method' instead of augmenting.
return s;
}
return `${s} ${cat.name}`;
};
newCategories.push({ name: augmentName(a), kinds: yes });
newCategories.push({ name: augmentName(b), kinds: no });
}
return newCategories;
};
const isFunctionLiteral = (node: ts.Node | undefined) => {
if (node === undefined) {
return false;
}
switch (node.kind) {
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.FunctionExpression:
return true;
default:
return false;
}
};
const decoratedNameString = (member: Member): string => {
if (member.name == null) {
return '';
}
let decoratorNames = '';
if (member.decorators) {
decoratorNames = member.decorators.map((decorator) => decorator.getText().replace(/@|(\([^)]*\))/gm, '')).join('');
}
return decoratorNames + nameString(member.name);
};
const nameString = (name: ts.PropertyName): string => {
switch (name.kind) {
case ts.SyntaxKind.Identifier:
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NumericLiteral:
return (name as ts.Identifier | ts.LiteralExpression).text;
default:
return '';
}
};
/**
* Returns the last element of an array. (Or undefined).
*/
const arrayLast = <T extends {}>(array: ArrayLike<T>): T => {
if (array && array.length) {
return array[array.length - 1];
}
};
/**
* Array.prototype.findIndex, but the last index.
*/
const arrayFindLastIndex = <T extends {}>(
array: ArrayLike<T>,
predicate: (el: T, elIndex: number, array: ArrayLike<T>) => boolean
): number => {
if (array && array.length) {
for (let i = array.length; i-- > 0;) {
if (predicate(array[i], i, array)) {
return i;
}
}
}
return -1;
};
/**
* Applies a Replacement to a part of the text which starts at offset.
* See also Replacement.apply
*/
const applyReplacementOffset = (content: string, replacement: Lint.Replacement, offset: number) => {
return content.substring(0, replacement.start - offset)
+ replacement.text
+ content.substring(replacement.start - offset + replacement.length);
};
/**
* Get the indexes of the boundaries between nodes in the node array. The following points must be taken into account:
* - Trivia should stay with its corresponding node (comments on the same line following the token belong to the
* previous token, the rest to the next).
* - Reordering the subtexts should not result in code being commented out due to being moved between a '//' and
* the following newline.
* - The end of one node must be the start of the next, otherwise the intravening whitespace will be lost when
* reordering.
*
* Hence, the boundaries are chosen to be _after_ the newline following the node, or the beginning of the next token,
* if that comes first.
*/
const getSplitIndexes = (members: ts.NodeArray<Member>, text: string) => {
const result = members.map((member) => getNextSplitIndex(text, member.getFullStart()));
result.push(getNextSplitIndex(text, arrayLast(members).getEnd()));
return result;
};
/**
* Calculates the index after the newline following pos, or the beginning of the next token, whichever comes first.
* See also getSplitIndexes.
* This method is a modified version of TypeScript's internal iterateCommentRanges const. => =
*/
const getNextSplitIndex = (text: string, pos: number) => {
const enum CharacterCodes {
lineFeed = 0x0A, // \n
carriageReturn = 0x0D, // \r
formFeed = 0x0C, // \f
tab = 0x09, // \t
verticalTab = 0x0B, // \v
slash = 0x2F, // /
asterisk = 0x2A, // *
space = 0x0020, // ' '
maxAsciiCharacter = 0x7F
}
scan: while (pos >= 0 && pos < text.length) {
const ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
// falls through
case CharacterCodes.lineFeed:
pos++;
// split is after new line
return pos;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
// skip whitespace
pos++;
continue;
case CharacterCodes.slash:
const nextChar = text.charCodeAt(pos + 1);
if (nextChar === CharacterCodes.slash || nextChar === CharacterCodes.asterisk) {
const isSingleLineComment = nextChar === CharacterCodes.slash;
pos += 2;
if (isSingleLineComment) {
while (pos < text.length) {
if (ts.isLineBreak(text.charCodeAt(pos))) {
// the comment ends here, go back to default logic to handle parsing new line and result
continue scan;
}
pos++;
}
} else {
while (pos < text.length) {
if (
text.charCodeAt(pos) === CharacterCodes.asterisk
&& text.charCodeAt(pos + 1) === CharacterCodes.slash
) {
pos += 2;
continue scan;
}