-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
112 lines (93 loc) · 3.1 KB
/
index.js
File metadata and controls
112 lines (93 loc) · 3.1 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
const OPTIONS = {
comment: false,
label: false,
prefix: '__INLINE__',
remove: true,
}
const argumentsInliningVisitor = {
Identifier (path) {
for (let i = 0; i < this.params.length; i++) {
if (path.node.name === this.params[i].name) {
if (this.args[i]) {
path.replaceWith(this.args[i])
path.skip() // don't recurse
} else {
path.replaceWithSourceString('undefined')
}
}
}
}
}
const inlineFunctionVisitor = {
CallExpression (path) {
if (path.node.callee.name === this.name) {
const { params } = this
const args = path.node.arguments // grab these before we replace the node
const returnStatement = this.types.cloneDeep(this.returnStatement)
path.replaceWith(returnStatement)
path.traverse(argumentsInliningVisitor, { args, params })
path.replaceWith(returnStatement.argument)
}
}
}
function findComment (node, want) {
const comments = node.leadingComments || []
for (let i = comments.length - 1; i >= 0; --i) {
const comment = comments[i]
if (comment.type !== 'CommentBlock') {
break
}
if (comment.value.trim() === want) {
return `leadingComments.${i}`
}
}
}
function hasSingleStatement (node) {
return node.body.body.length === 1
}
function matchLabel (types, statement, label) {
return types.isLabeledStatement(statement) && statement.label.name === label
}
module.exports = function ({ types }, options) {
const { comment, label, prefix, remove } = Object.assign({}, OPTIONS, options)
if (!(comment || label || prefix)) {
return {}
}
return {
visitor: {
FunctionDeclaration (path) {
const { node } = path
let returnStatement
if (hasSingleStatement(node)) {
returnStatement = node.body.body[0]
} else {
return
}
const { name } = node.id
let commentPath
if (prefix && name.startsWith(prefix)) {
// do nothing
} else if (label && matchLabel(types, returnStatement, label)) {
returnStatement = returnStatement.body
} else if (comment && (commentPath = findComment(node, comment))) {
if (remove) {
// remove the comment so it doesn't get attached to the
// next declaration
path.get(commentPath).remove()
}
} else {
return
}
path.parentPath.traverse(inlineFunctionVisitor, {
name,
params: node.params,
returnStatement,
types,
})
if (remove) {
path.remove()
}
}
}
}
}