csharpc

05 — Testing

Differential testing against .NET

csharpc’s correctness criterion is simple: a program compiled by csharpc must behave exactly like the same program run on .NET. The test suite enforces this directly. Real .NET is the oracle.

                  ┌─▶ dotnet run sample.cs  ──▶ sample.expected (+ sample.exitcode)   [recorded once, checked in]
tests/samples/  ──┤
  sample.cs       └─▶ csharpc sample.cs ──▶ ./sample ──▶ stdout + exit code ──▶ diff
  • Recording uses .NET 10+ file-based apps: dotnet run sample.cs compiles and runs a single file with no project. Its stdout becomes sample.expected. A nonzero exit code is written to sample.exitcode (absent means 0).

  • Checking builds csharpc (Release), compiles each sample at -O2 (or $CSHARPC_OPT), runs it with a timeout ($CSHARPC_TEST_TIMEOUT, default 20 s), and requires byte-identical stdout and the same exit code. stderr isn’t compared, because the .NET stack trace is out of scope.

  • Rejection samples pin down programs csharpc must refuse cleanly: valid C# that used to crash the compiler and now gets an explicit diagnostic (283_unsupported_field_in_base, 284_recursive_generic_expansion). A sample.diagnostics file holds csharpc’s expected stderr (paths relative to tests/samples/); the compiler must exit with 1 and print exactly that. It is csharpc’s own specification, written from the compiler’s output, not a .NET recording. --regen still records sample.expected from .NET, which shows that the program is valid C#.

There are no hand-written expected outputs. That rules out a whole class of mistakes: the expected 0.30000000000000004, -2147483648 or 1E-05 is whatever .NET actually prints.

Running

tests/run.sh                    # all samples
tests/run.sh 06                 # samples whose name contains "06"
CSHARPC_OPT=-O0 tests/run.sh    # unoptimized codegen (catches bugs that the optimizer hides)
tests/run.sh --all-opts         # -O0 and -O2
tests/run.sh --shard 0/4        # one deterministic slice of the sample list (what CI runs)
tests/run.sh --repeat 20 544    # flake hunting; the run fails if any repeat fails
tests/run.sh --list             # print the selected names and do not build
tests/run.sh --regen            # re-record .expected/.exitcode from real .NET
tests/run.sh --regen 07         # re-record a single sample
tests/run.sh --via-il -O0 07    # the program as IL: `dotnet build 07*.cs`, then `csharpc 07*.dll`

CSHARPC_JOBS=N tests/run.sh compiles and runs up to N samples at once (default 1). The output is what a sequential run prints, in sample order, with the same PASS/FAIL/SKIP lines, per-binary timeout and exit code; every sample gets scratch files of its own. The first sample of each pass (-O0, -O2) runs alone so the shared runtime/corelib cache in ~/.cache/csharpc is filled once, and the samples listed in tests/serial-samples.txt run alone too: those that observe their neighbours (connecting to a port that was just closed on purpose, wall-clock windows of a few tens of milliseconds, inotify). Add a sample there if it flakes only when run next to others. --repeat and --via-il always run one sample at a time. CI uses 3 on every platform (jobs_for_platform in tools/ci-plan.sh).

--via-il runs the same samples against the same recordings through csc first, as the dotnet pipeline hands csharpc its input (ADR 0010): each sample is built with dotnet build NAME.cs (the build dotnet run NAME.cs makes, with its runtimeconfig.json) and csharpc compiles NAME.dll, Main included, from IL. Samples with a .diagnostics file pass when csharpc rejects the assembly (exit 1, any diagnostic). CSHARPC_IL_BUILD=dir keeps the SDK builds between runs (a sample is rebuilt when its .cs is newer) and CSHARPC_IL_JOBS=N builds N samples at once (default 2). Linux hosts only. CI runs it in the informational Program as IL workflow; tests/il-main-known-failures.txt lists the samples known to fail that way, and a shard fails on a sample outside the list or a listed one that passes (tests/il-main-check.sh).

