@lsby/eslint-plugin 0.0.20 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,37 +1,173 @@
1
1
  "use strict";
2
- // 禁止 else(当条件是等于或不等于时)
3
- // 对于等于/不等于的条件判断,else 表示"除当前条件外的所有可能"
4
- // 当状态集合未来扩展时, 依然会被包含在else分支里, 导致状态遗漏却无任何报错
5
- // 应当使用提早返回 switch + 穷尽检查
2
+ // 禁止对于等于/不等于条件的 else 处理多种状态
3
+ // 因为对于这些条件,else 表示"除给定状态外的所有可能"
4
+ // 对于状态小于等于两个的条件, else 只会兜底一种情况, 这是正确的
5
+ // 但如果状态继续增加, else 兜底必然匹配一个以上种状态
6
+ // 此时 else 部分会默默吃掉新增状态却无任何提示, 这很容易造成意外的状态逻辑遗漏
7
+ // 这种情况下应当使用提早返回 或 switch + 穷尽检查
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
6
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
+ const ts = __importStar(require("typescript"));
7
43
  const rule = {
8
44
  meta: {
9
45
  type: 'problem',
10
- docs: { description: '当条件是等于或不等于时,禁止使用 else 分支,防止隐含的状态遗漏' },
11
- messages: {
12
- noElse: '禁止在等于/不等于条件下使用 else 分支。当条件状态扩展时, else 分支可能遗漏新的状态。请改用提前返回(early return)或 switch 语句',
46
+ docs: {
47
+ description: '禁止对等于/不等于条件使用 else。当新增状态时,else 会隐匿地处理新状态,容易造成状态逻辑遗漏。应使用提早返回或 switch + 穷尽检查替代。',
13
48
  },
49
+ messages: { noElse: '禁止在等于/不等于条件中使用 else,请使用提早返回或 switch 语句进行穷尽检查。' },
14
50
  schema: [],
15
51
  },
16
52
  defaultOptions: [],
17
53
  create(context) {
54
+ const parserServices = context.parserServices;
55
+ const typeChecker = parserServices?.program?.getTypeChecker();
56
+ /**
57
+ * 计算类型中的字面量值个数
58
+ */
59
+ function countLiteralVariants(type) {
60
+ // 先检查联合类型,因为它可能包含其他标志
61
+ if ((type.flags & ts.TypeFlags.Union) !== 0) {
62
+ const union = type;
63
+ // Count distinct types in union
64
+ let count = 0;
65
+ for (const t of union.types) {
66
+ count += countLiteralVariants(t);
67
+ }
68
+ return count;
69
+ }
70
+ // 布尔类型有 2 个值:true 和 false
71
+ if ((type.flags & ts.TypeFlags.Boolean) !== 0) {
72
+ return 2;
73
+ }
74
+ // 布尔字面量类型(true 或 false)
75
+ if ((type.flags & ts.TypeFlags.BooleanLiteral) !== 0) {
76
+ return 1;
77
+ }
78
+ // null 类型(1 个值)
79
+ if ((type.flags & ts.TypeFlags.Null) !== 0) {
80
+ return 1;
81
+ }
82
+ // undefined 类型(1 个值)
83
+ if ((type.flags & ts.TypeFlags.Undefined) !== 0) {
84
+ return 1;
85
+ }
86
+ // 字面量类型
87
+ if ((type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) !== 0) {
88
+ return 1;
89
+ }
90
+ // 其他类型(如 number、string 等)认为是无限的
91
+ return Infinity;
92
+ }
18
93
  /**
19
- * 检查条件中是否包含等于或不等于操作符
94
+ * 检查条件中是否包含等于或不等于操作符,以及被比较的值
95
+ * 返回 [operand1, operand2] 或 null
20
96
  */
21
- function hasEqualityOperator(node) {
97
+ function getEqualityOperands(node) {
22
98
  if (node.type === 'BinaryExpression') {
23
- return ['===', '!==', '==', '!='].includes(node.operator);
99
+ const binExpr = node;
100
+ if (['===', '!==', '==', '!='].includes(binExpr.operator)) {
101
+ return [binExpr.left, binExpr.right];
102
+ }
103
+ return null;
24
104
  }
25
105
  if (node.type === 'LogicalExpression') {
26
- return hasEqualityOperator(node.left) || hasEqualityOperator(node.right);
106
+ const left = getEqualityOperands(node.left);
107
+ if (left)
108
+ return left;
109
+ return getEqualityOperands(node.right);
110
+ }
111
+ return null;
112
+ }
113
+ /**
114
+ * 检查是否应该允许 else(状态数 ≤ 2)
115
+ * 返回 true 表示允许 else,false 表示不允许
116
+ */
117
+ function shouldAllowElse(leftExpr, rightExpr) {
118
+ if (!typeChecker || !parserServices?.esTreeNodeToTSNodeMap) {
119
+ // 无法获取类型信息时,按原始规则:不允许 else
120
+ return false;
121
+ }
122
+ try {
123
+ // 获取 TypeScript 节点
124
+ const leftNode = parserServices.esTreeNodeToTSNodeMap.get(leftExpr);
125
+ const rightNode = parserServices.esTreeNodeToTSNodeMap.get(rightExpr);
126
+ if (!leftNode || !rightNode) {
127
+ // 无法映射节点时,按原始规则:不允许 else
128
+ return false;
129
+ }
130
+ // 获取两个操作数的类型
131
+ let leftType = typeChecker.getTypeAtLocation(leftNode);
132
+ let rightType = typeChecker.getTypeAtLocation(rightNode);
133
+ // 对于标识符,尝试获取声明的类型
134
+ if (leftExpr.type === 'Identifier') {
135
+ const leftSymbol = typeChecker.getSymbolAtLocation(leftNode);
136
+ if (leftSymbol && leftSymbol.valueDeclaration) {
137
+ leftType = typeChecker.getTypeOfSymbolAtLocation(leftSymbol, leftSymbol.valueDeclaration);
138
+ }
139
+ }
140
+ if (rightExpr.type === 'Identifier') {
141
+ const rightSymbol = typeChecker.getSymbolAtLocation(rightNode);
142
+ if (rightSymbol && rightSymbol.valueDeclaration) {
143
+ rightType = typeChecker.getTypeOfSymbolAtLocation(rightSymbol, rightSymbol.valueDeclaration);
144
+ }
145
+ }
146
+ // 计算每边的字面量值个数
147
+ const leftCount = countLiteralVariants(leftType);
148
+ const rightCount = countLiteralVariants(rightType);
149
+ // 只有当两边都是有限的且都 ≤ 2 个状态时,才允许 else
150
+ const bothFinite = isFinite(leftCount) && isFinite(rightCount);
151
+ const allow = bothFinite && leftCount <= 2 && rightCount <= 2;
152
+ return allow;
153
+ }
154
+ catch {
155
+ // 如果出错,按原始规则:不允许 else
156
+ return false;
27
157
  }
28
- return false;
29
158
  }
30
159
  return {
31
160
  IfStatement(node) {
32
161
  // 仅在 if 条件是等于或不等于的情况下,禁止 else
33
- if (node.alternate !== null && hasEqualityOperator(node.test)) {
34
- context.report({ node: node.alternate, messageId: 'noElse' });
162
+ if (node.alternate !== null) {
163
+ const operands = getEqualityOperands(node.test);
164
+ if (operands) {
165
+ const [left, right] = operands;
166
+ // 检查是否应该允许 else(基于类型的字面量值个数)
167
+ if (!shouldAllowElse(left, right)) {
168
+ context.report({ node: node.alternate, messageId: 'noElse' });
169
+ }
170
+ }
35
171
  }
36
172
  },
37
173
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lsby/eslint-plugin",
3
- "version": "0.0.20",
3
+ "version": "0.0.22",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [