@angular-modernizer/plugin-solid 1.2.0 → 2.0.0

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,314 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LSPViolationRule = void 0;
4
- const ts_morph_1 = require("ts-morph");
5
4
  /**
6
- * LSP Violation Rule (`solid:lsp-violation`) - detects Liskov Substitution
7
- * Principle violations that break substitutability.
5
+ * Former Liskov Substitution checks (missing interface members, missing
6
+ * abstract methods, `not implemented` throws, `instanceof` checks). Reports
7
+ * nothing: a class that misses a required member of an implemented interface
8
+ * or an abstract method of its base does not compile (TS2420, TS2515), so on
9
+ * code that builds those checks could only fire on members they failed to see
10
+ * (inherited, optional, constructor parameter properties, arrow properties).
11
+ * An `instanceof` check alone (`error instanceof HttpErrorResponse`) shows no
12
+ * subtype that breaks its base's contract.
8
13
  *
9
- * Detection patterns (`violationType` in the metadata):
10
- * - `missing-interface-method`, `missing-interface-property`: members of an
11
- * implemented interface that the class does not declare (Angular internal
12
- * members starting with `ɵ` are ignored)
13
- * - `missing-abstract-method`: abstract methods of the base class that are
14
- * not implemented
15
- * - `throws-not-implemented`: implementations of abstract methods whose
16
- * first `throw` mentions `NotImplemented` or `not implemented`
17
- * - `instanceof-check`, `excessive-instanceof-checks`: `instanceof` checks in
18
- * methods (3 or more in one method count as excessive)
14
+ * The id stays registered so configurations naming it keep loading; ConfigLoader
15
+ * warns that `rules['solid:lsp-violation']` has no effect.
19
16
  *
20
- * @example
21
- * ```typescript
22
- * // Violation: derived class weakens base contract
23
- * class Bird { fly(): void {} }
24
- * class Penguin extends Bird {
25
- * fly(): void { throw new Error('Penguins cannot fly'); }
26
- * }
27
- * ```
17
+ * @deprecated Reports nothing; removed in 3.0. The TypeScript compiler reports
18
+ * missing interface members and abstract methods.
28
19
  */