CSHARPC_NATIVE=path/to/csharpc-native runs the suite with the compiler csharpc built from itself (tools/bootstrap/selfhost.sh, M6) instead of the managed one: the samples and recordings are the same, so a difference is a csharpc that miscompiled csharpc. The Bootstrap workflow runs it in 8 shards for the -O0 and the -O2 native compiler, with tools/bootstrap/native-known-failures.txt as the list (same check as above); tools/bootstrap/native-diff.sh shows where the two compilers’ IR differs.

Environment: DOTNET (path to the dotnet executable; the .NET 11 SDK must be first on PATH), CSHARPC_OPT, CSHARPC_TEST_TIMEOUT, CSHARPC_TEST_TARGET (cross-target runs, see below).

Platforms

Expectations are recorded from .NET on Linux and checked on every CI platform (Linux x86-64, Linux ARM64, macOS ARM64, Windows x64). A test whose behaviour differs under real .NET on another OS too (for example a DllImport("libm.so.6"), a Linux soname that .NET can’t load on macOS) is listed with its reason in tests/platform-skips.txt and reported as SKIP ... (platform-dependent ...) there; never list a test because csharpc differs from .NET. run.sh resolves $TMPDIR to a path without symlinks (macOS’s /var/folders is reached through /var -> /private/var, which getcwd would expose). On macOS the scripts need bash 4+ and GNU coreutils (brew install bash coreutils, with $(brew --prefix coreutils)/libexec/gnubin on PATH); tests/debuginfo.sh drives gdb and is Linux-only.

