From 0ece71bee720c4b343a5cf98098ec74f2ad6346c Mon Sep 17 00:00:00 2001 From: iHiD <286476+iHiD@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:36:07 +0900 Subject: [PATCH] Find the tests in the test file with acorn, without loading TypeScript The reporter parsed the test file with @exercism/static-analysis, which uses @typescript-eslint/typescript-estree and so loads the whole TypeScript compiler on every run. Test files are plain JavaScript, so acorn reads them as well. On all 180 spec files in the track and the fixtures, the new code finds the same tests, names, task IDs, code and locations. Co-authored-by: iHiD <286476+iHiD@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- pnpm-lock.yaml | 140 +---------------------------------- src/output.ts | 50 ++++--------- src/tests.ts | 197 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 217 insertions(+), 174 deletions(-) create mode 100644 src/tests.ts diff --git a/package.json b/package.json index 0c3ee3d..81a9948 100644 --- a/package.json +++ b/package.json @@ -28,13 +28,11 @@ }, "dependencies": { "@exercism/babel-preset-javascript": "^0.7.0", - "@exercism/static-analysis": "^0.14.0", "@jest/console": "^30.4.0", "@jest/reporters": "^30.4.0", "@jest/test-result": "^30.4.0", "@jest/types": "^30.4.0", - "@typescript-eslint/typescript-estree": "^8.37.0", - "@typescript-eslint/visitor-keys": "^8.37.0", + "acorn": "^8.15.0", "babel-jest": "^30.4.0", "chalk": "^6.0.0", "core-js": "^3.44.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b91f1a2..9ec1202 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,9 +11,6 @@ importers: '@exercism/babel-preset-javascript': specifier: ^0.7.0 version: 0.7.0 - '@exercism/static-analysis': - specifier: ^0.14.0 - version: 0.14.0(@typescript-eslint/typescript-estree@8.63.0(typescript@5.7.3))(@typescript-eslint/visitor-keys@8.72.1) '@jest/console': specifier: ^30.4.0 version: 30.5.2 @@ -26,12 +23,9 @@ importers: '@jest/types': specifier: ^30.4.0 version: 30.5.1 - '@typescript-eslint/typescript-estree': - specifier: ^8.37.0 - version: 8.63.0(typescript@5.7.3) - '@typescript-eslint/visitor-keys': - specifier: ^8.37.0 - version: 8.72.1 + acorn: + specifier: ^8.15.0 + version: 8.15.0 babel-jest: specifier: ^30.4.0 version: 30.5.2(@babel/core@7.29.7) @@ -781,12 +775,6 @@ packages: eslint: '>= 9.28' typescript: ~5.7.3 - '@exercism/static-analysis@0.14.0': - resolution: {integrity: sha512-ZqaT7PBAolrejONdsmiE+YgQ1GmTjuGtIIquk69CowwNBaiBsy6VMg9hXOJNEk3ELUxKDT8IBQzdmtEk7PqgOA==} - peerDependencies: - '@typescript-eslint/typescript-estree': ^8.0.1 - '@typescript-eslint/visitor-keys': ^8.0.1 - '@humanfs/core@0.19.1': resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} engines: {node: '>=18.18.0'} @@ -1120,12 +1108,6 @@ packages: peerDependencies: typescript: '>=4.8.4 <5.9.0' - '@typescript-eslint/project-service@8.63.0': - resolution: {integrity: sha512-e5dh0/UI0ok53AlZ5wRkXCB32z/f2jUZqPR/ygAw5WYaSw8j9EoJWlS7wQjr/dmOaqWjnPIn2m+HhVPCMWGZVQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/scope-manager@8.0.1': resolution: {integrity: sha512-NpixInP5dm7uukMiRyiHjRKkom5RIFA4dfiHvalanD2cF0CLUuQqxfg8PtEUo9yqJI2bBhF+pcSafqnG3UBnRQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1140,12 +1122,6 @@ packages: peerDependencies: typescript: '>=4.8.4 <5.9.0' - '@typescript-eslint/tsconfig-utils@8.63.0': - resolution: {integrity: sha512-sUAbkulqBAsncKnbRP3+7CtQFRKicexnj7ZwNC6ddCR7EmrXvjvdCYMJbUIqMd6lwoEriZjwLo08aS5tSjVMHg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/type-utils@8.37.0': resolution: {integrity: sha512-SPkXWIkVZxhgwSwVq9rqj/4VFo7MnWwVaRNznfQDc/xPYHjXnPfLWn+4L6FF1cAz6e7dsqBeMawgl7QjUMj4Ow==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1161,14 +1137,6 @@ packages: resolution: {integrity: sha512-ax0nv7PUF9NOVPs+lmQ7yIE7IQmAf8LGcXbMvHX5Gm+YJUYNAl340XkGnrimxZ0elXyoQJuN5sbg6C4evKA4SQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/types@8.63.0': - resolution: {integrity: sha512-xyLtl9DUBBFrcJS4x2pIqGLH68/tC2uOa4Z7pUteW09D3bXnnXUom4dyPikzWgB7llmIc1zoeI3aoUdC4rPK/Q==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/types@8.72.1': - resolution: {integrity: sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/typescript-estree@8.0.1': resolution: {integrity: sha512-8V9hriRvZQXPWU3bbiUV4Epo7EvgM6RTs+sUmxp5G//dBGy402S7Fx0W0QkB2fb4obCF8SInoUzvTYtc3bkb5w==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1184,12 +1152,6 @@ packages: peerDependencies: typescript: '>=4.8.4 <5.9.0' - '@typescript-eslint/typescript-estree@8.63.0': - resolution: {integrity: sha512-ygBkU+B7ex5UI/gKhaqexWev79uISfIv7XQCRNYO/jmD8rGLPyWLAb3KMRT6nd8Gt9bmUBi9+iX6tBdYfOY81Q==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - '@typescript-eslint/utils@8.0.1': resolution: {integrity: sha512-CBFR0G0sCt0+fzfnKaciu9IBsKvEKYwN9UZ+eeogK1fYHg4Qxk1yf/wLQkLXlq8wbU2dFlgAesxt8Gi76E8RTA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1211,14 +1173,6 @@ packages: resolution: {integrity: sha512-YzfhzcTnZVPiLfP/oeKtDp2evwvHLMe0LOy7oe+hb9KKIumLNohYS9Hgp1ifwpu42YWxhZE8yieggz6JpqO/1w==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/visitor-keys@8.63.0': - resolution: {integrity: sha512-UexrHGnGTpbuQHct2ExOc2ZcFbGUS9FOesCxxqdBGcpI1BxYu/LZ6U8Aq6/72XtF/qRBk9nhuGHFJIXXMhPMdw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/visitor-keys@8.72.1': - resolution: {integrity: sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@ungap/structured-clone@1.4.0': resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==} @@ -1460,10 +1414,6 @@ packages: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} - brace-expansion@5.0.7: - resolution: {integrity: sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==} - engines: {node: 18 || 20 || >=22} - braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} @@ -1744,10 +1694,6 @@ packages: resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - eslint-visitor-keys@5.0.1: - resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - eslint@9.31.0: resolution: {integrity: sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2428,10 +2374,6 @@ packages: resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} engines: {node: '>=6'} - minimatch@10.2.5: - resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} - engines: {node: 18 || 20 || >=22} - minimatch@10.2.6: resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} engines: {node: 18 || 20 || >=22} @@ -2580,10 +2522,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.5: - resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -2865,10 +2803,6 @@ packages: resolution: {integrity: sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==} engines: {node: '>=18'} - tinyglobby@0.2.17: - resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} - engines: {node: '>=12.0.0'} - to-regex-range@5.0.1: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} @@ -3943,11 +3877,6 @@ snapshots: - jest - supports-color - '@exercism/static-analysis@0.14.0(@typescript-eslint/typescript-estree@8.63.0(typescript@5.7.3))(@typescript-eslint/visitor-keys@8.72.1)': - dependencies: - '@typescript-eslint/typescript-estree': 8.63.0(typescript@5.7.3) - '@typescript-eslint/visitor-keys': 8.72.1 - '@humanfs/core@0.19.1': {} '@humanfs/node@0.16.6': @@ -4425,15 +4354,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.63.0(typescript@5.7.3)': - dependencies: - '@typescript-eslint/tsconfig-utils': 8.63.0(typescript@5.7.3) - '@typescript-eslint/types': 8.63.0 - debug: 4.4.3 - typescript: 5.7.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/scope-manager@8.0.1': dependencies: '@typescript-eslint/types': 8.0.1 @@ -4448,10 +4368,6 @@ snapshots: dependencies: typescript: 5.7.3 - '@typescript-eslint/tsconfig-utils@8.63.0(typescript@5.7.3)': - dependencies: - typescript: 5.7.3 - '@typescript-eslint/type-utils@8.37.0(eslint@9.31.0)(typescript@5.7.3)': dependencies: '@typescript-eslint/types': 8.37.0 @@ -4468,10 +4384,6 @@ snapshots: '@typescript-eslint/types@8.37.0': {} - '@typescript-eslint/types@8.63.0': {} - - '@typescript-eslint/types@8.72.1': {} - '@typescript-eslint/typescript-estree@8.0.1(typescript@5.7.3)': dependencies: '@typescript-eslint/types': 8.0.1 @@ -4503,21 +4415,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/typescript-estree@8.63.0(typescript@5.7.3)': - dependencies: - '@typescript-eslint/project-service': 8.63.0(typescript@5.7.3) - '@typescript-eslint/tsconfig-utils': 8.63.0(typescript@5.7.3) - '@typescript-eslint/types': 8.63.0 - '@typescript-eslint/visitor-keys': 8.63.0 - debug: 4.4.3 - minimatch: 10.2.5 - semver: 7.8.5 - tinyglobby: 0.2.17 - ts-api-utils: 2.5.0(typescript@5.7.3) - typescript: 5.7.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/utils@8.0.1(eslint@9.31.0)(typescript@5.7.3)': dependencies: '@eslint-community/eslint-utils': 4.4.0(eslint@9.31.0) @@ -4550,16 +4447,6 @@ snapshots: '@typescript-eslint/types': 8.37.0 eslint-visitor-keys: 4.2.1 - '@typescript-eslint/visitor-keys@8.63.0': - dependencies: - '@typescript-eslint/types': 8.63.0 - eslint-visitor-keys: 5.0.1 - - '@typescript-eslint/visitor-keys@8.72.1': - dependencies: - '@typescript-eslint/types': 8.72.1 - eslint-visitor-keys: 5.0.1 - '@ungap/structured-clone@1.4.0': {} '@unrs/resolver-binding-android-arm-eabi@1.13.0': @@ -4794,10 +4681,6 @@ snapshots: dependencies: balanced-match: 4.0.4 - brace-expansion@5.0.7: - dependencies: - balanced-match: 4.0.4 - braces@3.0.3: dependencies: fill-range: 7.1.1 @@ -5096,8 +4979,6 @@ snapshots: eslint-visitor-keys@4.2.1: {} - eslint-visitor-keys@5.0.1: {} - eslint@9.31.0: dependencies: '@eslint-community/eslint-utils': 4.4.0(eslint@9.31.0) @@ -5212,10 +5093,6 @@ snapshots: dependencies: bser: 2.1.2 - fdir@6.5.0(picomatch@4.0.5): - optionalDependencies: - picomatch: 4.0.5 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6064,10 +5941,6 @@ snapshots: mimic-fn@2.1.0: {} - minimatch@10.2.5: - dependencies: - brace-expansion: 5.0.7 - minimatch@10.2.6: dependencies: brace-expansion: 5.0.12 @@ -6209,8 +6082,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.5: {} - picomatch@4.0.7: {} pify@4.0.1: {} @@ -6515,11 +6386,6 @@ snapshots: glob: 10.5.0 minimatch: 10.2.6 - tinyglobby@0.2.17: - dependencies: - fdir: 6.5.0(picomatch@4.0.5) - picomatch: 4.0.5 - to-regex-range@5.0.1: dependencies: is-number: 7.0.0 diff --git a/src/output.ts b/src/output.ts index 6ec9fb8..8ecf069 100644 --- a/src/output.ts +++ b/src/output.ts @@ -1,6 +1,4 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { AstParser, extractTests } from '@exercism/static-analysis' -import type { ExtractedTestCase, ParsedSource } from '@exercism/static-analysis' import type { ConsoleBuffer } from '@jest/console' import type { AggregatedResult, @@ -10,6 +8,8 @@ import type { import type { Config } from '@jest/types' import fs from 'fs' import path from 'path' +import { parseTests } from './tests' +import type { ParsedTests, TestCase } from './tests' interface OutputInterface { status: 'fail' | 'pass' | 'error' @@ -42,8 +42,7 @@ export class Output { Pick private readonly globalConfig: Config.GlobalConfig private readonly outputFile: string - private readonly sources: Record - private readonly tests: Record> + private readonly sources: Record private readonly config: null | ExerciseConfig constructor(globalConfig: Config.GlobalConfig) { @@ -54,7 +53,6 @@ export class Output { this.config = findConfig(path.dirname(this.outputFile)) this.sources = {} - this.tests = {} } public error(message: string): void { @@ -130,9 +128,8 @@ export class Output { const parsedSources: Record< string, { - program: ParsedSource['program'] - source: ParsedSource['source'] - tests: Record + source: string + tests: Record } > = {} @@ -142,22 +139,15 @@ export class Output { .filter((path, index, self) => self.indexOf(path) === index) .forEach((file) => { try { - const [{ program, source }] = AstParser.ANALYZER.parseSync( - fs.readFileSync(file).toString() - ) - const tests = extractTests(program) + const { source, tests } = parseTests(fs.readFileSync(file).toString()) parsedSources[file] = { - program, source, - tests: tests.reduce>( - (results, item) => { - results[item.name(' > ')] = item - results[item.name(' ' as ' > ')] = item - return results - }, - {} - ), + tests: tests.reduce>((results, item) => { + results[item.name(' > ')] = item + results[item.name(' ' as ' > ')] = item + return results + }, {}), } } catch (err: unknown) { console.error( @@ -238,22 +228,14 @@ export class Output { }) } - private getSource(specFilePath: string): { - source: ParsedSource - tests: ExtractedTestCase[] - } { + private getSource(specFilePath: string): ParsedTests { if (!this.sources[specFilePath]) { - const [{ program, source }] = AstParser.ANALYZER.parseSync( + this.sources[specFilePath] = parseTests( fs.readFileSync(specFilePath).toString() ) - this.tests[specFilePath] = extractTests(program) - this.sources[specFilePath] = { program, source } } - return { - source: this.sources[specFilePath], - tests: this.tests[specFilePath], - } + return this.sources[specFilePath] } public testInnerFinished( @@ -302,7 +284,7 @@ export class Output { function buildOutput( specFilePath: string, buffer: ConsoleBuffer, - { tests }: { source: ParsedSource; tests: ExtractedTestCase[] } + { tests }: ParsedTests ): Record { const outputs = buffer.reduce>((outputs, entry) => { // The origin stack trace will look something like this: @@ -320,7 +302,7 @@ function buildOutput( // ... // }) - let foundTest: ExtractedTestCase | undefined + let foundTest: TestCase | undefined // Using find because it will break when something is found! entry.origin.split('\n').find((originLine) => { if (!originLine.includes(specFilePath)) { diff --git a/src/tests.ts b/src/tests.ts new file mode 100644 index 0000000..dd01706 --- /dev/null +++ b/src/tests.ts @@ -0,0 +1,197 @@ +// Finds the tests in a test file, so the reporter can show each test's code +// and work out which test printed each console message. +// +// This used to be done by @exercism/static-analysis, which parses with +// @typescript-eslint/typescript-estree. That package loads the whole +// TypeScript compiler (about 9 MB of JavaScript) on every run, which took +// about a quarter of each run. Test files are plain JavaScript, so acorn, a +// small JavaScript parser, can read them in a fraction of the time. +import { parse } from 'acorn' +import type { + AnyNode, + ArrowFunctionExpression, + CallExpression, + Expression, + FunctionExpression, + Literal, + Node, + SourceLocation, +} from 'acorn' + +type TestFunction = (FunctionExpression | ArrowFunctionExpression) & { + loc: SourceLocation +} + +export interface TestCase { + /** The function passed to test(...) */ + testNode: TestFunction + description: string[] + test: string + /** The number of top-level describe blocks up to and including this test */ + topLevelIndex: number + name: (glue?: string) => string + testCode: (source: string) => string +} + +export interface ParsedTests { + source: string + tests: TestCase[] +} + +const DESCRIBES = ['describe', 'xdescribe'] +const TESTS = ['test', 'xtest', 'it', 'xit'] +const MODIFIERS = ['skip', 'only'] + +function isIdentifier(node: Node, names: string[]): boolean { + return ( + node.type === 'Identifier' && + names.includes((node as AnyNode & { name: string }).name) + ) +} + +function isStringLiteral( + node: Node | undefined +): node is Literal & { value: string } { + return node?.type === 'Literal' && typeof (node as Literal).value === 'string' +} + +// describe('...'), describe.skip('...'), xdescribe.only('...') and so on +function isDescribe(node: Expression): boolean { + if (node.type !== 'CallExpression') return false + const { callee } = node + if (callee.type === 'Identifier') return DESCRIBES.includes(callee.name) + return ( + callee.type === 'MemberExpression' && + isIdentifier(callee.object, DESCRIBES) && + (isIdentifier(callee.property, MODIFIERS) || + (isStringLiteral(callee.property) && + MODIFIERS.includes(callee.property.value))) + ) +} + +// test('...'), it.skip('...'), xtest.only('...') and so on +function isTest(node: Expression): boolean { + if (node.type !== 'CallExpression') return false + const { callee } = node + if (callee.type === 'Identifier') return TESTS.includes(callee.name) + return ( + callee.type === 'MemberExpression' && + isIdentifier(callee.object, TESTS) && + isIdentifier(callee.property, MODIFIERS) + ) +} + +function isTestFunction(node: Node | undefined): node is TestFunction { + return ( + node?.type === 'FunctionExpression' || + node?.type === 'ArrowFunctionExpression' + ) +} + +function sourceOf(source: string, node: Node): string { + return source.substring(node.start, node.end) +} + +function isNode(value: unknown): value is Node { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { type?: unknown }).type === 'string' + ) +} + +function children(node: Node): Node[] { + const result: Node[] = [] + Object.entries(node).forEach(([key, value]) => { + if (key === 'loc') return + if (Array.isArray(value)) { + value.forEach((item) => { + if (isNode(item)) result.push(item) + }) + } else if (isNode(value)) { + result.push(value) + } + }) + return result +} + +/** + * Finds the tests in the same way as @exercism/static-analysis did. Tests + * and describe blocks named with anything other than a string literal (such + * as a template literal) are left out. + */ +export function parseTests(source: string): ParsedTests { + const program = parse(source, { + ecmaVersion: 'latest', + sourceType: 'module', + locations: true, + allowHashBang: true, + }) + + const tests: TestCase[] = [] + const description: string[] = [] + let topLevelDescribes = 0 + + function visit(node: Node): void { + if (node.type === 'ExpressionStatement') { + const { expression } = node as AnyNode & { expression: Expression } + + if (isDescribe(expression)) { + const [nameArgument] = (expression as CallExpression).arguments + if (!isStringLiteral(nameArgument)) return + + if (description.length === 0) topLevelDescribes += 1 + description.push(nameArgument.value) + children(node).forEach(visit) + description.pop() + return + } + + if (isTest(expression)) { + const [nameArgument, testArgument] = (expression as CallExpression) + .arguments + if (isStringLiteral(nameArgument) && isTestFunction(testArgument)) { + tests.push( + createTestCase( + testArgument, + [...description], + nameArgument.value, + topLevelDescribes + ) + ) + } + return + } + } + + children(node).forEach(visit) + } + + visit(program) + return { source, tests } +} + +function createTestCase( + testNode: TestFunction, + description: string[], + test: string, + topLevelIndex: number +): TestCase { + return { + testNode, + description, + test, + topLevelIndex, + name(glue = ' > '): string { + return [...description, test].join(glue) + }, + testCode(source: string): string { + if (testNode.body.type === 'BlockStatement') { + return testNode.body.body + .map((statement) => sourceOf(source, statement)) + .join('\n') + } + return sourceOf(source, testNode.body) + }, + } +}