29
20
  class LSPViolationRule {
30
21
  id = 'solid:lsp-violation';
31
- name = 'Liskov Substitution Principle Violation';
32
- description = 'Detects classes that violate the Liskov Substitution Principle';
22
+ name = 'Liskov Substitution Principle Violation (deprecated)';
23
+ description = 'Deprecated, reports nothing: missing interface members and abstract methods are compile errors';
33
24
  severity = 'warning';
34
25
  category = 'solid-violation';
35
- tags = [
36
- 'solid',
37
- 'lsp',
38
- 'liskov-substitution',
39
- 'inheritance',
40
- 'interfaces',
41
- 'polymorphism',
42
- ];
43
- async analyze(context) {
44
- const violations = [];
45
- const sourceFile = context.sourceFile;
46
- // Find all class declarations
47
- const classes = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ClassDeclaration);
48
- for (const classDecl of classes) {
49
- const classViolations = this.analyzeClass(classDecl, sourceFile.getFilePath());
50
- violations.push(...classViolations);
51
- }
52
- return Promise.resolve(violations);
53
- }
54
- /**
55
- * Analyze a class for LSP violations.
56
- */
57
- analyzeClass(classDecl, filePath) {
58
- const violations = [];
59
- try {
60
- // Check 1: Interface implementation violations
61
- const interfaceViolations = this.checkInterfaceImplementation(classDecl, filePath);
62
- violations.push(...interfaceViolations);
63
- // Check 2: Abstract method implementation violations
64
- const abstractViolations = this.checkAbstractMethodImplementation(classDecl, filePath);
65
- violations.push(...abstractViolations);
66
- // Check 3: Inheritance-based violations (instanceof checks)
67
- const inheritanceViolations = this.checkInheritanceBasedViolations(classDecl, filePath);
68
- violations.push(...inheritanceViolations);
69
- // Note: Abstract method and inheritance-based checks are complex with ts-morph
70
- // and may not work reliably in all contexts. Interface compliance is the
71
- // most important LSP aspect that can be reliably detected.
72
- }
73
- catch (_error) {
74
- // If we can't analyze the class, skip it
75
- }
76
- return violations;
77
- }
78
- /**
79
- * Check interface implementation compliance.
80
- */
81
- checkInterfaceImplementation(classDecl, filePath) {
82
- const violations = [];
83
- const className = classDecl.getName() ?? 'AnonymousClass';
84
- try {
85
- // Get implemented interfaces
86
- const implementedInterfaces = classDecl.getImplements();
87
- for (const interfaceImpl of implementedInterfaces) {
88
- const interfaceType = interfaceImpl.getType();
89
- const declarations = interfaceType.getSymbol()?.getDeclarations();
90
- if (declarations && declarations.length > 0) {
91
- const interfaceDecl = declarations[0];
92
- // Check if all interface methods are implemented
93
- const interfaceMethods = interfaceDecl.getMethods();
94
- const interfaceProperties = interfaceDecl.getProperties();
95
- // Check methods
96
- for (const interfaceMethod of interfaceMethods) {
97
- const methodName = interfaceMethod.getName();
98
- const classMethod = classDecl.getMethod(methodName);
99
- if (!classMethod) {
100
- violations.push({
101
- ruleId: this.id,
102
- message: `Class '${className}' implements interface '${interfaceDecl.getName()}' but does not implement method '${methodName}'`,
103
- filePath,
104
- line: classDecl.getStartLineNumber(),
105
- column: classDecl.getStart() - classDecl.getStartLinePos(),
106
- suggestedFix: `Implement method '${methodName}' in class '${className}'`,
107
- metadata: {
108
- className,
109
- interfaceName: interfaceDecl.getName(),
110
- missingMethod: methodName,
111
- violationType: 'missing-interface-method',
112
- principle: 'LSP',
113
- },
114
- });
115
- }
116
- }
117
- // Check properties
118
- for (const interfaceProperty of interfaceProperties) {
119
- const propertyName = interfaceProperty.getName();
120
- // TODO: Implement in Phase 2 - proper handling of external/internal properties
121
- // Currently we skip Angular internal properties (ɵ) but need better logic for:
122
- // - Public vs private properties in interfaces
123
- // - Optional properties (@Input() prop?: Type)
124
- // - Properties with different visibility modifiers
125
- // - Inherited properties from base interfaces
126
- // Skip Angular internal properties (starting with ɵ)
127
- if (propertyName.startsWith('ɵ')) {
128
- continue;
129
- }
130
- const classProperty = classDecl.getProperty(propertyName) ??
131
- classDecl.getGetAccessor(propertyName) ??
132
- classDecl.getSetAccessor(propertyName);
133
- if (!classProperty) {
134
- violations.push({
135
- ruleId: this.id,
136
- message: `Class '${className}' implements interface '${interfaceDecl.getName()}' but does not implement property '${propertyName}'`,
137
- filePath,
138
- line: classDecl.getStartLineNumber(),
139
- column: classDecl.getStart() - classDecl.getStartLinePos(),
140
- suggestedFix: `Implement property '${propertyName}' in class '${className}'`,
141
- metadata: {
142
- className,
143
- interfaceName: interfaceDecl.getName(),
144
- missingProperty: propertyName,
145
- violationType: 'missing-interface-property',
146
- principle: 'LSP',
147
- },
148
- });
149
- }
150
- }
151
- }
152
- }
153
- }
154
- catch (_error) {
155
- // Skip if we can't analyze interfaces
156
- }
157
- return violations;
158
- }
159
- /**
160
- * Check abstract method implementation compliance.
161
- */
162
- checkAbstractMethodImplementation(classDecl, filePath) {
163
- const violations = [];
164
- const className = classDecl.getName() ?? 'AnonymousClass';
165
- try {
166
- // Check if this class extends an abstract class
167
- const heritageClauses = classDecl.getHeritageClauses();
168
- const extendsClause = heritageClauses.find((h) => h.getToken() === ts_morph_1.SyntaxKind.ExtendsKeyword);
169
- if (extendsClause) {
170
- for (const typeNode of extendsClause.getTypeNodes()) {
171
- const baseType = typeNode.getType();
172
- const baseDeclarations = baseType.getSymbol()?.getDeclarations();
173
- if (baseDeclarations) {
174
- for (const baseDecl of baseDeclarations) {
175
- if (baseDecl.getKind() === ts_morph_1.SyntaxKind.ClassDeclaration) {
176
- const baseClassDecl = baseDecl;
177
- // Check if base class is abstract
178
- if (baseClassDecl.isAbstract()) {
179
- // Get all abstract methods from base class
180
- const abstractMethods = baseClassDecl
181
- .getMethods()
182
- .filter((m) => m.isAbstract());
183
- for (const abstractMethod of abstractMethods) {
184
- const methodName = abstractMethod.getName();
185
- const implementedMethod = classDecl.getMethod(methodName);
186
- if (!implementedMethod) {
187
- violations.push({
188
- ruleId: this.id,
189
- message: `Class '${className}' extends abstract class '${baseClassDecl.getName()}' but does not implement abstract method '${methodName}'`,
190
- filePath,
191
- line: classDecl.getStartLineNumber(),
192
- column: classDecl.getStart() - classDecl.getStartLinePos(),
193
- suggestedFix: `Implement abstract method '${methodName}' in class '${className}'`,
194
- metadata: {
195
- className,
196
- baseClassName: baseClassDecl.getName(),
197
- missingMethod: methodName,
198
- violationType: 'missing-abstract-method',
199
- principle: 'LSP',
200
- },
201
- });
202
- }
203
- else {
204
- // Check if implementation throws exceptions (potential LSP violation)
205
- const methodBody = implementedMethod.getBody();
206
- if (methodBody) {
207
- const throwStatements = methodBody.getDescendantsOfKind(ts_morph_1.SyntaxKind.ThrowStatement);
208
- if (throwStatements.length > 0) {
209
- // Check if it's just throwing NotImplementedError or similar
210
- const firstThrow = throwStatements[0];
211
- const expression = firstThrow?.getExpression();
212
- if (expression &&
213
- (expression.getText().includes('NotImplemented') ||
214
- expression.getText().includes('not implemented'))) {
215
- violations.push({
216
- ruleId: this.id,
217
- message: `Method '${methodName}' in class '${className}' throws NotImplementedError, violating LSP expectations`,
218
- filePath,
219
- line: implementedMethod.getStartLineNumber(),
220
- column: implementedMethod.getStart() -
221
- implementedMethod.getStartLinePos(),
222
- suggestedFix: `Implement '${methodName}' properly or reconsider the inheritance hierarchy`,
223
- metadata: {
224
- className,
225
- methodName,
226
- violationType: 'throws-not-implemented',
227
- principle: 'LSP',
228
- },
229
- });
230
- }
231
- }
232
- }
233
- }
234
- }
235
- }
236
- }
237
- }
238
- }
239
- }
240
- }
241
- }
242
- catch (_error) {
243
- // Skip if we can't analyze abstract methods
244
- }
245
- return violations;
246
- }
247
- /**
248
- * Check for inheritance-based violations like instanceof checks.
249
- */
250
- checkInheritanceBasedViolations(classDecl, filePath) {
251
- const violations = [];
252
- const className = classDecl.getName() ?? 'AnonymousClass';
253
- try {
254
- // Find all methods in this class
255
- const methods = classDecl.getMethods();
256
- for (const method of methods) {
257
- const methodBody = method.getBody();
258
- if (methodBody) {
259
- // Look for instanceof expressions
260
- const instanceofExpressions = methodBody
261
- .getDescendantsOfKind(ts_morph_1.SyntaxKind.BinaryExpression)
262
- .filter((expr) => expr.getOperatorToken().getKind() ===
263
- ts_morph_1.SyntaxKind.InstanceOfKeyword);
264
- if (instanceofExpressions.length > 0) {
265
- // Check if this is part of a larger instanceof chain (switch-like pattern)
266
- const methodText = methodBody.getText();
267
- const instanceofCount = (methodText.match(/instanceof/g) ?? [])
268
- .length;
269
- if (instanceofCount >= 3) {
270
- violations.push({
271
- ruleId: this.id,
272
- message: `Method '${method.getName()}' in class '${className}' uses ${instanceofCount} instanceof checks, indicating poor inheritance design (LSP violation)`,
273
- filePath,
274
- line: method.getStartLineNumber(),
275
- column: method.getStart() - method.getStartLinePos(),
276
- suggestedFix: `Consider using polymorphism instead of instanceof checks. Implement common behavior in base class or use Strategy pattern.`,
277
- metadata: {
278
- className,
279
- methodName: method.getName(),
280
- instanceofCount,
281
- violationType: 'excessive-instanceof-checks',
282
- principle: 'LSP',
283
- },
284
- });
285
- }
286
- else if (instanceofCount >= 1) {
287
- // Single instanceof might still be problematic
288
- violations.push({
289
- ruleId: this.id,
290
- message: `Method '${method.getName()}' in class '${className}' uses instanceof check, potentially violating LSP`,
291
- filePath,
292
- line: method.getStartLineNumber(),
293
- column: method.getStart() - method.getStartLinePos(),
294
- suggestedFix: `Consider using polymorphism or method overriding instead of instanceof checks`,
295
- metadata: {
296
- className,
297
- methodName: method.getName(),
298
- instanceofCount,
299
- violationType: 'instanceof-check',
300
- principle: 'LSP',
301
- },
302
- });
303
- }
304
- }
305
- }
306
- }
307
- }
308
- catch (_error) {
309
- // Skip if we can't analyze inheritance patterns
310
- }
311
- return violations;
26
+ tags = ['solid', 'lsp', 'deprecated'];
27
+ analyze(_context) {
28
+ return Promise.resolve([]);
312
29
  }
313
30
  }
