forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsdocs.js
543 lines (516 loc) · 14.7 KB
/
jsdocs.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*jslint node: true */
'use strict';
var esprima = require('esprima-fb');
var fs = require('fs');
var Syntax = esprima.Syntax;
var findExportDefinition = require('./findExportDefinition');
var genericTransform = require('./generic-function-visitor');
var genericVisitor = genericTransform.visitorList[0];
var traverseFlat = require('./traverseFlat');
var parseTypehint = require('./TypeExpressionParser').parse;
// Don't save object properties source code that is longer than this
var MAX_PROPERTY_SOURCE_LENGTH = 1000;
function invariant(condition, message) {
if (!condition) {
throw new Error(message);
}
}
/**
* If the expression is an identifier, it is resolved in the scope chain.
* If it is an assignment expression, it resolves to the right hand side.
*
* In all other cases the expression itself is returned.
*
* Since the scope chain constructed by the traverse function is very simple
* (it doesn't take into account *changes* to the variable through assignment
* statements), this function doesn't return the correct value in every
* situation. But it's good enough for how it is used in the parser.
*
* @param {object} expr
* @param {array} scopeChain
*
* @return {object}
*/
function resolveToValue(expr, scopeChain) {
switch (expr.type) {
case Syntax.AssignmentExpression:
if (expr.operator === '=') {
return resolveToValue(expr.right, scopeChain);
}
break;
case Syntax.Identifier:
var value;
scopeChain.some(function(scope, i) {
if (hasOwnProperty.call(scope, expr.name) && scope[expr.name]) {
value = resolveToValue(scope[expr.name], scopeChain.slice(i));
return true;
}
});
return value;
}
return expr;
}
/**
* Strips the "static upstream" warning from the docblock.
*
* @param {?string} docblock
* @return {?string}
*/
function stripStaticUpstreamWarning(docblock) {
if (!docblock) {
return docblock;
}
// Esprima strips out the starting and ending tokens, so add them back
docblock = '/*' + docblock + '*/\n';
return docblock;
}
/**
* Parse a typehint into the 'nice' form, if possible.
*/
function safeParseTypehint(typehint) {
if (!typehint) {
return null;
}
try {
return JSON.stringify(parseTypehint(typehint));
} catch (e) {
return typehint;
}
}
/**
* Gets the docblock for the file
*
* @param {array<object>} commentsForFile
* @return {?string}
*/
function getFileDocBlock(commentsForFile) {
var docblock;
commentsForFile.some(function(comment, i) {
if (comment.loc.start.line === 1) {
var lines = comment.value.split('\n');
var filteredLines = lines.filter(function(line) {
var hasCopyright = !!line.match(/^\s*\*\s+Copyright/);
var hasProvides = !!line.match(/^\s*\*\s+@provides/);
return !hasCopyright && !hasProvides;
});
docblock = filteredLines.join('\n');
return true;
}
});
return stripStaticUpstreamWarning(docblock);
}
/**
* Gets the docblock for a given node.
*
* @param {object} Node to get docblock for
* @param {array<object>} commentsForFile
* @param {array<string>} linesForFile
* @return {?string}
*/
function getDocBlock(node, commentsForFile, linesForFile) {
if (node.isSynthesized === true) {
return '';
}
var docblock;
var prevLine = node.loc.start.line - 1;
// skip blank lines
while (linesForFile[prevLine - 1].trim() === '') {
prevLine--;
}
commentsForFile.some(function(comment, i) {
if (comment.loc.end.line === prevLine) {
if (comment.type === 'Line') {
// Don't accept line comments that are separated
if (prevLine !== node.loc.start.line - 1) {
return true;
}
var line = prevLine;
docblock = '';
for (var ii = i; ii >= 0; ii--) {
var lineComment = commentsForFile[ii];
if (lineComment.loc.end.line === line) {
docblock = '//' + lineComment.value +
(docblock ? '\n' + docblock : '');
line--;
} else {
break;
}
}
} else {
docblock = stripStaticUpstreamWarning(comment.value);
}
return true;
}
});
return docblock;
}
/**
* Given the comments for a file, return the module name (by looking for
* @providesModule).
*
* @param {array<object>}
* @return {?string}
*/
function getModuleName(commentsForFile) {
var moduleName;
commentsForFile.forEach(function(comment) {
if (comment.type === 'Block') {
var matches = comment.value.match(/@providesModule\s+(\S*)/);
if (matches && matches[1]) {
moduleName = matches[1];
}
}
});
return moduleName;
}
/**
* Esprima includes the leading colon (and possibly spaces) as part of the
* typehint, so we have to strip those out.
*/
function sanitizeTypehint(string) {
for (var i = 0; i < string.length; i++) {
if (string[i] != ' ' && string[i] != ':') {
return string.substring(i);
}
}
return null;
}
/**
* @param {object} node
* @param {object} state
* @param {string} source
* @param {array<object>} commentsForFile
* @param {array<string>} linesForFile
* @return {object}
*/
function getFunctionData(node, state, source, commentsForFile, linesForFile) {
var params = [];
var typechecks = commentsForFile.typechecks;
var typehintsFromBlock = null;
if (typechecks) {
// esprima has trouble with some params so ignore them (e.g. $__0)
if (!node.params.some(function(param) { return !param.name; })) {
try {
typehintsFromBlock = genericTransform.getTypeHintsFromDocBlock(
node,
state.docBlocksByLine
);
} catch (e) {
}
}
}
node.params.forEach(function(param) {
// TODO: Handle other things like Syntax.ObjectPattern
if (param.type === Syntax.Identifier) {
var typehint;
if (param.typeAnnotation) {
typehint = sanitizeTypehint(source.substring(
param.typeAnnotation.range[0],
param.typeAnnotation.range[1]
));
} else if (typehintsFromBlock && typehintsFromBlock.params) {
typehintsFromBlock.params.some(function(paramTypehint) {
if (paramTypehint[0] === param.name) {
typehint = paramTypehint[1];
return true;
}
});
}
if (!typehint && typechecks) {
try {
typehint = genericTransform.getTypeHintFromInline(
param,
state.commentsByLine
);
} catch (e) {
}
}
params.push({
typehint: safeParseTypehint(typehint),
name: param.name + (param.optional ? '?' : ''),
});
} else if (param.type === Syntax.TypeAnnotatedIdentifier) {
params.push({
typehint: sanitizeTypehint(source.substring(
param.annotation.range[0],
param.annotation.range[1]
)),
name: param.id.name
});
}
});
var returnTypehint = null;
if (node.returnType) {
returnTypehint = sanitizeTypehint(source.substring(
node.returnType.range[0],
node.returnType.range[1]
));
} else if (typehintsFromBlock) {
returnTypehint = typehintsFromBlock.returns;
}
var tparams = null;
if (node.typeParameters) {
tparams = node.typeParameters.params.map(function(x) {
return x.name;
});
}
return {
line: node.loc.start.line,
source: source.substring.apply(source, node.range),
docblock: getDocBlock(node, commentsForFile, linesForFile),
modifiers: [],
params: params,
tparams: tparams,
returntypehint: safeParseTypehint(returnTypehint)
};
}
/**
* @param {object} node
* @param {object} state
* @param {string} source
* @param {array<object>} commentsForFile
* @param {array<string>} linesForFile
* @return {object}
*/
function getObjectData(node, state, source, scopeChain,
commentsForFile, linesForFile) {
var methods = [];
var properties = [];
var superClass = null;
node.properties.forEach(function(property) {
if (property.type === Syntax.SpreadProperty) {
if (property.argument.type === Syntax.Identifier) {
superClass = property.argument.name;
}
return;
}
switch (property.value.type) {
case Syntax.FunctionExpression:
var methodData = getFunctionData(property.value, state, source,
commentsForFile, linesForFile);
methodData.name = property.key.name || property.key.value;
methodData.source = source.substring.apply(source, property.range);
methodData.modifiers.push('static');
methods.push(methodData);
break;
case Syntax.Identifier:
var expr = resolveToValue(
property.value,
scopeChain
);
if (expr) {
if (expr.type === Syntax.FunctionDeclaration) {
var functionData =
getFunctionData(expr, state, source, commentsForFile, linesForFile);
functionData.name = property.key.name || property.key.value;
functionData.modifiers.push('static');
methods.push(functionData);
break;
} else {
property.value = expr;
}
}
/* falls through */
default:
var propertySource = '';
var valueRange = property.value.range;
if (valueRange[1] - valueRange[0] < MAX_PROPERTY_SOURCE_LENGTH) {
propertySource = source.substring.apply(source, valueRange);
}
var docBlock = getDocBlock(property, commentsForFile, linesForFile);
/* CodexVarDef: modifiers, type, name, default, docblock */
var propertyData = [
['static'],
'',
// Cast to String because this can be a Number
// Could also be a String literal (e.g. "key") hence the value
String(property.key.name || property.key.value),
propertySource,
docBlock || '',
property.loc.start.line
];
properties.push(propertyData);
break;
}
});
return {
methods: methods,
properties: properties,
superClass: superClass
};
}
/**
* @param {object} node
* @param {object} state
* @param {string} source
* @param {array<object>} commentsForFile
* @param {array<string>} linesForFile
* @return {object}
*/
function getClassData(node, state, source, commentsForFile, linesForFile) {
var methods = [];
invariant(node.body.type === Syntax.ClassBody, 'Expected ClassBody');
node.body.body.forEach(function(bodyItem) {
if (bodyItem.type === Syntax.MethodDefinition) {
if (bodyItem.value.type === Syntax.FunctionExpression) {
var methodData =
getFunctionData(bodyItem.value, state, source,
commentsForFile, linesForFile);
methodData.name = bodyItem.key.name;
methodData.source = source.substring.apply(source, bodyItem.range);
if (bodyItem.static) {
methodData.modifiers.push('static');
}
methods.push(methodData);
}
}
});
var data = {
methods: methods
};
if (node.superClass && node.superClass.type === Syntax.Identifier) {
data.superClass = node.superClass.name;
}
if (node.typeParameters) {
data.tparams = node.typeParameters.params.map(function(x) {
return x.name;
});
}
return data;
}
/**
* Finds all the requires
*
* @param {object} ast
* @return {array<object>}
*/
function findRequires(ast) {
var requires = [];
traverseFlat(ast, function(node, scopeChain) {
var requireData = getRequireData(node);
if (requireData) {
requires.push(requireData);
}
return !requireData;
});
return requires;
}
/**
* If the given node is a 'require' statement, returns a list of following data
* {
* name: string
* }
*
* @return ?object
*/
function getRequireData(node) {
if (!node || node.type !== Syntax.CallExpression) {
return null;
}
var callee = node.callee;
if (callee.type !== Syntax.Identifier
|| (callee.name !== 'require')) {
return null;
}
var args = node['arguments'];
if (args.length === 0) {
return null;
}
var firstArgument = args[0];
if (firstArgument.type !== Syntax.Literal) {
return null;
}
return {
name: firstArgument.value
};
}
/**
* Given the source of a file, this returns the data about the module's exported
* value.
*
* @param {string} source
* @return {?object} data
*/
function parseSource(source) {
var lines = source.split('\n');
var ast = esprima.parse(source, {
loc: true,
comment: true,
range: true,
sourceType: 'nonStrictModule',
});
/**
* This sets up genericTransform so that it can be queried above.
*/
var _state = {
g: {
source: source
}
};
if (genericVisitor.test(ast, [], _state)) {
// HACK: Mark that this file has typechecks on the comments object.
ast.comments.typechecks = true;
// This fills out the data for genericTransform.
genericVisitor(function() {}, ast, [], _state);
}
var result = findExportDefinition(ast.body);
if (result) {
var definition = result.definition;
var scopeChain = result.scopeChain;
var data;
var moduleName = getModuleName(ast.comments);
if (!moduleName) {
return null;
}
if (definition.type === Syntax.NewExpression &&
definition.callee.type === Syntax.Identifier) {
var name = definition.callee.name;
// If the class is defined in the scopeChain, export that instead.
scopeChain.some(function(scope) {
if (hasOwnProperty.call(scope, name) &&
scope[name].type === Syntax.ClassDeclaration) {
definition = scope[name];
return true;
}
});
}
switch (definition.type) {
case Syntax.ClassDeclaration:
data = getClassData(definition, _state, source, ast.comments, lines);
data.type = 'class';
break;
case Syntax.ObjectExpression:
data = getObjectData(definition, _state, source, scopeChain,
ast.comments, lines);
data.type = 'object';
break;
case Syntax.FunctionDeclaration:
case Syntax.FunctionExpression:
data = getFunctionData(definition, _state, source, ast.comments, lines);
data.type = 'function';
break;
default:
data = {type: 'module'};
break;
}
if (data) {
data.line = definition.loc.start.line;
data.name = moduleName;
data.docblock =
getDocBlock(definition, ast.comments, lines) ||
getFileDocBlock(ast.comments);
data.requires = findRequires(ast.body);
return data;
}
}
return null;
}
module.exports = parseSource;