tests/slicer.sh is the test of the opt-in mixed-mode CoreLib route for the types that are not shipped yet (the shipped ones, List<T> so far, run in the ordinary suite) (ADR 0023, issue #191 part B): it slices Guid, StringBuilder and Number out of the framework’s System.Private.CoreLib (tools/il-first/slicer, needs the Mono.Cecil of the ILLink tasks package) and runs samples compiled against the slice with the recordings made on real .NET. Off by default, so not part of the merge gate.

Windows. The scripts run in Git Bash (tests/platform.sh holds the per-OS helpers; checkouts must keep LF line endings, core.autocrlf=false). .NET on Windows ends Console.WriteLine with Environment.NewLine, "\r\n", so the expected stdout is the recording with every "\n" turned into "\r\n", compared byte for byte (csharpc writes the standard streams in binary mode). An unhandled exception ends .NET with exit code 0xE0434352, which Git Bash reports as 127 (the conformance runner, in Python, maps it back to the recorded 134). tests/check-oracle.sh runs every test under real dotnet run on the machine and checks that derivation; CI runs it on Windows. Tests for which it doesn’t hold are listed in tests/platform-skips.txt with the reason; most are marked live:, which records their expected output and exit status from real .NET on the test machine at test time instead of skipping them (programs that write their own bare "\n", AppendLine lengths, Windows paths, TZ, which .NET ignores on Windows, DllImport("libc"), culture data from another ICU version).

Culture. The recordings come from Linux in the C locale, where the current culture is the invariant one (with ICU’s root collation). csharpc follows the user’s culture like .NET (19 — Globalization), so the scripts pin it on both sides: on Linux tests/platform.sh exports LC_ALL=C.UTF-8 (and unsets LC_MESSAGES/LANGUAGE); on macOS and Windows, where the culture comes from the system settings, real .NET runs with tests/oracle-hook (a startup hook that makes the invariant culture current) and csharpc programs are compiled together with tests/culture-pin/CulturePin.cs (a [ModuleInitializer] doing the same). DOTNET_SYSTEM_GLOBALIZATION_INVARIANT is not equivalent: it also makes comparisons ordinal. A sample with a NAME.env file (VAR=value lines, e.g. LC_ALL=pt_BR.UTF-8) is recorded and run with that environment on both sides instead, without the pin.

NativeAOT as the oracle. csharpc is a drop-in for NativeAOT, so where NativeAOT and the JIT print different things for the same program, csharpc matches NativeAOT. Such a sample has a NAME.aot file (one line naming the difference, e.g. string.IsInterned: the JIT interns every literal up front, NativeAOT only what string.Intern added). tests/run.sh --regen records it from its dotnet publish -p:PublishAot=true build instead of dotnet run, and tests/check-oracle.sh checks it the same way on every OS (platform_aot_run in tests/platform.sh). NativeAOT has no startup hooks, so on macOS and Windows its culture is the user’s: an .aot sample must not print culture-dependent text.

WebAssembly. CSHARPC_TEST_TARGET=wasm32-wasip1 makes tests/run.sh, tests/conformance.sh and tests/programs.sh compile every test with --target wasm32-wasip1 and run it with tests/wasm-run.sh: wasmtime with the environment inherited, the host file system preopened at / (csrt follows $PWD as the current directory) and an 8 MiB wasm stack. It needs the WASI SDK (WASI_SDK_PATH, LLVM 18: wasi-sdk 24) and wasmtime on PATH (WASMTIME overrides). The expected output is the Linux recording, unchanged: there is no .NET for plain WASI to record with, and a WASI build is meant to behave like a native one. An unhandled exception traps, and wasmtime exits with 134, the recorded status. Tests whose recorded behaviour WebAssembly can’t have are listed under wasi in tests/platform-skips.txt, each with its reason: they need threads, assume LP64 C types in P/Invoke signatures, or print errno numbers. CI runs the three suites this way in the test (wasm32-wasi) job. It also runs 310_gc_roots_in_locals with CSRT_GC_STRESS=1 (a collection at every allocation), which checks that the compiler’s GC root spilling is complete (ADR 0011).

The opt-in generational nursery (--gc-nursery) has its own workflow, GC nursery (.github/workflows/nursery.yml, Linux x86-64, outside the merge bar): the differential suite at -O0 and -O2 and the conformance corpus with CSHARPC_GC_NURSERY=1 CSRT_GC_NURSERY_MB=1 (a minor collection every MiB), then the collection-heavy samples under CSRT_GC_STRESS=50. A missing write barrier shows up there as wrong output or a crash (ADR 0004).

The informational workflows (GC concurrent, GC nursery, Program as IL, Bootstrap, Benchmarks) each have a concurrency group per workflow and ref with cancel-in-progress, so a burst of merges to main leaves only the newest commit’s run, queued or running, and none of them gates a merge. Benchmarks, GC concurrent and GC nursery do not run on a push to main: a merge used to start two 120-minute benchmark jobs and two more suites that competed with every open PR’s merge-bar jobs for the hosted runners. They run weekly (Mondays 06:00, 08:00 and 09:00 UTC, with TechEmpower at 07:00), on demand, and on their measurement branches: ci/perf*, ci/bench* and ci/m7-* for Benchmarks, ci/gc-* and ci/m7-gc-concurrent* for GC concurrent, ci/nursery* for GC nursery, and ci/m7-* or ci/techempower* for TechEmpower (a feature branch that merges main must not start the load tests). Any other ci/** branch, such as a flake hunt, leaves those runners alone.

Failure output shows the compile errors (including CSLLVM0001 “not supported yet” diagnostics) or the first lines of a unified diff between the expected and actual stdout.

CI

The merge bar for a PR that touches src/** also includes the Bootstrap checks “Roslyn hosted from IL” and “csharpc compiles csharpc (-O0)” / ”(-O2)” (.github/workflows/bootstrap.yml on pull_request): the five jobs below do not compile Roslyn or csharpc itself, and Bootstrap was red on main twice in two days while every PR gate was green. The 16 native-suite shards and the two heavy-samples jobs of that workflow run nightly on main, on ci/m6-** pushes and on dispatch, not on every merge (#406).

The merge bar is the five jobs test (x86-64), test (arm64), test (macos-arm64), test (windows-x64) and test (wasm32-wasi) in .github/workflows/ci.yml. A full run (push to main or ci/**, a pull request, or a manual dispatch of that workflow) splits the differential suite across shards and runs size, conformance, programs, projects, the Windows oracle and the IL front-end beside them. Each test (<platform>) job is only the aggregate: it fails if any shard or the suites job failed, or if the shard manifests do not list every sample at -O0 and at -O2 exactly once (tools/ci-plan.sh coverage). Shards are a round-robin over the LC_ALL=C sorted sample names (tests/run.sh --shard INDEX/COUNT).

Each shard compiles and runs several samples at once (CSHARPC_JOBS, 3 on every platform), which makes it 2-3x faster than a sequential shard, so a platform needs fewer of them: x86-64 and windows-x64 4, the other platforms 3 (17 differential jobs; raised from 3/2 in #403, when the grown suite made shards take 40-75 minutes against the 100-minute job limit). The queue, not the work, is the usual delay (runner minutes are capped across the repository), so the counts aim at finishing near the platform’s suites job rather than at the shortest shard. The suites jobs (size, conformance, programs, projects, IL; 11-21 minutes) set the wall clock of an unqueued gate.

macOS runners are the scarce ones: the account gets only a few at once, and every full run needs several, so with a handful of pull requests open the macOS shards queued for hours (2026-11-25). A pull request therefore runs the macOS differential suite at -O2 only, in 2 shards (REDUCED_PR_PLATFORMS in tools/ci-plan.sh), and test (macos-arm64) checks that every sample ran at -O2 exactly once. Every other platform, every push to main or ci/**, and the nightly full run on main (schedule, 04:00 UTC) run both opts everywhere. The trade-off: a macOS-only -O0 difference is caught by the nightly run, not by the PR, and a merge that reuses the PR’s gate (the identical-tree skip below) can publish the rolling latest-main prerelease before that night’s run.

A push or pull request that only touches docs/**, *.md, .github/workflows/pages.yml (the docs site’s deploy), or LICENSE / COPYING / NOTICE / AUTHORS skips the compiler suite when some ancestor of that commit already has the five test checks green. The same five job names still run and pass, which is what a required check needs; paths-ignore would leave them pending. The skip does not apply when that ancestor’s gate is missing, failed, or cancelled (a docs push that cancels an in-progress full run therefore runs the suite). main ignores a CI-Only: trailer and a ci/targets file, so those cannot drop the gate.

A push to main whose tree is identical to the tree of a commit that already has the five test checks green skips the suite the same way (mode tree in tools/ci-plan.sh; the gate jobs print the commit they rely on). The candidates are the pushed commit itself (fast-forward), its parents (the merged PR’s head is the second parent of a merge commit) and the heads GitHub lists for it. A candidate counts only when it descends from the commit main pointed at before the push: a pull request’s checks test its merge with the base at that time, which is the head’s own tree exactly when the head already contained that base, and main only moves forward. A PR that was behind main when it was merged produces a different tree and runs the full suite. Unlike a docs-only skip, such a run publishes: it has a tree (identical tested tree) job, which exists only in that mode, and tools/ci-plan.sh release-gate accepts it in place of the sharded diff ( jobs (the five test checks must still be success). The Release workflow builds and smoke-tests the pushed commit itself.

Targeted runs

A targeted run is partial. Its jobs are named partial (<platform>), and it does not report test (<platform>) as success, so it is not the merge bar. Release publishes only after a full gate (successful diff ( shards for every platform, or the tree job of an identical-tree skip, and the five test checks); a partial or docs-only CI success does not publish.

Two ways to start one:

  1. Push a ci/** branch (the agent checkout cannot dispatch workflows: gh workflow run is HTTP 403). Put the spec in the tip commit’s message, or in a ci/targets file, or both (trailer keys win). The run title shows the commit message, so keep the trailer on the commit you push.

    CI-Only: filter=544_blocking_collection platforms=macos-arm64 repeat=20

    ci/targets (not read on main or on pull requests):

    filter=544_blocking_collection
    platforms=macos-arm64
    opt=-O0
    repeat=20
    skip_other=true
  2. Actions → CI (targeted) → Run workflow, for a token that has actions: write. The same keys are the inputs. The workflow is not named CI, so it cannot turn the merge-bar checks green and it does not trigger a release.

filter is a sample-name substring. platforms is all or a comma-separated list of x86-64, arm64, macos-arm64, windows-x64, wasm32-wasi. opt is all, -O0, or -O2. repeat is 1–50 and requires a filter (a repeat of the whole suite is refused). skip_other defaults to true on a targeted run, which skips size, conformance, programs, projects, the oracle and IL. The run must narrow the suite (a filter, a platform subset, one opt level, or a repeat); a bare CI-Only: is rejected. Partial runs are one job per platform, not sharded, so a repeat’s log stays together. Delete ci/targets before merging the branch.

Adding a sample

  1. Write tests/samples/NN_topic.cs as an ordinary C# program. Top-level statements are fine. Start with a comment explaining what it tests.
  2. Make sure it compiles and runs on .NET: dotnet run tests/samples/NN_topic.cs.
  3. Record it: tests/run.sh --regen NN_topic. Commit both the .cs and .expected files (and .exitcode if present).
  4. Run tests/run.sh NN_topic.

Guidelines:

  • Make it deterministic. No time, randomness, environment, thread scheduling or hash-code-order output.
  • Mind the culture. Tests run with the invariant culture current (see above). To test a culture, use it explicitly (CultureInfo.GetCultureInfo("de-DE"), or set CurrentCulture), or give the sample a NAME.env; culture data can differ between ICU versions, so such samples are live: on macOS and Windows.
  • Avoid compile-time folding hiding runtime paths. Roslyn folds constant expressions, and so does csharpc’s ToStringValue. To test runtime behavior, route values through variables or args.Length (as 11_divide_by_zero.cs does). Also note that C# rejects constant conversions that overflow ((short)40000 is error CS0221 without unchecked).
  • Keep warnings off stdout. dotnet run prints build warnings to stdout, where they would land in .expected. Avoid warning-producing code (or suppress it with #pragma warning disable), and check the recorded file.
  • Testing a failure path: let the exception go unhandled. Both runtimes exit with 134, and stdout up to that point must match (09–12).
  • Samples ahead of the compiler are fine. A sample may use a feature csharpc doesn’t support yet. It fails with CSLLVM0001 until the feature lands, which makes the suite a to-do list.

Exit codes

situation .NET csharpc
normal completion, void Main 0 0
int Main / top-level return n n n
Environment.Exit(n) n n (stdout is flushed first)
unhandled exception 134 (SIGABRT) 134 (abort() in csrt)
C# compile error (dotnet run) 1 (build failed) csharpc exits 1 and no binary is produced

Other checks

  • Every module is run through the LLVM verifier before optimization. Invalid IR is an internal compiler error (exit 70, <output>.invalid.ll written for inspection).
  • --dump-cfg and --emit llvm-ir (at -O0 and -O2) are the main debugging tools. When libLLVM crashes, use CSHARPC_TRACE=1 and gdb (07-spike-log.md).
  • tests/size.sh compiles the small programs in tests/size/ with the default options and fails when one exceeds its budget in tests/size/budgets/<program>.txt (one file per program, so PRs that move different programs’ budgets never conflict; one <platform> <program> <bytes> line per platform, size + max(4 KiB, 3 %): file sizes move in whole pages; the reasons for the numbers are comments in the same file; a new program adds both <program>.cs and budgets/<program>.txt). Being smaller than .NET is part of the standing goal (06-roadmap.md), so a size regression is a test failure. Platforms without budgets print the sizes (tests/size.sh --print gives budget lines). On Linux it also runs tools/checksec.sh --check on the same executables, so a size win can’t come from dropping hardening: full RELRO, NX stack, separate code (no 4 KiB file page shared between code and anything else) and, on AArch64, a segment layout that loads with 64 KiB pages.