/
getFunctionHeadLoc.ts
79 lines (70 loc) · 1.94 KB
/
getFunctionHeadLoc.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
import {
AST_NODE_TYPES,
AST_TOKEN_TYPES,
TSESLint,
TSESTree,
} from '@typescript-eslint/experimental-utils';
type FunctionNode =
| TSESTree.ArrowFunctionExpression
| TSESTree.FunctionExpression
| TSESTree.FunctionDeclaration;
/**
* Creates a report location for the given function.
* The location only encompasses the "start" of the function, and not the body
*
* eg.
*
* ```
* function foo(args) {}
* ^^^^^^^^^^^^^^^^^^
*
* get y(args) {}
* ^^^^^^^^^^^
*
* const x = (args) => {}
* ^^^^^^^^^
* ```
*/
export function getFunctionHeadLoc(
node: FunctionNode,
sourceCode: TSESLint.SourceCode,
): TSESTree.SourceLocation {
function getLocStart(): TSESTree.LineAndColumnData {
if (node.parent && node.parent.type === AST_NODE_TYPES.MethodDefinition) {
// return the start location for class method
if (node.parent.decorators && node.parent.decorators.length > 0) {
// exclude decorators
return sourceCode.getTokenAfter(
node.parent.decorators[node.parent.decorators.length - 1],
)!.loc.start;
}
return node.parent.loc.start;
}
if (
node.parent &&
node.parent.type === AST_NODE_TYPES.Property &&
node.parent.method
) {
// return the start location for object method shorthand
return node.parent.loc.start;
}
// return the start location for a regular function
return node.loc.start;
}
function getLocEnd(): TSESTree.LineAndColumnData {
if (node.type === AST_NODE_TYPES.ArrowFunctionExpression) {
// find the end location for arrow function expression
return sourceCode.getTokenBefore(
node.body,
token =>
token.type === AST_TOKEN_TYPES.Punctuator && token.value === '=>',
)!.loc.end;
}
// return the end location for a regular function
return sourceCode.getTokenBefore(node.body)!.loc.end;
}
return {
start: getLocStart(),
end: getLocEnd(),
};
}