Skip to content

Commit

Permalink
feat(functional-parameters): allow overriding options based on where …
Browse files Browse the repository at this point in the history
…the function type is declared

fix #575
  • Loading branch information
RebeccaStevens committed Apr 22, 2024
1 parent 2a8bbbc commit 71364aa
Show file tree
Hide file tree
Showing 7 changed files with 388 additions and 73 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,9 @@ The [below section](#rules) gives details on which rules are enabled by each rul

### Currying

| Name | Description | 💼 | ⚠️ | 🚫 | 🔧 | 💡 | 💭 ||
| :----------------------------------------------------------- | :----------------------------- | :--------------------------- | :-- | :-- | :-- | :-- | :-- | :-- |
| [functional-parameters](docs/rules/functional-parameters.md) | Enforce functional parameters. | ☑️ ✅ 🔒 ![badge-currying][] | | | | | | |
| Name | Description | 💼 | ⚠️ | 🚫 | 🔧 | 💡 | 💭 ||
| :----------------------------------------------------------- | :----------------------------- | :--------------------------- | :-- | :---------------------------- | :-- | :-- | :-- | :-- |
| [functional-parameters](docs/rules/functional-parameters.md) | Enforce functional parameters. | ☑️ ✅ 🔒 ![badge-currying][] | | ![badge-disableTypeChecked][] | | | 💭 | |

### No Exceptions

Expand Down
44 changes: 43 additions & 1 deletion docs/rules/functional-parameters.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
# Enforce functional parameters (`functional/functional-parameters`)

💼 This rule is enabled in the following configs: `currying`, ☑️ `lite`, ✅ `recommended`, 🔒 `strict`.
💼🚫 This rule is enabled in the following configs: `currying`, ☑️ `lite`, ✅ `recommended`, 🔒 `strict`. This rule is _disabled_ in the `disableTypeChecked` config.

💭 This rule requires [type information](https://typescript-eslint.io/linting/typed-linting).

<!-- end auto-generated rule header -->

Disallow use of rest parameters, the `arguments` keyword and enforces that functions take at least 1 parameter.

Note: type information is only required when using the [overrides](#overrides) option.

## Rule Details

In functions, `arguments` is a special variable that is implicitly available.
Expand Down Expand Up @@ -67,6 +71,23 @@ type Options = {
};
ignoreIdentifierPattern?: string[] | string;
ignorePrefixSelector?: string[] | string;
overrides?: Array<{
match:
| {
from: "file";
path?: string;
}
| {
from: "lib";
}
| {
from: "package";
package?: string;
}
| TypeDeclarationSpecifier[];
options: Omit<Options, "overrides">;
disable: boolean;
}>;
};
```

Expand Down Expand Up @@ -196,3 +217,24 @@ const sum = [1, 2, 3].reduce((carry, current) => current, 0);

This option takes a RegExp string or an array of RegExp strings.
It allows for the ability to ignore violations based on a function's name.

### `overrides`

_Using this option requires type infomation._

Allows for applying overrides to the options based on where the function's type is defined.
This can be used to override the settings for types coming from 3rd party libraries.

Note: Only the first matching override will be used.

#### `overrides[n].specifiers`

A specifier, or an array of specifiers to match the function type against.

#### `overrides[n].options`

The options to use when a specifiers matches.

#### `overrides[n].disable`

If true, when a specifier matches, this rule will not be applied to the matching node.
181 changes: 118 additions & 63 deletions src/rules/functional-parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { deepmerge } from "deepmerge-ts";
import {
type IgnoreIdentifierPatternOption,
type IgnorePrefixSelectorOption,
type OverridableOptions,
getCoreOptions,
ignoreIdentifierPatternOptionSchema,
ignorePrefixSelectorOptionSchema,
shouldIgnorePattern,
Expand All @@ -20,7 +22,9 @@ import {
type RuleResult,
createRuleUsingFunction,
} from "#eslint-plugin-functional/utils/rule";
import { typeSpecifiersSchema } from "#eslint-plugin-functional/utils/schemas";
import {
getEnclosingFunction,
isArgument,
isGetter,
isIIFE,
Expand All @@ -45,25 +49,65 @@ export const fullName = `${ruleNameScope}/${name}`;
*/
type ParameterCountOptions = "atLeastOne" | "exactlyOne";

type CoreOptions = IgnoreIdentifierPatternOption &
IgnorePrefixSelectorOption & {
allowRestParameter: boolean;
allowArgumentsKeyword: boolean;
enforceParameterCount:
| ParameterCountOptions
| false
| {
count: ParameterCountOptions;
ignoreLambdaExpression: boolean;
ignoreIIFE: boolean;
ignoreGettersAndSetters: boolean;
};
};

/**
* The options this rule can take.
*/
type Options = [
IgnoreIdentifierPatternOption &
IgnorePrefixSelectorOption & {
allowRestParameter: boolean;
allowArgumentsKeyword: boolean;
enforceParameterCount:
| ParameterCountOptions
| false
| {
count: ParameterCountOptions;
ignoreLambdaExpression: boolean;
ignoreIIFE: boolean;
ignoreGettersAndSetters: boolean;
};
},
];
type Options = [OverridableOptions<CoreOptions>];

const coreOptionsPropertiesSchema: JSONSchema4ObjectSchema["properties"] = {
allowRestParameter: {
type: "boolean",
},
allowArgumentsKeyword: {
type: "boolean",
},
enforceParameterCount: {
oneOf: [
{
type: "boolean",
enum: [false],
},
{
type: "string",
enum: ["atLeastOne", "exactlyOne"],
},
{
type: "object",
properties: {
count: {
type: "string",
enum: ["atLeastOne", "exactlyOne"],
},
ignoreGettersAndSetters: {
type: "boolean",
},
ignoreLambdaExpression: {
type: "boolean",
},
ignoreIIFE: {
type: "boolean",
},
},
additionalProperties: false,
},
],
},
};

/**
* The schema for the rule options.
Expand All @@ -74,43 +118,25 @@ const schema: JSONSchema4[] = [
properties: deepmerge(
ignoreIdentifierPatternOptionSchema,
ignorePrefixSelectorOptionSchema,
coreOptionsPropertiesSchema,
{
allowRestParameter: {
type: "boolean",
},
allowArgumentsKeyword: {
type: "boolean",
},
enforceParameterCount: {
oneOf: [
{
type: "boolean",
enum: [false],
},
{
type: "string",
enum: ["atLeastOne", "exactlyOne"],
},
{
type: "object",
properties: {
count: {
type: "string",
enum: ["atLeastOne", "exactlyOne"],
},
ignoreGettersAndSetters: {
type: "boolean",
},
ignoreLambdaExpression: {
type: "boolean",
},
ignoreIIFE: {
type: "boolean",
},
overrides: {
type: "array",
items: {
type: "object",
properties: {
specifiers: typeSpecifiersSchema,
options: {
type: "object",
properties: coreOptionsPropertiesSchema,
additionalProperties: false,
},
disable: {
type: "boolean",
},
additionalProperties: false,
},
],
additionalProperties: false,
},
},
} satisfies JSONSchema4ObjectSchema["properties"],
),
Expand Down Expand Up @@ -156,6 +182,7 @@ const meta: NamedCreateRuleCustomMeta<keyof typeof errorMessages, Options> = {
description: "Enforce functional parameters.",
recommended: "recommended",
recommendedSeverity: "error",
requiresTypeChecking: true,
},
messages: errorMessages,
schema,
Expand All @@ -165,7 +192,7 @@ const meta: NamedCreateRuleCustomMeta<keyof typeof errorMessages, Options> = {
* Get the rest parameter violations.
*/
function getRestParamViolations(
[{ allowRestParameter }]: Readonly<Options>,
{ allowRestParameter }: Readonly<CoreOptions>,
node: ESFunction,
): RuleResult<keyof typeof errorMessages, Options>["descriptors"] {
return !allowRestParameter &&
Expand All @@ -184,7 +211,7 @@ function getRestParamViolations(
* Get the parameter count violations.
*/
function getParamCountViolations(
[{ enforceParameterCount }]: Readonly<Options>,
{ enforceParameterCount }: Readonly<CoreOptions>,
node: ESFunction,
): RuleResult<keyof typeof errorMessages, Options>["descriptors"] {
if (
Expand Down Expand Up @@ -235,8 +262,20 @@ function checkFunction(
context: Readonly<RuleContext<keyof typeof errorMessages, Options>>,
options: Readonly<Options>,
): RuleResult<keyof typeof errorMessages, Options> {
const [optionsObject] = options;
const { ignoreIdentifierPattern } = optionsObject;
const optionsToUse = getCoreOptions<CoreOptions, Options>(
node,
context,
options,
);

if (optionsToUse === null) {
return {
context,
descriptors: [],
};
}

const { ignoreIdentifierPattern } = optionsToUse;

if (shouldIgnorePattern(node, context, ignoreIdentifierPattern)) {
return {
Expand All @@ -248,8 +287,8 @@ function checkFunction(
return {
context,
descriptors: [
...getRestParamViolations(options, node),
...getParamCountViolations(options, node),
...getRestParamViolations(optionsToUse, node),
...getParamCountViolations(optionsToUse, node),
],
};
}
Expand All @@ -262,8 +301,27 @@ function checkIdentifier(
context: Readonly<RuleContext<keyof typeof errorMessages, Options>>,
options: Readonly<Options>,
): RuleResult<keyof typeof errorMessages, Options> {
const [optionsObject] = options;
const { ignoreIdentifierPattern } = optionsObject;
if (node.name !== "arguments") {
return {
context,
descriptors: [],
};
}

const functionNode = getEnclosingFunction(node);
const optionsToUse =
functionNode === null
? options[0]
: getCoreOptions<CoreOptions, Options>(functionNode, context, options);

if (optionsToUse === null) {
return {
context,
descriptors: [],
};
}

const { ignoreIdentifierPattern } = optionsToUse;

if (shouldIgnorePattern(node, context, ignoreIdentifierPattern)) {
return {
Expand All @@ -272,15 +330,12 @@ function checkIdentifier(
};
}

const { allowArgumentsKeyword } = optionsObject;
const { allowArgumentsKeyword } = optionsToUse;

return {
context,
descriptors:
!allowArgumentsKeyword &&
node.name === "arguments" &&
!isPropertyName(node) &&
!isPropertyAccess(node)
!allowArgumentsKeyword && !isPropertyName(node) && !isPropertyAccess(node)
? [
{
node,
Expand Down
21 changes: 15 additions & 6 deletions src/utils/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,21 @@ export function isInFunctionBody(
node: TSESTree.Node,
async?: boolean,
): boolean {
const functionNode = getAncestorOfType(
const functionNode = getEnclosingFunction(node);

return (
functionNode !== null &&
(async === undefined || functionNode.async === async)
);
}

/**
* Get the function the given node is in.
*
* Will return null if not in a function.
*/
export function getEnclosingFunction(node: TSESTree.Node) {
return getAncestorOfType(
(
n,
c,
Expand All @@ -62,11 +76,6 @@ export function isInFunctionBody(
| TSESTree.FunctionExpression => isFunctionLike(n) && n.body === c,
node,
);

return (
functionNode !== null &&
(async === undefined || functionNode.async === async)
);
}

/**
Expand Down
Loading

0 comments on commit 71364aa

Please sign in to comment.