Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

no-unit-test.js

1,305 lines46.9 KB

1import { existsSync, readFileSync, statSync } from 'node:fs'
2import { basename, dirname, join, relative, resolve, sep } from 'node:path'
3import { parseForESLint } from '@typescript-eslint/parser'
4import {
5 findVariable,
6 isFunction,
7 isOracleConfigSource,
8 registeredTest,
9} from '../registration.js'
10​
11/**
12 * An oracle's expected results come from its model, and its check compares
13 * production with them. A test that compares production with a value that a
14 * person wrote down is a unit test. Its expectation has no independent
15 * source, so it is not oracle coverage, even in a file named for an oracle.
16 *
17 * Each oracle file declares its parts with `declareOracle` from
18 * oracle-declaration:
19 *
20 * declareOracle({ check: [checkHistory], model: [modelHistory] })
21 *
22 * The check compares production observations with the model, or with a
23 * second formulation. The grammar is the generators that produce legal
24 * histories. Each is optional: a differential or metamorphic oracle has no
25 * model, and a companion module can declare only the part that its importers
26 * use. Every test in the file must reach a declared part:
27 *
28 * - A generated property or a fixed history reaches the check.
29 * - A model pin reaches the model. It checks one model rule against its
30 * authority.
31 * - A calibration reaches the check. It shows that the check rejects a
32 * wrong answer.
33 * - A grammar calibration reaches the grammar. It shows that the generators
34 * reach the states that the laws need.
35 *
36 * A generated property counts as its own check: `fc.property(...)` or
37 * `fc.asyncProperty(...)` from fast-check, run by the test directly or
38 * through code it calls, or a `.prop([...])` registration. Its predicate
39 * states a law over inputs that nobody wrote down. It does not count when all
40 * its arbitraries are `fc.constant` or `fc.constantFrom`, written inline or
41 * bound to a const name, or when its predicate never reads its input: then it
42 * checks written values. A predicate is read where it is defined, in this file
43 * or in a test module that the file imports. One that the rule cannot read, as
44 * from a package, counts.
45 *
46 * A test reaches a part when its body uses the part, or uses a function or
47 * value that reaches it. The rule follows bindings through the file and
48 * through relative imports of other test modules, so a driver in a companion
49 * module that calls the check counts. An import is followed whether it is
50 * named, a default, or a namespace whose member the code reads; `export *`
51 * does not carry a default. A `let` holds each value that code assigns to it,
52 * such as a driver that a hook builds. A `for...of` loop variable takes each
53 * element of its array in turn, and the loop registers one test per element,
54 * so every element must reach. It does not follow imports of
55 * production: `src/` modules of a published package, which declare no oracle
56 * part. A private package, such as an end-to-end suite, keeps its tests in
57 * `src/`, and the rule follows those.
58 *
59 * The rule reports each test that reaches no declared part. Move such a test
60 * to an ordinary test file, where it stays as supplemental coverage. A file
61 * whose tests reach no part, and that declares none itself, gets one report
62 * that asks for the declaration.
63 *
64 * Files whose names start with `oracle-`, such as `oracle-replay.test.ts`,
65 * test the shared oracle machinery, and the rule skips them.
66 *
67 * A unit test that happens to use a declared grammar passes the rule.
68 * The rule cannot see whether a test that reaches a part also compares
69 * production with hand-written values, or whether a declared part is really
70 * a check or a model. Reviewers still check those.
71 *
72 * An oracle file registers only oracle tests, so it may not call an imported
73 * helper that registers a test of its own. Such a call gets an
74 * importedRegistration report: the author registers those tests from an
75 * ordinary test file. The helper is found through a named, default, or
76 * namespace import. A helper that registers the body its caller passes does not
77 * register a test of its own. Its caller's body is the test, and it is judged
78 * at the call, as a local parameter registration is: the argument at the body
79 * parameter's position, so a trailing timeout is not the body. A helper may
80 * wrap the body in a function of its own; when that wrapper uses a part, every
81 * call's test reaches it. A call to a helper in an oracle-named module is not
82 * judged here, because that module's tests are linted on their own. An
83 * `oracle-` machinery module is not linted, so its helpers are judged here as
84 * an ordinary module's are.
85 */
86​
87const declarationHelper = `declareOracle`
88​
89/**
90 * Every module that an earlier lint parsed, by path, with the mtime and size
91 * it was read at. Parsing is the costly part, so a module is parsed again only
92 * when it changes. The reach that a lint computes is never kept between lints,
93 * so an edit to any module reaches the next lint: see LintSession.
94 */
95const parsedModules = new Map()
96​
97/**
98 * The reach state of one lint run: the modules it loaded, the production
99 * package flags it read, and the reach search that resolves bindings.
100 */
101class LintSession {
102 modules = new Map()
103 published = new Map()
104 search = new ReachSearch()
106​
107/**
108 * Resolves reach through cycles. A binding or export that is still being
109 * computed reads as not reaching, which is its least fixed point. A value that
110 * consulted such an assumption above its own computation is not kept, since the
111 * assumption may not hold: it is computed again on its next read. A reaching
112 * value is always kept, because reach only comes from declared parts.
113 */
114class ReachSearch {
115 #frames = []
116 #active = new Map()
117​
118 solve(cache, key, compute) {
119 const known = cache.get(key)
120 if (known !== undefined) return known
121 if (!this.#active.has(cache)) this.#active.set(cache, new Map())
122 const active = this.#active.get(cache)
123 const depth = active.get(key)
124 if (depth !== undefined) {
125 const frame = this.#frames.at(-1)
126 frame.low = Math.min(frame.low, depth)
127 return false
128 }
129 const frame = { depth: this.#frames.length, low: Infinity }
130 this.#frames.push(frame)
131 active.set(key, frame.depth)
132 let reaches
133 try {
134 reaches = compute()
135 } finally {
136 this.#frames.pop()
137 active.delete(key)
138 }
139 const caller = this.#frames.at(-1)
140 if (caller !== undefined) caller.low = Math.min(caller.low, frame.low)
141 if (reaches || frame.low >= frame.depth) cache.set(key, reaches)
142 return reaches
143 }
145​
146/**
147 * Whether a binding that a module imports from `source` reaches a part. A
148 * module that cannot be loaded reaches nothing.
149 */
150function importedModuleReaches(fromFile, source, name, session) {
151 const file = resolveTestModule(fromFile, source, session)
152 const module = file === undefined ? undefined : loadModule(file, session)
153 return module !== undefined && module.exportReaches(name)
155​
156/** Whether a function that a module imports from `source` registers a test. */
157function importedRegisters(fromFile, source, name, session, visiting) {
158 const file = resolveTestModule(fromFile, source, session)
159 const module = file === undefined ? undefined : loadModule(file, session)
160 return module?.registrationShape(name, visiting)
162​
163/**
164 * The shape of an imported helper that a call in an oracle file invokes, or
165 * undefined. The root is the callee under any curried calls, as in
166 * `serializerProp(property, [arb])(name, check)`: a named or default import,
167 * or a member of a namespace import, as in `helpers.registerUnits()`. A helper
168 * in a module that is linted on its own is judged there.
169 */
170function importedHelperShape(node, file, sourceCode, session) {
171 let callee = node.callee
172 while (callee.type === `CallExpression`) callee = callee.callee
173 const target = importedTarget(callee, sourceCode.getScope(node))
174 if (target === undefined) return undefined
175 const module = resolveTestModule(file, target.source, session)
176 if (module === undefined || lintedOnItsOwn(module)) return undefined
177 return loadModule(module, session)?.registrationShape(target.name)
179​
180/**
181 * The import that an identifier or a namespace member names, as
182 * `{ source, name }`, or undefined when it names no import.
183 */
184function importedTarget(node, scope) {
185 if (
186 node.type === `MemberExpression` &&
187 !node.computed &&
188 node.object.type === `Identifier`
189 ) {
190 const definition = findVariable(scope, node.object.name)?.defs[0]
191 return definition?.type === `ImportBinding` &&
192 definition.node.type === `ImportNamespaceSpecifier`
193 ? { source: definition.parent.source.value, name: node.property.name }
194 : undefined
195 }
196 if (node.type !== `Identifier`) return undefined
197 const definition = findVariable(scope, node.name)?.defs[0]
198 return definition?.type === `ImportBinding`
199 ? importBindingTarget(definition)
200 : undefined
202​
203/**
204 * The export that an import binding names: the specifier's name, or `default`.
205 * A namespace import names a whole module, so it gives undefined.
206 */
207function importBindingTarget(definition) {
208 const source = definition.parent.source.value
209 if (definition.node.type === `ImportSpecifier`) {
210 const { imported } = definition.node
211 return { source, name: imported.name ?? imported.value }
212 }
213 if (definition.node.type === `ImportDefaultSpecifier`) {
214 return { source, name: `default` }
215 }
216 return undefined
218​
219/**
220 * Whether the lint selection lints a module as an oracle file: its name
221 * contains `oracle`, and it is not an `oracle-` machinery module, which no
222 * lint reads.
223 */
224function lintedOnItsOwn(file) {
225 const name = basename(file)
226 return name.includes(`oracle`) && !name.startsWith(`oracle-`)
228​
229/**
230 * Whether a helper call reaches a part through the body its caller passes. The
231 * body is the argument at the position of the helper's body parameter. It
232 * reaches when it uses a part. A fast-check property (`.prop`) also reaches
233 * when one of its arbitraries generates values and its body reads the value,
234 * because then the body is a generated property. A wrapper that the helper
235 * writes around the body, and that uses a part itself, makes the test reach.
236 */
237function callerBodyReaches(node, helper, module) {
238 if (helper.wrapperReaches) return true
239 const body = curriedArguments(node, helper.level)[helper.index]
240 if (body === undefined) return false
241 if (module.nodeReaches(body)) return true
242 return (
243 helper.prop &&
244 isFunction(body) &&
245 generatesValues(node, module) &&
246 module.usesInput(body)
247 )
249​
250/**
251 * The arguments of one call in a curried call: level 0 is the call of the
252 * helper itself, and each later level is the call of the function before it
253 * returned.
254 */
255function curriedArguments(node, level) {
256 const calls = []
257 for (let call = node; call.type === `CallExpression`; call = call.callee) {
258 calls.unshift(call)
259 }
260 return calls[level]?.arguments ?? []
262​
263/**
264 * Whether an arbitrary generates values: a call that is not a constant, or a
265 * variable whose initializer is one. An identifier is followed to its definition.
266 */
267function generatedArbitrary(value, module) {
268 if (value?.type === `Identifier`) {
269 const definition = findVariable(module.scopeOf(value), value.name)?.defs[0]
270 return (
271 definition?.type === `Variable` &&
272 definition.node.init !== null &&
273 generatedArbitrary(definition.node.init, module)
274 )
275 }
276 return value?.type === `CallExpression` && !isConstant(value)
278​
279/** Whether a curried call's arguments include a non-constant arbitrary. */
280function generatesValues(node, module) {
281 for (
282 let inner = node.callee;
283 inner.type === `CallExpression`;
284 inner = inner.callee
285 ) {
286 for (const argument of inner.arguments) {
287 const values =
288 argument.type === `ArrayExpression` ? argument.elements : [argument]
289 if (values.some((value) => generatedArbitrary(value, module))) {
290 return true
291 }
292 }
293 }
294 return false
296​
297/** The test module that a relative import names, or undefined. */
298function resolveTestModule(fromFile, source, session) {
299 if (!source.startsWith(`.`)) return undefined
300 const base = resolve(dirname(fromFile), source)
301 const stem = base.replace(/\.(m?js|tsx?)$/, ``)
302 // A `.js` specifier names the TypeScript source when one exists, and
303 // otherwise the JavaScript module itself.
304 const file = [
305 `${stem}.ts`,
306 `${stem}.tsx`,
307 ...(/\.m?js$/.test(base) ? [base] : []),
308 `${base}/index.ts`,
309 ].find((candidate) => existsSync(candidate))
310 // Production declares no oracle part, so the rule does not parse it.
311 if (file === undefined || isProductionModule(file, session)) return undefined
312 return file
314​
315/**
316 * Whether a file is shipped source: under `src/` in a published package. A
317 * private package, such as an end-to-end suite, keeps its tests in `src/`.
318 */
319function isProductionModule(file, session) {
320 for (let directory = dirname(file); ; directory = dirname(directory)) {
321 const manifest = join(directory, `package.json`)
322 if (existsSync(manifest)) {
323 if (!session.published.has(directory)) {
324 const { private: isPrivate } = JSON.parse(
325 readFileSync(manifest, `utf8`),
326 )
327 session.published.set(directory, isPrivate !== true)
328 }
329 return (
330 session.published.get(directory) &&
331 relative(directory, file).split(sep)[0] === `src`
332 )
333 }
334 if (dirname(directory) === directory) return false
335 }
337​
338/** The name of an object property, whether its key is an identifier or a string. */
339function propertyName(property) {
340 if (property.computed) return stringValue(property.key)
341 return property.key.name ?? stringValue(property.key)
343​
344function inTypeQuery(identifier) {
345 for (let node = identifier.parent; node; node = node.parent) {
346 if (node.type === `TSTypeQuery`) return true
347 }
348 return false
350​
351/** ESLint sets `parent` on the file it lints; a module parsed here needs it too. */
352function setParents(node, parent) {
353 node.parent = parent
354 for (const [key, child] of Object.entries(node)) {
355 if (key === `parent`) continue
356 for (const item of Array.isArray(child) ? child : [child]) {
357 if (typeof item?.type === `string`) setParents(item, node)
358 }
359 }
361​
362/**
363 * The module that a file names, for this lint. A module that cannot be read or
364 * does not parse reaches nothing. Its own lint reports the error.
365 */
366function loadModule(file, session) {
367 if (!session.modules.has(file)) {
368 let parsed
369 try {
370 parsed = parseModule(file)
371 } catch {
372 parsed = undefined
373 }
374 const module =
375 parsed === undefined
376 ? undefined
377 : new OracleModule(file, parsed.ast, parsed.scopeManager, session)
378 session.modules.set(file, module)
379 }
380 return session.modules.get(file)
382​
383/** The parsed AST of a module, reused while its mtime and size are unchanged. */
384function parseModule(file) {
385 const { mtimeMs, size } = statSync(file)
386 const cached = parsedModules.get(file)
387 if (cached?.mtimeMs === mtimeMs && cached.size === size) return cached
388 const { ast, scopeManager } = parseForESLint(readFileSync(file, `utf8`), {
389 filePath: file,
390 jsx: file.endsWith(`.tsx`),
391 loc: true,
392 range: true,
393 sourceType: `module`,
394 })
395 setParents(ast, null)
396 const parsed = { mtimeMs, size, ast, scopeManager }
397 parsedModules.set(file, parsed)
398 return parsed
400​
401class OracleModule {
402 constructor(file, ast, scopeManager, session) {
403 this.file = file
404 this.scopeManager = scopeManager
405 this.session = session
406 this.reach = new Map()
407 // Reach of a binding seen from another module, which ignores parameters.
408 this.exportedReach = new Map()
409 // Reach of an exported name, by name.
410 this.exportReachCache = new Map()
411 // Resolved references in source order, so a node's references are one
412 // contiguous range.
413 this.references = scopeManager.scopes
414 .flatMap((scope) => scope.references)
415 // A type annotation runs nothing, so only value references reach.
416 // `typeof check` in a type names a value, and still runs nothing.
417 .filter(
418 (reference) =>
419 reference.resolved !== null &&
420 reference.isValueReference &&
421 !inTypeQuery(reference.identifier),
422 )
423 .sort((a, b) => a.identifier.range[0] - b.identifier.range[0])
424 this.resolvedAt = new Map(
425 this.references.map((reference) => [
426 reference.identifier,
427 reference.resolved,
428 ]),
429 )
430 // Start offsets of the generated properties in this module, in order.
431 this.properties = []
432 walk(ast, (node) => {
433 if (this.#isGeneratedProperty(node)) this.properties.push(node.range[0])
434 })
435 this.properties.sort((a, b) => a - b)
436 // Names that `typeModel` lists, with the string literal that names each.
437 this.typeModels = new Map()
438 this.declared = this.#declaredParts()
439 this.#resolveTypeModels(ast)
440 this.exported = new Map()
441 this.starSources = []
442 for (const statement of ast.body) this.#recordExports(statement)
443 }
444​
445 /** The variables that `declareOracle({ check, model })` names. */
446 #declaredParts() {
447 const declared = new Set()
448 for (const reference of this.references) {
449 const call = reference.identifier.parent
450 const definition = reference.resolved.defs[0]
451 if (
452 reference.identifier.name !== declarationHelper ||
453 call.type !== `CallExpression` ||
454 call.callee !== reference.identifier ||
455 definition?.type !== `ImportBinding` ||
456 !isOracleConfigSource(definition.parent.source.value)
457 ) {
458 continue
459 }
460 for (const property of this.#declarationProperties(call.arguments[0])) {
461 const value = property.value
462 const parts =
463 value?.type === `ArrayExpression` ? value.elements : [value]
464 if (propertyName(property) === `typeModel`) {
465 for (const part of parts) {
466 const name = stringValue(part)
467 if (name !== undefined) this.typeModels.set(name, part)
468 }
469 continue
470 }
471 for (const part of parts) {
472 const variable =
473 part?.type === `Identifier` ? this.resolvedAt.get(part) : undefined
474 if (variable !== undefined) declared.add(variable)
475 }
476 }
477 }
478 return declared
479 }
480​
481 /**
482 * The properties of a declaration object. A spread of a const object
483 * literal contributes that object's properties, as the type accepts it.
484 */
485 #declarationProperties(object, seen = new Set()) {
486 if (object?.type !== `ObjectExpression` || seen.has(object)) return []
487 seen.add(object)
488 return object.properties.flatMap((property) => {
489 if (property.type !== `SpreadElement`) return [property]
490 const definition =
491 property.argument.type === `Identifier`
492 ? this.resolvedAt.get(property.argument)?.defs[0]
493 : undefined
494 return definition?.type === `Variable` &&
495 definition.parent.kind === `const`
496 ? this.#declarationProperties(definition.node.init, seen)
497 : []
498 })
499 }
500​
501 #recordExports(statement) {
502 if (statement.type === `ExportDefaultDeclaration`) {
503 this.#recordDefaultExport(statement.declaration)
504 return
505 }
506 if (statement.type === `ExportAllDeclaration`) {
507 if (statement.exported === null) {
508 this.starSources.push(statement.source.value)
509 }
510 return
511 }
512 if (statement.type !== `ExportNamedDeclaration`) return
513 if (statement.declaration !== null) {
514 // A class declares its name twice: in the module and inside its own
515 // scope. The module binding is the one a declaration refers to.
516 const moduleScope = this.#moduleScope()
517 for (const variable of this.scopeManager.getDeclaredVariables(
518 statement.declaration,
519 )) {
520 if (variable.scope === moduleScope)
521 this.exported.set(variable.name, { variable })
522 }
523 return
524 }
525 for (const specifier of statement.specifiers) {
526 const exported = specifier.exported.name ?? specifier.exported.value
527 const local = specifier.local.name ?? specifier.local.value
528 if (statement.source !== null) {
529 this.exported.set(exported, {
530 source: statement.source.value,
531 imported: local,
532 })
533 } else {
534 const variable = findVariable(this.#moduleScope(), local)
535 if (variable !== undefined) this.exported.set(exported, { variable })
536 }
537 }
538 }
539​
540 /**
541 * `export default` names a module binding, declares a named function or
542 * class, or exports an expression, which reaches when its code does.
543 */
544 #recordDefaultExport(declaration) {
545 const moduleScope = this.#moduleScope()
546 const variable =
547 declaration.type === `Identifier`
548 ? findVariable(moduleScope, declaration.name)
549 : declaration.id
550 ? this.scopeManager
551 .getDeclaredVariables(declaration)
552 .find((declared) => declared.scope === moduleScope)
553 : undefined
554 this.exported.set(
555 `default`,
556 variable === undefined ? { node: declaration } : { variable },
557 )
558 }
559​
560 #moduleScope() {
561 return (
562 this.scopeManager.scopes.find((scope) => scope.type === `module`) ??
563 this.scopeManager.globalScope
564 )
565 }
566​
567 get declaresParts() {
568 return this.declared.size > 0 || this.typeModels.size > 0
569 }
570​
571 /**
572 * A type model is a type alias or interface in this module's scope, which
573 * a type-level test uses as its expected type. Record where each is used,
574 * and the names that name no such type.
575 */
576 #resolveTypeModels(ast) {
577 this.typeModelUses = []
578 this.unknownTypeModels = []
579 if (this.typeModels.size === 0) return
580 const defined = new Map()
581 for (const statement of ast.body) {
582 const declaration =
583 statement.type === `ExportNamedDeclaration`
584 ? statement.declaration
585 : statement
586 if (
587 declaration?.type === `TSTypeAliasDeclaration` ||
588 declaration?.type === `TSInterfaceDeclaration`
589 ) {
590 defined.set(declaration.id.name, declaration)
591 }
592 }
593 for (const [name, literal] of this.typeModels) {
594 if (!defined.has(name)) this.unknownTypeModels.push(literal)
595 }
596 // A type built from a model, such as `PublishedValueFor<Variant>` under
597 // another name, predicts what the model predicts.
598 const models = new Set(
599 [...this.typeModels.keys()].filter((name) => defined.has(name)),
600 )
601 const namesModel = (node) => {
602 let found = false
603 walk(node, (child) => {
604 if (
605 child.type === `TSTypeReference` &&
606 child.typeName.type === `Identifier` &&
607 models.has(child.typeName.name)
608 ) {
609 found = true
610 }
611 })
612 return found
613 }
614 for (let grew = true; grew;) {
615 grew = false
616 for (const [name, declaration] of defined) {
617 if (!models.has(name) && namesModel(declaration)) {
618 models.add(name)
619 grew = true
620 }
621 }
622 }
623 walk(ast, (node) => {
624 if (
625 node.type === `TSTypeReference` &&
626 node.typeName.type === `Identifier` &&
627 models.has(node.typeName.name)
628 ) {
629 this.typeModelUses.push(node.range[0])
630 }
631 })
632 this.typeModelUses.sort((a, b) => a - b)
633 }
634​
635 /**
636 * Whether a binding is a declared part, or uses one. Seen from another
637 * module (`local` false), a parameter reaches nothing: the importer passes
638 * its own arguments, so this module's call sites say nothing about it.
639 */
640 variableReaches(variable, local = true) {
641 if (variable === undefined) return false
642 if (this.declared.has(variable)) return true
643 return this.session.search.solve(
644 local ? this.reach : this.exportedReach,
645 variable,
646 () =>
647 variable.defs.some((definition) =>
648 this.#definitionReaches(definition, local),
649 ) ||
650 this.#assignedValueReaches(variable, local) ||
651 (local && this.#fedByReachingValue(variable, local)),
652 )
653 }
654​
655 /**
656 * A binding that code assigns after its declaration, such as a `let` that a
657 * hook sets, holds the value assigned to it. It reaches when one does.
658 */
659 #assignedValueReaches(variable, local) {
660 return variable.references.some(
661 (reference) =>
662 reference.isWrite() &&
663 !reference.init &&
664 reference.writeExpr != null &&
665 this.nodeReaches(reference.writeExpr, local),
666 )
667 }
668​
669 /**
670 * A collection that code fills with values from a declared part, such as a
671 * coverage Set that grammar-driven tests add the model's predictions to,
672 * carries those values. A test that reads it uses the part.
673 */
674 #fedByReachingValue(variable, local) {
675 return variable.references.some((reference) => {
676 const member = reference.identifier.parent
677 const call = member?.parent
678 return (
679 member?.type === `MemberExpression` &&
680 member.object === reference.identifier &&
681 !member.computed &&
682 accumulatorMethods.has(member.property.name) &&
683 call?.type === `CallExpression` &&
684 call.callee === member &&
685 call.arguments.some((argument) => this.nodeReaches(argument, local))
686 )
687 })
688 }
689​
690 #definitionReaches(definition, local) {
691 switch (definition.type) {
692 case `ImportBinding`: {
693 // A namespace import reaches through the member that each use names.
694 const target = importBindingTarget(definition)
695 return (
696 target !== undefined &&
697 this.#importReaches(target.source, target.name)
698 )
699 }
700 case `FunctionName`:
701 case `ClassName`:
702 return this.nodeReaches(definition.node, local)
703 case `Variable`: {
704 const loop = definition.parent.parent
705 if (loop?.type === `ForOfStatement` && loop.left === definition.parent)
706 return this.#everyElementReaches(loop.right, local)
707 return (
708 definition.node.init !== null &&
709 this.nodeReaches(definition.node.init, local)
710 )
711 }
712 case `Parameter`:
713 return local && this.#parameterReaches(definition)
714 default:
715 return false
716 }
717 }
718​
719 /**
720 * A parameter reaches a part when every call of its function passes an
721 * argument that reaches one, as when a helper registers the property that
722 * its caller passes in. A function that the file never calls by name
723 * passes nothing the rule can see.
724 */
725 #parameterReaches(definition) {
726 const index = definition.node.params.indexOf(definition.name)
727 const calls = this.#callsOf(definition)
728 return (
729 index >= 0 &&
730 calls.length > 0 &&
731 calls.every((call) => {
732 const argument = call.arguments[index]
733 return argument !== undefined && this.nodeReaches(argument)
734 })
735 )
736 }
737​
738 /** The calls, by name, of the function that declares a parameter. */
739 #callsOf(definition) {
740 const fn = definition.node
741 const binding =
742 fn.type === `FunctionDeclaration`
743 ? fn.id
744 : fn.parent.type === `VariableDeclarator`
745 ? fn.parent.id
746 : undefined
747 if (binding?.type !== `Identifier`) return []
748 const variable = this.scopeManager
749 .getDeclaredVariables(fn.type === `FunctionDeclaration` ? fn : fn.parent)
750 .find((declared) => declared.name === binding.name)
751 return (variable?.references ?? [])
752 .map((reference) => reference.identifier.parent)
753 .filter(
754 (call) =>
755 call.type === `CallExpression` &&
756 call.callee.type === `Identifier` &&
757 call.callee.name === binding.name,
758 )
759 }
760​
761 /**
762 * A `for...of` loop variable takes each element in turn, and a registration
763 * in the loop registers one test per element, so every element must reach.
764 * The rule reads an array written in the loop or bound to a const name.
765 */
766 #everyElementReaches(iterable, local) {
767 let array = iterable
768 if (array.type === `Identifier`) {
769 const definition = this.resolvedAt.get(array)?.defs[0]
770 array =
771 definition?.type === `Variable` && definition.parent.kind === `const`
772 ? definition.node.init
773 : undefined
774 }
775 return (
776 array?.type === `ArrayExpression` &&
777 array.elements.length > 0 &&
778 array.elements.every(
779 (element) =>
780 element !== null &&
781 element.type !== `SpreadElement` &&
782 this.nodeReaches(element, local),
783 )
784 )
785 }
786​
787 #importReaches(source, name) {
788 return importedModuleReaches(this.file, source, name, this.session)
789 }
790​
791 /** Whether an export of this module is a declared part, or uses one. */
792 exportReaches(name) {
793 return this.session.search.solve(this.exportReachCache, name, () => {
794 const entry = this.exported.get(name)
795 if (entry?.variable !== undefined)
796 return this.variableReaches(entry.variable, false)
797 if (entry?.node !== undefined) return this.nodeReaches(entry.node, false)
798 if (entry !== undefined)
799 return this.#importReaches(entry.source, entry.imported)
800 // `export *` does not carry a default export.
801 if (name === `default`) return false
802 return this.starSources.some((source) =>
803 this.#importReaches(source, name),
804 )
805 })
806 }
807​
808 /**
809 * How an export of this module registers tests, or undefined when it
810 * registers none. A function registers the body that it writes ('own') or
811 * the body that its caller passes ('parameter'). A cycle of re-exports
812 * registers nothing.
813 */
814 registrationShape(name, visiting = new Set()) {
815 const key = `${this.file}\0${name}`
816 if (visiting.has(key)) return undefined
817 visiting.add(key)
818 const entry = this.exported.get(name)
819 if (entry?.variable !== undefined) {
820 const definition = entry.variable.defs[0]
821 const fn =
822 definition?.type === `FunctionName`
823 ? definition.node
824 : definition?.type === `Variable` && isFunction(definition.node.init)
825 ? definition.node.init
826 : undefined
827 return fn === undefined ? undefined : this.#bodyShape(fn)
828 }
829 if (entry?.node !== undefined) {
830 return isFunction(entry.node) ? this.#bodyShape(entry.node) : undefined
831 }
832 if (entry !== undefined) {
833 return importedRegisters(
834 this.file,
835 entry.source,
836 entry.imported,
837 this.session,
838 visiting,
839 )
840 }
841 if (name === `default`) return undefined
842 for (const source of this.starSources) {
843 const shape = importedRegisters(
844 this.file,
845 source,
846 name,
847 this.session,
848 visiting,
849 )
850 if (shape !== undefined) return shape
851 }
852 return undefined
853 }
854​
855 /**
856 * The shape of the registrations in a function's body. A registration
857 * registers the caller's body when its body is a parameter of the function,
858 * or of a function that it returns, or when its body is a wrapper written
859 * here that calls such a parameter. The shape records where the caller
860 * passes that body, and whether the wrapper uses a part itself. Any other
861 * registration registers a body that the function writes, which wins.
862 */
863 #bodyShape(fn) {
864 const sourceCode = { getScope: (node) => this.scopeOf(node) }
865 let shape
866 walk(fn, (node) => {
867 if (node.type !== `CallExpression`) return
868 const test = registeredTest(node, sourceCode)
869 if (test === undefined) return
870 const position = this.#passedBody(test.body, fn, sourceCode)
871 if (position === undefined) shape = { kind: `own` }
872 else if (shape?.kind !== `own`) {
873 shape = {
874 kind: `parameter`,
875 ...position,
876 prop: calleeCall(node.callee, `prop`) !== undefined,
877 // Seen from the caller, the helper's parameters reach nothing.
878 wrapperReaches:
879 isFunction(test.body) && this.nodeReaches(test.body, false),
880 }
881 }
882 })
883 return shape
884 }
885​
886 /**
887 * Where a registration's body comes from, when its caller passes it: the
888 * body is a parameter of `fn` or of a function inside `fn`, or a wrapper
889 * that calls one. The position is `{ index, level }`: the parameter's index,
890 * and the number of functions from `fn` to the one that declares it.
891 */
892 #passedBody(body, fn, sourceCode) {
893 const positionOf = (identifier) => {
894 const definition = findVariable(
895 sourceCode.getScope(identifier),
896 identifier.name,
897 )?.defs[0]
898 if (definition?.type !== `Parameter`) return undefined
899 const owner = definition.node
900 let level = 0
901 for (let node = owner; node !== fn; node = node.parent) {
902 // A parameter of the wrapper itself, or of a function outside `fn`.
903 if (node === null || node === body) return undefined
904 if (isFunction(node)) level++
905 }
906 return { index: owner.params.indexOf(definition.name), level }
907 }
908 if (body.type === `Identifier`) return positionOf(body)
909 if (!isFunction(body)) return undefined
910 let position
911 walk(body, (node) => {
912 if (
913 position === undefined &&
914 node.type === `CallExpression` &&
915 node.callee.type === `Identifier`
916 ) {
917 position = positionOf(node.callee)
918 }
919 })
920 return position
921 }
922​
923 /** The innermost scope of a node, as ESLint's `getScope` finds it. */
924 scopeOf(node) {
925 for (let current = node; current; current = current.parent) {
926 const scope = this.scopeManager.acquire(current, true)
927 if (scope) return scope
928 }
929 return this.scopeManager.globalScope
930 }
931​
932 /**
933 * A generated property: `fc.property(...)` or `fc.asyncProperty(...)` from
934 * fast-check, or a `.prop([...])` registration. Its predicate states a law
935 * over inputs that nobody wrote down, so it is its own check. A property
936 * whose arbitraries are all constants checks one written input, so it does
937 * not count.
938 */
939 #isGeneratedProperty(node) {
940 if (node.type !== `CallExpression`) return false
941 const { callee } = node
942 if (callee.type !== `MemberExpression` || callee.computed) return false
943 const name = callee.property.name
944 if (name !== `property` && name !== `asyncProperty`) return false
945 if (!this.#isFastCheck(callee.object)) return false
946 const predicate = node.arguments.at(-1)
947 return (
948 node.arguments
949 .slice(0, -1)
950 .some((value) => !this.#constantArbitrary(value)) &&
951 this.#predicateUsesInput(predicate)
952 )
953 }
954​
955 /**
956 * `fc.constant(x)` or `fc.constantFrom(...)`, written here or bound to a
957 * const name. An arbitrary from elsewhere cannot be seen, so it is not one.
958 */
959 #constantArbitrary(value, seen = new Set()) {
960 if (value?.type !== `Identifier`) return isConstant(value)
961 const definition = this.resolvedAt.get(value)?.defs[0]
962 if (
963 definition?.type !== `Variable` ||
964 definition.parent.kind !== `const` ||
965 seen.has(definition.node)
966 ) {
967 return false
968 }
969 seen.add(definition.node)
970 return this.#constantArbitrary(definition.node.init, seen)
971 }
972​
973 /**
974 * Whether a property's predicate reads its input. A named predicate is read
975 * at its definition. One passed in as a parameter cannot be seen here, so
976 * it counts.
977 */
978 #predicateUsesInput(predicate) {
979 if (predicate?.type !== `Identifier`) return this.usesInput(predicate)
980 const definition = this.resolvedAt.get(predicate)?.defs[0]
981 if (definition?.type === `FunctionName`)
982 return this.usesInput(definition.node)
983 if (definition?.type === `Variable`)
984 return this.usesInput(definition.node.init)
985 if (definition?.type === `ImportBinding`)
986 return this.#importedFunctionUsesInput(definition) ?? true
987 return true
988 }
989​
990 /**
991 * Whether an imported function reads a parameter, read at its definition.
992 * Undefined when the rule cannot load the function, as for a package.
993 */
994 #importedFunctionUsesInput(definition) {
995 const target = importBindingTarget(definition)
996 const file =
997 target === undefined
998 ? undefined
999 : resolveTestModule(this.file, target.source, this.session)
1000 const module =
1001 file === undefined ? undefined : loadModule(file, this.session)
1002 return module?.exportedFunctionUsesInput(target.name)
1004​
1005 /** Whether an export is a function that reads a parameter; undefined if it is not one. */
1006 exportedFunctionUsesInput(name) {
1007 const definition = this.exported.get(name)?.variable?.defs[0]
1008 if (definition?.type === `FunctionName`)
1009 return this.usesInput(definition.node)
1010 if (definition?.type === `Variable`)
1011 return this.usesInput(definition.node.init)
1012 return undefined
1014​
1015 /** A function that reads at least one of its parameters. */
1016 usesInput(fn) {
1017 if (!isFunction(fn) && fn?.type !== `FunctionDeclaration`) return false
1018 return this.scopeManager
1019 .getDeclaredVariables(fn)
1020 .some(
1021 (variable) =>
1022 variable.defs[0]?.type === `Parameter` &&
1023 variable.references.length > 0,
1026​
1027 /**
1028 * Whether a `.prop([...])` registration runs a generated property: some
1029 * arbitrary is not a constant, and the test reads its input. A named test
1030 * is checked at its definition, and a test passed in as a parameter at
1031 * every call of its helper.
1032 */
1033 propRegistrationGenerates(registration, body, sourceCode) {
1034 const prop = calleeCall(registration.callee, `prop`)
1035 if (prop === undefined) return false
1036 const [arbitraries] = prop.arguments
1037 const values =
1038 arbitraries?.type === `ArrayExpression`
1039 ? arbitraries.elements
1040 : arbitraries?.type === `ObjectExpression`
1041 ? arbitraries.properties.map((property) => property.value)
1042 : undefined
1043 // Arbitraries that a caller passes in are not visible here, so only
1044 // written-out constants disqualify the registration.
1045 if (values?.every((value) => this.#constantArbitrary(value))) return false
1046 if (isFunction(body)) return this.usesInput(body)
1047 const definition = findVariable(sourceCode.getScope(body), body.name)
1048 ?.defs[0]
1049 // A named predicate: a function declaration or a const bound to one.
1050 if (definition?.type === `FunctionName`)
1051 return this.usesInput(definition.node)
1052 if (definition?.type === `Variable`)
1053 return this.usesInput(definition.node.init)
1054 if (definition?.type === `ImportBinding`)
1055 return this.#importedFunctionUsesInput(definition) ?? true
1056 if (definition?.type !== `Parameter`) return false
1057 const calls = this.#callsOf(definition)
1058 return (
1059 calls.length > 0 &&
1060 calls.every((call) => {
1061 const index = definition.node.params.indexOf(definition.name)
1062 return this.usesInput(call.arguments[index])
1063 })
1066​
1067 #isFastCheck(node) {
1068 const definition =
1069 node.type === `Identifier`
1070 ? this.resolvedAt.get(node)?.defs[0]
1071 : undefined
1072 return (
1073 definition?.type === `ImportBinding` &&
1074 fastCheckModules.has(definition.parent.source.value)
1077​
1078 /** Whether code uses a declared part, directly or through a binding. */
1079 nodeReaches(node, local = true) {
1080 // Code that runs a generated property that it contains.
1081 if (containsOffset(this.properties, node)) return true
1082 // A type-level test reaches a type model by naming it in a type.
1083 if (containsOffset(this.typeModelUses, node)) return true
1084 const [start, end] = node.range
1085 let low = 0
1086 let high = this.references.length
1087 while (low < high) {
1088 const middle = (low + high) >> 1
1089 if (this.references[middle].identifier.range[0] < start) low = middle + 1
1090 else high = middle
1092 for (let index = low; index < this.references.length; index++) {
1093 const reference = this.references[index]
1094 if (reference.identifier.range[0] >= end) break
1095 if (this.#referenceReaches(reference, local)) return true
1097 return false
1099​
1100 /** A use of a namespace member, such as `model.step`, reaches through that export. */
1101 #referenceReaches(reference, local) {
1102 const member = reference.identifier.parent
1103 const definition = reference.resolved.defs[0]
1104 if (
1105 definition?.type === `ImportBinding` &&
1106 definition.node.type === `ImportNamespaceSpecifier` &&
1107 member?.type === `MemberExpression` &&
1108 member.object === reference.identifier &&
1109 !member.computed
1110 ) {
1111 return this.#importReaches(
1112 definition.parent.source.value,
1113 member.property.name,
1116 return this.variableReaches(reference.resolved, local)
1119​
1120const fastCheckModules = new Set([`fast-check`, `@fast-check/vitest`])
1121​
1122// Methods that put a value into a collection.
1123const accumulatorMethods = new Set([`add`, `set`, `push`, `unshift`])
1124​
1125/** `fc.constant(x)` or `fc.constantFrom(...)`: an arbitrary of written values. */
1126function isConstant(node) {
1127 return (
1128 node?.type === `CallExpression` &&
1129 node.callee.type === `MemberExpression` &&
1130 !node.callee.computed &&
1131 [`constant`, `constantFrom`].includes(node.callee.property.name)
1134​
1135/** The value of a string literal or of a template with no substitutions. */
1136function stringValue(node) {
1137 if (node?.type === `Literal` && typeof node.value === `string`)
1138 return node.value
1139 if (node?.type === `TemplateLiteral` && node.expressions.length === 0)
1140 return node.quasis[0].value.cooked
1141 return undefined
1143​
1144/** Whether a sorted list of start offsets has one inside a node. */
1145function containsOffset(offsets, node) {
1146 const [start, end] = node.range
1147 let low = 0
1148 let high = offsets.length
1149 while (low < high) {
1150 const middle = (low + high) >> 1
1151 if (offsets[middle] < start) low = middle + 1
1152 else high = middle
1154 return low < offsets.length && offsets[low] < end
1156​
1157function walk(node, visit) {
1158 visit(node)
1159 for (const [key, child] of Object.entries(node)) {
1160 if (key === `parent`) continue
1161 for (const item of Array.isArray(child) ? child : [child]) {
1162 if (typeof item?.type === `string`) walk(item, visit)
1166​
1167/** The `.<name>(...)` call in a registration's callee chain, if any. */
1168function calleeCall(callee, name) {
1169 for (let node = callee; node;) {
1170 if (
1171 node.type === `CallExpression` &&
1172 node.callee.type === `MemberExpression` &&
1173 !node.callee.computed &&
1174 node.callee.property.name === name
1175 ) {
1176 return node
1178 node =
1179 node.type === `CallExpression`
1180 ? node.callee
1181 : node.type === `MemberExpression`
1182 ? node.object
1183 : undefined
1185 return undefined
1187​
1188/** Whether a function written in an `.each(...)` table uses a declared part. */
1189function tableFunctionReaches(module, table) {
1190 let reaches = false
1191 for (const row of table.arguments) {
1192 walk(row, (node) => {
1193 if (!reaches && isFunction(node) && module.nodeReaches(node)) {
1194 reaches = true
1196 })
1198 return reaches
1200​
1201function isPlaceholder(body) {
1202 return (
1203 isFunction(body) &&
1204 body.body.type === `BlockStatement` &&
1205 body.body.body.length === 0
1208​
1209/**
1210 * The test module that a relative specifier names in `fromFile`, as this rule
1211 * resolves it: undefined for production source, a package, or a missing file.
1212 * The lint selection in scripts/agent-lint-feedback.mjs follows these edges, so
1213 * an edit reaches the oracle files that this rule reads.
1214 */
1215const selectionSession = new LintSession()
1216export function resolveImportedTestModule(fromFile, specifier) {
1217 return resolveTestModule(fromFile, specifier, selectionSession)
1219​
1220export default {
1221 meta: {
1222 type: `problem`,
1223 docs: {
1224 description: `Report tests in oracle files that reach no declared check or model.`,
1225 },
1226 schema: [],
1227 messages: {
1228 unitTest: `This test reaches no part that this file declares with declareOracle, so its expected result has no independent source. A unit test belongs in an ordinary test file: move it there. A fixed history runs through the declared check, a model pin uses the declared model, and a grammar calibration uses the declared grammar.`,
1229 unknownTypeModel: `This typeModel name is not a type alias or interface in this file. A type model is the expected type that type-level tests compare with, so it must be declared here.`,
1230 importedRegistration: `This oracle file calls a helper that registers tests. An oracle file registers only oracle tests, so register those tests from an ordinary test file and keep this file to its checks and model.`,
1231 undeclared: `This oracle file registers tests and declares no oracle part. Name its check, model, and grammar with \`declareOracle({ check: [...], model: [...], grammar: [...] })\` from oracle-declaration. Then move each test that reaches none of them to an ordinary test file.`,
1232 },
1233 },
1234 create(context) {
1235 // `oracle-config`, `oracle-reach`, and the other `oracle-` modules are the
1236 // shared oracle machinery. Their tests check that machinery, not a law.
1237 if (basename(context.filename).startsWith(`oracle-`)) return {}
1238 const { sourceCode } = context
1239 const session = new LintSession()
1240 const module = new OracleModule(
1241 context.filename,
1242 sourceCode.ast,
1243 sourceCode.scopeManager,
1244 session,
1246 const unreached = []
1247 let anyReached = false
1248 return {
1249 CallExpression(node) {
1250 // A curried callee is not a call of its own: the outermost call is the
1251 // registration.
1252 const outermost = !(
1253 node.parent.type === `CallExpression` && node.parent.callee === node
1255 const helper = outermost
1256 ? importedHelperShape(node, context.filename, sourceCode, session)
1257 : undefined
1258 if (helper?.kind === `own`) {
1259 context.report({ node, messageId: `importedRegistration` })
1261 if (helper?.kind === `parameter`) {
1262 // The helper registers the body its caller passes, so the caller's
1263 // body is the test, judged here as a local parameter registration is.
1264 if (callerBodyReaches(node, helper, module)) anyReached = true
1265 else unreached.push(node)
1266 return
1268 const test = registeredTest(node, sourceCode)
1269 if (test === undefined || isPlaceholder(test.body)) return
1270 // An `.each(table)` row can carry a function that the test body calls,
1271 // such as a hostile observation each check must reject. A function in
1272 // the table that uses a declared part makes the test use it. Plain
1273 // data, such as the grammar's cells, does not: the body must use them.
1274 const table =
1275 calleeCall(node.callee, `each`) ?? calleeCall(node.callee, `for`)
1276 const reaches =
1277 module.propRegistrationGenerates(node, test.body, sourceCode) ||
1278 (table !== undefined && tableFunctionReaches(module, table)) ||
1279 (test.body.type === `Identifier`
1280 ? module.variableReaches(
1281 findVariable(sourceCode.getScope(test.body), test.body.name),
1283 : module.nodeReaches(test.body))
1284 if (reaches) anyReached = true
1285 else unreached.push(node)
1286 },
1287 'Program:exit'() {
1288 for (const node of module.unknownTypeModels) {
1289 context.report({ node, messageId: `unknownTypeModel` })
1291 // A file that relies on a companion module's declaration declares
1292 // nothing itself. It is undeclared only when no test reaches a part.
1293 if (!module.declaresParts && !anyReached) {
1294 if (unreached.length > 0) {
1295 context.report({ node: unreached[0], messageId: `undeclared` })
1297 return
1299 for (const node of unreached) {
1300 context.report({ node, messageId: `unitTest` })
1302 },
1304 },