diff --git a/.claude/rules/ci.md b/.claude/rules/ci.md index a9684a0c4c..a65d946abf 100644 --- a/.claude/rules/ci.md +++ b/.claude/rules/ci.md @@ -17,6 +17,7 @@ paths: - No scheduled or unattended check without a path that turns its findings into fix pull requests. - **Performance measures are reported, not failed.** A performance row over its limit fails no check: wall time, peak memory, `.safedi` size, and a growth row's time, memory, size and code. A wall time differs between runners and between runs of one, so a failure on it was answered by running the job again; a change that moved another measure was answered by a commit that moved a limit and a run of every check again. "Check Generate Time on Linux" (`--report-measures`) and "Check Function Compile Time on Linux" (`--report-only`) therefore report a row over its limit as a warning, and "Post Timing to the Pull Request" writes both reports, with the change's tool against the newest release's, into one comment on the pull request that every run rewrites. The limits stay, as what the report calls over, and a change still does not raise one without approval. `Scripts/perf-watch.py --commit SHA [--before-commit SHA]` lists from a run's report every row over its limit, its ratio and limit, and how it moved since an earlier run: run it on each landing on main and on a release branch's heads, and give each row over a limit or worse an owner, so a regression is listed debt with a fix planned and never unseen. A shape or a row the tool cannot generate, or does not finish, still fails, as do the checks of correctness. A new check of a performance measure joins that comment (an artifact named `timing-comment-…` holding a Markdown report) and fails only when it measured nothing. Only that job has `pull-requests: write`, and it runs none of the pull request's code. - New Linux jobs use the container and setup of "Build Tests on Linux" and "Build and Test on Linux" in `ci.yml`, except "Build and Test on Latest Swift" (`swift:latest`), "Lint Swift" (`swift:6.3`, a release build of SwiftFormat), and "Build Release SafeDITool on Linux", which runs `publish.yml`'s Linux build command in `publish.yml`'s container, because publishing 2.3.0-alpha-1 crashed Swift 6.3.3 compiling that release build of code every CI job had passed. "Delete This Run's Scratch Ref" (`verify.yml`, `graph-fuzzer.yml`) and "Post Timing to the Pull Request" have no container: each runs only GitHub's API, the first git too. +- "Compile Generated Mocks on Linux" runs `Scripts/compile-generated-mocks.py` on a change that touches the sources: seven fixed graphs generated and compiled with `-DDEBUG`, about six minutes on four processors after a debug build of the tool, the library and the macros (about five minutes with no cache). It fails on a module the compiler refuses and prints the first errors; a module above a refused one is not compiled. Add a graph as one file under `Scripts/compile-generated-mocks/`, with a `// module: NAME` line before each module's declarations when it has more than one; the fixtures are input, so `.swiftformat` leaves them alone. - `ci.yml` runs every check on a branch with no pull request: `gh workflow run ci.yml --ref `. A landing stack is checked this way, never through a pull request opened only to carry its CI. The run counts every file as changed, reads no stack position, and compares "Check Generate Time on Linux" and the fuzzer's base comparison with the branch's merge base with main. - `verify.yml` ("Verify on Linux") runs "Build Tests on Linux"'s build for one branch: `gh workflow run verify.yml --ref -f filter=` (empty runs the suite; `-f pins=true` also checks the fuzzer's pins). It restores main's content-stamped build (`.github/scripts/stamp-source-times.sh`) and passed-compile-check caches; keep its container and `RELEASE_SWIFT_TEST_ARGUMENTS` in step with "Build Tests on Linux" and `graph-fuzzer.yml`'s coverage build, which restores its key. `-f mode=fast` needs a filter and builds in debug without coverage, from "Warm the Fast Verify Build Cache"'s cache. `-f mode=function-compile-time` runs only "Check Function Compile Time on Linux"'s build and check ("Verify Function Compile Time on Linux"; keep the two jobs' container, command and check in step) and tests nothing: run it before a pull request that adds or grows a long function under `Sources/SafeDICore` joins a stack, because the limit is about Linux's Swift 6.2 and CI runs on a stack's top only. - **A restored build compiles every test target again when what the tests are compiled against changed.** A restored build did not always compile a test target again when a module it imports changed, and linked tests compiled for an enum of SafeDICore without its new case, which crashed them; such a target can as well pass a test that should fail. `.github/scripts/stamp-source-times.sh` therefore gives a file under `Tests` a time from its content and from `Sources`, the test support target and the manifest together, so a change to any of those compiles every test target again. A job that restores a build of the tests stamps first. To rule a restored build out of one result, label the pull request `clean-build` and re-run (every restore of a SwiftPM or xcodebuild build in `ci.yml` is skipped; the label is read as it is now), or pass `verify.yml` `-f clean=true`. diff --git a/.claude/rules/scripts.md b/.claude/rules/scripts.md index acb7b0189c..32cb220951 100644 --- a/.claude/rules/scripts.md +++ b/.claude/rules/scripts.md @@ -19,6 +19,7 @@ What each script is for. Read this before running or changing one, and before wr - `Scripts/unexecuted-lines.py` is "Check Line Coverage on Linux": it needs both test jobs' reports, so it cannot check a local run. `.claude/rules/ci.md` says how to read a CI run's result locally. - Tools only agents run are skills under `.claude/skills/`: `verify-touched` runs the suites a branch touches, before any full Verify. Before a review, run `pre-review` on the final head and put its block in the hand-back: lint, the touched suites, every fuzzer corpus with its pins on CI when the change owes them, and the lists a reviewer would otherwise ask for (32 of the 49 findings of one day's review rounds were ones an existing command shows). - `Scripts/generate-time-check.py BASE_TOOL HEAD_TOOL DIRECTORY` is "Check Generate Time on Linux": it times two builds of `SafeDITool` generating synthetic seam, inline and public mock graphs in alternating runs. It fails when the head tool cannot generate a shape; under `--report-measures`, which CI passes, a measure over its limit (wall time, peak memory, `.safedi` size, a growth row) is reported and fails nothing ("Performance measures are reported" in `.claude/rules/ci.md`). +- `Scripts/compile-generated-mocks.py TOOL BIN_PATH DIRECTORY` is "Compile Generated Mocks on Linux": it generates fixed graphs (`--list`) with a debug build's tool and compiles each module's generated code, mocks included, as a debug build does; a graph whose generated code once failed to compile joins as a file under `Scripts/compile-generated-mocks/`. - `Scripts/perf-watch.py [--before EARLIER_REPORT] REPORT`, or `--commit SHA [--before-commit SHA]`, reads that check's report (a file, or the artifact of a commit's newest CI run) and lists every row over its limit with its ratio and limit, how it moved since the earlier run, and every other row that got worse. - `Scripts/check-claude-instruction-files.sh` fails when an instruction file could be truncated or would load at launch by mistake, when a rules file is missing from the table under "Where the rest lives", when an instruction file names a Swift symbol no other tracked file contains (`Scripts/check-instruction-symbols.py`), or when reading one tracked file would load more rules than a budget allows (`Scripts/check-instruction-load.py`, whose `--report FILE…` prints what a file loads); "Check Markdown links" runs it. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae66d58d15..9cb32de847 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2217,7 +2217,7 @@ jobs: # leaves the builds for the next run or for eviction. prune-build-caches: name: Delete Older Build Directories - needs: [spm, linux-build, linux-latest-swift-group, generate-time, example-integrations, stack-position] + needs: [spm, linux-build, linux-latest-swift-group, generate-time, compile-generated-mocks, example-integrations, stack-position] if: ${{ !cancelled() && needs.stack-position.outputs.stacked-under == '' && github.event_name == 'push' && github.ref == 'refs/heads/main' }} runs-on: ubuntu-latest permissions: @@ -2236,7 +2236,7 @@ jobs: REF: ${{ github.ref }} COMMIT: ${{ github.sha }} run: | - for prefix in spm-release-v2-macOS-xcode-26.0- spm-release-v2-Linux-swift-6.2- spm-debug-v2-Linux-swift- generate-time-build-v1-Linux-swift-6.2-; do + for prefix in spm-release-v2-macOS-xcode-26.0- spm-release-v2-Linux-swift-6.2- spm-debug-v2-Linux-swift- generate-time-build-v1-Linux-swift-6.2- compile-generated-mocks-build-v1-Linux-swift-6.2-; do if ! builds=$(gh api -X GET "repos/$REPOSITORY/actions/caches" -f key="$prefix" -f ref="$REF" -F per_page=100 --jq '.actions_caches[] | "\(.id) \(.key)"' 2>&1); then echo "::warning::Listing $REF's builds under $prefix failed: $(printf '%s' "$builds" | tr '\r\n' ' ')" continue @@ -3648,6 +3648,73 @@ jobs: # run's, which may be days older. retention-days: 30 + # The generated code of fixed graphs, mocks included, compiled as an + # app's debug build compiles it (Scripts/compile-generated-mocks.py): the + # lifelike chain at five features with and without screens that open + # screens above them, the calling-mocks shape, an app of 150 mocked + # features, and each graph under Scripts/compile-generated-mocks/ that a + # release candidate's code did not compile for. The tests compare the + # generator's text and the graph fuzzer compiles small drawn graphs, so + # code the compiler refuses in a shape an app has was otherwise found + # only by an app-sized build. A debug build of the tool, the library and its + # macros, which no other job builds with these arguments, so the job + # keeps a build cache of its own, keyed as "Check Generate Time on + # Linux" keys its release build. + compile-generated-mocks: + name: Compile Generated Mocks on Linux + needs: [changes, stack-position] + if: ${{ !cancelled() && needs.stack-position.outputs.stacked-under == '' && needs.changes.outputs.source != 'false' }} + runs-on: ubuntu-latest + container: swift:6.2 + permissions: + contents: read + defaults: + run: + shell: bash + steps: + - name: Checkout Repo + uses: actions/checkout@v7 + # Retried for the reason "Install curl for Codecov" gives. + - name: Install Python + uses: ./.github/actions/retry + with: + command: command -v python3 >/dev/null || { timeout 120 apt-get -o Acquire::http::Timeout=20 -o Acquire::Retries=0 update && timeout 120 apt-get -o Acquire::http::Timeout=20 -o Acquire::Retries=0 install -y --no-install-recommends python3; } || { sed -i -E 's#http://(archive|security)\.ubuntu\.com/ubuntu#http://azure.archive.ubuntu.com/ubuntu#' /etc/apt/sources.list.d/ubuntu.sources; false; } + - name: Check the Script + run: python3 -I Scripts/compile-generated-mocks.py --self-test "$RUNNER_TEMP/compile-generated-mocks-self-test" + # For the reason "Build Tests on Linux" gives. + - name: Stamp Source Times + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + .github/scripts/stamp-source-times.sh + - name: Restore Build Directory + if: ${{ needs.stack-position.outputs.clean-build != 'true' }} + uses: actions/cache/restore@v6 + with: + path: .build + key: compile-generated-mocks-build-v1-${{ runner.os }}-swift-6.2-${{ hashFiles('Package.resolved') }}-${{ github.sha }} + restore-keys: | + compile-generated-mocks-build-v1-${{ runner.os }}-swift-6.2-${{ hashFiles('Package.resolved') }}- + compile-generated-mocks-build-v1-${{ runner.os }}-swift-6.2- + - name: Resolve Package Dependencies + uses: ./.github/actions/retry + with: + command: swift package resolve + # The tool, and the library with the macros its users' modules expand. + - name: Build SafeDITool, SafeDI and the Macros + run: | + swift build --traits sourceBuild --product SafeDITool + swift build --traits sourceBuild --target SafeDI + - name: Save Build Directory + if: ${{ !cancelled() && github.event_name == 'push' && github.ref == 'refs/heads/main' }} + uses: actions/cache/save@v6 + with: + path: .build + key: compile-generated-mocks-build-v1-${{ runner.os }}-swift-6.2-${{ hashFiles('Package.resolved') }}-${{ github.sha }} + - name: Generate and Compile the Graphs + run: | + bin=$(swift build --traits sourceBuild --show-bin-path) + python3 -I Scripts/compile-generated-mocks.py --summary "$GITHUB_STEP_SUMMARY" "$bin/SafeDITool" "$bin" "$RUNNER_TEMP/compile-generated-mocks" + # Builds the SafeDITool of the pull request's base, which each fuzzer shard # below runs beside this commit's over the shard's graphs # (SafeDIToolBaseComparisonTests/longRun), comparing exit statuses, diff --git a/.swiftformat b/.swiftformat index b6b08dee30..00c6788097 100644 --- a/.swiftformat +++ b/.swiftformat @@ -6,6 +6,8 @@ # The written-calls fixtures keep the Manual’s spellings (`ErasedInstantiator<(), …>`) and the type annotations that # check what each call returns (`let _: Screen = …`), and a released copy must never change. --exclude Scripts/release-checks/written-calls +# Graphs whose generated code a release candidate did not compile, kept as the files that were found. +--exclude Scripts/compile-generated-mocks # format options --indent tab diff --git a/Scripts/compile-generated-mocks.py b/Scripts/compile-generated-mocks.py new file mode 100644 index 0000000000..4afd9d0134 --- /dev/null +++ b/Scripts/compile-generated-mocks.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Usage: compile-generated-mocks.py [--shapes NAME,…] [--jobs N] [--summary FILE] TOOL BIN_PATH DIRECTORY + compile-generated-mocks.py --list + compile-generated-mocks.py --self-test DIRECTORY + +Generates the code of fixed dependency graphs with TOOL (a `SafeDITool`), mocks included, and compiles every module of +each with `swiftc`, as an app's debug build does. Exits 1 when a module of a graph does not generate or does not +compile, and prints the compiler's first errors. It is "Compile Generated Mocks on Linux": a change to the generator +that makes it write code the compiler refuses, in a shape an app has, fails here in minutes, where the tests compare +text and the graph fuzzer draws small graphs. + +BIN_PATH is what `swift build --traits sourceBuild --show-bin-path` prints after a build of the `SafeDI` library and +its macros: the graphs' modules import `SafeDI` and expand its macros. + +The graphs: + lifelike-5, lifelike-back-edges-5, M80x80-calling-mocks + Scripts/generate-time-check.py's lifelike chain at five features, the same with screens that open screens above + them, and its calling-mocks shape: the shapes that check times, built here by the same functions, so the graph + that is timed is the graph that is compiled. + app-150-mocked-features + That script's app shape (150 features over 1,500 leaf screens, each leaf opened by three features) with every + feature a mock root and its properties private: 150 mock roots over one shared tree. + a file under Scripts/compile-generated-mocks/ + One graph a release candidate's generated code did not compile for, kept as its source. A file holds one module + (named `App`), or several, each started by a line `// module: NAME`, or `// module: NAME package: PACKAGE` for + a module in a package of its own (the others share one); a module depends on the file's modules it imports. Add a file to add a graph: a graph found by a build that failed belongs here once it is reduced. + +Each module is generated alone, reading the `.safedi` files of the modules it depends on, as the Bazel rule and the +Tuist plugin run the tool, with DEBUG set; then compiled with `-swift-version 6 -Onone -DDEBUG -enable-testing`, whole +module, against the modules before it. Graphs run `--jobs` at a time (default one a core).""" +import importlib.util +import os +import re +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor + +HERE = os.path.dirname(os.path.abspath(__file__)) +FIXTURES = os.path.join(HERE, "compile-generated-mocks") +MODULE_LINE = re.compile(r"^// module: (\w+)(?: package: (\w+))?", re.MULTILINE) +IMPORT_LINE = re.compile(r"^(?:@testable )?import (\w+)", re.MULTILINE) +ERROR_LINE = re.compile(r"^(?:\S*/)?([^/\s]+:\d+:\d+: error: .*)$", re.MULTILINE) +COMPILER_ARGUMENTS = ["-swift-version", "6", "-Onone", "-DDEBUG", "-enable-testing", "-whole-module-optimization", "-parse-as-library"] + + +def load_shapes(): + """Scripts/generate-time-check.py as a module: its shapes, and the `generate` that runs the tool per module.""" + specification = importlib.util.spec_from_file_location("generate_time_check", os.path.join(HERE, "generate-time-check.py")) + module = importlib.util.module_from_spec(specification) + specification.loader.exec_module(module) + return module + + +def app_with_mocked_features(shapes, features, leaves): + """The app shape with every feature a mock root, and its properties private as an app writes them.""" + (name, dependencies, source), = shapes.shape_app(features=features, leaves=leaves, reach=3, fan=2, values=3, root_values=60) + source = re.sub(r"@Instantiable\n(public final class F\d+:)", r"@Instantiable(generateMock: true)\n\1", source) + return [(name, dependencies, source.replace(" public let ", " private let "))] + + +def modules_of_file(text): + """A fixture's modules as (name, the file's modules it imports, source), each after the modules it depends on.""" + starts = list(MODULE_LINE.finditer(text)) + if starts: + sources = {found.group(1): text[found.start():(starts[index + 1].start() if index + 1 < len(starts) else len(text))] for index, found in enumerate(starts)} + else: + sources = {"App": text} + dependencies = {name: sorted(set(IMPORT_LINE.findall(source)) & set(sources) - {name}) for name, source in sources.items()} + ordered = [] + while len(ordered) < len(sources): + ready = [name for name in sources if name not in ordered and all(dependency in ordered for dependency in dependencies[name])] + if not ready: + raise ValueError(f"modules {sorted(set(sources) - set(ordered))} import each other in a ring") + ordered += ready + return [(name, dependencies[name], sources[name]) for name in ordered] + + +def packages_of_file(text): + """The package of each module of a fixture whose line names one (`// module: NAME package: PACKAGE`): two modules + in two packages see only each other's public declarations, which changes what a mock may call.""" + return {found.group(1): found.group(2) for found in MODULE_LINE.finditer(text) if found.group(2)} + + +def graphs(shapes, fixtures=FIXTURES): + """Every graph by name: a function that returns its modules.""" + found = { + "lifelike-5": lambda: shapes.shape_lifelike_chain(5), + "lifelike-back-edges-5": lambda: shapes.shape_lifelike_chain(5, back_edges=True), + "M80x80-calling-mocks": shapes.SHAPES["M80x80-calling-mocks"], + "app-150-mocked-features": lambda: app_with_mocked_features(shapes, 150, 1500), + } + for file in sorted(os.listdir(fixtures)) if os.path.isdir(fixtures) else []: + if file.endswith(".swift"): + def read(path=os.path.join(fixtures, file)): + with open(path) as handle: + return modules_of_file(handle.read()) + + def packages(path=os.path.join(fixtures, file)): + with open(path) as handle: + return packages_of_file(handle.read()) + read.packages = packages + found[file[:-len(".swift")]] = read + return found + + +def build_products(bin_path): + """(the macros' executable, the directory that holds SafeDI's module), found as Scripts/multi-module-repro.sh does: + SwiftPM's native build names the executable `SafeDIMacros-tool`, Swift Build names it `SafeDIMacros`.""" + macros = next((path for path in (f"{bin_path}/SafeDIMacros-tool", f"{bin_path}/SafeDIMacros-tool.exe", f"{bin_path}/SafeDIMacros") if os.path.isfile(path)), None) + if not macros: + raise ValueError(f"no SafeDIMacros executable in {bin_path}: build with `swift build --traits sourceBuild` first") + modules = f"{bin_path}/Modules" if os.path.exists(f"{bin_path}/Modules/SafeDI.swiftmodule") else bin_path + if not os.path.exists(f"{modules}/SafeDI.swiftmodule"): + raise ValueError(f"no SafeDI.swiftmodule in {bin_path}: build with `swift build --traits sourceBuild` first") + return macros, modules + + +def compile_graph(shapes, name, modules, tool, compiler, directory, packages={}): + """Generates and compiles one graph; returns (the failures, generate seconds, compile seconds, modules).""" + sources, output = f"{directory}/{name}/sources", f"{directory}/{name}/output" + for module, _, source in modules: + shapes.write(f"{sources}/{module}/Types.swift", source) + started = time.monotonic() + try: + shapes.generate(tool, modules, sources, output, packages=packages) + except shapes.Failure as failure: + return [f"{name}: does not generate: {str(failure).strip()[:600]}"], time.monotonic() - started, 0.0, len(modules) + generated = time.monotonic() + failures = [] + refused = set() + for module, dependencies, _ in modules: + if refused & set(dependencies): + # A module above one the compiler refused has no module to import: its errors would only repeat the first. + refused.add(module) + continue + result = subprocess.run(compiler + ["-module-name", module, "-package-name", packages.get(module, "GenerateTimeCheck"), "-emit-module", "-emit-module-path", f"{output}/{module}.swiftmodule", + "-c", "-o", f"{output}/{module}.o", "-I", output, f"{sources}/{module}/Types.swift", f"{output}/{module}.generated.swift"], + capture_output=True, text=True, errors="replace") + if result.returncode != 0: + refused.add(module) + text = result.stderr + result.stdout + errors = ERROR_LINE.findall(text) or [line for line in text.splitlines() if "error" in line] or [text.strip()[-300:]] + failures.append(f"{name}: module {module} does not compile ({len(errors)} error line(s)): " + "; ".join(error[:300] for error in errors[:3])) + return failures, generated - started, time.monotonic() - generated, len(modules) + + +def run(shapes, selected, tool, compiler, directory, jobs, summary): + def one(name): + try: + return compile_graph(shapes, name, selected[name](), tool, compiler, directory, getattr(selected[name], "packages", dict)()) + except (OSError, ValueError) as error: + return [f"{name}: {error}"], 0.0, 0.0, 0 + started = time.monotonic() + with ThreadPoolExecutor(max_workers=jobs) as pool: + results = dict(zip(selected, pool.map(one, selected))) + failures = [failure for found, _, _, _ in results.values() for failure in found] + lines = [f"**Generated code of {len(selected)} graph(s) compiled, mocks included: {len(failures)} failure(s), in {time.monotonic() - started:.0f} s with {jobs} at a time.**", ""] + lines += [f"- {failure}" for failure in failures] + ([""] if failures else []) + lines += ["| Graph | Modules | Generate | Compile | Verdict |", "|---|---|---|---|---|"] + lines += [f"| {name} | {count} | {generate_seconds:.1f} s | {compile_seconds:.1f} s | {'**fails**' if found else 'compiles'} |" for name, (found, generate_seconds, compile_seconds, count) in results.items()] + text = "\n".join(lines) + "\n" + print(text) + if summary: + with open(summary, "a") as handle: + handle.write(text) + if os.environ.get("GITHUB_ACTIONS") == "true": + for failure in failures: + print(f"::error::{failure.splitlines()[0][:900]}") + return 1 if failures else 0 + + +# A stand-in for the tool: writes each module's generated file and `.safedi`, and refuses a module that says so. +STAND_IN_TOOL = """#!/usr/bin/env python3 +import sys +arguments = sys.argv[1:] +source = open(open(arguments[1]).read().strip()).read() +if "REFUSE-TO-GENERATE" in source: + sys.exit("stand-in tool: refused") +open(arguments[arguments.index("--combined-output") + 1], "w").write("// generated\\n" + ("BROKEN\\n" if "GENERATE-BROKEN" in source else "")) +open(arguments[arguments.index("--module-info-output") + 1], "w").write("info") +""" +# A stand-in for swiftc: writes the module, and refuses a generated file that holds BROKEN as the compiler words it. +STAND_IN_COMPILER = """#!/usr/bin/env python3 +import sys +arguments = sys.argv[1:] +generated = arguments[-1] +if "BROKEN" in open(generated).read(): + sys.exit(generated + ":2:1: error: cannot find 'BROKEN' in scope") +for imported in __import__("re").findall(r"^import (\\w+)", open(arguments[-2]).read(), __import__("re").M): + if imported != "SafeDI": + open(arguments[arguments.index("-I") + 1] + "/" + imported + ".swiftmodule") +open(arguments[arguments.index("-emit-module-path") + 1], "w").write("module") +""" + + +def self_test(directory): + shapes = load_shapes() + failures = [] + tool, compiler = f"{directory}/tools/tool", f"{directory}/tools/compiler" + for path, text in ((tool, STAND_IN_TOOL), (compiler, STAND_IN_COMPILER)): + shapes.write(path, text) + os.chmod(path, 0o755) + two = "// module: Lib\nimport SafeDI\npublic struct A {}\n// module: App\nimport SafeDI\nimport Lib\nstruct B {}\n" + if [(name, dependencies) for name, dependencies, _ in modules_of_file(two.replace("// module: Lib", "// module: Zed").replace("import Lib", "import Zed"))] != [("Zed", []), ("App", ["Zed"])]: + failures.append("a file's modules are not ordered by what they import") + if [(name, dependencies) for name, dependencies, _ in modules_of_file("import SafeDI\nstruct A {}\n")] != [("App", [])]: + failures.append("a file with no module line is not one module named App") + if packages_of_file(two.replace("// module: Lib", "// module: Lib package: libpkg")) != {"Lib": "libpkg"} or packages_of_file(two): + failures.append("a module line's package is not read") + try: + modules_of_file("// module: A\nimport B\n// module: B\nimport A\n") + failures.append("two modules that import each other were ordered") + except ValueError: + pass + cases = { + "compiles": (two, 0, "| compiles | 2 |"), + "does-not-generate": (two.replace("struct B", "// REFUSE-TO-GENERATE\nstruct B"), 1, "does-not-generate: does not generate"), + "does-not-compile": (two.replace("struct B", "// GENERATE-BROKEN\nstruct B"), 1, "module App does not compile (1 error line(s)): App.generated.swift:2:1: error: cannot find 'BROKEN' in scope"), + # The module above a refused one is not compiled, so one defect is one failure. + "first-module-does-not-compile": (two.replace("struct A", "// GENERATE-BROKEN\npublic struct A"), 1, "module Lib does not compile"), + } + for name, (text, expected, line) in cases.items(): + shapes.write(f"{directory}/{name}.md", "") + status = run(shapes, {name: lambda text=text: modules_of_file(text)}, tool, [compiler], f"{directory}/runs", 2, f"{directory}/{name}.md") + with open(f"{directory}/{name}.md") as handle: + written = handle.read() + if status != expected or line not in written or written.count("does not compile") > 1: + failures.append(f"{name}: expected exit {expected} and {line!r}, got exit {status} and {written!r}") + found = graphs(shapes) + for name in ("lifelike-5", "lifelike-back-edges-5", "M80x80-calling-mocks", "app-150-mocked-features"): + if name not in found: + failures.append(f"graph {name} is not listed") + mocked = app_with_mocked_features(shapes, 5, 10)[0][2] + if mocked.count("@Instantiable(generateMock: true)") != 5 or " public let " in mocked or " private let " not in mocked: + failures.append("the app shape's features are not each a mock root with private properties") + for name, read in found.items(): + try: + modules = read() + if not modules or any("import SafeDI" not in source for _, _, source in modules): + failures.append(f"graph {name} has a module that does not import SafeDI") + except (OSError, ValueError) as error: + failures.append(f"graph {name}: {error}") + for failure in failures: + print(f"- {failure}") + print("self-test " + ("failed" if failures else "passed")) + return 1 if failures else 0 + + +def main(arguments): + options = {"--shapes": None, "--jobs": str(os.cpu_count() or 1), "--summary": None} + positional = [] + self_testing = listing = False + while arguments: + argument = arguments.pop(0) + if argument == "--self-test": + self_testing = True + elif argument == "--list": + listing = True + elif argument in options and arguments: + options[argument] = arguments.pop(0) + else: + positional.append(argument) + if listing and not positional: + print("\n".join(graphs(load_shapes()))) + return 0 + if len(positional) != (1 if self_testing else 3) or any(argument.startswith("--") for argument in positional) or not options["--jobs"].isdigit() or int(options["--jobs"]) < 1: + print(__doc__.split("\n\n")[0], file=sys.stderr) + return 2 + directory = os.path.abspath(positional[-1]) + if self_testing: + return self_test(directory) + shapes = load_shapes() + every = graphs(shapes) + names = options["--shapes"].split(",") if options["--shapes"] else list(every) + unknown = [name for name in names if name not in every] + if unknown: + print(f"unknown graph(s): {', '.join(unknown)}; the graphs are {', '.join(every)}", file=sys.stderr) + return 2 + try: + macros, modules = build_products(os.path.abspath(positional[1])) + except ValueError as error: + print(f"compile-generated-mocks.py: {error}", file=sys.stderr) + return 2 + swiftc = ["xcrun", "swiftc"] if sys.platform == "darwin" else ["swiftc"] + compiler = swiftc + COMPILER_ARGUMENTS + ["-I", modules, "-load-plugin-executable", f"{macros}#SafeDIMacros"] + return run(shapes, {name: every[name] for name in names}, os.path.abspath(positional[0]), compiler, directory, int(options["--jobs"]), options["--summary"]) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/Scripts/compile-generated-mocks/captured-hole-fill.swift b/Scripts/compile-generated-mocks/captured-hole-fill.swift new file mode 100644 index 0000000000..2f7ff204fe --- /dev/null +++ b/Scripts/compile-generated-mocks/captured-hole-fill.swift @@ -0,0 +1,160 @@ +// module: Lib package: shop +import SafeDI +public enum LeafCount { nonisolated(unsafe) public static var calls = 0 } +@Instantiable(generateMock: true) +public final class Leaf: Instantiable, @unchecked Sendable { + public init(leafPart: LeafPart) { self.leafPart = leafPart; LeafCount.calls += 1; call = LeafCount.calls } + public let call: Int + @Instantiated let leafPart: LeafPart +} +public enum ReadLeafCount { nonisolated(unsafe) public static var calls = 0 } +@Instantiable +public final class ReadLeaf: Instantiable, @unchecked Sendable { + public init(token: Token?) { self.token = token; ReadLeafCount.calls += 1; call = ReadLeafCount.calls } + public let call: Int + @Received(onlyIfAvailable: true) let token: Token? +} +public enum ScreenCount { nonisolated(unsafe) public static var calls = 0 } +@Instantiable(generateMock: true) +public final class Screen: Instantiable, @unchecked Sendable { + public init(screenBuilder: Instantiator, readLeaf: ReadLeaf, token: Token, leaf: Leaf) { self.screenBuilder = screenBuilder; self.readLeaf = readLeaf; self.token = token; self.leaf = leaf; ScreenCount.calls += 1; call = ScreenCount.calls } + public let call: Int + @Instantiated let screenBuilder: Instantiator + @Instantiated let readLeaf: ReadLeaf + @Instantiated let token: Token + @Instantiated let leaf: Leaf +} +public enum LeafHostCount { nonisolated(unsafe) public static var calls = 0 } +@Instantiable(generateMock: true) +public final class LeafHost: Instantiable, @unchecked Sendable { + public init(leaf: Leaf) { self.leaf = leaf; LeafHostCount.calls += 1; call = LeafHostCount.calls } + public let call: Int + @Instantiated let leaf: Leaf +} +public enum LeafPartCount { nonisolated(unsafe) public static var calls = 0 } +@Instantiable +public final class LeafPart: Instantiable, @unchecked Sendable { + public init() { LeafPartCount.calls += 1; call = LeafPartCount.calls } + public let call: Int +} +public protocol HoleApi: Sendable {} +public protocol GadgetApi: Sendable {} +@Instantiable +public final class Session: Instantiable, @unchecked Sendable { + public init() { } +} +@Instantiable +public final class Token: Instantiable, @unchecked Sendable { + public init() { } +} +@Instantiable +public final class FeaturePanel: Instantiable, @unchecked Sendable { + public init(holeApi: any HoleApi) { self.holeApi = holeApi; } + @Instantiated let holeApi: any HoleApi +} +@Instantiable(generateDependencyTree: true) +public final class FeatureSeam: Instantiable, @unchecked Sendable { + public init(featurePanel: LazilyInstantiated, token: Token, seamHoleApi: any HoleApi) { self.featurePanel = featurePanel; self.token = token; self.seamHoleApi = seamHoleApi; } + @Instantiated let featurePanel: LazilyInstantiated + @Instantiated let token: Token + @Instantiated let seamHoleApi: any HoleApi +} +@Instantiable +public final class WidgetPart: Instantiable, @unchecked Sendable { + public init(token: Token?) { self.token = token; } + @Received(onlyIfAvailable: true) let token: Token? +} +@Instantiable(generateMock: true) +public final class Widget: Instantiable, @unchecked Sendable { + public init(widgetPart: LazilyInstantiated, gadget: any GadgetApi) { self.widgetPart = widgetPart; self.gadget = gadget; } + @Instantiated let widgetPart: LazilyInstantiated + @Instantiated let gadget: any GadgetApi +} +public protocol PlugApi: Sendable {} +@Instantiable(generateMock: .public) +public final class Plug: Instantiable, @unchecked Sendable { + init(plugApi: any PlugApi) { self.plugApi = plugApi; } + @Instantiated let plugApi: any PlugApi +} +// module: App package: shop +import SafeDI +import Lib +@Instantiable(fulfillingAdditionalTypes: [HoleApi.self]) +public final class HoleImpl: Instantiable, HoleApi, @unchecked Sendable { + public init(session: Session?) { self.session = session; } + @Received(onlyIfAvailable: true) let session: Session? +} +@Instantiable(fulfillingAdditionalTypes: [GadgetApi.self]) +public final class GadgetImpl: Instantiable, GadgetApi, @unchecked Sendable { + public init() { } +} +@Instantiable(isRoot: true) +public final class AppRoot: Instantiable, @unchecked Sendable { + public init(session: Session, featureSeamBuilder: Instantiator) { self.session = session; self.featureSeamBuilder = featureSeamBuilder; } + @Instantiated let session: Session + @Instantiated let featureSeamBuilder: Instantiator +} +public protocol GizmoApi: Sendable {} +@Instantiable(generateMock: true) +public final class Gizmo: Instantiable, GizmoApi, @unchecked Sendable { + public init(session: Session) { self.session = session; } + @Received let session: Session +} +public enum AnyGizmoCount { nonisolated(unsafe) public static var calls = 0 } +public struct AnyGizmo: @unchecked Sendable { + public init(_ value: Gizmo) { AnyGizmoCount.calls += 1; self.value = value; self.call = AnyGizmoCount.calls } + public let value: Gizmo + public let call: Int +} +@Instantiable(generateMock: true) +public final class GizmoHost: Instantiable, @unchecked Sendable { + public init(anyGizmoBuilder: ErasedInstantiator<(), AnyGizmo>) { self.anyGizmoBuilder = anyGizmoBuilder; } + @Instantiated(fulfilledByType: "Gizmo", erasedToConcreteExistential: true) let anyGizmoBuilder: ErasedInstantiator<(), AnyGizmo> +} +@Instantiable(generateMock: true) +public final class AppScreen: Instantiable, @unchecked Sendable { + public init(session: Session, widget: Widget) { self.session = session; self.widget = widget; } + @Instantiated let session: Session + @Instantiated let widget: Widget +} +@Instantiable(fulfillingAdditionalTypes: [PlugApi.self]) +public final class PlugImpl: Instantiable, PlugApi, @unchecked Sendable { + public init() { } +} +@Instantiable +public final class WidgetHolder: Instantiable, @unchecked Sendable { + public init(plug: Plug, widget: Widget) { self.plug = plug; self.widget = widget; } + @Instantiated let plug: Plug + @Instantiated let widget: Widget +} +@Instantiable(generateMock: true) +public final class HolderHost: Instantiable, @unchecked Sendable { + public init(widgetHolderBuilder: Instantiator) { self.widgetHolderBuilder = widgetHolderBuilder; } + @Instantiated let widgetHolderBuilder: Instantiator +} +@Instantiable(generateMock: true) +public final class HolderSibling: Instantiable, @unchecked Sendable { + public init(widgetHolder: WidgetHolder) { self.widgetHolder = widgetHolder; } + @Instantiated let widgetHolder: WidgetHolder +} +@Instantiable +public final class RingInner: Instantiable, @unchecked Sendable { + public init(plug: Plug) { self.plug = plug; } + @Instantiated let plug: Plug +} +@Instantiable +public final class RingStep: Instantiable, @unchecked Sendable { + public init(ringBuilder: SendableInstantiator) { self.ringBuilder = ringBuilder; } + @Instantiated let ringBuilder: SendableInstantiator +} +@Instantiable +public final class Ring: Instantiable, @unchecked Sendable { + public init(ringStep: RingStep, ringInner: RingInner) { self.ringStep = ringStep; self.ringInner = ringInner; } + @Instantiated let ringStep: RingStep + @Instantiated let ringInner: RingInner +} +@Instantiable(generateMock: true) +public final class RingHost: Instantiable, @unchecked Sendable { + public init(ring: Ring) { self.ring = ring; } + @Instantiated let ring: Ring +} diff --git a/Scripts/compile-generated-mocks/sendable-builder-of-a-bare-leaf.swift b/Scripts/compile-generated-mocks/sendable-builder-of-a-bare-leaf.swift new file mode 100644 index 0000000000..8baa664467 --- /dev/null +++ b/Scripts/compile-generated-mocks/sendable-builder-of-a-bare-leaf.swift @@ -0,0 +1,80 @@ +// module: Lib package: shop +import SafeDI +public protocol HoleApi: Sendable {} +public protocol GadgetApi: Sendable {} +@Instantiable +public final class Session: Instantiable, @unchecked Sendable { + public init() { } +} +@Instantiable +public final class Token: Instantiable, @unchecked Sendable { + public init() { } +} +public enum DefaultStampCount { nonisolated(unsafe) public static var value = 0 } +public final class DefaultStamp: Sendable { public let serial: Int; public init() { DefaultStampCount.value += 1; serial = DefaultStampCount.value } } +@Instantiable(generateDependencyTree: true) +public final class FeatureSeam: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + public init(session: Session, holeApi: any HoleApi, defaultStamp: DefaultStamp = DefaultStamp()) { self.session = session; self.holeApi = holeApi; self.defaultStamp = defaultStamp } + @Received let session: Session + @Instantiated let holeApi: any HoleApi +} +@Instantiable +public final class WidgetPart: Instantiable, @unchecked Sendable { + public init() { } +} +@Instantiable(generateMock: .public) +public final class Widget: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + init(widgetPart: SendableLazilyInstantiated, gadget: any GadgetApi, defaultStamp: DefaultStamp = DefaultStamp()) { self.widgetPart = widgetPart; self.gadget = gadget; self.defaultStamp = defaultStamp } + @Instantiated let widgetPart: SendableLazilyInstantiated + @Instantiated let gadget: any GadgetApi +} +@Instantiable +public final class Tag: Instantiable, Sendable { + public init() { serial = 0 } + public let serial: Int +} +@Instantiable +public final class EnteredParent: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + public init(childBuilder: Instantiator, step: Int = 0, defaultStamp: DefaultStamp = DefaultStamp()) { self.childBuilder = childBuilder; self.step = step; self.defaultStamp = defaultStamp } + @Instantiated let childBuilder: Instantiator + let step: Int +} +@Instantiable +public final class EnteredChild: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + public init(parentBuilder: Instantiator, tag: SendableLazilyInstantiated, step: Int = 0, defaultStamp: DefaultStamp = DefaultStamp()) { self.parentBuilder = parentBuilder; self.tag = tag; self.step = step; self.defaultStamp = defaultStamp } + @Instantiated let parentBuilder: Instantiator + @Instantiated let tag: SendableLazilyInstantiated + let step: Int +} +@Instantiable(generateMock: true) +public final class EnteredRoot: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + public init(parentBuilder: Instantiator, childBuilder: Instantiator, defaultStamp: DefaultStamp = DefaultStamp()) { self.parentBuilder = parentBuilder; self.childBuilder = childBuilder; self.defaultStamp = defaultStamp } + @Instantiated let parentBuilder: Instantiator + @Instantiated let childBuilder: Instantiator +} +// module: App package: shop +import SafeDI +import Lib +@Instantiable(fulfillingAdditionalTypes: [HoleApi.self]) +public final class HoleImpl: Instantiable, HoleApi, @unchecked Sendable { + public init() { } +} +@Instantiable(isRoot: true) +public final class AppRoot: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + public init(session: Session, featureSeam: FeatureSeam, defaultStamp: DefaultStamp = DefaultStamp()) { self.session = session; self.featureSeam = featureSeam; self.defaultStamp = defaultStamp } + @Instantiated let session: Session + @Instantiated let featureSeam: FeatureSeam +} +@Instantiable(generateMock: true) +public final class AppScreen: Instantiable, @unchecked Sendable { + public let defaultStamp: DefaultStamp + public init(session: Session, widget: Widget, defaultStamp: DefaultStamp = DefaultStamp()) { self.session = session; self.widget = widget; self.defaultStamp = defaultStamp } + @Instantiated let session: Session + @Instantiated let widget: Widget +} diff --git a/Scripts/compile-generated-mocks/sendable-filled-call-builder-bound-apart.swift b/Scripts/compile-generated-mocks/sendable-filled-call-builder-bound-apart.swift new file mode 100644 index 0000000000..ab01a8e0cb --- /dev/null +++ b/Scripts/compile-generated-mocks/sendable-filled-call-builder-bound-apart.swift @@ -0,0 +1,59 @@ +// A root that builds a call of another package's public mock inside a `@Sendable` function, beside a builder of +// the same label: the builder the call is filled with is bound apart. The two modules are in two packages. + +// module: Feed package: feedpkg +import SafeDI + +public protocol Api: Sendable {} + +@Instantiable(generateMock: .public) +public struct F: Instantiable, Sendable { + init(api: any Api) { + self.api = api + } + + @Instantiated public let api: any Api +} + +// module: App package: apppkg +import Feed +import SafeDI + +@Instantiable(fulfillingAdditionalTypes: [Api.self]) +public struct Live: Api, Instantiable, Sendable { + public init() {} +} + +@Instantiable +public struct Hub: Instantiable, Sendable { + public init(f: F) { + self.f = f + } + + @Instantiated public let f: F +} + +@Instantiable(generateMock: true) +public struct First: Instantiable { + public init(hub: Hub) { + self.hub = hub + } + + @Instantiated public let hub: Hub +} + +@Instantiable(generateMock: true) +public struct Second: Instantiable { + public init(hubBuilder: SendableInstantiator, apiSendableBuilder: Gadget) { + self.hubBuilder = hubBuilder + self.apiSendableBuilder = apiSendableBuilder + } + + @Instantiated public let hubBuilder: SendableInstantiator + @Instantiated public let apiSendableBuilder: Gadget +} + +@Instantiable +public struct Gadget: Instantiable, Sendable { + public init() {} +} diff --git a/Scripts/compile-generated-mocks/unfillable-hole-under-a-shared-builder.swift b/Scripts/compile-generated-mocks/unfillable-hole-under-a-shared-builder.swift new file mode 100644 index 0000000000..3482c44b78 --- /dev/null +++ b/Scripts/compile-generated-mocks/unfillable-hole-under-a-shared-builder.swift @@ -0,0 +1,50 @@ +import SafeDI + +public protocol Api: AnyObject {} + +@Instantiable +public final class Repository: Instantiable { + public init(api: any Api) { + self.api = api + } + + @Instantiated public let api: any Api +} + +@Instantiable(generateMock: true) +public final class Child: Instantiable { + public init(repository: Repository) { + self.repository = repository + } + + @Instantiated public let repository: Repository +} + +@Instantiable(generateMock: true) +public final class Parent: Instantiable { + public init(childBuilder: Instantiator) { + self.childBuilder = childBuilder + } + + @Instantiated public let childBuilder: Instantiator +} + +@Instantiable(generateMock: true) +public final class OtherParent: Instantiable { + public init(childBuilder: Instantiator) { + self.childBuilder = childBuilder + } + + @Instantiated public let childBuilder: Instantiator +} + +@Instantiable(generateMock: true) +public final class Top: Instantiable { + public init(parent: Parent, otherParent: OtherParent) { + self.parent = parent + self.otherParent = otherParent + } + + @Instantiated public let parent: Parent + @Instantiated public let otherParent: OtherParent +} diff --git a/Scripts/generate-time-check.py b/Scripts/generate-time-check.py index 9e0846fde5..7335c15be3 100644 --- a/Scripts/generate-time-check.py +++ b/Scripts/generate-time-check.py @@ -1645,12 +1645,12 @@ def plugin_command(tool, name, direct, beneath, sources, output, environment): return [tool, inputs, "--swift-manifest", manifest, "--active-compilation-conditions", "DEBUG"] + UNEXPANDED_BUILD_SETTINGS -def generate(tool, modules, sources, output, variables={}, time_limit=None, under_plugin=None, views_refer_to_modules=False): +def generate(tool, modules, sources, output, variables={}, time_limit=None, under_plugin=None, views_refer_to_modules=False, packages={}): """Runs `generate` for each module into `output`, with `variables` added to its environment; returns (wall seconds, CPU seconds, peak bytes): the times summed over the modules, the peak the largest of the modules' processes' maximum resident set sizes. A module's process still running after `time_limit` seconds is killed, which fails the run. With `under_plugin`, a module's name, runs `generate` for that module alone, as the SwiftPM - plugin runs it.""" + plugin runs it. `packages` names the package of a module that is not in the one package the others share.""" os.makedirs(output, exist_ok=True) environment = dict(os.environ, TMPDIR=output, **variables) direct = {name: dependencies for name, dependencies, _ in modules} @@ -1664,7 +1664,7 @@ def generate(tool, modules, sources, output, variables={}, time_limit=None, unde write(f"{output}/{name}.csv", f"{sources}/{name}/Types.swift\n") command = [tool, "generate", f"{output}/{name}.csv", "--combined-output", f"{output}/{name}.generated.swift", "--module-info-output", f"{output}/{name}.safedi", "--active-compilation-conditions", "DEBUG", - "--module-name", name, "--package-name", "GenerateTimeCheck"] + "--module-name", name, "--package-name", packages.get(name, "GenerateTimeCheck")] if dependencies: write(f"{output}/{name}.dependencies.csv", "".join(f"{output}/{dependency}.safedi\n" for dependency in dependencies)) write(f"{output}/{name}.transitive.csv", "".join(f"{output}/{module}.safedi\n" for module in beneath[name]))