@inflexa-ai/typecheck 0.7.0 → 0.9.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.
package/README.md CHANGED
@@ -77,7 +77,7 @@ export default typecheck({
77
77
  - `rules` maps a rule id to `'error'`, `'off'`, or `['error', options]`.
78
78
  - For a file and a rule, the last override that matches the file and names the rule sets the severity.
79
79
  - `['error', options]` sets the options. `'error'` alone keeps the options of an earlier override that matches the file.
80
- - `typecheck()` puts its own block first. That block turns on `no-generated-empty-object-type` for `**/*.{ts,tsx}`.
80
+ - `typecheck()` puts its own block first. That block turns on `no-generated-empty-object-type` and `no-lookup-in-loop` for `**/*.{ts,tsx}`.
81
81
 
82
82
  Each of these problems stops the run with a message: an unknown rule id, a plugin that loads two times under one name, and options that the rule refuses.
83
83
 
@@ -90,6 +90,7 @@ Node.js removes the types of the file when it loads it. Thus the file uses only
90
90
  | `must-use-result` | [must-use-result](https://github.com/inflexa-ai/lint/blob/main/docs/rules/must-use-result.md) |
91
91
  | `require-abort-signal` | [require-abort-signal](https://github.com/inflexa-ai/lint/blob/main/docs/rules/require-abort-signal.md) |
92
92
  | `no-generated-empty-object-type` | [no-generated-empty-object-type](https://github.com/inflexa-ai/lint/blob/main/docs/rules/no-generated-empty-object-type.md) |
93
+ | `no-lookup-in-loop` | [no-lookup-in-loop](https://github.com/inflexa-ai/lint/blob/main/docs/rules/no-lookup-in-loop.md) |
93
94
 
94
95
  The rules of this package have no prefix. The rules of a plugin have the id `<plugin name>/<rule name>`, where the plugin name is the `name` of the plugin object. The `./typecheck` entry of `@inflexa-ai/oxlint-plugin-react` gives the plugin `@inflexa-ai/react`.
95
96
 
package/dist/config.d.ts CHANGED
@@ -36,9 +36,9 @@ export type ActiveRule = {
36
36
  export declare const CONFIG_FILE = "typecheck.config.ts";
37
37
  /**
38
38
  * The configuration of `inflexa-typecheck`. Its own block comes first and
39
- * turns on `no-generated-empty-object-type` for each TypeScript file, as the
40
- * former ESLint configuration did. Each other typed rule is on only where an
41
- * override of the repository turns it on.
39
+ * turns on `no-generated-empty-object-type`, as the former ESLint configuration
40
+ * did, and `no-lookup-in-loop` for each TypeScript file. Each other typed rule
41
+ * is on only where an override of the repository turns it on.
42
42
  */
43
43
  export declare function typecheck({ plugins, overrides }?: TypecheckOptions): TypecheckConfig;
44
44
  /**
package/dist/config.js CHANGED
@@ -21,7 +21,7 @@ export class TypecheckConfig {
21
21
  }
22
22
  export const CONFIG_FILE = 'typecheck.config.ts';
23
23
  export function typecheck({ plugins = [], overrides = [] } = {}) {
24
- return new TypecheckConfig(plugins, [{ files: ['**/*.{ts,tsx}'], rules: { 'no-generated-empty-object-type': 'error' } }, ...overrides]);
24
+ return new TypecheckConfig(plugins, [{ files: ['**/*.{ts,tsx}'], rules: { 'no-generated-empty-object-type': 'error', 'no-lookup-in-loop': 'error' } }, ...overrides]);
25
25
  }
26
26
  export async function loadConfig(cwd, file) {
27
27
  const target = path.resolve(cwd, file ?? CONFIG_FILE);
@@ -1,8 +1,10 @@
1
1
  import { mustUseResult } from './must-use-result.js';
2
2
  import { noGeneratedEmptyObjectType } from './no-generated-empty-object-type.js';
3
+ import { noLookupInLoop } from './no-lookup-in-loop.js';
3
4
  import { requireAbortSignal } from './require-abort-signal.js';
4
5
  export const rules = {
5
6
  'must-use-result': mustUseResult,
6
7
  'no-generated-empty-object-type': noGeneratedEmptyObjectType,
8
+ 'no-lookup-in-loop': noLookupInLoop,
7
9
  'require-abort-signal': requireAbortSignal,
8
10
  };
@@ -1,4 +1,4 @@
1
- import { isArrayLiteralExpression, isArrowFunction, isAwaitExpression, isBinaryExpression, isCallExpression, isFunctionExpression, isIdentifier, isParenthesizedExpression, isPropertyAccessExpression, isSourceFile, isVariableDeclaration, isYieldExpression, SyntaxKind, } from '@typescript/native/unstable/ast';
1
+ import { isArrayLiteralExpression, isArrowFunction, isAwaitExpression, isBinaryExpression, isCallExpression, isFunctionExpression, isIdentifier, isParenthesizedExpression, isExpressionStatement, isPropertyAccessExpression, isSatisfiesExpression, isSourceFile, isVariableDeclaration, isYieldExpression, SyntaxKind, } from '@typescript/native/unstable/ast';
2
2
  import { isUnionType } from '@typescript/native/unstable/sync';
3
3
  import { stringArraysOnly } from '../rule-options.js';
4
4
  const RESULT_PROPERTIES = ['mapErr', 'map', 'andThen', 'orElse', 'match', 'unwrapOr'];
@@ -8,7 +8,6 @@ const CHECKED_METHODS = new Set(['isOk', 'isErr']);
8
8
  const FORWARDING_METHODS = new Set(['orElse', 'map', 'mapErr', 'andThen']);
9
9
  const IGNORED_PARENTS = new Set([
10
10
  SyntaxKind.AsExpression,
11
- SyntaxKind.SatisfiesExpression,
12
11
  SyntaxKind.TypeAssertionExpression,
13
12
  SyntaxKind.NonNullExpression,
14
13
  SyntaxKind.ClassDeclaration,
@@ -21,16 +20,20 @@ function parentOf(node) {
21
20
  if (isSourceFile(node))
22
21
  return undefined;
23
22
  let parent = node.parent;
24
- while (isParenthesizedExpression(parent))
23
+ while (isParenthesizedExpression(parent) || isSatisfiesExpression(parent))
25
24
  parent = parent.parent;
26
25
  return parent;
27
26
  }
28
27
  function unwrap(node) {
29
28
  let current = node;
30
- while (isParenthesizedExpression(current))
29
+ while (isParenthesizedExpression(current) || isSatisfiesExpression(current))
31
30
  current = current.expression;
32
31
  return current;
33
32
  }
33
+ function isReadCheck(access) {
34
+ const statement = parentOf(access.parent);
35
+ return statement === undefined || !isExpressionStatement(statement);
36
+ }
34
37
  function memberName(node) {
35
38
  return isPropertyAccessExpression(node) && isIdentifier(node.name) ? node.name.text : undefined;
36
39
  }
@@ -71,6 +74,8 @@ function isHandledResult(node) {
71
74
  return isHandledResult(parent);
72
75
  if (parent !== undefined && (isPropertyAccessExpression(parent) || parent.kind === SyntaxKind.ElementAccessExpression)) {
73
76
  const name = memberName(parent);
77
+ if (name !== undefined && CHECKED_METHODS.has(name) && isCallee(parent))
78
+ return isReadCheck(parent);
74
79
  if (name !== undefined && HANDLED_METHODS.has(name) && isCallee(parent))
75
80
  return true;
76
81
  if (name !== undefined && HANDLED_PROPERTIES.has(name))
@@ -86,8 +91,7 @@ function isCheckedResult(node) {
86
91
  if (!isIdentifier(node) || parent === undefined)
87
92
  return false;
88
93
  const name = memberName(parent);
89
- const above = parentOf(parent);
90
- return name !== undefined && CHECKED_METHODS.has(name) && above !== undefined && isCallExpression(above);
94
+ return name !== undefined && CHECKED_METHODS.has(name) && isCallee(parent) && isReadCheck(parent);
91
95
  }
92
96
  function isReturned(node) {
93
97
  for (let current = node; !END_OF_WALK.has(current.kind); current = current.parent) {
@@ -123,7 +127,7 @@ export const mustUseResult = {
123
127
  url: 'https://github.com/inflexa-ai/lint/blob/main/docs/rules/must-use-result.md',
124
128
  },
125
129
  messages: {
126
- mustUseResult: 'Result must be handled with either of match, unwrapOr, _unsafeUnwrap or _unsafeUnwrapErr.',
130
+ mustUseResult: 'Handle the Result: call `match` or `unwrapOr`, or branch on `isOk()` or `isErr()`.',
127
131
  },
128
132
  defaultOptions: { consumers: [] },
129
133
  },
@@ -0,0 +1,15 @@
1
+ import type { RuleModule } from '../rule.ts';
2
+ /**
3
+ * A scan inside a loop multiplies: `selected.includes(row.id)` reads each
4
+ * element of `selected` once for each row, so the work grows with the product
5
+ * of both sizes, and the cost stays invisible until a customer has a thousand
6
+ * of each. A `Set` or a `Map` built one time before the loop answers the same
7
+ * question in constant time.
8
+ *
9
+ * The rule reports only the scans that a `Set` or a `Map` can replace: a value
10
+ * lookup, and a predicate that compares one value for equality. A predicate
11
+ * with any other test, such as a range or a prefix, has no keyed form. The
12
+ * receiver must be an array that the loop does not declare: an array that each
13
+ * pass builds again cannot be indexed one time.
14
+ */
15
+ export declare const noLookupInLoop: RuleModule;
@@ -0,0 +1,170 @@
1
+ import { isArrayBindingPattern, isArrowFunction, isBindingElement, isBinaryExpression, isBlock, isCallExpression, isDoStatement, isForInStatement, isForOfStatement, isForStatement, isFunctionDeclaration, isFunctionExpression, isIdentifier, isNonNullExpression, isObjectBindingPattern, isParenthesizedExpression, isPropertyAccessExpression, isReturnStatement, isSourceFile, isVariableDeclarationList, isWhileStatement, SyntaxKind, } from '@typescript/native/unstable/ast';
2
+ const VALUE_LOOKUPS = new Set(['includes', 'indexOf', 'lastIndexOf']);
3
+ const PREDICATE_LOOKUPS = new Set(['find', 'findIndex', 'findLast', 'findLastIndex', 'some', 'filter']);
4
+ const ITERATING = new Set(['every', 'filter', 'find', 'findIndex', 'findLast', 'findLastIndex', 'flatMap', 'forEach', 'map', 'reduce', 'reduceRight', 'some']);
5
+ function unwrap(node) {
6
+ let current = node;
7
+ while (isParenthesizedExpression(current) || isNonNullExpression(current))
8
+ current = current.expression;
9
+ return current;
10
+ }
11
+ function isCallback(node) {
12
+ return isArrowFunction(node) || isFunctionExpression(node);
13
+ }
14
+ function returnedExpression(callback) {
15
+ if (!isArrowFunction(callback) && !isFunctionExpression(callback))
16
+ return undefined;
17
+ const { body } = callback;
18
+ if (!isBlock(body))
19
+ return body;
20
+ const [only] = body.statements;
21
+ return body.statements.length === 1 && isReturnStatement(only) ? only.expression : undefined;
22
+ }
23
+ function isEquality(node) {
24
+ return isBinaryExpression(node) && (node.operatorToken.kind === SyntaxKind.EqualsEqualsEqualsToken || node.operatorToken.kind === SyntaxKind.EqualsEqualsToken);
25
+ }
26
+ function isEqualityPredicate(argument) {
27
+ if (argument === undefined)
28
+ return false;
29
+ const returned = returnedExpression(unwrap(argument));
30
+ return returned !== undefined && isEquality(unwrap(returned));
31
+ }
32
+ function boundNames(name, names = new Set()) {
33
+ if (isIdentifier(name))
34
+ names.add(name.text);
35
+ else if (isObjectBindingPattern(name) || isArrayBindingPattern(name)) {
36
+ for (const element of name.elements)
37
+ if (isBindingElement(element) && element.name !== undefined)
38
+ boundNames(element.name, names);
39
+ }
40
+ return names;
41
+ }
42
+ function elementNames(loop) {
43
+ const { initializer } = loop;
44
+ if (!isVariableDeclarationList(initializer))
45
+ return boundNames(unwrap(initializer));
46
+ if (initializer.declarations.length === 0)
47
+ return new Set();
48
+ return boundNames(initializer.declarations[0].name);
49
+ }
50
+ function mentions(node, names) {
51
+ if (isIdentifier(node) && names.has(node.text))
52
+ return true;
53
+ return node.forEachChild((child) => (mentions(child, names) ? true : undefined)) === true;
54
+ }
55
+ function comparesElement(comparison, names) {
56
+ if (!isBinaryExpression(comparison))
57
+ return false;
58
+ const isElement = (side) => {
59
+ const root = rootOf(side);
60
+ return root !== undefined && isIdentifier(root) && names.has(root.text);
61
+ };
62
+ return (isElement(comparison.left) && !mentions(comparison.right, names)) || (isElement(comparison.right) && !mentions(comparison.left, names));
63
+ }
64
+ function searchesForValue(body, names) {
65
+ if (isCallback(body) || isFunctionDeclaration(body))
66
+ return false;
67
+ if (isEquality(body) && comparesElement(body, names))
68
+ return true;
69
+ return body.forEachChild((child) => (searchesForValue(child, names) ? true : undefined)) === true;
70
+ }
71
+ function rootOf(receiver) {
72
+ let current = unwrap(receiver);
73
+ while (isPropertyAccessExpression(current))
74
+ current = unwrap(current.expression);
75
+ return isIdentifier(current) || current.kind === SyntaxKind.ThisKeyword ? current : undefined;
76
+ }
77
+ function repeatsIn(parent, child) {
78
+ if (isForStatement(parent))
79
+ return child === parent.condition || child === parent.incrementor || child === parent.statement;
80
+ if (isForOfStatement(parent) || isForInStatement(parent))
81
+ return child === parent.statement;
82
+ if (isWhileStatement(parent) || isDoStatement(parent))
83
+ return child === parent.expression || child === parent.statement;
84
+ return false;
85
+ }
86
+ export const noLookupInLoop = {
87
+ meta: {
88
+ docs: {
89
+ description: 'Look up a value in a loop through a Set or a Map, not through a scan of an array',
90
+ url: 'https://github.com/inflexa-ai/lint/blob/main/docs/rules/no-lookup-in-loop.md',
91
+ },
92
+ defaultOptions: {},
93
+ messages: {
94
+ lookupInLoop: '`{{receiver}}.{{method}}` scans the whole array on each pass of the loop around it, so the work grows with the product of both sizes. Before the loop, build a `Set` of the values, or a `Map` keyed by the value that the loop compares, one time. Read it inside the loop.',
95
+ searchInLoop: 'This `for...of` searches `{{receiver}}` for a value on each pass of the loop around it, so the work grows with the product of both sizes. Before the outer loop, build a `Set` of the values, or a `Map` keyed by the value that the inner loop compares, one time. Read it inside the loop.',
96
+ },
97
+ },
98
+ create(context) {
99
+ const { checker, sourceFile } = context;
100
+ function isArray(node) {
101
+ const type = checker.getTypeAtLocation(node);
102
+ const present = type === undefined ? undefined : checker.getNonNullableType(type);
103
+ return present !== undefined && (checker.isArrayType(present) || checker.isTupleType(present));
104
+ }
105
+ function isIteratingCall(call, callback) {
106
+ if (!isCallExpression(call) || call.arguments[0] !== callback || !isCallback(callback))
107
+ return false;
108
+ const callee = unwrap(call.expression);
109
+ return isPropertyAccessExpression(callee) && isIdentifier(callee.name) && ITERATING.has(callee.name.text) && isArray(callee.expression);
110
+ }
111
+ function repeatingContextOf(node) {
112
+ let child = node;
113
+ for (let parent = child.parent; !isSourceFile(child); child = parent, parent = parent.parent) {
114
+ if (repeatsIn(parent, child))
115
+ return parent;
116
+ if (isIteratingCall(parent, child))
117
+ return child;
118
+ }
119
+ return undefined;
120
+ }
121
+ function declaredOutside(root, repeating) {
122
+ if (root.kind === SyntaxKind.ThisKeyword)
123
+ return true;
124
+ const symbol = checker.getSymbolAtLocation(root);
125
+ const declaration = (symbol?.valueDeclaration ?? symbol?.declarations[0])?.resolve();
126
+ if (declaration === undefined)
127
+ return false;
128
+ if (declaration.getSourceFile().fileName !== sourceFile.fileName)
129
+ return true;
130
+ return declaration.pos < repeating.pos || declaration.end > repeating.end;
131
+ }
132
+ function check(call) {
133
+ const callee = unwrap(call.expression);
134
+ if (!isPropertyAccessExpression(callee) || !isIdentifier(callee.name))
135
+ return;
136
+ const method = callee.name.text;
137
+ if (!VALUE_LOOKUPS.has(method) && !(PREDICATE_LOOKUPS.has(method) && isEqualityPredicate(call.arguments[0])))
138
+ return;
139
+ const root = rootOf(callee.expression);
140
+ if (root === undefined || !isArray(callee.expression))
141
+ return;
142
+ const repeating = repeatingContextOf(call);
143
+ if (repeating === undefined || !declaredOutside(root, repeating))
144
+ return;
145
+ context.report({ node: call, messageId: 'lookupInLoop', data: { receiver: callee.expression.getText(sourceFile), method } });
146
+ }
147
+ function checkSearch(loop) {
148
+ const root = rootOf(loop.expression);
149
+ if (root === undefined || !isArray(loop.expression))
150
+ return;
151
+ const repeating = repeatingContextOf(loop);
152
+ if (repeating === undefined || !declaredOutside(root, repeating))
153
+ return;
154
+ const names = elementNames(loop);
155
+ if (names.size === 0 || !searchesForValue(loop.statement, names))
156
+ return;
157
+ context.report({ node: loop, messageId: 'searchInLoop', data: { receiver: loop.expression.getText(sourceFile) } });
158
+ }
159
+ return {
160
+ [SyntaxKind.CallExpression]: (node) => {
161
+ if (isCallExpression(node))
162
+ check(node);
163
+ },
164
+ [SyntaxKind.ForOfStatement]: (node) => {
165
+ if (isForOfStatement(node))
166
+ checkSearch(node);
167
+ },
168
+ };
169
+ },
170
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inflexa-ai/typecheck",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "The type check of Inflexa on TypeScript 7: the diagnostics of tsc --noEmit and the typed rules in one command.",
5
5
  "keywords": [
6
6
  "typescript",