This repository has been archived by the owner on Jan 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (49 loc) · 1.67 KB
/
index.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
var acorn = require('acorn')
var walk = require('acorn-walk')
module.exports = function (source, lineNumber) {
var ast = acorn.parse(source, { locations: true, sourceType: 'module' })
return functionNamesAtLineNumber(ast, lineNumber)
}
/*
* Because acorn/dist/walk uses function callbacks it looks async, but apparently
* isn't, so this method just wraps `walk`'s lack of a return value.
*/
function functionNamesAtLineNumber (ast, lineNumber) {
var names = []
walk.ancestor(ast, {
FunctionDeclaration: function (node, ancestors) {
if (isNodeBetweenLines(node, lineNumber)) {
names.push(nameFor(node.id))
}
},
FunctionExpression: function (node, ancestors) {
if (isNodeBetweenLines(node, lineNumber)) {
if (node.id) names.push(nameFor(node.id))
var parentNode = ancestors[ancestors.length - 2]
if (parentNode.type === 'Property') {
names.push(nameFor(parentNode.key))
} else if (parentNode.type === 'AssignmentExpression') {
if (parentNode.left.type === 'MemberExpression') {
names.push(nameFor(parentNode.left.property))
} else if (parentNode.left.type === 'Identifier') {
names.push(nameFor(parentNode.left))
}
} else if (parentNode.type === 'VariableDeclarator') {
names.push(nameFor(parentNode.id))
}
}
}
})
return names
}
function isNodeBetweenLines (node, lineNumber) {
return lineNumber >= node.loc.start.line &&
lineNumber <= node.loc.end.line
}
function nameFor (node) {
if (node.type === 'Literal') {
return node.value
} else if (node.type === 'Identifier') {
return node.name
}
}