| 24 | * @returns {Object} comment with return tag inferred |
| 25 | */ |
| 26 | export default function inferReturn(comment) { |
| 27 | if ( |
| 28 | Array.isArray(comment.returns) && |
| 29 | comment.returns.length && |
| 30 | comment.returns[0].type |
| 31 | ) { |
| 32 | return comment; |
| 33 | } |
| 34 | const path = findTarget(comment.context.ast); |
| 35 | let fn = path && path.node; |
| 36 | if (!fn) { |
| 37 | return comment; |
| 38 | } |
| 39 | |
| 40 | // In case of `/** */ var x = function () {}` findTarget returns |
| 41 | // the declarator. |
| 42 | if (t.isVariableDeclarator(fn)) { |
| 43 | fn = fn.init; |
| 44 | } |
| 45 | |
| 46 | const fnReturnType = getReturnType(fn); |
| 47 | if (fnReturnType) { |
| 48 | let returnType = typeAnnotation(fnReturnType); |
| 49 | let yieldsType = null; |
| 50 | |
| 51 | if (fn.generator && returnType.type === 'TypeApplication') { |
| 52 | comment.generator = true; |
| 53 | let numArgs; |
| 54 | |
| 55 | if (t.isFlow(fnReturnType)) { |
| 56 | numArgs = FLOW_GENERATORS[returnType.expression.name]; |
| 57 | } else if (t.isTSTypeAnnotation(fnReturnType)) { |
| 58 | numArgs = TS_GENERATORS[returnType.expression.name]; |
| 59 | } |
| 60 | |
| 61 | if (returnType.applications.length === numArgs) { |
| 62 | yieldsType = returnType.applications[0]; |
| 63 | |
| 64 | if (numArgs > 1) { |
| 65 | returnType = returnType.applications[1]; |
| 66 | } else { |
| 67 | returnType = { |
| 68 | type: 'VoidLiteral' |
| 69 | }; |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | if (yieldsType) { |
| 75 | if (comment.yields && comment.yields.length > 0) { |
| 76 | comment.yields[0].type = yieldsType; |
| 77 | } else { |
| 78 | comment.yields = [ |
| 79 | { |
| 80 | title: 'yields', |
| 81 | type: yieldsType |
| 82 | } |
| 83 | ]; |