Skip to content

feat(immutable-data): add support for detecting map and set mutations #935

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

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/rules/immutable-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ This rule accepts an options object of the following type:
```ts
type Options = {
ignoreClasses: boolean | "fieldsOnly";
ignoreMapsAndSets: boolean;
ignoreImmediateMutation: boolean;
ignoreNonConstDeclarations:
| boolean
Expand Down Expand Up @@ -113,6 +114,7 @@ type Options = {
```ts
type Options = {
ignoreClasses: false;
ignoreMapsAndSets: false;
ignoreImmediateMutation: true;
ignoreNonConstDeclarations: false;
};
Expand Down Expand Up @@ -159,6 +161,10 @@ Ignore mutations inside classes.

Classes already aren't functional so ignore mutations going on inside them.

### `ignoreMapsAndSets`

Ignore mutations of builtin `Map`s and `Set`s.

### `ignoreIdentifierPattern`

This option takes a RegExp string or an array of RegExp strings.
Expand Down
16 changes: 16 additions & 0 deletions src/options/ignore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,22 @@ export const ignoreClassesOptionSchema: JSONSchema4ObjectSchema["properties"] =
},
};

/**
* The option to ignore mapsAndSets.
*/
export type IgnoreMapsAndSetsOption = Readonly<{
ignoreMapsAndSets: boolean;
}>;

/**
* The schema for the option to ignore maps and sets.
*/
export const ignoreMapsAndSetsOptionSchema: JSONSchema4ObjectSchema["properties"] = {
ignoreMapsAndSets: {
type: "boolean",
},
};

/**
* The option to ignore prefix selector.
*/
Expand Down
135 changes: 123 additions & 12 deletions src/rules/immutable-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@ import {
type IgnoreAccessorPatternOption,
type IgnoreClassesOption,
type IgnoreIdentifierPatternOption,
type IgnoreMapsAndSetsOption,
type OverridableOptions,
type RawOverridableOptions,
getCoreOptions,
ignoreAccessorPatternOptionSchema,
ignoreClassesOptionSchema,
ignoreIdentifierPatternOptionSchema,
ignoreMapsAndSetsOptionSchema,
shouldIgnoreClasses,
shouldIgnorePattern,
upgradeRawOverridableOptions,
} from "#/options";
import { isExpected, ruleNameScope } from "#/utils/misc";
import { ruleNameScope } from "#/utils/misc";
import { type NamedCreateRuleCustomMeta, type Rule, type RuleResult, createRule, getTypeOfNode } from "#/utils/rule";
import { overridableOptionsSchema } from "#/utils/schemas";
import { findRootIdentifier, isDefinedByMutableVariable, isInConstructor } from "#/utils/tree";
Expand All @@ -27,9 +29,13 @@ import {
isArrayType,
isCallExpression,
isIdentifier,
isMapConstructorType,
isMapType,
isMemberExpression,
isNewExpression,
isObjectConstructorType,
isSetConstructorType,
isSetType,
isTSAsExpression,
} from "#/utils/type-guards";

