Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rule require-throws #574

Merged
merged 7 commits into from
Jun 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 32 additions & 31 deletions .README/rules/require-returns.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,54 @@
### `require-returns`

Requires returns are documented.
Requires that returns are documented.

Will also report if multiple `@returns` tags are present.

#### Options

- `checkConstructors` - A value indicating whether `constructor`s should
be checked for `@returns` tags. Defaults to `false`.
be checked for `@returns` tags. Defaults to `false`.
- `checkGetters` - Boolean to determine whether getter methods should
be checked for `@returns` tags. Defaults to `true`.
- `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the document
block avoids the need for a `@returns`. Defaults to an array with
`inheritdoc`. If you set this array, it will overwrite the default,
be checked for `@returns` tags. Defaults to `true`.
- `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the
document block avoids the need for a `@returns`. Defaults to an array
with `inheritdoc`. If you set this array, it will overwrite the default,
so be sure to add back `inheritdoc` if you wish its presence to cause
exemption of the rule.
- `forceRequireReturn` - Set to `true` to always insist on
`@returns` documentation regardless of implicit or explicit `return`'s
in the function. May be desired to flag that a project is aware of an
`undefined`/`void` return. Defaults to `false`.
`@returns` documentation regardless of implicit or explicit `return`'s
in the function. May be desired to flag that a project is aware of an
`undefined`/`void` return. Defaults to `false`.
- `forceReturnsWithAsync` - By default `async` functions that do not explicitly
return a value pass this rule as an `async` function will always return a
`Promise`, even if the `Promise` resolves to void. You can force all `async`
functions to require return statements by setting `forceReturnsWithAsync`
to `true` on the options object. This may be useful for flagging that there
has been consideration of return type. Defaults to `false`.
return a value pass this rule as an `async` function will always return a
`Promise`, even if the `Promise` resolves to void. You can force all
`async` functions to require return statements by setting
`forceReturnsWithAsync` to `true` on the options object. This may be useful
for flagging that there has been consideration of return type. Defaults
to `false`.
- `contexts` - Set this to an array of strings representing the AST context
where you wish the rule to be applied.
Overrides the default contexts (see below). Set to `"any"` if you want
the rule to apply to any jsdoc block throughout your files (as is necessary
for finding function blocks not attached to a function declaration or
expression, i.e., `@callback` or `@function` (or its aliases `@func` or
`@method`) (including those associated with an `@interface`). This
rule will only apply on non-default contexts when there is such a tag
present and the `forceRequireReturn` option is set or if the
`forceReturnsWithAsync` option is set with a present `@async` tag
(since we are not checking against the actual `return` values in these
cases).
where you wish the rule to be applied.
Overrides the default contexts (see below). Set to `"any"` if you want
the rule to apply to any jsdoc block throughout your files (as is necessary
for finding function blocks not attached to a function declaration or
expression, i.e., `@callback` or `@function` (or its aliases `@func` or
`@method`) (including those associated with an `@interface`). This
rule will only apply on non-default contexts when there is such a tag
present and the `forceRequireReturn` option is set or if the
`forceReturnsWithAsync` option is set with a present `@async` tag
(since we are not checking against the actual `return` values in these
cases).

```js
'jsdoc/require-returns': ['error', {forceReturnsWithAsync: true}]
```

| | |
| -------- | ------------------------------------------------------------------------------------------------------------- |
| | |
| -------- | ------- |
| Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled |
| Tags | `returns` |
| Aliases | `return` |
| Options | `checkConstructors`, `checkGetters`, `contexts`, `exemptedBy`, `forceRequireReturn`, `forceReturnsWithAsync` |
| Settings | `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` |
| Tags | `returns` |
| Aliases | `return` |
| Options | `checkConstructors`, `checkGetters`, `contexts`, `exemptedBy`, `forceRequireReturn`, `forceReturnsWithAsync` |
| Settings | `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` |

<!-- assertions requireReturns -->
32 changes: 32 additions & 0 deletions .README/rules/require-throws.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
### `require-throws`

Requires that throw statements are documented.

#### Options

- `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the
document block avoids the need for a `@throws`. Defaults to an array
with `inheritdoc`. If you set this array, it will overwrite the default,
so be sure to add back `inheritdoc` if you wish its presence to cause
exemption of the rule.
- `contexts` - Set this to an array of strings representing the AST context
where you wish the rule to be applied.
Overrides the default contexts (see below). Set to `"any"` if you want
the rule to apply to any jsdoc block throughout your files (as is necessary
for finding function blocks not attached to a function declaration or
expression, i.e., `@callback` or `@function` (or its aliases `@func` or
`@method`) (including those associated with an `@interface`).

```js
'jsdoc/require-throws': 'error',
```

| | |
| -------- | --- |
| Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled |
| Tags | `throws` |
| Aliases | `exception` |
| Options | `contexts`, `exemptedBy` |
| Settings | `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` |

<!-- assertions requireThrows -->
63 changes: 32 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12226,56 +12226,57 @@ function quux () {
<a name="eslint-plugin-jsdoc-rules-require-returns"></a>
### <code>require-returns</code>

Requires returns are documented.
Requires that returns are documented.

Will also report if multiple `@returns` tags are present.

<a name="eslint-plugin-jsdoc-rules-require-returns-options-26"></a>
#### Options

- `checkConstructors` - A value indicating whether `constructor`s should
be checked for `@returns` tags. Defaults to `false`.
be checked for `@returns` tags. Defaults to `false`.
- `checkGetters` - Boolean to determine whether getter methods should
be checked for `@returns` tags. Defaults to `true`.
- `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the document
block avoids the need for a `@returns`. Defaults to an array with
`inheritdoc`. If you set this array, it will overwrite the default,
be checked for `@returns` tags. Defaults to `true`.
- `exemptedBy` - Array of tags (e.g., `['type']`) whose presence on the
document block avoids the need for a `@returns`. Defaults to an array
with `inheritdoc`. If you set this array, it will overwrite the default,
so be sure to add back `inheritdoc` if you wish its presence to cause
exemption of the rule.
- `forceRequireReturn` - Set to `true` to always insist on
`@returns` documentation regardless of implicit or explicit `return`'s
in the function. May be desired to flag that a project is aware of an
`undefined`/`void` return. Defaults to `false`.
`@returns` documentation regardless of implicit or explicit `return`'s
in the function. May be desired to flag that a project is aware of an
`undefined`/`void` return. Defaults to `false`.
- `forceReturnsWithAsync` - By default `async` functions that do not explicitly
return a value pass this rule as an `async` function will always return a
`Promise`, even if the `Promise` resolves to void. You can force all `async`
functions to require return statements by setting `forceReturnsWithAsync`
to `true` on the options object. This may be useful for flagging that there
has been consideration of return type. Defaults to `false`.
return a value pass this rule as an `async` function will always return a
`Promise`, even if the `Promise` resolves to void. You can force all
`async` functions to require return statements by setting
`forceReturnsWithAsync` to `true` on the options object. This may be useful
for flagging that there has been consideration of return type. Defaults
to `false`.
- `contexts` - Set this to an array of strings representing the AST context
where you wish the rule to be applied.
Overrides the default contexts (see below). Set to `"any"` if you want
the rule to apply to any jsdoc block throughout your files (as is necessary
for finding function blocks not attached to a function declaration or
expression, i.e., `@callback` or `@function` (or its aliases `@func` or
`@method`) (including those associated with an `@interface`). This
rule will only apply on non-default contexts when there is such a tag
present and the `forceRequireReturn` option is set or if the
`forceReturnsWithAsync` option is set with a present `@async` tag
(since we are not checking against the actual `return` values in these
cases).
where you wish the rule to be applied.
Overrides the default contexts (see below). Set to `"any"` if you want
the rule to apply to any jsdoc block throughout your files (as is necessary
for finding function blocks not attached to a function declaration or
expression, i.e., `@callback` or `@function` (or its aliases `@func` or
`@method`) (including those associated with an `@interface`). This
rule will only apply on non-default contexts when there is such a tag
present and the `forceRequireReturn` option is set or if the
`forceReturnsWithAsync` option is set with a present `@async` tag
(since we are not checking against the actual `return` values in these
cases).

```js
'jsdoc/require-returns': ['error', {forceReturnsWithAsync: true}]
```

| | |
| -------- | ------------------------------------------------------------------------------------------------------------- |
| | |
| -------- | ------- |
| Context | `ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled |
| Tags | `returns` |
| Aliases | `return` |
| Options | `checkConstructors`, `checkGetters`, `contexts`, `exemptedBy`, `forceRequireReturn`, `forceReturnsWithAsync` |
| Settings | `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` |
| Tags | `returns` |
| Aliases | `return` |
| Options | `checkConstructors`, `checkGetters`, `contexts`, `exemptedBy`, `forceRequireReturn`, `forceReturnsWithAsync` |
| Settings | `overrideReplacesDocs`, `augmentsExtendsReplacesDocs`, `implementsReplacesDocs` |

The following patterns are considered problems:

Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import requireReturns from './rules/requireReturns';
import requireReturnsCheck from './rules/requireReturnsCheck';
import requireReturnsDescription from './rules/requireReturnsDescription';
import requireReturnsType from './rules/requireReturnsType';
import requireThrows from './rules/requireThrows';
import validTypes from './rules/validTypes';
import requireJsdoc from './rules/requireJsdoc';

Expand Down Expand Up @@ -119,6 +120,7 @@ export default {
'require-returns-check': requireReturnsCheck,
'require-returns-description': requireReturnsDescription,
'require-returns-type': requireReturnsType,
'require-throws': requireThrows,
'valid-types': validTypes,
},
};
4 changes: 4 additions & 0 deletions src/iterateJsdoc.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,10 @@ const getUtils = (
return jsdocUtils.hasReturnValue(node);
};

utils.hasThrowValue = () => {
return jsdocUtils.hasThrowValue(node);
};

utils.isAsync = () => {
return node.async;
};
Expand Down
56 changes: 56 additions & 0 deletions src/jsdocUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,61 @@ const hasReturnValue = (node) => {
}
};

/**
* Checks if a node has a throws statement.
*
* @param {object} node
* @returns {boolean}
*/
const hasThrowValue = (node) => {
if (!node) {
return false;
}
switch (node.type) {
case 'FunctionExpression':
case 'FunctionDeclaration':
case 'ArrowFunctionExpression': {
return node.expression || hasThrowValue(node.body);
}
case 'BlockStatement': {
return node.body.some((bodyNode) => {
return bodyNode.type !== 'FunctionDeclaration' && hasThrowValue(bodyNode);
});
}
case 'WhileStatement':
case 'DoWhileStatement':
case 'ForStatement':
case 'ForInStatement':
case 'ForOfStatement':
case 'WithStatement': {
return hasThrowValue(node.body);
}
case 'IfStatement': {
return hasThrowValue(node.consequent) || hasThrowValue(node.alternate);
}

// We only consider it to throw an error if the catch or finally blocks throw an error.
case 'TryStatement': {
return hasThrowValue(node.handler && node.handler.body) ||
hasThrowValue(node.finalizer);
}
case 'SwitchStatement': {
return node.cases.some(
(someCase) => {
return someCase.consequent.some(hasThrowValue);
},
);
}
case 'ThrowStatement': {
return true;
}

default: {
return false;
}
}
};

/** @param {string} tag */
/*
const isInlineTag = (tag) => {
Expand Down Expand Up @@ -668,6 +723,7 @@ export default {
hasDefinedTypeReturnTag,
hasReturnValue,
hasTag,
hasThrowValue,
isNamepathDefiningTag,
isValidTag,
parseClosureTemplateTag,
Expand Down
86 changes: 86 additions & 0 deletions src/rules/requireThrows.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import iterateJsdoc from '../iterateJsdoc';

/**
* We can skip checking for a throws value, in case the documentation is inherited
* or the method is either a constructor or an abstract method.
*
* @param {*} utils
* a reference to the utils which are used to probe if a tag is present or not.
* @returns {boolean}
* true in case deep checking can be skipped; otherwise false.
*/
const canSkip = (utils) => {
return utils.hasATag([
// inheritdoc implies that all documentation is inherited
// see https://jsdoc.app/tags-inheritdoc.html
//
// Abstract methods are by definition incomplete,
// so it is not necessary to document that they throw an error.
'abstract',
'virtual',

// The designated type can itself document `@throws`
'type',
]) ||
utils.avoidDocs();
};

export default iterateJsdoc(({
report,
utils,
}) => {
// A preflight check. We do not need to run a deep check for abstract
// functions.
if (canSkip(utils)) {
return;
}

const tagName = utils.getPreferredTagName({tagName: 'throws'});
if (!tagName) {
return;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how to cover this case in a test?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be enough to add a (passing) example which doesn't have @throws at all (or where it has @throws but settings.jsdoc.tagNamePreference is set to map throws to something else like throw and if @throw wasn't present).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only line that I can't figure out how to cover. I feel like it should be covered by this test, but it seems like I'm not understanding how utils.getPreferredTagName() is working?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries, I've added the test (it was setting throws to false on tagNamePreference settings, i.e., if someone had indicated they wished to block the throws tag yet were still using this rule. :)

I think it looked good, but need a little more time to give it another look over before merging.

}

const tags = utils.getTags(tagName);
const iteratingFunction = utils.isIteratingFunction();

// In case the code returns something, we expect a return value in JSDoc.
const [tag] = tags;
const missingThrowsTag = typeof tag === 'undefined' || tag === null;

const shouldReport = () => {
if (!missingThrowsTag) {
return false;
}

return iteratingFunction && utils.hasThrowValue();
};

if (shouldReport()) {
report(`Missing JSDoc @${tagName} declaration.`);
}
}, {
contextDefaults: true,
meta: {
schema: [
{
additionalProperties: false,
properties: {
contexts: {
items: {
type: 'string',
},
type: 'array',
},
exemptedBy: {
items: {
type: 'string',
},
type: 'array',
},
},
type: 'object',
},
],
type: 'suggestion',
},
});