314
31
  exports.LSPViolationRule = LSPViolationRule;
@@ -1,60 +1,76 @@
1
1
  import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
2
2
  /**
3
- * OCP Violation Rule (`solid:ocp-violation`) - detects code that has to be
4
- * modified for new features (Open/Closed Principle violation).
3
+ * OCP Violation Rule (`solid:ocp-violation`) - reports if-else chains that
4
+ * dispatch on one value, so every new value means editing the chain.
5
5
  *
6
- * Detection patterns in class methods (`violationType` in the metadata):
7
- * - `large-switch-statement`: switch statements with more than 5 cases
8
- * - `long-if-else-chain`: if/else chains with more than 4 branches
9
- * - `too-many-parameters`: methods with more than 4 parameters
6
+ * One finding per chain (`violationType: 'long-if-else-chain'`, severity
7
+ * warning, at the first `if`) when the chain has more than 4 conditions
8
+ * (the `if` plus its `else if` links; a final plain `else` is not counted)
9
+ * and every condition compares the same discriminant with `===` or `==`,
10
+ * also as `a === x || a === y`. The discriminant is a variable, parameter,
11
+ * property access chain (`this.state.kind`) or element access with a
12
+ * reference or literal key (`values[key]`); two references are the same
13
+ * when they resolve to the same symbols and keys, names alone do not match.
14
+ *
15
+ * Chains are checked everywhere in the file: methods, constructors, nested
16
+ * classes and functions outside classes. Switch statements are reported by
17
+ * `solid:god-switch`, parameter counts by no SOLID rule.
10
18
  *
11
19
  * @example
12
20
  * ```typescript
13
- * // Violation: requires modification for each new shape type
14
- * function createShape(type: string) {
15
- * switch (type) {
16
- * case 'circle': return new Circle();
17
- * case 'square': return new Square();
18
- * // Every new shape requires editing this function
19
- * }
21
+ * // Reported: 5 conditions on `kind`
22
+ * function area(kind: string): number {
23
+ * if (kind === 'circle') return 1;
24
+ * else if (kind === 'square') return 2;
25
+ * else if (kind === 'triangle') return 3;
26
+ * else if (kind === 'hexagon') return 4;
27
+ * else if (kind === 'star') return 5;
28
+ * return 0;
20
29
  * }
21
30
  * ```
22
31
  */