Expand All @@ -45,6 +51,7 @@ export const fullName: `${typeof ruleNameScope}/${typeof name}` = `${ruleNameSco

type CoreOptions = IgnoreAccessorPatternOption &
IgnoreClassesOption &
IgnoreMapsAndSetsOption &
IgnoreIdentifierPatternOption & {
ignoreImmediateMutation: boolean;
ignoreNonConstDeclarations:
Expand All @@ -64,6 +71,7 @@ const coreOptionsPropertiesSchema = deepmerge(
ignoreIdentifierPatternOptionSchema,
ignoreAccessorPatternOptionSchema,
ignoreClassesOptionSchema,
ignoreMapsAndSetsOptionSchema,
{
ignoreImmediateMutation: {
type: "boolean",
Expand Down Expand Up @@ -98,6 +106,7 @@ const schema: JSONSchema4[] = [overridableOptionsSchema(coreOptionsPropertiesSch
const defaultOptions = [
{
ignoreClasses: false,
ignoreMapsAndSets: false,
ignoreImmediateMutation: true,
ignoreNonConstDeclarations: false,
},
Expand All @@ -110,6 +119,8 @@ const errorMessages = {
generic: "Modifying an existing object/array is not allowed.",
object: "Modifying properties of existing object not allowed.",
array: "Modifying an array is not allowed.",
map: "Modifying a map is not allowed.",
set: "Modifying a set is not allowed.",
} as const;

/**
Expand Down Expand Up @@ -151,14 +162,38 @@ const arrayMutatorMethods = new Set([
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods#Accessor_methods
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Iteration_methods
*/
const arrayNewObjectReturningMethods = ["concat", "slice", "filter", "map", "reduce", "reduceRight"];
const arrayNewObjectReturningMethods = new Set(["concat", "slice", "filter", "map", "reduce", "reduceRight"]);

/**
* Array constructor functions that create a new array.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods
*/
const arrayConstructorFunctions = ["from", "of"];
const arrayConstructorFunctions = new Set(["from", "of"]);

/**
* Map methods that mutate an map.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
*/
const mapMutatorMethods = new Set(["clear", "delete", "set"]);

/**
* Map methods that return a new object without mutating the original.
*/
const mapNewObjectReturningMethods = new Set<string>([]);

/**
* Set methods that mutate an set.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
*/
const setMutatorMethods = new Set(["add", "clear", "delete"]);

/**
* Set methods that return a new object without mutating the original.
*/
const setNewObjectReturningMethods = new Set(["difference", "intersection", "symmetricDifference", "union"]);

/**
* Object constructor functions that mutate an object.
Expand All @@ -170,7 +205,7 @@ const objectConstructorMutatorFunctions = new Set(["assign", "defineProperties",
/**
* Object constructor functions that return new objects.
*/
const objectConstructorNewObjectReturningMethods = [
const objectConstructorNewObjectReturningMethods = new Set([
"create",
"entries",
"fromEntries",
Expand All @@ -181,14 +216,14 @@ const objectConstructorNewObjectReturningMethods = [
"groupBy",
"keys",
"values",
];
]);

/**
* String constructor functions that return new objects.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods
*/
const stringConstructorNewObjectReturningMethods = ["split"];
const stringConstructorNewObjectReturningMethods = new Set(["split"]);

/**
* Check if the given assignment expression violates this rule.
Expand Down Expand Up @@ -391,35 +426,49 @@ function isInChainCallAndFollowsNew(
}

// Check for: new Array()
if (isNewExpression(node) && isArrayConstructorType(context, getTypeOfNode(node.callee, context))) {
return true;
if (isNewExpression(node)) {
const type = getTypeOfNode(node.callee, context);
return (
isArrayConstructorType(context, type) ||
isMapConstructorType(context, type) ||
isSetConstructorType(context, type)
);
}

if (isCallExpression(node) && isMemberExpression(node.callee) && isIdentifier(node.callee.property)) {
// Check for: Array.from(iterable)
if (
arrayConstructorFunctions.some(isExpected(node.callee.property.name)) &&
arrayConstructorFunctions.has(node.callee.property.name) &&
isArrayConstructorType(context, getTypeOfNode(node.callee.object, context))
) {
return true;
}

// Check for: array.slice(0)
if (arrayNewObjectReturningMethods.some(isExpected(node.callee.property.name))) {
if (arrayNewObjectReturningMethods.has(node.callee.property.name)) {
return true;
}

if (mapNewObjectReturningMethods.has(node.callee.property.name)) {
return true;
}

// Check for: set.difference(otherSet)
if (setNewObjectReturningMethods.has(node.callee.property.name)) {
return true;
}

// Check for: Object.entries(object)
if (
objectConstructorNewObjectReturningMethods.some(isExpected(node.callee.property.name)) &&
objectConstructorNewObjectReturningMethods.has(node.callee.property.name) &&
isObjectConstructorType(context, getTypeOfNode(node.callee.object, context))
) {
return true;
}

// Check for: "".split("")
if (
stringConstructorNewObjectReturningMethods.some(isExpected(node.callee.property.name)) &&
stringConstructorNewObjectReturningMethods.has(node.callee.property.name) &&
getTypeOfNode(node.callee.object, context).isStringLiteral()
) {
return true;
Expand Down Expand Up @@ -510,6 +559,68 @@ function checkCallExpression(
}
}

// Set mutation?
if (
setMutatorMethods.has(node.callee.property.name) &&
(!ignoreImmediateMutation || !isInChainCallAndFollowsNew(node.callee, context)) &&
isSetType(context, getTypeOfNode(node.callee.object, context))
) {
if (ignoreNonConstDeclarations === false) {
return {
context,
descriptors: [{ node, messageId: "set" }],
};
}
const rootIdentifier = findRootIdentifier(node.callee.object);
if (
rootIdentifier === undefined ||
!isDefinedByMutableVariable(
rootIdentifier,
context,
(variableNode) =>
ignoreNonConstDeclarations === true ||
!ignoreNonConstDeclarations.treatParametersAsConst ||
shouldIgnorePattern(variableNode, context, ignoreIdentifierPattern, ignoreAccessorPattern),
)
) {
return {
context,
descriptors: [{ node, messageId: "set" }],
};
}
}

// Map mutation?
if (
mapMutatorMethods.has(node.callee.property.name) &&
(!ignoreImmediateMutation || !isInChainCallAndFollowsNew(node.callee, context)) &&
isMapType(context, getTypeOfNode(node.callee.object, context))
) {
if (ignoreNonConstDeclarations === false) {
return {
context,
descriptors: [{ node, messageId: "map" }],
};
}
const rootIdentifier = findRootIdentifier(node.callee.object);
if (
rootIdentifier === undefined ||
!isDefinedByMutableVariable(
rootIdentifier,
context,
(variableNode) =>
ignoreNonConstDeclarations === true ||
!ignoreNonConstDeclarations.treatParametersAsConst ||
shouldIgnorePattern(variableNode, context, ignoreIdentifierPattern, ignoreAccessorPattern),
)
) {
return {
context,
descriptors: [{ node, messageId: "map" }],
};
}
}

// Non-array object mutation (ex. Object.assign on identifier)?
if (
objectConstructorMutatorFunctions.has(node.callee.property.name) &&
Expand Down
7 changes: 0 additions & 7 deletions src/utils/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,6 @@ import {

export const ruleNameScope = "functional";

/**
* Higher order function to check if the two given values are the same.
*/
export function isExpected<T>(expected: T): (actual: T) => boolean {
return (actual) => actual === expected;
}

/**
* Does the given ExpressionStatement specify directive prologues.
*/
Expand Down
16 changes: 16 additions & 0 deletions src/utils/type-guards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,13 +324,29 @@ export function isArrayType(context: RuleContext<string, ReadonlyArray<unknown>>
return typeMatches(context, "Array", type);
}

export function isMapType(context: RuleContext<string, ReadonlyArray<unknown>>, type: Type | null): boolean {
return typeMatches(context, "Map", type);
}

export function isSetType(context: RuleContext<string, ReadonlyArray<unknown>>, type: Type | null): boolean {
return typeMatches(context, "Set", type);
}

export function isArrayConstructorType(
context: RuleContext<string, ReadonlyArray<unknown>>,
type: Type | null,
): boolean {
return typeMatches(context, "ArrayConstructor", type);
}

export function isMapConstructorType(context: RuleContext<string, ReadonlyArray<unknown>>, type: Type | null): boolean {
return typeMatches(context, "MapConstructor", type);
}

export function isSetConstructorType(context: RuleContext<string, ReadonlyArray<unknown>>, type: Type | null): boolean {
return typeMatches(context, "SetConstructor", type);
}

export function isObjectConstructorType(
context: RuleContext<string, ReadonlyArray<unknown>>,
type: Type | null,
Expand Down
Loading
Loading