-
Notifications
You must be signed in to change notification settings - Fork 486
/
Copy pathparams.js
360 lines (330 loc) · 11.5 KB
/
params.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
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
'use strict';
/* @flow */
const t = require('babel-types');
const generate = require('babel-generator').default;
const _ = require('lodash');
const findTarget = require('./finders').findTarget;
const flowDoctrine = require('../flow_doctrine');
const util = require('util');
const debuglog = util.debuglog('documentation');
const parseJSDoc = require('../parse');
const isJSDocComment = require('../is_jsdoc_comment');
function getInlineDescription(param) {
if (param.trailingComments && isJSDocComment(param.trailingComments[0])) {
var parsedInlineComment = parseJSDoc(param.trailingComments[0].value);
if (parsedInlineComment && parsedInlineComment.description) {
return {
description: parsedInlineComment.description
};
}
}
return {};
}
/**
* Infers param tags by reading function parameter names
*
* @param {Object} comment parsed comment
* @returns {Object} comment with parameters
*/
function inferParams(comment /*: Comment */) {
var path = findTarget(comment.context.ast);
// In case of `/** */ var x = function () {}` findTarget returns
// the declarator.
if (t.isVariableDeclarator(path)) {
path = path.get('init');
}
// If this is an ES6 class with a constructor method, infer
// parameters from that constructor method.
if (t.isClassDeclaration(path)) {
let constructor = path.node.body.body.find(item => {
// https://github.com/babel/babylon/blob/master/ast/spec.md#classbody
return t.isClassMethod(item) && item.kind === 'constructor';
});
if (constructor) {
return inferAndCombineParams(constructor.params, comment);
}
}
if (!t.isFunction(path)) {
return comment;
}
return inferAndCombineParams(path.node.params, comment);
}
function inferAndCombineParams(params, comment) {
var inferredParams = params.map((param, i) => paramToDoc(param, '', i));
var mergedParams = mergeTrees(inferredParams, comment.params);
// Then merge the trees. This is the hard part.
return _.assign(comment, {
params: mergedParams
});
}
// Utility methods ============================================================
//
const PATH_SPLIT_CAPTURING = /(\[])?(\.)/g;
/**
* Index tags by their `name` property into an ES6 map.
*/
function mapTags(tags) {
return new Map(
tags.map(tag => {
return [tag.name, tag];
})
);
}
/**
* Babel parses JavaScript source code and produces an abstract syntax
* tree that includes methods and their arguments. This function takes
* that AST and uses it to infer details that would otherwise need
* explicit documentation, like the names of comments and their
* default values.
*
* It is especially careful to allow the user and the machine to collaborate:
* documentation.js should not overwrite any details that the user
* explicitly sets.
*
* @private
* @param {Object} param the abstract syntax tree of the parameter in JavaScript
* @param {number} i the number of this parameter, in argument order
* @param {string} prefix of the comment, if it is nested, like in the case of destructuring
* @returns {Object} parameter with inference.
*/
function paramToDoc(
param,
prefix /*: string */,
i /*: ?number */
) /*: CommentTag|Array<CommentTag> */ {
const autoName = '$' + String(i);
const prefixedName = prefix + '.' + param.name;
switch (param.type) {
case 'AssignmentPattern': // (a = b)
const newAssignmentParam = paramToDoc(param.left, '', i);
if (Array.isArray(newAssignmentParam)) {
throw new Error('Encountered an unexpected parameter type');
}
return _.assign(newAssignmentParam, {
default: generate(param.right, {
compact: true
}).code,
type: {
type: 'OptionalType',
expression: newAssignmentParam.type
}
});
// ObjectPattern <AssignmentProperty | RestElement>
case 'ObjectPattern': // { a }
if (prefix === '') {
// If this is a root-level param, like f({ x }), then we need to name
// it, like $0 or $1, depending on its position.
return {
title: 'param',
name: autoName,
anonymous: true,
type: (param.typeAnnotation && flowDoctrine(param)) || {
type: 'NameExpression',
name: 'Object'
},
properties: _.flatMap(param.properties, prop => {
return paramToDoc(prop, prefix + autoName);
})
};
} else if (param.indexed) {
// Likewise, if this object pattern sits inside of an ArrayPattern,
// like [{ foo }], it shouldn't just look like $0.foo, but like $0.0.foo,
// so make sure it isn't indexed first.
return {
title: 'param',
name: prefixedName,
anonymous: true,
type: (param.typeAnnotation && flowDoctrine(param)) || {
type: 'NameExpression',
name: 'Object'
},
properties: _.flatMap(param.properties, prop => {
return paramToDoc(prop, prefixedName);
})
};
}
// If, otherwise, this is nested, we don't really represent it as
// a parameter in and of itself - we just want its children, and
// it will be the . in obj.prop
return _.flatMap(param.properties, prop => {
return paramToDoc(prop, prefix);
});
// ArrayPattern<Pattern | null>
case 'ArrayPattern': // ([a, b, { c }])
if (prefix === '') {
return {
title: 'param',
name: autoName,
anonymous: true,
type: (param.typeAnnotation && flowDoctrine(param)) || {
type: 'NameExpression',
name: 'Array'
},
// Array destructuring lets you name the elements in the array,
// but those names don't really make sense within the JSDoc
// indexing tradition, or have any external meaning. So
// instead we're going to (immutably) rename the parameters to their
// indices
properties: _.flatMap(param.elements, (element, idx) => {
var indexedElement = _.assign({}, element, {
name: String(idx),
indexed: true
});
return paramToDoc(indexedElement, autoName);
})
};
}
return _.flatMap(param.elements, (element, idx) => {
var indexedElement = _.assign({}, element, {
name: String(idx)
});
return paramToDoc(indexedElement, prefix);
});
case 'ObjectProperty':
return _.assign(
paramToDoc(param.value, prefix + '.' + param.key.name),
{
name: prefix + '.' + param.key.name
},
getInlineDescription(param)
);
case 'RestProperty': // (a, ...b)
case 'RestElement':
let type /*: DoctrineType */ = {
type: 'RestType'
};
if (param.typeAnnotation) {
type.expression = flowDoctrine(param.typeAnnotation.typeAnnotation);
}
return {
title: 'param',
name: param.argument.name,
name: prefix ? `${prefix}.${param.argument.name}` : param.argument.name,
lineNumber: param.loc.start.line,
type
};
default:
// (a)
var newParam /*: CommentTagNamed */ = {
title: 'param',
name: prefix ? prefixedName : param.name,
lineNumber: param.loc.start.line
};
// Flow/TS annotations
if (param.typeAnnotation && param.typeAnnotation.typeAnnotation) {
newParam.type = flowDoctrine(param.typeAnnotation.typeAnnotation);
}
return _.assign(newParam, getInlineDescription(param));
}
}
/**
* Recurse through a potentially nested parameter tag,
* replacing the auto-generated name, like $0, with an explicit
* name provided from a JSDoc comment. For instance, if you have a code
* block like
*
* function f({ x });
*
* It would by default be documented with a first param $0, with a member $0.x
*
* If you specify the name of the param, then it could be documented with, say,
* options and options.x. So we need to recursively rename not just $0 but
* also $0.x and maybe $0.x.y.z all to options.x and options.x.y.z
*/
function renameTree(node, explicitName) {
var parts = node.name.split(PATH_SPLIT_CAPTURING);
parts[0] = explicitName;
node.name = parts.join('');
if (node.properties) {
node.properties.forEach(property => renameTree(property, explicitName));
}
}
function mergeTrees(inferred, explicit) {
// The first order of business is ensuring that the root types are specified
// in the right order. For the order of arguments, the inferred reality
// is the ground-truth: a function like
// function addThem(a, b, c) {}
// Should always see (a, b, c) in that order
// First, if all parameters are specified, allow explicit names to apply
// to destructuring parameters, which do not have inferred names. This is
// _only_ enabled in the case in which all parameters are specified explicitly
if (inferred.length === explicit.length) {
for (var i = 0; i < inferred.length; i++) {
if (inferred[i].anonymous === true) {
renameTree(inferred[i], explicit[i].name);
}
}
}
return mergeTopNodes(inferred, explicit);
}
function mergeTopNodes(inferred, explicit) {
const mapExplicit = mapTags(explicit);
const inferredNames = new Set(inferred.map(tag => tag.name));
const explicitTagsWithoutInference = explicit.filter(
tag => !inferredNames.has(tag.name)
);
if (explicitTagsWithoutInference.length) {
debuglog(
`${explicitTagsWithoutInference.length} tags were specified but didn't match ` +
`inferred information ${explicitTagsWithoutInference
.map(t => t.name)
.join(', ')}`
);
}
return inferred
.map(inferredTag => {
const explicitTag = mapExplicit.get(inferredTag.name);
return explicitTag ? combineTags(inferredTag, explicitTag) : inferredTag;
})
.concat(explicitTagsWithoutInference);
}
// This method is used for _non-root_ properties only - we use mergeTopNodes
// for root properties, which strictly requires inferred only. In this case,
// we combine all tags:
// - inferred & explicit
// - explicit only
// - inferred only
function mergeNodes(inferred, explicit) {
const intersection = _.intersectionBy(inferred, explicit, tag => tag.name);
const explicitOnly = _.differenceBy(explicit, inferred, tag => tag.name);
const inferredOnly = _.differenceBy(inferred, explicit, tag => tag.name);
const mapExplicit = mapTags(explicit);
return intersection
.map(inferredTag => {
const explicitTag = mapExplicit.get(inferredTag.name);
return explicitTag ? combineTags(inferredTag, explicitTag) : inferredTag;
})
.concat(explicitOnly)
.concat(inferredOnly);
}
function combineTags(inferredTag, explicitTag) {
let type = explicitTag.type;
var defaultValue;
if (!explicitTag.type) {
type = inferredTag.type;
} else if (explicitTag.type.type !== 'OptionalType' && inferredTag.default) {
type = {
type: 'OptionalType',
expression: explicitTag.type
};
defaultValue = inferredTag.default;
}
const hasProperties = (inferredTag.properties &&
inferredTag.properties.length) ||
(explicitTag.properties && explicitTag.properties.length);
return _.assign(
explicitTag,
hasProperties
? {
properties: mergeNodes(
inferredTag.properties || [],
explicitTag.properties || []
)
}
: {},
{ type },
defaultValue ? { default: defaultValue } : {}
);
}
module.exports = inferParams;
module.exports.mergeTrees = mergeTrees;