1
+import type { ESTree, Scope, SourceCode, Variable } from '@oxlint/plugins';
2
+
3
+/** Resolve an identifier node to its binding by walking lexical scopes upward. */
4
+export function resolveIdentifier(
5
+ sourceCode: SourceCode,
6
+ identifier: ESTree.Node & { readonly name: string }
7
+): Variable | null {
8
+ let scope: Scope | null = sourceCode.getScope(identifier);
9
+ while (scope !== null) {
10
+ const variable = scope.set.get(identifier.name);
11
+ if (variable !== undefined) return variable;
12
+ scope = scope.upper;
13
+ }
14
+ return null;
15
+}
16
+
17
+/** Effect modules whose members the Effect rules recognize. */
18
+export type EffectModule = 'Context' | 'Effect' | 'Layer' | 'ManagedRuntime';
19
+
20
+const effectModules: ReadonlySet<string> = new Set<EffectModule>([
21
+ 'Context',
22
+ 'Effect',
23
+ 'Layer',
24
+ 'ManagedRuntime',
25
+]);
26
+
27
+/** Local names bound to each Effect module by the file's imports. */
28
+export interface EffectModuleNames {
29
+ readonly sourceCode: SourceCode;
30
+ readonly modules: ReadonlyMap<EffectModule, ReadonlySet<string>>;
31
+}
32
+
33
+const isEffectModule = (name: string): name is EffectModule => effectModules.has(name);
34
+
35
+const importedName = (specifier: ESTree.ImportSpecifier): string =>
36
+ specifier.imported.type === 'Identifier' ? specifier.imported.name : specifier.imported.value;
37
+
38
+/** Collect `import { Effect } from "effect"` and `import * as Effect from "effect/Effect"` bindings. */
39
+export function collectEffectModuleNames(sourceCode: SourceCode): EffectModuleNames {
40
+ const names = new Map<EffectModule, Set<string>>();
41
+ const add = (module: EffectModule, local: string) => {
42
+ const existing = names.get(module) ?? new Set<string>();
43
+ existing.add(local);
44
+ names.set(module, existing);
45
+ };
46
+
47
+ for (const statement of sourceCode.ast.body) {
48
+ if (statement.type !== 'ImportDeclaration') continue;
49
+ const source = statement.source.value;
50
+ if (source === 'effect') {
51
+ for (const specifier of statement.specifiers) {
52
+ if (specifier.type !== 'ImportSpecifier') continue;
53
+ const name = importedName(specifier);
54
+ if (isEffectModule(name)) add(name, specifier.local.name);
55
+ }
56
+ continue;
57
+ }
58
+ const module = source.startsWith('effect/') ? source.slice('effect/'.length) : '';
59
+ if (!isEffectModule(module)) continue;
60
+ for (const specifier of statement.specifiers) {
61
+ if (
62
+ specifier.type === 'ImportNamespaceSpecifier' ||
63
+ specifier.type === 'ImportDefaultSpecifier'
64
+ ) {
65
+ add(module, specifier.local.name);
66
+ }
67
+ }
68
+ }
69
+
70
+ return { sourceCode, modules: names };
71
+}
72
+
73
+/** Strip parentheses, type assertions and instantiation expressions from an expression. */
74
+export function unwrapExpression(expression: ESTree.Expression): ESTree.Expression {
75
+ let current = expression;
76
+ while (
77
+ current.type === 'ParenthesizedExpression' ||
78
+ current.type === 'TSAsExpression' ||
79
+ current.type === 'TSSatisfiesExpression' ||
80
+ current.type === 'TSTypeAssertion' ||
81
+ current.type === 'TSNonNullExpression' ||
82
+ current.type === 'TSInstantiationExpression'
83
+ ) {
84
+ current = current.expression;
85
+ }
86
+ return current;
87
+}
88
+
89
+/** Like {@link unwrapExpression}, for any node. */
90
+export function unwrapNode(node: ESTree.Node): ESTree.Node {
91
+ let current = node;
92
+ while (
93
+ current.type === 'ParenthesizedExpression' ||
94
+ current.type === 'TSAsExpression' ||
95
+ current.type === 'TSSatisfiesExpression' ||
96
+ current.type === 'TSTypeAssertion' ||
97
+ current.type === 'TSNonNullExpression' ||
98
+ current.type === 'TSInstantiationExpression'
99
+ ) {
100
+ current = current.expression;
101
+ }
102
+ return current;
103
+}
104
+
105
+/** The member name when `node` is `<module>.<member>` for one of the module's local names, else null. */
106
+export function moduleMemberName(
107
+ node: ESTree.Node | null | undefined,
108
+ names: EffectModuleNames,
109
+ module: EffectModule
110
+): string | null {
111
+ if (node === null || node === undefined) return null;
112
+ const expression = node.type === 'TSInstantiationExpression' ? node.expression : node;
113
+ if (
114
+ expression.type !== 'MemberExpression' ||
115
+ expression.computed ||
116
+ expression.object.type !== 'Identifier' ||
117
+ !(names.modules.get(module)?.has(expression.object.name) ?? false) ||
118
+ expression.property.type !== 'Identifier'
119
+ ) {
120
+ return null;
121
+ }
122
+ const binding = resolveIdentifier(names.sourceCode, expression.object);
123
+ if (!binding?.defs.some(definition => definition.type === 'ImportBinding')) return null;
124
+ return expression.property.name;
125
+}
126
+
127
+/** The member name when `node` is a call of `<module>.<member>(...)`, else null. */
128
+export function moduleCallName(
129
+ node: ESTree.Node | null | undefined,
130
+ names: EffectModuleNames,
131
+ module: EffectModule
132
+): string | null {
133
+ return node?.type === 'CallExpression'
134
+ ? moduleMemberName(unwrapExpression(node.callee), names, module)
135
+ : null;
136
+}
137
+
138
+/** The parts of `class X extends Context.Service<...>()("key", options) {}`. */
139
+export interface ServiceClass {
140
+ readonly node: ESTree.Class;
141
+ readonly name: string | null;
142
+ readonly options: ESTree.ObjectExpression | null;
143
+}
144
+
145
+/** Read a Context.Service class declaration, or null when the class is not one. */
146
+export function serviceClass(node: ESTree.Class, names: EffectModuleNames): ServiceClass | null {
147
+ if (node.superClass === null) return null;
148
+ const superClass = unwrapExpression(node.superClass);
149
+ if (superClass.type !== 'CallExpression') return null;
150
+ const factory = unwrapExpression(superClass.callee);
151
+ if (
152
+ factory.type !== 'CallExpression' ||
153
+ moduleMemberName(unwrapExpression(factory.callee), names, 'Context') !== 'Service'
154
+ ) {
155
+ return null;
156
+ }
157
+ const optionsArgument = superClass.arguments[1];
158
+ const options =
159
+ optionsArgument !== undefined && optionsArgument.type !== 'SpreadElement'
160
+ ? unwrapExpression(optionsArgument)
161
+ : null;
162
+ return {
163
+ node,
164
+ name: node.id?.name ?? null,
165
+ options: options?.type === 'ObjectExpression' ? options : null,
166
+ };
167
+}
168
+
169
+/** The name of a non-computed property key, or null. */
170
+export function keyName(key: ESTree.Node): string | null {
171
+ if (key.type === 'Identifier' || key.type === 'PrivateIdentifier') return key.name;
172
+ if (key.type === 'Literal' && typeof key.value === 'string') return key.value;
173
+ return null;
174
+}
175
+
176
+const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
177
+
178
+/** Whether the file is a `*.test.*` or `*.spec.*` file. */
179
+export const isTestFile = (filename: string): boolean =>
180
+ TEST_FILE.test(filename.replaceAll('\\', '/'));
181
+
182
+const skippedKeys: ReadonlySet<string> = new Set(['parent', 'loc', 'range', 'start', 'end']);
183
+
184
+const isNode = (value: unknown): value is ESTree.Node =>
185
+ typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string';
186
+
187
+/** Visit every descendant of `node`. Return false from `visit` to skip a node's children. */
188
+export function walk(node: ESTree.Node, visit: (node: ESTree.Node) => boolean): void {
189
+ if (!visit(node)) return;
190
+ for (const [key, value] of Object.entries(node)) {
191
+ if (skippedKeys.has(key)) continue;
192
+ if (Array.isArray(value)) {
193
+ for (const item of value) {
194
+ if (isNode(item)) walk(item, visit);
195
+ }
196
+ } else if (isNode(value)) {
197
+ walk(value, visit);
198
+ }
199
+ }
200
+}
201
+
202
+/** A function expression, arrow, or declaration. */
203
+export type FunctionNode = ESTree.ArrowFunctionExpression | ESTree.Function;
204
+
205
+/** Whether `node` is a function expression, arrow, or declaration. */
206
+export const isFunction = (node: ESTree.Node | null | undefined): node is FunctionNode =>
207
+ node?.type === 'ArrowFunctionExpression' ||
208
+ node?.type === 'FunctionExpression' ||
209
+ node?.type === 'FunctionDeclaration';
210
+
211
+/** The return statements of a function body, without descending into nested functions. */
212
+export function ownReturns(body: ESTree.Node): readonly ESTree.ReturnStatement[] {
213
+ const returns: ESTree.ReturnStatement[] = [];
214
+ walk(body, node => {
215
+ if (node !== body && isFunction(node)) return false;
216
+ if (node.type === 'ReturnStatement') returns.push(node);
217
+ return true;
218
+ });
219
+ return returns;
220
+}
221
+
222
+/** The expressions a function produces: its expression body or the arguments of its own returns. */
223
+export function returnedExpressions(fn: FunctionNode): readonly ESTree.Expression[] {
224
+ if (fn.body === null) return [];
225
+ if (fn.body.type !== 'BlockStatement') return [fn.body];
226
+ return ownReturns(fn.body).flatMap(statement =>
227
+ statement.argument === null ? [] : [statement.argument]
228
+ );
229
+}
230
+
231
+const isPipeMember = (node: ESTree.Node): node is ESTree.MemberExpression =>
232
+ node.type === 'MemberExpression' &&
233
+ !node.computed &&
234
+ node.property.type === 'Identifier' &&
235
+ node.property.name === 'pipe';
236
+
237
+/** For `x.pipe(...)`, the receiver `x`; otherwise null. */
238
+export function pipeReceiver(node: ESTree.Node): ESTree.Expression | null {
239
+ if (node.type !== 'CallExpression') return null;
240
+ const callee = unwrapExpression(node.callee);
241
+ return isPipeMember(callee) ? unwrapExpression(callee.object) : null;
242
+}
243
+
244
+/**
245
+ * The steps that run before `call` when it is an argument of a pipeline-like call such as `x.pipe(a, call)`,
246
+ * `pipe(x, a, call)`, or `Effect.fn("name")(body, a, call)`, including earlier `.pipe(...)` receivers.
247
+ */
248
+export function precedingSteps(call: ESTree.Node): readonly ESTree.Node[] {
249
+ const parent = call.parent;
250
+ if (parent?.type !== 'CallExpression') return [];
251
+ const index = parent.arguments.findIndex(argument => argument === call);
252
+ if (index < 0) return [];
253
+ const steps: ESTree.Node[] = [];
254
+ let receiver = pipeReceiver(parent);
255
+ while (receiver !== null) {
256
+ steps.push(receiver);
257
+ if (receiver.type === 'CallExpression') steps.push(...receiver.arguments);
258
+ receiver = pipeReceiver(receiver);
259
+ }
260
+ steps.push(...parent.arguments.slice(0, index));
261
+ return steps;
262
+}
263
+
264
+/** The generator passed to `Effect.gen(...)`, or null when `node` is not such a call. */
265
+export function genFunction(node: ESTree.Node, names: EffectModuleNames): ESTree.Function | null {
266
+ if (moduleCallName(node, names, 'Effect') !== 'gen' || node.type !== 'CallExpression')
267
+ return null;
268
+ const body = node.arguments.at(-1);
269
+ return body?.type === 'FunctionExpression' ? body : null;
270
+}