23
32
  export declare class OCPViolationRule implements AnalysisRule {
24
33
  readonly id = "solid:ocp-violation";
25
34
  readonly name = "Open/Closed Principle Violation";
26
- readonly description = "Detects code that violates the Open/Closed Principle";
35
+ readonly description = "Detects if-else chains that compare one discriminant in more than 4 conditions (Open/Closed Principle)";
27
36
  readonly severity = "warning";
28
37
  readonly category = "solid-violation";
29
38
  readonly tags: string[];
30
- /**
31
- * Maximum number of switch cases allowed.
32
- */
33
- private readonly maxSwitchCases;
34
- /**
35
- * Maximum number of if-else conditions in a chain.
36
- */
37
- private readonly maxIfElseChain;
38
- /**
39
- * Maximum number of parameters allowed in a method.
40
- */
41
- private readonly maxMethodParameters;
39
+ /** Conditions a chain may have before it is reported. */
40
+ private readonly maxConditions;
42
41
  analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
42
+ /** True when the `if` is the `else` branch of another `if`. */
43
+ private isElseIfLink;
44
+ private checkChain;
45
+ /** Conditions of the `if` and of its `else if` links, in order. */
46
+ private chainConditions;
43
47
  /**
44
- * Analyze a class for OCP violations.
45
- */
46
- private analyzeClass;
47
- /**
48
- * Analyze a method for OCP violations.
48
+ * The reference every comparison of every condition shares, or
49
+ * `undefined` when a condition is no equality comparison or no reference
50
+ * is shared.
49
51
  */
50
- private analyzeMethod;
52
+ private commonDiscriminant;
51
53
  /**
52
- * Analyze a switch statement for OCP violations.
54
+ * Operand pairs of `===`/`==` comparisons joined by `||`, or `undefined`
55
+ * when the condition has another shape.
53
56
  */
54
- private analyzeSwitchStatement;
57
+ private comparisons;
55
58
  /**
56
- * Analyze if-else chains for OCP violations.
59
+ * Canonical key of a variable, parameter, property access chain or element
60
+ * access, built from symbols (`this` for a `this` root; the property name
61
+ * only when the receiver has no type information). `undefined` for
62
+ * anything else.
57
63
  */
58
- private analyzeIfElseChain;
64
+ private reference;
65
+ private referenceKey;
66
+ /** Key of an element access argument: a reference or a string or number literal. */
67
+ private elementKey;
68
+ private symbolId;
69
+ /** Strips parentheses and non-null assertions. */
70
+ private unwrap;
71
+ /** Name of the function, method or accessor that holds the chain. */
72
+ private chainOwner;
73
+ private isFunctionLike;
74
+ private functionName;
59
75
  }
60
76
  //# sourceMappingURL=ocp-violation.rule.d.ts.map