1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | const astUtils = require("./utils/ast-utils");
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u;
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | module.exports = {
|
24 | meta: {
|
25 | type: "suggestion",
|
26 |
|
27 | docs: {
|
28 | description: "disallow assignment operators in `return` statements",
|
29 | category: "Best Practices",
|
30 | recommended: false,
|
31 | url: "https://eslint.org/docs/rules/no-return-assign"
|
32 | },
|
33 |
|
34 | schema: [
|
35 | {
|
36 | enum: ["except-parens", "always"]
|
37 | }
|
38 | ],
|
39 |
|
40 | messages: {
|
41 | returnAssignment: "Return statement should not contain assignment.",
|
42 | arrowAssignment: "Arrow function should not return assignment."
|
43 | }
|
44 | },
|
45 |
|
46 | create(context) {
|
47 | const always = (context.options[0] || "except-parens") !== "except-parens";
|
48 | const sourceCode = context.getSourceCode();
|
49 |
|
50 | return {
|
51 | AssignmentExpression(node) {
|
52 | if (!always && astUtils.isParenthesised(sourceCode, node)) {
|
53 | return;
|
54 | }
|
55 |
|
56 | let currentChild = node;
|
57 | let parent = currentChild.parent;
|
58 |
|
59 |
|
60 | while (parent && !SENTINEL_TYPE.test(parent.type)) {
|
61 | currentChild = parent;
|
62 | parent = parent.parent;
|
63 | }
|
64 |
|
65 |
|
66 | if (parent && parent.type === "ReturnStatement") {
|
67 | context.report({
|
68 | node: parent,
|
69 | messageId: "returnAssignment"
|
70 | });
|
71 | } else if (parent && parent.type === "ArrowFunctionExpression" && parent.body === currentChild) {
|
72 | context.report({
|
73 | node: parent,
|
74 | messageId: "arrowAssignment"
|
75 | });
|
76 | }
|
77 | }
|
78 | };
|
79 | }
|
80 | };
|