-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseSignature.js
More file actions
140 lines (127 loc) · 4.83 KB
/
parseSignature.js
File metadata and controls
140 lines (127 loc) · 4.83 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
const {Parser} = require("acorn")
/**
* Return an opts data structure that describes the options and arguments.
* @param {*} func
*/
module.exports = function parseSignatures(handlers) {
if (typeof handlers === 'function') {
return parseSignature(handlers);
}
let commands = {};
for (let name in handlers) {
let optDesc = parseSignature(handlers[name]);
commands[name] = {name, optDesc};
}
return {
optionParamIndex: null,
options: {},
positional: [{name: 'command', required: true}],
commands
};
}
function parseSignature(fn) {
const result = {
synopsis: null,
optionParamIndex: null,
options: {},
positional: [],
};
// massage source into somthing acorn will parse.
// 'function(){}' -> '(function(){})'
// 'a(){}' -> 'function a(){}'
let comments = [], options = {
ecmaVersion: 'latest',
onComment(block, text, start, end) {
comments.push([text, start]);
},
};
let node, source = '('+fn+')';
try{
node = Parser.parse(source, options)
} catch(e) {
// function source may be using method shorthand, eg {a(){}}.a.toString() -> 'a() {}'
source = '(' + fn.toString().replace(/^(async )?/, '$1function ') + ')'
node = Parser.parse(source, options)
}
node = node.body[0].expression;
// remove comments after start of body
comments = comments.filter(c => c[1] < node.body.start)
let firstTimeCalled = true;
function setSynopsis(end=source.length) {
if (comments.length && result.synopsis == null && comments[0][1] < end) {
// first comment is the function synopsis, as long as it starts before the token
result.synopsis = comments.shift()[0].trim();
}
}
function getCommentUntil(tokenEnd, name) {
if (firstTimeCalled) firstTimeCalled = setSynopsis(tokenEnd);
if (!comments.length) return null;
// find the end of the line after tokenEnd
const re = /\n|$/g;
re.lastIndex = tokenEnd;
const until = re.exec(source).index;
// remove comments until that index and join
let ix = comments.findIndex(c => c[1] > until);
if (ix == -1) ix = comments.length;
return comments.splice(0, ix).map(c => c[0]).join('\n').trim();
}
function mapNodes(nodes, handlers, unknown=node=>({error: 'unknown node type', type: node.type, node})) {
return nodes.map(node => (handlers[node.type]||unknown)(node))
}
function positional({name, required=false, rest=false, end}) {
result.positional.push({name, required, rest, synopsis: getCommentUntil(end)});
}
mapNodes(node.params, {
Identifier({name, end}) {
positional({name, end, required: true});
},
RestElement({argument: {name}, end}) {
positional({name, end, rest: true});
},
AssignmentPattern({left, end}) {
// Handle default values for both identifiers and object patterns
if (left.type === 'ObjectPattern') {
// This is an object pattern with a default, e.g., {opt1}={}
if (result.optionParamIndex) throw new Error('only one options object allowed');
result.optionParamIndex = result.positional.length;
mapNodes(left.properties, {
Property({key: {name}, value: {name: alias, left: valueLeft, right}, end}) {
if (valueLeft) alias = valueLeft.name;
if (name == alias) alias = undefined;
const hasArg = !(right && right.type == 'Literal' && right.value === false);
const synopsis = getCommentUntil(end);
result.options[name] = {name, hasArg, synopsis};
if (alias) {
result.options[name].alias = alias;
result.options[alias] = result.options[name];
}
}
});
} else {
// This is an identifier with a default value
positional({name: left.name, end});
}
},
ObjectPattern({properties}) {
if (result.optionParamIndex) throw new Error('only one options object allowed');
result.optionParamIndex = result.positional.length;
mapNodes(properties, {
Property({key: {name}, value: {name: alias, left, right}, end}) {
if (left) alias = left.name;
if (name == alias) alias = undefined;
const hasArg = !(right && right.type == 'Literal' && right.value === false);
const synopsis = getCommentUntil(end);
result.options[name] = {name, hasArg, synopsis};
if (alias) {
result.options[name].alias = alias;
result.options[alias] = result.options[name];
}
}
});
}
});
// If there are no args, the synopsis won't be set yet.
setSynopsis();
// warning if unused comments?
return result;
}