-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
index.ts
1731 lines (1575 loc) · 55.5 KB
/
index.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
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import {
AST_NODE_TYPES,
AST_TOKEN_TYPES,
TSESLint,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import { OffsetStorage } from './OffsetStorage';
import { TokenInfo } from './TokenInfo';
import {
createRule,
ExcludeKeys,
isClosingBraceToken,
isClosingBracketToken,
isClosingParenToken,
isColonToken,
isCommentToken,
isNotClosingParenToken,
isNotOpeningParenToken,
isOpeningBraceToken,
isOpeningParenToken,
isSemicolonToken,
RequireKeys,
} from '../../util';
const GLOBAL_LINEBREAK_REGEX = /\r\n|[\r\n\u2028\u2029]/gu;
const WHITESPACE_REGEX = /\s*$/u;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const KNOWN_NODES = new Set([
AST_NODE_TYPES.AssignmentExpression,
AST_NODE_TYPES.AssignmentPattern,
AST_NODE_TYPES.ArrayExpression,
AST_NODE_TYPES.ArrayPattern,
AST_NODE_TYPES.ArrowFunctionExpression,
AST_NODE_TYPES.AwaitExpression,
AST_NODE_TYPES.BlockStatement,
AST_NODE_TYPES.BinaryExpression,
AST_NODE_TYPES.BreakStatement,
AST_NODE_TYPES.CallExpression,
AST_NODE_TYPES.CatchClause,
AST_NODE_TYPES.ClassBody,
AST_NODE_TYPES.ClassDeclaration,
AST_NODE_TYPES.ClassExpression,
AST_NODE_TYPES.ConditionalExpression,
AST_NODE_TYPES.ContinueStatement,
AST_NODE_TYPES.DoWhileStatement,
AST_NODE_TYPES.DebuggerStatement,
AST_NODE_TYPES.EmptyStatement,
AST_NODE_TYPES.ExpressionStatement,
AST_NODE_TYPES.ForStatement,
AST_NODE_TYPES.ForInStatement,
AST_NODE_TYPES.ForOfStatement,
AST_NODE_TYPES.FunctionDeclaration,
AST_NODE_TYPES.FunctionExpression,
AST_NODE_TYPES.Identifier,
AST_NODE_TYPES.IfStatement,
AST_NODE_TYPES.Literal,
AST_NODE_TYPES.LabeledStatement,
AST_NODE_TYPES.LogicalExpression,
AST_NODE_TYPES.MemberExpression,
AST_NODE_TYPES.MetaProperty,
AST_NODE_TYPES.MethodDefinition,
AST_NODE_TYPES.NewExpression,
AST_NODE_TYPES.ObjectExpression,
AST_NODE_TYPES.ObjectPattern,
AST_NODE_TYPES.Program,
AST_NODE_TYPES.Property,
AST_NODE_TYPES.RestElement,
AST_NODE_TYPES.ReturnStatement,
AST_NODE_TYPES.SequenceExpression,
AST_NODE_TYPES.SpreadElement,
AST_NODE_TYPES.Super,
AST_NODE_TYPES.SwitchCase,
AST_NODE_TYPES.SwitchStatement,
AST_NODE_TYPES.TaggedTemplateExpression,
AST_NODE_TYPES.TemplateElement,
AST_NODE_TYPES.TemplateLiteral,
AST_NODE_TYPES.ThisExpression,
AST_NODE_TYPES.ThrowStatement,
AST_NODE_TYPES.TryStatement,
AST_NODE_TYPES.UnaryExpression,
AST_NODE_TYPES.UpdateExpression,
AST_NODE_TYPES.VariableDeclaration,
AST_NODE_TYPES.VariableDeclarator,
AST_NODE_TYPES.WhileStatement,
AST_NODE_TYPES.WithStatement,
AST_NODE_TYPES.YieldExpression,
AST_NODE_TYPES.JSXIdentifier,
AST_NODE_TYPES.JSXMemberExpression,
AST_NODE_TYPES.JSXEmptyExpression,
AST_NODE_TYPES.JSXExpressionContainer,
AST_NODE_TYPES.JSXElement,
AST_NODE_TYPES.JSXClosingElement,
AST_NODE_TYPES.JSXOpeningElement,
AST_NODE_TYPES.JSXAttribute,
AST_NODE_TYPES.JSXSpreadAttribute,
AST_NODE_TYPES.JSXText,
AST_NODE_TYPES.ExportDefaultDeclaration,
AST_NODE_TYPES.ExportNamedDeclaration,
AST_NODE_TYPES.ExportAllDeclaration,
AST_NODE_TYPES.ExportSpecifier,
AST_NODE_TYPES.ImportDeclaration,
AST_NODE_TYPES.ImportSpecifier,
AST_NODE_TYPES.ImportDefaultSpecifier,
AST_NODE_TYPES.ImportNamespaceSpecifier,
// Class properties aren't yet supported by eslint...
AST_NODE_TYPES.ClassProperty,
// ts keywords
AST_NODE_TYPES.TSAbstractKeyword,
AST_NODE_TYPES.TSAnyKeyword,
AST_NODE_TYPES.TSBooleanKeyword,
AST_NODE_TYPES.TSNeverKeyword,
AST_NODE_TYPES.TSNumberKeyword,
AST_NODE_TYPES.TSStringKeyword,
AST_NODE_TYPES.TSSymbolKeyword,
AST_NODE_TYPES.TSUndefinedKeyword,
AST_NODE_TYPES.TSUnknownKeyword,
AST_NODE_TYPES.TSVoidKeyword,
AST_NODE_TYPES.TSNullKeyword,
// ts specific nodes we want to support
AST_NODE_TYPES.TSAbstractClassProperty,
AST_NODE_TYPES.TSAbstractMethodDefinition,
AST_NODE_TYPES.TSArrayType,
AST_NODE_TYPES.TSAsExpression,
AST_NODE_TYPES.TSCallSignatureDeclaration,
AST_NODE_TYPES.TSConditionalType,
AST_NODE_TYPES.TSConstructorType,
AST_NODE_TYPES.TSConstructSignatureDeclaration,
AST_NODE_TYPES.TSDeclareFunction,
AST_NODE_TYPES.TSEmptyBodyFunctionExpression,
AST_NODE_TYPES.TSEnumDeclaration,
AST_NODE_TYPES.TSEnumMember,
AST_NODE_TYPES.TSExportAssignment,
AST_NODE_TYPES.TSExternalModuleReference,
AST_NODE_TYPES.TSFunctionType,
AST_NODE_TYPES.TSImportType,
AST_NODE_TYPES.TSIndexedAccessType,
AST_NODE_TYPES.TSIndexSignature,
AST_NODE_TYPES.TSInferType,
AST_NODE_TYPES.TSInterfaceBody,
AST_NODE_TYPES.TSInterfaceDeclaration,
AST_NODE_TYPES.TSInterfaceHeritage,
AST_NODE_TYPES.TSIntersectionType,
AST_NODE_TYPES.TSImportEqualsDeclaration,
AST_NODE_TYPES.TSLiteralType,
AST_NODE_TYPES.TSMappedType,
AST_NODE_TYPES.TSMethodSignature,
'TSMinusToken',
AST_NODE_TYPES.TSModuleBlock,
AST_NODE_TYPES.TSModuleDeclaration,
AST_NODE_TYPES.TSNonNullExpression,
AST_NODE_TYPES.TSParameterProperty,
AST_NODE_TYPES.TSParenthesizedType,
'TSPlusToken',
AST_NODE_TYPES.TSPropertySignature,
AST_NODE_TYPES.TSQualifiedName,
'TSQuestionToken',
AST_NODE_TYPES.TSRestType,
AST_NODE_TYPES.TSThisType,
AST_NODE_TYPES.TSTupleType,
AST_NODE_TYPES.TSTypeAnnotation,
AST_NODE_TYPES.TSTypeLiteral,
AST_NODE_TYPES.TSTypeOperator,
AST_NODE_TYPES.TSTypeParameter,
AST_NODE_TYPES.TSTypeParameterDeclaration,
AST_NODE_TYPES.TSTypeParameterInstantiation,
AST_NODE_TYPES.TSTypeReference,
AST_NODE_TYPES.TSUnionType,
]);
const STATEMENT_LIST_PARENTS = new Set([
AST_NODE_TYPES.Program,
AST_NODE_TYPES.BlockStatement,
AST_NODE_TYPES.SwitchCase,
]);
const DEFAULT_VARIABLE_INDENT = 1;
const DEFAULT_PARAMETER_INDENT = 1;
const DEFAULT_FUNCTION_BODY_INDENT = 1;
/*
* General rule strategy:
* 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another
* specified token or to the first column.
* 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a
* BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly
* brace of the BlockStatement.
* 3. After traversing the AST, calculate the expected indentation levels of every token according to the
* OffsetStorage container.
* 4. For each line, compare the expected indentation of the first token to the actual indentation in the file,
* and report the token if the two values are not equal.
*/
const ELEMENT_LIST_SCHEMA = {
oneOf: [
{
type: 'integer',
minimum: 0,
},
{
enum: ['first', 'off'],
},
],
};
interface VariableDeclaratorObj {
var?: ElementList;
let?: ElementList;
const?: ElementList;
}
type ElementList = number | 'first' | 'off';
interface IndentConfig {
SwitchCase?: number;
VariableDeclarator?: ElementList | VariableDeclaratorObj;
outerIIFEBody?: number;
MemberExpression?: number | 'off';
FunctionDeclaration?: {
parameters?: ElementList;
body?: number;
};
FunctionExpression?: {
parameters?: ElementList;
body?: number;
};
CallExpression?: {
arguments?: ElementList;
};
ArrayExpression?: ElementList;
ObjectExpression?: ElementList;
ImportDeclaration?: ElementList;
flatTernaryExpressions?: boolean;
ignoredNodes?: string[];
ignoreComments?: boolean;
}
type Options = [('tab' | number)?, IndentConfig?];
type MessageIds = 'wrongIndentation';
type AppliedOptions = ExcludeKeys<
// slight hack to make interface work with Record<string, unknown>
RequireKeys<Pick<IndentConfig, keyof IndentConfig>, keyof IndentConfig>,
AST_NODE_TYPES.VariableDeclarator
> & {
VariableDeclarator: 'off' | VariableDeclaratorObj;
};
export default createRule<Options, MessageIds>({
name: 'indent',
meta: {
type: 'layout',
docs: {
description: 'Enforce consistent indentation.',
category: 'Stylistic Issues',
recommended: false,
},
fixable: 'whitespace',
schema: [
{
oneOf: [
{
enum: ['tab'],
},
{
type: 'integer',
minimum: 0,
},
],
},
{
type: 'object',
properties: {
SwitchCase: {
type: 'integer',
minimum: 0,
default: 0,
},
VariableDeclarator: {
oneOf: [
ELEMENT_LIST_SCHEMA,
{
type: 'object',
properties: {
var: ELEMENT_LIST_SCHEMA,
let: ELEMENT_LIST_SCHEMA,
const: ELEMENT_LIST_SCHEMA,
},
additionalProperties: false,
},
],
},
outerIIFEBody: {
type: 'integer',
minimum: 0,
},
MemberExpression: {
oneOf: [
{
type: 'integer',
minimum: 0,
},
{
enum: ['off'],
},
],
},
FunctionDeclaration: {
type: 'object',
properties: {
parameters: ELEMENT_LIST_SCHEMA,
body: {
type: 'integer',
minimum: 0,
},
},
additionalProperties: false,
},
FunctionExpression: {
type: 'object',
properties: {
parameters: ELEMENT_LIST_SCHEMA,
body: {
type: 'integer',
minimum: 0,
},
},
additionalProperties: false,
},
CallExpression: {
type: 'object',
properties: {
arguments: ELEMENT_LIST_SCHEMA,
},
additionalProperties: false,
},
ArrayExpression: ELEMENT_LIST_SCHEMA,
ObjectExpression: ELEMENT_LIST_SCHEMA,
ImportDeclaration: ELEMENT_LIST_SCHEMA,
flatTernaryExpressions: {
type: 'boolean',
default: false,
},
ignoredNodes: {
type: 'array',
items: {
type: 'string',
not: {
pattern: ':exit$',
},
},
},
ignoreComments: {
type: 'boolean',
default: false,
},
},
additionalProperties: false,
},
],
messages: {
wrongIndentation:
'Expected indentation of {{expected}} but found {{actual}}.',
},
},
defaultOptions: [
// typescript docs and playground use 4 space indent
4,
{
// typescript docs indent the case from the switch
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#example-4
SwitchCase: 1,
VariableDeclarator: {
var: DEFAULT_VARIABLE_INDENT,
let: DEFAULT_VARIABLE_INDENT,
const: DEFAULT_VARIABLE_INDENT,
},
outerIIFEBody: 1,
FunctionDeclaration: {
parameters: DEFAULT_PARAMETER_INDENT,
body: DEFAULT_FUNCTION_BODY_INDENT,
},
FunctionExpression: {
parameters: DEFAULT_PARAMETER_INDENT,
body: DEFAULT_FUNCTION_BODY_INDENT,
},
CallExpression: {
arguments: DEFAULT_PARAMETER_INDENT,
},
MemberExpression: 1,
ArrayExpression: 1,
ObjectExpression: 1,
ImportDeclaration: 1,
flatTernaryExpressions: false,
ignoredNodes: [],
ignoreComments: false,
},
],
create(context, [userIndent, userOptions]) {
const indentType = userIndent === 'tab' ? 'tab' : 'space';
const indentSize = userIndent === 'tab' ? 1 : userIndent!;
const options = userOptions as AppliedOptions;
if (
typeof userOptions!.VariableDeclarator === 'number' ||
userOptions!.VariableDeclarator === 'first'
) {
// typescript doesn't narrow the type for some reason
options.VariableDeclarator = {
var: userOptions!.VariableDeclarator as number | 'first',
let: userOptions!.VariableDeclarator as number | 'first',
const: userOptions!.VariableDeclarator as number | 'first',
};
}
const sourceCode = context.getSourceCode();
const tokenInfo = new TokenInfo(sourceCode);
const offsets = new OffsetStorage(
tokenInfo,
indentSize,
indentType === 'space' ? ' ' : '\t',
);
const parameterParens = new WeakSet<TSESTree.Token>();
/**
* Creates an error message for a line, given the expected/actual indentation.
* @param expectedAmount The expected amount of indentation characters for this line
* @param actualSpaces The actual number of indentation spaces that were found on this line
* @param actualTabs The actual number of indentation tabs that were found on this line
* @returns An error message for this line
*/
function createErrorMessageData(
expectedAmount: number,
actualSpaces: number,
actualTabs: number,
): { expected: string; actual: string | number } {
const expectedStatement = `${expectedAmount} ${indentType}${
expectedAmount === 1 ? '' : 's'
}`; // e.g. "2 tabs"
const foundSpacesWord = `space${actualSpaces === 1 ? '' : 's'}`; // e.g. "space"
const foundTabsWord = `tab${actualTabs === 1 ? '' : 's'}`; // e.g. "tabs"
let foundStatement;
if (actualSpaces > 0) {
/*
* Abbreviate the message if the expected indentation is also spaces.
* e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
*/
foundStatement =
indentType === 'space'
? actualSpaces
: `${actualSpaces} ${foundSpacesWord}`;
} else if (actualTabs > 0) {
foundStatement =
indentType === 'tab' ? actualTabs : `${actualTabs} ${foundTabsWord}`;
} else {
foundStatement = '0';
}
return {
expected: expectedStatement,
actual: foundStatement,
};
}
/**
* Reports a given indent violation
* @param token Token violating the indent rule
* @param neededIndent Expected indentation string
*/
function report(token: TSESTree.Token, neededIndent: string): void {
const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
const numSpaces = actualIndent.filter(char => char === ' ').length;
const numTabs = actualIndent.filter(char => char === '\t').length;
context.report({
node: token,
messageId: 'wrongIndentation',
data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
loc: {
start: { line: token.loc.start.line, column: 0 },
end: { line: token.loc.start.line, column: token.loc.start.column },
},
fix(fixer) {
return fixer.replaceTextRange(
[token.range[0] - token.loc.start.column, token.range[0]],
neededIndent,
);
},
});
}
/**
* Checks if a token's indentation is correct
* @param token Token to examine
* @param desiredIndent Desired indentation of the string
* @returns `true` if the token's indentation is correct
*/
function validateTokenIndent(
token: TSESTree.Token,
desiredIndent: string,
): boolean {
const indentation = tokenInfo.getTokenIndent(token);
return (
indentation === desiredIndent ||
// To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
(indentation.includes(' ') && indentation.includes('\t'))
);
}
/**
* Check to see if the node is a file level IIFE
* @param node The function node to check.
* @returns True if the node is the outer IIFE
*/
function isOuterIIFE(node: TSESTree.Node): boolean {
/*
* Verify that the node is an IIFE
*/
if (
!node.parent ||
node.parent.type !== AST_NODE_TYPES.CallExpression ||
node.parent.callee !== node
) {
return false;
}
/*
* Navigate legal ancestors to determine whether this IIFE is outer.
* A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
* For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
*/
let statement = node.parent?.parent;
while (
statement &&
((statement.type === AST_NODE_TYPES.UnaryExpression &&
['!', '~', '+', '-'].includes(statement.operator)) ||
statement.type === AST_NODE_TYPES.AssignmentExpression ||
statement.type === AST_NODE_TYPES.LogicalExpression ||
statement.type === AST_NODE_TYPES.SequenceExpression ||
statement.type === AST_NODE_TYPES.VariableDeclarator)
) {
statement = statement.parent;
}
return (
!!statement &&
(statement.type === AST_NODE_TYPES.ExpressionStatement ||
statement.type === AST_NODE_TYPES.VariableDeclaration) &&
!!statement.parent &&
statement.parent.type === AST_NODE_TYPES.Program
);
}
/**
* Counts the number of linebreaks that follow the last non-whitespace character in a string
* @param str The string to check
* @returns The number of JavaScript linebreaks that follow the last non-whitespace character,
* or the total number of linebreaks if the string is all whitespace.
*/
function countTrailingLinebreaks(str: string): number {
const trailingWhitespace = WHITESPACE_REGEX.exec(str)![0];
const linebreakMatches = GLOBAL_LINEBREAK_REGEX.exec(trailingWhitespace);
return linebreakMatches === null ? 0 : linebreakMatches.length;
}
/**
* Check indentation for lists of elements (arrays, objects, function params)
* @param elements List of elements that should be offset
* @param startToken The start token of the list that element should be aligned against, e.g. '['
* @param endToken The end token of the list, e.g. ']'
* @param offset The amount that the elements should be offset
*/
function addElementListIndent(
elements: (TSESTree.Node | null)[],
startToken: TSESTree.Token,
endToken: TSESTree.Token,
offset: number | string,
): void {
/**
* Gets the first token of a given element, including surrounding parentheses.
* @param element A node in the `elements` list
* @returns The first token of this element
*/
function getFirstToken(element: TSESTree.Node): TSESTree.Token {
let token = sourceCode.getTokenBefore(element)!;
while (isOpeningParenToken(token) && token !== startToken) {
token = sourceCode.getTokenBefore(token)!;
}
return sourceCode.getTokenAfter(token)!;
}
// Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
offsets.setDesiredOffsets(
[startToken.range[1], endToken.range[0]],
startToken,
typeof offset === 'number' ? offset : 1,
);
offsets.setDesiredOffset(endToken, startToken, 0);
// If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
const firstElement = elements[0];
if (offset === 'first' && elements.length && !firstElement) {
return;
}
elements.forEach((element, index) => {
if (!element) {
// Skip holes in arrays
return;
}
if (offset === 'off') {
// Ignore the first token of every element if the "off" option is used
offsets.ignoreToken(getFirstToken(element));
}
// Offset the following elements correctly relative to the first element
if (index === 0) {
return;
}
if (
offset === 'first' &&
tokenInfo.isFirstTokenOfLine(getFirstToken(element))
) {
offsets.matchOffsetOf(
getFirstToken(firstElement!),
getFirstToken(element),
);
} else {
const previousElement = elements[index - 1];
const firstTokenOfPreviousElement =
previousElement && getFirstToken(previousElement);
const previousElementLastToken =
previousElement && sourceCode.getLastToken(previousElement)!;
if (
previousElement &&
previousElementLastToken &&
previousElementLastToken.loc.end.line -
countTrailingLinebreaks(previousElementLastToken.value) >
startToken.loc.end.line
) {
offsets.setDesiredOffsets(
[previousElement.range[1], element.range[1]],
firstTokenOfPreviousElement,
0,
);
}
}
});
}
/**
* Check and decide whether to check for indentation for blockless nodes
* Scenarios are for or while statements without braces around them
*/
function addBlocklessNodeIndent(node: TSESTree.Node): void {
if (node.type !== AST_NODE_TYPES.BlockStatement) {
const lastParentToken = sourceCode.getTokenBefore(
node,
isNotOpeningParenToken,
)!;
let firstBodyToken = sourceCode.getFirstToken(node)!;
let lastBodyToken = sourceCode.getLastToken(node)!;
while (
isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)!) &&
isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken)!)
) {
firstBodyToken = sourceCode.getTokenBefore(firstBodyToken)!;
lastBodyToken = sourceCode.getTokenAfter(lastBodyToken)!;
}
offsets.setDesiredOffsets(
[firstBodyToken.range[0], lastBodyToken.range[1]],
lastParentToken,
1,
);
/*
* For blockless nodes with semicolon-first style, don't indent the semicolon.
* e.g.
* if (foo) bar()
* ; [1, 2, 3].map(foo)
*/
const lastToken = sourceCode.getLastToken(node);
if (
lastToken &&
node.type !== AST_NODE_TYPES.EmptyStatement &&
isSemicolonToken(lastToken)
) {
offsets.setDesiredOffset(lastToken, lastParentToken, 0);
}
}
}
/**
* Checks the indentation for nodes that are like function calls
*/
function addFunctionCallIndent(
node: TSESTree.CallExpression | TSESTree.NewExpression,
): void {
const openingParen = node.arguments.length
? sourceCode.getFirstTokenBetween(
node.callee,
node.arguments[0],
isOpeningParenToken,
)!
: sourceCode.getLastToken(node, 1)!;
const closingParen = sourceCode.getLastToken(node)!;
parameterParens.add(openingParen);
parameterParens.add(closingParen);
offsets.setDesiredOffset(
openingParen,
sourceCode.getTokenBefore(openingParen),
0,
);
addElementListIndent(
node.arguments,
openingParen,
closingParen,
options.CallExpression.arguments!,
);
}
/**
* Checks the indentation of parenthesized values, given a list of tokens in a program
* @param tokens A list of tokens
*/
function addParensIndent(tokens: TSESTree.Token[]): void {
const parenStack: TSESTree.Token[] = [];
const parenPairs: { left: TSESTree.Token; right: TSESTree.Token }[] = [];
tokens.forEach(nextToken => {
// Accumulate a list of parenthesis pairs
if (isOpeningParenToken(nextToken)) {
parenStack.push(nextToken);
} else if (isClosingParenToken(nextToken)) {
parenPairs.unshift({ left: parenStack.pop()!, right: nextToken });
}
});
parenPairs.forEach(pair => {
const leftParen = pair.left;
const rightParen = pair.right;
// We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
if (
!parameterParens.has(leftParen) &&
!parameterParens.has(rightParen)
) {
const parenthesizedTokens = new Set(
sourceCode.getTokensBetween(leftParen, rightParen),
);
parenthesizedTokens.forEach(token => {
if (!parenthesizedTokens.has(offsets.getFirstDependency(token)!)) {
offsets.setDesiredOffset(token, leftParen, 1);
}
});
}
offsets.setDesiredOffset(rightParen, leftParen, 0);
});
}
/**
* Ignore all tokens within an unknown node whose offset do not depend
* on another token's offset within the unknown node
*/
function ignoreNode(node: TSESTree.Node): void {
const unknownNodeTokens = new Set(
sourceCode.getTokens(node, { includeComments: true }),
);
unknownNodeTokens.forEach(token => {
if (!unknownNodeTokens.has(offsets.getFirstDependency(token)!)) {
const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
if (token === firstTokenOfLine) {
offsets.ignoreToken(token);
} else {
offsets.setDesiredOffset(token, firstTokenOfLine, 0);
}
}
});
}
/**
* Check whether the given token is on the first line of a statement.
* @param leafNode The expression node that the token belongs directly.
* @returns `true` if the token is on the first line of a statement.
*/
function isOnFirstLineOfStatement(
token: TSESTree.Token,
leafNode: TSESTree.Node,
): boolean {
let node: TSESTree.Node | undefined = leafNode;
while (
node.parent &&
!node.parent.type.endsWith('Statement') &&
!node.parent.type.endsWith('Declaration')
) {
node = node.parent;
}
node = node.parent;
return !node || node.loc.start.line === token.loc.start.line;
}
/**
* Check whether there are any blank (whitespace-only) lines between
* two tokens on separate lines.
* @returns `true` if the tokens are on separate lines and
* there exists a blank line between them, `false` otherwise.
*/
function hasBlankLinesBetween(
firstToken: TSESTree.Token,
secondToken: TSESTree.Token,
): boolean {
const firstTokenLine = firstToken.loc.end.line;
const secondTokenLine = secondToken.loc.start.line;
if (
firstTokenLine === secondTokenLine ||
firstTokenLine === secondTokenLine - 1
) {
return false;
}
for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
if (!tokenInfo.firstTokensByLineNumber.has(line)) {
return true;
}
}
return false;
}
const ignoredNodeFirstTokens = new Set();
const baseOffsetListeners: TSESLint.RuleListener = {
'ArrayExpression, ArrayPattern'(
node: TSESTree.ArrayExpression | TSESTree.ArrayPattern,
) {
const openingBracket = sourceCode.getFirstToken(node)!;
const closingBracket = sourceCode.getTokenAfter(
node.elements[node.elements.length - 1] ?? openingBracket,
isClosingBracketToken,
)!;
addElementListIndent(
node.elements,
openingBracket,
closingBracket,
options.ArrayExpression,
);
},
ArrowFunctionExpression(node) {
const firstToken = sourceCode.getFirstToken(node)!;
if (isOpeningParenToken(firstToken)) {
const openingParen = firstToken;
const closingParen = sourceCode.getTokenBefore(
node.body,
isClosingParenToken,
)!;
parameterParens.add(openingParen);
parameterParens.add(closingParen);
addElementListIndent(
node.params,
openingParen,
closingParen,
options.FunctionExpression.parameters!,
);
}
addBlocklessNodeIndent(node.body);
},
AssignmentExpression(node) {
const operator = sourceCode.getFirstTokenBetween(
node.left,
node.right,
token => token.value === node.operator,
)!;
offsets.setDesiredOffsets(
[operator.range[0], node.range[1]],
sourceCode.getLastToken(node.left),
1,
);
offsets.ignoreToken(operator);
offsets.ignoreToken(sourceCode.getTokenAfter(operator)!);
},
'BinaryExpression, LogicalExpression'(
node: TSESTree.BinaryExpression | TSESTree.LogicalExpression,
) {
const operator = sourceCode.getFirstTokenBetween(
node.left,
node.right,
token => token.value === node.operator,
)!;
/*
* For backwards compatibility, don't check BinaryExpression indents, e.g.
* var foo = bar &&
* baz;
*/
const tokenAfterOperator = sourceCode.getTokenAfter(operator)!;
offsets.ignoreToken(operator);
offsets.ignoreToken(tokenAfterOperator);
offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
},
'BlockStatement, ClassBody'(
node: TSESTree.BlockStatement | TSESTree.ClassBody,
) {
let blockIndentLevel;
if (node.parent && isOuterIIFE(node.parent)) {
blockIndentLevel = options.outerIIFEBody;
} else if (
node.parent &&
(node.parent.type === AST_NODE_TYPES.FunctionExpression ||
node.parent.type === AST_NODE_TYPES.ArrowFunctionExpression)
) {
blockIndentLevel = options.FunctionExpression.body;
} else if (
node.parent &&
node.parent.type === AST_NODE_TYPES.FunctionDeclaration
) {
blockIndentLevel = options.FunctionDeclaration.body;
} else {
blockIndentLevel = 1;
}
/*
* For blocks that aren't lone statements, ensure that the opening curly brace
* is aligned with the parent.
*/
if (node.parent && !STATEMENT_LIST_PARENTS.has(node.parent.type)) {
offsets.setDesiredOffset(
sourceCode.getFirstToken(node)!,
sourceCode.getFirstToken(node.parent),
0,
);
}
addElementListIndent(
node.body,
sourceCode.getFirstToken(node)!,
sourceCode.getLastToken(node)!,
blockIndentLevel!,
);
},
CallExpression: addFunctionCallIndent,
'ClassDeclaration[superClass], ClassExpression[superClass]'(
node: TSESTree.ClassDeclaration | TSESTree.ClassExpression,
) {
const classToken = sourceCode.getFirstToken(node)!;
const extendsToken = sourceCode.getTokenBefore(
node.superClass!,
isNotOpeningParenToken,
)!;
offsets.setDesiredOffsets(
[extendsToken.range[0], node.body.range[0]],
classToken,
1,
);
},
ConditionalExpression(node) {
const firstToken = sourceCode.getFirstToken(node)!;
// `flatTernaryExpressions` option is for the following style:
// var a =
// foo > 0 ? bar :
// foo < 0 ? baz :
// /*else*/ qiz ;
if (