diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7e72805..b2ad6a96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,88 +6,12 @@ on: pull_request: branches: [main] -env: - CARGO_TERM_COLOR: always - jobs: build: + # Track from the committed C seed: cc and POSIX tools only. runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install LLVM - run: | - wget https://apt.llvm.org/llvm.sh - chmod +x llvm.sh - sudo ./llvm.sh 22 - sudo apt-get install -y libpolly-22-dev zlib1g-dev libzstd-dev || true - - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - - - name: Cache cargo - uses: actions/cache@v4 - with: - path: | - ~/.cargo/registry - ~/.cargo/git - target - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - - - name: Build - run: cargo build --release - - - name: Run tests - run: cargo test - - - name: Check examples - run: | - for f in examples/*.trk; do - echo "Checking $f..." - if [[ "$f" == *"_err.trk" ]]; then - if ./target/release/track check "$f" 2>/dev/null; then - echo "Error: Expected rejection for $f but check succeeded!" - exit 1 - else - echo "✓ Rejection test passed for $f" - fi - else - ./target/release/track check "$f" - fi - done - - - name: Native compiler package (yard) - run: | - scripts/embed_runtime.sh --check - (cd compiler && ../target/release/yard check) - (cd compiler && ../target/release/yard build) - (cd compiler && ../target/release/yard test) - for f in compiler/src/*.trk; do - echo "Checking $f..." - ./target/release/track check "$f" - done - - - name: Bootstrap fixed point from Rust (stage0 -> stage3, then native) - run: YARD=./target/release/yard scripts/bootstrap.sh --from-rust - - - name: Compiler sources are warning-clean - run: ./build/bootstrap/stage3/trackc check --deny-warnings compiler/src/main.trk - - - name: Self-hosting from .trk alone (native, no C toolchain) - run: scripts/selfhost.sh - - - name: Verify versions - run: | - ./target/release/track --version | grep -q "1.0.0" - ./target/release/yard --version | grep -q "1.0.0" - ./build/bootstrap/stage3/trackc --version | grep -q "1.0.0" - echo "✓ versions ok" - - - seed-bootstrap: - # Track from the committed C seed: cc and POSIX tools only, no Rust. - runs-on: ubuntu-latest + env: + TRACKC: ${{ github.workspace }}/build/bootstrap/stage3/trackc steps: - uses: actions/checkout@v4 @@ -104,34 +28,51 @@ jobs: - name: Seed is up to date run: env PATH=/usr/bin:/bin scripts/update_seed.sh --check - - name: Compiler sources are warning-clean - run: ./build/bootstrap/stage3/trackc check --deny-warnings compiler/src/main.trk + - name: Compiler and yard sources are warning-clean + run: | + env PATH=/usr/bin:/bin "$TRACKC" check --deny-warnings compiler/src/main.trk + env PATH=/usr/bin:/bin "$TRACKC" check --deny-warnings tools/yard/main.trk - - name: yard (written in Track) passes its suite + - name: Every compiler source checks; yard checks and builds the compiler package run: | - ./build/bootstrap/stage3/trackc check --deny-warnings tools/yard/main.trk - env PATH=/usr/bin:/bin TRACKC="$PWD/build/bootstrap/stage3/trackc" tests/yard/run.sh + for f in compiler/src/*.trk; do + env PATH=/usr/bin:/bin "$TRACKC" check "$f" || { echo "check failed: $f"; exit 1; } + done + mkdir -p build + env PATH=/usr/bin:/bin "$TRACKC" build --native tools/yard/main.trk -o build/yard + (cd compiler && env PATH=/usr/bin:/bin TRACKC="$TRACKC" ../build/yard check) + (cd compiler && env PATH=/usr/bin:/bin TRACKC="$TRACKC" ../build/yard build) - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 + - name: Test suite (tests/run.sh) + run: env PATH=/usr/bin:/bin tests/run.sh -j "$(nproc)" -K - - name: Install LLVM - run: | - wget https://apt.llvm.org/llvm.sh - chmod +x llvm.sh - sudo ./llvm.sh 22 - sudo apt-get install -y libpolly-22-dev zlib1g-dev libzstd-dev || true + - name: yard (written in Track) passes its suite + run: env PATH=/usr/bin:/bin tests/yard/run.sh - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - with: - components: rustfmt, clippy + - name: trackc lsp passes its recorded sessions + run: env PATH=/usr/bin:/bin tests/lsp/run.sh "$TRACKC" - - name: Check formatting - run: cargo fmt --all -- --check + - name: Self-hosting from .trk alone (native, no C toolchain) + run: env PATH=/usr/bin:/bin scripts/selfhost.sh "$TRACKC" - - name: Run clippy - run: cargo clippy -- -D warnings + - name: Check examples + run: | + for f in examples/*.trk; do + if [[ "$f" == *"_err.trk" ]]; then + if env PATH=/usr/bin:/bin "$TRACKC" check "$f" >/dev/null 2>&1; then + echo "Error: expected rejection for $f but check succeeded" + exit 1 + fi + echo "✓ rejected $f" + else + env PATH=/usr/bin:/bin "$TRACKC" check "$f" + fi + done + - name: Verify versions + run: | + mkdir -p build + env PATH=/usr/bin:/bin "$TRACKC" build --native tools/yard/main.trk -o build/yard >/dev/null + "$TRACKC" --version | grep -q "1.0.0" + build/yard --version | grep -q "1.0.0" + echo "✓ versions ok" diff --git a/.gitignore b/.gitignore index 74d5e926..83db43b1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ +# yard writes target/ (target/_yard_root.trk, target/objects/) in the project it builds /target /tmp_benchmark *.o *.out +!tests/cases/**/*.out *.exe # IDE diff --git a/CHANGELOG.md b/CHANGELOG.md index b6ec8db8..ff59f0c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Removed +- **All Rust code.** The Rust stage 0 compiler, the Rust yard and the Rust + LSP (`src/`), `Cargo.toml`, `Cargo.lock` and the cargo test suites + (`tests/*.rs`) are deleted. Track builds from the C seed with + `scripts/bootstrap.sh` (cc -> stage1..3 -> native) and tests with + `tests/run.sh`, `tests/yard/run.sh` and `tests/lsp/run.sh`; yard is + `tools/yard/*.trk` and the language server is `trackc lsp`. + `scripts/bootstrap.sh --from-rust` is gone, and `bench/` compares + trackc's C and native backends. + ### Added - **Runtime written in Track** (`compiler/rt/*.trk`): every function of `runtime/track_runtime.c` on raw syscalls, no libc. `trackc build diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 12d8a831..00000000 --- a/Cargo.lock +++ /dev/null @@ -1,1592 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - -[[package]] -name = "anyhow" -version = "1.0.103" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" - -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" - -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "auto_impl" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdcb70bdbc4d478427380519163274ac86e52916e10f0a8889adf0f96d3fee7" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "beef" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytes" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" - -[[package]] -name = "cc" -version = "1.2.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cranelift-bforest" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e986f88294c33bf0e58ffb5bc65621251d4254a43abac04df651594bbee8c75" -dependencies = [ - "cranelift-entity", -] - -[[package]] -name = "cranelift-codegen" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9e785b0978305cb2921cb86c2abbc8e1bc45408710bbcc2ac6a17bd37e454a" -dependencies = [ - "bumpalo", - "cranelift-bforest", - "cranelift-codegen-meta", - "cranelift-codegen-shared", - "cranelift-control", - "cranelift-entity", - "cranelift-isle", - "gimli", - "hashbrown 0.14.5", - "log", - "regalloc2", - "rustc-hash", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-codegen-meta" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb4184add80d5da946190f3ad7c3babab468d44eae09dcef0f42c09268d62a2" -dependencies = [ - "cranelift-codegen-shared", -] - -[[package]] -name = "cranelift-codegen-shared" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab78a22ec023f93fd580080a95342470b575228b019f5f13b76536703d337383" - -[[package]] -name = "cranelift-control" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8c3058104a9d495034ffca37fa0dfe735bd4a62373ac533229ff7a8dbe785a7" -dependencies = [ - "arbitrary", -] - -[[package]] -name = "cranelift-entity" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecc6fc033e07a240c8bb902503ad7d9d00671510b345f6c390f2b73863acabd" - -[[package]] -name = "cranelift-frontend" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9c3ac4bd3168d7dadd95acbdc547b461a1ef5ddc472a95d313909b4739ac85" -dependencies = [ - "cranelift-codegen", - "log", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-isle" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19ac03f29eb9606a39a250a95320d9a187e3c0a7997f41e494725dc6277ddd79" - -[[package]] -name = "cranelift-jit" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90d536bc731165d58bc9faeb8e52d9643d97822b59d35b98578f86c3a3dce07" -dependencies = [ - "anyhow", - "cranelift-codegen", - "cranelift-control", - "cranelift-entity", - "cranelift-module", - "cranelift-native", - "libc", - "log", - "region", - "target-lexicon", - "wasmtime-jit-icache-coherence", - "windows-sys 0.52.0", -] - -[[package]] -name = "cranelift-module" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0e621bfff94ef7f1ac282c2457b42a184ebedecd711867348c8593e5ee4ff0a" -dependencies = [ - "anyhow", - "cranelift-codegen", - "cranelift-control", -] - -[[package]] -name = "cranelift-native" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50deb0661ed42f3695ce9ac7a71ae5491e1bd90f4e40871b74a75202c7f1e02" -dependencies = [ - "cranelift-codegen", - "libc", - "target-lexicon", -] - -[[package]] -name = "cranelift-object" -version = "0.108.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7f77f96cf6fd7f091e1aca73604fa861e4a56cf96a8f90d44ee2f161369465" -dependencies = [ - "anyhow", - "cranelift-codegen", - "cranelift-control", - "cranelift-module", - "log", - "object 0.33.0", - "target-lexicon", -] - -[[package]] -name = "crc32fast" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "dashmap" -version = "5.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" -dependencies = [ - "cfg-if", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - -[[package]] -name = "displaydoc" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "fallible-iterator" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "flate2" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-macro" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "futures-sink" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "gimli" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" -dependencies = [ - "fallible-iterator", - "indexmap", - "stable_deref_trait", -] - -[[package]] -name = "hashbrown" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" -dependencies = [ - "ahash", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", -] - -[[package]] -name = "inkwell" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7decbc9dfa45a4a827a6ff7b822c113b1285678a937e84213417d4ca8a095782" -dependencies = [ - "bitflags 2.13.0", - "inkwell_internals", - "libc", - "llvm-sys", - "thiserror", -] - -[[package]] -name = "inkwell_internals" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cfe97ee860815a90ed17e09639513269e39420a7440f3f4c996f238c514cf8d" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "llvm-sys" -version = "221.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2abcc34a3b190f03c2a61b555f218f529589ff13657bdd2ff8ac3e85f2abe6bb" -dependencies = [ - "anyhow", - "cc", - "lazy_static", - "libc", - "regex-lite", - "semver", -] - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - -[[package]] -name = "logos" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7251356ef8cb7aec833ddf598c6cb24d17b689d20b993f9d11a3d764e34e6458" -dependencies = [ - "logos-derive", -] - -[[package]] -name = "logos-codegen" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59f80069600c0d66734f5ff52cc42f2dabd6b29d205f333d61fd7832e9e9963f" -dependencies = [ - "beef", - "fnv", - "lazy_static", - "proc-macro2", - "quote", - "regex-syntax", - "syn", -] - -[[package]] -name = "logos-derive" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24fb722b06a9dc12adb0963ed585f19fc61dc5413e6a9be9422ef92c091e731d" -dependencies = [ - "logos-codegen", -] - -[[package]] -name = "lsp-types" -version = "0.94.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66bfd44a06ae10647fe3f8214762e9369fd4248df1350924b4ef9e770a85ea1" -dependencies = [ - "bitflags 1.3.2", - "serde", - "serde_json", - "serde_repr", - "url", -] - -[[package]] -name = "mach" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b823e83b2affd8f40a9ee8c29dbc56404c1e34cd2710921f2801e2cf29527afa" -dependencies = [ - "libc", -] - -[[package]] -name = "memchr" -version = "2.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "object" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8dd6c0cdf9429bce006e1362bfce61fa1bfd8c898a643ed8d2b471934701d3d" -dependencies = [ - "crc32fast", - "hashbrown 0.14.5", - "indexmap", - "memchr", -] - -[[package]] -name = "object" -version = "0.36.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" -dependencies = [ - "flate2", - "memchr", - "ruzstd", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.0", -] - -[[package]] -name = "regalloc2" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad156d539c879b7a24a363a2016d77961786e71f48f2e2fc8302a92abd2429a6" -dependencies = [ - "hashbrown 0.13.2", - "log", - "rustc-hash", - "slice-group-by", - "smallvec", -] - -[[package]] -name = "regex" -version = "1.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-lite" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "region" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877e54ea2adcd70d80e9179344c97f93ef0dffd6b03e1f4529e6e83ab2fa9ae0" -dependencies = [ - "bitflags 1.3.2", - "libc", - "mach", - "winapi", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "ruzstd" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fad02996bfc73da3e301efe90b1837be9ed8f4a462b6ed410aa35d00381de89f" -dependencies = [ - "twox-hash", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.150" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_repr" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "slice-group-by" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "826167069c09b99d56f31e9ae5c99049e932a98c9dc2dac47645b08dbbf76ba7" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" - -[[package]] -name = "socket2" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "syn" -version = "2.0.118" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "target-lexicon" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" - -[[package]] -name = "thiserror" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tokio" -version = "1.52.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" -dependencies = [ - "bytes", - "libc", - "mio", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio-util" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.22.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" -dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "toml_write", - "winnow", -] - -[[package]] -name = "toml_write" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" - -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "futures-core", - "futures-util", - "pin-project", - "pin-project-lite", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-lsp" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4ba052b54a6627628d9b3c34c176e7eda8359b7da9acd497b9f20998d118508" -dependencies = [ - "async-trait", - "auto_impl", - "bytes", - "dashmap", - "futures", - "httparse", - "lsp-types", - "memchr", - "serde", - "serde_json", - "tokio", - "tokio-util", - "tower", - "tower-lsp-macros", - "tracing", -] - -[[package]] -name = "tower-lsp-macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84fd902d4e0b9a4b27f2f440108dc034e1758628a9b702f8ec61ad66355422fa" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "track" -version = "1.0.0" -dependencies = [ - "cranelift-codegen", - "cranelift-frontend", - "cranelift-jit", - "cranelift-module", - "cranelift-object", - "inkwell", - "logos", - "object 0.36.7", - "regex", - "serde", - "serde_json", - "target-lexicon", - "tokio", - "toml", - "tower-lsp", -] - -[[package]] -name = "twox-hash" -version = "1.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" -dependencies = [ - "cfg-if", - "static_assertions", -] - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", - "serde_derive", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasmtime-jit-icache-coherence" -version = "21.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dcbcaa9994bfd411256bbeedfa7ebc69d5fbd3892c49456af64111c44d2f9fd" -dependencies = [ - "anyhow", - "cfg-if", - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "yoke" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zmij" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index 538d2c15..00000000 --- a/Cargo.toml +++ /dev/null @@ -1,44 +0,0 @@ -[package] -name = "track" -version = "1.0.0" -edition = "2024" - -[[bin]] -name = "track" -path = "src/main.rs" - -[[bin]] -name = "yard" -path = "src/yard_bin.rs" - -[[bin]] -name = "track-lsp" -path = "src/lsp_bin.rs" - -[lib] -name = "track" -path = "src/lib.rs" - -[dependencies] -logos = "0.14" -toml = "0.8" -serde = { version = "1", features = ["derive"] } -tokio = { version = "1", features = ["full"] } -tower-lsp = { version = "0.20", features = ["proposed"] } -serde_json = "1" -regex = "1" - -# Cranelift -cranelift-codegen = "0.108" -cranelift-frontend = "0.108" -cranelift-module = "0.108" -cranelift-object = "0.108" -cranelift-jit = "0.108" -target-lexicon = "0.12" -object = "0.36" - -inkwell = { version = "0.9.0", features = ["llvm22-1"], optional = true } - -[features] -default = [] -llvm = ["dep:inkwell"] diff --git a/README.md b/README.md index dc2540e1..a284df95 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ - **No Garbage Collector.** Resource lifecycles are verified at compile time; there is no collector and only a small runtime, in C or in Track. - **Linear Ownership.** Rejects use-after-free and double-free. The self-hosted compiler infers where each allocation's life ends and places it on the stack or frees it there ([docs/lifecycles.md](docs/lifecycles.md)). - **Lexical Lenses.** Scoped mutable access without manual pointer arithmetic or ownership transfer. -- **Native Backend.** `trackc build --native` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. The Rust bootstrap compiler uses Cranelift. +- **Native Backend.** `trackc build --native` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. ## Hello World @@ -51,27 +51,28 @@ curl -fsSL https://raw.githubusercontent.com/dev-dami/track/main/scripts/install ### Build from Source -Requires Rust (2021 edition). +Requires a C compiler (`cc`) and POSIX tools; nothing else. ```bash -# Build release binaries -cargo build --release - -# Run installer script -./scripts/install.sh +scripts/bootstrap.sh # cc -> stage1..3 -> native; trackc is build/bootstrap/stage3/trackc +build/bootstrap/stage3/trackc build --native tools/yard/main.trk -o yard # yard, written in Track +./scripts/install.sh # or: bootstrap and install trackc + yard ``` ## Usage -### Single-File Compiler (`track`) +### Compiler (`trackc`) ```bash # Type-check a source file -track check examples/hello.trk +trackc check examples/hello.trk -# Compile to native executable -track build examples/hello.trk +# Compile to an executable (through C, or natively with --native) +trackc build examples/hello.trk -o hello ./hello + +# Language server for editors +trackc lsp ``` ### Package Manager & Build Orchestrator (`yard`) @@ -102,8 +103,8 @@ Track is self-hosting: `compiler/` is the Track compiler written in Track (`compiler/src/`, plus its runtime in `compiler/rt/`). It compiles itself to a verified fixed point, through C or natively. A clean checkout bootstraps with only `cc`. `scripts/bootstrap.sh` builds the committed C -seed (`bootstrap/seed/`), and Rust is not needed. The Rust compiler in -`src/` remains an optional stage 0 (`--from-rust`). The native stages of +seed (`bootstrap/seed/`). (Earlier versions used a Rust compiler in `src/` as +stage 0; it has been removed, along with the Rust yard and LSP.) The native stages of the default run need an x86-64 Linux host with `sha256sum` and GNU `date` (`+%s%N`); elsewhere, use `scripts/bootstrap.sh --no-native`. @@ -112,7 +113,6 @@ the default run need an x86-64 Linux host with `sha256sum` and GNU `date` # cc builds bootstrap/seed/ -> stage1; stage1 -> stage2 -> stage3; check the # C and binary fixed point, then the native fixed point (n2 = n3 = n4) scripts/bootstrap.sh # trackc is build/bootstrap/stage3/trackc -scripts/bootstrap.sh --from-rust # same, with the Rust stage 0 (cargo) scripts/update_seed.sh # regenerate the seed after compiler changes T=build/bootstrap/stage3/trackc @@ -132,12 +132,13 @@ word-ABI runtime, the C backend contract and the native backend, and ## Testing ```bash -cargo test # Rust suites, incl. the self-hosting parity tests -(cd compiler && yard test) # native compiler tests scripts/bootstrap.sh # seed bootstrap: C and native fixed points +tests/run.sh -j 4 # language, runtime, native, CLI and tools suites +tests/yard/run.sh # yard behaviour +tests/lsp/run.sh # recorded `trackc lsp` sessions scripts/update_seed.sh --check # seed matches compiler/src scripts/selfhost.sh # native fixed point, no C toolchain -bench/native.sh # native vs C vs Rust scoreboard +bench/native.sh # native vs C scoreboard ``` ## License diff --git a/SPEC.md b/SPEC.md index 3c08a634..2e20a53a 100644 --- a/SPEC.md +++ b/SPEC.md @@ -150,7 +150,7 @@ Generic functions are **templates** monomorphized at call sites. - **Syntax**: `fn name(x: T, y: U) -> T { ... }`. - **Inference**: Type parameters are inferred from argument types (variable bindings, literals). Annotate `let x: i64 = ...` when inference is ambiguous. - **Monomorphization**: Each distinct instantiation (`identity`, `identity`) produces a mangled concrete function (`identity__Ti32`). Call sites are rewritten; only instances are checked and emitted. No boxing, no runtime cost. -- **Self-hosted backend**: because every value is a machine word (§11), `trackc` emits one C function per generic template; it behaves exactly like the per-instance functions of the Rust compiler. +- **Self-hosted backend**: because every value is a machine word (§11), `trackc` emits one C function per generic template; it behaves exactly like the per-instance functions the former Rust compiler emitted. - **Limitations (v0.6.0)**: Generic functions are fully supported. Generic structs (`struct Stack`) header-parsing is reserved for a follow-on; `Stack` as a type argument is not yet monomorphized. --- diff --git a/bench/native.sh b/bench/native.sh index 1c004c1e..370f1a6a 100755 --- a/bench/native.sh +++ b/bench/native.sh @@ -1,6 +1,6 @@ #!/bin/sh # Native-race scoreboard: user-mode cycles of each bench/progs program built -# three ways (trackc --native, trackc via C/gcc -O2, the Rust compiler), with +# two ways (trackc --native, trackc via C/gcc -O2), with # output checked identical, plus native self-compile time. A second table adds wall ms, page faults and # user-vs-total (user+kernel) cycles so never-freed heap cost is visible. # Usage: bench/native.sh [trackc] (default $BOOTSTRAP_DIR/stage3/trackc, else build/bootstrap/stage3/trackc) @@ -9,9 +9,6 @@ set -eu root=$(cd "$(dirname "$0")/.." && pwd); cd "$root" T=${1:-${BOOTSTRAP_DIR:-build/bootstrap}/stage3/trackc} case "$T" in /*) ;; *) T="$root/$T" ;; esac -R=${RUST_TRACK:-${CARGO_TARGET_DIR:-$root/target}/release/track} -# A fresh worktree has no target/: build the Rust compiler like bootstrap.sh does. -[ -x "$R" ] || [ -n "${RUST_TRACK:-}" ] || (cd "$root" && cargo build --release --quiet) runs=${RACE_RUNS:-3} o=$(mktemp -d); trap 'rm -rf "$o"' EXIT fail=0 @@ -40,19 +37,18 @@ probe() { printf "%s%s", x[int((n + 1) / 2)], (k < 4 ? " " : "\n") } }' } rows= -printf '%-11s %9s %9s %9s %8s %8s\n' prog native C rust "nat/C" "nat/rust" +printf '%-11s %9s %9s %8s\n' prog native C "nat/C" for f in bench/progs/*.trk; do n=$(basename "$f" .trk) "$T" build --native "$f" -o "$o/$n.nat" >/dev/null 2>&1 || { echo "$n: native build failed"; fail=1; continue; } "$T" build "$f" -o "$o/$n.c" >/dev/null 2>&1 || { echo "$n: C build failed"; fail=1; continue; } - (cd "$o" && "$R" build "$root/$f" >/dev/null 2>&1 && mv "$n" "$n.rs") || { echo "$n: rust build failed"; fail=1; continue; } - a=$("$o/$n.nat" 2>&1; echo "rc=$?"); b=$("$o/$n.c" 2>&1; echo "rc=$?"); c=$("$o/$n.rs" 2>&1; echo "rc=$?") - if [ "$a" != "$b" ] || [ "$a" != "$c" ]; then echo "$n: OUTPUT MISMATCH"; fail=1; continue; fi - cn=$(cyc "$o/$n.nat"); cc=$(cyc "$o/$n.c"); cr=$(cyc "$o/$n.rs") - printf '%-11s %8sM %8sM %8sM %8s %8s\n' "$n" "$cn" "$cc" "$cr" \ - "$(awk "BEGIN{printf \"%.2f\", $cn/$cc}")" "$(awk "BEGIN{printf \"%.2f\", $cn/$cr}")" - for k in native C rust; do - case $k in native) b=nat ;; C) b=c ;; rust) b=rs ;; esac + a=$("$o/$n.nat" 2>&1; echo "rc=$?"); b=$("$o/$n.c" 2>&1; echo "rc=$?") + if [ "$a" != "$b" ]; then echo "$n: OUTPUT MISMATCH"; fail=1; continue; fi + cn=$(cyc "$o/$n.nat"); cc=$(cyc "$o/$n.c") + printf '%-11s %8sM %8sM %8s\n' "$n" "$cn" "$cc" \ + "$(awk "BEGIN{printf \"%.2f\", $cn/$cc}")" + for k in native C; do + case $k in native) b=nat ;; C) b=c ;; esac rows="$rows$(printf '%-11s %-7s %s' "$n" "$k" "$(probe "$o/$n.$b")") " done diff --git a/bench/race.sh b/bench/race.sh index fac0c694..ba2f5f46 100755 --- a/bench/race.sh +++ b/bench/race.sh @@ -1,21 +1,23 @@ #!/bin/sh -# Race scoreboard: trackc (self-hosted) vs the Rust compiler on the same work. +# Race scoreboard: the C-built trackc (stage3) vs the native trackc on the +# same work. The native trackc is trackc's own `--native` build of +# compiler/src/main.trk; programs are built through C by the first and with +# --native by the second. # Usage: bench/race.sh [trackc] (default: build/bootstrap/stage3/trackc) -# Env: RUST_TRACK, YARD override target/release/{track,yard}; RACE_SKIP_COMPILER=1 -# skips the compiler-build rows; RACE_RUNS sets the run count (default 5). -# Prints the median wall-clock ms; ratio = trackc/rust (below 1.00 = trackc wins). +# Env: NATIVE_TRACKC names a native trackc (default: built here from trackc); +# RACE_SKIP_COMPILER=1 skips the compiler rows; RACE_RUNS sets the run +# count (default 5). +# Prints the median wall-clock ms; ratio = trackc/native (below 1.00 = C-built wins). # Run rows also show user-mode megacycles of one run (perf stat) and their # ratio, cratio: the steadier number when the machine is loaded. # A second table lists wall ms, page faults and user vs user+kernel megacycles. -# Every bench/progs/*.trk program is built with both compilers and both +# Every bench/progs/*.trk program is built both ways and both # binaries must print identical output, else the row says MISMATCH and the # script exits non-zero at the end. set -eu root=$(cd "$(dirname "$0")/.." && pwd); cd "$root" abs() { case "$1" in /*) echo "$1" ;; *) echo "$root/$1" ;; esac; } T=$(abs "${1:-build/bootstrap/stage3/trackc}") -R=$(abs "${RUST_TRACK:-target/release/track}") -Y=$(abs "${YARD:-target/release/yard}") N=${RACE_RUNS:-5} med() { # med -> median ms of N runs i=0 @@ -58,29 +60,34 @@ probe() { printf "%s%s", x[int((n + 1) / 2)], (k < 4 ? " " : "\n") } }' } o=$(mktemp -d); trap 'rm -rf "$o"' EXIT +if [ -n "${NATIVE_TRACKC:-}" ]; then + R=$(abs "$NATIVE_TRACKC") +else + R="$o/trackc-native" + "$T" build --native compiler/src/main.trk -o "$R" >/dev/null +fi fail=0 rows= -printf '%-30s %8s %8s %6s %8s %8s %6s %s\n' "task" "trackc" "rust" "ratio" "t Mcyc" "r Mcyc" "cratio" "output" +printf '%-30s %8s %8s %6s %8s %8s %6s %s\n' "task" "trackc" "native" "ratio" "t Mcyc" "r Mcyc" "cratio" "output" if [ "${RACE_SKIP_COMPILER:-0}" != 1 ]; then row "check compiler/src/main.trk" "$(med "$T" check compiler/src/main.trk)" "$(med "$R" check compiler/src/main.trk)" - row "build compiler (end to end)" "$(med "$T" build compiler/src/main.trk -o "$o/t")" "$(cd compiler && med sh -c "rm -rf target && '$Y' build")" + row "build compiler (end to end)" "$(med "$T" build compiler/src/main.trk -o "$o/t")" "$(med "$R" build --native compiler/src/main.trk -o "$o/n")" fi for f in bench/progs/*.trk; do [ -f "$f" ] || continue; n=$(basename "$f" .trk) "$T" build "$f" -o "$o/$n.tk" >/dev/null 2>&1 || { row "run $n" fail - "trackc build failed"; fail=1; continue; } - # The Rust compiler writes ./ in the current directory. - (cd "$o" && "$R" build "$root/$f" >/dev/null 2>&1 && mv "$n" "$n.rs") || { row "run $n" - fail "rust build failed"; fail=1; continue; } + "$R" build --native "$f" -o "$o/$n.nat" >/dev/null 2>&1 || { row "run $n" - fail "native build failed"; fail=1; continue; } "$o/$n.tk" >"$o/$n.out.tk" 2>&1 || true - "$o/$n.rs" >"$o/$n.out.rs" 2>&1 || true - if cmp -s "$o/$n.out.tk" "$o/$n.out.rs"; then + "$o/$n.nat" >"$o/$n.out.nat" 2>&1 || true + if cmp -s "$o/$n.out.tk" "$o/$n.out.nat"; then chk="same ($(wc -l <"$o/$n.out.tk" | tr -d ' ') lines)" else chk="MISMATCH"; fail=1 fi rows="$rows$(printf '%-11s %-7s %s' "$n" trackc "$(probe "$o/$n.tk")") -$(printf '%-11s %-7s %s' "$n" rust "$(probe "$o/$n.rs")") +$(printf '%-11s %-7s %s' "$n" native "$(probe "$o/$n.nat")") " - row "run $n" "$(med "$o/$n.tk")" "$(med "$o/$n.rs")" "$chk" "$(cyc "$o/$n.tk")" "$(cyc "$o/$n.rs")" + row "run $n" "$(med "$o/$n.tk")" "$(med "$o/$n.nat")" "$chk" "$(cyc "$o/$n.tk")" "$(cyc "$o/$n.nat")" done # honest scoreboard: wall ms, page faults, user vs user+kernel megacycles (median of runs) printf '\n%-11s %-7s %8s %9s %9s %10s %7s\n' prog build "wall ms" faults "user Mcyc" "total Mcyc" "kern %" diff --git a/compiler/src/lexer.trk b/compiler/src/lexer.trk index 6d10d040..3687a436 100644 --- a/compiler/src/lexer.trk +++ b/compiler/src/lexer.trk @@ -1,6 +1,6 @@ // lexer.trk — tokenizer for Track source files. // -// Mirrors the bootstrap lexer (`src/lexer/mod.rs`): whitespace is +// Mirrors the former Rust bootstrap lexer (`src/lexer/mod.rs`, deleted): whitespace is // [ \t\r\n], `//` comments run to the end of the line, identifiers are // ASCII [A-Za-z_][A-Za-z0-9_]*, integers are decimal i64, and strings are // unescaped at lex time. Each token is a TK_WIDTH-word record diff --git a/compiler/tests/backend_test.trk b/compiler/tests/backend_test.trk index e6a9cf71..a9e4668b 100644 --- a/compiler/tests/backend_test.trk +++ b/compiler/tests/backend_test.trk @@ -1,5 +1,5 @@ // Checker and C emitter on in-memory programs. Rejections exit the -// process, so they are covered by the Rust suite (tests/selfhost_tests.rs); +// process, so they are covered by tests/run.sh (tests/sh/selfhost.sh); // here every program must be accepted. import "base"; diff --git a/docs/bootstrap.md b/docs/bootstrap.md index f7cd1049..d46158f2 100644 --- a/docs/bootstrap.md +++ b/docs/bootstrap.md @@ -4,7 +4,7 @@ Track 1.0 is self-hosting: `trackc`, the compiler in `compiler/src/`, is written entirely in Track and compiles itself to a fixed point. A clean checkout builds `trackc` with only a C compiler (`cc`) and POSIX -tools. Rust is not needed. The default run then also checks the native +tools. The default run then also checks the native fixed point (`scripts/selfhost.sh`), which runs x86-64 Linux executables and uses `sha256sum` and GNU `date +%s%N` (nanosecond timing); on other hosts (macOS, ARM) use `scripts/bootstrap.sh --no-native` for the C-only bootstrap. @@ -34,8 +34,9 @@ The gate has three parts. Stage 1 and stage 2 must emit byte-identical C for the compiler, which shows the two builds of `trackc` behave the same. The stage 2 and stage 3 executables must then be byte-identical. Last, the native stages `n2`, `n3` and `n4` must be byte-identical (`--no-native` -skips this part). CI runs the seed path with no Rust toolchain on `PATH`. -`tests/selfhost_tests.rs` repeats the C check under `cargo test`. +skips this part). CI runs the seed path with only `/usr/bin:/bin` on `PATH` +and checks that no Rust toolchain is reachable there. +`tests/sh/selfhost.sh` (run by `tests/run.sh`) repeats the C check. ### The seed @@ -56,8 +57,8 @@ scripts/update_seed.sh --check # fail if bootstrap/seed/ is stale (CI) Rerun `scripts/update_seed.sh` in the same change as any edit to `compiler/src/`, `compiler/rt/` or `runtime/`. By default it bootstraps from the current seed. If the sources use something the old seed cannot compile, -point `TRACKC` at any working `trackc`, for example the stage3 of -`scripts/bootstrap.sh --from-rust`. It builds the compiler twice from that +point `TRACKC` at any working `trackc`, for example one built from an +intermediate commit the old seed can compile. It builds the compiler twice from that binary and writes the fixed-point C. A runtime change (`runtime/` or `compiler/rt/`, then `embed_runtime.sh` / @@ -65,25 +66,20 @@ A runtime change (`runtime/` or `compiler/rt/`, then `embed_runtime.sh` / old runtime, so its stage2 and stage3 differ and the default run (and `--check`) stops with "stage2 and stage3 executables differ". Build a trackc from the new sources first, e.g. `TRACKC=build/bootstrap/stage3/trackc` -after `scripts/bootstrap.sh --no-native` reports the mismatch, or -`--from-rust` while stage 0 still exists. +after `scripts/bootstrap.sh --no-native` reports the mismatch. The seed is C rather than a binary. C can be reviewed, it compresses well in git history, and it builds on any host with a C compiler. One step later the native stages give a static x86-64 ELF that needs no toolchain. -### The Rust stage 0 +### History: the Rust stage 0 -The Rust compiler in `src/` still works as stage 0: - -```sh -scripts/bootstrap.sh --from-rust # or BOOTSTRAP_FROM=rust; YARD=... picks a yard binary -``` - -This path runs `cargo build --release` (or uses `$YARD`), and `yard build` -compiles `compiler/` to `stage1/trackc`. From stage 1 on the stages are the -same. With a fresh seed, both paths give byte-identical `stage2` and -`stage3`. +Earlier, a Rust compiler in `src/` (with a Rust yard and +LSP) was an alternative stage 0 (`scripts/bootstrap.sh --from-rust`): yard +built `compiler/` to `stage1/trackc`, and from stage 1 on both paths gave +byte-identical `stage2` and `stage3`. The C seed was first generated that +way. The Rust code, `Cargo.toml` and the cargo test suites have been +deleted; yard and the LSP are now Track (`tools/yard/`, `trackc lsp`). ## Using trackc @@ -101,7 +97,7 @@ trackc life --place hello.trk # placement of every allocation site `trackc` loads the root file and every local module it imports. Imports resolve beside the importing file first (`/.trk`, -`//mod.trk`), then with the Rust compiler's project-relative +`//mod.trk`), then with the (former) Rust compiler's project-relative candidates (`src/`, the current directory, `compiler/src/`, `compiler/`). `std`, `std/io`, `std/fs`, `std/sys`, `std/mem`, and `math/vec` are built-in namespaces. @@ -114,7 +110,7 @@ built-in namespaces. | `lexer.trk` | tokens as `(kind, value, start, end)` records; keywords interned first | | `ast.trk` | node pool: seven words per node, child lists in a list pool | | `parser.trk` | recursive descent over the full grammar, same precedence as `src/parser/` | -| `loader.trk` | whole-program loading in the order the Rust checker visits modules | +| `loader.trk` | whole-program loading in the order the former Rust checker visited modules | | `symbols.trk` | functions, enum/union layouts, aliases, integer constants | | `checker.trk` | the ownership checker | | `life.trk` | lifecycle summaries, errors E0211-E0214, warnings W0301-W0305, the placement plan ([lifecycles.md](lifecycles.md)) | @@ -267,8 +263,8 @@ in-bounds index and `a`, `i` in registers reads the element as a memory operand; `n % d` by a constant adds the sign fix-up `s & -d` to `n` beside the quotient multiply instead of after it. `syscall6`, `load64`, `store64`, `load8`, `store8` compile to instructions, as do the libc names `elf.trk` uses -(`open64`, `write`, `fchmod`, `close`, `memset`) so that the Rust -bootstrap compiler, which knows no machine builtins, links them from libc. String +(`open64`, `write`, `fchmod`, `close`, `memset`) so that the +C backend, which knows no machine builtins, links them from libc. String literals follow the code. `_start` calls `rt_start(argc, argv)`, then `main()`, then `sys_exit(result)` (the compiler/rt `rt_start` runs main and exits itself, so the rest is a fallback; see docs/native.md). @@ -350,7 +346,7 @@ and tail calls are optimised away, so very deep non-tail recursion (about a million calls) overflows the stack and dies with SIGSEGV where the C build at `-O2` may survive. The natively built `trackc` compiles itself to a byte-identical fixed -point (`tests/native_tests.rs`); `scripts/native_parity.sh ` +point (`tests/sh/native.sh`); `scripts/native_parity.sh ` compares native and C builds of the examples. ### Bootstrapping from .trk alone @@ -376,8 +372,9 @@ the script on every push. ## The runtime -`runtime/track_runtime.c` is the single source of truth. The Rust compiler -embeds it with `include_str!`; `scripts/embed_runtime.sh` regenerates +`runtime/track_runtime.c` is the single source of truth (the Rust compiler +used to embed it with `include_str!`, as its header comment still says); +`scripts/embed_runtime.sh` regenerates `compiler/src/runtime_c.trk`, which holds the source as Track string literals plus each function's prototype and arity. CI runs `scripts/embed_runtime.sh --check` so the two copies cannot drift. @@ -387,7 +384,7 @@ literals plus each function's prototype and arity. CI runs ## Ownership checker -`checker.trk` implements the same rules as `src/checker/` (see +`checker.trk` implements the rules the Rust checker in `src/checker/` had (see [SPEC.md](../SPEC.md)): moves of non-copy values, borrows that freeze their target while the reference is live, lens locks, the `if`/`else` merge rule, no consumption of outer resources in loops, reference escape analysis, lens @@ -395,13 +392,14 @@ escape analysis, forbidden manual frees, and the "did you mean" check for misspelled calls. Instead of cloning maps at every branch it keeps a table of variable slots (name, state, type, mutability, lens flag, the previous slot with the same name, provenance) and snapshots slot states at -branches. `tests/selfhost_tests.rs` asserts that both checkers return the -same verdict on a shared set of accepted and rejected programs. +branches. Its verdicts on a shared set of accepted and rejected programs, +once compared with the Rust checker, are pinned in `tests/cases/` and run +by `tests/run.sh`. ## Testing ```sh -cargo test --test selfhost_tests # fixed point, parity, verdicts, native tests -(cd compiler && yard test) # native tests built by the Rust compiler +tests/run.sh -j 4 # fixed point, verdicts, native tests, compiler/tests +(cd compiler && yard test) # compiler/tests via yard (tools/yard) (cd compiler && target/trackc run tests/parser_test.trk) # ... or by trackc ``` diff --git a/docs/generics.md b/docs/generics.md index 95aa47e5..2a1ec1a8 100644 --- a/docs/generics.md +++ b/docs/generics.md @@ -56,4 +56,4 @@ identity(y) // error: cannot infer T — annotate y first ## See Also - `examples/generics.trk` — working demo (`identity`, `pair`, nested calls) -- `src/mono.rs` — the monomorphization pass (template table → per-site mangled instances) +- `src/mono.rs` (deleted with the Rust compiler) — the Rust monomorphization pass; `trackc` emits one C function per template instead (see SPEC.md) diff --git a/docs/lifecycles.md b/docs/lifecycles.md index 49b84172..fc8ce21f 100644 --- a/docs/lifecycles.md +++ b/docs/lifecycles.md @@ -260,7 +260,7 @@ value (`'p'` in e5), or at the literal if nothing calls the function. *As built (L5w):* the four rules are widened; every case below has an error test and a look-alike that must check clean in -`tests/selfhost_tests.rs` (`LIFE_ERRORS`, `LIFE_CLEAN`). +`tests/selfhost_tests.rs` (`LIFE_ERRORS`, `LIFE_CLEAN`; now `tests/sh/lifecycle.sh`). - **E0211** also fires for an owned place read through a `&` variable (`take(r.p)`, `take(*r)`, `r.0`, `r[i]`) passed to a by-value parameter @@ -330,7 +330,7 @@ no caller. unaffected, so the bootstrap's byte-identical gates are untouched. - The compiler's own sources stay warning-clean. The L6 accept requires `trackc check --deny-warnings compiler/src/main.trk`. -- Rust checker parity (`tests/selfhost_tests.rs`, shared verdicts): the +- Rust checker parity (historical; the Rust checker is deleted) (`tests/selfhost_tests.rs`, shared verdicts): the new errors are trackc-only, like K2's early-return moves. Mark the new test programs trackc-only. `compiler/` must still pass the Rust stage 0, and it does, because it holds handles as `i64`, which these @@ -659,7 +659,7 @@ Every card in this chart has landed. Every accept includes the **self-hosting gate**: `scripts/bootstrap.sh` (stage1/stage2 C identical, stage2/stage3 binaries identical), `scripts/selfhost.sh` (n2 = n3 = n4), and -`cargo test --test selfhost_tests`. The compiler is the biggest test. +`tests/run.sh` (formerly `cargo test --test selfhost_tests`). The compiler is the biggest test. "check budget" means `trackc check compiler/src/main.trk` stays at most 15 ms above the base and under 75 ms (median of 5). diff --git a/docs/lsp.md b/docs/lsp.md index 16e53f4d..a544486b 100644 --- a/docs/lsp.md +++ b/docs/lsp.md @@ -8,8 +8,8 @@ trackc lsp It speaks JSON-RPC 2.0 over stdin/stdout with `Content-Length` framing (the LSP base protocol) and is written in Track (`compiler/src/lsp.trk`). -The Rust `track-lsp` binary still builds but is deprecated; it will be -removed with the rest of the Rust code. +It replaced the Rust `track-lsp` binary, which has been deleted with the +rest of the Rust code. ## Features @@ -80,7 +80,7 @@ Any LSP client: run the command `trackc` with the argument `lsp`, for tests/lsp/run.sh path/to/trackc ``` -replays the recorded sessions in `tests/lsp/cases/` (no cargo needed). +replays the recorded sessions in `tests/lsp/cases/`. `--update` re-records them. ## Syntax Highlighting diff --git a/docs/v080a-foundations.md b/docs/v080a-foundations.md index 1a1230d3..13fe5f28 100644 --- a/docs/v080a-foundations.md +++ b/docs/v080a-foundations.md @@ -107,7 +107,7 @@ Yard's build-order and artifact-naming milestone is complete: Existing JSON cache files remain readable; the new object paths force a rebuild when migrating from the old flat artifact layout. -The regression gate is `cargo test --test yard_tests`. It covers colliding +The regression gate was `cargo test --test yard_tests` and is now `tests/yard/run.sh`. It covers colliding basenames, a user module named `_track_runtime.trk`, warm-cache reuse, stable metadata after a clean build, and execution of the linked binary. These guarantees concern build ordering and artifact identity; byte-for-byte native diff --git a/docs/yard.md b/docs/yard.md index f5eb539e..ea4c7fbd 100644 --- a/docs/yard.md +++ b/docs/yard.md @@ -2,7 +2,7 @@ Yard is the package manager and build orchestrator for the Track programming language. -Yard is written in Track (`tools/yard/*.trk`) and drives the self-hosted compiler `trackc`. The Rust implementation (`src/yard/`, `cargo build --bin yard`) is still in the tree until the remaining Rust parts are ported; both behave the same for everything below. +Yard is written in Track (`tools/yard/*.trk`) and drives the self-hosted compiler `trackc`. It replaced an earlier Rust implementation (`src/yard/`), since deleted; the behaviour below is unchanged. ## Building yard @@ -40,7 +40,7 @@ tests/yard/run.sh # builds yard with trackc, then tests it YARD_BIN=./yard tests/yard/run.sh # tests an existing binary ``` -Each case matches a test in `tests/yard_tests.rs`. The runner needs no cargo. +Each case matches a test of the deleted Rust suite (`tests/yard_tests.rs`), named in its header. ## Project Structure diff --git a/page/dist/assets/index-COmd7Ako.js b/page/dist/assets/index-kdLLru-r.js similarity index 72% rename from page/dist/assets/index-COmd7Ako.js rename to page/dist/assets/index-kdLLru-r.js index d44cef47..7c7a07d5 100644 --- a/page/dist/assets/index-COmd7Ako.js +++ b/page/dist/assets/index-kdLLru-r.js @@ -1,4 +1,4 @@ -(function(){const h=document.createElement("link").relList;if(h&&h.supports&&h.supports("modulepreload"))return;for(const S of document.querySelectorAll('link[rel="modulepreload"]'))r(S);new MutationObserver(S=>{for(const N of S)if(N.type==="childList")for(const _ of N.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&r(_)}).observe(document,{childList:!0,subtree:!0});function y(S){const N={};return S.integrity&&(N.integrity=S.integrity),S.referrerPolicy&&(N.referrerPolicy=S.referrerPolicy),S.crossOrigin==="use-credentials"?N.credentials="include":S.crossOrigin==="anonymous"?N.credentials="omit":N.credentials="same-origin",N}function r(S){if(S.ep)return;S.ep=!0;const N=y(S);fetch(S.href,N)}})();function um(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var ku={exports:{}},Hn={};/** +(function(){const h=document.createElement("link").relList;if(h&&h.supports&&h.supports("modulepreload"))return;for(const N of document.querySelectorAll('link[rel="modulepreload"]'))o(N);new MutationObserver(N=>{for(const _ of N)if(_.type==="childList")for(const z of _.addedNodes)z.tagName==="LINK"&&z.rel==="modulepreload"&&o(z)}).observe(document,{childList:!0,subtree:!0});function y(N){const _={};return N.integrity&&(_.integrity=N.integrity),N.referrerPolicy&&(_.referrerPolicy=N.referrerPolicy),N.crossOrigin==="use-credentials"?_.credentials="include":N.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function o(N){if(N.ep)return;N.ep=!0;const _=y(N);fetch(N.href,_)}})();function um(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ku={exports:{}},Hn={};/** * @license React * react-jsx-runtime.production.js * @@ -6,7 +6,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Zd;function eh(){if(Zd)return Hn;Zd=1;var o=Symbol.for("react.transitional.element"),h=Symbol.for("react.fragment");function y(r,S,N){var _=null;if(N!==void 0&&(_=""+N),S.key!==void 0&&(_=""+S.key),"key"in S){N={};for(var O in S)O!=="key"&&(N[O]=S[O])}else N=S;return S=N.ref,{$$typeof:o,type:r,key:_,ref:S!==void 0?S:null,props:N}}return Hn.Fragment=h,Hn.jsx=y,Hn.jsxs=y,Hn}var Qd;function th(){return Qd||(Qd=1,ku.exports=eh()),ku.exports}var s=th(),Au={exports:{}},ee={};/** + */var Zd;function e0(){if(Zd)return Hn;Zd=1;var r=Symbol.for("react.transitional.element"),h=Symbol.for("react.fragment");function y(o,N,_){var z=null;if(_!==void 0&&(z=""+_),N.key!==void 0&&(z=""+N.key),"key"in N){_={};for(var O in N)O!=="key"&&(_[O]=N[O])}else _=N;return N=_.ref,{$$typeof:r,type:o,key:z,ref:N!==void 0?N:null,props:_}}return Hn.Fragment=h,Hn.jsx=y,Hn.jsxs=y,Hn}var Qd;function t0(){return Qd||(Qd=1,ku.exports=e0()),ku.exports}var s=t0(),Au={exports:{}},ee={};/** * @license React * react.production.js * @@ -14,7 +14,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Vd;function lh(){if(Vd)return ee;Vd=1;var o=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),S=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),_=Symbol.for("react.context"),O=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),w=Symbol.for("react.activity"),I=Symbol.iterator;function V(m){return m===null||typeof m!="object"?null:(m=I&&m[I]||m["@@iterator"],typeof m=="function"?m:null)}var M={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},D=Object.assign,ie={};function ye(m,E,H){this.props=m,this.context=E,this.refs=ie,this.updater=H||M}ye.prototype.isReactComponent={},ye.prototype.setState=function(m,E){if(typeof m!="object"&&typeof m!="function"&&m!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,m,E,"setState")},ye.prototype.forceUpdate=function(m){this.updater.enqueueForceUpdate(this,m,"forceUpdate")};function ce(){}ce.prototype=ye.prototype;function Ne(m,E,H){this.props=m,this.context=E,this.refs=ie,this.updater=H||M}var De=Ne.prototype=new ce;De.constructor=Ne,D(De,ye.prototype),De.isPureReactComponent=!0;var Ye=Array.isArray;function Ee(){}var P={H:null,A:null,T:null,S:null},B=Object.prototype.hasOwnProperty;function W(m,E,H){var G=H.ref;return{$$typeof:o,type:m,key:E,ref:G!==void 0?G:null,props:H}}function ke(m,E){return W(m.type,E,m.props)}function Qe(m){return typeof m=="object"&&m!==null&&m.$$typeof===o}function Re(m){var E={"=":"=0",":":"=2"};return"$"+m.replace(/[=:]/g,function(H){return E[H]})}var ft=/\/+/g;function dt(m,E){return typeof m=="object"&&m!==null&&m.key!=null?Re(""+m.key):E.toString(36)}function Ve(m){switch(m.status){case"fulfilled":return m.value;case"rejected":throw m.reason;default:switch(typeof m.status=="string"?m.then(Ee,Ee):(m.status="pending",m.then(function(E){m.status==="pending"&&(m.status="fulfilled",m.value=E)},function(E){m.status==="pending"&&(m.status="rejected",m.reason=E)})),m.status){case"fulfilled":return m.value;case"rejected":throw m.reason}}throw m}function T(m,E,H,G,Q){var J=typeof m;(J==="undefined"||J==="boolean")&&(m=null);var de=!1;if(m===null)de=!0;else switch(J){case"bigint":case"string":case"number":de=!0;break;case"object":switch(m.$$typeof){case o:case h:de=!0;break;case L:return de=m._init,T(de(m._payload),E,H,G,Q)}}if(de)return Q=Q(m),de=G===""?"."+dt(m,0):G,Ye(Q)?(H="",de!=null&&(H=de.replace(ft,"$&/")+"/"),T(Q,E,H,"",function(ol){return ol})):Q!=null&&(Qe(Q)&&(Q=ke(Q,H+(Q.key==null||m&&m.key===Q.key?"":(""+Q.key).replace(ft,"$&/")+"/")+de)),E.push(Q)),1;de=0;var Ke=G===""?".":G+":";if(Ye(m))for(var ae=0;ae>>1,U=T[pe];if(0>>1;peS(H,$))GS(Q,H)?(T[pe]=Q,T[G]=$,pe=G):(T[pe]=H,T[E]=$,pe=E);else if(GS(Q,$))T[pe]=Q,T[G]=$,pe=G;else break e}}return R}function S(T,R){var $=T.sortIndex-R.sortIndex;return $!==0?$:T.id-R.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var N=performance;o.unstable_now=function(){return N.now()}}else{var _=Date,O=_.now();o.unstable_now=function(){return _.now()-O}}var j=[],g=[],L=1,w=null,I=3,V=!1,M=!1,D=!1,ie=!1,ye=typeof setTimeout=="function"?setTimeout:null,ce=typeof clearTimeout=="function"?clearTimeout:null,Ne=typeof setImmediate<"u"?setImmediate:null;function De(T){for(var R=y(g);R!==null;){if(R.callback===null)r(g);else if(R.startTime<=T)r(g),R.sortIndex=R.expirationTime,h(j,R);else break;R=y(g)}}function Ye(T){if(D=!1,De(T),!M)if(y(j)!==null)M=!0,Ee||(Ee=!0,Re());else{var R=y(g);R!==null&&Ve(Ye,R.startTime-T)}}var Ee=!1,P=-1,B=5,W=-1;function ke(){return ie?!0:!(o.unstable_now()-WT&&ke());){var pe=w.callback;if(typeof pe=="function"){w.callback=null,I=w.priorityLevel;var U=pe(w.expirationTime<=T);if(T=o.unstable_now(),typeof U=="function"){w.callback=U,De(T),R=!0;break t}w===y(j)&&r(j),De(T)}else r(j);w=y(j)}if(w!==null)R=!0;else{var m=y(g);m!==null&&Ve(Ye,m.startTime-T),R=!1}}break e}finally{w=null,I=$,V=!1}R=void 0}}finally{R?Re():Ee=!1}}}var Re;if(typeof Ne=="function")Re=function(){Ne(Qe)};else if(typeof MessageChannel<"u"){var ft=new MessageChannel,dt=ft.port2;ft.port1.onmessage=Qe,Re=function(){dt.postMessage(null)}}else Re=function(){ye(Qe,0)};function Ve(T,R){P=ye(function(){T(o.unstable_now())},R)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(T){T.callback=null},o.unstable_forceFrameRate=function(T){0>T||125pe?(T.sortIndex=$,h(g,T),y(j)===null&&T===y(g)&&(D?(ce(P),P=-1):D=!0,Ve(Ye,$-pe))):(T.sortIndex=U,h(j,T),M||V||(M=!0,Ee||(Ee=!0,Re()))),T},o.unstable_shouldYield=ke,o.unstable_wrapCallback=function(T){var R=I;return function(){var $=I;I=R;try{return T.apply(this,arguments)}finally{I=$}}}})(Eu)),Eu}var Wd;function ih(){return Wd||(Wd=1,Cu.exports=nh()),Cu.exports}var Mu={exports:{}},lt={};/** + */var Jd;function n0(){return Jd||(Jd=1,(function(r){function h(T,R){var $=T.length;T.push(R);e:for(;0<$;){var pe=$-1>>>1,U=T[pe];if(0>>1;peN(H,$))GN(Q,H)?(T[pe]=Q,T[G]=$,pe=G):(T[pe]=H,T[E]=$,pe=E);else if(GN(Q,$))T[pe]=Q,T[G]=$,pe=G;else break e}}return R}function N(T,R){var $=T.sortIndex-R.sortIndex;return $!==0?$:T.id-R.id}if(r.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var _=performance;r.unstable_now=function(){return _.now()}}else{var z=Date,O=z.now();r.unstable_now=function(){return z.now()-O}}var A=[],g=[],L=1,w=null,I=3,V=!1,M=!1,D=!1,ie=!1,ye=typeof setTimeout=="function"?setTimeout:null,ce=typeof clearTimeout=="function"?clearTimeout:null,Ne=typeof setImmediate<"u"?setImmediate:null;function De(T){for(var R=y(g);R!==null;){if(R.callback===null)o(g);else if(R.startTime<=T)o(g),R.sortIndex=R.expirationTime,h(A,R);else break;R=y(g)}}function Ye(T){if(D=!1,De(T),!M)if(y(A)!==null)M=!0,Ee||(Ee=!0,Re());else{var R=y(g);R!==null&&Ve(Ye,R.startTime-T)}}var Ee=!1,P=-1,B=5,W=-1;function ke(){return ie?!0:!(r.unstable_now()-WT&&ke());){var pe=w.callback;if(typeof pe=="function"){w.callback=null,I=w.priorityLevel;var U=pe(w.expirationTime<=T);if(T=r.unstable_now(),typeof U=="function"){w.callback=U,De(T),R=!0;break t}w===y(A)&&o(A),De(T)}else o(A);w=y(A)}if(w!==null)R=!0;else{var m=y(g);m!==null&&Ve(Ye,m.startTime-T),R=!1}}break e}finally{w=null,I=$,V=!1}R=void 0}}finally{R?Re():Ee=!1}}}var Re;if(typeof Ne=="function")Re=function(){Ne(Qe)};else if(typeof MessageChannel<"u"){var ft=new MessageChannel,dt=ft.port2;ft.port1.onmessage=Qe,Re=function(){dt.postMessage(null)}}else Re=function(){ye(Qe,0)};function Ve(T,R){P=ye(function(){T(r.unstable_now())},R)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(T){T.callback=null},r.unstable_forceFrameRate=function(T){0>T||125pe?(T.sortIndex=$,h(g,T),y(A)===null&&T===y(g)&&(D?(ce(P),P=-1):D=!0,Ve(Ye,$-pe))):(T.sortIndex=U,h(A,T),M||V||(M=!0,Ee||(Ee=!0,Re()))),T},r.unstable_shouldYield=ke,r.unstable_wrapCallback=function(T){var R=I;return function(){var $=I;I=R;try{return T.apply(this,arguments)}finally{I=$}}}})(Eu)),Eu}var Wd;function i0(){return Wd||(Wd=1,Cu.exports=n0()),Cu.exports}var Mu={exports:{}},lt={};/** * @license React * react-dom.production.js * @@ -30,7 +30,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var $d;function ch(){if($d)return lt;$d=1;var o=Hu();function h(j){var g="https://react.dev/errors/"+j;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(h){console.error(h)}}return o(),Mu.exports=ch(),Mu.exports}/** + */var $d;function c0(){if($d)return lt;$d=1;var r=Hu();function h(A){var g="https://react.dev/errors/"+A;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(h){console.error(h)}}return r(),Mu.exports=c0(),Mu.exports}/** * @license React * react-dom-client.production.js * @@ -38,150 +38,150 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Id;function uh(){if(Id)return Bn;Id=1;var o=ih(),h=Hu(),y=sh();function r(e){var t="https://react.dev/errors/"+e;if(1U||(e.current=pe[U],pe[U]=null,U--)}function H(e,t){U++,pe[U]=e.current,e.current=t}var G=m(null),Q=m(null),J=m(null),de=m(null);function Ke(e,t){switch(H(J,t),H(Q,e),H(G,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?md(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=md(t),e=pd(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}E(G),H(G,e)}function ae(){E(G),E(Q),E(J)}function ol(e){e.memoizedState!==null&&H(de,e);var t=G.current,l=pd(t,e.type);t!==l&&(H(Q,e),H(G,l))}function Yt(e){Q.current===e&&(E(G),E(Q)),de.current===e&&(E(de),On._currentValue=$)}var rl,ia;function _t(e){if(rl===void 0)try{throw Error()}catch(l){var t=l.stack.trim().match(/\n( *(at )?)/);rl=t&&t[1]||"",ia=-1U||(e.current=pe[U],pe[U]=null,U--)}function H(e,t){U++,pe[U]=e.current,e.current=t}var G=m(null),Q=m(null),J=m(null),de=m(null);function Ke(e,t){switch(H(J,t),H(Q,e),H(G,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?md(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=md(t),e=pd(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}E(G),H(G,e)}function ae(){E(G),E(Q),E(J)}function rl(e){e.memoizedState!==null&&H(de,e);var t=G.current,l=pd(t,e.type);t!==l&&(H(Q,e),H(G,l))}function Yt(e){Q.current===e&&(E(G),E(Q)),de.current===e&&(E(de),On._currentValue=$)}var ol,ia;function _t(e){if(ol===void 0)try{throw Error()}catch(l){var t=l.stack.trim().match(/\n( *(at )?)/);ol=t&&t[1]||"",ia=-1)":-1n||f[a]!==v[n]){var k=` -`+f[a].replace(" at new "," at ");return e.displayName&&k.includes("")&&(k=k.replace("",e.displayName)),k}while(1<=a&&0<=n);break}}}finally{oc=!1,Error.prepareStackTrace=l}return(l=e?e.displayName||e.name:"")?_t(l):""}function Mm(e,t){switch(e.tag){case 26:case 27:case 5:return _t(e.type);case 16:return _t("Lazy");case 13:return e.child!==t&&t!==null?_t("Suspense Fallback"):_t("Suspense");case 19:return _t("SuspenseList");case 0:case 15:return rc(e.type,!1);case 11:return rc(e.type.render,!1);case 1:return rc(e.type,!0);case 31:return _t("Activity");default:return""}}function Yu(e){try{var t="",l=null;do t+=Mm(e,l),l=e,e=e.return;while(e);return t}catch(a){return` +`+f[a].replace(" at new "," at ");return e.displayName&&k.includes("")&&(k=k.replace("",e.displayName)),k}while(1<=a&&0<=n);break}}}finally{rc=!1,Error.prepareStackTrace=l}return(l=e?e.displayName||e.name:"")?_t(l):""}function Mm(e,t){switch(e.tag){case 26:case 27:case 5:return _t(e.type);case 16:return _t("Lazy");case 13:return e.child!==t&&t!==null?_t("Suspense Fallback"):_t("Suspense");case 19:return _t("SuspenseList");case 0:case 15:return oc(e.type,!1);case 11:return oc(e.type.render,!1);case 1:return oc(e.type,!0);case 31:return _t("Activity");default:return""}}function Yu(e){try{var t="",l=null;do t+=Mm(e,l),l=e,e=e.return;while(e);return t}catch(a){return` Error generating stack: `+a.message+` -`+a.stack}}var fc=Object.prototype.hasOwnProperty,dc=o.unstable_scheduleCallback,mc=o.unstable_cancelCallback,wm=o.unstable_shouldYield,Om=o.unstable_requestPaint,mt=o.unstable_now,Dm=o.unstable_getCurrentPriorityLevel,Xu=o.unstable_ImmediatePriority,Zu=o.unstable_UserBlockingPriority,qn=o.unstable_NormalPriority,Rm=o.unstable_LowPriority,Qu=o.unstable_IdlePriority,Um=o.log,Hm=o.unstable_setDisableYieldValue,Za=null,pt=null;function fl(e){if(typeof Um=="function"&&Hm(e),pt&&typeof pt.setStrictMode=="function")try{pt.setStrictMode(Za,e)}catch{}}var ht=Math.clz32?Math.clz32:qm,Bm=Math.log,Lm=Math.LN2;function qm(e){return e>>>=0,e===0?32:31-(Bm(e)/Lm|0)|0}var Gn=256,Yn=262144,Xn=4194304;function Bl(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Zn(e,t,l){var a=e.pendingLanes;if(a===0)return 0;var n=0,i=e.suspendedLanes,c=e.pingedLanes;e=e.warmLanes;var u=a&134217727;return u!==0?(a=u&~i,a!==0?n=Bl(a):(c&=u,c!==0?n=Bl(c):l||(l=u&~e,l!==0&&(n=Bl(l))))):(u=a&~i,u!==0?n=Bl(u):c!==0?n=Bl(c):l||(l=a&~e,l!==0&&(n=Bl(l)))),n===0?0:t!==0&&t!==n&&(t&i)===0&&(i=n&-n,l=t&-t,i>=l||i===32&&(l&4194048)!==0)?t:n}function Qa(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Gm(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vu(){var e=Xn;return Xn<<=1,(Xn&62914560)===0&&(Xn=4194304),e}function pc(e){for(var t=[],l=0;31>l;l++)t.push(e);return t}function Va(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ym(e,t,l,a,n,i){var c=e.pendingLanes;e.pendingLanes=l,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=l,e.entangledLanes&=l,e.errorRecoveryDisabledLanes&=l,e.shellSuspendCounter=0;var u=e.entanglements,f=e.expirationTimes,v=e.hiddenUpdates;for(l=c&~l;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var Jm=/[\n"\\]/g;function Nt(e){return e.replace(Jm,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function xc(e,t,l,a,n,i,c,u){e.name="",c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"?e.type=c:e.removeAttribute("type"),t!=null?c==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Tt(t)):e.value!==""+Tt(t)&&(e.value=""+Tt(t)):c!=="submit"&&c!=="reset"||e.removeAttribute("value"),t!=null?Sc(e,c,Tt(t)):l!=null?Sc(e,c,Tt(l)):a!=null&&e.removeAttribute("value"),n==null&&i!=null&&(e.defaultChecked=!!i),n!=null&&(e.checked=n&&typeof n!="function"&&typeof n!="symbol"),u!=null&&typeof u!="function"&&typeof u!="symbol"&&typeof u!="boolean"?e.name=""+Tt(u):e.removeAttribute("name")}function io(e,t,l,a,n,i,c,u){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(e.type=i),t!=null||l!=null){if(!(i!=="submit"&&i!=="reset"||t!=null)){vc(e);return}l=l!=null?""+Tt(l):"",t=t!=null?""+Tt(t):l,u||t===e.value||(e.value=t),e.defaultValue=t}a=a??n,a=typeof a!="function"&&typeof a!="symbol"&&!!a,e.checked=u?e.checked:!!a,e.defaultChecked=!!a,c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"&&(e.name=c),vc(e)}function Sc(e,t,l){t==="number"&&Kn(e.ownerDocument)===e||e.defaultValue===""+l||(e.defaultValue=""+l)}function fa(e,t,l,a){if(e=e.options,t){t={};for(var n=0;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),kc=!1;if(Qt)try{var $a={};Object.defineProperty($a,"passive",{get:function(){kc=!0}}),window.addEventListener("test",$a,$a),window.removeEventListener("test",$a,$a)}catch{kc=!1}var ml=null,Ac=null,Wn=null;function mo(){if(Wn)return Wn;var e,t=Ac,l=t.length,a,n="value"in ml?ml.value:ml.textContent,i=n.length;for(e=0;e=Pa),vo=" ",xo=!1;function So(e,t){switch(e){case"keyup":return z0.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function zo(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ha=!1;function T0(e,t){switch(e){case"compositionend":return zo(t);case"keypress":return t.which!==32?null:(xo=!0,vo);case"textInput":return e=t.data,e===vo&&xo?null:e;default:return null}}function N0(e,t){if(ha)return e==="compositionend"||!wc&&So(e,t)?(e=mo(),Wn=Ac=ml=null,ha=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:l,offset:t-e};e=a}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Eo(l)}}function wo(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wo(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Oo(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Kn(e.document);t instanceof e.HTMLIFrameElement;){try{var l=typeof t.contentWindow.location.href=="string"}catch{l=!1}if(l)e=t.contentWindow;else break;t=Kn(e.document)}return t}function Rc(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var O0=Qt&&"documentMode"in document&&11>=document.documentMode,ga=null,Uc=null,an=null,Hc=!1;function Do(e,t,l){var a=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Hc||ga==null||ga!==Kn(a)||(a=ga,"selectionStart"in a&&Rc(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),an&&ln(an,a)||(an=a,a=Yi(Uc,"onSelect"),0>=c,n-=c,Ht=1<<32-ht(t)+n|l<le?(re=Z,Z=null):re=Z.sibling;var ge=x(p,Z,b[le],A);if(ge===null){Z===null&&(Z=re);break}e&&Z&&ge.alternate===null&&t(p,Z),d=i(ge,d,le),he===null?K=ge:he.sibling=ge,he=ge,Z=re}if(le===b.length)return l(p,Z),me&&Kt(p,le),K;if(Z===null){for(;lele?(re=Z,Z=null):re=Z.sibling;var Rl=x(p,Z,ge.value,A);if(Rl===null){Z===null&&(Z=re);break}e&&Z&&Rl.alternate===null&&t(p,Z),d=i(Rl,d,le),he===null?K=Rl:he.sibling=Rl,he=Rl,Z=re}if(ge.done)return l(p,Z),me&&Kt(p,le),K;if(Z===null){for(;!ge.done;le++,ge=b.next())ge=C(p,ge.value,A),ge!==null&&(d=i(ge,d,le),he===null?K=ge:he.sibling=ge,he=ge);return me&&Kt(p,le),K}for(Z=a(Z);!ge.done;le++,ge=b.next())ge=z(Z,p,le,ge.value,A),ge!==null&&(e&&ge.alternate!==null&&Z.delete(ge.key===null?le:ge.key),d=i(ge,d,le),he===null?K=ge:he.sibling=ge,he=ge);return e&&Z.forEach(function(Pp){return t(p,Pp)}),me&&Kt(p,le),K}function _e(p,d,b,A){if(typeof b=="object"&&b!==null&&b.type===D&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case V:e:{for(var K=b.key;d!==null;){if(d.key===K){if(K=b.type,K===D){if(d.tag===7){l(p,d.sibling),A=n(d,b.props.children),A.return=p,p=A;break e}}else if(d.elementType===K||typeof K=="object"&&K!==null&&K.$$typeof===B&&Wl(K)===d.type){l(p,d.sibling),A=n(d,b.props),rn(A,b),A.return=p,p=A;break e}l(p,d);break}else t(p,d);d=d.sibling}b.type===D?(A=Zl(b.props.children,p.mode,A,b.key),A.return=p,p=A):(A=ii(b.type,b.key,b.props,null,p.mode,A),rn(A,b),A.return=p,p=A)}return c(p);case M:e:{for(K=b.key;d!==null;){if(d.key===K)if(d.tag===4&&d.stateNode.containerInfo===b.containerInfo&&d.stateNode.implementation===b.implementation){l(p,d.sibling),A=n(d,b.children||[]),A.return=p,p=A;break e}else{l(p,d);break}else t(p,d);d=d.sibling}A=Zc(b,p.mode,A),A.return=p,p=A}return c(p);case B:return b=Wl(b),_e(p,d,b,A)}if(Ve(b))return X(p,d,b,A);if(Re(b)){if(K=Re(b),typeof K!="function")throw Error(r(150));return b=K.call(b),F(p,d,b,A)}if(typeof b.then=="function")return _e(p,d,di(b),A);if(b.$$typeof===Ne)return _e(p,d,ui(p,b),A);mi(p,b)}return typeof b=="string"&&b!==""||typeof b=="number"||typeof b=="bigint"?(b=""+b,d!==null&&d.tag===6?(l(p,d.sibling),A=n(d,b),A.return=p,p=A):(l(p,d),A=Xc(b,p.mode,A),A.return=p,p=A),c(p)):l(p,d)}return function(p,d,b,A){try{on=0;var K=_e(p,d,b,A);return Aa=null,K}catch(Z){if(Z===ka||Z===ri)throw Z;var he=yt(29,Z,null,p.mode);return he.lanes=A,he.return=p,he}finally{}}}var Fl=ar(!0),nr=ar(!1),bl=!1;function ls(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function as(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function vl(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function xl(e,t,l){var a=e.updateQueue;if(a===null)return null;if(a=a.shared,(be&2)!==0){var n=a.pending;return n===null?t.next=t:(t.next=n.next,n.next=t),a.pending=t,t=ni(e),Go(e,null,l),t}return ai(e,a,t,l),ni(e)}function fn(e,t,l){if(t=t.updateQueue,t!==null&&(t=t.shared,(l&4194048)!==0)){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,Ju(e,l)}}function ns(e,t){var l=e.updateQueue,a=e.alternate;if(a!==null&&(a=a.updateQueue,l===a)){var n=null,i=null;if(l=l.firstBaseUpdate,l!==null){do{var c={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};i===null?n=i=c:i=i.next=c,l=l.next}while(l!==null);i===null?n=i=t:i=i.next=t}else n=i=t;l={baseState:a.baseState,firstBaseUpdate:n,lastBaseUpdate:i,shared:a.shared,callbacks:a.callbacks},e.updateQueue=l;return}e=l.lastBaseUpdate,e===null?l.firstBaseUpdate=t:e.next=t,l.lastBaseUpdate=t}var is=!1;function dn(){if(is){var e=Na;if(e!==null)throw e}}function mn(e,t,l,a){is=!1;var n=e.updateQueue;bl=!1;var i=n.firstBaseUpdate,c=n.lastBaseUpdate,u=n.shared.pending;if(u!==null){n.shared.pending=null;var f=u,v=f.next;f.next=null,c===null?i=v:c.next=v,c=f;var k=e.alternate;k!==null&&(k=k.updateQueue,u=k.lastBaseUpdate,u!==c&&(u===null?k.firstBaseUpdate=v:u.next=v,k.lastBaseUpdate=f))}if(i!==null){var C=n.baseState;c=0,k=v=f=null,u=i;do{var x=u.lane&-536870913,z=x!==u.lane;if(z?(oe&x)===x:(a&x)===x){x!==0&&x===Ta&&(is=!0),k!==null&&(k=k.next={lane:0,tag:u.tag,payload:u.payload,callback:null,next:null});e:{var X=e,F=u;x=t;var _e=l;switch(F.tag){case 1:if(X=F.payload,typeof X=="function"){C=X.call(_e,C,x);break e}C=X;break e;case 3:X.flags=X.flags&-65537|128;case 0:if(X=F.payload,x=typeof X=="function"?X.call(_e,C,x):X,x==null)break e;C=w({},C,x);break e;case 2:bl=!0}}x=u.callback,x!==null&&(e.flags|=64,z&&(e.flags|=8192),z=n.callbacks,z===null?n.callbacks=[x]:z.push(x))}else z={lane:x,tag:u.tag,payload:u.payload,callback:u.callback,next:null},k===null?(v=k=z,f=C):k=k.next=z,c|=x;if(u=u.next,u===null){if(u=n.shared.pending,u===null)break;z=u,u=z.next,z.next=null,n.lastBaseUpdate=z,n.shared.pending=null}}while(!0);k===null&&(f=C),n.baseState=f,n.firstBaseUpdate=v,n.lastBaseUpdate=k,i===null&&(n.shared.lanes=0),Nl|=c,e.lanes=c,e.memoizedState=C}}function ir(e,t){if(typeof e!="function")throw Error(r(191,e));e.call(t)}function cr(e,t){var l=e.callbacks;if(l!==null)for(e.callbacks=null,e=0;ei?i:8;var c=T.T,u={};T.T=u,Ts(e,!1,t,l);try{var f=n(),v=T.S;if(v!==null&&v(u,f),f!==null&&typeof f=="object"&&typeof f.then=="function"){var k=Y0(f,a);gn(e,t,k,zt(e))}else gn(e,t,a,zt(e))}catch(C){gn(e,t,{then:function(){},status:"rejected",reason:C},zt())}finally{R.p=i,c!==null&&u.types!==null&&(c.types=u.types),T.T=c}}function J0(){}function zs(e,t,l,a){if(e.tag!==5)throw Error(r(476));var n=Br(e).queue;Hr(e,n,t,$,l===null?J0:function(){return Lr(e),l(a)})}function Br(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ft,lastRenderedState:$},next:null};var l={};return t.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ft,lastRenderedState:l},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Lr(e){var t=Br(e);t.next===null&&(t=e.alternate.memoizedState),gn(e,t.next.queue,{},zt())}function _s(){return Ie(On)}function qr(){return He().memoizedState}function Gr(){return He().memoizedState}function W0(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var l=zt();e=vl(l);var a=xl(t,e,l);a!==null&&(rt(a,t,l),fn(a,t,l)),t={cache:Ic()},e.payload=t;return}t=t.return}}function $0(e,t,l){var a=zt();l={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},_i(e)?Xr(t,l):(l=Gc(e,t,l,a),l!==null&&(rt(l,e,a),Zr(l,t,a)))}function Yr(e,t,l){var a=zt();gn(e,t,l,a)}function gn(e,t,l,a){var n={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(_i(e))Xr(t,n);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var c=t.lastRenderedState,u=i(c,l);if(n.hasEagerState=!0,n.eagerState=u,gt(u,c))return ai(e,t,n,0),Te===null&&li(),!1}catch{}finally{}if(l=Gc(e,t,n,a),l!==null)return rt(l,e,a),Zr(l,t,a),!0}return!1}function Ts(e,t,l,a){if(a={lane:2,revertLane:lu(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},_i(e)){if(t)throw Error(r(479))}else t=Gc(e,l,a,2),t!==null&&rt(t,e,2)}function _i(e){var t=e.alternate;return e===te||t!==null&&t===te}function Xr(e,t){Ca=gi=!0;var l=e.pending;l===null?t.next=t:(t.next=l.next,l.next=t),e.pending=t}function Zr(e,t,l){if((l&4194048)!==0){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,Ju(e,l)}}var yn={readContext:Ie,use:vi,useCallback:Me,useContext:Me,useEffect:Me,useImperativeHandle:Me,useLayoutEffect:Me,useInsertionEffect:Me,useMemo:Me,useReducer:Me,useRef:Me,useState:Me,useDebugValue:Me,useDeferredValue:Me,useTransition:Me,useSyncExternalStore:Me,useId:Me,useHostTransitionStatus:Me,useFormState:Me,useActionState:Me,useOptimistic:Me,useMemoCache:Me,useCacheRefresh:Me};yn.useEffectEvent=Me;var Qr={readContext:Ie,use:vi,useCallback:function(e,t){return at().memoizedState=[e,t===void 0?null:t],e},useContext:Ie,useEffect:jr,useImperativeHandle:function(e,t,l){l=l!=null?l.concat([e]):null,Si(4194308,4,wr.bind(null,t,e),l)},useLayoutEffect:function(e,t){return Si(4194308,4,e,t)},useInsertionEffect:function(e,t){Si(4,2,e,t)},useMemo:function(e,t){var l=at();t=t===void 0?null:t;var a=e();if(Il){fl(!0);try{e()}finally{fl(!1)}}return l.memoizedState=[a,t],a},useReducer:function(e,t,l){var a=at();if(l!==void 0){var n=l(t);if(Il){fl(!0);try{l(t)}finally{fl(!1)}}}else n=t;return a.memoizedState=a.baseState=n,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},a.queue=e,e=e.dispatch=$0.bind(null,te,e),[a.memoizedState,e]},useRef:function(e){var t=at();return e={current:e},t.memoizedState=e},useState:function(e){e=ys(e);var t=e.queue,l=Yr.bind(null,te,t);return t.dispatch=l,[e.memoizedState,l]},useDebugValue:xs,useDeferredValue:function(e,t){var l=at();return Ss(l,e,t)},useTransition:function(){var e=ys(!1);return e=Hr.bind(null,te,e.queue,!0,!1),at().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,l){var a=te,n=at();if(me){if(l===void 0)throw Error(r(407));l=l()}else{if(l=t(),Te===null)throw Error(r(349));(oe&127)!==0||dr(a,t,l)}n.memoizedState=l;var i={value:l,getSnapshot:t};return n.queue=i,jr(pr.bind(null,a,i,e),[e]),a.flags|=2048,Ma(9,{destroy:void 0},mr.bind(null,a,i,l,t),null),l},useId:function(){var e=at(),t=Te.identifierPrefix;if(me){var l=Bt,a=Ht;l=(a&~(1<<32-ht(a)-1)).toString(32)+l,t="_"+t+"R_"+l,l=yi++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof a.is=="string"?c.createElement("select",{is:a.is}):c.createElement("select"),a.multiple?i.multiple=!0:a.size&&(i.size=a.size);break;default:i=typeof a.is=="string"?c.createElement(n,{is:a.is}):c.createElement(n)}}i[$e]=t,i[nt]=a;e:for(c=t.child;c!==null;){if(c.tag===5||c.tag===6)i.appendChild(c.stateNode);else if(c.tag!==4&&c.tag!==27&&c.child!==null){c.child.return=c,c=c.child;continue}if(c===t)break e;for(;c.sibling===null;){if(c.return===null||c.return===t)break e;c=c.return}c.sibling.return=c.return,c=c.sibling}t.stateNode=i;e:switch(et(i,n,a),n){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break e;case"img":a=!0;break e;default:a=!1}a&&Pt(t)}}return je(t),Bs(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,l),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==a&&Pt(t);else{if(typeof a!="string"&&t.stateNode===null)throw Error(r(166));if(e=J.current,za(t)){if(e=t.stateNode,l=t.memoizedProps,a=null,n=Fe,n!==null)switch(n.tag){case 27:case 5:a=n.memoizedProps}e[$e]=t,e=!!(e.nodeValue===l||a!==null&&a.suppressHydrationWarning===!0||fd(e.nodeValue,l)),e||gl(t,!0)}else e=Xi(e).createTextNode(a),e[$e]=t,t.stateNode=e}return je(t),null;case 31:if(l=t.memoizedState,e===null||e.memoizedState!==null){if(a=za(t),l!==null){if(e===null){if(!a)throw Error(r(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(r(557));e[$e]=t}else Ql(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;je(t),e=!1}else l=Jc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=l),e=!0;if(!e)return t.flags&256?(vt(t),t):(vt(t),null);if((t.flags&128)!==0)throw Error(r(558))}return je(t),null;case 13:if(a=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(n=za(t),a!==null&&a.dehydrated!==null){if(e===null){if(!n)throw Error(r(318));if(n=t.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(r(317));n[$e]=t}else Ql(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;je(t),n=!1}else n=Jc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),n=!0;if(!n)return t.flags&256?(vt(t),t):(vt(t),null)}return vt(t),(t.flags&128)!==0?(t.lanes=l,t):(l=a!==null,e=e!==null&&e.memoizedState!==null,l&&(a=t.child,n=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(n=a.alternate.memoizedState.cachePool.pool),i=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(i=a.memoizedState.cachePool.pool),i!==n&&(a.flags|=2048)),l!==e&&l&&(t.child.flags|=8192),ji(t,t.updateQueue),je(t),null);case 4:return ae(),e===null&&cu(t.stateNode.containerInfo),je(t),null;case 10:return Wt(t.type),je(t),null;case 19:if(E(Ue),a=t.memoizedState,a===null)return je(t),null;if(n=(t.flags&128)!==0,i=a.rendering,i===null)if(n)vn(a,!1);else{if(we!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(i=hi(e),i!==null){for(t.flags|=128,vn(a,!1),e=i.updateQueue,t.updateQueue=e,ji(t,e),t.subtreeFlags=0,e=l,l=t.child;l!==null;)Yo(l,e),l=l.sibling;return H(Ue,Ue.current&1|2),me&&Kt(t,a.treeForkCount),t.child}e=e.sibling}a.tail!==null&&mt()>Oi&&(t.flags|=128,n=!0,vn(a,!1),t.lanes=4194304)}else{if(!n)if(e=hi(i),e!==null){if(t.flags|=128,n=!0,e=e.updateQueue,t.updateQueue=e,ji(t,e),vn(a,!0),a.tail===null&&a.tailMode==="hidden"&&!i.alternate&&!me)return je(t),null}else 2*mt()-a.renderingStartTime>Oi&&l!==536870912&&(t.flags|=128,n=!0,vn(a,!1),t.lanes=4194304);a.isBackwards?(i.sibling=t.child,t.child=i):(e=a.last,e!==null?e.sibling=i:t.child=i,a.last=i)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=mt(),e.sibling=null,l=Ue.current,H(Ue,n?l&1|2:l&1),me&&Kt(t,a.treeForkCount),e):(je(t),null);case 22:case 23:return vt(t),ss(),a=t.memoizedState!==null,e!==null?e.memoizedState!==null!==a&&(t.flags|=8192):a&&(t.flags|=8192),a?(l&536870912)!==0&&(t.flags&128)===0&&(je(t),t.subtreeFlags&6&&(t.flags|=8192)):je(t),l=t.updateQueue,l!==null&&ji(t,l.retryQueue),l=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),a=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(a=t.memoizedState.cachePool.pool),a!==l&&(t.flags|=2048),e!==null&&E(Jl),null;case 24:return l=null,e!==null&&(l=e.memoizedState.cache),t.memoizedState.cache!==l&&(t.flags|=2048),Wt(Be),je(t),null;case 25:return null;case 30:return null}throw Error(r(156,t.tag))}function tp(e,t){switch(Vc(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Wt(Be),ae(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Yt(t),null;case 31:if(t.memoizedState!==null){if(vt(t),t.alternate===null)throw Error(r(340));Ql()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(vt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(r(340));Ql()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return E(Ue),null;case 4:return ae(),null;case 10:return Wt(t.type),null;case 22:case 23:return vt(t),ss(),e!==null&&E(Jl),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Wt(Be),null;case 25:return null;default:return null}}function gf(e,t){switch(Vc(t),t.tag){case 3:Wt(Be),ae();break;case 26:case 27:case 5:Yt(t);break;case 4:ae();break;case 31:t.memoizedState!==null&&vt(t);break;case 13:vt(t);break;case 19:E(Ue);break;case 10:Wt(t.type);break;case 22:case 23:vt(t),ss(),e!==null&&E(Jl);break;case 24:Wt(Be)}}function xn(e,t){try{var l=t.updateQueue,a=l!==null?l.lastEffect:null;if(a!==null){var n=a.next;l=n;do{if((l.tag&e)===e){a=void 0;var i=l.create,c=l.inst;a=i(),c.destroy=a}l=l.next}while(l!==n)}}catch(u){xe(t,t.return,u)}}function _l(e,t,l){try{var a=t.updateQueue,n=a!==null?a.lastEffect:null;if(n!==null){var i=n.next;a=i;do{if((a.tag&e)===e){var c=a.inst,u=c.destroy;if(u!==void 0){c.destroy=void 0,n=t;var f=l,v=u;try{v()}catch(k){xe(n,f,k)}}}a=a.next}while(a!==i)}}catch(k){xe(t,t.return,k)}}function yf(e){var t=e.updateQueue;if(t!==null){var l=e.stateNode;try{cr(t,l)}catch(a){xe(e,e.return,a)}}}function bf(e,t,l){l.props=Pl(e.type,e.memoizedProps),l.state=e.memoizedState;try{l.componentWillUnmount()}catch(a){xe(e,t,a)}}function Sn(e,t){try{var l=e.ref;if(l!==null){switch(e.tag){case 26:case 27:case 5:var a=e.stateNode;break;case 30:a=e.stateNode;break;default:a=e.stateNode}typeof l=="function"?e.refCleanup=l(a):l.current=a}}catch(n){xe(e,t,n)}}function Lt(e,t){var l=e.ref,a=e.refCleanup;if(l!==null)if(typeof a=="function")try{a()}catch(n){xe(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(n){xe(e,t,n)}else l.current=null}function vf(e){var t=e.type,l=e.memoizedProps,a=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":l.autoFocus&&a.focus();break e;case"img":l.src?a.src=l.src:l.srcSet&&(a.srcset=l.srcSet)}}catch(n){xe(e,e.return,n)}}function Ls(e,t,l){try{var a=e.stateNode;_p(a,e.type,l,t),a[nt]=t}catch(n){xe(e,e.return,n)}}function xf(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&El(e.type)||e.tag===4}function qs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||xf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&El(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Gs(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(e,t):(t=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,t.appendChild(e),l=l._reactRootContainer,l!=null||t.onclick!==null||(t.onclick=Zt));else if(a!==4&&(a===27&&El(e.type)&&(l=e.stateNode,t=null),e=e.child,e!==null))for(Gs(e,t,l),e=e.sibling;e!==null;)Gs(e,t,l),e=e.sibling}function Ci(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?l.insertBefore(e,t):l.appendChild(e);else if(a!==4&&(a===27&&El(e.type)&&(l=e.stateNode),e=e.child,e!==null))for(Ci(e,t,l),e=e.sibling;e!==null;)Ci(e,t,l),e=e.sibling}function Sf(e){var t=e.stateNode,l=e.memoizedProps;try{for(var a=e.type,n=t.attributes;n.length;)t.removeAttributeNode(n[0]);et(t,a,l),t[$e]=e,t[nt]=l}catch(i){xe(e,e.return,i)}}var el=!1,Ge=!1,Ys=!1,zf=typeof WeakSet=="function"?WeakSet:Set,We=null;function lp(e,t){if(e=e.containerInfo,ou=$i,e=Oo(e),Rc(e)){if("selectionStart"in e)var l={start:e.selectionStart,end:e.selectionEnd};else e:{l=(l=e.ownerDocument)&&l.defaultView||window;var a=l.getSelection&&l.getSelection();if(a&&a.rangeCount!==0){l=a.anchorNode;var n=a.anchorOffset,i=a.focusNode;a=a.focusOffset;try{l.nodeType,i.nodeType}catch{l=null;break e}var c=0,u=-1,f=-1,v=0,k=0,C=e,x=null;t:for(;;){for(var z;C!==l||n!==0&&C.nodeType!==3||(u=c+n),C!==i||a!==0&&C.nodeType!==3||(f=c+a),C.nodeType===3&&(c+=C.nodeValue.length),(z=C.firstChild)!==null;)x=C,C=z;for(;;){if(C===e)break t;if(x===l&&++v===n&&(u=c),x===i&&++k===a&&(f=c),(z=C.nextSibling)!==null)break;C=x,x=C.parentNode}C=z}l=u===-1||f===-1?null:{start:u,end:f}}else l=null}l=l||{start:0,end:0}}else l=null;for(ru={focusedElem:e,selectionRange:l},$i=!1,We=t;We!==null;)if(t=We,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,We=e;else for(;We!==null;){switch(t=We,i=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(l=0;l title"))),et(i,a,l),i[$e]=e,Je(i),a=i;break e;case"link":var c=jd("link","href",n).get(a+(l.href||""));if(c){for(var u=0;u_e&&(c=_e,_e=F,F=c);var p=Mo(u,F),d=Mo(u,_e);if(p&&d&&(z.rangeCount!==1||z.anchorNode!==p.node||z.anchorOffset!==p.offset||z.focusNode!==d.node||z.focusOffset!==d.offset)){var b=C.createRange();b.setStart(p.node,p.offset),z.removeAllRanges(),F>_e?(z.addRange(b),z.extend(d.node,d.offset)):(b.setEnd(d.node,d.offset),z.addRange(b))}}}}for(C=[],z=u;z=z.parentNode;)z.nodeType===1&&C.push({element:z,left:z.scrollLeft,top:z.scrollTop});for(typeof u.focus=="function"&&u.focus(),u=0;ul?32:l,T.T=null,l=Ws,Ws=null;var i=Al,c=il;if(Xe=0,Ua=Al=null,il=0,(be&6)!==0)throw Error(r(331));var u=be;if(be|=4,Of(i.current),Ef(i,i.current,c,l),be=u,An(0,!1),pt&&typeof pt.onPostCommitFiberRoot=="function")try{pt.onPostCommitFiberRoot(Za,i)}catch{}return!0}finally{R.p=n,T.T=a,Ff(e,t)}}function Pf(e,t,l){t=At(l,t),t=js(e.stateNode,t,2),e=xl(e,t,2),e!==null&&(Va(e,2),qt(e))}function xe(e,t,l){if(e.tag===3)Pf(e,e,l);else for(;t!==null;){if(t.tag===3){Pf(t,e,l);break}else if(t.tag===1){var a=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(kl===null||!kl.has(a))){e=At(l,e),l=Pr(2),a=xl(t,l,2),a!==null&&(ef(l,a,t,e),Va(a,2),qt(a));break}}t=t.return}}function Ps(e,t,l){var a=e.pingCache;if(a===null){a=e.pingCache=new ip;var n=new Set;a.set(t,n)}else n=a.get(t),n===void 0&&(n=new Set,a.set(t,n));n.has(l)||(Qs=!0,n.add(l),e=rp.bind(null,e,t,l),t.then(e,e))}function rp(e,t,l){var a=e.pingCache;a!==null&&a.delete(t),e.pingedLanes|=e.suspendedLanes&l,e.warmLanes&=~l,Te===e&&(oe&l)===l&&(we===4||we===3&&(oe&62914560)===oe&&300>mt()-wi?(be&2)===0&&Ha(e,0):Vs|=l,Ra===oe&&(Ra=0)),qt(e)}function ed(e,t){t===0&&(t=Vu()),e=Xl(e,t),e!==null&&(Va(e,t),qt(e))}function fp(e){var t=e.memoizedState,l=0;t!==null&&(l=t.retryLane),ed(e,l)}function dp(e,t){var l=0;switch(e.tag){case 31:case 13:var a=e.stateNode,n=e.memoizedState;n!==null&&(l=n.retryLane);break;case 19:a=e.stateNode;break;case 22:a=e.stateNode._retryCache;break;default:throw Error(r(314))}a!==null&&a.delete(t),ed(e,l)}function mp(e,t){return dc(e,t)}var Li=null,La=null,eu=!1,qi=!1,tu=!1,Cl=0;function qt(e){e!==La&&e.next===null&&(La===null?Li=La=e:La=La.next=e),qi=!0,eu||(eu=!0,hp())}function An(e,t){if(!tu&&qi){tu=!0;do for(var l=!1,a=Li;a!==null;){if(e!==0){var n=a.pendingLanes;if(n===0)var i=0;else{var c=a.suspendedLanes,u=a.pingedLanes;i=(1<<31-ht(42|e)+1)-1,i&=n&~(c&~u),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(l=!0,nd(a,i))}else i=oe,i=Zn(a,a===Te?i:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(i&3)===0||Qa(a,i)||(l=!0,nd(a,i));a=a.next}while(l);tu=!1}}function pp(){td()}function td(){qi=eu=!1;var e=0;Cl!==0&&Np()&&(e=Cl);for(var t=mt(),l=null,a=Li;a!==null;){var n=a.next,i=ld(a,t);i===0?(a.next=null,l===null?Li=n:l.next=n,n===null&&(La=l)):(l=a,(e!==0||(i&3)!==0)&&(qi=!0)),a=n}Xe!==0&&Xe!==5||An(e),Cl!==0&&(Cl=0)}function ld(e,t){for(var l=e.suspendedLanes,a=e.pingedLanes,n=e.expirationTimes,i=e.pendingLanes&-62914561;0u)break;var k=f.transferSize,C=f.initiatorType;k&&dd(C)&&(f=f.responseEnd,c+=k*(f"u"?null:document;function Td(e,t,l){var a=qa;if(a&&typeof t=="string"&&t){var n=Nt(t);n='link[rel="'+e+'"][href="'+n+'"]',typeof l=="string"&&(n+='[crossorigin="'+l+'"]'),_d.has(n)||(_d.add(n),e={rel:e,crossOrigin:l,href:t},a.querySelector(n)===null&&(t=a.createElement("link"),et(t,"link",e),Je(t),a.head.appendChild(t)))}}function Dp(e){cl.D(e),Td("dns-prefetch",e,null)}function Rp(e,t){cl.C(e,t),Td("preconnect",e,t)}function Up(e,t,l){cl.L(e,t,l);var a=qa;if(a&&e&&t){var n='link[rel="preload"][as="'+Nt(t)+'"]';t==="image"&&l&&l.imageSrcSet?(n+='[imagesrcset="'+Nt(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(n+='[imagesizes="'+Nt(l.imageSizes)+'"]')):n+='[href="'+Nt(e)+'"]';var i=n;switch(t){case"style":i=Ga(e);break;case"script":i=Ya(e)}Ot.has(i)||(e=w({rel:"preload",href:t==="image"&&l&&l.imageSrcSet?void 0:e,as:t},l),Ot.set(i,e),a.querySelector(n)!==null||t==="style"&&a.querySelector(Mn(i))||t==="script"&&a.querySelector(wn(i))||(t=a.createElement("link"),et(t,"link",e),Je(t),a.head.appendChild(t)))}}function Hp(e,t){cl.m(e,t);var l=qa;if(l&&e){var a=t&&typeof t.as=="string"?t.as:"script",n='link[rel="modulepreload"][as="'+Nt(a)+'"][href="'+Nt(e)+'"]',i=n;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=Ya(e)}if(!Ot.has(i)&&(e=w({rel:"modulepreload",href:e},t),Ot.set(i,e),l.querySelector(n)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(wn(i)))return}a=l.createElement("link"),et(a,"link",e),Je(a),l.head.appendChild(a)}}}function Bp(e,t,l){cl.S(e,t,l);var a=qa;if(a&&e){var n=oa(a).hoistableStyles,i=Ga(e);t=t||"default";var c=n.get(i);if(!c){var u={loading:0,preload:null};if(c=a.querySelector(Mn(i)))u.loading=5;else{e=w({rel:"stylesheet",href:e,"data-precedence":t},l),(l=Ot.get(i))&&yu(e,l);var f=c=a.createElement("link");Je(f),et(f,"link",e),f._p=new Promise(function(v,k){f.onload=v,f.onerror=k}),f.addEventListener("load",function(){u.loading|=1}),f.addEventListener("error",function(){u.loading|=2}),u.loading|=4,Qi(c,t,a)}c={type:"stylesheet",instance:c,count:1,state:u},n.set(i,c)}}}function Lp(e,t){cl.X(e,t);var l=qa;if(l&&e){var a=oa(l).hoistableScripts,n=Ya(e),i=a.get(n);i||(i=l.querySelector(wn(n)),i||(e=w({src:e,async:!0},t),(t=Ot.get(n))&&bu(e,t),i=l.createElement("script"),Je(i),et(i,"link",e),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},a.set(n,i))}}function qp(e,t){cl.M(e,t);var l=qa;if(l&&e){var a=oa(l).hoistableScripts,n=Ya(e),i=a.get(n);i||(i=l.querySelector(wn(n)),i||(e=w({src:e,async:!0,type:"module"},t),(t=Ot.get(n))&&bu(e,t),i=l.createElement("script"),Je(i),et(i,"link",e),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},a.set(n,i))}}function Nd(e,t,l,a){var n=(n=J.current)?Zi(n):null;if(!n)throw Error(r(446));switch(e){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(t=Ga(l.href),l=oa(n).hoistableStyles,a=l.get(t),a||(a={type:"style",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){e=Ga(l.href);var i=oa(n).hoistableStyles,c=i.get(e);if(c||(n=n.ownerDocument||n,c={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(e,c),(i=n.querySelector(Mn(e)))&&!i._p&&(c.instance=i,c.state.loading=5),Ot.has(e)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Ot.set(e,l),i||Gp(n,e,l,c.state))),t&&a===null)throw Error(r(528,""));return c}if(t&&a!==null)throw Error(r(529,""));return null;case"script":return t=l.async,l=l.src,typeof l=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ya(l),l=oa(n).hoistableScripts,a=l.get(t),a||(a={type:"script",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,e))}}function Ga(e){return'href="'+Nt(e)+'"'}function Mn(e){return'link[rel="stylesheet"]['+e+"]"}function kd(e){return w({},e,{"data-precedence":e.precedence,precedence:null})}function Gp(e,t,l,a){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?a.loading=1:(t=e.createElement("link"),a.preload=t,t.addEventListener("load",function(){return a.loading|=1}),t.addEventListener("error",function(){return a.loading|=2}),et(t,"link",l),Je(t),e.head.appendChild(t))}function Ya(e){return'[src="'+Nt(e)+'"]'}function wn(e){return"script[async]"+e}function Ad(e,t,l){if(t.count++,t.instance===null)switch(t.type){case"style":var a=e.querySelector('style[data-href~="'+Nt(l.href)+'"]');if(a)return t.instance=a,Je(a),a;var n=w({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return a=(e.ownerDocument||e).createElement("style"),Je(a),et(a,"style",n),Qi(a,l.precedence,e),t.instance=a;case"stylesheet":n=Ga(l.href);var i=e.querySelector(Mn(n));if(i)return t.state.loading|=4,t.instance=i,Je(i),i;a=kd(l),(n=Ot.get(n))&&yu(a,n),i=(e.ownerDocument||e).createElement("link"),Je(i);var c=i;return c._p=new Promise(function(u,f){c.onload=u,c.onerror=f}),et(i,"link",a),t.state.loading|=4,Qi(i,l.precedence,e),t.instance=i;case"script":return i=Ya(l.src),(n=e.querySelector(wn(i)))?(t.instance=n,Je(n),n):(a=l,(n=Ot.get(i))&&(a=w({},l),bu(a,n)),e=e.ownerDocument||e,n=e.createElement("script"),Je(n),et(n,"link",a),e.head.appendChild(n),t.instance=n);case"void":return null;default:throw Error(r(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(a=t.instance,t.state.loading|=4,Qi(a,l.precedence,e));return t.instance}function Qi(e,t,l){for(var a=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=a.length?a[a.length-1]:null,i=n,c=0;c title"):null)}function Yp(e,t,l){if(l===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return e=t.disabled,typeof t.precedence=="string"&&e==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Ed(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function Xp(e,t,l,a){if(l.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var n=Ga(a.href),i=t.querySelector(Mn(n));if(i){t=i._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Ki.bind(e),t.then(e,e)),l.state.loading|=4,l.instance=i,Je(i);return}i=t.ownerDocument||t,a=kd(a),(n=Ot.get(n))&&yu(a,n),i=i.createElement("link"),Je(i);var c=i;c._p=new Promise(function(u,f){c.onload=u,c.onerror=f}),et(i,"link",a),l.instance=i}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(l,t),(t=l.state.preload)&&(l.state.loading&3)===0&&(e.count++,l=Ki.bind(e),t.addEventListener("load",l),t.addEventListener("error",l))}}var vu=0;function Zp(e,t){return e.stylesheets&&e.count===0&&Wi(e,e.stylesheets),0vu?50:800)+t);return e.unsuspend=l,function(){e.unsuspend=null,clearTimeout(a),clearTimeout(n)}}:null}function Ki(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Wi(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Ji=null;function Wi(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Ji=new Map,t.forEach(Qp,e),Ji=null,Ki.call(e))}function Qp(e,t){if(!(t.state.loading&4)){var l=Ji.get(e);if(l)var a=l.get(null);else{l=new Map,Ji.set(e,l);for(var n=e.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(h){console.error(h)}}return o(),ju.exports=uh(),ju.exports}var rh=oh();const fh=um(rh);/** +`+a.stack}}var fc=Object.prototype.hasOwnProperty,dc=r.unstable_scheduleCallback,mc=r.unstable_cancelCallback,wm=r.unstable_shouldYield,Om=r.unstable_requestPaint,mt=r.unstable_now,Dm=r.unstable_getCurrentPriorityLevel,Xu=r.unstable_ImmediatePriority,Zu=r.unstable_UserBlockingPriority,qn=r.unstable_NormalPriority,Rm=r.unstable_LowPriority,Qu=r.unstable_IdlePriority,Um=r.log,Hm=r.unstable_setDisableYieldValue,Za=null,pt=null;function fl(e){if(typeof Um=="function"&&Hm(e),pt&&typeof pt.setStrictMode=="function")try{pt.setStrictMode(Za,e)}catch{}}var ht=Math.clz32?Math.clz32:qm,Bm=Math.log,Lm=Math.LN2;function qm(e){return e>>>=0,e===0?32:31-(Bm(e)/Lm|0)|0}var Gn=256,Yn=262144,Xn=4194304;function Bl(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Zn(e,t,l){var a=e.pendingLanes;if(a===0)return 0;var n=0,i=e.suspendedLanes,c=e.pingedLanes;e=e.warmLanes;var u=a&134217727;return u!==0?(a=u&~i,a!==0?n=Bl(a):(c&=u,c!==0?n=Bl(c):l||(l=u&~e,l!==0&&(n=Bl(l))))):(u=a&~i,u!==0?n=Bl(u):c!==0?n=Bl(c):l||(l=a&~e,l!==0&&(n=Bl(l)))),n===0?0:t!==0&&t!==n&&(t&i)===0&&(i=n&-n,l=t&-t,i>=l||i===32&&(l&4194048)!==0)?t:n}function Qa(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Gm(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vu(){var e=Xn;return Xn<<=1,(Xn&62914560)===0&&(Xn=4194304),e}function pc(e){for(var t=[],l=0;31>l;l++)t.push(e);return t}function Va(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ym(e,t,l,a,n,i){var c=e.pendingLanes;e.pendingLanes=l,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=l,e.entangledLanes&=l,e.errorRecoveryDisabledLanes&=l,e.shellSuspendCounter=0;var u=e.entanglements,f=e.expirationTimes,v=e.hiddenUpdates;for(l=c&~l;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var Jm=/[\n"\\]/g;function Nt(e){return e.replace(Jm,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function xc(e,t,l,a,n,i,c,u){e.name="",c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"?e.type=c:e.removeAttribute("type"),t!=null?c==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Tt(t)):e.value!==""+Tt(t)&&(e.value=""+Tt(t)):c!=="submit"&&c!=="reset"||e.removeAttribute("value"),t!=null?Sc(e,c,Tt(t)):l!=null?Sc(e,c,Tt(l)):a!=null&&e.removeAttribute("value"),n==null&&i!=null&&(e.defaultChecked=!!i),n!=null&&(e.checked=n&&typeof n!="function"&&typeof n!="symbol"),u!=null&&typeof u!="function"&&typeof u!="symbol"&&typeof u!="boolean"?e.name=""+Tt(u):e.removeAttribute("name")}function ir(e,t,l,a,n,i,c,u){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(e.type=i),t!=null||l!=null){if(!(i!=="submit"&&i!=="reset"||t!=null)){vc(e);return}l=l!=null?""+Tt(l):"",t=t!=null?""+Tt(t):l,u||t===e.value||(e.value=t),e.defaultValue=t}a=a??n,a=typeof a!="function"&&typeof a!="symbol"&&!!a,e.checked=u?e.checked:!!a,e.defaultChecked=!!a,c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"&&(e.name=c),vc(e)}function Sc(e,t,l){t==="number"&&Kn(e.ownerDocument)===e||e.defaultValue===""+l||(e.defaultValue=""+l)}function fa(e,t,l,a){if(e=e.options,t){t={};for(var n=0;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),kc=!1;if(Qt)try{var $a={};Object.defineProperty($a,"passive",{get:function(){kc=!0}}),window.addEventListener("test",$a,$a),window.removeEventListener("test",$a,$a)}catch{kc=!1}var ml=null,Ac=null,Wn=null;function dr(){if(Wn)return Wn;var e,t=Ac,l=t.length,a,n="value"in ml?ml.value:ml.textContent,i=n.length;for(e=0;e=Pa),br=" ",vr=!1;function xr(e,t){switch(e){case"keyup":return zp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Sr(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ha=!1;function Tp(e,t){switch(e){case"compositionend":return Sr(t);case"keypress":return t.which!==32?null:(vr=!0,br);case"textInput":return e=t.data,e===br&&vr?null:e;default:return null}}function Np(e,t){if(ha)return e==="compositionend"||!wc&&xr(e,t)?(e=dr(),Wn=Ac=ml=null,ha=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:l,offset:t-e};e=a}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Cr(l)}}function Mr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Mr(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function wr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Kn(e.document);t instanceof e.HTMLIFrameElement;){try{var l=typeof t.contentWindow.location.href=="string"}catch{l=!1}if(l)e=t.contentWindow;else break;t=Kn(e.document)}return t}function Rc(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var Op=Qt&&"documentMode"in document&&11>=document.documentMode,ga=null,Uc=null,an=null,Hc=!1;function Or(e,t,l){var a=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Hc||ga==null||ga!==Kn(a)||(a=ga,"selectionStart"in a&&Rc(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),an&&ln(an,a)||(an=a,a=Yi(Uc,"onSelect"),0>=c,n-=c,Ht=1<<32-ht(t)+n|l<le?(oe=Z,Z=null):oe=Z.sibling;var ge=x(p,Z,b[le],j);if(ge===null){Z===null&&(Z=oe);break}e&&Z&&ge.alternate===null&&t(p,Z),d=i(ge,d,le),he===null?K=ge:he.sibling=ge,he=ge,Z=oe}if(le===b.length)return l(p,Z),me&&Kt(p,le),K;if(Z===null){for(;lele?(oe=Z,Z=null):oe=Z.sibling;var Rl=x(p,Z,ge.value,j);if(Rl===null){Z===null&&(Z=oe);break}e&&Z&&Rl.alternate===null&&t(p,Z),d=i(Rl,d,le),he===null?K=Rl:he.sibling=Rl,he=Rl,Z=oe}if(ge.done)return l(p,Z),me&&Kt(p,le),K;if(Z===null){for(;!ge.done;le++,ge=b.next())ge=C(p,ge.value,j),ge!==null&&(d=i(ge,d,le),he===null?K=ge:he.sibling=ge,he=ge);return me&&Kt(p,le),K}for(Z=a(Z);!ge.done;le++,ge=b.next())ge=S(Z,p,le,ge.value,j),ge!==null&&(e&&ge.alternate!==null&&Z.delete(ge.key===null?le:ge.key),d=i(ge,d,le),he===null?K=ge:he.sibling=ge,he=ge);return e&&Z.forEach(function(Ph){return t(p,Ph)}),me&&Kt(p,le),K}function _e(p,d,b,j){if(typeof b=="object"&&b!==null&&b.type===D&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case V:e:{for(var K=b.key;d!==null;){if(d.key===K){if(K=b.type,K===D){if(d.tag===7){l(p,d.sibling),j=n(d,b.props.children),j.return=p,p=j;break e}}else if(d.elementType===K||typeof K=="object"&&K!==null&&K.$$typeof===B&&Wl(K)===d.type){l(p,d.sibling),j=n(d,b.props),on(j,b),j.return=p,p=j;break e}l(p,d);break}else t(p,d);d=d.sibling}b.type===D?(j=Zl(b.props.children,p.mode,j,b.key),j.return=p,p=j):(j=ii(b.type,b.key,b.props,null,p.mode,j),on(j,b),j.return=p,p=j)}return c(p);case M:e:{for(K=b.key;d!==null;){if(d.key===K)if(d.tag===4&&d.stateNode.containerInfo===b.containerInfo&&d.stateNode.implementation===b.implementation){l(p,d.sibling),j=n(d,b.children||[]),j.return=p,p=j;break e}else{l(p,d);break}else t(p,d);d=d.sibling}j=Zc(b,p.mode,j),j.return=p,p=j}return c(p);case B:return b=Wl(b),_e(p,d,b,j)}if(Ve(b))return X(p,d,b,j);if(Re(b)){if(K=Re(b),typeof K!="function")throw Error(o(150));return b=K.call(b),F(p,d,b,j)}if(typeof b.then=="function")return _e(p,d,di(b),j);if(b.$$typeof===Ne)return _e(p,d,ui(p,b),j);mi(p,b)}return typeof b=="string"&&b!==""||typeof b=="number"||typeof b=="bigint"?(b=""+b,d!==null&&d.tag===6?(l(p,d.sibling),j=n(d,b),j.return=p,p=j):(l(p,d),j=Xc(b,p.mode,j),j.return=p,p=j),c(p)):l(p,d)}return function(p,d,b,j){try{rn=0;var K=_e(p,d,b,j);return Aa=null,K}catch(Z){if(Z===ka||Z===oi)throw Z;var he=yt(29,Z,null,p.mode);return he.lanes=j,he.return=p,he}finally{}}}var Fl=lo(!0),ao=lo(!1),bl=!1;function ls(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function as(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function vl(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function xl(e,t,l){var a=e.updateQueue;if(a===null)return null;if(a=a.shared,(be&2)!==0){var n=a.pending;return n===null?t.next=t:(t.next=n.next,n.next=t),a.pending=t,t=ni(e),qr(e,null,l),t}return ai(e,a,t,l),ni(e)}function fn(e,t,l){if(t=t.updateQueue,t!==null&&(t=t.shared,(l&4194048)!==0)){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,Ju(e,l)}}function ns(e,t){var l=e.updateQueue,a=e.alternate;if(a!==null&&(a=a.updateQueue,l===a)){var n=null,i=null;if(l=l.firstBaseUpdate,l!==null){do{var c={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};i===null?n=i=c:i=i.next=c,l=l.next}while(l!==null);i===null?n=i=t:i=i.next=t}else n=i=t;l={baseState:a.baseState,firstBaseUpdate:n,lastBaseUpdate:i,shared:a.shared,callbacks:a.callbacks},e.updateQueue=l;return}e=l.lastBaseUpdate,e===null?l.firstBaseUpdate=t:e.next=t,l.lastBaseUpdate=t}var is=!1;function dn(){if(is){var e=Na;if(e!==null)throw e}}function mn(e,t,l,a){is=!1;var n=e.updateQueue;bl=!1;var i=n.firstBaseUpdate,c=n.lastBaseUpdate,u=n.shared.pending;if(u!==null){n.shared.pending=null;var f=u,v=f.next;f.next=null,c===null?i=v:c.next=v,c=f;var k=e.alternate;k!==null&&(k=k.updateQueue,u=k.lastBaseUpdate,u!==c&&(u===null?k.firstBaseUpdate=v:u.next=v,k.lastBaseUpdate=f))}if(i!==null){var C=n.baseState;c=0,k=v=f=null,u=i;do{var x=u.lane&-536870913,S=x!==u.lane;if(S?(re&x)===x:(a&x)===x){x!==0&&x===Ta&&(is=!0),k!==null&&(k=k.next={lane:0,tag:u.tag,payload:u.payload,callback:null,next:null});e:{var X=e,F=u;x=t;var _e=l;switch(F.tag){case 1:if(X=F.payload,typeof X=="function"){C=X.call(_e,C,x);break e}C=X;break e;case 3:X.flags=X.flags&-65537|128;case 0:if(X=F.payload,x=typeof X=="function"?X.call(_e,C,x):X,x==null)break e;C=w({},C,x);break e;case 2:bl=!0}}x=u.callback,x!==null&&(e.flags|=64,S&&(e.flags|=8192),S=n.callbacks,S===null?n.callbacks=[x]:S.push(x))}else S={lane:x,tag:u.tag,payload:u.payload,callback:u.callback,next:null},k===null?(v=k=S,f=C):k=k.next=S,c|=x;if(u=u.next,u===null){if(u=n.shared.pending,u===null)break;S=u,u=S.next,S.next=null,n.lastBaseUpdate=S,n.shared.pending=null}}while(!0);k===null&&(f=C),n.baseState=f,n.firstBaseUpdate=v,n.lastBaseUpdate=k,i===null&&(n.shared.lanes=0),Nl|=c,e.lanes=c,e.memoizedState=C}}function no(e,t){if(typeof e!="function")throw Error(o(191,e));e.call(t)}function io(e,t){var l=e.callbacks;if(l!==null)for(e.callbacks=null,e=0;ei?i:8;var c=T.T,u={};T.T=u,Ts(e,!1,t,l);try{var f=n(),v=T.S;if(v!==null&&v(u,f),f!==null&&typeof f=="object"&&typeof f.then=="function"){var k=Yp(f,a);gn(e,t,k,zt(e))}else gn(e,t,a,zt(e))}catch(C){gn(e,t,{then:function(){},status:"rejected",reason:C},zt())}finally{R.p=i,c!==null&&u.types!==null&&(c.types=u.types),T.T=c}}function Jp(){}function zs(e,t,l,a){if(e.tag!==5)throw Error(o(476));var n=Bo(e).queue;Ho(e,n,t,$,l===null?Jp:function(){return Lo(e),l(a)})}function Bo(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ft,lastRenderedState:$},next:null};var l={};return t.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ft,lastRenderedState:l},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Lo(e){var t=Bo(e);t.next===null&&(t=e.alternate.memoizedState),gn(e,t.next.queue,{},zt())}function _s(){return Ie(On)}function qo(){return He().memoizedState}function Go(){return He().memoizedState}function Wp(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var l=zt();e=vl(l);var a=xl(t,e,l);a!==null&&(ot(a,t,l),fn(a,t,l)),t={cache:Ic()},e.payload=t;return}t=t.return}}function $p(e,t,l){var a=zt();l={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},_i(e)?Xo(t,l):(l=Gc(e,t,l,a),l!==null&&(ot(l,e,a),Zo(l,t,a)))}function Yo(e,t,l){var a=zt();gn(e,t,l,a)}function gn(e,t,l,a){var n={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(_i(e))Xo(t,n);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var c=t.lastRenderedState,u=i(c,l);if(n.hasEagerState=!0,n.eagerState=u,gt(u,c))return ai(e,t,n,0),Te===null&&li(),!1}catch{}finally{}if(l=Gc(e,t,n,a),l!==null)return ot(l,e,a),Zo(l,t,a),!0}return!1}function Ts(e,t,l,a){if(a={lane:2,revertLane:lu(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},_i(e)){if(t)throw Error(o(479))}else t=Gc(e,l,a,2),t!==null&&ot(t,e,2)}function _i(e){var t=e.alternate;return e===te||t!==null&&t===te}function Xo(e,t){Ca=gi=!0;var l=e.pending;l===null?t.next=t:(t.next=l.next,l.next=t),e.pending=t}function Zo(e,t,l){if((l&4194048)!==0){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,Ju(e,l)}}var yn={readContext:Ie,use:vi,useCallback:Me,useContext:Me,useEffect:Me,useImperativeHandle:Me,useLayoutEffect:Me,useInsertionEffect:Me,useMemo:Me,useReducer:Me,useRef:Me,useState:Me,useDebugValue:Me,useDeferredValue:Me,useTransition:Me,useSyncExternalStore:Me,useId:Me,useHostTransitionStatus:Me,useFormState:Me,useActionState:Me,useOptimistic:Me,useMemoCache:Me,useCacheRefresh:Me};yn.useEffectEvent=Me;var Qo={readContext:Ie,use:vi,useCallback:function(e,t){return at().memoizedState=[e,t===void 0?null:t],e},useContext:Ie,useEffect:jo,useImperativeHandle:function(e,t,l){l=l!=null?l.concat([e]):null,Si(4194308,4,wo.bind(null,t,e),l)},useLayoutEffect:function(e,t){return Si(4194308,4,e,t)},useInsertionEffect:function(e,t){Si(4,2,e,t)},useMemo:function(e,t){var l=at();t=t===void 0?null:t;var a=e();if(Il){fl(!0);try{e()}finally{fl(!1)}}return l.memoizedState=[a,t],a},useReducer:function(e,t,l){var a=at();if(l!==void 0){var n=l(t);if(Il){fl(!0);try{l(t)}finally{fl(!1)}}}else n=t;return a.memoizedState=a.baseState=n,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},a.queue=e,e=e.dispatch=$p.bind(null,te,e),[a.memoizedState,e]},useRef:function(e){var t=at();return e={current:e},t.memoizedState=e},useState:function(e){e=ys(e);var t=e.queue,l=Yo.bind(null,te,t);return t.dispatch=l,[e.memoizedState,l]},useDebugValue:xs,useDeferredValue:function(e,t){var l=at();return Ss(l,e,t)},useTransition:function(){var e=ys(!1);return e=Ho.bind(null,te,e.queue,!0,!1),at().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,l){var a=te,n=at();if(me){if(l===void 0)throw Error(o(407));l=l()}else{if(l=t(),Te===null)throw Error(o(349));(re&127)!==0||fo(a,t,l)}n.memoizedState=l;var i={value:l,getSnapshot:t};return n.queue=i,jo(po.bind(null,a,i,e),[e]),a.flags|=2048,Ma(9,{destroy:void 0},mo.bind(null,a,i,l,t),null),l},useId:function(){var e=at(),t=Te.identifierPrefix;if(me){var l=Bt,a=Ht;l=(a&~(1<<32-ht(a)-1)).toString(32)+l,t="_"+t+"R_"+l,l=yi++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof a.is=="string"?c.createElement("select",{is:a.is}):c.createElement("select"),a.multiple?i.multiple=!0:a.size&&(i.size=a.size);break;default:i=typeof a.is=="string"?c.createElement(n,{is:a.is}):c.createElement(n)}}i[$e]=t,i[nt]=a;e:for(c=t.child;c!==null;){if(c.tag===5||c.tag===6)i.appendChild(c.stateNode);else if(c.tag!==4&&c.tag!==27&&c.child!==null){c.child.return=c,c=c.child;continue}if(c===t)break e;for(;c.sibling===null;){if(c.return===null||c.return===t)break e;c=c.return}c.sibling.return=c.return,c=c.sibling}t.stateNode=i;e:switch(et(i,n,a),n){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break e;case"img":a=!0;break e;default:a=!1}a&&Pt(t)}}return je(t),Bs(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,l),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==a&&Pt(t);else{if(typeof a!="string"&&t.stateNode===null)throw Error(o(166));if(e=J.current,za(t)){if(e=t.stateNode,l=t.memoizedProps,a=null,n=Fe,n!==null)switch(n.tag){case 27:case 5:a=n.memoizedProps}e[$e]=t,e=!!(e.nodeValue===l||a!==null&&a.suppressHydrationWarning===!0||fd(e.nodeValue,l)),e||gl(t,!0)}else e=Xi(e).createTextNode(a),e[$e]=t,t.stateNode=e}return je(t),null;case 31:if(l=t.memoizedState,e===null||e.memoizedState!==null){if(a=za(t),l!==null){if(e===null){if(!a)throw Error(o(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(o(557));e[$e]=t}else Ql(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;je(t),e=!1}else l=Jc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=l),e=!0;if(!e)return t.flags&256?(vt(t),t):(vt(t),null);if((t.flags&128)!==0)throw Error(o(558))}return je(t),null;case 13:if(a=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(n=za(t),a!==null&&a.dehydrated!==null){if(e===null){if(!n)throw Error(o(318));if(n=t.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(o(317));n[$e]=t}else Ql(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;je(t),n=!1}else n=Jc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),n=!0;if(!n)return t.flags&256?(vt(t),t):(vt(t),null)}return vt(t),(t.flags&128)!==0?(t.lanes=l,t):(l=a!==null,e=e!==null&&e.memoizedState!==null,l&&(a=t.child,n=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(n=a.alternate.memoizedState.cachePool.pool),i=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(i=a.memoizedState.cachePool.pool),i!==n&&(a.flags|=2048)),l!==e&&l&&(t.child.flags|=8192),ji(t,t.updateQueue),je(t),null);case 4:return ae(),e===null&&cu(t.stateNode.containerInfo),je(t),null;case 10:return Wt(t.type),je(t),null;case 19:if(E(Ue),a=t.memoizedState,a===null)return je(t),null;if(n=(t.flags&128)!==0,i=a.rendering,i===null)if(n)vn(a,!1);else{if(we!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(i=hi(e),i!==null){for(t.flags|=128,vn(a,!1),e=i.updateQueue,t.updateQueue=e,ji(t,e),t.subtreeFlags=0,e=l,l=t.child;l!==null;)Gr(l,e),l=l.sibling;return H(Ue,Ue.current&1|2),me&&Kt(t,a.treeForkCount),t.child}e=e.sibling}a.tail!==null&&mt()>Oi&&(t.flags|=128,n=!0,vn(a,!1),t.lanes=4194304)}else{if(!n)if(e=hi(i),e!==null){if(t.flags|=128,n=!0,e=e.updateQueue,t.updateQueue=e,ji(t,e),vn(a,!0),a.tail===null&&a.tailMode==="hidden"&&!i.alternate&&!me)return je(t),null}else 2*mt()-a.renderingStartTime>Oi&&l!==536870912&&(t.flags|=128,n=!0,vn(a,!1),t.lanes=4194304);a.isBackwards?(i.sibling=t.child,t.child=i):(e=a.last,e!==null?e.sibling=i:t.child=i,a.last=i)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=mt(),e.sibling=null,l=Ue.current,H(Ue,n?l&1|2:l&1),me&&Kt(t,a.treeForkCount),e):(je(t),null);case 22:case 23:return vt(t),ss(),a=t.memoizedState!==null,e!==null?e.memoizedState!==null!==a&&(t.flags|=8192):a&&(t.flags|=8192),a?(l&536870912)!==0&&(t.flags&128)===0&&(je(t),t.subtreeFlags&6&&(t.flags|=8192)):je(t),l=t.updateQueue,l!==null&&ji(t,l.retryQueue),l=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),a=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(a=t.memoizedState.cachePool.pool),a!==l&&(t.flags|=2048),e!==null&&E(Jl),null;case 24:return l=null,e!==null&&(l=e.memoizedState.cache),t.memoizedState.cache!==l&&(t.flags|=2048),Wt(Be),je(t),null;case 25:return null;case 30:return null}throw Error(o(156,t.tag))}function th(e,t){switch(Vc(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Wt(Be),ae(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Yt(t),null;case 31:if(t.memoizedState!==null){if(vt(t),t.alternate===null)throw Error(o(340));Ql()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(vt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(o(340));Ql()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return E(Ue),null;case 4:return ae(),null;case 10:return Wt(t.type),null;case 22:case 23:return vt(t),ss(),e!==null&&E(Jl),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Wt(Be),null;case 25:return null;default:return null}}function gf(e,t){switch(Vc(t),t.tag){case 3:Wt(Be),ae();break;case 26:case 27:case 5:Yt(t);break;case 4:ae();break;case 31:t.memoizedState!==null&&vt(t);break;case 13:vt(t);break;case 19:E(Ue);break;case 10:Wt(t.type);break;case 22:case 23:vt(t),ss(),e!==null&&E(Jl);break;case 24:Wt(Be)}}function xn(e,t){try{var l=t.updateQueue,a=l!==null?l.lastEffect:null;if(a!==null){var n=a.next;l=n;do{if((l.tag&e)===e){a=void 0;var i=l.create,c=l.inst;a=i(),c.destroy=a}l=l.next}while(l!==n)}}catch(u){xe(t,t.return,u)}}function _l(e,t,l){try{var a=t.updateQueue,n=a!==null?a.lastEffect:null;if(n!==null){var i=n.next;a=i;do{if((a.tag&e)===e){var c=a.inst,u=c.destroy;if(u!==void 0){c.destroy=void 0,n=t;var f=l,v=u;try{v()}catch(k){xe(n,f,k)}}}a=a.next}while(a!==i)}}catch(k){xe(t,t.return,k)}}function yf(e){var t=e.updateQueue;if(t!==null){var l=e.stateNode;try{io(t,l)}catch(a){xe(e,e.return,a)}}}function bf(e,t,l){l.props=Pl(e.type,e.memoizedProps),l.state=e.memoizedState;try{l.componentWillUnmount()}catch(a){xe(e,t,a)}}function Sn(e,t){try{var l=e.ref;if(l!==null){switch(e.tag){case 26:case 27:case 5:var a=e.stateNode;break;case 30:a=e.stateNode;break;default:a=e.stateNode}typeof l=="function"?e.refCleanup=l(a):l.current=a}}catch(n){xe(e,t,n)}}function Lt(e,t){var l=e.ref,a=e.refCleanup;if(l!==null)if(typeof a=="function")try{a()}catch(n){xe(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(n){xe(e,t,n)}else l.current=null}function vf(e){var t=e.type,l=e.memoizedProps,a=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":l.autoFocus&&a.focus();break e;case"img":l.src?a.src=l.src:l.srcSet&&(a.srcset=l.srcSet)}}catch(n){xe(e,e.return,n)}}function Ls(e,t,l){try{var a=e.stateNode;_h(a,e.type,l,t),a[nt]=t}catch(n){xe(e,e.return,n)}}function xf(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&El(e.type)||e.tag===4}function qs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||xf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&El(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Gs(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(e,t):(t=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,t.appendChild(e),l=l._reactRootContainer,l!=null||t.onclick!==null||(t.onclick=Zt));else if(a!==4&&(a===27&&El(e.type)&&(l=e.stateNode,t=null),e=e.child,e!==null))for(Gs(e,t,l),e=e.sibling;e!==null;)Gs(e,t,l),e=e.sibling}function Ci(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?l.insertBefore(e,t):l.appendChild(e);else if(a!==4&&(a===27&&El(e.type)&&(l=e.stateNode),e=e.child,e!==null))for(Ci(e,t,l),e=e.sibling;e!==null;)Ci(e,t,l),e=e.sibling}function Sf(e){var t=e.stateNode,l=e.memoizedProps;try{for(var a=e.type,n=t.attributes;n.length;)t.removeAttributeNode(n[0]);et(t,a,l),t[$e]=e,t[nt]=l}catch(i){xe(e,e.return,i)}}var el=!1,Ge=!1,Ys=!1,zf=typeof WeakSet=="function"?WeakSet:Set,We=null;function lh(e,t){if(e=e.containerInfo,ru=$i,e=wr(e),Rc(e)){if("selectionStart"in e)var l={start:e.selectionStart,end:e.selectionEnd};else e:{l=(l=e.ownerDocument)&&l.defaultView||window;var a=l.getSelection&&l.getSelection();if(a&&a.rangeCount!==0){l=a.anchorNode;var n=a.anchorOffset,i=a.focusNode;a=a.focusOffset;try{l.nodeType,i.nodeType}catch{l=null;break e}var c=0,u=-1,f=-1,v=0,k=0,C=e,x=null;t:for(;;){for(var S;C!==l||n!==0&&C.nodeType!==3||(u=c+n),C!==i||a!==0&&C.nodeType!==3||(f=c+a),C.nodeType===3&&(c+=C.nodeValue.length),(S=C.firstChild)!==null;)x=C,C=S;for(;;){if(C===e)break t;if(x===l&&++v===n&&(u=c),x===i&&++k===a&&(f=c),(S=C.nextSibling)!==null)break;C=x,x=C.parentNode}C=S}l=u===-1||f===-1?null:{start:u,end:f}}else l=null}l=l||{start:0,end:0}}else l=null;for(ou={focusedElem:e,selectionRange:l},$i=!1,We=t;We!==null;)if(t=We,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,We=e;else for(;We!==null;){switch(t=We,i=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(l=0;l title"))),et(i,a,l),i[$e]=e,Je(i),a=i;break e;case"link":var c=jd("link","href",n).get(a+(l.href||""));if(c){for(var u=0;u_e&&(c=_e,_e=F,F=c);var p=Er(u,F),d=Er(u,_e);if(p&&d&&(S.rangeCount!==1||S.anchorNode!==p.node||S.anchorOffset!==p.offset||S.focusNode!==d.node||S.focusOffset!==d.offset)){var b=C.createRange();b.setStart(p.node,p.offset),S.removeAllRanges(),F>_e?(S.addRange(b),S.extend(d.node,d.offset)):(b.setEnd(d.node,d.offset),S.addRange(b))}}}}for(C=[],S=u;S=S.parentNode;)S.nodeType===1&&C.push({element:S,left:S.scrollLeft,top:S.scrollTop});for(typeof u.focus=="function"&&u.focus(),u=0;ul?32:l,T.T=null,l=Ws,Ws=null;var i=Al,c=il;if(Xe=0,Ua=Al=null,il=0,(be&6)!==0)throw Error(o(331));var u=be;if(be|=4,Of(i.current),Ef(i,i.current,c,l),be=u,An(0,!1),pt&&typeof pt.onPostCommitFiberRoot=="function")try{pt.onPostCommitFiberRoot(Za,i)}catch{}return!0}finally{R.p=n,T.T=a,Ff(e,t)}}function Pf(e,t,l){t=At(l,t),t=js(e.stateNode,t,2),e=xl(e,t,2),e!==null&&(Va(e,2),qt(e))}function xe(e,t,l){if(e.tag===3)Pf(e,e,l);else for(;t!==null;){if(t.tag===3){Pf(t,e,l);break}else if(t.tag===1){var a=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(kl===null||!kl.has(a))){e=At(l,e),l=Po(2),a=xl(t,l,2),a!==null&&(ef(l,a,t,e),Va(a,2),qt(a));break}}t=t.return}}function Ps(e,t,l){var a=e.pingCache;if(a===null){a=e.pingCache=new ih;var n=new Set;a.set(t,n)}else n=a.get(t),n===void 0&&(n=new Set,a.set(t,n));n.has(l)||(Qs=!0,n.add(l),e=oh.bind(null,e,t,l),t.then(e,e))}function oh(e,t,l){var a=e.pingCache;a!==null&&a.delete(t),e.pingedLanes|=e.suspendedLanes&l,e.warmLanes&=~l,Te===e&&(re&l)===l&&(we===4||we===3&&(re&62914560)===re&&300>mt()-wi?(be&2)===0&&Ha(e,0):Vs|=l,Ra===re&&(Ra=0)),qt(e)}function ed(e,t){t===0&&(t=Vu()),e=Xl(e,t),e!==null&&(Va(e,t),qt(e))}function fh(e){var t=e.memoizedState,l=0;t!==null&&(l=t.retryLane),ed(e,l)}function dh(e,t){var l=0;switch(e.tag){case 31:case 13:var a=e.stateNode,n=e.memoizedState;n!==null&&(l=n.retryLane);break;case 19:a=e.stateNode;break;case 22:a=e.stateNode._retryCache;break;default:throw Error(o(314))}a!==null&&a.delete(t),ed(e,l)}function mh(e,t){return dc(e,t)}var Li=null,La=null,eu=!1,qi=!1,tu=!1,Cl=0;function qt(e){e!==La&&e.next===null&&(La===null?Li=La=e:La=La.next=e),qi=!0,eu||(eu=!0,hh())}function An(e,t){if(!tu&&qi){tu=!0;do for(var l=!1,a=Li;a!==null;){if(e!==0){var n=a.pendingLanes;if(n===0)var i=0;else{var c=a.suspendedLanes,u=a.pingedLanes;i=(1<<31-ht(42|e)+1)-1,i&=n&~(c&~u),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(l=!0,nd(a,i))}else i=re,i=Zn(a,a===Te?i:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(i&3)===0||Qa(a,i)||(l=!0,nd(a,i));a=a.next}while(l);tu=!1}}function ph(){td()}function td(){qi=eu=!1;var e=0;Cl!==0&&Nh()&&(e=Cl);for(var t=mt(),l=null,a=Li;a!==null;){var n=a.next,i=ld(a,t);i===0?(a.next=null,l===null?Li=n:l.next=n,n===null&&(La=l)):(l=a,(e!==0||(i&3)!==0)&&(qi=!0)),a=n}Xe!==0&&Xe!==5||An(e),Cl!==0&&(Cl=0)}function ld(e,t){for(var l=e.suspendedLanes,a=e.pingedLanes,n=e.expirationTimes,i=e.pendingLanes&-62914561;0u)break;var k=f.transferSize,C=f.initiatorType;k&&dd(C)&&(f=f.responseEnd,c+=k*(f"u"?null:document;function Td(e,t,l){var a=qa;if(a&&typeof t=="string"&&t){var n=Nt(t);n='link[rel="'+e+'"][href="'+n+'"]',typeof l=="string"&&(n+='[crossorigin="'+l+'"]'),_d.has(n)||(_d.add(n),e={rel:e,crossOrigin:l,href:t},a.querySelector(n)===null&&(t=a.createElement("link"),et(t,"link",e),Je(t),a.head.appendChild(t)))}}function Dh(e){cl.D(e),Td("dns-prefetch",e,null)}function Rh(e,t){cl.C(e,t),Td("preconnect",e,t)}function Uh(e,t,l){cl.L(e,t,l);var a=qa;if(a&&e&&t){var n='link[rel="preload"][as="'+Nt(t)+'"]';t==="image"&&l&&l.imageSrcSet?(n+='[imagesrcset="'+Nt(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(n+='[imagesizes="'+Nt(l.imageSizes)+'"]')):n+='[href="'+Nt(e)+'"]';var i=n;switch(t){case"style":i=Ga(e);break;case"script":i=Ya(e)}Ot.has(i)||(e=w({rel:"preload",href:t==="image"&&l&&l.imageSrcSet?void 0:e,as:t},l),Ot.set(i,e),a.querySelector(n)!==null||t==="style"&&a.querySelector(Mn(i))||t==="script"&&a.querySelector(wn(i))||(t=a.createElement("link"),et(t,"link",e),Je(t),a.head.appendChild(t)))}}function Hh(e,t){cl.m(e,t);var l=qa;if(l&&e){var a=t&&typeof t.as=="string"?t.as:"script",n='link[rel="modulepreload"][as="'+Nt(a)+'"][href="'+Nt(e)+'"]',i=n;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=Ya(e)}if(!Ot.has(i)&&(e=w({rel:"modulepreload",href:e},t),Ot.set(i,e),l.querySelector(n)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(wn(i)))return}a=l.createElement("link"),et(a,"link",e),Je(a),l.head.appendChild(a)}}}function Bh(e,t,l){cl.S(e,t,l);var a=qa;if(a&&e){var n=ra(a).hoistableStyles,i=Ga(e);t=t||"default";var c=n.get(i);if(!c){var u={loading:0,preload:null};if(c=a.querySelector(Mn(i)))u.loading=5;else{e=w({rel:"stylesheet",href:e,"data-precedence":t},l),(l=Ot.get(i))&&yu(e,l);var f=c=a.createElement("link");Je(f),et(f,"link",e),f._p=new Promise(function(v,k){f.onload=v,f.onerror=k}),f.addEventListener("load",function(){u.loading|=1}),f.addEventListener("error",function(){u.loading|=2}),u.loading|=4,Qi(c,t,a)}c={type:"stylesheet",instance:c,count:1,state:u},n.set(i,c)}}}function Lh(e,t){cl.X(e,t);var l=qa;if(l&&e){var a=ra(l).hoistableScripts,n=Ya(e),i=a.get(n);i||(i=l.querySelector(wn(n)),i||(e=w({src:e,async:!0},t),(t=Ot.get(n))&&bu(e,t),i=l.createElement("script"),Je(i),et(i,"link",e),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},a.set(n,i))}}function qh(e,t){cl.M(e,t);var l=qa;if(l&&e){var a=ra(l).hoistableScripts,n=Ya(e),i=a.get(n);i||(i=l.querySelector(wn(n)),i||(e=w({src:e,async:!0,type:"module"},t),(t=Ot.get(n))&&bu(e,t),i=l.createElement("script"),Je(i),et(i,"link",e),l.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},a.set(n,i))}}function Nd(e,t,l,a){var n=(n=J.current)?Zi(n):null;if(!n)throw Error(o(446));switch(e){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(t=Ga(l.href),l=ra(n).hoistableStyles,a=l.get(t),a||(a={type:"style",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){e=Ga(l.href);var i=ra(n).hoistableStyles,c=i.get(e);if(c||(n=n.ownerDocument||n,c={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(e,c),(i=n.querySelector(Mn(e)))&&!i._p&&(c.instance=i,c.state.loading=5),Ot.has(e)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Ot.set(e,l),i||Gh(n,e,l,c.state))),t&&a===null)throw Error(o(528,""));return c}if(t&&a!==null)throw Error(o(529,""));return null;case"script":return t=l.async,l=l.src,typeof l=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ya(l),l=ra(n).hoistableScripts,a=l.get(t),a||(a={type:"script",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(o(444,e))}}function Ga(e){return'href="'+Nt(e)+'"'}function Mn(e){return'link[rel="stylesheet"]['+e+"]"}function kd(e){return w({},e,{"data-precedence":e.precedence,precedence:null})}function Gh(e,t,l,a){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?a.loading=1:(t=e.createElement("link"),a.preload=t,t.addEventListener("load",function(){return a.loading|=1}),t.addEventListener("error",function(){return a.loading|=2}),et(t,"link",l),Je(t),e.head.appendChild(t))}function Ya(e){return'[src="'+Nt(e)+'"]'}function wn(e){return"script[async]"+e}function Ad(e,t,l){if(t.count++,t.instance===null)switch(t.type){case"style":var a=e.querySelector('style[data-href~="'+Nt(l.href)+'"]');if(a)return t.instance=a,Je(a),a;var n=w({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return a=(e.ownerDocument||e).createElement("style"),Je(a),et(a,"style",n),Qi(a,l.precedence,e),t.instance=a;case"stylesheet":n=Ga(l.href);var i=e.querySelector(Mn(n));if(i)return t.state.loading|=4,t.instance=i,Je(i),i;a=kd(l),(n=Ot.get(n))&&yu(a,n),i=(e.ownerDocument||e).createElement("link"),Je(i);var c=i;return c._p=new Promise(function(u,f){c.onload=u,c.onerror=f}),et(i,"link",a),t.state.loading|=4,Qi(i,l.precedence,e),t.instance=i;case"script":return i=Ya(l.src),(n=e.querySelector(wn(i)))?(t.instance=n,Je(n),n):(a=l,(n=Ot.get(i))&&(a=w({},l),bu(a,n)),e=e.ownerDocument||e,n=e.createElement("script"),Je(n),et(n,"link",a),e.head.appendChild(n),t.instance=n);case"void":return null;default:throw Error(o(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(a=t.instance,t.state.loading|=4,Qi(a,l.precedence,e));return t.instance}function Qi(e,t,l){for(var a=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=a.length?a[a.length-1]:null,i=n,c=0;c title"):null)}function Yh(e,t,l){if(l===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return e=t.disabled,typeof t.precedence=="string"&&e==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Ed(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function Xh(e,t,l,a){if(l.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var n=Ga(a.href),i=t.querySelector(Mn(n));if(i){t=i._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Ki.bind(e),t.then(e,e)),l.state.loading|=4,l.instance=i,Je(i);return}i=t.ownerDocument||t,a=kd(a),(n=Ot.get(n))&&yu(a,n),i=i.createElement("link"),Je(i);var c=i;c._p=new Promise(function(u,f){c.onload=u,c.onerror=f}),et(i,"link",a),l.instance=i}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(l,t),(t=l.state.preload)&&(l.state.loading&3)===0&&(e.count++,l=Ki.bind(e),t.addEventListener("load",l),t.addEventListener("error",l))}}var vu=0;function Zh(e,t){return e.stylesheets&&e.count===0&&Wi(e,e.stylesheets),0vu?50:800)+t);return e.unsuspend=l,function(){e.unsuspend=null,clearTimeout(a),clearTimeout(n)}}:null}function Ki(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Wi(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Ji=null;function Wi(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Ji=new Map,t.forEach(Qh,e),Ji=null,Ki.call(e))}function Qh(e,t){if(!(t.state.loading&4)){var l=Ji.get(e);if(l)var a=l.get(null);else{l=new Map,Ji.set(e,l);for(var n=e.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(h){console.error(h)}}return r(),ju.exports=u0(),ju.exports}var o0=r0();const f0=um(o0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const dh=o=>o.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),om=(...o)=>o.filter((h,y,r)=>!!h&&h.trim()!==""&&r.indexOf(h)===y).join(" ").trim();/** + */const d0=r=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),rm=(...r)=>r.filter((h,y,o)=>!!h&&h.trim()!==""&&o.indexOf(h)===y).join(" ").trim();/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */var mh={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + */var m0={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const ph=fe.forwardRef(({color:o="currentColor",size:h=24,strokeWidth:y=2,absoluteStrokeWidth:r,className:S="",children:N,iconNode:_,...O},j)=>fe.createElement("svg",{ref:j,...mh,width:h,height:h,stroke:o,strokeWidth:r?Number(y)*24/Number(h):y,className:om("lucide",S),...O},[..._.map(([g,L])=>fe.createElement(g,L)),...Array.isArray(N)?N:[N]]));/** + */const p0=fe.forwardRef(({color:r="currentColor",size:h=24,strokeWidth:y=2,absoluteStrokeWidth:o,className:N="",children:_,iconNode:z,...O},A)=>fe.createElement("svg",{ref:A,...m0,width:h,height:h,stroke:r,strokeWidth:o?Number(y)*24/Number(h):y,className:rm("lucide",N),...O},[...z.map(([g,L])=>fe.createElement(g,L)),...Array.isArray(_)?_:[_]]));/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Oe=(o,h)=>{const y=fe.forwardRef(({className:r,...S},N)=>fe.createElement(ph,{ref:N,iconNode:h,className:om(`lucide-${dh(o)}`,r),...S}));return y.displayName=`${o}`,y};/** + */const Oe=(r,h)=>{const y=fe.forwardRef(({className:o,...N},_)=>fe.createElement(p0,{ref:_,iconNode:h,className:rm(`lucide-${d0(r)}`,o),...N}));return y.displayName=`${r}`,y};/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const hh=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],rm=Oe("ArrowLeft",hh);/** + */const h0=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],om=Oe("ArrowLeft",h0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const gh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],sc=Oe("ArrowRight",gh);/** + */const g0=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],sc=Oe("ArrowRight",g0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const yh=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Ou=Oe("BookOpen",yh);/** + */const y0=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Ou=Oe("BookOpen",y0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const bh=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Bu=Oe("Check",bh);/** + */const b0=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Bu=Oe("Check",b0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const vh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],xh=Oe("CircleCheck",vh);/** + */const v0=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],x0=Oe("CircleCheck",v0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Sh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]],zh=Oe("Clock",Sh);/** + */const S0=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]],z0=Oe("Clock",S0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const _h=[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]],Th=Oe("CodeXml",_h);/** + */const _0=[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]],T0=Oe("CodeXml",_0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Nh=[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]],fm=Oe("Code",Nh);/** + */const N0=[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]],fm=Oe("Code",N0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const kh=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Lu=Oe("Copy",kh);/** + */const k0=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Lu=Oe("Copy",k0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Ah=[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]],jh=Oe("Cpu",Ah);/** + */const A0=[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]],j0=Oe("Cpu",A0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Ch=[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]],dm=Oe("FileCode",Ch);/** + */const C0=[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]],dm=Oe("FileCode",C0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Eh=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Mh=Oe("FileText",Eh);/** + */const E0=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],M0=Oe("FileText",E0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const wh=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],Oh=Oe("Github",wh);/** + */const w0=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],O0=Oe("Github",w0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Dh=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Rh=Oe("Layers",Dh);/** + */const D0=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],R0=Oe("Layers",D0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Uh=[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]],Hh=Oe("Menu",Uh);/** + */const U0=[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]],H0=Oe("Menu",U0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Bh=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z",key:"1btarq"}]],Lh=Oe("Milestone",Bh);/** + */const B0=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z",key:"1btarq"}]],L0=Oe("Milestone",B0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const qh=[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]],mm=Oe("Play",qh);/** + */const q0=[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]],mm=Oe("Play",q0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Gh=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]],uc=Oe("Search",Gh);/** + */const G0=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]],uc=Oe("Search",G0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Yh=[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]],Xh=Oe("Sparkles",Yh);/** + */const Y0=[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]],X0=Oe("Sparkles",Y0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Zh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Qh=Oe("Target",Zh);/** + */const Z0=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Q0=Oe("Target",Z0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Vh=[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]],pm=Oe("Terminal",Vh);/** + */const V0=[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]],pm=Oe("Terminal",V0);/** * @license lucide-react v0.475.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Kh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],hm=Oe("X",Kh);function gm(o){var h,y,r="";if(typeof o=="string"||typeof o=="number")r+=o;else if(typeof o=="object")if(Array.isArray(o)){var S=o.length;for(h=0;h{const y=new Array(o.length+h.length);for(let r=0;r({classGroupId:o,validator:h}),ym=(o=new Map,h=null,y)=>({nextPart:o,validators:h,classGroupId:y}),ic="-",em=[],Fh="arbitrary..",Ih=o=>{const h=eg(o),{conflictingClassGroups:y,conflictingClassGroupModifiers:r}=o;return{getClassGroupId:_=>{if(_.startsWith("[")&&_.endsWith("]"))return Ph(_);const O=_.split(ic),j=O[0]===""&&O.length>1?1:0;return bm(O,j,h)},getConflictingClassGroupIds:(_,O)=>{if(O){const j=r[_],g=y[_];return j?g?Wh(g,j):j:g||em}return y[_]||em}}},bm=(o,h,y)=>{if(o.length-h===0)return y.classGroupId;const S=o[h],N=y.nextPart.get(S);if(N){const g=bm(o,h+1,N);if(g)return g}const _=y.validators;if(_===null)return;const O=h===0?o.join(ic):o.slice(h).join(ic),j=_.length;for(let g=0;go.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const h=o.slice(1,-1),y=h.indexOf(":"),r=h.slice(0,y);return r?Fh+r:void 0})(),eg=o=>{const{theme:h,classGroups:y}=o;return tg(y,h)},tg=(o,h)=>{const y=ym();for(const r in o){const S=o[r];qu(S,y,r,h)}return y},qu=(o,h,y,r)=>{const S=o.length;for(let N=0;N{if(typeof o=="string"){ag(o,h,y);return}if(typeof o=="function"){ng(o,h,y,r);return}ig(o,h,y,r)},ag=(o,h,y)=>{const r=o===""?h:vm(h,o);r.classGroupId=y},ng=(o,h,y,r)=>{if(cg(o)){qu(o(r),h,y,r);return}h.validators===null&&(h.validators=[]),h.validators.push($h(y,o))},ig=(o,h,y,r)=>{const S=Object.entries(o),N=S.length;for(let _=0;_{let y=o;const r=h.split(ic),S=r.length;for(let N=0;N"isThemeGetter"in o&&o.isThemeGetter===!0,sg=o=>{if(o<1)return{get:()=>{},set:()=>{}};let h=0,y=Object.create(null),r=Object.create(null);const S=(N,_)=>{y[N]=_,h++,h>o&&(h=0,r=y,y=Object.create(null))};return{get(N){let _=y[N];if(_!==void 0)return _;if((_=r[N])!==void 0)return S(N,_),_},set(N,_){N in y?y[N]=_:S(N,_)}}},Du="!",tm=":",ug=[],lm=(o,h,y,r,S)=>({modifiers:o,hasImportantModifier:h,baseClassName:y,maybePostfixModifierPosition:r,isExternal:S}),og=o=>{const{prefix:h,experimentalParseClassName:y}=o;let r=S=>{const N=[];let _=0,O=0,j=0,g;const L=S.length;for(let D=0;Dj?g-j:void 0;return lm(N,V,I,M)};if(h){const S=h+tm,N=r;r=_=>_.startsWith(S)?N(_.slice(S.length)):lm(ug,!1,_,void 0,!0)}if(y){const S=r;r=N=>y({className:N,parseClassName:S})}return r},rg=o=>{const h=new Map;return o.orderSensitiveModifiers.forEach((y,r)=>{h.set(y,1e6+r)}),y=>{const r=[];let S=[];for(let N=0;N0&&(S.sort(),r.push(...S),S=[]),r.push(_)):S.push(_)}return S.length>0&&(S.sort(),r.push(...S)),r}},fg=o=>({cache:sg(o.cacheSize),parseClassName:og(o),sortModifiers:rg(o),postfixLookupClassGroupIds:dg(o),...Ih(o)}),dg=o=>{const h=Object.create(null),y=o.postfixLookupClassGroups;if(y)for(let r=0;r{const{parseClassName:y,getClassGroupId:r,getConflictingClassGroupIds:S,sortModifiers:N,postfixLookupClassGroupIds:_}=h,O=[],j=o.trim().split(mg);let g="";for(let L=j.length-1;L>=0;L-=1){const w=j[L],{isExternal:I,modifiers:V,hasImportantModifier:M,baseClassName:D,maybePostfixModifierPosition:ie}=y(w);if(I){g=w+(g.length>0?" "+g:g);continue}let ye=!!ie,ce;if(ye){const P=D.substring(0,ie);ce=r(P);const B=ce&&_[ce]?r(D):void 0;B&&B!==ce&&(ce=B,ye=!1)}else ce=r(D);if(!ce){if(!ye){g=w+(g.length>0?" "+g:g);continue}if(ce=r(D),!ce){g=w+(g.length>0?" "+g:g);continue}ye=!1}const Ne=V.length===0?"":V.length===1?V[0]:N(V).join(":"),De=M?Ne+Du:Ne,Ye=De+ce;if(O.indexOf(Ye)>-1)continue;O.push(Ye);const Ee=S(ce,ye);for(let P=0;P0?" "+g:g)}return g},hg=(...o)=>{let h=0,y,r,S="";for(;h{if(typeof o=="string")return o;let h,y="";for(let r=0;r{let y,r,S,N;const _=j=>{const g=h.reduce((L,w)=>w(L),o());return y=fg(g),r=y.cache.get,S=y.cache.set,N=O,O(j)},O=j=>{const g=r(j);if(g)return g;const L=pg(j,y);return S(j,L),L};return N=_,(...j)=>N(hg(...j))},yg=[],Ze=o=>{const h=y=>y[o]||yg;return h.isThemeGetter=!0,h},Sm=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,zm=/^\((?:(\w[\w-]*):)?(.+)\)$/i,bg=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,vg=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,xg=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Sg=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,zg=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,_g=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ul=o=>bg.test(o),ne=o=>!!o&&!Number.isNaN(Number(o)),Gt=o=>!!o&&Number.isInteger(Number(o)),wu=o=>o.endsWith("%")&&ne(o.slice(0,-1)),sl=o=>vg.test(o),_m=()=>!0,Tg=o=>xg.test(o)&&!Sg.test(o),Gu=()=>!1,Ng=o=>zg.test(o),kg=o=>_g.test(o),Ag=o=>!q(o)&&!Y(o),jg=o=>o.startsWith("@container")&&(o[10]==="/"&&o[11]!==void 0||o[11]==="s"&&o[16]!==void 0&&o.startsWith("-size/",10)||o[11]==="n"&&o[18]!==void 0&&o.startsWith("-normal/",10)),Cg=o=>Hl(o,km,Gu),q=o=>Sm.test(o),la=o=>Hl(o,Am,Tg),am=o=>Hl(o,Hg,ne),Eg=o=>Hl(o,Cm,_m),Mg=o=>Hl(o,jm,Gu),nm=o=>Hl(o,Tm,Gu),wg=o=>Hl(o,Nm,kg),ac=o=>Hl(o,Em,Ng),Y=o=>zm.test(o),Ln=o=>na(o,Am),Og=o=>na(o,jm),im=o=>na(o,Tm),Dg=o=>na(o,km),Rg=o=>na(o,Nm),nc=o=>na(o,Em,!0),Ug=o=>na(o,Cm,!0),Hl=(o,h,y)=>{const r=Sm.exec(o);return r?r[1]?h(r[1]):y(r[2]):!1},na=(o,h,y=!1)=>{const r=zm.exec(o);return r?r[1]?h(r[1]):y:!1},Tm=o=>o==="position"||o==="percentage",Nm=o=>o==="image"||o==="url",km=o=>o==="length"||o==="size"||o==="bg-size",Am=o=>o==="length",Hg=o=>o==="number",jm=o=>o==="family-name",Cm=o=>o==="number"||o==="weight",Em=o=>o==="shadow",Bg=()=>{const o=Ze("color"),h=Ze("font"),y=Ze("text"),r=Ze("font-weight"),S=Ze("tracking"),N=Ze("leading"),_=Ze("breakpoint"),O=Ze("container"),j=Ze("spacing"),g=Ze("radius"),L=Ze("shadow"),w=Ze("inset-shadow"),I=Ze("text-shadow"),V=Ze("drop-shadow"),M=Ze("blur"),D=Ze("perspective"),ie=Ze("aspect"),ye=Ze("ease"),ce=Ze("animate"),Ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],De=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],Ye=()=>[...De(),Y,q],Ee=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],B=()=>[Y,q,j],W=()=>[Ul,"full","auto",...B()],ke=()=>[Gt,"none","subgrid",Y,q],Qe=()=>["auto",{span:["full",Gt,Y,q]},Gt,Y,q],Re=()=>[Gt,"auto",Y,q],ft=()=>["auto","min","max","fr",Y,q],dt=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],Ve=()=>["start","end","center","stretch","center-safe","end-safe"],T=()=>["auto",...B()],R=()=>[Ul,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...B()],$=()=>[Ul,"screen","full","dvw","lvw","svw","min","max","fit",...B()],pe=()=>[Ul,"screen","full","lh","dvh","lvh","svh","min","max","fit",...B()],U=()=>[o,Y,q],m=()=>[...De(),im,nm,{position:[Y,q]}],E=()=>["no-repeat",{repeat:["","x","y","space","round"]}],H=()=>["auto","cover","contain",Dg,Cg,{size:[Y,q]}],G=()=>[wu,Ln,la],Q=()=>["","none","full",g,Y,q],J=()=>["",ne,Ln,la],de=()=>["solid","dashed","dotted","double"],Ke=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>[ne,wu,im,nm],ol=()=>["","none",M,Y,q],Yt=()=>["none",ne,Y,q],rl=()=>["none",ne,Y,q],ia=()=>[ne,Y,q],_t=()=>[Ul,"full",...B()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[sl],breakpoint:[sl],color:[_m],container:[sl],"drop-shadow":[sl],ease:["in","out","in-out"],font:[Ag],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[sl],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[sl],shadow:[sl],spacing:["px",ne],text:[sl],"text-shadow":[sl],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ul,q,Y,ie]}],container:["container"],"container-type":[{"@container":["","normal","size",Y,q]}],"container-named":[jg],columns:[{columns:[ne,q,Y,O]}],"break-after":[{"break-after":Ne()}],"break-before":[{"break-before":Ne()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:Ye()}],overflow:[{overflow:Ee()}],"overflow-x":[{"overflow-x":Ee()}],"overflow-y":[{"overflow-y":Ee()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:W()}],"inset-x":[{"inset-x":W()}],"inset-y":[{"inset-y":W()}],start:[{"inset-s":W(),start:W()}],end:[{"inset-e":W(),end:W()}],"inset-bs":[{"inset-bs":W()}],"inset-be":[{"inset-be":W()}],top:[{top:W()}],right:[{right:W()}],bottom:[{bottom:W()}],left:[{left:W()}],visibility:["visible","invisible","collapse"],z:[{z:[Gt,"auto",Y,q]}],basis:[{basis:[Ul,"full","auto",O,...B()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,Ul,"auto","initial","none",q]}],grow:[{grow:["",ne,Y,q]}],shrink:[{shrink:["",ne,Y,q]}],order:[{order:[Gt,"first","last","none",Y,q]}],"grid-cols":[{"grid-cols":ke()}],"col-start-end":[{col:Qe()}],"col-start":[{"col-start":Re()}],"col-end":[{"col-end":Re()}],"grid-rows":[{"grid-rows":ke()}],"row-start-end":[{row:Qe()}],"row-start":[{"row-start":Re()}],"row-end":[{"row-end":Re()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ft()}],"auto-rows":[{"auto-rows":ft()}],gap:[{gap:B()}],"gap-x":[{"gap-x":B()}],"gap-y":[{"gap-y":B()}],"justify-content":[{justify:[...dt(),"normal"]}],"justify-items":[{"justify-items":[...Ve(),"normal"]}],"justify-self":[{"justify-self":["auto",...Ve()]}],"align-content":[{content:["normal",...dt()]}],"align-items":[{items:[...Ve(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...Ve(),{baseline:["","last"]}]}],"place-content":[{"place-content":dt()}],"place-items":[{"place-items":[...Ve(),"baseline"]}],"place-self":[{"place-self":["auto",...Ve()]}],p:[{p:B()}],px:[{px:B()}],py:[{py:B()}],ps:[{ps:B()}],pe:[{pe:B()}],pbs:[{pbs:B()}],pbe:[{pbe:B()}],pt:[{pt:B()}],pr:[{pr:B()}],pb:[{pb:B()}],pl:[{pl:B()}],m:[{m:T()}],mx:[{mx:T()}],my:[{my:T()}],ms:[{ms:T()}],me:[{me:T()}],mbs:[{mbs:T()}],mbe:[{mbe:T()}],mt:[{mt:T()}],mr:[{mr:T()}],mb:[{mb:T()}],ml:[{ml:T()}],"space-x":[{"space-x":B()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":B()}],"space-y-reverse":["space-y-reverse"],size:[{size:R()}],"inline-size":[{inline:["auto",...$()]}],"min-inline-size":[{"min-inline":["auto",...$()]}],"max-inline-size":[{"max-inline":["none",...$()]}],"block-size":[{block:["auto",...pe()]}],"min-block-size":[{"min-block":["auto",...pe()]}],"max-block-size":[{"max-block":["none",...pe()]}],w:[{w:[O,"screen",...R()]}],"min-w":[{"min-w":[O,"screen","none",...R()]}],"max-w":[{"max-w":[O,"screen","none","prose",{screen:[_]},...R()]}],h:[{h:["screen","lh",...R()]}],"min-h":[{"min-h":["screen","lh","none",...R()]}],"max-h":[{"max-h":["screen","lh",...R()]}],"font-size":[{text:["base",y,Ln,la]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,Ug,Eg]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",wu,q]}],"font-family":[{font:[Og,Mg,h]}],"font-features":[{"font-features":[q]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[S,Y,q]}],"line-clamp":[{"line-clamp":[ne,"none",Y,am]}],leading:[{leading:[N,...B()]}],"list-image":[{"list-image":["none",Y,q]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Y,q]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:U()}],"text-color":[{text:U()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...de(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",Y,la]}],"text-decoration-color":[{decoration:U()}],"underline-offset":[{"underline-offset":[ne,"auto",Y,q]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:B()}],"tab-size":[{tab:[Gt,Y,q]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y,q]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Y,q]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:m()}],"bg-repeat":[{bg:E()}],"bg-size":[{bg:H()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Gt,Y,q],radial:["",Y,q],conic:[Gt,Y,q]},Rg,wg]}],"bg-color":[{bg:U()}],"gradient-from-pos":[{from:G()}],"gradient-via-pos":[{via:G()}],"gradient-to-pos":[{to:G()}],"gradient-from":[{from:U()}],"gradient-via":[{via:U()}],"gradient-to":[{to:U()}],rounded:[{rounded:Q()}],"rounded-s":[{"rounded-s":Q()}],"rounded-e":[{"rounded-e":Q()}],"rounded-t":[{"rounded-t":Q()}],"rounded-r":[{"rounded-r":Q()}],"rounded-b":[{"rounded-b":Q()}],"rounded-l":[{"rounded-l":Q()}],"rounded-ss":[{"rounded-ss":Q()}],"rounded-se":[{"rounded-se":Q()}],"rounded-ee":[{"rounded-ee":Q()}],"rounded-es":[{"rounded-es":Q()}],"rounded-tl":[{"rounded-tl":Q()}],"rounded-tr":[{"rounded-tr":Q()}],"rounded-br":[{"rounded-br":Q()}],"rounded-bl":[{"rounded-bl":Q()}],"border-w":[{border:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-bs":[{"border-bs":J()}],"border-w-be":[{"border-be":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...de(),"hidden","none"]}],"divide-style":[{divide:[...de(),"hidden","none"]}],"border-color":[{border:U()}],"border-color-x":[{"border-x":U()}],"border-color-y":[{"border-y":U()}],"border-color-s":[{"border-s":U()}],"border-color-e":[{"border-e":U()}],"border-color-bs":[{"border-bs":U()}],"border-color-be":[{"border-be":U()}],"border-color-t":[{"border-t":U()}],"border-color-r":[{"border-r":U()}],"border-color-b":[{"border-b":U()}],"border-color-l":[{"border-l":U()}],"divide-color":[{divide:U()}],"outline-style":[{outline:[...de(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,Y,q]}],"outline-w":[{outline:["",ne,Ln,la]}],"outline-color":[{outline:U()}],shadow:[{shadow:["","none",L,nc,ac]}],"shadow-color":[{shadow:U()}],"inset-shadow":[{"inset-shadow":["none",w,nc,ac]}],"inset-shadow-color":[{"inset-shadow":U()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:U()}],"ring-offset-w":[{"ring-offset":[ne,la]}],"ring-offset-color":[{"ring-offset":U()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":U()}],"text-shadow":[{"text-shadow":["none",I,nc,ac]}],"text-shadow-color":[{"text-shadow":U()}],opacity:[{opacity:[ne,Y,q]}],"mix-blend":[{"mix-blend":[...Ke(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ke()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":ae()}],"mask-image-linear-to-pos":[{"mask-linear-to":ae()}],"mask-image-linear-from-color":[{"mask-linear-from":U()}],"mask-image-linear-to-color":[{"mask-linear-to":U()}],"mask-image-t-from-pos":[{"mask-t-from":ae()}],"mask-image-t-to-pos":[{"mask-t-to":ae()}],"mask-image-t-from-color":[{"mask-t-from":U()}],"mask-image-t-to-color":[{"mask-t-to":U()}],"mask-image-r-from-pos":[{"mask-r-from":ae()}],"mask-image-r-to-pos":[{"mask-r-to":ae()}],"mask-image-r-from-color":[{"mask-r-from":U()}],"mask-image-r-to-color":[{"mask-r-to":U()}],"mask-image-b-from-pos":[{"mask-b-from":ae()}],"mask-image-b-to-pos":[{"mask-b-to":ae()}],"mask-image-b-from-color":[{"mask-b-from":U()}],"mask-image-b-to-color":[{"mask-b-to":U()}],"mask-image-l-from-pos":[{"mask-l-from":ae()}],"mask-image-l-to-pos":[{"mask-l-to":ae()}],"mask-image-l-from-color":[{"mask-l-from":U()}],"mask-image-l-to-color":[{"mask-l-to":U()}],"mask-image-x-from-pos":[{"mask-x-from":ae()}],"mask-image-x-to-pos":[{"mask-x-to":ae()}],"mask-image-x-from-color":[{"mask-x-from":U()}],"mask-image-x-to-color":[{"mask-x-to":U()}],"mask-image-y-from-pos":[{"mask-y-from":ae()}],"mask-image-y-to-pos":[{"mask-y-to":ae()}],"mask-image-y-from-color":[{"mask-y-from":U()}],"mask-image-y-to-color":[{"mask-y-to":U()}],"mask-image-radial":[{"mask-radial":[Y,q]}],"mask-image-radial-from-pos":[{"mask-radial-from":ae()}],"mask-image-radial-to-pos":[{"mask-radial-to":ae()}],"mask-image-radial-from-color":[{"mask-radial-from":U()}],"mask-image-radial-to-color":[{"mask-radial-to":U()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":De()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":ae()}],"mask-image-conic-to-pos":[{"mask-conic-to":ae()}],"mask-image-conic-from-color":[{"mask-conic-from":U()}],"mask-image-conic-to-color":[{"mask-conic-to":U()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:m()}],"mask-repeat":[{mask:E()}],"mask-size":[{mask:H()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Y,q]}],filter:[{filter:["","none",Y,q]}],blur:[{blur:ol()}],brightness:[{brightness:[ne,Y,q]}],contrast:[{contrast:[ne,Y,q]}],"drop-shadow":[{"drop-shadow":["","none",V,nc,ac]}],"drop-shadow-color":[{"drop-shadow":U()}],grayscale:[{grayscale:["",ne,Y,q]}],"hue-rotate":[{"hue-rotate":[ne,Y,q]}],invert:[{invert:["",ne,Y,q]}],saturate:[{saturate:[ne,Y,q]}],sepia:[{sepia:["",ne,Y,q]}],"backdrop-filter":[{"backdrop-filter":["","none",Y,q]}],"backdrop-blur":[{"backdrop-blur":ol()}],"backdrop-brightness":[{"backdrop-brightness":[ne,Y,q]}],"backdrop-contrast":[{"backdrop-contrast":[ne,Y,q]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,Y,q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,Y,q]}],"backdrop-invert":[{"backdrop-invert":["",ne,Y,q]}],"backdrop-opacity":[{"backdrop-opacity":[ne,Y,q]}],"backdrop-saturate":[{"backdrop-saturate":[ne,Y,q]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,Y,q]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":B()}],"border-spacing-x":[{"border-spacing-x":B()}],"border-spacing-y":[{"border-spacing-y":B()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Y,q]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",Y,q]}],ease:[{ease:["linear","initial",ye,Y,q]}],delay:[{delay:[ne,Y,q]}],animate:[{animate:["none",ce,Y,q]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[D,Y,q]}],"perspective-origin":[{"perspective-origin":Ye()}],rotate:[{rotate:Yt()}],"rotate-x":[{"rotate-x":Yt()}],"rotate-y":[{"rotate-y":Yt()}],"rotate-z":[{"rotate-z":Yt()}],scale:[{scale:rl()}],"scale-x":[{"scale-x":rl()}],"scale-y":[{"scale-y":rl()}],"scale-z":[{"scale-z":rl()}],"scale-3d":["scale-3d"],skew:[{skew:ia()}],"skew-x":[{"skew-x":ia()}],"skew-y":[{"skew-y":ia()}],transform:[{transform:[Y,q,"","none","gpu","cpu"]}],"transform-origin":[{origin:Ye()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:_t()}],"translate-x":[{"translate-x":_t()}],"translate-y":[{"translate-y":_t()}],"translate-z":[{"translate-z":_t()}],"translate-none":["translate-none"],zoom:[{zoom:[Gt,Y,q]}],accent:[{accent:U()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:U()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Y,q]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":U()}],"scrollbar-track-color":[{"scrollbar-track":U()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":B()}],"scroll-mx":[{"scroll-mx":B()}],"scroll-my":[{"scroll-my":B()}],"scroll-ms":[{"scroll-ms":B()}],"scroll-me":[{"scroll-me":B()}],"scroll-mbs":[{"scroll-mbs":B()}],"scroll-mbe":[{"scroll-mbe":B()}],"scroll-mt":[{"scroll-mt":B()}],"scroll-mr":[{"scroll-mr":B()}],"scroll-mb":[{"scroll-mb":B()}],"scroll-ml":[{"scroll-ml":B()}],"scroll-p":[{"scroll-p":B()}],"scroll-px":[{"scroll-px":B()}],"scroll-py":[{"scroll-py":B()}],"scroll-ps":[{"scroll-ps":B()}],"scroll-pe":[{"scroll-pe":B()}],"scroll-pbs":[{"scroll-pbs":B()}],"scroll-pbe":[{"scroll-pbe":B()}],"scroll-pt":[{"scroll-pt":B()}],"scroll-pr":[{"scroll-pr":B()}],"scroll-pb":[{"scroll-pb":B()}],"scroll-pl":[{"scroll-pl":B()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Y,q]}],fill:[{fill:["none",...U()]}],"stroke-w":[{stroke:[ne,Ln,la,am]}],stroke:[{stroke:["none",...U()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Lg=gg(Bg);function tt(...o){return Lg(Jh(o))}const qg=({activeTab:o,onSelectTab:h,onOpenSearch:y})=>{const[r,S]=fe.useState(!1),N=[{id:"docs",label:"Docs"},{id:"stdlib",label:"Standard Library"},{id:"playground",label:"Playground"},{id:"blog",label:"Blog"},{id:"roadmap",label:"Roadmap"}];return s.jsxs("header",{className:"sticky top-0 z-40 w-full border-b border-zinc-800 bg-[#090a0d]/95 backdrop-blur",children:[s.jsxs("div",{className:"mx-auto flex max-w-6xl items-center justify-between px-4 sm:px-6 h-14",children:[s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("button",{onClick:()=>h("home"),className:"flex items-center gap-2.5 text-left focus:outline-none",children:[s.jsx("span",{className:"font-mono text-sm font-bold tracking-tight text-zinc-100 hover:text-amber-400 transition-colors",children:"TRACK"}),s.jsx("span",{className:"rounded border border-zinc-800 bg-zinc-900 px-1.5 py-0.5 font-mono text-[10px] text-zinc-400",children:"v0.7.0"})]}),s.jsx("nav",{className:"hidden md:flex items-center gap-1",children:N.map(_=>{const O=o===_.id;return s.jsx("button",{onClick:()=>h(_.id),className:tt("px-3 py-1 text-xs font-mono transition-colors rounded",O?"text-amber-400 bg-zinc-900 font-semibold":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:_.label},_.id)})})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("button",{onClick:y,className:"flex items-center gap-2 rounded border border-zinc-800 bg-zinc-900/60 px-2.5 py-1 text-xs font-mono text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 transition-colors",children:[s.jsx(uc,{className:"h-3 w-3"}),s.jsx("span",{className:"hidden sm:inline",children:"Search"}),s.jsx("kbd",{className:"text-[10px] text-zinc-500 font-mono",children:"⌘K"})]}),s.jsx("a",{href:"https://github.com/dev-dami/track",target:"_blank",rel:"noreferrer",className:"text-zinc-400 hover:text-zinc-200 transition-colors p-1",title:"GitHub Repository",children:s.jsx(Oh,{className:"h-4 w-4"})}),s.jsx("button",{onClick:()=>S(!r),className:"md:hidden text-zinc-400 hover:text-zinc-200 p-1",children:r?s.jsx(hm,{className:"h-4 w-4"}):s.jsx(Hh,{className:"h-4 w-4"})})]})]}),r&&s.jsx("div",{className:"md:hidden border-t border-zinc-800 bg-[#090a0d] px-4 py-3 space-y-1",children:N.map(_=>s.jsx("button",{onClick:()=>{h(_.id),S(!1)},className:tt("block w-full text-left px-2 py-1.5 text-xs font-mono rounded",o===_.id?"text-amber-400 bg-zinc-900 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:_.label},_.id))})]})},Gg=({onSelectTab:o})=>s.jsx("footer",{className:"border-t border-zinc-800/80 bg-[#090a0d] text-zinc-400 font-mono text-xs mt-16",children:s.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-8 sm:px-6 flex flex-col sm:flex-row items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("button",{onClick:()=>o("docs"),className:"hover:text-zinc-200 transition-colors",children:"Docs"}),s.jsx("span",{children:"•"}),s.jsx("button",{onClick:()=>o("stdlib"),className:"hover:text-zinc-200 transition-colors",children:"Stdlib"}),s.jsx("span",{children:"•"}),s.jsx("button",{onClick:()=>o("blog"),className:"hover:text-zinc-200 transition-colors",children:"Blog"}),s.jsx("span",{children:"•"}),s.jsx("button",{onClick:()=>o("roadmap"),className:"hover:text-zinc-200 transition-colors",children:"Roadmap"}),s.jsx("span",{children:"•"}),s.jsx("a",{href:"https://github.com/dev-dami/track",target:"_blank",rel:"noreferrer",className:"hover:text-zinc-200 transition-colors",children:"GitHub"})]}),s.jsx("div",{className:"text-zinc-500 text-[11px]",children:"Track Programming Language © 2026. MIT Licensed."})]})}),Yg=({isOpen:o,onClose:h,onSelect:y,searchItems:r})=>{const[S,N]=fe.useState(""),[_,O]=fe.useState(0),[j,g]=fe.useState("all"),L=fe.useRef(null);fe.useEffect(()=>{o&&(setTimeout(()=>L.current?.focus(),50),N(""),O(0))},[o]),fe.useEffect(()=>{const M=D=>{(D.metaKey||D.ctrlKey)&&D.key==="k"&&(D.preventDefault(),o&&h()),D.key==="Escape"&&o&&h()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[o,h]);const w=r.filter(M=>{const D=j==="all"||M.category===j,ie=M.title.toLowerCase().includes(S.toLowerCase())||M.snippet.toLowerCase().includes(S.toLowerCase())||M.section&&M.section.toLowerCase().includes(S.toLowerCase());return D&&ie}),I=M=>{M.key==="ArrowDown"?(M.preventDefault(),O(D=>DD>0?D-1:D)):M.key==="Enter"&&w[_]&&(M.preventDefault(),y(w[_]),h())};if(!o)return null;const V={docs:Ou,stdlib:fm,blog:Mh,example:Rh,spec:Xh};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center p-4 pt-16 md:pt-24 bg-black/70 backdrop-blur-md animate-in fade-in duration-150",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-xl border border-zinc-700/80 bg-zinc-950 shadow-2xl ring-1 ring-white/10",onClick:M=>M.stopPropagation(),children:[s.jsxs("div",{className:"relative flex items-center border-b border-zinc-800/80 px-4 py-3 bg-zinc-900/60",children:[s.jsx(uc,{className:"h-4 w-4 text-zinc-400 shrink-0 mr-3"}),s.jsx("input",{ref:L,type:"text",value:S,onChange:M=>{N(M.target.value),O(0)},onKeyDown:I,placeholder:"Search Track docs, stdlib, specs, memory model...",className:"w-full bg-transparent font-sans text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none"}),S&&s.jsx("button",{onClick:()=>N(""),className:"text-zinc-500 hover:text-zinc-300 p-1 mr-2",children:s.jsx(hm,{className:"h-4 w-4"})}),s.jsx("kbd",{className:"hidden sm:inline-block rounded border border-zinc-700 bg-zinc-800/80 px-1.5 py-0.5 text-[10px] font-mono text-zinc-400",children:"ESC"})]}),s.jsx("div",{className:"flex items-center gap-1.5 border-b border-zinc-800/60 bg-zinc-900/40 px-4 py-2 text-xs font-mono",children:["all","docs","stdlib","blog","example","spec"].map(M=>s.jsx("button",{onClick:()=>{g(M),O(0)},className:tt("rounded px-2 py-0.5 capitalize transition-colors",j===M?"bg-amber-500/20 text-amber-300 font-semibold":"text-zinc-400 hover:bg-zinc-800/60 hover:text-zinc-200"),children:M},M))}),s.jsx("div",{className:"max-h-96 overflow-y-auto p-2 divide-y divide-zinc-900/60",children:w.length===0?s.jsxs("div",{className:"py-12 text-center text-xs text-zinc-500 font-mono",children:['No results found for "',S,'". Try searching for ',s.jsx("span",{className:"text-amber-400",children:'"lens"'}),", ",s.jsx("span",{className:"text-cyan-400",children:'"yard"'}),", or ",s.jsx("span",{className:"text-emerald-400",children:'"net_socket"'}),"."]}):w.map((M,D)=>{const ie=V[M.category]||Ou,ye=D===_;return s.jsxs("div",{onClick:()=>{y(M),h()},onMouseEnter:()=>O(D),className:tt("group flex items-start gap-3 rounded-lg p-3 cursor-pointer transition-all",ye?"bg-zinc-800/90 text-zinc-100 ring-1 ring-inset ring-amber-500/30":"text-zinc-300 hover:bg-zinc-900/80"),children:[s.jsx("div",{className:tt("rounded-md p-2 mt-0.5 shrink-0 border border-zinc-800",ye?"bg-amber-500/20 text-amber-300":"bg-zinc-900 text-zinc-400"),children:s.jsx(ie,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-semibold text-sm text-zinc-100 font-sans",children:M.title}),M.section&&s.jsxs("span",{className:"text-[11px] font-mono text-zinc-500",children:["/ ",M.section]}),s.jsx("span",{className:"ml-auto text-[10px] font-mono uppercase tracking-wider rounded border border-zinc-800 px-1.5 py-0.5 text-zinc-400",children:M.category})]}),s.jsx("p",{className:"text-xs text-zinc-400 line-clamp-2 mt-1 font-sans",children:M.snippet})]}),s.jsx(sc,{className:tt("h-4 w-4 shrink-0 self-center text-zinc-500 transition-transform",ye&&"translate-x-0.5 text-amber-400")})]},M.id)})}),s.jsxs("div",{className:"flex items-center justify-between border-t border-zinc-800/80 bg-zinc-900/60 px-4 py-2 text-[11px] font-mono text-zinc-500",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"rounded bg-zinc-800 px-1 py-0.5 text-zinc-400 mr-1",children:"↑↓"}),"Navigate"]}),s.jsxs("span",{children:[s.jsx("kbd",{className:"rounded bg-zinc-800 px-1 py-0.5 text-zinc-400 mr-1",children:"↵"}),"Select"]})]}),s.jsx("span",{children:"Track v0.7.0 Documentation Index"})]})]})})};function cm(o){let h=o.replace(/&/g,"&").replace(//g,">");const y=/(".*?"|".*?")/g,r=/\b(0x[0-9a-fA-F]+|0b[01]+|\d+)\b/g,S=/\b(let|mut|fn|struct|enum|union|match|if|else|while|return|with|type|const|import|abort|as|macro|use)\b/g,N=/\b(i8|i16|i32|i64|u8|u16|u32|u64|bool|void|ptr|Str|Vec|Option|Result|Token|Expr|Stmt)\b/g,_=/(->|=>)/g;return h.split(` -`).map(O=>{if(O.trim().startsWith("//"))return`${O}`;const j=[];let g=O.replace(y,L=>{const w=`__STR_${j.length}__`;return j.push(`${L}`),w});return g=g.replace(S,'$1'),g=g.replace(N,'$1'),g=g.replace(r,'$1'),g=g.replace(_,'$1'),g=g.replace(/\bfn\s+([a-zA-Z0-9_]+)/g,'fn $1'),g=g.replace(/([A-Z][a-zA-Z0-9_]*)::([A-Za-z0-9_]+)/g,'$1::$2'),j.forEach((L,w)=>{g=g.replace(`__STR_${w}__`,L)}),g}).join(` -`)}function sm(o){return o.replace(/&/g,"&").replace(//g,">").split(` -`).map(r=>{if(r.trim().startsWith("#"))return`${r}`;let S=r;return S=S.replace(/\b(curl|yard|track|cargo|bash|git|cd|mkdir|cp|echo)\b/g,'$1'),S=S.replace(/(--[a-zA-Z0-9_-]+|-[a-zA-Z0-9]+)/g,'$1'),S=S.replace(/(".*?"|".*?")/g,'$1'),S}).join(` -`)}const cc=({code:o,language:h="track",filename:y,showLineNumbers:r=!0,highlightLines:S=[],onRun:N,className:_})=>{const[O,j]=fe.useState(!1),g=()=>{navigator.clipboard.writeText(o),j(!0),setTimeout(()=>j(!1),2e3)},L=()=>h==="bash"?sm(o):cm(o),w=o.trimEnd().split(` -`);return s.jsxs("div",{className:tt("group relative my-4 overflow-hidden rounded-lg border border-zinc-800/80 bg-zinc-950/90 shadow-xl backdrop-blur-md transition-all hover:border-zinc-700/80",_),children:[(y||h)&&s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800/80 bg-zinc-900/60 px-4 py-2 text-xs font-mono text-zinc-400",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[h==="bash"?s.jsx(pm,{className:"h-3.5 w-3.5 text-amber-400"}):s.jsx(dm,{className:"h-3.5 w-3.5 text-cyan-400"}),s.jsx("span",{className:"font-semibold text-zinc-200",children:y||h})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N&&s.jsxs("button",{onClick:N,className:"flex items-center gap-1 rounded bg-amber-500/20 px-2 py-0.5 text-xs text-amber-300 transition-colors hover:bg-amber-500/30 font-mono",title:"Run in Playground",children:[s.jsx(mm,{className:"h-3 w-3 fill-current"}),s.jsx("span",{children:"Run"})]}),s.jsx("button",{onClick:g,className:"flex items-center gap-1 rounded px-2 py-0.5 text-xs text-zinc-400 transition-colors hover:bg-zinc-800 hover:text-zinc-200",title:"Copy code",children:O?s.jsxs(s.Fragment,{children:[s.jsx(Bu,{className:"h-3.5 w-3.5 text-emerald-400"}),s.jsx("span",{className:"text-emerald-400",children:"Copied!"})]}):s.jsxs(s.Fragment,{children:[s.jsx(Lu,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Copy"})]})})]})]}),s.jsx("div",{className:"overflow-x-auto p-4 text-xs font-mono leading-relaxed",children:r?s.jsx("div",{className:"table w-full border-collapse",children:w.map((I,V)=>{const M=V+1,D=S.includes(M),ie=h==="bash"?sm(I):cm(I);return s.jsxs("div",{className:tt("table-row transition-colors",D?"bg-amber-500/10 -mx-4 px-4 block rounded":""),children:[s.jsx("span",{className:"table-cell select-none pr-4 text-right text-zinc-600 w-8",children:M}),s.jsx("span",{className:"table-cell whitespace-pre text-zinc-200 font-mono",dangerouslySetInnerHTML:{__html:ie||" "}})]},V)})}):s.jsx("pre",{className:"text-zinc-200 font-mono whitespace-pre",dangerouslySetInnerHTML:{__html:L()}})})]})},Xg=({command:o,prefix:h="$",className:y})=>{const[r,S]=fe.useState(!1),N=()=>{navigator.clipboard.writeText(o),S(!0),setTimeout(()=>S(!1),2e3)};return s.jsxs("div",{className:tt("group flex items-center justify-between gap-3 rounded-lg border border-zinc-800/90 bg-zinc-950/80 px-3.5 py-2.5 font-mono text-xs shadow-inner backdrop-blur transition-all hover:border-zinc-700/80",y),children:[s.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto select-all",children:[s.jsx("span",{className:"select-none text-amber-500/80 font-bold",children:h}),s.jsx("span",{className:"text-zinc-200 whitespace-nowrap",children:o})]}),s.jsx("button",{onClick:N,className:"flex items-center gap-1 shrink-0 rounded border border-zinc-800 bg-zinc-900/80 px-2 py-1 text-xs text-zinc-400 transition-colors hover:border-zinc-700 hover:text-zinc-100",title:"Copy command",children:r?s.jsxs(s.Fragment,{children:[s.jsx(Bu,{className:"h-3.5 w-3.5 text-emerald-400"}),s.jsx("span",{className:"text-emerald-400 text-[11px]",children:"Copied"})]}):s.jsxs(s.Fragment,{children:[s.jsx(Lu,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"text-[11px]",children:"Copy"})]})})]})},Zg=[{feature:"Memory Safety Model",track:"Linear Ownership + Lexical Lenses (Compile-time verified)",rust:"Borrow Checker with Lifetime Parameters",zig:"Manual Allocators (Runtime safety checks)",c:"Manual (Unchecked, undefined behavior)",go:"Tracing Garbage Collector (Stop-the-world)",advantage:"track"},{feature:"Lifetime Annotations",track:"None (Zero lifetime syntax or annotations)",rust:"Infectious syntax ('a, 'b: 'a, elision rules)",zig:"N/A (No lifetime analysis)",c:"N/A",go:"N/A",advantage:"track"},{feature:"Runtime / GC Overhead",track:"Zero Runtime, Zero GC, Deterministic latency",rust:"Zero Runtime, Zero GC",zig:"Zero Runtime, Zero GC",c:"Zero Runtime, Zero GC",go:"Heavy runtime (~2-10ms GC pauses)",advantage:"neutral"},{feature:"Error Handling Model",track:"Explicit Stack Tuples (T, i32) & Predicates",rust:"Monadic Result & ? Operator",zig:"Error Sets & try operator",c:"Status codes / global errno",go:"(value, error) multi-return",advantage:"track"},{feature:"Compiler Backend",track:"Cranelift Standalone (Sub-ms native compilation)",rust:"LLVM (Large memory & build overhead)",zig:"LLVM / C Emitter / Self-hosted x86",c:"GCC / Clang (LLVM)",go:"Custom Go Plan9 backend",advantage:"track"},{feature:"Package Manager",track:"Yard (Built-in test orchestrator & builder)",rust:"Cargo",zig:"Zig Build system",c:"CMake / Make / Meson (Fragmented)",go:"Go Modules",advantage:"neutral"},{feature:"Pattern Matching & Guards",track:"Full Nested Pattern Matching + Arm Guards",rust:"Full Pattern Matching + Guards",zig:"Basic switch expressions",c:"Integer switch statements only",go:"Type switches only",advantage:"track"},{feature:"Self-Hosting Status",track:"v0.7.0 Native Lexer -> v0.9.0 3-Stage Byte Verify",rust:"Self-hosted via LLVM",zig:"Self-hosted",c:"Self-hosted (GCC/Clang)",go:"Self-hosted",advantage:"neutral"}],aa=[{id:"hello",title:"Hello World",category:"Toolchain",description:"Minimal entrypoint with std/io and void main function.",filename:"examples/hello.trk",code:`import "std/io"; + */const K0=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],hm=Oe("X",K0);function gm(r){var h,y,o="";if(typeof r=="string"||typeof r=="number")o+=r;else if(typeof r=="object")if(Array.isArray(r)){var N=r.length;for(h=0;h{const y=new Array(r.length+h.length);for(let o=0;o({classGroupId:r,validator:h}),ym=(r=new Map,h=null,y)=>({nextPart:r,validators:h,classGroupId:y}),ic="-",em=[],F0="arbitrary..",I0=r=>{const h=eg(r),{conflictingClassGroups:y,conflictingClassGroupModifiers:o}=r;return{getClassGroupId:z=>{if(z.startsWith("[")&&z.endsWith("]"))return P0(z);const O=z.split(ic),A=O[0]===""&&O.length>1?1:0;return bm(O,A,h)},getConflictingClassGroupIds:(z,O)=>{if(O){const A=o[z],g=y[z];return A?g?W0(g,A):A:g||em}return y[z]||em}}},bm=(r,h,y)=>{if(r.length-h===0)return y.classGroupId;const N=r[h],_=y.nextPart.get(N);if(_){const g=bm(r,h+1,_);if(g)return g}const z=y.validators;if(z===null)return;const O=h===0?r.join(ic):r.slice(h).join(ic),A=z.length;for(let g=0;gr.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const h=r.slice(1,-1),y=h.indexOf(":"),o=h.slice(0,y);return o?F0+o:void 0})(),eg=r=>{const{theme:h,classGroups:y}=r;return tg(y,h)},tg=(r,h)=>{const y=ym();for(const o in r){const N=r[o];qu(N,y,o,h)}return y},qu=(r,h,y,o)=>{const N=r.length;for(let _=0;_{if(typeof r=="string"){ag(r,h,y);return}if(typeof r=="function"){ng(r,h,y,o);return}ig(r,h,y,o)},ag=(r,h,y)=>{const o=r===""?h:vm(h,r);o.classGroupId=y},ng=(r,h,y,o)=>{if(cg(r)){qu(r(o),h,y,o);return}h.validators===null&&(h.validators=[]),h.validators.push($0(y,r))},ig=(r,h,y,o)=>{const N=Object.entries(r),_=N.length;for(let z=0;z<_;z++){const[O,A]=N[z];qu(A,vm(h,O),y,o)}},vm=(r,h)=>{let y=r;const o=h.split(ic),N=o.length;for(let _=0;_"isThemeGetter"in r&&r.isThemeGetter===!0,sg=r=>{if(r<1)return{get:()=>{},set:()=>{}};let h=0,y=Object.create(null),o=Object.create(null);const N=(_,z)=>{y[_]=z,h++,h>r&&(h=0,o=y,y=Object.create(null))};return{get(_){let z=y[_];if(z!==void 0)return z;if((z=o[_])!==void 0)return N(_,z),z},set(_,z){_ in y?y[_]=z:N(_,z)}}},Du="!",tm=":",ug=[],lm=(r,h,y,o,N)=>({modifiers:r,hasImportantModifier:h,baseClassName:y,maybePostfixModifierPosition:o,isExternal:N}),rg=r=>{const{prefix:h,experimentalParseClassName:y}=r;let o=N=>{const _=[];let z=0,O=0,A=0,g;const L=N.length;for(let D=0;DA?g-A:void 0;return lm(_,V,I,M)};if(h){const N=h+tm,_=o;o=z=>z.startsWith(N)?_(z.slice(N.length)):lm(ug,!1,z,void 0,!0)}if(y){const N=o;o=_=>y({className:_,parseClassName:N})}return o},og=r=>{const h=new Map;return r.orderSensitiveModifiers.forEach((y,o)=>{h.set(y,1e6+o)}),y=>{const o=[];let N=[];for(let _=0;_0&&(N.sort(),o.push(...N),N=[]),o.push(z)):N.push(z)}return N.length>0&&(N.sort(),o.push(...N)),o}},fg=r=>({cache:sg(r.cacheSize),parseClassName:rg(r),sortModifiers:og(r),postfixLookupClassGroupIds:dg(r),...I0(r)}),dg=r=>{const h=Object.create(null),y=r.postfixLookupClassGroups;if(y)for(let o=0;o{const{parseClassName:y,getClassGroupId:o,getConflictingClassGroupIds:N,sortModifiers:_,postfixLookupClassGroupIds:z}=h,O=[],A=r.trim().split(mg);let g="";for(let L=A.length-1;L>=0;L-=1){const w=A[L],{isExternal:I,modifiers:V,hasImportantModifier:M,baseClassName:D,maybePostfixModifierPosition:ie}=y(w);if(I){g=w+(g.length>0?" "+g:g);continue}let ye=!!ie,ce;if(ye){const P=D.substring(0,ie);ce=o(P);const B=ce&&z[ce]?o(D):void 0;B&&B!==ce&&(ce=B,ye=!1)}else ce=o(D);if(!ce){if(!ye){g=w+(g.length>0?" "+g:g);continue}if(ce=o(D),!ce){g=w+(g.length>0?" "+g:g);continue}ye=!1}const Ne=V.length===0?"":V.length===1?V[0]:_(V).join(":"),De=M?Ne+Du:Ne,Ye=De+ce;if(O.indexOf(Ye)>-1)continue;O.push(Ye);const Ee=N(ce,ye);for(let P=0;P0?" "+g:g)}return g},hg=(...r)=>{let h=0,y,o,N="";for(;h{if(typeof r=="string")return r;let h,y="";for(let o=0;o{let y,o,N,_;const z=A=>{const g=h.reduce((L,w)=>w(L),r());return y=fg(g),o=y.cache.get,N=y.cache.set,_=O,O(A)},O=A=>{const g=o(A);if(g)return g;const L=pg(A,y);return N(A,L),L};return _=z,(...A)=>_(hg(...A))},yg=[],Ze=r=>{const h=y=>y[r]||yg;return h.isThemeGetter=!0,h},Sm=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,zm=/^\((?:(\w[\w-]*):)?(.+)\)$/i,bg=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,vg=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,xg=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Sg=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,zg=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,_g=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ul=r=>bg.test(r),ne=r=>!!r&&!Number.isNaN(Number(r)),Gt=r=>!!r&&Number.isInteger(Number(r)),wu=r=>r.endsWith("%")&&ne(r.slice(0,-1)),sl=r=>vg.test(r),_m=()=>!0,Tg=r=>xg.test(r)&&!Sg.test(r),Gu=()=>!1,Ng=r=>zg.test(r),kg=r=>_g.test(r),Ag=r=>!q(r)&&!Y(r),jg=r=>r.startsWith("@container")&&(r[10]==="/"&&r[11]!==void 0||r[11]==="s"&&r[16]!==void 0&&r.startsWith("-size/",10)||r[11]==="n"&&r[18]!==void 0&&r.startsWith("-normal/",10)),Cg=r=>Hl(r,km,Gu),q=r=>Sm.test(r),la=r=>Hl(r,Am,Tg),am=r=>Hl(r,Hg,ne),Eg=r=>Hl(r,Cm,_m),Mg=r=>Hl(r,jm,Gu),nm=r=>Hl(r,Tm,Gu),wg=r=>Hl(r,Nm,kg),ac=r=>Hl(r,Em,Ng),Y=r=>zm.test(r),Ln=r=>na(r,Am),Og=r=>na(r,jm),im=r=>na(r,Tm),Dg=r=>na(r,km),Rg=r=>na(r,Nm),nc=r=>na(r,Em,!0),Ug=r=>na(r,Cm,!0),Hl=(r,h,y)=>{const o=Sm.exec(r);return o?o[1]?h(o[1]):y(o[2]):!1},na=(r,h,y=!1)=>{const o=zm.exec(r);return o?o[1]?h(o[1]):y:!1},Tm=r=>r==="position"||r==="percentage",Nm=r=>r==="image"||r==="url",km=r=>r==="length"||r==="size"||r==="bg-size",Am=r=>r==="length",Hg=r=>r==="number",jm=r=>r==="family-name",Cm=r=>r==="number"||r==="weight",Em=r=>r==="shadow",Bg=()=>{const r=Ze("color"),h=Ze("font"),y=Ze("text"),o=Ze("font-weight"),N=Ze("tracking"),_=Ze("leading"),z=Ze("breakpoint"),O=Ze("container"),A=Ze("spacing"),g=Ze("radius"),L=Ze("shadow"),w=Ze("inset-shadow"),I=Ze("text-shadow"),V=Ze("drop-shadow"),M=Ze("blur"),D=Ze("perspective"),ie=Ze("aspect"),ye=Ze("ease"),ce=Ze("animate"),Ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],De=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],Ye=()=>[...De(),Y,q],Ee=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],B=()=>[Y,q,A],W=()=>[Ul,"full","auto",...B()],ke=()=>[Gt,"none","subgrid",Y,q],Qe=()=>["auto",{span:["full",Gt,Y,q]},Gt,Y,q],Re=()=>[Gt,"auto",Y,q],ft=()=>["auto","min","max","fr",Y,q],dt=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],Ve=()=>["start","end","center","stretch","center-safe","end-safe"],T=()=>["auto",...B()],R=()=>[Ul,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...B()],$=()=>[Ul,"screen","full","dvw","lvw","svw","min","max","fit",...B()],pe=()=>[Ul,"screen","full","lh","dvh","lvh","svh","min","max","fit",...B()],U=()=>[r,Y,q],m=()=>[...De(),im,nm,{position:[Y,q]}],E=()=>["no-repeat",{repeat:["","x","y","space","round"]}],H=()=>["auto","cover","contain",Dg,Cg,{size:[Y,q]}],G=()=>[wu,Ln,la],Q=()=>["","none","full",g,Y,q],J=()=>["",ne,Ln,la],de=()=>["solid","dashed","dotted","double"],Ke=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>[ne,wu,im,nm],rl=()=>["","none",M,Y,q],Yt=()=>["none",ne,Y,q],ol=()=>["none",ne,Y,q],ia=()=>[ne,Y,q],_t=()=>[Ul,"full",...B()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[sl],breakpoint:[sl],color:[_m],container:[sl],"drop-shadow":[sl],ease:["in","out","in-out"],font:[Ag],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[sl],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[sl],shadow:[sl],spacing:["px",ne],text:[sl],"text-shadow":[sl],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ul,q,Y,ie]}],container:["container"],"container-type":[{"@container":["","normal","size",Y,q]}],"container-named":[jg],columns:[{columns:[ne,q,Y,O]}],"break-after":[{"break-after":Ne()}],"break-before":[{"break-before":Ne()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:Ye()}],overflow:[{overflow:Ee()}],"overflow-x":[{"overflow-x":Ee()}],"overflow-y":[{"overflow-y":Ee()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:W()}],"inset-x":[{"inset-x":W()}],"inset-y":[{"inset-y":W()}],start:[{"inset-s":W(),start:W()}],end:[{"inset-e":W(),end:W()}],"inset-bs":[{"inset-bs":W()}],"inset-be":[{"inset-be":W()}],top:[{top:W()}],right:[{right:W()}],bottom:[{bottom:W()}],left:[{left:W()}],visibility:["visible","invisible","collapse"],z:[{z:[Gt,"auto",Y,q]}],basis:[{basis:[Ul,"full","auto",O,...B()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,Ul,"auto","initial","none",q]}],grow:[{grow:["",ne,Y,q]}],shrink:[{shrink:["",ne,Y,q]}],order:[{order:[Gt,"first","last","none",Y,q]}],"grid-cols":[{"grid-cols":ke()}],"col-start-end":[{col:Qe()}],"col-start":[{"col-start":Re()}],"col-end":[{"col-end":Re()}],"grid-rows":[{"grid-rows":ke()}],"row-start-end":[{row:Qe()}],"row-start":[{"row-start":Re()}],"row-end":[{"row-end":Re()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ft()}],"auto-rows":[{"auto-rows":ft()}],gap:[{gap:B()}],"gap-x":[{"gap-x":B()}],"gap-y":[{"gap-y":B()}],"justify-content":[{justify:[...dt(),"normal"]}],"justify-items":[{"justify-items":[...Ve(),"normal"]}],"justify-self":[{"justify-self":["auto",...Ve()]}],"align-content":[{content:["normal",...dt()]}],"align-items":[{items:[...Ve(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...Ve(),{baseline:["","last"]}]}],"place-content":[{"place-content":dt()}],"place-items":[{"place-items":[...Ve(),"baseline"]}],"place-self":[{"place-self":["auto",...Ve()]}],p:[{p:B()}],px:[{px:B()}],py:[{py:B()}],ps:[{ps:B()}],pe:[{pe:B()}],pbs:[{pbs:B()}],pbe:[{pbe:B()}],pt:[{pt:B()}],pr:[{pr:B()}],pb:[{pb:B()}],pl:[{pl:B()}],m:[{m:T()}],mx:[{mx:T()}],my:[{my:T()}],ms:[{ms:T()}],me:[{me:T()}],mbs:[{mbs:T()}],mbe:[{mbe:T()}],mt:[{mt:T()}],mr:[{mr:T()}],mb:[{mb:T()}],ml:[{ml:T()}],"space-x":[{"space-x":B()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":B()}],"space-y-reverse":["space-y-reverse"],size:[{size:R()}],"inline-size":[{inline:["auto",...$()]}],"min-inline-size":[{"min-inline":["auto",...$()]}],"max-inline-size":[{"max-inline":["none",...$()]}],"block-size":[{block:["auto",...pe()]}],"min-block-size":[{"min-block":["auto",...pe()]}],"max-block-size":[{"max-block":["none",...pe()]}],w:[{w:[O,"screen",...R()]}],"min-w":[{"min-w":[O,"screen","none",...R()]}],"max-w":[{"max-w":[O,"screen","none","prose",{screen:[z]},...R()]}],h:[{h:["screen","lh",...R()]}],"min-h":[{"min-h":["screen","lh","none",...R()]}],"max-h":[{"max-h":["screen","lh",...R()]}],"font-size":[{text:["base",y,Ln,la]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,Ug,Eg]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",wu,q]}],"font-family":[{font:[Og,Mg,h]}],"font-features":[{"font-features":[q]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[N,Y,q]}],"line-clamp":[{"line-clamp":[ne,"none",Y,am]}],leading:[{leading:[_,...B()]}],"list-image":[{"list-image":["none",Y,q]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Y,q]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:U()}],"text-color":[{text:U()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...de(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",Y,la]}],"text-decoration-color":[{decoration:U()}],"underline-offset":[{"underline-offset":[ne,"auto",Y,q]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:B()}],"tab-size":[{tab:[Gt,Y,q]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y,q]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Y,q]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:m()}],"bg-repeat":[{bg:E()}],"bg-size":[{bg:H()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Gt,Y,q],radial:["",Y,q],conic:[Gt,Y,q]},Rg,wg]}],"bg-color":[{bg:U()}],"gradient-from-pos":[{from:G()}],"gradient-via-pos":[{via:G()}],"gradient-to-pos":[{to:G()}],"gradient-from":[{from:U()}],"gradient-via":[{via:U()}],"gradient-to":[{to:U()}],rounded:[{rounded:Q()}],"rounded-s":[{"rounded-s":Q()}],"rounded-e":[{"rounded-e":Q()}],"rounded-t":[{"rounded-t":Q()}],"rounded-r":[{"rounded-r":Q()}],"rounded-b":[{"rounded-b":Q()}],"rounded-l":[{"rounded-l":Q()}],"rounded-ss":[{"rounded-ss":Q()}],"rounded-se":[{"rounded-se":Q()}],"rounded-ee":[{"rounded-ee":Q()}],"rounded-es":[{"rounded-es":Q()}],"rounded-tl":[{"rounded-tl":Q()}],"rounded-tr":[{"rounded-tr":Q()}],"rounded-br":[{"rounded-br":Q()}],"rounded-bl":[{"rounded-bl":Q()}],"border-w":[{border:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-bs":[{"border-bs":J()}],"border-w-be":[{"border-be":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...de(),"hidden","none"]}],"divide-style":[{divide:[...de(),"hidden","none"]}],"border-color":[{border:U()}],"border-color-x":[{"border-x":U()}],"border-color-y":[{"border-y":U()}],"border-color-s":[{"border-s":U()}],"border-color-e":[{"border-e":U()}],"border-color-bs":[{"border-bs":U()}],"border-color-be":[{"border-be":U()}],"border-color-t":[{"border-t":U()}],"border-color-r":[{"border-r":U()}],"border-color-b":[{"border-b":U()}],"border-color-l":[{"border-l":U()}],"divide-color":[{divide:U()}],"outline-style":[{outline:[...de(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,Y,q]}],"outline-w":[{outline:["",ne,Ln,la]}],"outline-color":[{outline:U()}],shadow:[{shadow:["","none",L,nc,ac]}],"shadow-color":[{shadow:U()}],"inset-shadow":[{"inset-shadow":["none",w,nc,ac]}],"inset-shadow-color":[{"inset-shadow":U()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:U()}],"ring-offset-w":[{"ring-offset":[ne,la]}],"ring-offset-color":[{"ring-offset":U()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":U()}],"text-shadow":[{"text-shadow":["none",I,nc,ac]}],"text-shadow-color":[{"text-shadow":U()}],opacity:[{opacity:[ne,Y,q]}],"mix-blend":[{"mix-blend":[...Ke(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ke()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":ae()}],"mask-image-linear-to-pos":[{"mask-linear-to":ae()}],"mask-image-linear-from-color":[{"mask-linear-from":U()}],"mask-image-linear-to-color":[{"mask-linear-to":U()}],"mask-image-t-from-pos":[{"mask-t-from":ae()}],"mask-image-t-to-pos":[{"mask-t-to":ae()}],"mask-image-t-from-color":[{"mask-t-from":U()}],"mask-image-t-to-color":[{"mask-t-to":U()}],"mask-image-r-from-pos":[{"mask-r-from":ae()}],"mask-image-r-to-pos":[{"mask-r-to":ae()}],"mask-image-r-from-color":[{"mask-r-from":U()}],"mask-image-r-to-color":[{"mask-r-to":U()}],"mask-image-b-from-pos":[{"mask-b-from":ae()}],"mask-image-b-to-pos":[{"mask-b-to":ae()}],"mask-image-b-from-color":[{"mask-b-from":U()}],"mask-image-b-to-color":[{"mask-b-to":U()}],"mask-image-l-from-pos":[{"mask-l-from":ae()}],"mask-image-l-to-pos":[{"mask-l-to":ae()}],"mask-image-l-from-color":[{"mask-l-from":U()}],"mask-image-l-to-color":[{"mask-l-to":U()}],"mask-image-x-from-pos":[{"mask-x-from":ae()}],"mask-image-x-to-pos":[{"mask-x-to":ae()}],"mask-image-x-from-color":[{"mask-x-from":U()}],"mask-image-x-to-color":[{"mask-x-to":U()}],"mask-image-y-from-pos":[{"mask-y-from":ae()}],"mask-image-y-to-pos":[{"mask-y-to":ae()}],"mask-image-y-from-color":[{"mask-y-from":U()}],"mask-image-y-to-color":[{"mask-y-to":U()}],"mask-image-radial":[{"mask-radial":[Y,q]}],"mask-image-radial-from-pos":[{"mask-radial-from":ae()}],"mask-image-radial-to-pos":[{"mask-radial-to":ae()}],"mask-image-radial-from-color":[{"mask-radial-from":U()}],"mask-image-radial-to-color":[{"mask-radial-to":U()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":De()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":ae()}],"mask-image-conic-to-pos":[{"mask-conic-to":ae()}],"mask-image-conic-from-color":[{"mask-conic-from":U()}],"mask-image-conic-to-color":[{"mask-conic-to":U()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:m()}],"mask-repeat":[{mask:E()}],"mask-size":[{mask:H()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Y,q]}],filter:[{filter:["","none",Y,q]}],blur:[{blur:rl()}],brightness:[{brightness:[ne,Y,q]}],contrast:[{contrast:[ne,Y,q]}],"drop-shadow":[{"drop-shadow":["","none",V,nc,ac]}],"drop-shadow-color":[{"drop-shadow":U()}],grayscale:[{grayscale:["",ne,Y,q]}],"hue-rotate":[{"hue-rotate":[ne,Y,q]}],invert:[{invert:["",ne,Y,q]}],saturate:[{saturate:[ne,Y,q]}],sepia:[{sepia:["",ne,Y,q]}],"backdrop-filter":[{"backdrop-filter":["","none",Y,q]}],"backdrop-blur":[{"backdrop-blur":rl()}],"backdrop-brightness":[{"backdrop-brightness":[ne,Y,q]}],"backdrop-contrast":[{"backdrop-contrast":[ne,Y,q]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,Y,q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,Y,q]}],"backdrop-invert":[{"backdrop-invert":["",ne,Y,q]}],"backdrop-opacity":[{"backdrop-opacity":[ne,Y,q]}],"backdrop-saturate":[{"backdrop-saturate":[ne,Y,q]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,Y,q]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":B()}],"border-spacing-x":[{"border-spacing-x":B()}],"border-spacing-y":[{"border-spacing-y":B()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Y,q]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",Y,q]}],ease:[{ease:["linear","initial",ye,Y,q]}],delay:[{delay:[ne,Y,q]}],animate:[{animate:["none",ce,Y,q]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[D,Y,q]}],"perspective-origin":[{"perspective-origin":Ye()}],rotate:[{rotate:Yt()}],"rotate-x":[{"rotate-x":Yt()}],"rotate-y":[{"rotate-y":Yt()}],"rotate-z":[{"rotate-z":Yt()}],scale:[{scale:ol()}],"scale-x":[{"scale-x":ol()}],"scale-y":[{"scale-y":ol()}],"scale-z":[{"scale-z":ol()}],"scale-3d":["scale-3d"],skew:[{skew:ia()}],"skew-x":[{"skew-x":ia()}],"skew-y":[{"skew-y":ia()}],transform:[{transform:[Y,q,"","none","gpu","cpu"]}],"transform-origin":[{origin:Ye()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:_t()}],"translate-x":[{"translate-x":_t()}],"translate-y":[{"translate-y":_t()}],"translate-z":[{"translate-z":_t()}],"translate-none":["translate-none"],zoom:[{zoom:[Gt,Y,q]}],accent:[{accent:U()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:U()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Y,q]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":U()}],"scrollbar-track-color":[{"scrollbar-track":U()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":B()}],"scroll-mx":[{"scroll-mx":B()}],"scroll-my":[{"scroll-my":B()}],"scroll-ms":[{"scroll-ms":B()}],"scroll-me":[{"scroll-me":B()}],"scroll-mbs":[{"scroll-mbs":B()}],"scroll-mbe":[{"scroll-mbe":B()}],"scroll-mt":[{"scroll-mt":B()}],"scroll-mr":[{"scroll-mr":B()}],"scroll-mb":[{"scroll-mb":B()}],"scroll-ml":[{"scroll-ml":B()}],"scroll-p":[{"scroll-p":B()}],"scroll-px":[{"scroll-px":B()}],"scroll-py":[{"scroll-py":B()}],"scroll-ps":[{"scroll-ps":B()}],"scroll-pe":[{"scroll-pe":B()}],"scroll-pbs":[{"scroll-pbs":B()}],"scroll-pbe":[{"scroll-pbe":B()}],"scroll-pt":[{"scroll-pt":B()}],"scroll-pr":[{"scroll-pr":B()}],"scroll-pb":[{"scroll-pb":B()}],"scroll-pl":[{"scroll-pl":B()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Y,q]}],fill:[{fill:["none",...U()]}],"stroke-w":[{stroke:[ne,Ln,la,am]}],stroke:[{stroke:["none",...U()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Lg=gg(Bg);function tt(...r){return Lg(J0(r))}const qg=({activeTab:r,onSelectTab:h,onOpenSearch:y})=>{const[o,N]=fe.useState(!1),_=[{id:"docs",label:"Docs"},{id:"stdlib",label:"Standard Library"},{id:"playground",label:"Playground"},{id:"blog",label:"Blog"},{id:"roadmap",label:"Roadmap"}];return s.jsxs("header",{className:"sticky top-0 z-40 w-full border-b border-zinc-800 bg-[#090a0d]/95 backdrop-blur",children:[s.jsxs("div",{className:"mx-auto flex max-w-6xl items-center justify-between px-4 sm:px-6 h-14",children:[s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("button",{onClick:()=>h("home"),className:"flex items-center gap-2.5 text-left focus:outline-none",children:[s.jsx("span",{className:"font-mono text-sm font-bold tracking-tight text-zinc-100 hover:text-amber-400 transition-colors",children:"TRACK"}),s.jsx("span",{className:"rounded border border-zinc-800 bg-zinc-900 px-1.5 py-0.5 font-mono text-[10px] text-zinc-400",children:"v1.0.0"})]}),s.jsx("nav",{className:"hidden md:flex items-center gap-1",children:_.map(z=>{const O=r===z.id;return s.jsx("button",{onClick:()=>h(z.id),className:tt("px-3 py-1 text-xs font-mono transition-colors rounded",O?"text-amber-400 bg-zinc-900 font-semibold":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:z.label},z.id)})})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("button",{onClick:y,className:"flex items-center gap-2 rounded border border-zinc-800 bg-zinc-900/60 px-2.5 py-1 text-xs font-mono text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 transition-colors",children:[s.jsx(uc,{className:"h-3 w-3"}),s.jsx("span",{className:"hidden sm:inline",children:"Search"}),s.jsx("kbd",{className:"text-[10px] text-zinc-500 font-mono",children:"⌘K"})]}),s.jsx("a",{href:"https://github.com/dev-dami/track",target:"_blank",rel:"noreferrer",className:"text-zinc-400 hover:text-zinc-200 transition-colors p-1",title:"GitHub Repository",children:s.jsx(O0,{className:"h-4 w-4"})}),s.jsx("button",{onClick:()=>N(!o),className:"md:hidden text-zinc-400 hover:text-zinc-200 p-1",children:o?s.jsx(hm,{className:"h-4 w-4"}):s.jsx(H0,{className:"h-4 w-4"})})]})]}),o&&s.jsx("div",{className:"md:hidden border-t border-zinc-800 bg-[#090a0d] px-4 py-3 space-y-1",children:_.map(z=>s.jsx("button",{onClick:()=>{h(z.id),N(!1)},className:tt("block w-full text-left px-2 py-1.5 text-xs font-mono rounded",r===z.id?"text-amber-400 bg-zinc-900 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:z.label},z.id))})]})},Gg=({onSelectTab:r})=>s.jsx("footer",{className:"border-t border-zinc-800/80 bg-[#090a0d] text-zinc-400 font-mono text-xs mt-16",children:s.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-8 sm:px-6 flex flex-col sm:flex-row items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("button",{onClick:()=>r("docs"),className:"hover:text-zinc-200 transition-colors",children:"Docs"}),s.jsx("span",{children:"•"}),s.jsx("button",{onClick:()=>r("stdlib"),className:"hover:text-zinc-200 transition-colors",children:"Stdlib"}),s.jsx("span",{children:"•"}),s.jsx("button",{onClick:()=>r("blog"),className:"hover:text-zinc-200 transition-colors",children:"Blog"}),s.jsx("span",{children:"•"}),s.jsx("button",{onClick:()=>r("roadmap"),className:"hover:text-zinc-200 transition-colors",children:"Roadmap"}),s.jsx("span",{children:"•"}),s.jsx("a",{href:"https://github.com/dev-dami/track",target:"_blank",rel:"noreferrer",className:"hover:text-zinc-200 transition-colors",children:"GitHub"})]}),s.jsx("div",{className:"text-zinc-500 text-[11px]",children:"Track Programming Language © 2026. MIT Licensed."})]})}),Yg=({isOpen:r,onClose:h,onSelect:y,searchItems:o})=>{const[N,_]=fe.useState(""),[z,O]=fe.useState(0),[A,g]=fe.useState("all"),L=fe.useRef(null);fe.useEffect(()=>{r&&(setTimeout(()=>L.current?.focus(),50),_(""),O(0))},[r]),fe.useEffect(()=>{const M=D=>{(D.metaKey||D.ctrlKey)&&D.key==="k"&&(D.preventDefault(),r&&h()),D.key==="Escape"&&r&&h()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,h]);const w=o.filter(M=>{const D=A==="all"||M.category===A,ie=M.title.toLowerCase().includes(N.toLowerCase())||M.snippet.toLowerCase().includes(N.toLowerCase())||M.section&&M.section.toLowerCase().includes(N.toLowerCase());return D&&ie}),I=M=>{M.key==="ArrowDown"?(M.preventDefault(),O(D=>DD>0?D-1:D)):M.key==="Enter"&&w[z]&&(M.preventDefault(),y(w[z]),h())};if(!r)return null;const V={docs:Ou,stdlib:fm,blog:M0,example:R0,spec:X0};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center p-4 pt-16 md:pt-24 bg-black/70 backdrop-blur-md animate-in fade-in duration-150",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-xl border border-zinc-700/80 bg-zinc-950 shadow-2xl ring-1 ring-white/10",onClick:M=>M.stopPropagation(),children:[s.jsxs("div",{className:"relative flex items-center border-b border-zinc-800/80 px-4 py-3 bg-zinc-900/60",children:[s.jsx(uc,{className:"h-4 w-4 text-zinc-400 shrink-0 mr-3"}),s.jsx("input",{ref:L,type:"text",value:N,onChange:M=>{_(M.target.value),O(0)},onKeyDown:I,placeholder:"Search Track docs, stdlib, specs, memory model...",className:"w-full bg-transparent font-sans text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none"}),N&&s.jsx("button",{onClick:()=>_(""),className:"text-zinc-500 hover:text-zinc-300 p-1 mr-2",children:s.jsx(hm,{className:"h-4 w-4"})}),s.jsx("kbd",{className:"hidden sm:inline-block rounded border border-zinc-700 bg-zinc-800/80 px-1.5 py-0.5 text-[10px] font-mono text-zinc-400",children:"ESC"})]}),s.jsx("div",{className:"flex items-center gap-1.5 border-b border-zinc-800/60 bg-zinc-900/40 px-4 py-2 text-xs font-mono",children:["all","docs","stdlib","blog","example","spec"].map(M=>s.jsx("button",{onClick:()=>{g(M),O(0)},className:tt("rounded px-2 py-0.5 capitalize transition-colors",A===M?"bg-amber-500/20 text-amber-300 font-semibold":"text-zinc-400 hover:bg-zinc-800/60 hover:text-zinc-200"),children:M},M))}),s.jsx("div",{className:"max-h-96 overflow-y-auto p-2 divide-y divide-zinc-900/60",children:w.length===0?s.jsxs("div",{className:"py-12 text-center text-xs text-zinc-500 font-mono",children:['No results found for "',N,'". Try searching for ',s.jsx("span",{className:"text-amber-400",children:'"lens"'}),", ",s.jsx("span",{className:"text-cyan-400",children:'"yard"'}),", or ",s.jsx("span",{className:"text-emerald-400",children:'"net_socket"'}),"."]}):w.map((M,D)=>{const ie=V[M.category]||Ou,ye=D===z;return s.jsxs("div",{onClick:()=>{y(M),h()},onMouseEnter:()=>O(D),className:tt("group flex items-start gap-3 rounded-lg p-3 cursor-pointer transition-all",ye?"bg-zinc-800/90 text-zinc-100 ring-1 ring-inset ring-amber-500/30":"text-zinc-300 hover:bg-zinc-900/80"),children:[s.jsx("div",{className:tt("rounded-md p-2 mt-0.5 shrink-0 border border-zinc-800",ye?"bg-amber-500/20 text-amber-300":"bg-zinc-900 text-zinc-400"),children:s.jsx(ie,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-semibold text-sm text-zinc-100 font-sans",children:M.title}),M.section&&s.jsxs("span",{className:"text-[11px] font-mono text-zinc-500",children:["/ ",M.section]}),s.jsx("span",{className:"ml-auto text-[10px] font-mono uppercase tracking-wider rounded border border-zinc-800 px-1.5 py-0.5 text-zinc-400",children:M.category})]}),s.jsx("p",{className:"text-xs text-zinc-400 line-clamp-2 mt-1 font-sans",children:M.snippet})]}),s.jsx(sc,{className:tt("h-4 w-4 shrink-0 self-center text-zinc-500 transition-transform",ye&&"translate-x-0.5 text-amber-400")})]},M.id)})}),s.jsxs("div",{className:"flex items-center justify-between border-t border-zinc-800/80 bg-zinc-900/60 px-4 py-2 text-[11px] font-mono text-zinc-500",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"rounded bg-zinc-800 px-1 py-0.5 text-zinc-400 mr-1",children:"↑↓"}),"Navigate"]}),s.jsxs("span",{children:[s.jsx("kbd",{className:"rounded bg-zinc-800 px-1 py-0.5 text-zinc-400 mr-1",children:"↵"}),"Select"]})]}),s.jsx("span",{children:"Track v1.0.0 Documentation Index"})]})]})})};function cm(r){let h=r.replace(/&/g,"&").replace(//g,">");const y=/(".*?"|".*?")/g,o=/\b(0x[0-9a-fA-F]+|0b[01]+|\d+)\b/g,N=/\b(let|mut|fn|struct|enum|union|match|if|else|while|return|with|type|const|import|abort|as|macro|use)\b/g,_=/\b(i8|i16|i32|i64|u8|u16|u32|u64|bool|void|ptr|Str|Vec|Option|Result|Token|Expr|Stmt)\b/g,z=/(->|=>)/g;return h.split(` +`).map(O=>{if(O.trim().startsWith("//"))return`${O}`;const A=[];let g=O.replace(y,L=>{const w=`__STR_${A.length}__`;return A.push(`${L}`),w});return g=g.replace(N,'$1'),g=g.replace(_,'$1'),g=g.replace(o,'$1'),g=g.replace(z,'$1'),g=g.replace(/\bfn\s+([a-zA-Z0-9_]+)/g,'fn $1'),g=g.replace(/([A-Z][a-zA-Z0-9_]*)::([A-Za-z0-9_]+)/g,'$1::$2'),A.forEach((L,w)=>{g=g.replace(`__STR_${w}__`,L)}),g}).join(` +`)}function sm(r){return r.replace(/&/g,"&").replace(//g,">").split(` +`).map(o=>o.trim().startsWith("#")?`${o}`:o.replace(/(".*?"|".*?")|\b(curl|yard|track|trackc|cargo|bash|git|cd|mkdir|cp|echo)\b|(\s)(--[a-zA-Z0-9_-]+|-[a-zA-Z0-9]+)/g,(N,_,z,O,A)=>_?`${_}`:z?`${z}`:`${O}${A}`)).join(` +`)}const cc=({code:r,language:h="track",filename:y,showLineNumbers:o=!0,highlightLines:N=[],onRun:_,className:z})=>{const[O,A]=fe.useState(!1),g=()=>{navigator.clipboard.writeText(r),A(!0),setTimeout(()=>A(!1),2e3)},L=()=>h==="bash"?sm(r):cm(r),w=r.trimEnd().split(` +`);return s.jsxs("div",{className:tt("group relative my-4 overflow-hidden rounded-lg border border-zinc-800/80 bg-zinc-950/90 shadow-xl backdrop-blur-md transition-all hover:border-zinc-700/80",z),children:[(y||h)&&s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800/80 bg-zinc-900/60 px-4 py-2 text-xs font-mono text-zinc-400",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[h==="bash"?s.jsx(pm,{className:"h-3.5 w-3.5 text-amber-400"}):s.jsx(dm,{className:"h-3.5 w-3.5 text-cyan-400"}),s.jsx("span",{className:"font-semibold text-zinc-200",children:y||h})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[_&&s.jsxs("button",{onClick:_,className:"flex items-center gap-1 rounded bg-amber-500/20 px-2 py-0.5 text-xs text-amber-300 transition-colors hover:bg-amber-500/30 font-mono",title:"Run in Playground",children:[s.jsx(mm,{className:"h-3 w-3 fill-current"}),s.jsx("span",{children:"Run"})]}),s.jsx("button",{onClick:g,className:"flex items-center gap-1 rounded px-2 py-0.5 text-xs text-zinc-400 transition-colors hover:bg-zinc-800 hover:text-zinc-200",title:"Copy code",children:O?s.jsxs(s.Fragment,{children:[s.jsx(Bu,{className:"h-3.5 w-3.5 text-emerald-400"}),s.jsx("span",{className:"text-emerald-400",children:"Copied!"})]}):s.jsxs(s.Fragment,{children:[s.jsx(Lu,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Copy"})]})})]})]}),s.jsx("div",{className:"overflow-x-auto p-4 text-xs font-mono leading-relaxed",children:o?s.jsx("div",{className:"table w-full border-collapse",children:w.map((I,V)=>{const M=V+1,D=N.includes(M),ie=h==="bash"?sm(I):cm(I);return s.jsxs("div",{className:tt("table-row transition-colors",D?"bg-amber-500/10 -mx-4 px-4 block rounded":""),children:[s.jsx("span",{className:"table-cell select-none pr-4 text-right text-zinc-600 w-8",children:M}),s.jsx("span",{className:"table-cell whitespace-pre text-zinc-200 font-mono",dangerouslySetInnerHTML:{__html:ie||" "}})]},V)})}):s.jsx("pre",{className:"text-zinc-200 font-mono whitespace-pre",dangerouslySetInnerHTML:{__html:L()}})})]})},Xg=({command:r,prefix:h="$",className:y})=>{const[o,N]=fe.useState(!1),_=()=>{navigator.clipboard.writeText(r),N(!0),setTimeout(()=>N(!1),2e3)};return s.jsxs("div",{className:tt("group flex items-center justify-between gap-3 rounded-lg border border-zinc-800/90 bg-zinc-950/80 px-3.5 py-2.5 font-mono text-xs shadow-inner backdrop-blur transition-all hover:border-zinc-700/80",y),children:[s.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto select-all",children:[s.jsx("span",{className:"select-none text-amber-500/80 font-bold",children:h}),s.jsx("span",{className:"text-zinc-200 whitespace-nowrap",children:r})]}),s.jsx("button",{onClick:_,className:"flex items-center gap-1 shrink-0 rounded border border-zinc-800 bg-zinc-900/80 px-2 py-1 text-xs text-zinc-400 transition-colors hover:border-zinc-700 hover:text-zinc-100",title:"Copy command",children:o?s.jsxs(s.Fragment,{children:[s.jsx(Bu,{className:"h-3.5 w-3.5 text-emerald-400"}),s.jsx("span",{className:"text-emerald-400 text-[11px]",children:"Copied"})]}):s.jsxs(s.Fragment,{children:[s.jsx(Lu,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"text-[11px]",children:"Copy"})]})})]})},Zg=[{feature:"Memory Safety Model",track:"Linear Ownership + Lexical Lenses (Compile-time verified)",rust:"Borrow Checker with Lifetime Parameters",zig:"Manual Allocators (Runtime safety checks)",c:"Manual (Unchecked, undefined behavior)",go:"Tracing Garbage Collector (Stop-the-world)",advantage:"track"},{feature:"Lifetime Annotations",track:"None (Zero lifetime syntax or annotations)",rust:"Infectious syntax ('a, 'b: 'a, elision rules)",zig:"N/A (No lifetime analysis)",c:"N/A",go:"N/A",advantage:"track"},{feature:"Runtime / GC Overhead",track:"Zero Runtime, Zero GC, Deterministic latency",rust:"Zero Runtime, Zero GC",zig:"Zero Runtime, Zero GC",c:"Zero Runtime, Zero GC",go:"Heavy runtime (~2-10ms GC pauses)",advantage:"neutral"},{feature:"Error Handling Model",track:"Explicit Stack Tuples (T, i32) & Predicates",rust:"Monadic Result & ? Operator",zig:"Error Sets & try operator",c:"Status codes / global errno",go:"(value, error) multi-return",advantage:"track"},{feature:"Compiler Backend",track:"Built-in native x86-64 backend, or portable C emitter",rust:"LLVM (Large memory & build overhead)",zig:"LLVM / C Emitter / Self-hosted x86",c:"GCC / Clang (LLVM)",go:"Custom Go Plan9 backend",advantage:"track"},{feature:"Package Manager",track:"Yard (Built-in test orchestrator & builder)",rust:"Cargo",zig:"Zig Build system",c:"CMake / Make / Meson (Fragmented)",go:"Go Modules",advantage:"neutral"},{feature:"Pattern Matching & Guards",track:"Full Nested Pattern Matching + Arm Guards",rust:"Full Pattern Matching + Guards",zig:"Basic switch expressions",c:"Integer switch statements only",go:"Type switches only",advantage:"track"},{feature:"Self-Hosting Status",track:"Self-hosted: trackc is written in Track; C-seed bootstrap with byte-identical fixed points",rust:"Self-hosted via LLVM",zig:"Self-hosted",c:"Self-hosted (GCC/Clang)",go:"Self-hosted",advantage:"neutral"}],aa=[{id:"hello",title:"Hello World",category:"Toolchain",description:"Minimal entrypoint with std/io and void main function.",filename:"examples/hello.trk",code:`import "std/io"; fn main() -> void { io::print("Hello, Track!"); @@ -322,49 +322,11 @@ fn main() -> void { let p = Packet::Data(256, true); handle_packet(p); }`,expectedOutput:`Verified data packet length: -256`}],Qg=({onSelectTab:o,onOpenPlaygroundWithCode:h})=>{const[y,r]=fe.useState("hello"),S=aa.find(N=>N.id===y)||aa[0];return s.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-12 sm:px-6 space-y-16",children:[s.jsxs("section",{className:"space-y-6 pt-4 text-left",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-xs font-mono text-amber-500 font-semibold tracking-wide uppercase",children:"Systems Programming Language"}),s.jsxs("h1",{className:"text-3xl sm:text-5xl font-extrabold font-sans text-zinc-100 tracking-tight leading-tight",children:["Deterministic Memory Safety ",s.jsx("br",{className:"hidden sm:inline"}),"without Lifetime Annotations."]})]}),s.jsx("p",{className:"text-base text-zinc-300 font-sans leading-relaxed max-w-3xl",children:"Track is a low-level systems programming language designed for real-time predictability, zero-cost abstractions, and compile-time memory safety without a garbage collector or complex lifetime parameters."}),s.jsxs("div",{className:"pt-2 max-w-2xl",children:[s.jsxs("div",{className:"text-xs font-mono text-zinc-400 mb-1.5 flex items-center gap-1.5",children:[s.jsx(pm,{className:"h-3.5 w-3.5 text-zinc-500"}),s.jsx("span",{children:"Install standalone compiler & toolchain:"})]}),s.jsx(Xg,{command:"curl -fsSL https://raw.githubusercontent.com/dev-dami/track/main/scripts/install.sh | bash"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-4 pt-2 font-mono text-xs",children:[s.jsxs("button",{onClick:()=>o("docs"),className:"flex items-center gap-1.5 bg-amber-500 text-zinc-950 px-3.5 py-2 rounded font-bold hover:bg-amber-400 transition-colors",children:[s.jsx(Ou,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Documentation"}),s.jsx(sc,{className:"h-3.5 w-3.5"})]}),s.jsxs("button",{onClick:()=>o("stdlib"),className:"flex items-center gap-1.5 border border-zinc-800 bg-zinc-900/80 text-zinc-200 px-3.5 py-2 rounded font-medium hover:border-zinc-700 transition-colors",children:[s.jsx(Th,{className:"h-3.5 w-3.5 text-cyan-400"}),s.jsx("span",{children:"Standard Library"})]}),s.jsxs("button",{onClick:()=>o("playground"),className:"flex items-center gap-1.5 border border-zinc-800 bg-zinc-900/80 text-zinc-200 px-3.5 py-2 rounded font-medium hover:border-zinc-700 transition-colors",children:[s.jsx(jh,{className:"h-3.5 w-3.5 text-amber-400"}),s.jsx("span",{children:"Interactive Playground"})]}),s.jsxs("button",{onClick:()=>o("roadmap"),className:"flex items-center gap-1.5 text-zinc-400 hover:text-zinc-200 transition-colors px-2 py-2",children:[s.jsx(Lh,{className:"h-3.5 w-3.5 text-purple-400"}),s.jsx("span",{children:"v0.9.0 Bootstrapping Roadmap"})]})]})]}),s.jsxs("section",{className:"space-y-4 pt-4 border-t border-zinc-800/60",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-2",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Track by Example"}),s.jsx("div",{className:"flex items-center gap-1 overflow-x-auto pb-1 font-mono text-xs",children:aa.slice(0,6).map(N=>s.jsx("button",{onClick:()=>r(N.id),className:tt("px-2.5 py-1 rounded transition-colors whitespace-nowrap",y===N.id?"bg-zinc-800 text-amber-400 font-semibold":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900"),children:N.title.split(" ")[0]},N.id))})]}),s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800 bg-zinc-900/70 px-4 py-2 text-xs font-mono text-zinc-400",children:[s.jsx("span",{children:S.filename}),s.jsx("span",{className:"text-zinc-500",children:S.description})]}),s.jsx("div",{className:"p-2",children:s.jsx(cc,{code:S.code,language:"track",showLineNumbers:!0,onRun:()=>{h?h(S.code):o("playground")}})})]})]}),s.jsxs("section",{className:"space-y-6 pt-4 border-t border-zinc-800/60",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Core Language Architecture"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 text-sm",children:[s.jsxs("div",{className:"space-y-2 border-l-2 border-amber-500/80 pl-4",children:[s.jsx("h3",{className:"font-mono font-bold text-zinc-100",children:"Deterministic Linear Ownership"}),s.jsxs("p",{className:"text-xs text-zinc-400 leading-relaxed font-sans",children:["Resource lifecycles are statically verified at compile time. Variables transition strictly through ",s.jsx("code",{className:"text-amber-300 font-mono",children:"Active"}),", ",s.jsx("code",{className:"text-cyan-300 font-mono",children:"Borrowed"}),", ",s.jsx("code",{className:"text-amber-400 font-mono",children:"Locked"}),", and ",s.jsx("code",{className:"text-purple-400 font-mono",children:"Spent"}),", with automatic destruction at spend points."]})]}),s.jsxs("div",{className:"space-y-2 border-l-2 border-cyan-500/80 pl-4",children:[s.jsxs("h3",{className:"font-mono font-bold text-zinc-100",children:["Lexical Lenses (",s.jsx("code",{className:"text-cyan-400 font-mono",children:"with"}),")"]}),s.jsxs("p",{className:"text-xs text-zinc-400 leading-relaxed font-sans",children:["Non-escaping lexical views replace lifetime parameters (",s.jsx("code",{className:"text-zinc-300 font-mono",children:"'a"}),"). Mutation is strictly bounded to the ",s.jsx("code",{className:"text-cyan-300 font-mono",children:"with"})," block, freezing the outer variable and restoring ownership on scope exit."]})]}),s.jsxs("div",{className:"space-y-2 border-l-2 border-emerald-500/80 pl-4",children:[s.jsx("h3",{className:"font-mono font-bold text-zinc-100",children:"Standalone Cranelift Backend"}),s.jsx("p",{className:"text-xs text-zinc-400 leading-relaxed font-sans",children:"Fast, standalone native code generation for x86_64 and aarch64 without multi-gigabyte LLVM dynamic libraries. Multi-threaded worker ISA sharing ensures instant check and build cycles."})]})]})]}),s.jsxs("section",{className:"space-y-4 pt-4 border-t border-zinc-800/60",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Comparison with Other Systems Languages"}),s.jsx("p",{className:"text-xs text-zinc-400 font-sans",children:"How Track compares in memory safety guarantees, cognitive overhead, and backend architecture."}),s.jsx("div",{className:"overflow-x-auto rounded border border-zinc-800 bg-[#0d0e12]",children:s.jsxs("table",{className:"w-full text-left font-sans text-xs systems-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Feature"}),s.jsx("th",{className:"text-amber-400 bg-zinc-900/90 font-bold",children:"Track"}),s.jsx("th",{children:"Rust"}),s.jsx("th",{children:"Zig"}),s.jsx("th",{children:"C"}),s.jsx("th",{children:"Go"})]})}),s.jsx("tbody",{children:Zg.map((N,_)=>s.jsxs("tr",{children:[s.jsx("td",{className:"font-mono font-medium text-zinc-300",children:N.feature}),s.jsx("td",{className:"font-mono text-amber-300 bg-zinc-900/40 font-semibold",children:N.track}),s.jsx("td",{className:"text-zinc-400",children:N.rust}),s.jsx("td",{className:"text-zinc-400",children:N.zig}),s.jsx("td",{className:"text-zinc-400",children:N.c}),s.jsx("td",{className:"text-zinc-400",children:N.go})]},_))})]})})]}),s.jsxs("section",{className:"space-y-4 pt-4 border-t border-zinc-800/60",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Toolchain & Self-Hosting Roadmap"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-xs font-mono",children:[s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2",children:[s.jsx("div",{className:"text-amber-400 font-bold",children:"Package Manager: Yard"}),s.jsxs("p",{className:"text-zinc-400 font-sans",children:[s.jsx("code",{className:"text-zinc-200",children:"yard"})," manages dependencies, builds native packages, runs lint passes, and executes native Track test suites (",s.jsx("code",{className:"text-zinc-200",children:"yard test"}),")."]})]}),s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2",children:[s.jsx("div",{className:"text-cyan-400 font-bold",children:"Language Server: track-lsp"}),s.jsxs("p",{className:"text-zinc-400 font-sans",children:["Provides real-time AST diagnostics, autocompletion, and type-checks ",s.jsx("code",{className:"text-zinc-200",children:"```track"})," code blocks embedded in markdown files."]})]})]})]})]})},ul=[{id:"intro",title:"Introduction & Design Philosophy",subtitle:"Deterministic memory safety without lifetime annotations or garbage collection",category:"Getting Started",content:"\nTrack is a modern, low-level systems programming language designed from the ground up for predictable latency, deterministic resource management, zero-cost abstractions, and real-time execution.\n\n### The Problem Track Solves\n\nSystems programmers have historically been forced into a difficult triad of trade-offs:\n1. **Manual Memory Management (C / C++)**: Extreme performance and control, but plagued with spatial and temporal memory safety bugs (use-after-free, double-free, buffer overflows, memory leaks).\n2. **Garbage Collection (Go / Java / C#)**: Safe memory management, but at the cost of non-deterministic stop-the-world pauses, hidden runtime allocations, increased memory overhead, and unsuitable predictability for kernels and embedded runtimes.\n3. **Complex Lifetime Annotations (Rust)**: Safe and GC-free, but introduces significant cognitive complexity with infectious lifetime parameters (`'a`, `'b`), borrow-checker fighting, and complex reference graphs.\n\n### Track's Core Innovations\n\nTrack answers this with three foundational principles:\n- **No Garbage Collector, No Hidden Runtime**: Resource lifecycles are statically verified at compile time. Destruction code (`vec_free`, `str_free`) is automatically emitted at deterministically computed spend points.\n- **Linear Ownership State Machine**: Resources have exactly one active owner. Every variable transitions strictly between 4 states: `Active`, `Borrowed`, `Locked`, and `Spent`.\n- **Lexical Lenses (`with` blocks)**: Scoped, non-escaping mutable views that eliminate lifetime annotations altogether.\n- **Cranelift Standalone Backend**: Instant compilation with native machine code generation for x86_64 and aarch64, avoiding heavy LLVM dynamic dependencies.\n- **Explicit Stack-Based Error Handling**: No monadic wrappers (`Option` / `Result`), no `?` hidden control flow, no stack unwinding. Errors are first-class stack values.\n ",codeSnippets:[{title:"hello.trk — Standard I/O and Void Main",language:"track",code:`import "std/io"; +256`}],Qg=({onSelectTab:r,onOpenPlaygroundWithCode:h})=>{const[y,o]=fe.useState("hello"),N=aa.find(_=>_.id===y)||aa[0];return s.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-12 sm:px-6 space-y-16",children:[s.jsxs("section",{className:"space-y-6 pt-4 text-left",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-xs font-mono text-amber-500 font-semibold tracking-wide uppercase",children:"Systems Programming Language"}),s.jsxs("h1",{className:"text-3xl sm:text-5xl font-extrabold font-sans text-zinc-100 tracking-tight leading-tight",children:["Deterministic Memory Safety ",s.jsx("br",{className:"hidden sm:inline"}),"without Lifetime Annotations."]})]}),s.jsx("p",{className:"text-base text-zinc-300 font-sans leading-relaxed max-w-3xl",children:"Track is a low-level systems programming language designed for real-time predictability, zero-cost abstractions, and compile-time memory safety without a garbage collector or complex lifetime parameters."}),s.jsxs("div",{className:"pt-2 max-w-2xl",children:[s.jsxs("div",{className:"text-xs font-mono text-zinc-400 mb-1.5 flex items-center gap-1.5",children:[s.jsx(pm,{className:"h-3.5 w-3.5 text-zinc-500"}),s.jsx("span",{children:"Install standalone compiler & toolchain:"})]}),s.jsx(Xg,{command:"curl -fsSL https://raw.githubusercontent.com/dev-dami/track/main/scripts/install.sh | bash"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-4 pt-2 font-mono text-xs",children:[s.jsxs("button",{onClick:()=>r("docs"),className:"flex items-center gap-1.5 bg-amber-500 text-zinc-950 px-3.5 py-2 rounded font-bold hover:bg-amber-400 transition-colors",children:[s.jsx(Ou,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Documentation"}),s.jsx(sc,{className:"h-3.5 w-3.5"})]}),s.jsxs("button",{onClick:()=>r("stdlib"),className:"flex items-center gap-1.5 border border-zinc-800 bg-zinc-900/80 text-zinc-200 px-3.5 py-2 rounded font-medium hover:border-zinc-700 transition-colors",children:[s.jsx(T0,{className:"h-3.5 w-3.5 text-cyan-400"}),s.jsx("span",{children:"Standard Library"})]}),s.jsxs("button",{onClick:()=>r("playground"),className:"flex items-center gap-1.5 border border-zinc-800 bg-zinc-900/80 text-zinc-200 px-3.5 py-2 rounded font-medium hover:border-zinc-700 transition-colors",children:[s.jsx(j0,{className:"h-3.5 w-3.5 text-amber-400"}),s.jsx("span",{children:"Interactive Playground"})]}),s.jsxs("button",{onClick:()=>r("roadmap"),className:"flex items-center gap-1.5 text-zinc-400 hover:text-zinc-200 transition-colors px-2 py-2",children:[s.jsx(L0,{className:"h-3.5 w-3.5 text-purple-400"}),s.jsx("span",{children:"Self-Hosting Roadmap"})]})]})]}),s.jsxs("section",{className:"space-y-4 pt-4 border-t border-zinc-800/60",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-2",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Track by Example"}),s.jsx("div",{className:"flex items-center gap-1 overflow-x-auto pb-1 font-mono text-xs",children:aa.slice(0,6).map(_=>s.jsx("button",{onClick:()=>o(_.id),className:tt("px-2.5 py-1 rounded transition-colors whitespace-nowrap",y===_.id?"bg-zinc-800 text-amber-400 font-semibold":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900"),children:_.title.split(" ")[0]},_.id))})]}),s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800 bg-zinc-900/70 px-4 py-2 text-xs font-mono text-zinc-400",children:[s.jsx("span",{children:N.filename}),s.jsx("span",{className:"text-zinc-500",children:N.description})]}),s.jsx("div",{className:"p-2",children:s.jsx(cc,{code:N.code,language:"track",showLineNumbers:!0,onRun:()=>{h?h(N.code):r("playground")}})})]})]}),s.jsxs("section",{className:"space-y-6 pt-4 border-t border-zinc-800/60",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Core Language Architecture"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 text-sm",children:[s.jsxs("div",{className:"space-y-2 border-l-2 border-amber-500/80 pl-4",children:[s.jsx("h3",{className:"font-mono font-bold text-zinc-100",children:"Deterministic Linear Ownership"}),s.jsxs("p",{className:"text-xs text-zinc-400 leading-relaxed font-sans",children:["Resource lifecycles are statically verified at compile time. Variables transition strictly through ",s.jsx("code",{className:"text-amber-300 font-mono",children:"Active"}),", ",s.jsx("code",{className:"text-cyan-300 font-mono",children:"Borrowed"}),", ",s.jsx("code",{className:"text-amber-400 font-mono",children:"Locked"}),", and ",s.jsx("code",{className:"text-purple-400 font-mono",children:"Spent"}),", with automatic destruction at spend points."]})]}),s.jsxs("div",{className:"space-y-2 border-l-2 border-cyan-500/80 pl-4",children:[s.jsxs("h3",{className:"font-mono font-bold text-zinc-100",children:["Lexical Lenses (",s.jsx("code",{className:"text-cyan-400 font-mono",children:"with"}),")"]}),s.jsxs("p",{className:"text-xs text-zinc-400 leading-relaxed font-sans",children:["Non-escaping lexical views replace lifetime parameters (",s.jsx("code",{className:"text-zinc-300 font-mono",children:"'a"}),"). Mutation is strictly bounded to the ",s.jsx("code",{className:"text-cyan-300 font-mono",children:"with"})," block, freezing the outer variable and restoring ownership on scope exit."]})]}),s.jsxs("div",{className:"space-y-2 border-l-2 border-emerald-500/80 pl-4",children:[s.jsx("h3",{className:"font-mono font-bold text-zinc-100",children:"Native Backend, No Linker"}),s.jsx("p",{className:"text-xs text-zinc-400 leading-relaxed font-sans",children:"trackc build --native writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. Prefer C? trackc build compiles through generated C."})]})]})]}),s.jsxs("section",{className:"space-y-4 pt-4 border-t border-zinc-800/60",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Comparison with Other Systems Languages"}),s.jsx("p",{className:"text-xs text-zinc-400 font-sans",children:"How Track compares in memory safety guarantees, cognitive overhead, and backend architecture."}),s.jsx("div",{className:"overflow-x-auto rounded border border-zinc-800 bg-[#0d0e12]",children:s.jsxs("table",{className:"w-full text-left font-sans text-xs systems-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Feature"}),s.jsx("th",{className:"text-amber-400 bg-zinc-900/90 font-bold",children:"Track"}),s.jsx("th",{children:"Rust"}),s.jsx("th",{children:"Zig"}),s.jsx("th",{children:"C"}),s.jsx("th",{children:"Go"})]})}),s.jsx("tbody",{children:Zg.map((_,z)=>s.jsxs("tr",{children:[s.jsx("td",{className:"font-mono font-medium text-zinc-300",children:_.feature}),s.jsx("td",{className:"font-mono text-amber-300 bg-zinc-900/40 font-semibold",children:_.track}),s.jsx("td",{className:"text-zinc-400",children:_.rust}),s.jsx("td",{className:"text-zinc-400",children:_.zig}),s.jsx("td",{className:"text-zinc-400",children:_.c}),s.jsx("td",{className:"text-zinc-400",children:_.go})]},z))})]})})]}),s.jsxs("section",{className:"space-y-4 pt-4 border-t border-zinc-800/60",children:[s.jsx("h2",{className:"text-xl font-bold font-sans text-zinc-100",children:"Toolchain & Self-Hosting Roadmap"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-xs font-mono",children:[s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2",children:[s.jsx("div",{className:"text-amber-400 font-bold",children:"Package Manager: Yard"}),s.jsxs("p",{className:"text-zinc-400 font-sans",children:[s.jsx("code",{className:"text-zinc-200",children:"yard"})," manages dependencies, builds native packages, runs lint passes, and executes native Track test suites (",s.jsx("code",{className:"text-zinc-200",children:"yard test"}),")."]})]}),s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2",children:[s.jsx("div",{className:"text-cyan-400 font-bold",children:"Language Server: trackc lsp"}),s.jsxs("p",{className:"text-zinc-400 font-sans",children:["Provides real-time AST diagnostics, autocompletion, and type-checks ",s.jsx("code",{className:"text-zinc-200",children:"```track"})," code blocks embedded in markdown files."]})]})]})]})]})},ul=[{id:"intro",title:"Introduction & Design Philosophy",subtitle:"Deterministic memory safety without lifetime annotations or garbage collection",category:"Getting Started",content:"\nTrack is a modern, low-level systems programming language designed from the ground up for predictable latency, deterministic resource management, zero-cost abstractions, and real-time execution.\n\n### The Problem Track Solves\n\nSystems programmers have historically been forced into a difficult triad of trade-offs:\n1. **Manual Memory Management (C / C++)**: Extreme performance and control, but plagued with spatial and temporal memory safety bugs (use-after-free, double-free, buffer overflows, memory leaks).\n2. **Garbage Collection (Go / Java / C#)**: Safe memory management, but at the cost of non-deterministic stop-the-world pauses, hidden runtime allocations, increased memory overhead, and unsuitable predictability for kernels and embedded runtimes.\n3. **Complex Lifetime Annotations (Rust)**: Safe and GC-free, but introduces significant cognitive complexity with infectious lifetime parameters (`'a`, `'b`), borrow-checker fighting, and complex reference graphs.\n\n### Track's Core Innovations\n\nTrack answers this with three foundational principles:\n- **No Garbage Collector, No Hidden Runtime**: Resource lifecycles are statically verified at compile time. Destruction code (`vec_free`, `str_free`) is automatically emitted at deterministically computed spend points.\n- **Linear Ownership State Machine**: Resources have exactly one active owner. Every variable transitions strictly between 4 states: `Active`, `Borrowed`, `Locked`, and `Spent`.\n- **Lexical Lenses (`with` blocks)**: Scoped, non-escaping mutable views that eliminate lifetime annotations altogether.\n- **Native Backend**: `trackc build --native` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. The default path goes through generated C.\n- **Explicit Stack-Based Error Handling**: No monadic wrappers (`Option` / `Result`), no `?` hidden control flow, no stack unwinding. Errors are first-class stack values.\n ",codeSnippets:[{title:"hello.trk — Standard I/O and Void Main",language:"track",code:`import "std/io"; fn main() -> void { io::print("Hello, Track systems world!"); -}`}]},{id:"installation",title:"Installation & Toolchain Setup",subtitle:"Get up and running with track, yard, and track-lsp in seconds",category:"Getting Started",content:` -Track provides a unified, single-binary toolchain consisting of the standalone compiler (\`track\`), the package manager & test runner (\`yard\`), and the Language Server Protocol daemon (\`track-lsp\`). - -### Quick Installation via Shell Script - -On Linux (x86_64, aarch64) or macOS, install the complete Track toolchain using the official installer: - -\`\`\`bash -curl -fsSL https://raw.githubusercontent.com/dev-dami/track/main/scripts/install.sh | bash -\`\`\` - -This downloads and configures \`track\`, \`yard\`, and \`track-lsp\` into your \`/usr/local/bin\` or \`~/.local/bin\`. - -### Building from Source - -Track's host compiler is implemented in Rust (2024 edition) and builds cleanly using Cargo: - -\`\`\`bash -# Clone the repository -git clone https://github.com/dev-dami/track.git -cd track - -# Build release binaries (track, yard, track-lsp) -cargo build --release - -# Run local installer -./scripts/install.sh -\`\`\` - -### Verifying Toolchain Installation - -\`\`\`bash -track --version -# track 0.7.0 - -yard --version -# yard 0.7.0 -\`\`\` - `,codeSnippets:[{title:"Terminal Quickstart",language:"bash",code:`# Create a new Track package +}`}]},{id:"installation",title:"Installation & Toolchain Setup",subtitle:"Get up and running with trackc and yard",category:"Getting Started",content:"\nTrack ships as a self-hosted toolchain: the compiler (`trackc`, written in Track), the package manager & test runner (`yard`, also written in Track), and the Language Server (`trackc lsp`, built into the compiler).\n\n### Quick Installation via Shell Script\n\nThe installer bootstraps `trackc` from the committed C seed and builds `yard`. It needs a C compiler (`cc`), `git` and POSIX tools:\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/dev-dami/track/main/scripts/install.sh | bash\n```\n\nThe binaries are installed into `~/.track/bin` by default (override with `--dir` or `TRACK_INSTALL_DIR`).\n\n### Building from Source\n\nTrack is self-hosting: `trackc` is written in Track and compiles itself to a verified fixed point. A clean checkout needs only a C compiler (`cc`) and POSIX tools; there is no Rust toolchain involved.\n\n```bash\n# Clone the repository\ngit clone https://github.com/dev-dami/track.git\ncd track\n# cc -> stage1..3 -> native; trackc is build/bootstrap/stage3/trackc\nscripts/bootstrap.sh\n# yard, written in Track\nbuild/bootstrap/stage3/trackc build --native tools/yard/main.trk -o yard\n# Or bootstrap and install trackc + yard in one step\n./scripts/install.sh\n```\n\nOn hosts other than x86-64 Linux (macOS, ARM) use `scripts/bootstrap.sh --no-native` for the C-only bootstrap.\n\n### Verifying Toolchain Installation\n\n```bash\ntrackc --version\n# trackc 1.0.0\n```\n ",codeSnippets:[{title:"Terminal Quickstart",language:"bash",code:`# Create a new Track package yard init my_kernel_module cd my_kernel_module @@ -542,7 +504,7 @@ fn pair(a: T, b: U) -> (T, U) { 1. **Call Site Type Inference**: Type parameters (\`T\`, \`U\`) are inferred automatically from actual argument types. 2. **Specialization & Mangling**: Each distinct combination produces a mangled concrete function (e.g. \`identity__Ti32\`, \`pair__Ti32_Ubool\`). -3. **Direct Emitted Cranelift Machine Code**: No dynamic boxing, no runtime vtable pointer indirection. +3. **Direct Emitted Machine Code**: No dynamic boxing, no runtime vtable pointer indirection. `,codeSnippets:[{title:"Monomorphized Generics Demo",language:"track",code:`fn swap_pair(p: (A, B)) -> (B, A) { let (first, second) = p; return (second, first); @@ -565,13 +527,12 @@ fn main() -> void { │ └── lexer_test.trk └── target/ └── my_project`}]},{id:"lsp",title:"Language Server Protocol (LSP) & IDE Setup",subtitle:"Real-time diagnostics, auto-completion, and markdown track-block checking",category:"Toolchain & Compiler",content:` -Track ships with a dedicated LSP daemon (\`track-lsp\`) built on top of Tower-LSP and Tokio. +Track's language server is part of the self-hosted compiler. Start it with \`trackc lsp\`; it is written in Track (\`compiler/src/lsp.trk\`) and speaks JSON-RPC 2.0 over stdin/stdout. ### Key Capabilities -- **Live Diagnostics**: Real-time ownership checking, type errors, and span highlights in \`.trk\` files. -- **Markdown Code Block Checking**: \`track-lsp\` parses and type-checks \`\`\`track code blocks inside \`.md\` documentation files! -- **Fast Auto-Completion**: Keywords, stdlib modules, structs, and tagged union variants. -- **AST Caching & Stale Result Discarding**: Prevents publishing outdated diagnostics on fast keystrokes. +- **Live Diagnostics**: Exactly what \`trackc check\` reports (lexer, parser, ownership and lifecycle errors, plus warnings), published on open, change and save. +- **Markdown Code Block Checking**: \`\`\`track blocks inside \`.md\` files are checked per block. +- **Auto-Completion & Hover**: Keywords, types, built-ins, macros, and the file's own functions and enum/union variants. ### VS Code Configuration @@ -580,7 +541,8 @@ Add this to your \`.vscode/settings.json\`: \`\`\`json { "language-server.track": { - "command": "track-lsp", + "command": "trackc", + "args": ["lsp"], "filePatterns": ["*.trk", "*.md"] } } @@ -589,7 +551,7 @@ Add this to your \`.vscode/settings.json\`: ### TextMate Syntax Highlighting TextMate grammar is provided at \`grammars/track.tmLanguage.json\`. `,codeSnippets:[{title:"VS Code Extension Setup",language:"bash",code:`mkdir -p ~/.vscode/extensions/track-syntax/syntaxes -cp grammars/track.tmLanguage.json ~/.vscode/extensions/track-syntax/syntaxes/`}]},{id:"self-hosting",title:"Self-Hosted Compiler & Roadmap to v0.9.0",subtitle:"Track lexer in native Track and the 3-stage bootstrapping gate",category:"Toolchain & Compiler",content:"\nTrack is actively executing its path to full compiler self-bootstrapping.\n\n### Milestone Progress Overview\n\n```\n[v0.1.6] Slices & Memory Primitives ✅ DONE\n[v0.2.0] UFCS, Lenses & CFG Merging ✅ DONE\n[v0.3.0] Perf & Self-Hosting Readiness ✅ DONE\n[v0.4.0] Tuples & Pattern Matching ✅ DONE\n[v0.5.0] Explicit Error Handling ✅ DONE\n[v0.6.0] Monomorphized Generics ✅ DONE\n[v0.7.0] Self-Hosted Lexer in Track ✅ DONE (compiler/src/lexer.trk)\n[v0.8.0] Parser, Checker & C-Emitter ⏳ IN PROGRESS\n[v0.9.0] 3-Stage Bootstrapping Verified 🎯 MILESTONE\n```\n\n### v0.7.0 Milestone: Self-Hosted Lexer\nIn v0.7.0, Track successfully ported the host lexer from Rust into 100% native Track (`compiler/src/lexer.trk`), recognizing 50+ token variants with native union matching and 10 unit test suites.\n\n### The 3-Stage Bootstrapping Gate (v0.9.0)\n1. **Stage 0**: Host Rust `track` compiler compiles `compiler/*.trk` → emits `track_stage1` executable.\n2. **Stage 1**: `track_stage1` compiles `compiler/*.trk` → emits `track_stage2` executable.\n3. **Stage 2**: `track_stage2` compiles `compiler/*.trk` → emits `track_stage3` executable.\n4. **Verification**: Assert byte-for-byte binary equality (`cmp track_stage2 track_stage3`).\n ",codeSnippets:[{title:"compiler/src/token.trk — Native Token Union",language:"track",code:`union Token { +cp grammars/track.tmLanguage.json ~/.vscode/extensions/track-syntax/syntaxes/`}]},{id:"self-hosting",title:"Self-Hosted Compiler & Bootstrap",subtitle:"trackc is written in Track and compiles itself to a verified fixed point",category:"Toolchain & Compiler",content:"\nTrack 1.0 is self-hosting: `trackc`, the compiler in `compiler/src/`, is written entirely in Track. `yard` and `trackc lsp` are written in Track too. The earlier Rust stage 0 has been removed.\n\n### Milestone Progress Overview\n\n```\n[v0.1.6] Slices & Memory Primitives ✅ DONE\n[v0.2.0] UFCS, Lenses & CFG Merging ✅ DONE\n[v0.3.0] Perf & Self-Hosting Readiness ✅ DONE\n[v0.4.0] Tuples & Pattern Matching ✅ DONE\n[v0.5.0] Explicit Error Handling ✅ DONE\n[v0.6.0] Monomorphized Generics ✅ DONE\n[v0.7.0] Self-Hosted Lexer in Track ✅ DONE (compiler/src/lexer.trk)\n[v0.8.0] Parser, Checker & C-Emitter ✅ DONE\n[v0.9.0] 3-Stage Bootstrapping Verified ✅ DONE\n[v1.0.0] Self-Hosting, Rust removed ✅ DONE\n```\n\n### The Bootstrap\n\nA clean checkout builds `trackc` with only a C compiler (`cc`) and POSIX tools. `scripts/bootstrap.sh` starts from a committed C seed (`bootstrap/seed/`, the C that `trackc` emits for its own sources):\n\n1. **Stage 0**: `cc` builds the C seed into `stage1/trackc`.\n2. **Stage 1**: `stage1/trackc` compiles `compiler/src/main.trk` → `stage2/trackc`.\n3. **Stage 2**: `stage2/trackc` compiles `compiler/src/main.trk` → `stage3/trackc`.\n4. **Native**: `scripts/selfhost.sh` rebuilds `trackc` natively (`--native`, no C toolchain) until the native stages `n2`, `n3` and `n4` are byte-identical.\n\nThe gate checks that stage 1 and stage 2 emit identical C, that the stage 2 and stage 3 executables are byte-identical, and that the native stages reproduce themselves. After any change to `compiler/src/`, run `scripts/update_seed.sh` to regenerate the seed. See `docs/bootstrap.md` in the repository for the full pipeline.\n ",codeSnippets:[{title:"compiler/src/token.trk — Native Token Union",language:"track",code:`union Token { KwLet, KwMut, KwFn, @@ -605,13 +567,13 @@ cp grammars/track.tmLanguage.json ~/.vscode/extensions/track-syntax/syntaxes/`}] FatArrow, ColonColon, Eof, -}`}]}],Vg=({onSelectTab:o,onOpenPlaygroundWithCode:h,initialChapterId:y="intro"})=>{const[r,S]=fe.useState(y),[N,_]=fe.useState(""),O=ul.find(V=>V.id===r)||ul[0],j=ul.findIndex(V=>V.id===O.id),g=j>0?ul[j-1]:null,L=jV.title.toLowerCase().includes(N.toLowerCase())||V.subtitle.toLowerCase().includes(N.toLowerCase())||V.content.toLowerCase().includes(N.toLowerCase())),I=Array.from(new Set(ul.map(V=>V.category)));return s.jsx("div",{className:"mx-auto max-w-6xl px-4 py-8 sm:px-6",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-8 items-start",children:[s.jsxs("aside",{className:"md:col-span-4 lg:col-span-3 space-y-6 md:sticky md:top-20",children:[s.jsxs("div",{className:"relative",children:[s.jsx(uc,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-zinc-500"}),s.jsx("input",{type:"text",value:N,onChange:V=>_(V.target.value),placeholder:"Search docs...",className:"w-full rounded border border-zinc-800 bg-[#0d0e12] py-1.5 pl-8 pr-3 text-xs font-mono text-zinc-200 placeholder-zinc-500 focus:border-amber-500 focus:outline-none"})]}),s.jsx("div",{className:"space-y-4 max-h-[75vh] overflow-y-auto pr-1",children:I.map(V=>{const M=w.filter(D=>D.category===V);return M.length===0?null:s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"font-mono text-[11px] font-bold uppercase tracking-wider text-zinc-500 px-2 py-1",children:V}),s.jsx("div",{className:"space-y-0.5 border-l border-zinc-800 ml-2 pl-2",children:M.map(D=>{const ie=D.id===O.id;return s.jsx("button",{onClick:()=>{S(D.id),window.scrollTo({top:0,behavior:"smooth"})},className:tt("block w-full text-left py-1 px-2 text-xs font-sans rounded transition-colors",ie?"text-amber-400 font-semibold bg-zinc-900":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:D.title},D.id)})})]},V)})})]}),s.jsxs("main",{className:"md:col-span-8 lg:col-span-9 space-y-8 text-left",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4",children:[s.jsxs("div",{className:"text-[11px] font-mono text-zinc-500 mb-1",children:["Docs › ",O.category]}),s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:O.title}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1 leading-relaxed",children:O.subtitle})]}),s.jsx("div",{className:"space-y-6 text-sm text-zinc-300 font-sans leading-relaxed",children:O.content.split(` +}`}]}],Vg=({onSelectTab:r,onOpenPlaygroundWithCode:h,initialChapterId:y="intro"})=>{const[o,N]=fe.useState(y),[_,z]=fe.useState(""),O=ul.find(V=>V.id===o)||ul[0],A=ul.findIndex(V=>V.id===O.id),g=A>0?ul[A-1]:null,L=AV.title.toLowerCase().includes(_.toLowerCase())||V.subtitle.toLowerCase().includes(_.toLowerCase())||V.content.toLowerCase().includes(_.toLowerCase())),I=Array.from(new Set(ul.map(V=>V.category)));return s.jsx("div",{className:"mx-auto max-w-6xl px-4 py-8 sm:px-6",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-8 items-start",children:[s.jsxs("aside",{className:"md:col-span-4 lg:col-span-3 space-y-6 md:sticky md:top-20",children:[s.jsxs("div",{className:"relative",children:[s.jsx(uc,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-zinc-500"}),s.jsx("input",{type:"text",value:_,onChange:V=>z(V.target.value),placeholder:"Search docs...",className:"w-full rounded border border-zinc-800 bg-[#0d0e12] py-1.5 pl-8 pr-3 text-xs font-mono text-zinc-200 placeholder-zinc-500 focus:border-amber-500 focus:outline-none"})]}),s.jsx("div",{className:"space-y-4 max-h-[75vh] overflow-y-auto pr-1",children:I.map(V=>{const M=w.filter(D=>D.category===V);return M.length===0?null:s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"font-mono text-[11px] font-bold uppercase tracking-wider text-zinc-500 px-2 py-1",children:V}),s.jsx("div",{className:"space-y-0.5 border-l border-zinc-800 ml-2 pl-2",children:M.map(D=>{const ie=D.id===O.id;return s.jsx("button",{onClick:()=>{N(D.id),window.scrollTo({top:0,behavior:"smooth"})},className:tt("block w-full text-left py-1 px-2 text-xs font-sans rounded transition-colors",ie?"text-amber-400 font-semibold bg-zinc-900":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:D.title},D.id)})})]},V)})})]}),s.jsxs("main",{className:"md:col-span-8 lg:col-span-9 space-y-8 text-left",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4",children:[s.jsxs("div",{className:"text-[11px] font-mono text-zinc-500 mb-1",children:["Docs › ",O.category]}),s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:O.title}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1 leading-relaxed",children:O.subtitle})]}),s.jsx("div",{className:"space-y-6 text-sm text-zinc-300 font-sans leading-relaxed",children:O.content.split(` `).map((V,M)=>{const D=V.trim();if(!D)return null;if(D.startsWith("### "))return s.jsx("h3",{className:"text-base font-bold font-sans text-zinc-100 mt-6 mb-2 tracking-tight",children:D.replace("### ","")},M);if(D.startsWith("## "))return s.jsx("h2",{className:"text-lg font-bold font-sans text-zinc-100 mt-8 mb-3 border-b border-zinc-800/80 pb-1",children:D.replace("## ","")},M);if(D.startsWith("> "))return s.jsx("blockquote",{className:"border-l-2 border-amber-500/80 pl-4 my-4 font-mono text-xs text-zinc-300 italic",children:D.replace("> ","").replace(/\*/g,"")},M);if(D.startsWith("- ")||D.startsWith("1. ")){const ie=D.split(` `);return s.jsx("ul",{className:"space-y-1.5 my-3 pl-5 list-disc marker:text-zinc-500",children:ie.map((ye,ce)=>s.jsx("li",{className:"text-zinc-300 text-xs sm:text-sm",children:ye.replace(/^[-*]|\d+\.\s*/,"")},ce))},M)}if(D.startsWith("```")){const ie=D.split(` `),ye=ie[0].replace("```",""),ce=ie.slice(1,-1).join(` -`);return s.jsx(cc,{code:ce,language:ye||"track",onRun:()=>{h?h(ce):o("playground")}},M)}return s.jsx("p",{className:"text-zinc-300 text-xs sm:text-sm leading-relaxed font-sans",children:D},M)})}),O.codeSnippets&&O.codeSnippets.length>0&&s.jsxs("div",{className:"space-y-3 pt-4",children:[s.jsx("div",{className:"text-xs font-mono font-bold text-zinc-400",children:"Code Reference:"}),O.codeSnippets.map((V,M)=>s.jsx(cc,{code:V.code,language:V.language,filename:V.title,onRun:()=>{h?h(V.code):o("playground")}},M))]}),s.jsxs("div",{className:"flex items-center justify-between border-t border-zinc-800 pt-6 mt-10 text-xs font-mono",children:[g?s.jsxs("button",{onClick:()=>{S(g.id),window.scrollTo({top:0,behavior:"smooth"})},className:"flex items-center gap-1.5 text-zinc-400 hover:text-amber-400 transition-colors",children:[s.jsx(rm,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:g.title})]}):s.jsx("div",{}),L&&s.jsxs("button",{onClick:()=>{S(L.id),window.scrollTo({top:0,behavior:"smooth"})},className:"flex items-center gap-1.5 text-zinc-400 hover:text-amber-400 transition-colors",children:[s.jsx("span",{children:L.title}),s.jsx(sc,{className:"h-3.5 w-3.5"})]})]})]})]})})},Ru=[{name:"std/io",category:"I/O & Streams",description:"Standard output, error reporting, formatted printing, and terminal stream operations.",functions:[{name:"print_str",signature:"fn print_str(s: Str) -> void",description:"Outputs a string to standard output with automatic flush.",example:'print_str("Hello Track!");',errorModel:"None"},{name:"print_int",signature:"fn print_int(n: i64) -> void",description:"Formats and prints a signed 64-bit integer to stdout.",example:"print_int(42);",errorModel:"None"},{name:"print_hex",signature:"fn print_hex(val: u64) -> void",description:"Prints a value in hexadecimal notation prefixed by 0x.",example:"print_hex(0xDEADBEEF);",errorModel:"None"},{name:"print_err",signature:"fn print_err(msg: Str) -> void",description:"Outputs an error message to standard error stream (stderr).",example:'print_err("fatal initialization failure");',errorModel:"None"},{name:"read_line",signature:"fn read_line() -> Str",description:"Reads a line of text from standard input into an owned Str buffer.",example:"let input = read_line();",errorModel:"None"}]},{name:"std/fs",category:"File System",description:"POSIX file descriptor operations, file copying, size queries, and deletion.",functions:[{name:"file_open",signature:"fn file_open(path: ptr, mode: ptr) -> i32",description:"Opens a file descriptor. Returns null file descriptor (0) on failure.",example:`let fd = file_open("config.trk", "r"); -if (fd == 0) { abort("cannot open"); }`,errorModel:"Sentinel (-1)"},{name:"file_read_all",signature:"fn file_read_all(fd: i32) -> Str",description:"Reads the entire file into an owned string. Automatically frees when spent.",example:"let content = file_read_all(fd);",errorModel:"None"},{name:"file_write",signature:"fn file_write(fd: i32, content: &Str) -> i32",description:"Writes byte buffer to file descriptor. Returns 0 on success.",example:"file_write(fd, &content);",errorModel:"Status Code"},{name:"file_exists",signature:"fn file_exists(path: ptr) -> bool",description:"Boolean predicate checking file presence before access.",example:'if (file_exists("data.bin")) { /* ... */ }',errorModel:"Boolean Predicate"},{name:"file_size",signature:"fn file_size(path: ptr) -> i64",description:"Returns file length in bytes, or -1 if file cannot be statted.",example:'let bytes = file_size("kernel.bin");',errorModel:"Sentinel (-1)"},{name:"file_copy",signature:"fn file_copy(src: ptr, dst: ptr) -> i32",description:"Copies file from source path to destination path. Returns 0 on success.",example:'let res = file_copy("src.trk", "bak.trk");',errorModel:"Status Code"},{name:"file_remove",signature:"fn file_remove(path: ptr) -> i32",description:"Deletes a file from the filesystem. Returns 0 on success, -1 on failure.",example:'file_remove("temp.lock");',errorModel:"Status Code"}]},{name:"std/net",category:"Networking",description:"High-performance POSIX TCP server, client connection, and raw packet transfer.",functions:[{name:"net_socket_tcp_listen",signature:"fn net_socket_tcp_listen(port: i32) -> i32",description:"Binds and listens on local TCP port. Returns server socket file descriptor or -1.",example:"let server_fd = net_socket_tcp_listen(8080);",errorModel:"Sentinel (-1)"},{name:"net_socket_connect",signature:"fn net_socket_connect(host: ptr, port: i32) -> i32",description:"Establishes a client TCP connection to target host and port.",example:'let client_fd = net_socket_connect("127.0.0.1", 8080);',errorModel:"Sentinel (-1)"},{name:"net_socket_accept",signature:"fn net_socket_accept(server_fd: i32) -> i32",description:"Accepts incoming client connection. Returns connected peer socket descriptor.",example:"let peer_fd = net_socket_accept(server_fd);",errorModel:"Sentinel (-1)"},{name:"net_socket_send",signature:"fn net_socket_send(fd: i32, buf: ptr, len: i64) -> i64",description:"Transmits raw bytes over active socket. Returns bytes sent.",example:"let sent = net_socket_send(peer_fd, buf, 1024);",errorModel:"Sentinel (-1)"},{name:"net_socket_recv",signature:"fn net_socket_recv(fd: i32, buf: ptr, max_len: i64) -> i64",description:"Receives raw bytes from socket into target buffer.",example:"let read_bytes = net_socket_recv(peer_fd, buf, 4096);",errorModel:"Sentinel (-1)"},{name:"net_socket_close",signature:"fn net_socket_close(fd: i32) -> void",description:"Closes and disposes active network socket descriptor.",example:"net_socket_close(client_fd);",errorModel:"None"}]},{name:"std/str",category:"String & Memory",description:"Heap string allocation, substring search, splitting, trim, and conversion primitives.",functions:[{name:"str_from_literal",signature:"fn str_from_literal(raw: ptr) -> Str",description:"Constructs an owned Str structure from a null-terminated string literal.",example:'let s = str_from_literal("track");',errorModel:"None"},{name:"str_len",signature:"fn str_len(s: &Str) -> u32",description:"Calculates the byte length of a string reference in O(1).",example:"let length = str_len(&s);",errorModel:"None"},{name:"str_eq",signature:"fn str_eq(a: &Str, b: &Str) -> bool",description:"Tests if two strings have equal length and identical byte content.",example:"let same = str_eq(&a, &b);",errorModel:"None"},{name:"str_concat",signature:"fn str_concat(a: &Str, b: &Str) -> Str",description:"Allocates a new buffer containing the concatenated content of both strings.",example:"let joined = str_concat(&first, &last);",errorModel:"None"},{name:"str_find",signature:"fn str_find(s: Str, needle: Str) -> i32",description:"Finds index of needle in string, or returns -1 if not found.",example:'let idx = str_find("hello world", "world"); // 6',errorModel:"Sentinel (-1)"},{name:"str_is_int",signature:"fn str_is_int(s: Str) -> bool",description:"Boolean predicate verifying that string contains valid numeric digits.",example:"if (str_is_int(token)) { let n = str_to_int(token); }",errorModel:"Boolean Predicate"},{name:"str_to_int",signature:"fn str_to_int(s: Str) -> i64",description:"Parses string to signed integer. Pair with str_is_int.",example:'let val = str_to_int("1337");',errorModel:"None"},{name:"str_substr",signature:"fn str_substr(s: Str, start: u32, len: u32) -> Str",description:"Extracts a new owned substring slice.",example:"let sub = str_substr(raw, 0, 4);",errorModel:"None"},{name:"str_trim",signature:"fn str_trim(s: Str) -> Str",description:"Returns a trimmed string with leading and trailing whitespace removed.",example:"let clean = str_trim(dirty_input);",errorModel:"None"}]},{name:"std/os & std/process",category:"System & Process",description:"Process spawning, environment variable queries, and memory ceiling limits.",functions:[{name:"os_args_count",signature:"fn os_args_count() -> i32",description:"Returns total count of command-line arguments (argc).",example:"let count = os_args_count();",errorModel:"None"},{name:"os_arg",signature:"fn os_arg(index: i32) -> Str",description:"Fetches command-line argument by zero-based index (argv[i]).",example:"let target_file = os_arg(1);",errorModel:"None"},{name:"env_exists",signature:"fn env_exists(key: ptr) -> bool",description:"Tests if an environment variable is present in the current process.",example:'if (env_exists("TRACK_DEBUG")) { /* ... */ }',errorModel:"Boolean Predicate"},{name:"env_get",signature:"fn env_get(key: ptr) -> Str",description:"Reads value of environment variable. Pair with env_exists.",example:'let path = env_get("PATH");',errorModel:"None"},{name:"process_spawn",signature:"fn process_spawn(command: ptr) -> i32",description:"Spawns a child process and waits for termination. Returns process exit code.",example:'let status = process_spawn("cc -O2 -c out.c -o out.o");',errorModel:"Status Code"},{name:"sys_set_memory_limit",signature:"fn sys_set_memory_limit(bytes: u64) -> void",description:"Enforces a strict virtual memory ceiling on the active process.",example:"sys_set_memory_limit(128 * 1024 * 1024); // 128MB max",errorModel:"None"},{name:"sys_get_memory_used",signature:"fn sys_get_memory_used() -> u64",description:"Returns current resident set size (RSS) memory consumption in bytes.",example:"let bytes_used = sys_get_memory_used();",errorModel:"None"},{name:"abort",signature:"fn abort(msg: ptr) -> void",description:"Prints fatal message to stderr and immediately terminates process with code 134.",example:'abort("unrecoverable heap corruption");',errorModel:"Fatal Abort"}]},{name:"mem/alloc",category:"Memory Primitives",description:"Low-level manual memory allocators, zeroing, and block reallocation.",functions:[{name:"alloc",signature:"fn alloc(bytes: u64) -> ptr",description:"Allocates raw uninitialized memory block. Freed automatically when spent.",example:"let buf: ptr = alloc(4096);",errorModel:"None"},{name:"mem_realloc",signature:"fn mem_realloc(p: ptr, new_size: u64) -> ptr",description:"Resizes an existing memory block.",example:"let expanded = mem_realloc(buf, 8192);",errorModel:"None"},{name:"memset",signature:"fn memset(dest: ptr, val: i32, count: u64) -> void",description:"Fills target memory block with specified byte value.",example:"memset(buf, 0, 1024);",errorModel:"None"},{name:"memcpy",signature:"fn memcpy(dest: ptr, src: ptr, count: u64) -> void",description:"Copies count bytes from source memory buffer to destination.",example:"memcpy(dst, src, 1024);",errorModel:"None"},{name:"memcmp",signature:"fn memcmp(a: ptr, b: ptr, count: u64) -> i32",description:"Compares two memory buffers. Returns 0 if identical.",example:"let matches = (memcmp(a, b, len) == 0);",errorModel:"None"}]}],Kg=()=>{const[o,h]=fe.useState("all"),[y,r]=fe.useState(""),S=Ru.flatMap(_=>_.functions.map(O=>({...O,moduleName:_.name,moduleCategory:_.category}))),N=S.filter(_=>{const O=o==="all"||_.moduleName===o,j=_.name.toLowerCase().includes(y.toLowerCase())||_.signature.toLowerCase().includes(y.toLowerCase())||_.description.toLowerCase().includes(y.toLowerCase())||_.moduleName.toLowerCase().includes(y.toLowerCase());return O&&j});return s.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-8 sm:px-6",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4 mb-6",children:[s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:"Standard Library Reference"}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1",children:"Zero-overhead C runtime wrappers, memory allocators, POSIX file I/O, and TCP sockets."})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-8 items-start",children:[s.jsxs("aside",{className:"md:col-span-4 lg:col-span-3 space-y-4 md:sticky md:top-20",children:[s.jsxs("div",{className:"relative",children:[s.jsx(uc,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-zinc-500"}),s.jsx("input",{type:"text",value:y,onChange:_=>r(_.target.value),placeholder:"Filter functions...",className:"w-full rounded border border-zinc-800 bg-[#0d0e12] py-1.5 pl-8 pr-3 text-xs font-mono text-zinc-200 placeholder-zinc-500 focus:border-amber-500 focus:outline-none"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"font-mono text-[11px] font-bold uppercase tracking-wider text-zinc-500 px-2 py-1",children:"Modules"}),s.jsxs("div",{className:"space-y-0.5 border-l border-zinc-800 ml-2 pl-2",children:[s.jsxs("button",{onClick:()=>h("all"),className:tt("block w-full text-left py-1 px-2 text-xs font-mono rounded transition-colors",o==="all"?"text-amber-400 font-semibold bg-zinc-900":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:["All (",S.length,")"]}),Ru.map(_=>s.jsx("button",{onClick:()=>h(_.name),className:tt("block w-full text-left py-1 px-2 text-xs font-mono rounded transition-colors",o===_.name?"text-amber-400 font-semibold bg-zinc-900":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:_.name},_.name))]})]})]}),s.jsx("main",{className:"md:col-span-8 lg:col-span-9 space-y-6",children:N.length===0?s.jsx("div",{className:"py-12 text-center text-zinc-500 font-mono text-xs",children:"No matching functions found."}):N.map((_,O)=>s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2.5 text-left",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-zinc-800/60 pb-2",children:[s.jsx("span",{className:"font-mono text-xs font-bold text-zinc-200",children:_.name}),s.jsx("span",{className:"font-mono text-[11px] text-zinc-500",children:_.moduleName})]}),s.jsx("div",{className:"font-mono text-xs text-amber-400 bg-zinc-900/90 p-2 rounded overflow-x-auto select-all",children:_.signature}),s.jsx("p",{className:"text-xs text-zinc-300 font-sans leading-relaxed",children:_.description}),s.jsxs("div",{className:"pt-1",children:[s.jsx("div",{className:"text-[10px] font-mono text-zinc-500 mb-1",children:"Example:"}),s.jsx("pre",{className:"font-mono text-[11px] text-zinc-400 bg-[#08080a] p-2 rounded border border-zinc-900 overflow-x-auto whitespace-pre",children:_.example})]})]},O))})]})]})},Jg=({initialCode:o})=>{const[h,y]=fe.useState(o||aa[1].code),[r,S]=fe.useState("linear-auto-free"),[N,_]=fe.useState("cranelift"),[O,j]=fe.useState("release"),[g,L]=fe.useState("x86_64"),[w,I]=fe.useState("output"),[V,M]=fe.useState(!1),[D,ie]=fe.useState(!1),[ye,ce]=fe.useState("");fe.useEffect(()=>{const W=ke=>{(ke.metaKey||ke.ctrlKey)&&ke.key==="Enter"&&(ke.preventDefault(),Ne())};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[h,N,O]);const Ne=()=>{M(!0),setTimeout(()=>{M(!1),h.includes("Hello")?ce(`Hello, Track! +`);return s.jsx(cc,{code:ce,language:ye||"track",onRun:()=>{h?h(ce):r("playground")}},M)}return s.jsx("p",{className:"text-zinc-300 text-xs sm:text-sm leading-relaxed font-sans",children:D},M)})}),O.codeSnippets&&O.codeSnippets.length>0&&s.jsxs("div",{className:"space-y-3 pt-4",children:[s.jsx("div",{className:"text-xs font-mono font-bold text-zinc-400",children:"Code Reference:"}),O.codeSnippets.map((V,M)=>s.jsx(cc,{code:V.code,language:V.language,filename:V.title,onRun:()=>{h?h(V.code):r("playground")}},M))]}),s.jsxs("div",{className:"flex items-center justify-between border-t border-zinc-800 pt-6 mt-10 text-xs font-mono",children:[g?s.jsxs("button",{onClick:()=>{N(g.id),window.scrollTo({top:0,behavior:"smooth"})},className:"flex items-center gap-1.5 text-zinc-400 hover:text-amber-400 transition-colors",children:[s.jsx(om,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:g.title})]}):s.jsx("div",{}),L&&s.jsxs("button",{onClick:()=>{N(L.id),window.scrollTo({top:0,behavior:"smooth"})},className:"flex items-center gap-1.5 text-zinc-400 hover:text-amber-400 transition-colors",children:[s.jsx("span",{children:L.title}),s.jsx(sc,{className:"h-3.5 w-3.5"})]})]})]})]})})},Ru=[{name:"std/io",category:"I/O & Streams",description:"Standard output, error reporting, formatted printing, and terminal stream operations.",functions:[{name:"print_str",signature:"fn print_str(s: Str) -> void",description:"Outputs a string to standard output with automatic flush.",example:'print_str("Hello Track!");',errorModel:"None"},{name:"print_int",signature:"fn print_int(n: i64) -> void",description:"Formats and prints a signed 64-bit integer to stdout.",example:"print_int(42);",errorModel:"None"},{name:"print_hex",signature:"fn print_hex(val: u64) -> void",description:"Prints a value in hexadecimal notation prefixed by 0x.",example:"print_hex(0xDEADBEEF);",errorModel:"None"},{name:"print_err",signature:"fn print_err(msg: Str) -> void",description:"Outputs an error message to standard error stream (stderr).",example:'print_err("fatal initialization failure");',errorModel:"None"},{name:"read_line",signature:"fn read_line() -> Str",description:"Reads a line of text from standard input into an owned Str buffer.",example:"let input = read_line();",errorModel:"None"}]},{name:"std/fs",category:"File System",description:"POSIX file descriptor operations, file copying, size queries, and deletion.",functions:[{name:"file_open",signature:"fn file_open(path: ptr, mode: ptr) -> i32",description:"Opens a file descriptor. Returns null file descriptor (0) on failure.",example:`let fd = file_open("config.trk", "r"); +if (fd == 0) { abort("cannot open"); }`,errorModel:"Sentinel (-1)"},{name:"file_read_all",signature:"fn file_read_all(fd: i32) -> Str",description:"Reads the entire file into an owned string. Automatically frees when spent.",example:"let content = file_read_all(fd);",errorModel:"None"},{name:"file_write",signature:"fn file_write(fd: i32, content: &Str) -> i32",description:"Writes byte buffer to file descriptor. Returns 0 on success.",example:"file_write(fd, &content);",errorModel:"Status Code"},{name:"file_exists",signature:"fn file_exists(path: ptr) -> bool",description:"Boolean predicate checking file presence before access.",example:'if (file_exists("data.bin")) { /* ... */ }',errorModel:"Boolean Predicate"},{name:"file_size",signature:"fn file_size(path: ptr) -> i64",description:"Returns file length in bytes, or -1 if file cannot be statted.",example:'let bytes = file_size("kernel.bin");',errorModel:"Sentinel (-1)"},{name:"file_copy",signature:"fn file_copy(src: ptr, dst: ptr) -> i32",description:"Copies file from source path to destination path. Returns 0 on success.",example:'let res = file_copy("src.trk", "bak.trk");',errorModel:"Status Code"},{name:"file_remove",signature:"fn file_remove(path: ptr) -> i32",description:"Deletes a file from the filesystem. Returns 0 on success, -1 on failure.",example:'file_remove("temp.lock");',errorModel:"Status Code"}]},{name:"std/net",category:"Networking",description:"High-performance POSIX TCP server, client connection, and raw packet transfer.",functions:[{name:"net_socket_tcp_listen",signature:"fn net_socket_tcp_listen(port: i32) -> i32",description:"Binds and listens on local TCP port. Returns server socket file descriptor or -1.",example:"let server_fd = net_socket_tcp_listen(8080);",errorModel:"Sentinel (-1)"},{name:"net_socket_connect",signature:"fn net_socket_connect(host: ptr, port: i32) -> i32",description:"Establishes a client TCP connection to target host and port.",example:'let client_fd = net_socket_connect("127.0.0.1", 8080);',errorModel:"Sentinel (-1)"},{name:"net_socket_accept",signature:"fn net_socket_accept(server_fd: i32) -> i32",description:"Accepts incoming client connection. Returns connected peer socket descriptor.",example:"let peer_fd = net_socket_accept(server_fd);",errorModel:"Sentinel (-1)"},{name:"net_socket_send",signature:"fn net_socket_send(fd: i32, buf: ptr, len: i64) -> i64",description:"Transmits raw bytes over active socket. Returns bytes sent.",example:"let sent = net_socket_send(peer_fd, buf, 1024);",errorModel:"Sentinel (-1)"},{name:"net_socket_recv",signature:"fn net_socket_recv(fd: i32, buf: ptr, max_len: i64) -> i64",description:"Receives raw bytes from socket into target buffer.",example:"let read_bytes = net_socket_recv(peer_fd, buf, 4096);",errorModel:"Sentinel (-1)"},{name:"net_socket_close",signature:"fn net_socket_close(fd: i32) -> void",description:"Closes and disposes active network socket descriptor.",example:"net_socket_close(client_fd);",errorModel:"None"}]},{name:"std/str",category:"String & Memory",description:"Heap string allocation, substring search, splitting, trim, and conversion primitives.",functions:[{name:"str_from_literal",signature:"fn str_from_literal(raw: ptr) -> Str",description:"Constructs an owned Str structure from a null-terminated string literal.",example:'let s = str_from_literal("track");',errorModel:"None"},{name:"str_len",signature:"fn str_len(s: &Str) -> u32",description:"Calculates the byte length of a string reference in O(1).",example:"let length = str_len(&s);",errorModel:"None"},{name:"str_eq",signature:"fn str_eq(a: &Str, b: &Str) -> bool",description:"Tests if two strings have equal length and identical byte content.",example:"let same = str_eq(&a, &b);",errorModel:"None"},{name:"str_concat",signature:"fn str_concat(a: &Str, b: &Str) -> Str",description:"Allocates a new buffer containing the concatenated content of both strings.",example:"let joined = str_concat(&first, &last);",errorModel:"None"},{name:"str_find",signature:"fn str_find(s: Str, needle: Str) -> i32",description:"Finds index of needle in string, or returns -1 if not found.",example:'let idx = str_find("hello world", "world"); // 6',errorModel:"Sentinel (-1)"},{name:"str_is_int",signature:"fn str_is_int(s: Str) -> bool",description:"Boolean predicate verifying that string contains valid numeric digits.",example:"if (str_is_int(token)) { let n = str_to_int(token); }",errorModel:"Boolean Predicate"},{name:"str_to_int",signature:"fn str_to_int(s: Str) -> i64",description:"Parses string to signed integer. Pair with str_is_int.",example:'let val = str_to_int("1337");',errorModel:"None"},{name:"str_substr",signature:"fn str_substr(s: Str, start: u32, len: u32) -> Str",description:"Extracts a new owned substring slice.",example:"let sub = str_substr(raw, 0, 4);",errorModel:"None"},{name:"str_trim",signature:"fn str_trim(s: Str) -> Str",description:"Returns a trimmed string with leading and trailing whitespace removed.",example:"let clean = str_trim(dirty_input);",errorModel:"None"}]},{name:"std/os & std/process",category:"System & Process",description:"Process spawning, environment variable queries, and memory ceiling limits.",functions:[{name:"os_args_count",signature:"fn os_args_count() -> i32",description:"Returns total count of command-line arguments (argc).",example:"let count = os_args_count();",errorModel:"None"},{name:"os_arg",signature:"fn os_arg(index: i32) -> Str",description:"Fetches command-line argument by zero-based index (argv[i]).",example:"let target_file = os_arg(1);",errorModel:"None"},{name:"env_exists",signature:"fn env_exists(key: ptr) -> bool",description:"Tests if an environment variable is present in the current process.",example:'if (env_exists("TRACK_DEBUG")) { /* ... */ }',errorModel:"Boolean Predicate"},{name:"env_get",signature:"fn env_get(key: ptr) -> Str",description:"Reads value of environment variable. Pair with env_exists.",example:'let path = env_get("PATH");',errorModel:"None"},{name:"process_spawn",signature:"fn process_spawn(command: ptr) -> i32",description:"Spawns a child process and waits for termination. Returns process exit code.",example:'let status = process_spawn("cc -O2 -c out.c -o out.o");',errorModel:"Status Code"},{name:"sys_set_memory_limit",signature:"fn sys_set_memory_limit(bytes: u64) -> void",description:"Enforces a strict virtual memory ceiling on the active process.",example:"sys_set_memory_limit(128 * 1024 * 1024); // 128MB max",errorModel:"None"},{name:"sys_get_memory_used",signature:"fn sys_get_memory_used() -> u64",description:"Returns current resident set size (RSS) memory consumption in bytes.",example:"let bytes_used = sys_get_memory_used();",errorModel:"None"},{name:"abort",signature:"fn abort(msg: ptr) -> void",description:"Prints fatal message to stderr and immediately terminates process with code 134.",example:'abort("unrecoverable heap corruption");',errorModel:"Fatal Abort"}]},{name:"mem/alloc",category:"Memory Primitives",description:"Low-level manual memory allocators, zeroing, and block reallocation.",functions:[{name:"alloc",signature:"fn alloc(bytes: u64) -> ptr",description:"Allocates raw uninitialized memory block. Freed automatically when spent.",example:"let buf: ptr = alloc(4096);",errorModel:"None"},{name:"mem_realloc",signature:"fn mem_realloc(p: ptr, new_size: u64) -> ptr",description:"Resizes an existing memory block.",example:"let expanded = mem_realloc(buf, 8192);",errorModel:"None"},{name:"memset",signature:"fn memset(dest: ptr, val: i32, count: u64) -> void",description:"Fills target memory block with specified byte value.",example:"memset(buf, 0, 1024);",errorModel:"None"},{name:"memcpy",signature:"fn memcpy(dest: ptr, src: ptr, count: u64) -> void",description:"Copies count bytes from source memory buffer to destination.",example:"memcpy(dst, src, 1024);",errorModel:"None"},{name:"memcmp",signature:"fn memcmp(a: ptr, b: ptr, count: u64) -> i32",description:"Compares two memory buffers. Returns 0 if identical.",example:"let matches = (memcmp(a, b, len) == 0);",errorModel:"None"}]}],Kg=()=>{const[r,h]=fe.useState("all"),[y,o]=fe.useState(""),N=Ru.flatMap(z=>z.functions.map(O=>({...O,moduleName:z.name,moduleCategory:z.category}))),_=N.filter(z=>{const O=r==="all"||z.moduleName===r,A=z.name.toLowerCase().includes(y.toLowerCase())||z.signature.toLowerCase().includes(y.toLowerCase())||z.description.toLowerCase().includes(y.toLowerCase())||z.moduleName.toLowerCase().includes(y.toLowerCase());return O&&A});return s.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-8 sm:px-6",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4 mb-6",children:[s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:"Standard Library Reference"}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1",children:"Zero-overhead C runtime wrappers, memory allocators, POSIX file I/O, and TCP sockets."})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-8 items-start",children:[s.jsxs("aside",{className:"md:col-span-4 lg:col-span-3 space-y-4 md:sticky md:top-20",children:[s.jsxs("div",{className:"relative",children:[s.jsx(uc,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-zinc-500"}),s.jsx("input",{type:"text",value:y,onChange:z=>o(z.target.value),placeholder:"Filter functions...",className:"w-full rounded border border-zinc-800 bg-[#0d0e12] py-1.5 pl-8 pr-3 text-xs font-mono text-zinc-200 placeholder-zinc-500 focus:border-amber-500 focus:outline-none"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"font-mono text-[11px] font-bold uppercase tracking-wider text-zinc-500 px-2 py-1",children:"Modules"}),s.jsxs("div",{className:"space-y-0.5 border-l border-zinc-800 ml-2 pl-2",children:[s.jsxs("button",{onClick:()=>h("all"),className:tt("block w-full text-left py-1 px-2 text-xs font-mono rounded transition-colors",r==="all"?"text-amber-400 font-semibold bg-zinc-900":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:["All (",N.length,")"]}),Ru.map(z=>s.jsx("button",{onClick:()=>h(z.name),className:tt("block w-full text-left py-1 px-2 text-xs font-mono rounded transition-colors",r===z.name?"text-amber-400 font-semibold bg-zinc-900":"text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/50"),children:z.name},z.name))]})]})]}),s.jsx("main",{className:"md:col-span-8 lg:col-span-9 space-y-6",children:_.length===0?s.jsx("div",{className:"py-12 text-center text-zinc-500 font-mono text-xs",children:"No matching functions found."}):_.map((z,O)=>s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2.5 text-left",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-zinc-800/60 pb-2",children:[s.jsx("span",{className:"font-mono text-xs font-bold text-zinc-200",children:z.name}),s.jsx("span",{className:"font-mono text-[11px] text-zinc-500",children:z.moduleName})]}),s.jsx("div",{className:"font-mono text-xs text-amber-400 bg-zinc-900/90 p-2 rounded overflow-x-auto select-all",children:z.signature}),s.jsx("p",{className:"text-xs text-zinc-300 font-sans leading-relaxed",children:z.description}),s.jsxs("div",{className:"pt-1",children:[s.jsx("div",{className:"text-[10px] font-mono text-zinc-500 mb-1",children:"Example:"}),s.jsx("pre",{className:"font-mono text-[11px] text-zinc-400 bg-[#08080a] p-2 rounded border border-zinc-900 overflow-x-auto whitespace-pre",children:z.example})]})]},O))})]})]})},Jg=({initialCode:r})=>{const[h,y]=fe.useState(r||aa[1].code),[o,N]=fe.useState("linear-auto-free"),[_,z]=fe.useState("cranelift"),[O,A]=fe.useState("release"),[g,L]=fe.useState("x86_64"),[w,I]=fe.useState("output"),[V,M]=fe.useState(!1),[D,ie]=fe.useState(!1),[ye,ce]=fe.useState("");fe.useEffect(()=>{const W=ke=>{(ke.metaKey||ke.ctrlKey)&&ke.key==="Enter"&&(ke.preventDefault(),Ne())};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[h,_,O]);const Ne=()=>{M(!0),setTimeout(()=>{M(!1),h.includes("Hello")?ce(`Hello, Track! Program exited with code 0.`):h.includes("make_buffer")||h.includes("consume_buffer")||h.includes("linear")?ce(`Buffer consumed. Automatically freed at exit. @@ -630,8 +592,8 @@ Program exited with code 0.`):h.includes("Packet::Data")?ce(`Verified data packe Program exited with code 0.`):ce(`Finished execution in 0.42ms. -Program exited with code 0.`)},180)},De=W=>{S(W);const ke=aa.find(Qe=>Qe.id===W);ke&&(y(ke.code),ce(""))},Ye=()=>{navigator.clipboard.writeText(h),ie(!0),setTimeout(()=>ie(!1),2e3)},Ee=W=>{if(W.key==="Tab"){W.preventDefault();const ke=W.target,Qe=ke.selectionStart,Re=ke.selectionEnd,ft=ke.value;y(ft.substring(0,Qe)+" "+ft.substring(Re)),setTimeout(()=>{ke.selectionStart=ke.selectionEnd=Qe+4},0)}},P=h.split(` -`).length,B=Array.from({length:Math.max(P,18)},(W,ke)=>ke+1);return s.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-6 sm:px-6 space-y-4 text-left",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-zinc-800 pb-3 font-mono text-xs",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("button",{onClick:Ne,disabled:V,className:"flex items-center gap-1.5 rounded bg-amber-500 hover:bg-amber-400 text-zinc-950 font-bold px-3 py-1.5 transition-colors disabled:opacity-50",title:"Run code (⌘+Enter)",children:[s.jsx(mm,{className:"h-3.5 w-3.5 fill-current"}),s.jsx("span",{children:V?"Compiling...":"Run"})]}),s.jsxs("button",{onClick:Ne,className:"flex items-center gap-1.5 rounded border border-zinc-800 bg-zinc-900 hover:bg-zinc-800 text-zinc-300 px-3 py-1.5 transition-colors",title:"Typecheck without building",children:[s.jsx(fm,{className:"h-3.5 w-3.5 text-zinc-400"}),s.jsx("span",{children:"Check"})]}),s.jsxs("div",{className:"flex items-center gap-1 pl-2 border-l border-zinc-800",children:[s.jsx("span",{className:"text-zinc-500 text-[11px]",children:"Example:"}),s.jsx("select",{value:r,onChange:W=>De(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-300 font-mono text-xs focus:outline-none focus:border-zinc-700",children:aa.map(W=>s.jsx("option",{value:W.id,children:W.title},W.id))})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("select",{value:g,onChange:W=>L(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-400 font-mono text-xs focus:outline-none",children:[s.jsx("option",{value:"x86_64",children:"x86_64"}),s.jsx("option",{value:"aarch64",children:"aarch64"})]}),s.jsxs("select",{value:N,onChange:W=>_(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-400 font-mono text-xs focus:outline-none",children:[s.jsx("option",{value:"cranelift",children:"Backend: Cranelift"}),s.jsx("option",{value:"c_emitter",children:"Backend: C Emitter (Stage 1)"})]}),s.jsxs("select",{value:O,onChange:W=>j(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-400 font-mono text-xs focus:outline-none",children:[s.jsx("option",{value:"release",children:"Release (-O3)"}),s.jsx("option",{value:"debug",children:"Debug"})]}),s.jsxs("button",{onClick:Ye,className:"flex items-center gap-1 rounded border border-zinc-800 bg-zinc-900 hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 px-2 py-1 transition-colors",title:"Copy code",children:[D?s.jsx(Bu,{className:"h-3 w-3 text-emerald-400"}):s.jsx(Lu,{className:"h-3 w-3"}),s.jsx("span",{children:D?"Copied":"Copy"})]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0c0d11] overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800/80 bg-zinc-900/80 px-4 py-1.5 text-xs font-mono text-zinc-400",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(dm,{className:"h-3.5 w-3.5 text-zinc-400"}),s.jsx("span",{children:"src/main.trk"})]}),s.jsx("div",{className:"text-[11px] text-zinc-500",children:"Track v0.7.0 • Tab indents with 4 spaces • ⌘+Enter to Run"})]}),s.jsxs("div",{className:"flex min-h-[380px] text-xs font-mono",children:[s.jsx("div",{className:"select-none py-3 px-3 text-right text-zinc-600 bg-zinc-950/60 border-r border-zinc-800/60 w-10 shrink-0 font-mono text-xs leading-5",children:B.map(W=>s.jsx("div",{children:W},W))}),s.jsx("textarea",{value:h,onChange:W=>y(W.target.value),onKeyDown:Ee,rows:Math.max(P+2,18),className:"flex-1 bg-transparent text-zinc-200 p-3 leading-5 resize-none focus:outline-none font-mono text-xs selection:bg-amber-500/20 selection:text-amber-300",spellCheck:!1})]})]}),s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0a0a0d] overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800 bg-zinc-900/60 px-3 py-1 text-xs font-mono",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{onClick:()=>I("output"),className:tt("px-2.5 py-1 rounded transition-colors",w==="output"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Standard Output"}),s.jsx("button",{onClick:()=>I("clif"),className:tt("px-2.5 py-1 rounded transition-colors",w==="clif"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Cranelift IR"}),s.jsx("button",{onClick:()=>I("tokens"),className:tt("px-2.5 py-1 rounded transition-colors",w==="tokens"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Tokens (v0.7 Lexer)"}),s.jsx("button",{onClick:()=>I("diagnostics"),className:tt("px-2.5 py-1 rounded transition-colors",w==="diagnostics"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Diagnostics Span"})]}),s.jsxs("div",{className:"text-[11px] text-zinc-500 flex items-center gap-2",children:[s.jsx("span",{children:"Exit Code: 0"}),s.jsx("span",{children:"•"}),s.jsx("span",{children:"Memory: 1.2 MB"})]})]}),s.jsxs("div",{className:"p-4 font-mono text-xs min-h-[160px] max-h-[260px] overflow-y-auto leading-relaxed text-left",children:[w==="output"&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"text-zinc-500",children:["$ track build --target=",g," --backend=",N," src/main.trk"]}),s.jsxs("div",{className:"text-emerald-400",children:["Compiling 1 package (main) via ",N==="cranelift"?"Cranelift JIT/AOT":"Portable C emitter","..."]}),s.jsx("div",{className:"text-zinc-400",children:"Running target/main:"}),s.jsx("div",{className:"text-zinc-100 font-semibold whitespace-pre pt-1",children:ye||"Click 'Run' or press ⌘+Enter to execute program."})]}),w==="clif"&&s.jsx("pre",{className:"text-zinc-300 text-xs overflow-x-auto whitespace-pre",children:`function u0:0(i64) -> i64 fast { +Program exited with code 0.`)},180)},De=W=>{N(W);const ke=aa.find(Qe=>Qe.id===W);ke&&(y(ke.code),ce(""))},Ye=()=>{navigator.clipboard.writeText(h),ie(!0),setTimeout(()=>ie(!1),2e3)},Ee=W=>{if(W.key==="Tab"){W.preventDefault();const ke=W.target,Qe=ke.selectionStart,Re=ke.selectionEnd,ft=ke.value;y(ft.substring(0,Qe)+" "+ft.substring(Re)),setTimeout(()=>{ke.selectionStart=ke.selectionEnd=Qe+4},0)}},P=h.split(` +`).length,B=Array.from({length:Math.max(P,18)},(W,ke)=>ke+1);return s.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-6 sm:px-6 space-y-4 text-left",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-zinc-800 pb-3 font-mono text-xs",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("button",{onClick:Ne,disabled:V,className:"flex items-center gap-1.5 rounded bg-amber-500 hover:bg-amber-400 text-zinc-950 font-bold px-3 py-1.5 transition-colors disabled:opacity-50",title:"Run code (⌘+Enter)",children:[s.jsx(mm,{className:"h-3.5 w-3.5 fill-current"}),s.jsx("span",{children:V?"Compiling...":"Run"})]}),s.jsxs("button",{onClick:Ne,className:"flex items-center gap-1.5 rounded border border-zinc-800 bg-zinc-900 hover:bg-zinc-800 text-zinc-300 px-3 py-1.5 transition-colors",title:"Typecheck without building",children:[s.jsx(fm,{className:"h-3.5 w-3.5 text-zinc-400"}),s.jsx("span",{children:"Check"})]}),s.jsxs("div",{className:"flex items-center gap-1 pl-2 border-l border-zinc-800",children:[s.jsx("span",{className:"text-zinc-500 text-[11px]",children:"Example:"}),s.jsx("select",{value:o,onChange:W=>De(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-300 font-mono text-xs focus:outline-none focus:border-zinc-700",children:aa.map(W=>s.jsx("option",{value:W.id,children:W.title},W.id))})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("select",{value:g,onChange:W=>L(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-400 font-mono text-xs focus:outline-none",children:[s.jsx("option",{value:"x86_64",children:"x86_64"}),s.jsx("option",{value:"aarch64",children:"aarch64"})]}),s.jsxs("select",{value:_,onChange:W=>z(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-400 font-mono text-xs focus:outline-none",children:[s.jsx("option",{value:"cranelift",children:"Backend: Cranelift"}),s.jsx("option",{value:"c_emitter",children:"Backend: C Emitter (Stage 1)"})]}),s.jsxs("select",{value:O,onChange:W=>A(W.target.value),className:"bg-zinc-900 border border-zinc-800 rounded px-2 py-1 text-zinc-400 font-mono text-xs focus:outline-none",children:[s.jsx("option",{value:"release",children:"Release (-O3)"}),s.jsx("option",{value:"debug",children:"Debug"})]}),s.jsxs("button",{onClick:Ye,className:"flex items-center gap-1 rounded border border-zinc-800 bg-zinc-900 hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 px-2 py-1 transition-colors",title:"Copy code",children:[D?s.jsx(Bu,{className:"h-3 w-3 text-emerald-400"}):s.jsx(Lu,{className:"h-3 w-3"}),s.jsx("span",{children:D?"Copied":"Copy"})]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0c0d11] overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800/80 bg-zinc-900/80 px-4 py-1.5 text-xs font-mono text-zinc-400",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(dm,{className:"h-3.5 w-3.5 text-zinc-400"}),s.jsx("span",{children:"src/main.trk"})]}),s.jsx("div",{className:"text-[11px] text-zinc-500",children:"Track v1.0.0 • Tab indents with 4 spaces • ⌘+Enter to Run"})]}),s.jsxs("div",{className:"flex min-h-[380px] text-xs font-mono",children:[s.jsx("div",{className:"select-none py-3 px-3 text-right text-zinc-600 bg-zinc-950/60 border-r border-zinc-800/60 w-10 shrink-0 font-mono text-xs leading-5",children:B.map(W=>s.jsx("div",{children:W},W))}),s.jsx("textarea",{value:h,onChange:W=>y(W.target.value),onKeyDown:Ee,rows:Math.max(P+2,18),className:"flex-1 bg-transparent text-zinc-200 p-3 leading-5 resize-none focus:outline-none font-mono text-xs selection:bg-amber-500/20 selection:text-amber-300",spellCheck:!1})]})]}),s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0a0a0d] overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-800 bg-zinc-900/60 px-3 py-1 text-xs font-mono",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{onClick:()=>I("output"),className:tt("px-2.5 py-1 rounded transition-colors",w==="output"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Standard Output"}),s.jsx("button",{onClick:()=>I("clif"),className:tt("px-2.5 py-1 rounded transition-colors",w==="clif"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Cranelift IR"}),s.jsx("button",{onClick:()=>I("tokens"),className:tt("px-2.5 py-1 rounded transition-colors",w==="tokens"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Tokens (v0.7 Lexer)"}),s.jsx("button",{onClick:()=>I("diagnostics"),className:tt("px-2.5 py-1 rounded transition-colors",w==="diagnostics"?"text-amber-400 bg-zinc-800 font-semibold":"text-zinc-400 hover:text-zinc-200"),children:"Diagnostics Span"})]}),s.jsxs("div",{className:"text-[11px] text-zinc-500 flex items-center gap-2",children:[s.jsx("span",{children:"Exit Code: 0"}),s.jsx("span",{children:"•"}),s.jsx("span",{children:"Memory: 1.2 MB"})]})]}),s.jsxs("div",{className:"p-4 font-mono text-xs min-h-[160px] max-h-[260px] overflow-y-auto leading-relaxed text-left",children:[w==="output"&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"text-zinc-500",children:["$ track build --target=",g," --backend=",_," src/main.trk"]}),s.jsxs("div",{className:"text-emerald-400",children:["Compiling 1 package (main) via ",_==="cranelift"?"Cranelift JIT/AOT":"Portable C emitter","..."]}),s.jsx("div",{className:"text-zinc-400",children:"Running target/main:"}),s.jsx("div",{className:"text-zinc-100 font-semibold whitespace-pre pt-1",children:ye||"Click 'Run' or press ⌘+Enter to execute program."})]}),w==="clif"&&s.jsx("pre",{className:"text-zinc-300 text-xs overflow-x-auto whitespace-pre",children:`function u0:0(i64) -> i64 fast { gv0 = vmctx stack_limit = gv0 @@ -874,8 +836,8 @@ src = "src" - **Zero-Config Defaults**: Running \`yard build\` in any package automatically resolves dependencies, discovers all \`.trk\` modules, builds in parallel, and links an executable into \`target/\`. - **Integrated Test Discovery (\`yard test\`)**: Automatically compiles unit test files (\`src/*_test.trk\`) and integration tests (\`tests/**/*.trk\`) as isolated temporary packages, executing them in parallel. - **Fast Fast-Checking (\`yard check\` & \`yard lint\`)**: Tokenizes, parses, and runs the linear checker in milliseconds without touching native backend codegen. - `}],Wg=({onSelectTab:o,onOpenPlaygroundWithCode:h,initialPostId:y})=>{const[r,S]=fe.useState(y||null),N=Uu.find(_=>_.id===r||_.slug===r);return N?s.jsxs("div",{className:"mx-auto max-w-3xl px-4 py-8 sm:px-6 space-y-8 text-left",children:[s.jsxs("button",{onClick:()=>{S(null),window.scrollTo({top:0,behavior:"smooth"})},className:"flex items-center gap-1.5 font-mono text-xs text-zinc-400 hover:text-amber-400 transition-colors",children:[s.jsx(rm,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Back to Articles"})]}),s.jsxs("header",{className:"space-y-2 border-b border-zinc-800 pb-4",children:[s.jsxs("div",{className:"text-xs font-mono text-zinc-500",children:[N.date," • ",N.readTime," • By ",N.author.name]}),s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100 leading-tight",children:N.title})]}),s.jsx("article",{className:"space-y-6 text-sm text-zinc-300 font-sans leading-relaxed",children:N.content.split(` + `}],Wg=({onSelectTab:r,onOpenPlaygroundWithCode:h,initialPostId:y})=>{const[o,N]=fe.useState(y||null),_=Uu.find(z=>z.id===o||z.slug===o);return _?s.jsxs("div",{className:"mx-auto max-w-3xl px-4 py-8 sm:px-6 space-y-8 text-left",children:[s.jsxs("button",{onClick:()=>{N(null),window.scrollTo({top:0,behavior:"smooth"})},className:"flex items-center gap-1.5 font-mono text-xs text-zinc-400 hover:text-amber-400 transition-colors",children:[s.jsx(om,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Back to Articles"})]}),s.jsxs("header",{className:"space-y-2 border-b border-zinc-800 pb-4",children:[s.jsxs("div",{className:"text-xs font-mono text-zinc-500",children:[_.date," • ",_.readTime," • By ",_.author.name]}),s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100 leading-tight",children:_.title})]}),s.jsx("article",{className:"space-y-6 text-sm text-zinc-300 font-sans leading-relaxed",children:_.content.split(` -`).map((_,O)=>{const j=_.trim();if(!j)return null;if(j.startsWith("### "))return s.jsx("h3",{className:"text-base font-bold font-sans text-zinc-100 mt-6 mb-2",children:j.replace("### ","")},O);if(j.startsWith("> "))return s.jsx("blockquote",{className:"border-l-2 border-amber-500/80 pl-4 my-4 font-mono text-xs text-zinc-300 italic",children:j.replace("> ","").replace(/\*/g,"")},O);if(j.startsWith("```")){const g=j.split(` +`).map((z,O)=>{const A=z.trim();if(!A)return null;if(A.startsWith("### "))return s.jsx("h3",{className:"text-base font-bold font-sans text-zinc-100 mt-6 mb-2",children:A.replace("### ","")},O);if(A.startsWith("> "))return s.jsx("blockquote",{className:"border-l-2 border-amber-500/80 pl-4 my-4 font-mono text-xs text-zinc-300 italic",children:A.replace("> ","").replace(/\*/g,"")},O);if(A.startsWith("```")){const g=A.split(` `),L=g[0].replace("```",""),w=g.slice(1,-1).join(` -`);return s.jsx(cc,{code:w,language:L||"track",onRun:()=>{h?h(w):o("playground")}},O)}return s.jsx("p",{className:"text-zinc-300 leading-relaxed",children:j},O)})})]}):s.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8 sm:px-6 space-y-8 text-left",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4",children:[s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:"Engineering & Systems Journal"}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1",children:"Technical deep dives on compiler architecture, type theory, Cranelift code generation, and memory models."})]}),s.jsx("div",{className:"divide-y divide-zinc-800/60",children:Uu.map(_=>s.jsxs("div",{onClick:()=>{S(_.id),window.scrollTo({top:0,behavior:"smooth"})},className:"py-6 group cursor-pointer space-y-2 hover:bg-zinc-900/20 -mx-4 px-4 rounded transition-colors",children:[s.jsxs("div",{className:"text-xs font-mono text-zinc-500 flex items-center gap-2",children:[s.jsx("span",{children:_.date}),s.jsx("span",{children:"•"}),s.jsx("span",{children:_.readTime})]}),s.jsx("h2",{className:"text-lg font-bold font-sans text-zinc-100 group-hover:text-amber-400 transition-colors",children:_.title}),s.jsx("p",{className:"text-xs text-zinc-400 font-sans line-clamp-2 leading-relaxed",children:_.summary}),s.jsx("div",{className:"pt-1",children:s.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-mono text-amber-500 group-hover:text-amber-400",children:[s.jsx("span",{children:"Read paper"}),s.jsx(sc,{className:"h-3 w-3"})]})})]},_.id))})]})},$g=[{version:"v0.1.6",title:"Slices, Strings & Memory Primitives",status:"completed",date:"June 2026",description:"First-class slices ([]T), owned heap string type (Str), POSIX TCP socket library, and standalone yard CLI.",highlights:["First-class slices []T with .len()","Owned Str type with auto deallocation","POSIX socket networking (std/net)","Initial Yard build tool"]},{version:"v0.2.0",title:"UFCS, Lexical Lenses & CFG Merging",status:"completed",date:"June 2026",description:"Lexical lens blocks (with ->), CFG state merging for if/else and loops, and Uniform Function Call Syntax.",highlights:["Lexical lenses (with u -> user)","CFG branch state merging","Primitive copy inference","Pointer arithmetic & & borrows"]},{version:"v0.3.0",title:"Performance & Self-Hosting Readiness",status:"completed",date:"July 2026",description:"Shared Arc across parallel worker threads, eliminated per-file ISA re-initialization, and LSP caching.",highlights:["Multi-threaded Cranelift backend","track-lsp released with AST caching","yard lint & yard clean commands","Extended std/fs, std/os, std/process"]},{version:"v0.4.0",title:"Advanced Pattern Matching & Anonymous Tuples",status:"completed",date:"July 2026",description:"First-class anonymous tuples (T1, T2), tuple destructuring let (a, b) = expr, nested patterns, and match arm guards.",highlights:["Anonymous tuple types (i64, Str, bool)","Tuple destructuring syntax","Nested variant pattern matching","Pattern guards (match x { n if n > 10 => ... })"]},{version:"v0.5.0",title:"Explicit Stack-Based Error Handling",status:"completed",date:"August 2026",description:"Formalized the official zero-wrapper error philosophy: no Option/Result, status codes, tuple returns, out-params, and abort(msg).",highlights:["No Result/Option or ? operator","(T, i32) multi-value return conventions","abort(msg) fatal exit primitive","Predicate companions (str_is_int, env_exists)"]},{version:"v0.6.0",title:"Monomorphized Generics",status:"completed",date:"August 2026",description:"Generic function templates (fn name), type parameter inference at call sites, and specialization pass in src/mono.rs.",highlights:["Generic functions with compile-time monomorphization","Zero vtable / zero dynamic dispatch overhead","Recursive nested generic call resolution","docs/generics.md guide"]},{version:"v0.7.0",title:"Self-Hosted Track Lexer & Yard Test Engine",status:"completed",date:"August 2026",description:"100% native tokenizer written in Track (compiler/src/lexer.trk) with 50+ union variants and native yard test orchestrator.",highlights:["Ported logos lexer into 100% native Track","compiler/ is an isolated Yard package","yard test discovers & runs src/*_test.trk","Copy variant constructors fix in linear checker"]},{version:"v0.8.0",title:"Self-Hosted Parser, Linear Checker & C-Emitter",status:"in-progress",date:"Late 2026",description:"Native Track parser (compiler/parser.trk), native linear ownership checker, and portable C backend emitter.",highlights:["Native recursive descent parser in Track","Self-hosted linear ownership checker","Portable C code emitter","Compiler span error diagnostics"]},{version:"v0.9.0",title:"Full 3-Stage Compiler Self-Bootstrapping",status:"milestone",date:"Milestone Gate",description:"Verification of 3-stage bootstrapping: Stage 0 (Rust) -> Stage 1 (Track C) -> Stage 2 (Track) -> Byte-for-byte identity gate.",highlights:["Stage 0 builds Stage 1 compiler","Stage 1 compiles Stage 2 compiler","Stage 2 compiles Stage 3 compiler","cmp track_stage2 track_stage3 byte verification"]}],Fg=()=>s.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8 sm:px-6 space-y-8 text-left",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4",children:[s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:"Compiler Self-Bootstrapping Roadmap"}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1",children:"Path from early memory primitives to verified 3-stage self-compilation in v0.9.0."})]}),s.jsx("div",{className:"space-y-4",children:$g.map((o,h)=>{const y=o.status==="completed",r=o.status==="in-progress";return s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2 text-left",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-zinc-800/60 pb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono text-xs font-bold text-amber-400",children:o.version}),s.jsx("span",{className:"font-mono text-xs text-zinc-300 font-medium",children:o.title})]}),s.jsx("div",{className:"flex items-center gap-1.5 font-mono text-[11px]",children:y?s.jsxs("span",{className:"text-emerald-400 flex items-center gap-1",children:[s.jsx(xh,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Completed"})]}):r?s.jsxs("span",{className:"text-amber-400 flex items-center gap-1",children:[s.jsx(zh,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"In Progress"})]}):s.jsxs("span",{className:"text-purple-400 flex items-center gap-1",children:[s.jsx(Qh,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Milestone Target"})]})})]}),s.jsx("p",{className:"text-xs text-zinc-300 font-sans leading-relaxed",children:o.description}),s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1.5 pt-1 font-mono text-[11px] text-zinc-400",children:o.highlights.map((S,N)=>s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-zinc-600",children:"•"}),s.jsx("span",{children:S})]},N))})]},h)})})]});function Ig(){const[o,h]=fe.useState("home"),[y,r]=fe.useState(!1),[S,N]=fe.useState(void 0),[_,O]=fe.useState("intro"),[j,g]=fe.useState(void 0),L=[...ul.map(M=>({id:`doc-${M.id}`,title:M.title,category:"docs",section:M.category,snippet:M.subtitle,path:`docs#${M.id}`})),...Ru.flatMap(M=>M.functions.map(D=>({id:`stdlib-${M.name}-${D.name}`,title:D.name,category:"stdlib",section:M.name,snippet:`${D.signature} — ${D.description}`,path:`stdlib#${D.name}`}))),...Uu.map(M=>({id:`blog-${M.id}`,title:M.title,category:"blog",section:M.author.name,snippet:M.summary,path:`blog#${M.id}`})),...aa.map(M=>({id:`example-${M.id}`,title:M.title,category:"example",section:M.category,snippet:M.description,path:`examples#${M.id}`}))],w=M=>{h(M),window.scrollTo({top:0,behavior:"smooth"})},I=M=>{N(M),h("playground"),window.scrollTo({top:0,behavior:"smooth"})},V=M=>{if(M.category==="docs"){const D=M.id.replace("doc-","");O(D),h("docs")}else if(M.category==="stdlib")h("stdlib");else if(M.category==="blog"){const D=M.id.replace("blog-","");g(D),h("blog")}else M.category==="example"&&h("docs");window.scrollTo({top:0,behavior:"smooth"})};return s.jsxs("div",{className:"min-h-screen bg-[#090a0d] text-zinc-200 flex flex-col font-sans selection:bg-amber-500/20 selection:text-amber-300",children:[s.jsx(qg,{activeTab:o,onSelectTab:w,onOpenSearch:()=>r(!0)}),s.jsxs("main",{className:"flex-1",children:[o==="home"&&s.jsx(Qg,{onSelectTab:w,onOpenPlaygroundWithCode:I}),o==="docs"&&s.jsx(Vg,{onSelectTab:w,onOpenPlaygroundWithCode:I,initialChapterId:_}),o==="stdlib"&&s.jsx(Kg,{onSelectTab:w,onOpenPlaygroundWithCode:I}),o==="playground"&&s.jsx(Jg,{initialCode:S}),o==="blog"&&s.jsx(Wg,{onSelectTab:w,onOpenPlaygroundWithCode:I,initialPostId:j}),o==="roadmap"&&s.jsx(Fg,{onSelectTab:w})]}),s.jsx(Yg,{isOpen:y,onClose:()=>r(!1),onSelect:V,searchItems:L}),s.jsx(Gg,{onSelectTab:w})]})}fh.createRoot(document.getElementById("root")).render(s.jsx(ah.StrictMode,{children:s.jsx(Ig,{})})); +`);return s.jsx(cc,{code:w,language:L||"track",onRun:()=>{h?h(w):r("playground")}},O)}return s.jsx("p",{className:"text-zinc-300 leading-relaxed",children:A},O)})})]}):s.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8 sm:px-6 space-y-8 text-left",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4",children:[s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:"Engineering & Systems Journal"}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1",children:"Technical deep dives on compiler architecture, type theory, Cranelift code generation, and memory models."})]}),s.jsx("div",{className:"divide-y divide-zinc-800/60",children:Uu.map(z=>s.jsxs("div",{onClick:()=>{N(z.id),window.scrollTo({top:0,behavior:"smooth"})},className:"py-6 group cursor-pointer space-y-2 hover:bg-zinc-900/20 -mx-4 px-4 rounded transition-colors",children:[s.jsxs("div",{className:"text-xs font-mono text-zinc-500 flex items-center gap-2",children:[s.jsx("span",{children:z.date}),s.jsx("span",{children:"•"}),s.jsx("span",{children:z.readTime})]}),s.jsx("h2",{className:"text-lg font-bold font-sans text-zinc-100 group-hover:text-amber-400 transition-colors",children:z.title}),s.jsx("p",{className:"text-xs text-zinc-400 font-sans line-clamp-2 leading-relaxed",children:z.summary}),s.jsx("div",{className:"pt-1",children:s.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-mono text-amber-500 group-hover:text-amber-400",children:[s.jsx("span",{children:"Read paper"}),s.jsx(sc,{className:"h-3 w-3"})]})})]},z.id))})]})},$g=[{version:"v0.1.6",title:"Slices, Strings & Memory Primitives",status:"completed",date:"June 2026",description:"First-class slices ([]T), owned heap string type (Str), POSIX TCP socket library, and standalone yard CLI.",highlights:["First-class slices []T with .len()","Owned Str type with auto deallocation","POSIX socket networking (std/net)","Initial Yard build tool"]},{version:"v0.2.0",title:"UFCS, Lexical Lenses & CFG Merging",status:"completed",date:"June 2026",description:"Lexical lens blocks (with ->), CFG state merging for if/else and loops, and Uniform Function Call Syntax.",highlights:["Lexical lenses (with u -> user)","CFG branch state merging","Primitive copy inference","Pointer arithmetic & & borrows"]},{version:"v0.3.0",title:"Performance & Self-Hosting Readiness",status:"completed",date:"July 2026",description:"Shared Arc across parallel worker threads, eliminated per-file ISA re-initialization, and LSP caching.",highlights:["Multi-threaded Cranelift backend","track-lsp released with AST caching","yard lint & yard clean commands","Extended std/fs, std/os, std/process"]},{version:"v0.4.0",title:"Advanced Pattern Matching & Anonymous Tuples",status:"completed",date:"July 2026",description:"First-class anonymous tuples (T1, T2), tuple destructuring let (a, b) = expr, nested patterns, and match arm guards.",highlights:["Anonymous tuple types (i64, Str, bool)","Tuple destructuring syntax","Nested variant pattern matching","Pattern guards (match x { n if n > 10 => ... })"]},{version:"v0.5.0",title:"Explicit Stack-Based Error Handling",status:"completed",date:"August 2026",description:"Formalized the official zero-wrapper error philosophy: no Option/Result, status codes, tuple returns, out-params, and abort(msg).",highlights:["No Result/Option or ? operator","(T, i32) multi-value return conventions","abort(msg) fatal exit primitive","Predicate companions (str_is_int, env_exists)"]},{version:"v0.6.0",title:"Monomorphized Generics",status:"completed",date:"August 2026",description:"Generic function templates (fn name), type parameter inference at call sites, and specialization pass in src/mono.rs.",highlights:["Generic functions with compile-time monomorphization","Zero vtable / zero dynamic dispatch overhead","Recursive nested generic call resolution","docs/generics.md guide"]},{version:"v0.7.0",title:"Self-Hosted Track Lexer & Yard Test Engine",status:"completed",date:"August 2026",description:"100% native tokenizer written in Track (compiler/src/lexer.trk) with 50+ union variants and native yard test orchestrator.",highlights:["Ported logos lexer into 100% native Track","compiler/ is an isolated Yard package","yard test discovers & runs src/*_test.trk","Copy variant constructors fix in linear checker"]},{version:"v0.8.0",title:"Self-Hosted Parser, Linear Checker & C-Emitter",status:"completed",date:"Late 2026",description:"Native Track parser, native linear ownership checker, and portable C backend emitter, all in compiler/src/.",highlights:["Native recursive descent parser in Track","Self-hosted linear ownership checker","Portable C code emitter","Compiler span error diagnostics"]},{version:"v0.9.0",title:"Full 3-Stage Compiler Self-Bootstrapping",status:"completed",date:"Milestone Gate",description:"Verification of 3-stage bootstrapping: stage 1 compiles stage 2, stage 2 compiles stage 3, and the stage 2 and stage 3 executables are byte-identical.",highlights:["Stage 1 compiles Stage 2 compiler","Stage 2 compiles Stage 3 compiler","Stage 2 and Stage 3 executables byte-identical"]},{version:"v1.0.0",title:"Self-Hosting: trackc, yard and LSP in Track",status:"completed",date:"2026",description:"trackc is written in Track and bootstraps from a committed C seed with only cc (scripts/bootstrap.sh). yard and trackc lsp are written in Track. The Rust stage 0 is removed.",highlights:["cc -> stage1..3 -> native trackc","Native stages n2 = n3 = n4 byte-identical","yard written in Track","trackc lsp written in Track"]}],Fg=()=>s.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8 sm:px-6 space-y-8 text-left",children:[s.jsxs("div",{className:"border-b border-zinc-800 pb-4",children:[s.jsx("h1",{className:"text-2xl sm:text-3xl font-bold font-sans text-zinc-100",children:"Compiler Self-Bootstrapping Roadmap"}),s.jsx("p",{className:"text-xs sm:text-sm text-zinc-400 font-sans mt-1",children:"Path from early memory primitives to a self-hosted compiler in v1.0.0."})]}),s.jsx("div",{className:"space-y-4",children:$g.map((r,h)=>{const y=r.status==="completed",o=r.status==="in-progress";return s.jsxs("div",{className:"rounded border border-zinc-800 bg-[#0d0e12] p-4 space-y-2 text-left",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-zinc-800/60 pb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono text-xs font-bold text-amber-400",children:r.version}),s.jsx("span",{className:"font-mono text-xs text-zinc-300 font-medium",children:r.title})]}),s.jsx("div",{className:"flex items-center gap-1.5 font-mono text-[11px]",children:y?s.jsxs("span",{className:"text-emerald-400 flex items-center gap-1",children:[s.jsx(x0,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Completed"})]}):o?s.jsxs("span",{className:"text-amber-400 flex items-center gap-1",children:[s.jsx(z0,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"In Progress"})]}):s.jsxs("span",{className:"text-purple-400 flex items-center gap-1",children:[s.jsx(Q0,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Milestone Target"})]})})]}),s.jsx("p",{className:"text-xs text-zinc-300 font-sans leading-relaxed",children:r.description}),s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1.5 pt-1 font-mono text-[11px] text-zinc-400",children:r.highlights.map((N,_)=>s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-zinc-600",children:"•"}),s.jsx("span",{children:N})]},_))})]},h)})})]});function Ig(){const[r,h]=fe.useState("home"),[y,o]=fe.useState(!1),[N,_]=fe.useState(void 0),[z,O]=fe.useState("intro"),[A,g]=fe.useState(void 0),L=[...ul.map(M=>({id:`doc-${M.id}`,title:M.title,category:"docs",section:M.category,snippet:M.subtitle,path:`docs#${M.id}`})),...Ru.flatMap(M=>M.functions.map(D=>({id:`stdlib-${M.name}-${D.name}`,title:D.name,category:"stdlib",section:M.name,snippet:`${D.signature} — ${D.description}`,path:`stdlib#${D.name}`}))),...Uu.map(M=>({id:`blog-${M.id}`,title:M.title,category:"blog",section:M.author.name,snippet:M.summary,path:`blog#${M.id}`})),...aa.map(M=>({id:`example-${M.id}`,title:M.title,category:"example",section:M.category,snippet:M.description,path:`examples#${M.id}`}))],w=M=>{h(M),window.scrollTo({top:0,behavior:"smooth"})},I=M=>{_(M),h("playground"),window.scrollTo({top:0,behavior:"smooth"})},V=M=>{if(M.category==="docs"){const D=M.id.replace("doc-","");O(D),h("docs")}else if(M.category==="stdlib")h("stdlib");else if(M.category==="blog"){const D=M.id.replace("blog-","");g(D),h("blog")}else M.category==="example"&&h("docs");window.scrollTo({top:0,behavior:"smooth"})};return s.jsxs("div",{className:"min-h-screen bg-[#090a0d] text-zinc-200 flex flex-col font-sans selection:bg-amber-500/20 selection:text-amber-300",children:[s.jsx(qg,{activeTab:r,onSelectTab:w,onOpenSearch:()=>o(!0)}),s.jsxs("main",{className:"flex-1",children:[r==="home"&&s.jsx(Qg,{onSelectTab:w,onOpenPlaygroundWithCode:I}),r==="docs"&&s.jsx(Vg,{onSelectTab:w,onOpenPlaygroundWithCode:I,initialChapterId:z}),r==="stdlib"&&s.jsx(Kg,{onSelectTab:w,onOpenPlaygroundWithCode:I}),r==="playground"&&s.jsx(Jg,{initialCode:N}),r==="blog"&&s.jsx(Wg,{onSelectTab:w,onOpenPlaygroundWithCode:I,initialPostId:A}),r==="roadmap"&&s.jsx(Fg,{onSelectTab:w})]}),s.jsx(Yg,{isOpen:y,onClose:()=>o(!1),onSelect:V,searchItems:L}),s.jsx(Gg,{onSelectTab:w})]})}f0.createRoot(document.getElementById("root")).render(s.jsx(a0.StrictMode,{children:s.jsx(Ig,{})})); diff --git a/page/dist/index.html b/page/dist/index.html index 286c629b..8a1cb97d 100644 --- a/page/dist/index.html +++ b/page/dist/index.html @@ -10,7 +10,7 @@ - + diff --git a/page/src/components/Navbar.tsx b/page/src/components/Navbar.tsx index 1fc6a399..0bc4e527 100644 --- a/page/src/components/Navbar.tsx +++ b/page/src/components/Navbar.tsx @@ -43,7 +43,7 @@ export const Navbar: React.FC = ({ TRACK - v0.7.0 + v1.0.0 diff --git a/page/src/components/SearchModal.tsx b/page/src/components/SearchModal.tsx index 9a815e26..b6e70a96 100644 --- a/page/src/components/SearchModal.tsx +++ b/page/src/components/SearchModal.tsx @@ -215,7 +215,7 @@ export const SearchModal: React.FC = ({ Select - Track v0.7.0 Documentation Index + Track v1.0.0 Documentation Index diff --git a/page/src/data/comparisonData.ts b/page/src/data/comparisonData.ts index 3735731d..91c680d5 100644 --- a/page/src/data/comparisonData.ts +++ b/page/src/data/comparisonData.ts @@ -47,7 +47,7 @@ export const languageComparisons: LanguageComparisonRow[] = [ }, { feature: 'Compiler Backend', - track: 'Cranelift Standalone (Sub-ms native compilation)', + track: 'Built-in native x86-64 backend, or portable C emitter', rust: 'LLVM (Large memory & build overhead)', zig: 'LLVM / C Emitter / Self-hosted x86', c: 'GCC / Clang (LLVM)', @@ -74,7 +74,7 @@ export const languageComparisons: LanguageComparisonRow[] = [ }, { feature: 'Self-Hosting Status', - track: 'v0.7.0 Native Lexer -> v0.9.0 3-Stage Byte Verify', + track: 'Self-hosted: trackc is written in Track; C-seed bootstrap with byte-identical fixed points', rust: 'Self-hosted via LLVM', zig: 'Self-hosted', c: 'Self-hosted (GCC/Clang)', diff --git a/page/src/data/docsData.ts b/page/src/data/docsData.ts index fb190b23..a3da5d8b 100644 --- a/page/src/data/docsData.ts +++ b/page/src/data/docsData.ts @@ -33,7 +33,7 @@ Track answers this with three foundational principles: - **No Garbage Collector, No Hidden Runtime**: Resource lifecycles are statically verified at compile time. Destruction code (\`vec_free\`, \`str_free\`) is automatically emitted at deterministically computed spend points. - **Linear Ownership State Machine**: Resources have exactly one active owner. Every variable transitions strictly between 4 states: \`Active\`, \`Borrowed\`, \`Locked\`, and \`Spent\`. - **Lexical Lenses (\`with\` blocks)**: Scoped, non-escaping mutable views that eliminate lifetime annotations altogether. -- **Cranelift Standalone Backend**: Instant compilation with native machine code generation for x86_64 and aarch64, avoiding heavy LLVM dynamic dependencies. +- **Native Backend**: \`trackc build --native\` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. The default path goes through generated C. - **Explicit Stack-Based Error Handling**: No monadic wrappers (\`Option\` / \`Result\`), no \`?\` hidden control flow, no stack unwinding. Errors are first-class stack values. `, codeSnippets: [ @@ -51,45 +51,44 @@ fn main() -> void { { id: 'installation', title: 'Installation & Toolchain Setup', - subtitle: 'Get up and running with track, yard, and track-lsp in seconds', + subtitle: 'Get up and running with trackc and yard', category: 'Getting Started', content: ` -Track provides a unified, single-binary toolchain consisting of the standalone compiler (\`track\`), the package manager & test runner (\`yard\`), and the Language Server Protocol daemon (\`track-lsp\`). +Track ships as a self-hosted toolchain: the compiler (\`trackc\`, written in Track), the package manager & test runner (\`yard\`, also written in Track), and the Language Server (\`trackc lsp\`, built into the compiler). ### Quick Installation via Shell Script -On Linux (x86_64, aarch64) or macOS, install the complete Track toolchain using the official installer: +The installer bootstraps \`trackc\` from the committed C seed and builds \`yard\`. It needs a C compiler (\`cc\`), \`git\` and POSIX tools: \`\`\`bash curl -fsSL https://raw.githubusercontent.com/dev-dami/track/main/scripts/install.sh | bash \`\`\` -This downloads and configures \`track\`, \`yard\`, and \`track-lsp\` into your \`/usr/local/bin\` or \`~/.local/bin\`. +The binaries are installed into \`~/.track/bin\` by default (override with \`--dir\` or \`TRACK_INSTALL_DIR\`). ### Building from Source -Track's host compiler is implemented in Rust (2024 edition) and builds cleanly using Cargo: +Track is self-hosting: \`trackc\` is written in Track and compiles itself to a verified fixed point. A clean checkout needs only a C compiler (\`cc\`) and POSIX tools; there is no Rust toolchain involved. \`\`\`bash # Clone the repository git clone https://github.com/dev-dami/track.git cd track - -# Build release binaries (track, yard, track-lsp) -cargo build --release - -# Run local installer +# cc -> stage1..3 -> native; trackc is build/bootstrap/stage3/trackc +scripts/bootstrap.sh +# yard, written in Track +build/bootstrap/stage3/trackc build --native tools/yard/main.trk -o yard +# Or bootstrap and install trackc + yard in one step ./scripts/install.sh \`\`\` +On hosts other than x86-64 Linux (macOS, ARM) use \`scripts/bootstrap.sh --no-native\` for the C-only bootstrap. + ### Verifying Toolchain Installation \`\`\`bash -track --version -# track 0.7.0 - -yard --version -# yard 0.7.0 +trackc --version +# trackc 1.0.0 \`\`\` `, codeSnippets: [ @@ -431,7 +430,7 @@ fn pair(a: T, b: U) -> (T, U) { 1. **Call Site Type Inference**: Type parameters (\`T\`, \`U\`) are inferred automatically from actual argument types. 2. **Specialization & Mangling**: Each distinct combination produces a mangled concrete function (e.g. \`identity__Ti32\`, \`pair__Ti32_Ubool\`). -3. **Direct Emitted Cranelift Machine Code**: No dynamic boxing, no runtime vtable pointer indirection. +3. **Direct Emitted Machine Code**: No dynamic boxing, no runtime vtable pointer indirection. `, codeSnippets: [ { @@ -509,13 +508,12 @@ src = "src" subtitle: 'Real-time diagnostics, auto-completion, and markdown track-block checking', category: 'Toolchain & Compiler', content: ` -Track ships with a dedicated LSP daemon (\`track-lsp\`) built on top of Tower-LSP and Tokio. +Track's language server is part of the self-hosted compiler. Start it with \`trackc lsp\`; it is written in Track (\`compiler/src/lsp.trk\`) and speaks JSON-RPC 2.0 over stdin/stdout. ### Key Capabilities -- **Live Diagnostics**: Real-time ownership checking, type errors, and span highlights in \`.trk\` files. -- **Markdown Code Block Checking**: \`track-lsp\` parses and type-checks \`\`\`track code blocks inside \`.md\` documentation files! -- **Fast Auto-Completion**: Keywords, stdlib modules, structs, and tagged union variants. -- **AST Caching & Stale Result Discarding**: Prevents publishing outdated diagnostics on fast keystrokes. +- **Live Diagnostics**: Exactly what \`trackc check\` reports (lexer, parser, ownership and lifecycle errors, plus warnings), published on open, change and save. +- **Markdown Code Block Checking**: \`\`\`track blocks inside \`.md\` files are checked per block. +- **Auto-Completion & Hover**: Keywords, types, built-ins, macros, and the file's own functions and enum/union variants. ### VS Code Configuration @@ -524,7 +522,8 @@ Add this to your \`.vscode/settings.json\`: \`\`\`json { "language-server.track": { - "command": "track-lsp", + "command": "trackc", + "args": ["lsp"], "filePatterns": ["*.trk", "*.md"] } } @@ -544,11 +543,11 @@ cp grammars/track.tmLanguage.json ~/.vscode/extensions/track-syntax/syntaxes/`, }, { id: 'self-hosting', - title: 'Self-Hosted Compiler & Roadmap to v0.9.0', - subtitle: 'Track lexer in native Track and the 3-stage bootstrapping gate', + title: 'Self-Hosted Compiler & Bootstrap', + subtitle: 'trackc is written in Track and compiles itself to a verified fixed point', category: 'Toolchain & Compiler', content: ` -Track is actively executing its path to full compiler self-bootstrapping. +Track 1.0 is self-hosting: \`trackc\`, the compiler in \`compiler/src/\`, is written entirely in Track. \`yard\` and \`trackc lsp\` are written in Track too. The earlier Rust stage 0 has been removed. ### Milestone Progress Overview @@ -560,18 +559,21 @@ Track is actively executing its path to full compiler self-bootstrapping. [v0.5.0] Explicit Error Handling ✅ DONE [v0.6.0] Monomorphized Generics ✅ DONE [v0.7.0] Self-Hosted Lexer in Track ✅ DONE (compiler/src/lexer.trk) -[v0.8.0] Parser, Checker & C-Emitter ⏳ IN PROGRESS -[v0.9.0] 3-Stage Bootstrapping Verified 🎯 MILESTONE +[v0.8.0] Parser, Checker & C-Emitter ✅ DONE +[v0.9.0] 3-Stage Bootstrapping Verified ✅ DONE +[v1.0.0] Self-Hosting, Rust removed ✅ DONE \`\`\` -### v0.7.0 Milestone: Self-Hosted Lexer -In v0.7.0, Track successfully ported the host lexer from Rust into 100% native Track (\`compiler/src/lexer.trk\`), recognizing 50+ token variants with native union matching and 10 unit test suites. +### The Bootstrap + +A clean checkout builds \`trackc\` with only a C compiler (\`cc\`) and POSIX tools. \`scripts/bootstrap.sh\` starts from a committed C seed (\`bootstrap/seed/\`, the C that \`trackc\` emits for its own sources): + +1. **Stage 0**: \`cc\` builds the C seed into \`stage1/trackc\`. +2. **Stage 1**: \`stage1/trackc\` compiles \`compiler/src/main.trk\` → \`stage2/trackc\`. +3. **Stage 2**: \`stage2/trackc\` compiles \`compiler/src/main.trk\` → \`stage3/trackc\`. +4. **Native**: \`scripts/selfhost.sh\` rebuilds \`trackc\` natively (\`--native\`, no C toolchain) until the native stages \`n2\`, \`n3\` and \`n4\` are byte-identical. -### The 3-Stage Bootstrapping Gate (v0.9.0) -1. **Stage 0**: Host Rust \`track\` compiler compiles \`compiler/*.trk\` → emits \`track_stage1\` executable. -2. **Stage 1**: \`track_stage1\` compiles \`compiler/*.trk\` → emits \`track_stage2\` executable. -3. **Stage 2**: \`track_stage2\` compiles \`compiler/*.trk\` → emits \`track_stage3\` executable. -4. **Verification**: Assert byte-for-byte binary equality (\`cmp track_stage2 track_stage3\`). +The gate checks that stage 1 and stage 2 emit identical C, that the stage 2 and stage 3 executables are byte-identical, and that the native stages reproduce themselves. After any change to \`compiler/src/\`, run \`scripts/update_seed.sh\` to regenerate the seed. See \`docs/bootstrap.md\` in the repository for the full pipeline. `, codeSnippets: [ { diff --git a/page/src/data/roadmapData.ts b/page/src/data/roadmapData.ts index 878efabc..b1324d3f 100644 --- a/page/src/data/roadmapData.ts +++ b/page/src/data/roadmapData.ts @@ -67,17 +67,25 @@ export const roadmapMilestones: Milestone[] = [ { version: 'v0.8.0', title: 'Self-Hosted Parser, Linear Checker & C-Emitter', - status: 'in-progress', + status: 'completed', date: 'Late 2026', - description: 'Native Track parser (compiler/parser.trk), native linear ownership checker, and portable C backend emitter.', + description: 'Native Track parser, native linear ownership checker, and portable C backend emitter, all in compiler/src/.', highlights: ['Native recursive descent parser in Track', 'Self-hosted linear ownership checker', 'Portable C code emitter', 'Compiler span error diagnostics'], }, { version: 'v0.9.0', title: 'Full 3-Stage Compiler Self-Bootstrapping', - status: 'milestone', + status: 'completed', date: 'Milestone Gate', - description: 'Verification of 3-stage bootstrapping: Stage 0 (Rust) -> Stage 1 (Track C) -> Stage 2 (Track) -> Byte-for-byte identity gate.', - highlights: ['Stage 0 builds Stage 1 compiler', 'Stage 1 compiles Stage 2 compiler', 'Stage 2 compiles Stage 3 compiler', 'cmp track_stage2 track_stage3 byte verification'], + description: 'Verification of 3-stage bootstrapping: stage 1 compiles stage 2, stage 2 compiles stage 3, and the stage 2 and stage 3 executables are byte-identical.', + highlights: ['Stage 1 compiles Stage 2 compiler', 'Stage 2 compiles Stage 3 compiler', 'Stage 2 and Stage 3 executables byte-identical'], + }, + { + version: 'v1.0.0', + title: 'Self-Hosting: trackc, yard and LSP in Track', + status: 'completed', + date: '2026', + description: 'trackc is written in Track and bootstraps from a committed C seed with only cc (scripts/bootstrap.sh). yard and trackc lsp are written in Track. The Rust stage 0 is removed.', + highlights: ['cc -> stage1..3 -> native trackc', 'Native stages n2 = n3 = n4 byte-identical', 'yard written in Track', 'trackc lsp written in Track'], }, ]; diff --git a/page/src/pages/HomePage.tsx b/page/src/pages/HomePage.tsx index ba69026e..23b3b618 100644 --- a/page/src/pages/HomePage.tsx +++ b/page/src/pages/HomePage.tsx @@ -82,7 +82,7 @@ export const HomePage: React.FC = ({ className="flex items-center gap-1.5 text-zinc-400 hover:text-zinc-200 transition-colors px-2 py-2" > - v0.9.0 Bootstrapping Roadmap + Self-Hosting Roadmap @@ -160,10 +160,10 @@ export const HomePage: React.FC = ({

- Standalone Cranelift Backend + Native Backend, No Linker

- Fast, standalone native code generation for x86_64 and aarch64 without multi-gigabyte LLVM dynamic libraries. Multi-threaded worker ISA sharing ensures instant check and build cycles. + trackc build --native writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. Prefer C? trackc build compiles through generated C.

@@ -219,7 +219,7 @@ export const HomePage: React.FC = ({

-
Language Server: track-lsp
+
Language Server: trackc lsp

Provides real-time AST diagnostics, autocompletion, and type-checks ```track code blocks embedded in markdown files.

diff --git a/page/src/pages/PlaygroundPage.tsx b/page/src/pages/PlaygroundPage.tsx index f9582fe7..47934f47 100644 --- a/page/src/pages/PlaygroundPage.tsx +++ b/page/src/pages/PlaygroundPage.tsx @@ -194,7 +194,7 @@ export const PlaygroundPage: React.FC = ({ src/main.trk
- Track v0.7.0 • Tab indents with 4 spaces • ⌘+Enter to Run + Track v1.0.0 • Tab indents with 4 spaces • ⌘+Enter to Run
diff --git a/page/src/pages/RoadmapPage.tsx b/page/src/pages/RoadmapPage.tsx index 5e9dedeb..7e0fd8c5 100644 --- a/page/src/pages/RoadmapPage.tsx +++ b/page/src/pages/RoadmapPage.tsx @@ -16,7 +16,7 @@ export const RoadmapPage: React.FC = () => { Compiler Self-Bootstrapping Roadmap

- Path from early memory primitives to verified 3-stage self-compilation in v0.9.0. + Path from early memory primitives to a self-hosted compiler in v1.0.0.

diff --git a/page/src/utils/syntaxHighlight.ts b/page/src/utils/syntaxHighlight.ts index 86c3c7ca..1bfa4569 100644 --- a/page/src/utils/syntaxHighlight.ts +++ b/page/src/utils/syntaxHighlight.ts @@ -68,14 +68,14 @@ export function highlightBash(code: string): string { if (line.trim().startsWith("#")) { return `${line}`; } - let tokenized = line; - // Command prefixes - tokenized = tokenized.replace(/\b(curl|yard|track|cargo|bash|git|cd|mkdir|cp|echo)\b/g, '$1'); - // Flags - tokenized = tokenized.replace(/(--[a-zA-Z0-9_-]+|-[a-zA-Z0-9]+)/g, '$1'); - // Strings - tokenized = tokenized.replace(/(".*?"|".*?")/g, '$1'); - return tokenized; + // One pass, so later rules never match inside spans emitted by earlier ones + return line.replace( + /(".*?"|".*?")|\b(curl|yard|track|trackc|cargo|bash|git|cd|mkdir|cp|echo)\b|(\s)(--[a-zA-Z0-9_-]+|-[a-zA-Z0-9]+)/g, + (_m, str, cmd, sp, flag) => + str ? `${str}` + : cmd ? `${cmd}` + : `${sp}${flag}` + ); }); return lines.join("\n"); diff --git a/scratch/benchmark.py b/scratch/benchmark.py index 22bb9118..3a67ba9b 100644 --- a/scratch/benchmark.py +++ b/scratch/benchmark.py @@ -2,7 +2,7 @@ """ Track Benchmark Suite — fair, statistically rigorous, auto-reporting. -When run, this script compiles and measures Track (Cranelift) vs C (gcc -O3) +When run, this script compiles and measures Track (trackc) vs C (gcc -O3) vs Rust (rustc -O) vs Python 3 across multiple workloads that stress different language subsystems: tight loops, branching, recursion, and tuple operations. All workloads use IDENTICAL algorithms across languages (no branchless @@ -29,7 +29,8 @@ # Paths & constants # --------------------------------------------------------------------------- BENCH_DIR = Path(__file__).resolve().parent / "benchmarks" -TRACK_BIN = Path(__file__).resolve().parent.parent / "target" / "release" / "track" +# trackc: $TRACKC, else the stage3 compiler scripts/bootstrap.sh leaves. +TRACK_BIN = Path(os.environ.get("TRACKC") or Path(__file__).resolve().parent.parent / "build" / "bootstrap" / "stage3" / "trackc") RESULTS_MD = Path(__file__).resolve().parent / "benchmark_results.md" BENCH_DIR.mkdir(parents=True, exist_ok=True) @@ -207,23 +208,11 @@ def get_versions(): return info def compile_track(f_trk: Path) -> Path | None: - # track build writes executable named after stem into cwd — run with cwd=BENCH_DIR - res = subprocess.run([str(TRACK_BIN), "build", str(f_trk)], cwd=str(BENCH_DIR), capture_output=True, text=True) - if res.returncode != 0: - # fallback: legacy `track ` form - res = subprocess.run([str(TRACK_BIN), str(f_trk)], cwd=str(BENCH_DIR), capture_output=True, text=True) - if res.returncode != 0: - print(f"[compile] track failed for {f_trk.name}: {res.stderr[:500]}") - return None bin_path = BENCH_DIR / f_trk.stem - # track may have emitted to parent cwd if invoked differently; also check parent - if not bin_path.exists(): - alt = Path(__file__).resolve().parent.parent / f_trk.stem - if alt.exists(): - alt.rename(bin_path) - else: - print(f"[compile] track binary not found for {f_trk.name}") - return None + res = subprocess.run([str(TRACK_BIN), "build", str(f_trk), "-o", str(bin_path)], cwd=str(BENCH_DIR), capture_output=True, text=True) + if res.returncode != 0 or not bin_path.exists(): + print(f"[compile] trackc failed for {f_trk.name}: {res.stderr[:500]}") + return None return bin_path def compile_c(f_c: Path, f_bin: Path) -> bool: @@ -366,7 +355,7 @@ def run_benchmarks(quick: bool = False): lines.append("|---|---|---|---|---|---|") # lang labels for display - label = {"track": "**Track (Cranelift)**", "c": "C (`gcc -O3`)", "rust": "Rust (`rustc -O`)", "python": "Python 3"} + label = {"track": "**Track (trackc)**", "c": "C (`gcc -O3`)", "rust": "Rust (`rustc -O`)", "python": "Python 3"} for name in per_task: res = per_task[name] track_med = res.get("track", (None,))[0] @@ -395,7 +384,7 @@ def run_benchmarks(quick: bool = False): lines.append("") lines.append("### Notes") lines.append("") - lines.append("- Track binaries are built with `track build` (Cranelift, `opt_level=speed`, `is_pic=false`) and linked via `cc -O3 -lm -no-pie`.") + lines.append("- Track binaries are built with `trackc build` (Track -> C, then the C compiler trackc invokes).") lines.append("- C is `gcc -O3`, Rust is `rustc -O` — both in release mode, single-file, no LTO tuning.") lines.append("- Python is CPython as found on `PATH`; 100M-iteration loops dominate its runtime.") lines.append("- Each task recompiles fresh sources in `scratch/benchmarks/` and is timed end-to-end (process spawn included) with warmup runs discarded; median is the primary metric.") diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 2e8cad55..5995989c 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -2,8 +2,6 @@ # Bootstrap the self-hosted Track compiler and verify the fixed point. # # stage 0 cc builds the committed C seed (bootstrap/seed/) -> stage1 trackc -# (or, with --from-rust / BOOTSTRAP_FROM=rust, the Rust compiler -# `yard` builds compiler/ -> stage1 trackc) # stage 1 stage1 compiles compiler/src/main.trk -> stage2 trackc # stage 2 stage2 compiles compiler/src/main.trk -> stage3 trackc # native scripts/selfhost.sh with stage3 as its seed: n2 = n3 = n4 @@ -11,32 +9,25 @@ # The gate: stage2 and stage3 C are byte-identical, the stage2 and stage3 # executables are byte-identical, and the native stages reproduce # themselves. The default path needs only a C compiler ($CC, default cc) -# and POSIX tools: no Rust, no cargo. +# and POSIX tools. # # scripts/bootstrap.sh # from the C seed -# scripts/bootstrap.sh --from-rust # from the Rust stage0 (cargo / $YARD) # scripts/bootstrap.sh --no-native # skip the native fixed point +# (--from-seed is accepted for old callers; the seed is the only route) # # Artifacts go to build/bootstrap/ (override with BOOTSTRAP_DIR); the native -# stages go to $BOOTSTRAP_DIR/selfhost unless SELFHOST_DIR is set. Set YARD -# to use a specific yard binary on the Rust path. +# stages go to $BOOTSTRAP_DIR/selfhost unless SELFHOST_DIR is set. set -eu -from=${BOOTSTRAP_FROM:-seed} native=1 for arg in "$@"; do case "$arg" in - --from-rust) from=rust ;; - --from-seed) from=seed ;; + --from-seed) ;; --no-native) native=0 ;; - -h|--help) sed -n '2,23p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; - *) echo "usage: $0 [--from-rust | --from-seed] [--no-native]" >&2; exit 2 ;; + -h|--help) sed -n '2,19p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "usage: $0 [--no-native] [--from-seed]" >&2; exit 2 ;; esac done -case "$from" in - seed|rust) ;; - *) echo "bootstrap: BOOTSTRAP_FROM must be 'seed' or 'rust', not '$from'" >&2; exit 2 ;; -esac root=$(cd "$(dirname "$0")/.." && pwd) out=${BOOTSTRAP_DIR:-"$root/build/bootstrap"} @@ -49,19 +40,6 @@ cc=${CC:-cc} # The flags trackc itself passes to the C compiler (cc_flags in main.trk). cflags="-std=gnu99 -O2 -fwrapv -fno-strict-aliasing -fno-builtin -w" -if [ "$from" = rust ]; then - yard=${YARD:-} - if [ -z "$yard" ]; then - (cd "$root" && cargo build --release --quiet) - yard="${CARGO_TARGET_DIR:-$root/target}/release/yard" - fi - # The stages run from other directories, so pin an absolute path. - case "$yard" in - /*) ;; - *) yard="$(pwd)/$yard" ;; - esac -fi - "$root/scripts/embed_runtime.sh" --check "$root/scripts/embed_rt.sh" --check @@ -72,22 +50,16 @@ mkdir -p "$out/stage1" "$out/stage2" "$out/stage3" TRACKC_CACHE="$out/cache" export TRACKC_CACHE -if [ "$from" = seed ]; then - for f in trackc.c trackc.rt.c; do - [ -f "$seed/$f" ] || { echo "bootstrap: missing bootstrap/seed/$f" >&2; exit 1; } - done - # CC may be a launcher command (`ccache cc`): check its first word only. - command -v "${cc%% *}" >/dev/null 2>&1 || { echo "bootstrap: C compiler '$cc' not found" >&2; exit 1; } - echo "==> stage 0: $cc builds the C seed (bootstrap/seed/, $(wc -l < "$seed/trackc.c") lines)" - cp "$seed/trackc.c" "$seed/trackc.rt.c" "$out/stage1/" - # Compile inside the stage directory with trackc's own base names, the - # same way trackc links its output. - (cd "$out/stage1" && $cc $cflags -o trackc trackc.c trackc.rt.c) -else - echo "==> stage 0: yard builds compiler/ (Rust bootstrap compiler)" - (cd "$root/compiler" && "$yard" build >/dev/null) - cp "$root/compiler/target/trackc" "$out/stage1/trackc" -fi +for f in trackc.c trackc.rt.c; do + [ -f "$seed/$f" ] || { echo "bootstrap: missing bootstrap/seed/$f" >&2; exit 1; } +done +# CC may be a launcher command (`ccache cc`): check its first word only. +command -v "${cc%% *}" >/dev/null 2>&1 || { echo "bootstrap: C compiler '$cc' not found" >&2; exit 1; } +echo "==> stage 0: $cc builds the C seed (bootstrap/seed/, $(wc -l < "$seed/trackc.c") lines)" +cp "$seed/trackc.c" "$seed/trackc.rt.c" "$out/stage1/" +# Compile inside the stage directory with trackc's own base names, the +# same way trackc links its output. +(cd "$out/stage1" && $cc $cflags -o trackc trackc.c trackc.rt.c) # Every stage compiles the same sources from the repository root, so the # loader resolves identical module paths at every stage. diff --git a/scripts/install.sh b/scripts/install.sh index c844efc2..f502d5d4 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -45,7 +45,7 @@ banner() { ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ BANNER printf "${RESET}" - printf "${DIM} Track — linear ownership, scoped lenses, Cranelift${RESET}\n" + printf "${DIM} Track — linear ownership, scoped lenses, self-hosted${RESET}\n" hr } @@ -90,18 +90,12 @@ step "Checking prerequisites" need_ok=1 if command -v git >/dev/null 2>&1; then ok "git $(git --version | head -n1 | awk '{print $3}')"; else err "git not found — install git"; need_ok=0; fi -if command -v cargo >/dev/null 2>&1; then - ok "cargo $(cargo --version | awk '{print $2}')" -else - err "cargo not found — install Rust: https://rustup.rs" - printf " ${DIM}curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh${RESET}\n" - need_ok=0 -fi -if command -v cc >/dev/null 2>&1 || command -v gcc >/dev/null 2>&1; then - ccv=$(cc --version 2>/dev/null | head -n1 || gcc --version | head -n1) +if command -v "${CC:-cc}" >/dev/null 2>&1; then + ccv=$("${CC:-cc}" --version 2>/dev/null | head -n1) ok "cc ${ccv:0:48}" else - warn "cc/gcc not found — linking may fail" + err "C compiler '${CC:-cc}' not found — the bootstrap builds the C seed with it" + need_ok=0 fi if [[ $need_ok == 0 ]]; then err "fix prerequisites and re-run"; exit 1; fi @@ -112,7 +106,7 @@ INSTALL_DIR="$REPLY" # expand ~ INSTALL_DIR="${INSTALL_DIR/#\~/$HOME}" -if [[ -d "$INSTALL_DIR" ]] && ls "$INSTALL_DIR"/track >/dev/null 2>&1; then +if [[ -d "$INSTALL_DIR" ]] && ls "$INSTALL_DIR"/trackc >/dev/null 2>&1; then warn "existing Track found at $INSTALL_DIR" ask "Overwrite existing binaries? (y/N)" "y" case "$REPLY" in y|Y|yes|YES) :;; *) info "aborted by user"; exit 0;; esac @@ -149,21 +143,26 @@ ok "cloned to $TMP_DIR/track" cd "$TMP_DIR/track" # ── build ───────────────────────────────────────────────────────── -step "Building release binaries" -printf " ${DIM}cargo build --release --bins (this may take a minute)${RESET}\n" -# show cargo output with dim prefix; keep colors if terminal -if ! cargo build --release --bins 2>&1 | sed 's/^/ '"$GRAY"'│ '"$RESET"'/'; then - err "cargo build failed — check Rust toolchain" +step "Bootstrapping trackc from the C seed" +printf " ${DIM}scripts/bootstrap.sh --no-native (this may take a minute)${RESET}\n" +if ! scripts/bootstrap.sh --no-native 2>&1 | sed 's/^/ '"$GRAY"'│ '"$RESET"'/'; then + err "bootstrap failed — check the C compiler" + exit 1 +fi +mkdir -p build/bin +cp build/bootstrap/stage3/trackc build/bin/trackc +if ! build/bin/trackc build --native tools/yard/main.trk -o build/bin/yard >/dev/null; then + err "building yard failed" exit 1 fi -ok "built track, yard, track-lsp" +ok "built trackc (with trackc lsp) and yard" # ── install ─────────────────────────────────────────────────────── step "Installing" mkdir -p "$INSTALL_DIR" -BINARIES=("track" "yard" "track-lsp") +BINARIES=("trackc" "yard") for bin in "${BINARIES[@]}"; do - src="target/release/$bin" + src="build/bin/$bin" if [[ ! -f "$src" ]]; then err "missing $src (build failed)"; exit 1; fi cp "$src" "$INSTALL_DIR/$bin" chmod +x "$INSTALL_DIR/$bin" @@ -262,11 +261,11 @@ printf "\n" hr printf "${BOLD}${GREEN} Track installed!${RESET}\n" printf " ${DIM}bin:${RESET} %s\n" "$INSTALL_DIR" -printf " ${DIM}track:${RESET} %s\n" "$("$INSTALL_DIR/track" --version 2>/dev/null || echo "track")" +printf " ${DIM}trackc:${RESET} %s\n" "$("$INSTALL_DIR/trackc" --version 2>/dev/null || echo "trackc")" printf " ${DIM}yard:${RESET} %s\n" "$("$INSTALL_DIR/yard" --version 2>/dev/null || echo "yard")" printf "\n" printf " ${BOLD}Quick start:${RESET}\n" -printf " ${CYAN}track --help${RESET} type-check / build\n" +printf " ${CYAN}trackc --help${RESET} type-check / build\n" printf " ${CYAN}yard init my_app${RESET} new project\n" printf " ${CYAN}yard run${RESET} build & run\n" if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then diff --git a/scripts/update_seed.sh b/scripts/update_seed.sh index 39d33955..ce4ca79a 100755 --- a/scripts/update_seed.sh +++ b/scripts/update_seed.sh @@ -3,17 +3,17 @@ # # The seed is the C that trackc emits for compiler/src/main.trk at its fixed # point (trackc.c) plus the C runtime it writes beside it (trackc.rt.c). -# scripts/bootstrap.sh builds it with plain cc, so Track bootstraps with no -# Rust toolchain. +# scripts/bootstrap.sh builds it with plain cc, so Track bootstraps from a C +# compiler alone. # # scripts/update_seed.sh # rewrite bootstrap/seed/ # scripts/update_seed.sh --check # fail if bootstrap/seed/ is out of date # # The fixed point comes from scripts/bootstrap.sh --no-native (stage3, built # from the current seed) unless TRACKC names a working trackc. If a change -# to compiler/src is beyond what the old seed can compile, use -# TRACKC=build/bootstrap/stage3/trackc from `scripts/bootstrap.sh -# --from-rust`, or any other trackc. Scratch goes to $BOOTSTRAP_DIR +# to compiler/src is beyond what the old seed can compile, build it in steps: +# point TRACKC at a trackc built from an intermediate compiler/src that the +# old seed can compile (e.g. an earlier commit's stage3). Scratch goes to $BOOTSTRAP_DIR # (default build/bootstrap). set -eu diff --git a/src/ast/mod.rs b/src/ast/mod.rs deleted file mode 100644 index fab88119..00000000 --- a/src/ast/mod.rs +++ /dev/null @@ -1,240 +0,0 @@ -#[derive(Debug, Clone, PartialEq)] -pub enum Expr { - IntLiteral(i64), - StringLiteral(String), - BoolLiteral(bool), - Variable(String), - - BinaryOp { - op: BinOp, - left: Box, - right: Box, - }, - - UnaryOp { - op: UnaryOp, - expr: Box, - }, - - ArrayLiteral { - elements: Vec, - }, - - TupleLiteral { - elements: Vec, - }, - - TupleIndex { - target: Box, - index: usize, - }, - - /// `value.field` on a struct. - FieldAccess { - target: Box, - field: String, - }, - - ArrayIndex { - target: Box, - index: Box, - }, - - SliceIndex { - target: Box, - start: Option>, - end: Option>, - }, - - Range { - start: Box, - end: Box, - }, - - AddressOf { - target: Box, - }, - - StructInitialization { - ty_name: String, - fields: Vec<(String, Expr)>, - }, - - LensBlock { - target: String, - lens_name: String, - body: Vec, - }, - - FunctionCall { - name: String, - args: Vec, - }, - - IfElse { - condition: Box, - then_body: Vec, - else_body: Vec, - }, - - WhileLoop { - condition: Box, - body: Vec, - }, - - ForIn { - var: String, - iter: Box, - body: Vec, - }, - - Return { - value: Option>, - }, - - Assign { - target: Box, - value: Box, - }, - - FnDef { - name: String, - generics: Vec, - params: Vec<(String, TrackType)>, - return_type: Option, - body: Vec, - }, - - Use { - path: String, - imports: Option>, - alias: Option, - }, - - ConstDef { - name: String, - value: Box, - }, - - TypeAlias { - name: String, - target: TrackType, - }, - - StructDef { - name: String, - fields: Vec<(String, TrackType)>, - }, - - MacroDef { - name: String, - params: Vec<(String, TrackType)>, - return_type: Option, - body: Vec, - }, - - MacroCall { - name: String, - args: Vec, - body: Option>, - }, - - LetDef { - name: String, - mutable: bool, - ty: Option, - value: Box, - }, - - LetDestructure { - pattern: Pattern, - mutable: bool, - value: Box, - }, - - EnumDef { - name: String, - underlying_type: Option, - variants: Vec<(String, Option)>, - }, - - UnionDef { - name: String, - variants: Vec<(String, Option)>, - }, - - Match { - target: Box, - arms: Vec, - }, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum TrackType { - U8, - I8, - I32, - U32, - I64, - U64, - Bool, - Ptr(Box), - Ref(Box), - Slice(Box), - Array(Box, usize), - Tuple(Vec), - Void, - Custom(String), -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum BinOp { - Add, - Sub, - Mul, - Div, - Mod, - Eq, - Neq, - Lt, - Gt, - Lte, - Gte, - And, - Or, - BitAnd, - BitOr, - Shl, - Shr, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum UnaryOp { - Neg, - Not, - Deref, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct MatchArm { - pub pattern: Pattern, - pub guard: Option, - pub body: Expr, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Pattern { - Ident(String), - Wildcard, - Literal(Box), - Tuple(Vec), - Variant { - enum_or_union: String, - variant: String, - bindings: Vec, - }, - Struct { - name: String, - fields: Vec<(String, Pattern)>, - }, -} diff --git a/src/checker/mod.rs b/src/checker/mod.rs deleted file mode 100644 index 1df91d43..00000000 --- a/src/checker/mod.rs +++ /dev/null @@ -1,1879 +0,0 @@ -use std::collections::HashMap; - -use crate::ast::{BinOp, Expr, TrackType}; - -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum VariableState { - Active, - Locked, - Spent, -} - -pub struct LinearChecker { - pub registry: HashMap, - pub types: HashMap, - pub functions: HashMap>, - pub borrows: HashMap>, - pub lens_locked: std::collections::HashSet, - pub lens_aliases: std::collections::HashSet, - pub mutables: std::collections::HashSet, - pub unions: HashMap)>>, - pub type_aliases: HashMap, - pub current_params: std::collections::HashSet, - pub current_return_type: Option, - pub barebones: bool, - pub loaded_modules: std::collections::HashSet, - /// Functions defined so far, across the root file and every module it - /// imports, so a clash between them is E0201 as in trackc. - pub defined_fns: std::collections::HashSet, - /// Enum/union layouts and aliases for codegen, including imported modules. - pub type_info: crate::codegen::TypeInfo, - pub const_values: HashMap, - pub structs: HashMap>, -} - -impl LinearChecker { - pub fn new_barebones() -> Self { - let mut c = Self::new(); - c.barebones = true; - c.functions.clear(); - c - } -} - -fn is_copy_type(ty: &TrackType) -> bool { - matches!( - ty, - TrackType::U8 - | TrackType::I8 - | TrackType::I32 - | TrackType::U32 - | TrackType::I64 - | TrackType::U64 - | TrackType::Bool - | TrackType::Ref(_) - ) -} - -impl Default for LinearChecker { - fn default() -> Self { - Self::new() - } -} - -impl LinearChecker { - pub fn new() -> Self { - Self { - registry: HashMap::new(), - types: HashMap::new(), - functions: HashMap::new(), - borrows: HashMap::new(), - lens_locked: std::collections::HashSet::new(), - lens_aliases: std::collections::HashSet::new(), - mutables: std::collections::HashSet::new(), - unions: HashMap::new(), - type_aliases: HashMap::new(), - current_params: std::collections::HashSet::new(), - current_return_type: None, - barebones: false, - loaded_modules: std::collections::HashSet::new(), - defined_fns: std::collections::HashSet::new(), - type_info: crate::codegen::TypeInfo::default(), - const_values: HashMap::new(), - structs: HashMap::new(), - } - } - - /// A new binding is mutable only if declared `let mut`; it shadows any - /// earlier binding of the same name. - fn set_mutable(&mut self, name: &str, mutable: bool) { - if mutable { - self.mutables.insert(name.to_string()); - } else { - self.mutables.remove(name); - } - } - - pub fn declare(&mut self, name: String) { - self.registry.insert(name, VariableState::Active); - } - - pub fn is_copy_var(&self, name: &str) -> bool { - // Enum/union variant constructors (e.g. `Color::Red`, `Token::Import`) are - // semantically value constants — reusing the same variant must not - // consume a linear resource. Treat any `::`-qualified name that was - // introduced as an enum/union variant as copy so `read_or_move` - // remains `Active` across uses and CFG merges. - if name.contains("::") { - return true; - } - if let Some(ty) = self.types.get(name) { - is_copy_type(ty) - } else { - false - } - } - - pub fn read_or_move(&mut self, name: &str) -> Result<(), String> { - match self.registry.get(name) { - Some(VariableState::Spent) => Err(format!( - "Compile Error: Use-after-free! Resource '{}' is already spent.", - name - )), - Some(VariableState::Locked) => Err(format!( - "Compile Error: Resource '{}' is frozen (either locked in a lens or borrowed).", - name - )), - Some(VariableState::Active) => { - if !self.is_copy_var(name) && !self.lens_aliases.contains(name) { - self.registry.insert(name.to_string(), VariableState::Spent); - } - Ok(()) - } - None => Err(format!("Compile Error: Undeclared variable '{}'.", name)), - } - } - - pub fn update_borrow_states(&mut self) { - if self.borrows.is_empty() && self.lens_locked.is_empty() { - for state in self.registry.values_mut() { - if *state == VariableState::Locked { - *state = VariableState::Active; - } - } - return; - } - - // Collect all variables that are borrowed by currently Active reference variables - let mut borrowed_vars = std::collections::HashSet::new(); - for (ref_name, provs) in &self.borrows { - if self.registry.get(ref_name) == Some(&VariableState::Active) { - for p in provs { - borrowed_vars.insert(p.clone()); - } - } - } - - // Update registry states - for (name, state) in self.registry.iter_mut() { - let is_locked = self.lens_locked.contains(name) || borrowed_vars.contains(name); - if is_locked && *state == VariableState::Active { - *state = VariableState::Locked; - } else if !is_locked && *state == VariableState::Locked { - *state = VariableState::Active; - } - } - } - - pub fn enter_lens(&mut self, name: &str) -> Result<(), String> { - if self.registry.get(name) == Some(&VariableState::Active) { - self.lens_locked.insert(name.to_string()); - self.registry - .insert(name.to_string(), VariableState::Locked); - Ok(()) - } else { - Err(format!( - "Compile Error: Cannot create lens. '{}' is not Active.", - name - )) - } - } - - pub fn exit_lens(&mut self, name: &str) { - self.lens_locked.remove(name); - if self.registry.get(name) == Some(&VariableState::Locked) { - self.registry - .insert(name.to_string(), VariableState::Active); - } - self.update_borrow_states(); - } - - pub fn check_program(&mut self, program: &[Expr]) -> Result<(), String> { - if !self.barebones { - // print is built-in and returns Void — barebones disables the implicit prelude - self.functions - .insert("print".to_string(), Some(TrackType::Void)); - - // Memory functions - self.functions.insert( - "alloc".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Custom( - "u8".to_string(), - )))), - ); - self.functions - .insert("memset".to_string(), Some(TrackType::Void)); - self.functions - .insert("memcpy".to_string(), Some(TrackType::Void)); - self.functions - .insert("memcmp".to_string(), Some(TrackType::I32)); - - // String functions - self.functions - .insert("str_len".to_string(), Some(TrackType::U32)); - self.functions - .insert("str_eq".to_string(), Some(TrackType::Bool)); - self.functions.insert( - "str_from_literal".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions.insert( - "str_concat".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - - // Vec functions - self.functions.insert( - "vec_init".to_string(), - Some(TrackType::Custom("Vec".to_string())), - ); - self.functions - .insert("vec_push".to_string(), Some(TrackType::Void)); - self.functions - .insert("vec_get".to_string(), Some(TrackType::I32)); - self.functions - .insert("vec_set".to_string(), Some(TrackType::Void)); - self.functions - .insert("vec_pop".to_string(), Some(TrackType::I32)); - - // I/O functions - self.functions - .insert("print_str".to_string(), Some(TrackType::Void)); - self.functions - .insert("print_int".to_string(), Some(TrackType::Void)); - self.functions - .insert("print_hex".to_string(), Some(TrackType::Void)); - self.functions.insert( - "read_line".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions.insert( - "file_open".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Custom( - "File".to_string(), - )))), - ); - self.functions.insert( - "file_read_all".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions - .insert("file_write".to_string(), Some(TrackType::Void)); - - // Ring buffer functions - self.functions.insert( - "ring_init".to_string(), - Some(TrackType::Custom("Ring".to_string())), - ); - self.functions - .insert("ring_push".to_string(), Some(TrackType::Bool)); - self.functions - .insert("ring_pop".to_string(), Some(TrackType::I32)); - self.functions - .insert("ring_peek".to_string(), Some(TrackType::I32)); - self.functions - .insert("ring_full".to_string(), Some(TrackType::Bool)); - self.functions - .insert("ring_empty".to_string(), Some(TrackType::Bool)); - self.functions - .insert("ring_count".to_string(), Some(TrackType::U32)); - - // Math functions - self.functions - .insert("math_abs".to_string(), Some(TrackType::I32)); - self.functions - .insert("math_max".to_string(), Some(TrackType::I32)); - self.functions - .insert("math_min".to_string(), Some(TrackType::I32)); - self.functions - .insert("math_pow".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_sqrt".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_clamp".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_random".to_string(), Some(TrackType::U64)); - - // Extended String & File & Sys functions - self.functions - .insert("str_find".to_string(), Some(TrackType::I64)); - self.functions - .insert("str_to_int".to_string(), Some(TrackType::I64)); - self.functions.insert( - "int_to_str".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions - .insert("file_remove".to_string(), Some(TrackType::I32)); - self.functions - .insert("file_size".to_string(), Some(TrackType::I64)); - self.functions - .insert("sys_exec".to_string(), Some(TrackType::I32)); - self.functions - .insert("sys_set_memory_limit".to_string(), Some(TrackType::Void)); - self.functions - .insert("sys_get_memory_used".to_string(), Some(TrackType::I64)); - self.functions.insert( - "env_get".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - - // Math Extensions - self.functions - .insert("math_abs".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_min".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_max".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_pow".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_sqrt".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_floor".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_ceil".to_string(), Some(TrackType::I64)); - self.functions - .insert("math_round".to_string(), Some(TrackType::I64)); - - // Extra String & IO Extensions - self.functions - .insert("print_err".to_string(), Some(TrackType::Void)); - self.functions - .insert("eprint".to_string(), Some(TrackType::Void)); - self.functions - .insert("str_contains".to_string(), Some(TrackType::I64)); - self.functions - .insert("str_is_int".to_string(), Some(TrackType::I32)); - - // Explicit error handling primitives (v0.5) - self.functions - .insert("abort".to_string(), Some(TrackType::Void)); - self.functions - .insert("env_exists".to_string(), Some(TrackType::I32)); - - // TCP Socket Net API - self.functions - .insert("net_socket_tcp_listen".to_string(), Some(TrackType::I32)); - self.functions - .insert("net_socket_accept".to_string(), Some(TrackType::I32)); - self.functions - .insert("net_socket_connect".to_string(), Some(TrackType::I32)); - self.functions - .insert("net_socket_send".to_string(), Some(TrackType::I64)); - self.functions - .insert("net_socket_recv".to_string(), Some(TrackType::I64)); - self.functions - .insert("net_socket_close".to_string(), Some(TrackType::Void)); - - // OS & FS Extensions (v0.2.0) - self.functions - .insert("os_args_count".to_string(), Some(TrackType::I32)); - self.functions.insert( - "os_arg".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions - .insert("dir_exists".to_string(), Some(TrackType::Bool)); - self.functions - .insert("file_copy".to_string(), Some(TrackType::I32)); - self.functions - .insert("process_spawn".to_string(), Some(TrackType::I32)); - - // Char & Byte Operations - self.functions - .insert("char_is_digit".to_string(), Some(TrackType::Bool)); - self.functions - .insert("char_is_alpha".to_string(), Some(TrackType::Bool)); - self.functions - .insert("char_is_alphanumeric".to_string(), Some(TrackType::Bool)); - self.functions - .insert("char_is_space".to_string(), Some(TrackType::Bool)); - self.functions - .insert("char_to_upper".to_string(), Some(TrackType::U8)); - self.functions - .insert("char_to_lower".to_string(), Some(TrackType::U8)); - - // Extended String & Memory - self.functions - .insert("str_starts_with".to_string(), Some(TrackType::Bool)); - self.functions - .insert("str_ends_with".to_string(), Some(TrackType::Bool)); - self.functions.insert( - "str_substr".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions.insert( - "str_trim".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions - .insert("str_char_at".to_string(), Some(TrackType::U8)); - self.functions.insert( - "mem_realloc".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Custom( - "u8".to_string(), - )))), - ); - self.functions - .insert("vec_reserve".to_string(), Some(TrackType::Void)); - self.functions - .insert("vec_clear".to_string(), Some(TrackType::Void)); - self.functions - .insert("vec_len".to_string(), Some(TrackType::I32)); - - // Path Operations - self.functions.insert( - "path_basename".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions.insert( - "path_ext".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - self.functions.insert( - "path_join".to_string(), - Some(TrackType::Custom("Str".to_string())), - ); - - // Runtime support used by the self-hosted compiler (word ABI). - for name in [ - "track_i64_collection_new", - "track_i64_collection_len", - "track_i64_collection_push", - "track_i64_collection_get", - "track_i64_collection_set", - "track_i64_collection_pop", - "track_i64_collection_truncate", - "track_sb_new", - "track_sb_push", - "track_sb_push_byte", - "track_sb_push_int", - "track_sb_len", - "track_sb_str", - "track_sb_clear", - "track_str_bytes", - "track_file_read", - "track_stdin_read", - "track_file_write_all", - "track_out", - "track_err", - "track_words_copy", - "sys_exit", - "clock_ms", - "array_len", - ] { - self.functions - .insert(name.to_string(), Some(TrackType::I64)); - } - } // end if !barebones — std package (import "std") still works via Use handling - - for stmt in program { - match stmt { - Expr::ConstDef { name, value } => { - const_divrem_ok(&self.const_values, value)?; - if let Some(v) = crate::codegen::eval_const(&self.const_values, value) { - self.const_values.insert(name.clone(), v); - self.type_info.consts.insert(name.clone(), v); - } - // Constants are module-level: visible to functions - // defined before them in the file. - self.declare(name.clone()); - if let Some(ty) = self.infer_type(value) { - self.types.insert(name.clone(), ty); - } - } - Expr::StructDef { name, fields } => { - self.structs.insert(name.clone(), fields.clone()); - self.type_info.structs.insert( - name.clone(), - fields.iter().map(|(f, _)| f.clone()).collect(), - ); - } - Expr::TypeAlias { name, target } => { - self.type_aliases.insert(name.clone(), target.clone()); - self.type_info.aliases.insert(name.clone(), target.clone()); - } - Expr::EnumDef { name, variants, .. } => { - for value in variants.iter().filter_map(|(_, v)| v.as_ref()) { - const_divrem_ok(&self.const_values, value)?; - } - for (vname, disc) in - crate::codegen::enum_discriminants(&self.const_values, variants) - { - // A unit variant is a constant to later constants. - self.const_values - .insert(format!("{}::{}", name, vname), disc); - self.type_info - .variants - .insert(format!("{}::{}", name, vname), disc); - } - for (var_name, _) in variants { - let fullname = format!("{}::{}", name, var_name); - self.types - .insert(fullname.clone(), TrackType::Custom(name.clone())); - self.declare(fullname); - } - } - Expr::UnionDef { name, variants } => { - self.unions.insert(name.clone(), variants.clone()); - for (idx, (vname, ty)) in variants.iter().enumerate() { - self.type_info - .variants - .insert(format!("{}::{}", name, vname), idx as i64); - if ty.is_some() { - self.type_info.payload_unions.insert(name.clone()); - } - } - for (var_name, ty_opt) in variants { - let fullname = format!("{}::{}", name, var_name); - if ty_opt.is_some() { - self.functions - .insert(fullname, Some(TrackType::Custom(name.clone()))); - } else { - self.types - .insert(fullname.clone(), TrackType::Custom(name.clone())); - self.declare(fullname); - } - } - } - Expr::FnDef { - name, - generics, - return_type, - .. - } => { - if !self.defined_fns.insert(name.clone()) { - return Err(format!( - "error[E0201]: duplicate definition of function '{}'", - name - )); - } - if !generics.is_empty() { - // Generic templates are checked via their instances. - continue; - } - self.functions.insert(name.clone(), return_type.clone()); - } - _ => {} - } - } - for stmt in program { - self.check_expr(stmt)?; - } - Ok(()) - } - - fn infer_type(&self, expr: &Expr) -> Option { - match expr { - Expr::IntLiteral(_) => Some(TrackType::I32), - Expr::BoolLiteral(_) => Some(TrackType::Bool), - Expr::StringLiteral(_) => Some(TrackType::Ptr(Box::new(TrackType::I32))), - Expr::Variable(name) => self.types.get(name).cloned(), - Expr::BinaryOp { op, left, .. } => { - if is_comparison(op) { - Some(TrackType::Bool) - } else { - self.infer_type(left) - } - } - Expr::UnaryOp { op, expr } => match op { - crate::ast::UnaryOp::Not => Some(TrackType::Bool), - crate::ast::UnaryOp::Neg => self.infer_type(expr), - crate::ast::UnaryOp::Deref => match self.infer_type(expr) { - Some(TrackType::Ptr(inner)) | Some(TrackType::Ref(inner)) => Some(*inner), - _ => None, - }, - }, - Expr::ArrayLiteral { elements } => { - let elem_type = elements - .first() - .and_then(|e| self.infer_type(e)) - .unwrap_or(TrackType::I32); - Some(TrackType::Array(Box::new(elem_type), elements.len())) - } - Expr::TupleLiteral { elements } => { - let elem_types = elements - .iter() - .map(|e| self.infer_type(e).unwrap_or(TrackType::I32)) - .collect(); - Some(TrackType::Tuple(elem_types)) - } - Expr::TupleIndex { target, index } => match self.infer_type(target) { - Some(TrackType::Tuple(types)) => types.get(*index).cloned(), - Some(TrackType::Ref(inner)) => match *inner { - TrackType::Tuple(types) => types.get(*index).cloned(), - _ => None, - }, - _ => None, - }, - Expr::ArrayIndex { target, .. } => match self.infer_type(target) { - Some(TrackType::Array(inner, _)) => Some(*inner), - Some(TrackType::Ptr(inner)) => Some(*inner), - Some(TrackType::Slice(inner)) => Some(*inner), - Some(TrackType::Ref(inner)) => match *inner { - TrackType::Array(elem, _) => Some(*elem), - TrackType::Ptr(elem) => Some(*elem), - TrackType::Slice(elem) => Some(*elem), - other => Some(other), - }, - _ => None, - }, - Expr::SliceIndex { target, .. } => match self.infer_type(target) { - Some(TrackType::Array(inner, _)) => Some(TrackType::Slice(inner)), - Some(TrackType::Slice(inner)) => Some(TrackType::Slice(inner)), - Some(TrackType::Ptr(inner)) => Some(TrackType::Slice(inner)), - Some(TrackType::Ref(inner)) => match *inner { - TrackType::Array(elem, _) => Some(TrackType::Slice(elem)), - TrackType::Slice(elem) => Some(TrackType::Slice(elem)), - TrackType::Ptr(elem) => Some(TrackType::Slice(elem)), - _ => None, - }, - _ => None, - }, - Expr::Range { .. } => Some(TrackType::Void), - Expr::AddressOf { target } => { - self.infer_type(target).map(|t| TrackType::Ref(Box::new(t))) - } - Expr::StructInitialization { ty_name, .. } => Some(TrackType::Custom(ty_name.clone())), - Expr::FieldAccess { target, field } => { - let ty = match self.infer_type(target)? { - TrackType::Ref(inner) => *inner, - other => other, - }; - match ty { - TrackType::Custom(name) => self - .structs - .get(&name)? - .iter() - .find(|(f, _)| f == field) - .map(|(_, t)| t.clone()), - _ => None, - } - } - Expr::StructDef { .. } => Some(TrackType::Void), - Expr::FunctionCall { name, .. } => self.functions.get(name).cloned().flatten(), - Expr::LensBlock { body, .. } => body.last().and_then(|e| self.infer_type(e)), - Expr::IfElse { then_body, .. } => then_body.last().and_then(|e| self.infer_type(e)), - Expr::WhileLoop { .. } => Some(TrackType::Void), - Expr::Return { .. } => Some(TrackType::Void), - Expr::Assign { .. } => Some(TrackType::Void), - Expr::FnDef { .. } => Some(TrackType::Void), - Expr::Use { .. } => Some(TrackType::Void), - Expr::ConstDef { .. } => Some(TrackType::Void), - Expr::MacroDef { .. } => Some(TrackType::Void), - Expr::MacroCall { name, .. } => { - if name == "now" { - Some(TrackType::I64) - } else { - self.functions.get(name).cloned().flatten() - } - } - Expr::LetDef { .. } | Expr::LetDestructure { .. } => Some(TrackType::Void), - Expr::EnumDef { .. } => Some(TrackType::Void), - Expr::UnionDef { .. } => Some(TrackType::Void), - Expr::TypeAlias { .. } => Some(TrackType::Void), - Expr::ForIn { .. } => Some(TrackType::Void), - Expr::Match { arms, .. } => arms.first().and_then(|arm| self.infer_type(&arm.body)), - } - } - - fn check_expr(&mut self, expr: &Expr) -> Result<(), String> { - match expr { - Expr::IntLiteral(_) - | Expr::StringLiteral(_) - | Expr::BoolLiteral(_) - | Expr::TypeAlias { .. } - | Expr::StructDef { .. } => Ok(()), - - Expr::FieldAccess { target, field } => { - self.check_borrow(target)?; - if !self - .structs - .values() - .any(|fs| fs.iter().any(|(f, _)| f == field)) - { - return Err(format!( - "Compile Error: Unknown field '{}' (no struct declares it).", - field - )); - } - Ok(()) - } - - Expr::Variable(name) => { - self.read_or_move(name)?; - Ok(()) - } - - Expr::BinaryOp { left, right, .. } => { - // Binary ops borrow both sides (copy semantics for primitives) - self.check_borrow(left)?; - self.check_borrow(right)?; - Ok(()) - } - - Expr::UnaryOp { expr, .. } => self.check_expr(expr), - - Expr::ArrayLiteral { elements } => { - for elem in elements { - self.check_expr(elem)?; - } - Ok(()) - } - - Expr::TupleLiteral { elements } => { - for elem in elements { - self.check_expr(elem)?; - } - Ok(()) - } - - Expr::TupleIndex { target, index } => { - self.check_borrow(target)?; - if let Some(ty) = self.infer_type(target) { - let tuple_types = match ty { - TrackType::Tuple(types) => Some(types), - TrackType::Ref(inner) => match *inner { - TrackType::Tuple(types) => Some(types), - _ => None, - }, - _ => None, - }; - if let Some(types) = tuple_types - && *index >= types.len() - { - return Err(format!( - "Compile Error: Tuple index {} out of bounds for tuple of length {}", - index, - types.len() - )); - } - } - Ok(()) - } - - Expr::ArrayIndex { target, index } => { - // Array index borrows both target and index - self.check_borrow(target)?; - self.check_borrow(index)?; - Ok(()) - } - - Expr::SliceIndex { target, start, end } => { - self.check_borrow(target)?; - if let Some(s) = start { - self.check_borrow(s)?; - } - if let Some(e) = end { - self.check_borrow(e)?; - } - Ok(()) - } - - Expr::Range { start, end } => { - self.check_borrow(start)?; - self.check_borrow(end)?; - Ok(()) - } - - Expr::AddressOf { target } => { - // &expr borrows but doesn't consume — check without moving - self.check_borrow(target)?; - Ok(()) - } - - Expr::StructInitialization { ty_name, fields } => { - if let Some(decl) = self.structs.get(ty_name) { - for (fname, _) in fields { - if !decl.iter().any(|(f, _)| f == fname) { - return Err(format!( - "Compile Error: Struct '{}' has no field '{}'.", - ty_name, fname - )); - } - } - } - for (_, fval) in fields { - self.reject_lens_escape(fval)?; - self.check_expr(fval)?; - } - Ok(()) - } - - Expr::FunctionCall { name, args } => { - // These are compiler-inserted automatically — users cannot call them directly - const FORBIDDEN: &[&str] = &["free", "str_free", "vec_free", "file_close"]; - if FORBIDDEN.contains(&name.as_str()) { - return Err(format!( - "Compile Error: '{}' is managed automatically by the compiler. \ - Linear types are freed at their spend points — do not call this directly.", - name - )); - } - - let clean_name = name.trim_start_matches('@'); - let target_name = if clean_name.contains("::") { - clean_name.split("::").last().unwrap() - } else { - clean_name - }; - - if !self.functions.contains_key(name) - && !self.functions.contains_key(clean_name) - && !self.functions.contains_key(target_name) - { - let mut best_match = None; - let mut min_dist = usize::MAX; - for candidate in self.functions.keys() { - let dist = levenshtein_distance(target_name, candidate); - if dist <= 2 && dist < min_dist { - min_dist = dist; - best_match = Some(candidate.clone()); - } - } - if let Some(suggestion) = best_match { - return Err(format!( - "Compile Error: Undefined function '{}'. Did you mean '{}'?", - name, suggestion - )); - } - } - - for arg in args { - self.check_expr(arg)?; - } - Ok(()) - } - - Expr::LetDef { - name, - mutable, - ty, - value, - } => { - self.reject_lens_escape(value)?; - self.check_expr(value)?; - let inferred = self.infer_type(value); - let final_ty = if let Some(annotated_ty) = ty { - annotated_ty.clone() - } else { - inferred.unwrap_or(TrackType::Void) - }; - - self.declare(name.clone()); - self.set_mutable(name, *mutable); - self.types.insert(name.clone(), final_ty.clone()); - - if matches!(final_ty, TrackType::Ref(_)) { - let prov = self.get_provenance(value); - self.borrows.insert(name.clone(), prov); - } - self.update_borrow_states(); - Ok(()) - } - - Expr::LensBlock { - target, - lens_name, - body, - } => { - self.enter_lens(target)?; - self.declare(lens_name.clone()); - self.set_mutable(lens_name, false); - self.lens_aliases.insert(lens_name.clone()); - if let Some(ty) = self.types.get(target).cloned() { - self.types.insert(lens_name.clone(), ty); - } - for expr in body { - self.check_expr(expr)?; - } - self.exit_lens(target); - self.registry.remove(lens_name); - self.types.remove(lens_name); - self.borrows.remove(lens_name); - self.lens_aliases.remove(lens_name); - Ok(()) - } - - Expr::IfElse { - condition, - then_body, - else_body, - } => { - self.check_expr(condition)?; - - // Clone state for each branch - // Snapshot pre-if state - let pre_if = self.registry.clone(); - let pre_if_types = self.types.clone(); - let pre_if_borrows = self.borrows.clone(); - let pre_if_mutables = self.mutables.clone(); - - // Check then branch directly - for stmt in then_body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - let then_end = std::mem::replace(&mut self.registry, pre_if.clone()); - let _then_types = std::mem::replace(&mut self.types, pre_if_types.clone()); - let then_end_borrows = std::mem::replace(&mut self.borrows, pre_if_borrows.clone()); - self.mutables = pre_if_mutables.clone(); - - // Check else branch directly - for stmt in else_body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - let else_end = std::mem::take(&mut self.registry); - let _else_types = std::mem::take(&mut self.types); - let else_end_borrows = std::mem::take(&mut self.borrows); - - // CFG Merge: both branches must leave variables in identical states - let mut merged = HashMap::new(); - let mut merged_types = HashMap::new(); - let mut merged_borrows = HashMap::new(); - for name in pre_if.keys() { - let then_s = then_end.get(name).copied().unwrap_or(VariableState::Spent); - let else_s = else_end.get(name).copied().unwrap_or(VariableState::Spent); - - if then_s != else_s { - return Err(format!( - "Compile Error: Resource '{}' has inconsistent state after if/else. \ - Then branch: {:?}, Else branch: {:?}", - name, then_s, else_s - )); - } - merged.insert(name.clone(), then_s); - if let Some(ty) = pre_if_types.get(name) { - merged_types.insert(name.clone(), ty.clone()); - } - // For borrows, take union or then branch (they must match or merge) - if let Some(b) = then_end_borrows - .get(name) - .or_else(|| else_end_borrows.get(name)) - { - merged_borrows.insert(name.clone(), b.clone()); - } - } - - self.registry = merged; - self.types = merged_types; - self.borrows = merged_borrows; - self.mutables = pre_if_mutables; - self.update_borrow_states(); - Ok(()) - } - - Expr::WhileLoop { condition, body } => { - // Check condition - self.check_expr(condition)?; - - // Run body to check for linear violations inside the loop - let pre_loop = self.registry.clone(); - let pre_loop_types = self.types.clone(); - let pre_loop_borrows = self.borrows.clone(); - let pre_loop_mutables = self.mutables.clone(); - - for stmt in body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - - // Reject linear resources defined outside the loop being consumed inside the loop - for (name, pre_state) in &pre_loop { - if *pre_state == VariableState::Active - && !self.is_copy_var(name) - && let Some(post_state) = self.registry.get(name) - && *post_state == VariableState::Spent - { - return Err(format!( - "Compile Error: Cannot consume linear resource '{}' inside a loop. It was declared outside the loop and would be double-freed/moved on subsequent iterations.", - name - )); - } - } - - self.registry = pre_loop; - self.types = pre_loop_types; - self.borrows = pre_loop_borrows; - self.mutables = pre_loop_mutables; - self.update_borrow_states(); - Ok(()) - } - - Expr::ForIn { var, iter, body } => { - self.check_expr(iter)?; - // As trackc: a known scalar is not iterable (codegen would - // read it as an array header and fault). - if !matches!(iter.as_ref(), Expr::Range { .. }) - && matches!( - self.infer_type(iter), - Some( - TrackType::U8 - | TrackType::I8 - | TrackType::I32 - | TrackType::U32 - | TrackType::I64 - | TrackType::U64 - | TrackType::Bool - ) - ) - { - return Err("error[E0200]: `for` iterates over a range or an array; use `for i in 0..n` to count.".to_string()); - } - let iter_ty = self.infer_type(iter).map(|ty| match ty { - TrackType::Ref(inner) => *inner, - other => other, - }); - let elem_ty = iter_ty.map_or(TrackType::I32, |ty| match ty { - TrackType::Slice(inner) => *inner, - TrackType::Array(inner, _) => *inner, - _ => TrackType::I32, - }); - - let pre_loop = self.registry.clone(); - let pre_loop_types = self.types.clone(); - let pre_loop_borrows = self.borrows.clone(); - let pre_loop_mutables = self.mutables.clone(); - - self.declare(var.clone()); - self.set_mutable(var, false); - self.types.insert(var.clone(), elem_ty); - - for stmt in body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - - for (name, pre_state) in &pre_loop { - if *pre_state == VariableState::Active - && !self.is_copy_var(name) - && let Some(post_state) = self.registry.get(name) - && *post_state == VariableState::Spent - { - return Err(format!( - "Compile Error: Cannot consume linear resource '{}' inside a loop.", - name - )); - } - } - - self.registry = pre_loop; - self.types = pre_loop_types; - self.borrows = pre_loop_borrows; - self.mutables = pre_loop_mutables; - self.update_borrow_states(); - Ok(()) - } - - Expr::Return { value } => { - if let Some(val) = value { - self.reject_lens_escape(val)?; - self.check_expr(val)?; - // Escape check - if let Some(TrackType::Ref(_)) = self.current_return_type { - let prov = self.get_provenance(val); - for v in &prov { - if !self.current_params.contains(v) { - return Err(format!( - "Compile Error: Cannot return reference to local variable '{}' (escapes function scope).", - v - )); - } - } - } - } - Ok(()) - } - - Expr::Assign { target, value } => { - self.reject_lens_escape(value)?; - self.check_expr(value)?; - // For simple variable assignment, check mutability and re-activate variable - if let Expr::Variable(name) = target.as_ref() { - if !self.registry.contains_key(name) { - return Err(format!("Compile Error: Undeclared variable '{}'.", name)); - } - if !self.mutables.contains(name) { - return Err(format!( - "Compile Error: Cannot mutate immutable variable '{}'. Use 'let mut {}' to declare a mutable variable.", - name, name - )); - } - self.registry.insert(name.clone(), VariableState::Active); - self.assign_types(name, value); - } else { - self.check_place(target)?; - } - self.update_borrow_states(); - Ok(()) - } - - Expr::FnDef { - generics, - params, - body, - return_type, - .. - } => { - if !generics.is_empty() { - return Ok(()); - } - // Enter function scope (preserve global module declarations) - let saved_registry = self.registry.clone(); - let saved_types = self.types.clone(); - let saved_borrows = std::mem::take(&mut self.borrows); - let saved_lens = std::mem::take(&mut self.lens_locked); - let saved_lens_aliases = std::mem::take(&mut self.lens_aliases); - let saved_params = std::mem::take(&mut self.current_params); - let saved_ret = self.current_return_type.clone(); - let saved_mutables = self.mutables.clone(); - - self.current_params = params.iter().map(|(n, _)| n.clone()).collect(); - self.current_return_type = return_type.clone(); - - for (name, ty) in params { - self.declare(name.clone()); - self.set_mutable(name, false); - self.types.insert(name.clone(), ty.clone()); - } - - self.update_borrow_states(); - - for stmt in body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - - // Escape check for implicit return at the end of function body - if let Some(TrackType::Ref(_)) = return_type { - let has_explicit_return = - body.iter().any(|stmt| matches!(stmt, Expr::Return { .. })); - if !has_explicit_return && let Some(last_stmt) = body.last() { - let prov = self.get_provenance(last_stmt); - for v in &prov { - if !self.current_params.contains(v) { - return Err(format!( - "Compile Error: Cannot return reference to local variable '{}' (escapes function scope).", - v - )); - } - } - } - } - - // Restore outer scope - self.registry = saved_registry; - self.types = saved_types; - self.borrows = saved_borrows; - self.lens_locked = saved_lens; - self.lens_aliases = saved_lens_aliases; - self.current_params = saved_params; - self.current_return_type = saved_ret; - self.mutables = saved_mutables; - Ok(()) - } - - Expr::Use { - path, - imports, - alias, - } => { - let norm_path = path.replace("::", "/"); - let provided = match norm_path.as_str() { - // Unified std package: `import "std"` → std::print, std::alloc, std::io::print, … - "std" => vec![ - ("print".to_string(), Some(TrackType::Void)), - ("println".to_string(), Some(TrackType::Void)), - ("eprint".to_string(), Some(TrackType::Void)), - ("read".to_string(), Some(TrackType::I64)), - ( - "alloc".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Void))), - ), - ("dealloc".to_string(), Some(TrackType::Void)), - ("exit".to_string(), Some(TrackType::Void)), - ("abort".to_string(), Some(TrackType::Void)), - ("clock_ms".to_string(), Some(TrackType::I64)), - // sub-namespaces under std:: - ("io::print".to_string(), Some(TrackType::Void)), - ("io::println".to_string(), Some(TrackType::Void)), - ("io::read".to_string(), Some(TrackType::I64)), - ("io::eprint".to_string(), Some(TrackType::Void)), - ( - "fs::file_open".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Void))), - ), - ("fs::file_close".to_string(), Some(TrackType::Void)), - ("fs::file_exists".to_string(), Some(TrackType::I32)), - ("fs::file_copy".to_string(), Some(TrackType::I32)), - ("fs::file_size".to_string(), Some(TrackType::I64)), - ("fs::dir_exists".to_string(), Some(TrackType::Bool)), - ( - "mem::alloc".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Void))), - ), - ("mem::dealloc".to_string(), Some(TrackType::Void)), - ("sys::exit".to_string(), Some(TrackType::Void)), - ("sys::abort".to_string(), Some(TrackType::Void)), - ("sys::clock_ms".to_string(), Some(TrackType::I64)), - ("char::char_is_digit".to_string(), Some(TrackType::Bool)), - ("str::str_find".to_string(), Some(TrackType::I64)), - ("process::process_spawn".to_string(), Some(TrackType::I32)), - ( - "net::net_socket_tcp_listen".to_string(), - Some(TrackType::I32), - ), - ], - "std/io" => vec![ - ("print".to_string(), Some(TrackType::Void)), - ("println".to_string(), Some(TrackType::Void)), - ("read".to_string(), Some(TrackType::I64)), - ("eprint".to_string(), Some(TrackType::Void)), - ], - "std/fs" => vec![ - ( - "file_open".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Void))), - ), - ("file_close".to_string(), Some(TrackType::Void)), - ("file_exists".to_string(), Some(TrackType::I32)), - ], - "std/sys" => vec![ - ("exit".to_string(), Some(TrackType::Void)), - ("abort".to_string(), Some(TrackType::Void)), - ("clock_ms".to_string(), Some(TrackType::I64)), - ], - "std/mem" => vec![ - ( - "alloc".to_string(), - Some(TrackType::Ptr(Box::new(TrackType::Void))), - ), - ("dealloc".to_string(), Some(TrackType::Void)), - ], - "math/vec" => vec![ - ("add".to_string(), Some(TrackType::I64)), - ("sub".to_string(), Some(TrackType::I64)), - ("dot".to_string(), Some(TrackType::I64)), - ("cross".to_string(), Some(TrackType::I64)), - ], - _ => { - // Local file import fallback — try to resolve `path` as a - // `.trk` file relative to the project. Candidates mirror - // yard's `src/` layout and the `compiler/` self-hosting - // directory. - let candidates = vec![ - format!("src/{}.trk", norm_path), - format!("{}.trk", norm_path), - format!("compiler/src/{}.trk", norm_path), - format!("compiler/{}.trk", norm_path), - format!("src/{}/mod.trk", norm_path), - ]; - let mut found: Option = None; - for cand in &candidates { - if std::path::Path::new(cand).exists() { - found = Some(cand.clone()); - break; - } - } - // Also try relative to current compiler package when - // checking from repository root: the import `token` - // inside `compiler/src/main.trk` should resolve to - // `compiler/src/token.trk` even when the candidate - // `src/token.trk` is tried first. - if found.is_none() { - for cand in &[ - format!("compiler/src/{}.trk", path), - format!("compiler/{}.trk", path), - ] { - if std::path::Path::new(cand).exists() { - found = Some(cand.clone()); - break; - } - } - } - if let Some(cand) = found { - if self.loaded_modules.contains(&cand) { - return Ok(()); - } - self.loaded_modules.insert(cand.clone()); - let src = std::fs::read_to_string(&cand).map_err(|e| { - format!("Failed to read module '{}' ({}): {}", path, cand, e) - })?; - let tokens = crate::lexer::Lexer::tokenize(&src) - .map_err(|e| format!("Lexer error in '{}': {}", cand, e))?; - let mut p = crate::parser::Parser::new(tokens, src.clone()); - let prog = p - .parse_program() - .map_err(|e| format!("Parse error in '{}': {}", cand, e))?; - // Run monomorphization then checker on the imported program - // so its types/functions become visible to the importer. - let mut prog_owned = prog; - crate::mono::monomorphize(&mut prog_owned) - .map_err(|e| format!("Monomorphize error in '{}': {}", cand, e))?; - self.check_program(&prog_owned)?; - return Ok(()); - } - return Err(format!("Compile Error: Unknown module '{}'", path)); - } - }; - - let default_ns = path.split('/').next_back().unwrap_or(path); - - if let Some(alias_name) = alias { - if let Some(items) = imports { - if items.len() == 1 { - let item_name = &items[0]; - if let Some((_, ret_ty)) = provided.iter().find(|(n, _)| n == item_name) - { - self.functions.insert(alias_name.clone(), ret_ty.clone()); - } else { - return Err(format!( - "Compile Error: Module '{}' does not export '{}'", - path, item_name - )); - } - } else { - for item_name in items { - if let Some((_, ret_ty)) = - provided.iter().find(|(n, _)| n == item_name) - { - self.functions.insert( - format!("{}::{}", alias_name, item_name), - ret_ty.clone(), - ); - } else { - return Err(format!( - "Compile Error: Module '{}' does not export '{}'", - path, item_name - )); - } - } - } - } else { - for (func_name, ret_ty) in &provided { - self.functions - .insert(format!("{}::{}", alias_name, func_name), ret_ty.clone()); - } - } - } else { - if let Some(items) = imports { - for item_name in items { - if let Some((_, ret_ty)) = provided.iter().find(|(n, _)| n == item_name) - { - self.functions.insert(item_name.clone(), ret_ty.clone()); - } else { - return Err(format!( - "Compile Error: Module '{}' does not export '{}'", - path, item_name - )); - } - } - } else { - for (func_name, ret_ty) in &provided { - self.functions - .insert(format!("{}::{}", default_ns, func_name), ret_ty.clone()); - } - } - } - Ok(()) - } - - Expr::ConstDef { name, value } => { - self.check_expr(value)?; - self.declare(name.clone()); - if let Some(ty) = self.infer_type(value) { - self.types.insert(name.clone(), ty); - } - self.update_borrow_states(); - Ok(()) - } - - Expr::MacroDef { - name, - params, - return_type, - body, - } => { - self.functions.insert(name.clone(), return_type.clone()); - - let saved_registry = std::mem::take(&mut self.registry); - let saved_types = std::mem::take(&mut self.types); - let saved_borrows = std::mem::take(&mut self.borrows); - let saved_lens = std::mem::take(&mut self.lens_locked); - let saved_lens_aliases = std::mem::take(&mut self.lens_aliases); - let saved_params = std::mem::take(&mut self.current_params); - let saved_ret = self.current_return_type.clone(); - let saved_mutables = self.mutables.clone(); - - self.current_params = params.iter().map(|(n, _)| n.clone()).collect(); - self.current_return_type = return_type.clone(); - - for (pname, pty) in params { - self.declare(pname.clone()); - self.set_mutable(pname, false); - self.types.insert(pname.clone(), pty.clone()); - } - - self.update_borrow_states(); - - for stmt in body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - - self.registry = saved_registry; - self.types = saved_types; - self.borrows = saved_borrows; - self.lens_locked = saved_lens; - self.lens_aliases = saved_lens_aliases; - self.current_params = saved_params; - self.current_return_type = saved_ret; - self.mutables = saved_mutables; - Ok(()) - } - - Expr::MacroCall { name, args, body } => { - if name == "compile_error" { - if let Some(Expr::StringLiteral(msg)) = args.first() { - return Err(format!("Compile Error: {}", msg)); - } else { - return Err( - "Compile Error: @compile_error requires a string message".to_string() - ); - } - } - - for arg in args { - self.check_expr(arg)?; - } - - if let Some(block_body) = body { - for stmt in block_body { - self.check_expr(stmt)?; - self.update_borrow_states(); - } - } - Ok(()) - } - - Expr::EnumDef { - name, - underlying_type: _, - variants, - } => { - for (var_name, val_opt) in variants { - let fullname = format!("{}::{}", name, var_name); - self.types - .insert(fullname.clone(), TrackType::Custom(name.clone())); - self.declare(fullname); - if let Some(val) = val_opt { - self.check_expr(val)?; - } - } - Ok(()) - } - - Expr::UnionDef { name, variants } => { - for (var_name, ty_opt) in variants { - let fullname = format!("{}::{}", name, var_name); - if ty_opt.is_some() { - self.functions - .insert(fullname, Some(TrackType::Custom(name.clone()))); - } else { - self.types - .insert(fullname.clone(), TrackType::Custom(name.clone())); - self.declare(fullname); - } - } - Ok(()) - } - - Expr::LetDestructure { - pattern, - mutable, - value, - } => { - self.reject_lens_escape(value)?; - self.check_expr(value)?; - let val_ty = self.infer_type(value).unwrap_or(TrackType::I32); - self.bind_pattern_variables(pattern, &val_ty, *mutable)?; - self.update_borrow_states(); - Ok(()) - } - - Expr::Match { target, arms } => { - self.check_expr(target)?; - let target_ty = self.infer_type(target).unwrap_or(TrackType::I32); - for arm in arms { - let saved_registry = self.registry.clone(); - let saved_types = self.types.clone(); - let saved_borrows = self.borrows.clone(); - let saved_lens = self.lens_locked.clone(); - let saved_lens_aliases = self.lens_aliases.clone(); - let saved_mutables = self.mutables.clone(); - - self.bind_pattern_variables(&arm.pattern, &target_ty, false)?; - - if let Some(ref guard_expr) = arm.guard { - self.check_expr(guard_expr)?; - } - - self.check_expr(&arm.body)?; - - self.registry = saved_registry; - self.types = saved_types; - self.borrows = saved_borrows; - self.lens_locked = saved_lens; - self.lens_aliases = saved_lens_aliases; - self.mutables = saved_mutables; - } - Ok(()) - } - } - } - - /// After `name = value`, the variable takes the value's type and - /// provenance. - fn assign_types(&mut self, name: &str, value: &Expr) { - if let Some(ty) = self.infer_type(value) { - self.types.insert(name.to_string(), ty.clone()); - if matches!(ty, TrackType::Ref(_)) { - let prov = self.get_provenance(value); - self.borrows.insert(name.to_string(), prov); - } else { - self.borrows.remove(name); - } - } - } - - /// Check an assignment target such as `p.x`, `t.0`, or `a[i]`: the root - /// variable must be usable and either `let mut` or a lens alias. - fn check_place(&mut self, place: &Expr) -> Result<(), String> { - match place { - Expr::FieldAccess { target, .. } | Expr::TupleIndex { target, .. } => { - self.check_place(target) - } - Expr::ArrayIndex { target, index } => { - self.check_borrow(index)?; - self.check_place(target) - } - Expr::Variable(name) => { - self.check_borrow(place)?; - if !self.mutables.contains(name) && !self.lens_aliases.contains(name) { - return Err(format!( - "Compile Error: Cannot mutate immutable variable '{}'. Use 'let mut {}' to declare a mutable variable.", - name, name - )); - } - Ok(()) - } - other => self.check_expr(other), - } - } - - fn bind_pattern_variables( - &mut self, - pattern: &crate::ast::Pattern, - target_type: &TrackType, - mutable: bool, - ) -> Result<(), String> { - match pattern { - crate::ast::Pattern::Ident(name) => { - self.declare(name.clone()); - self.types.insert(name.clone(), target_type.clone()); - self.set_mutable(name, mutable); - } - crate::ast::Pattern::Wildcard | crate::ast::Pattern::Literal(_) => {} - crate::ast::Pattern::Tuple(pats) => { - let elem_types = match target_type { - TrackType::Tuple(types) => types.clone(), - _ => vec![TrackType::I32; pats.len()], - }; - for (i, p) in pats.iter().enumerate() { - let ty = elem_types.get(i).cloned().unwrap_or(TrackType::I32); - self.bind_pattern_variables(p, &ty, mutable)?; - } - } - crate::ast::Pattern::Variant { - enum_or_union, - variant, - bindings, - } => { - for (i, p) in bindings.iter().enumerate() { - let bind_ty = match (enum_or_union.as_str(), variant.as_str(), i) { - ("Value", "Int", _) => TrackType::I32, - ("Value", "Float", _) => TrackType::I64, - ("Value", "Bool", _) => TrackType::Bool, - ("Result", "Ok", _) => TrackType::I64, - ("Result", "Err", _) => TrackType::I64, - _ => TrackType::I32, - }; - self.bind_pattern_variables(p, &bind_ty, mutable)?; - } - } - crate::ast::Pattern::Struct { fields, .. } => { - for (_fname, p) in fields { - self.bind_pattern_variables(p, &TrackType::I32, mutable)?; - } - } - } - Ok(()) - } - - /// Check an expression without consuming it (for & borrows) - fn check_borrow(&mut self, expr: &Expr) -> Result<(), String> { - match expr { - Expr::Variable(name) => { - match self.registry.get(name) { - Some(VariableState::Spent) => Err(format!( - "Compile Error: Cannot borrow spent resource '{}'.", - name - )), - Some(VariableState::Locked) => Err(format!( - "Compile Error: Cannot borrow locked resource '{}'.", - name - )), - Some(VariableState::Active) => Ok(()), // borrow, don't consume - None => Err(format!("Compile Error: Undeclared variable '{}'.", name)), - } - } - _ => self.check_expr(expr), - } - } - fn get_provenance(&self, expr: &Expr) -> Vec { - match expr { - Expr::AddressOf { target } => match target.as_ref() { - Expr::Variable(name) => vec![name.clone()], - Expr::ArrayIndex { - target: inner_target, - .. - } => self.get_provenance(inner_target), - Expr::FieldAccess { .. } => match place_root(target) { - Some(name) => vec![name.to_string()], - None => Vec::new(), - }, - _ => self.get_provenance(target), - }, - Expr::Variable(name) => { - if let Some(targets) = self.borrows.get(name) { - targets.clone() - } else if self - .types - .get(name) - .is_some_and(|t| matches!(t, TrackType::Ref(_))) - { - vec![name.clone()] - } else { - Vec::new() - } - } - Expr::FunctionCall { name: _, args } => { - let mut prov = Vec::new(); - for arg in args { - if let Some(ty) = self.infer_type(arg) - && matches!(ty, TrackType::Ref(_)) - { - prov.extend(self.get_provenance(arg)); - } - } - if prov.len() > 1 { - prov.sort(); - prov.dedup(); - } - prov - } - Expr::IfElse { - then_body, - else_body, - .. - } => { - let mut prov = Vec::new(); - if let Some(last) = then_body.last() { - prov.extend(self.get_provenance(last)); - } - if let Some(last) = else_body.last() { - prov.extend(self.get_provenance(last)); - } - if prov.len() > 1 { - prov.sort(); - prov.dedup(); - } - prov - } - Expr::LensBlock { body, .. } => body - .last() - .map_or(Vec::new(), |last| self.get_provenance(last)), - _ => Vec::new(), - } - } - - fn reject_lens_escape(&self, expr: &Expr) -> Result<(), String> { - if let Some(name) = self.find_lens_alias(expr) { - Err(format!( - "Compile Error: Lens '{}' cannot be moved, stored, returned, or escape its with block.", - name - )) - } else { - Ok(()) - } - } - - fn find_lens_alias(&self, expr: &Expr) -> Option { - if self.lens_aliases.is_empty() { - return None; - } - match expr { - Expr::Variable(name) if self.lens_aliases.contains(name) => Some(name.clone()), - Expr::BinaryOp { left, right, .. } => self - .find_lens_alias(left) - .or_else(|| self.find_lens_alias(right)), - Expr::UnaryOp { expr, .. } | Expr::AddressOf { target: expr } => { - self.find_lens_alias(expr) - } - Expr::ArrayLiteral { elements } => { - elements.iter().find_map(|e| self.find_lens_alias(e)) - } - Expr::ArrayIndex { target, index } => self - .find_lens_alias(target) - .or_else(|| self.find_lens_alias(index)), - Expr::SliceIndex { target, start, end } => self - .find_lens_alias(target) - .or_else(|| start.as_deref().and_then(|s| self.find_lens_alias(s))) - .or_else(|| end.as_deref().and_then(|e| self.find_lens_alias(e))), - Expr::Range { start, end } => self - .find_lens_alias(start) - .or_else(|| self.find_lens_alias(end)), - Expr::StructInitialization { fields, .. } => fields - .iter() - .find_map(|(_, value)| self.find_lens_alias(value)), - Expr::IfElse { - condition, - then_body, - else_body, - } => self - .find_lens_alias(condition) - .or_else(|| then_body.iter().find_map(|e| self.find_lens_alias(e))) - .or_else(|| else_body.iter().find_map(|e| self.find_lens_alias(e))), - Expr::WhileLoop { condition, body } => self - .find_lens_alias(condition) - .or_else(|| body.iter().find_map(|e| self.find_lens_alias(e))), - Expr::Return { value } => value.as_deref().and_then(|v| self.find_lens_alias(v)), - Expr::Assign { target, value } => self - .find_lens_alias(target) - .or_else(|| self.find_lens_alias(value)), - Expr::LetDef { value, .. } - | Expr::ConstDef { value, .. } - | Expr::LetDestructure { value, .. } => self.find_lens_alias(value), - Expr::TupleLiteral { elements } => { - elements.iter().find_map(|e| self.find_lens_alias(e)) - } - Expr::TupleIndex { target, .. } => self.find_lens_alias(target), - // Reading a field yields the field's value, not the lens itself. - Expr::FieldAccess { .. } => None, - Expr::FunctionCall { .. } => None, - Expr::MacroCall { args, body, .. } => args - .iter() - .find_map(|arg| self.find_lens_alias(arg)) - .or_else(|| { - body.as_ref() - .and_then(|body| body.iter().find_map(|e| self.find_lens_alias(e))) - }), - Expr::LensBlock { body, .. } => body.iter().find_map(|e| self.find_lens_alias(e)), - Expr::Match { target, arms } => self.find_lens_alias(target).or_else(|| { - arms.iter().find_map(|arm| { - arm.guard - .as_ref() - .and_then(|guard| self.find_lens_alias(guard)) - .or_else(|| self.find_lens_alias(&arm.body)) - }) - }), - Expr::IntLiteral(_) - | Expr::StringLiteral(_) - | Expr::BoolLiteral(_) - | Expr::FnDef { .. } - | Expr::Use { .. } - | Expr::MacroDef { .. } - | Expr::EnumDef { .. } - | Expr::UnionDef { .. } - | Expr::TypeAlias { .. } - | Expr::StructDef { .. } - | Expr::ForIn { .. } - | Expr::Variable(_) => None, - } - } -} - -/// The variable at the base of `a.b.0[i]`, if any. -fn place_root(expr: &Expr) -> Option<&str> { - match expr { - Expr::Variable(name) => Some(name), - Expr::FieldAccess { target, .. } - | Expr::TupleIndex { target, .. } - | Expr::ArrayIndex { target, .. } => place_root(target), - _ => None, - } -} - -fn is_comparison(op: &BinOp) -> bool { - matches!( - op, - BinOp::Eq | BinOp::Neq | BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte - ) -} - -#[allow(clippy::needless_range_loop)] -fn levenshtein_distance(a: &str, b: &str) -> usize { - let a_chars: Vec = a.chars().collect(); - let b_chars: Vec = b.chars().collect(); - let mut distances = vec![vec![0; b_chars.len() + 1]; a_chars.len() + 1]; - - for i in 0..=a_chars.len() { - distances[i][0] = i; - } - for j in 0..=b_chars.len() { - distances[0][j] = j; - } - - for i in 1..=a_chars.len() { - for j in 1..=b_chars.len() { - let cost = if a_chars[i - 1] == b_chars[j - 1] { - 0 - } else { - 1 - }; - distances[i][j] = (distances[i - 1][j] + 1) - .min(distances[i][j - 1] + 1) - .min(distances[i - 1][j - 1] + cost); - } - } - - distances[a_chars.len()][b_chars.len()] -} - -/// A constant whose `/` or `%` has known operands that trap at run time -/// (a zero divisor, INT64_MIN / -1) is E0200, with trackc's text. -fn const_divrem_ok(consts: &HashMap, expr: &Expr) -> Result<(), String> { - match expr { - Expr::UnaryOp { expr, .. } => const_divrem_ok(consts, expr), - Expr::BinaryOp { op, left, right } => { - const_divrem_ok(consts, left)?; - const_divrem_ok(consts, right)?; - if !matches!(op, BinOp::Div | BinOp::Mod) { - return Ok(()); - } - let eval = crate::codegen::eval_const; - match (eval(consts, left), eval(consts, right)) { - (Some(_), Some(0)) => { - Err("error[E0200]: division by zero in a constant expression".to_string()) - } - (Some(i64::MIN), Some(-1)) => { - Err("error[E0200]: division overflow in a constant expression".to_string()) - } - _ => Ok(()), - } - } - _ => Ok(()), - } -} diff --git a/src/codegen/mod.rs b/src/codegen/mod.rs deleted file mode 100644 index 6012e1dd..00000000 --- a/src/codegen/mod.rs +++ /dev/null @@ -1,1581 +0,0 @@ -//! Cranelift backend for the Rust bootstrap compiler. -//! -//! Every Track value is lowered to a single 64-bit machine word (the "word -//! ABI"): integers and booleans are sign/zero-normalised `i64`s, strings are -//! `char*` pointers, and tuples / tagged-union cells are pointers to arrays of -//! words. All Track functions take and return words, which keeps calls across -//! separately compiled modules well defined and matches the portable C backend -//! of the self-hosted compiler (`compiler/src/cgen.trk`) bit for bit. - -use std::collections::{HashMap, HashSet}; -use std::fs; -use std::path::Path; -use std::sync::Arc; - -use cranelift_codegen::ir::{ - self, AbiParam, InstBuilder, StackSlotData, StackSlotKind, Value, condcodes::IntCC, -}; -use cranelift_codegen::isa; -use cranelift_codegen::settings::{self, Configurable}; -use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable}; -use cranelift_module::{FuncId, Linkage, Module, default_libcall_names}; -use cranelift_object::{ObjectBuilder, ObjectModule}; -use target_lexicon::Triple; - -use crate::ast::{BinOp, Expr, Pattern, TrackType, UnaryOp}; - -const W: ir::Type = ir::types::I64; - -/// Type knowledge gathered by the checker across a module and everything it -/// imports. Codegen compiles one file at a time, so enum/union layouts and -/// type aliases defined in imported modules arrive through this table. -#[derive(Debug, Clone, Default)] -pub struct TypeInfo { - /// `Enum::Variant` / `Union::Variant` → discriminant. - pub variants: HashMap, - /// Unions with at least one payload variant; their values are heap cells - /// laid out as `[tag, payload...]`. - pub payload_unions: HashSet, - pub aliases: HashMap, - /// Integer constants, including those defined in imported modules. - pub consts: HashMap, - /// Struct name → field names in declaration order. - pub structs: HashMap>, -} - -pub struct CodeGen { - module_name: String, - module: ObjectModule, - fn_builder_ctx: FunctionBuilderContext, - functions: HashMap, - info: TypeInfo, - consts: HashMap, -} - -/// Evaluate a compile-time constant expression (integer literals, negation, -/// and arithmetic over known constants). -pub fn eval_const(consts: &HashMap, expr: &Expr) -> Option { - match expr { - Expr::IntLiteral(v) => Some(*v), - Expr::BoolLiteral(b) => Some(if *b { 1 } else { 0 }), - Expr::UnaryOp { - op: UnaryOp::Neg, - expr, - } => eval_const(consts, expr).map(|v| v.wrapping_neg()), - Expr::UnaryOp { - op: UnaryOp::Not, - expr, - } => eval_const(consts, expr).map(|v| (v == 0) as i64), - Expr::BinaryOp { op, left, right } => { - let l = eval_const(consts, left)?; - let r = eval_const(consts, right)?; - match op { - BinOp::Add => Some(l.wrapping_add(r)), - BinOp::Sub => Some(l.wrapping_sub(r)), - BinOp::Mul => Some(l.wrapping_mul(r)), - // 0 and INT64_MIN / -1 trap at run time: no folded value. - BinOp::Div => l.checked_div(r), - BinOp::Mod => l.checked_rem(r), - BinOp::BitAnd => Some(l & r), - BinOp::BitOr => Some(l | r), - BinOp::Shl => Some(l.wrapping_shl((r & 63) as u32)), - BinOp::Shr => Some(((l as u64) >> (r & 63)) as i64), - // Comparisons and logic fold to 0/1, as symbols.trk const_eval. - BinOp::Eq => Some((l == r) as i64), - BinOp::Neq => Some((l != r) as i64), - BinOp::Lt => Some((l < r) as i64), - BinOp::Gt => Some((l > r) as i64), - BinOp::Lte => Some((l <= r) as i64), - BinOp::Gte => Some((l >= r) as i64), - BinOp::And => Some((l != 0 && r != 0) as i64), - BinOp::Or => Some((l != 0 || r != 0) as i64), - } - } - Expr::Variable(name) => consts.get(name).copied(), - _ => None, - } -} - -/// Whether `expr` reads a name bound as a local, in the shapes eval_const -/// folds (it folds nothing else). -fn mentions_local(expr: &Expr, locals: &HashMap) -> bool { - match expr { - Expr::Variable(name) => locals.contains_key(name), - Expr::UnaryOp { expr, .. } => mentions_local(expr, locals), - Expr::BinaryOp { left, right, .. } => { - mentions_local(left, locals) || mentions_local(right, locals) - } - _ => false, - } -} - -/// Assign discriminants to enum variants: an explicit `= value` sets the -/// discriminant, otherwise it is one more than the previous variant. -pub fn enum_discriminants( - consts: &HashMap, - variants: &[(String, Option)], -) -> Vec<(String, i64)> { - let mut next = 0i64; - variants - .iter() - .map(|(name, value)| { - let disc = value - .as_ref() - .and_then(|v| eval_const(consts, v)) - .unwrap_or(next); - next = disc.wrapping_add(1); - (name.clone(), disc) - }) - .collect() -} - -/// Runtime tag stored in word 0 of every struct value: FNV-1a over the -/// name with 64-bit wrapping (identical in the self-hosted compiler). -pub fn struct_tag(name: &str) -> i64 { - let mut h: i64 = 2166136261; - for b in name.bytes() { - h ^= i64::from(b); - h = h.wrapping_mul(16777619); - } - h -} - -/// Number of words in a tuple type, resolving aliases. -fn tuple_len(aliases: &HashMap, ty: &TrackType) -> Option { - let mut current = ty; - for _ in 0..16 { - match current { - TrackType::Tuple(elems) => return Some(elems.len()), - TrackType::Custom(name) => current = aliases.get(name)?, - _ => return None, - } - } - None -} - -impl CodeGen { - pub fn create_default_isa() -> Arc { - let mut flag_builder = settings::builder(); - // Position-independent, linked as PIE: the heap then sits far above - // any integer a program prints, so the runtime's `print` (which - // prints a word that points at readable text as a string) cannot - // mistake a count for a heap string. Non-PIE put the brk heap a - // random 0..32 MiB above the image, where counts like 25988585 live. - flag_builder.set("is_pic", "true").unwrap(); - flag_builder.set("opt_level", "speed").unwrap(); - // More aggressive opts for near-native speed - let _ = flag_builder.set("regalloc_algorithm", "backtracking"); - let _ = flag_builder.set("enable_alias_analysis", "true"); - let _ = flag_builder.set("enable_verifier", "false"); - let isa_flags = settings::Flags::new(flag_builder); - - isa::lookup(Triple::host()) - .unwrap() - .finish(isa_flags) - .unwrap() - } - - pub fn new(module_name: &str) -> Self { - Self::new_with_isa(module_name, Self::create_default_isa()) - } - - pub fn new_with_isa(module_name: &str, isa: Arc) -> Self { - let object_builder = ObjectBuilder::new(isa, module_name, default_libcall_names()).unwrap(); - let module = ObjectModule::new(object_builder); - - Self { - module_name: module_name.to_string(), - module, - fn_builder_ctx: FunctionBuilderContext::new(), - functions: HashMap::new(), - info: TypeInfo::default(), - consts: HashMap::new(), - } - } - - /// Provide enum/union layouts and aliases discovered by the checker - /// (including imported modules). - pub fn set_type_info(&mut self, info: TypeInfo) { - self.consts - .extend(info.consts.iter().map(|(k, v)| (k.clone(), *v))); - self.info = info; - } - - fn signature( - &self, - name: &str, - params: &[(String, TrackType)], - ret: Option<&TrackType>, - ) -> ir::Signature { - let mut sig = self.module.make_signature(); - if name == "main" { - if params.is_empty() { - // C entry point: int main(int argc, char **argv) - sig.params.push(AbiParam::new(ir::types::I32)); - sig.params.push(AbiParam::new(W)); - } else { - for _ in params { - sig.params.push(AbiParam::new(W)); - } - } - sig.returns.push(AbiParam::new(ir::types::I32)); - return sig; - } - for _ in params { - sig.params.push(AbiParam::new(W)); - } - if let Some(rty) = ret - && *rty != TrackType::Void - { - sig.returns.push(AbiParam::new(W)); - } - sig - } - - pub fn compile_program(&mut self, program: &[Expr]) { - // First pass: constants, type layouts, and function declarations. - for expr in program { - match expr { - Expr::ConstDef { name, value } => { - if let Some(v) = eval_const(&self.consts, value) { - self.consts.insert(name.clone(), v); - } - } - Expr::TypeAlias { name, target } => { - self.info.aliases.insert(name.clone(), target.clone()); - } - Expr::StructDef { name, fields } => { - self.info.structs.insert( - name.clone(), - fields.iter().map(|(f, _)| f.clone()).collect(), - ); - } - Expr::EnumDef { name, variants, .. } => { - for (vname, disc) in enum_discriminants(&self.consts, variants) { - // A unit variant is a constant to later constants. - self.consts.insert(format!("{}::{}", name, vname), disc); - self.info - .variants - .insert(format!("{}::{}", name, vname), disc); - } - } - Expr::UnionDef { name, variants } => { - for (idx, (vname, ty)) in variants.iter().enumerate() { - self.info - .variants - .insert(format!("{}::{}", name, vname), idx as i64); - if ty.is_some() { - self.info.payload_unions.insert(name.clone()); - } - } - } - Expr::FnDef { - name, - generics, - params, - return_type, - .. - } => { - // Generic templates are never emitted — only their - // monomorphized instances (which have empty `generics`). - if !generics.is_empty() { - continue; - } - self.declare_track_fn(name, params, return_type.as_ref()); - } - Expr::MacroDef { - name, - params, - return_type, - .. - } => { - self.declare_track_fn(name, params, return_type.as_ref()); - } - _ => {} - } - } - - let mut has_main = false; - - // Second pass: define function bodies - for expr in program { - match expr { - Expr::FnDef { - name, - generics, - params, - return_type, - body, - } if generics.is_empty() => { - has_main |= name == "main"; - let func_id = self.functions[name.as_str()]; - self.compile_fn(func_id, name, params, return_type.as_ref(), body, program); - } - Expr::MacroDef { - name, - params, - return_type, - body, - } => { - has_main |= name == "main"; - let func_id = self.functions[name.as_str()]; - self.compile_fn(func_id, name, params, return_type.as_ref(), body, program); - } - _ => {} - } - } - - // Synthesize C main wrapper if needed (only for entry point modules) - if !has_main - && (self.module_name == "main" - || self.module_name == "track_module" - || self.module_name.ends_with("main")) - { - self.compile_fn_inner(None, "main", &[], None, &[], program); - } - } - - fn declare_track_fn( - &mut self, - name: &str, - params: &[(String, TrackType)], - ret: Option<&TrackType>, - ) { - let sig = self.signature(name, params, ret); - let func_id = self - .module - .declare_function(name, Linkage::Export, &sig) - .unwrap_or_else(|_| self.module.declare_anonymous_function(&sig).unwrap()); - self.functions.insert(name.to_string(), func_id); - } - - fn compile_fn( - &mut self, - func_id: FuncId, - name: &str, - params: &[(String, TrackType)], - return_type: Option<&TrackType>, - body: &[Expr], - program: &[Expr], - ) { - self.compile_fn_inner(Some(func_id), name, params, return_type, body, program); - } - - fn compile_fn_inner( - &mut self, - func_id: Option, - name: &str, - params: &[(String, TrackType)], - return_type: Option<&TrackType>, - body: &[Expr], - program: &[Expr], - ) { - let is_main = name == "main"; - let sig = self.signature(name, params, return_type); - let func_id = match func_id { - Some(id) => id, - None => self - .module - .declare_function("main", Linkage::Export, &sig) - .unwrap(), - }; - let mut ctx = self.module.make_context(); - ctx.func.signature = sig; - let returns_value = is_main || return_type.is_some_and(|rty| *rty != TrackType::Void); - - let mut builder = FunctionBuilder::new(&mut ctx.func, &mut self.fn_builder_ctx); - let entry_block = builder.create_block(); - builder.append_block_params_for_function_params(entry_block); - builder.switch_to_block(entry_block); - - let mut fn_ctx = FnContext { - var_map: HashMap::new(), - var_counter: 0, - functions: &mut self.functions, - info: &self.info, - consts: &self.consts, - filled: false, - is_main, - returns_value, - stack_tuples: HashMap::new(), - tuple_params: HashMap::new(), - }; - - if is_main && params.is_empty() { - // Publish argc/argv to the runtime before any user code runs. - let argc = builder.block_params(entry_block)[0]; - let argv = builder.block_params(entry_block)[1]; - let argc = builder.ins().sextend(W, argc); - fn_ctx.call_named( - &mut builder, - &mut self.module, - "track_runtime_init", - &[argc, argv], - ); - } else { - for (idx, (pname, pty)) in params.iter().enumerate() { - let var = fn_ctx.new_var(); - builder.declare_var(var, W); - let val = builder.block_params(entry_block)[idx]; - builder.def_var(var, val); - fn_ctx.var_map.insert(pname.clone(), var); - if let Some(n) = tuple_len(&self.info.aliases, pty) { - fn_ctx.tuple_params.insert(pname.clone(), n); - } - } - } - - // Top-level statements (global lets) run at the start of main. - if is_main { - for top_stmt in program { - if fn_ctx.filled { - break; - } - if !matches!(top_stmt, Expr::FnDef { .. } | Expr::MacroDef { .. }) { - fn_ctx.compile_expr(&mut builder, &mut self.module, top_stmt); - } - } - } - - let last_val = fn_ctx.compile_block(&mut builder, &mut self.module, body); - - if !fn_ctx.filled { - if is_main { - let zero = builder.ins().iconst(ir::types::I32, 0); - builder.ins().return_(&[zero]); - } else if returns_value { - let v = last_val.unwrap_or_else(|| builder.ins().iconst(W, 0)); - builder.ins().return_(&[v]); - } else { - builder.ins().return_(&[]); - } - } - - builder.seal_all_blocks(); - builder.finalize(); - self.module.define_function(func_id, &mut ctx).unwrap(); - self.module.clear_context(&mut ctx); - } - - pub fn write_object_file(self, output_path: &Path) -> Result<(), String> { - let product = self.module.finish(); - let bytes = product - .emit() - .map_err(|e| format!("Failed to emit Cranelift object module: {}", e))?; - fs::write(output_path, bytes).map_err(|e| { - format!( - "Failed to write object file '{}': {}", - output_path.display(), - e - ) - }) - } -} - -struct Scope { - vars: HashMap, - stack_tuples: HashMap, - tuple_params: HashMap, -} - -struct FnContext<'a> { - var_map: HashMap, - var_counter: u32, - functions: &'a mut HashMap, - info: &'a TypeInfo, - consts: &'a HashMap, - /// The current block already ends in a terminator; further statements in - /// the same lexical block are unreachable and skipped. - filled: bool, - is_main: bool, - returns_value: bool, - /// Locals bound directly to a tuple literal live in a stack slot and must - /// be copied to the heap when returned. - stack_tuples: HashMap, - tuple_params: HashMap, -} - -impl<'a> FnContext<'a> { - fn new_var(&mut self) -> Variable { - let var = Variable::from_u32(self.var_counter); - self.var_counter += 1; - var - } - - fn switch_to(&mut self, builder: &mut FunctionBuilder, block: ir::Block) { - builder.switch_to_block(block); - self.filled = false; - } - - fn jump(&mut self, builder: &mut FunctionBuilder, block: ir::Block, args: &[Value]) { - if !self.filled { - builder.ins().jump(block, args); - self.filled = true; - } - } - - /// `lhs / rhs` (or `%`) with trackc's trap semantics: a zero divisor or - /// `INT64_MIN / -1` calls `track_trap_div`, which flushes stdout and - /// raises SIGFPE (Cranelift's own sdiv trap is a SIGILL that loses the - /// buffered output). A known divisor other than 0 and -1 needs no check; - /// otherwise one unsigned compare, `rhs + 1 <= 1`, guards the fast path. - fn checked_divrem( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - is_div: bool, - lhs: Value, - rhs: Value, - divisor: Option, - ) -> Value { - let op = |builder: &mut FunctionBuilder| { - if is_div { - builder.ins().sdiv(lhs, rhs) - } else { - builder.ins().srem(lhs, rhs) - } - }; - if divisor.is_some_and(|d| d != 0 && d != -1) { - return op(builder); - } - let rare_block = builder.create_block(); - let neg_block = builder.create_block(); - let trap_block = builder.create_block(); - let fast_block = builder.create_block(); - let merge = builder.create_block(); - let result = builder.append_block_param(merge, W); - builder.set_cold_block(rare_block); - builder.set_cold_block(neg_block); - builder.set_cold_block(trap_block); - - let biased = builder.ins().iadd_imm(rhs, 1); - let rare = builder - .ins() - .icmp_imm(IntCC::UnsignedLessThanOrEqual, biased, 1); - builder.ins().brif(rare, rare_block, &[], fast_block, &[]); - self.filled = true; - - // rhs is 0 or -1: trap on 0 and on INT64_MIN / -1. - self.switch_to(builder, rare_block); - let zero = builder.ins().icmp_imm(IntCC::Equal, rhs, 0); - let min = builder.ins().icmp_imm(IntCC::Equal, lhs, i64::MIN); - let bad = builder.ins().bor(zero, min); - builder.ins().brif(bad, trap_block, &[], neg_block, &[]); - self.filled = true; - - // x / -1 == -x and x % -1 == 0 for every other x. - self.switch_to(builder, neg_block); - let v = if is_div { - builder.ins().ineg(lhs) - } else { - builder.ins().iconst(W, 0) - }; - self.jump(builder, merge, &[v]); - - self.switch_to(builder, trap_block); - let t = self - .call_named(builder, module, "track_trap_div", &[]) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - self.jump(builder, merge, &[t]); - - self.switch_to(builder, fast_block); - let v = op(builder); - self.jump(builder, merge, &[v]); - - self.switch_to(builder, merge); - result - } - - /// Normalise a value to a full word (booleans and narrow parameters). - fn word(&self, builder: &mut FunctionBuilder, v: Value) -> Value { - let ty = builder.func.dfg.value_type(v); - if ty == W { - v - } else if ty == ir::types::I32 { - builder.ins().sextend(W, v) - } else { - builder.ins().uextend(W, v) - } - } - - fn bool_word(&self, builder: &mut FunctionBuilder, cc: IntCC, a: Value, b: Value) -> Value { - let c = builder.ins().icmp(cc, a, b); - builder.ins().uextend(W, c) - } - - fn zero(&self, builder: &mut FunctionBuilder) -> Value { - builder.ins().iconst(W, 0) - } - - fn func_ref( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - name: &str, - argc: usize, - ) -> ir::FuncRef { - let func_id = if let Some(&fid) = self.functions.get(name) { - fid - } else { - let mut sig = module.make_signature(); - for _ in 0..argc { - sig.params.push(AbiParam::new(W)); - } - sig.returns.push(AbiParam::new(W)); - let fid = module - .declare_function(name, Linkage::Import, &sig) - .unwrap_or_else(|_| module.declare_anonymous_function(&sig).unwrap()); - self.functions.insert(name.to_string(), fid); - fid - }; - module.declare_func_in_func(func_id, builder.func) - } - - /// Call a function by symbol name with word arguments, adapting to the - /// declared signature of locally defined functions. - fn call_named( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - name: &str, - args: &[Value], - ) -> Option { - let local_func = self.func_ref(builder, module, name, args.len()); - let sig_ref = builder.func.dfg.ext_funcs[local_func].signature; - let expected: Vec = builder.func.dfg.signatures[sig_ref] - .params - .iter() - .map(|p| p.value_type) - .collect(); - let mut fixed_args = Vec::with_capacity(expected.len()); - for (idx, &ty) in expected.iter().enumerate() { - let arg = match args.get(idx) { - Some(&a) => self.word(builder, a), - None => self.zero(builder), - }; - fixed_args.push(if ty == W { - arg - } else { - builder.ins().ireduce(ty, arg) - }); - } - let call_inst = builder.ins().call(local_func, &fixed_args); - let results = builder.inst_results(call_inst); - results.first().copied().map(|r| self.word(builder, r)) - } - - fn alloc_words( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - words: &[Value], - ) -> Value { - let size = builder.ins().iconst(W, (words.len().max(1) * 8) as i64); - let ptr = self - .call_named(builder, module, "alloc", &[size]) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - for (i, &val) in words.iter().enumerate() { - builder - .ins() - .store(ir::MemFlags::new(), val, ptr, (i * 8) as i32); - } - ptr - } - - fn copy_words_to_heap( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - src: Value, - count: usize, - ) -> Value { - let words: Vec = (0..count) - .map(|i| { - builder - .ins() - .load(W, ir::MemFlags::new(), src, (i * 8) as i32) - }) - .collect(); - self.alloc_words(builder, module, &words) - } - - /// (tag, field index) of every struct declaring `field`, by struct name. - fn field_candidates(&self, field: &str) -> Vec<(i64, usize)> { - let mut names: Vec<&String> = self.info.structs.keys().collect(); - names.sort(); - names - .into_iter() - .filter_map(|name| { - self.info.structs[name] - .iter() - .position(|f| f == field) - .map(|idx| (struct_tag(name), idx)) - }) - .collect() - } - - /// Load (`store == None`) or store a struct field. A field name shared - /// by several structs dispatches on the tag in word 0. - fn field_access( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - ptr: Value, - field: &str, - store: Option, - ) -> Value { - let candidates = self.field_candidates(field); - let access = |builder: &mut FunctionBuilder, idx: usize| -> Value { - let offset = ((idx + 1) * 8) as i32; - match store { - Some(v) => { - builder.ins().store(ir::MemFlags::new(), v, ptr, offset); - v - } - None => builder.ins().load(W, ir::MemFlags::new(), ptr, offset), - } - }; - if candidates.len() == 1 { - return access(builder, candidates[0].1); - } - let merge = builder.create_block(); - let result = builder.append_block_param(merge, W); - let tag = builder.ins().load(W, ir::MemFlags::new(), ptr, 0); - for (expected, idx) in candidates { - let hit = builder.create_block(); - let miss = builder.create_block(); - let want = builder.ins().iconst(W, expected); - let is_hit = builder.ins().icmp(IntCC::Equal, tag, want); - builder.ins().brif(is_hit, hit, &[], miss, &[]); - self.filled = true; - self.switch_to(builder, hit); - let v = access(builder, idx); - self.jump(builder, merge, &[v]); - self.switch_to(builder, miss); - } - let bad = self - .call_named(builder, module, "track_bad_field", &[]) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - self.jump(builder, merge, &[bad]); - self.switch_to(builder, merge); - result - } - - fn compile_block( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - stmts: &[Expr], - ) -> Option { - // Bindings introduced inside a block go out of scope at its end. - let scope = self.enter_scope(); - let mut last = None; - for stmt in stmts { - if self.filled { - break; - } - last = self.compile_expr(builder, module, stmt); - } - self.exit_scope(scope); - last - } - - fn enter_scope(&self) -> Scope { - Scope { - vars: self.var_map.clone(), - stack_tuples: self.stack_tuples.clone(), - tuple_params: self.tuple_params.clone(), - } - } - - fn exit_scope(&mut self, scope: Scope) { - self.var_map = scope.vars; - self.stack_tuples = scope.stack_tuples; - self.tuple_params = scope.tuple_params; - } - - fn variant_key(&self, name: &str) -> Option { - self.info.variants.get(name).copied() - } - - fn is_payload_variant(&self, name: &str) -> bool { - name.split("::") - .next() - .is_some_and(|u| self.info.payload_unions.contains(u)) - } - - fn compile_expr( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - expr: &Expr, - ) -> Option { - if self.filled { - return None; - } - match expr { - Expr::IntLiteral(val) => Some(builder.ins().iconst(W, *val)), - - Expr::BoolLiteral(val) => Some(builder.ins().iconst(W, if *val { 1 } else { 0 })), - - Expr::StringLiteral(s) => { - let mut data_ctx = cranelift_module::DataDescription::new(); - let mut bytes = s.as_bytes().to_vec(); - bytes.push(0); // null terminate - data_ctx.define(bytes.into_boxed_slice()); - - let data_id = module.declare_anonymous_data(true, false).unwrap(); - module.define_data(data_id, &data_ctx).unwrap(); - - let local_data = module.declare_data_in_func(data_id, builder.func); - Some(builder.ins().symbol_value(W, local_data)) - } - - Expr::Variable(name) => { - if let Some(&var) = self.var_map.get(name) { - Some(builder.use_var(var)) - } else if name.contains("::") { - let disc = self.variant_key(name).unwrap_or(0); - let tag = builder.ins().iconst(W, disc); - if self.is_payload_variant(name) { - let zero = self.zero(builder); - Some(self.alloc_words(builder, module, &[tag, zero])) - } else { - Some(tag) - } - } else if let Some(&c) = self.consts.get(name) { - Some(builder.ins().iconst(W, c)) - } else { - None - } - } - - Expr::LetDef { name, value, .. } => { - let val = self - .compile_expr(builder, module, value) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - let var = self.new_var(); - builder.declare_var(var, W); - builder.def_var(var, val); - self.var_map.insert(name.clone(), var); - self.track_tuple_binding(name, value); - Some(val) - } - - Expr::Assign { target, value } => { - let val = self.compile_expr(builder, module, value)?; - let val = self.word(builder, val); - match &**target { - Expr::Variable(name) => { - if let Some(&var) = self.var_map.get(name) { - builder.def_var(var, val); - self.track_tuple_binding(name, value); - } - } - Expr::FieldAccess { target, field } => { - let ptr = self.compile_expr(builder, module, target)?; - self.field_access(builder, module, ptr, field, Some(val)); - } - Expr::TupleIndex { target, index } => { - let ptr = self.compile_expr(builder, module, target)?; - builder - .ins() - .store(ir::MemFlags::new(), val, ptr, (*index * 8) as i32); - } - Expr::ArrayIndex { target, index } => { - let arr = self.compile_expr(builder, module, target)?; - let idx = self.compile_expr(builder, module, index)?; - self.call_named(builder, module, "track_array_set", &[arr, idx, val]); - } - _ => {} - } - Some(val) - } - - Expr::BinaryOp { - op: op @ (BinOp::And | BinOp::Or), - left, - right, - } => { - // Short-circuit evaluation; result is a normalised 0/1 word. - let lhs = self.compile_expr(builder, module, left)?; - let zero = self.zero(builder); - let lhs_bool = self.bool_word(builder, IntCC::NotEqual, lhs, zero); - let rhs_block = builder.create_block(); - let merge = builder.create_block(); - let result = builder.append_block_param(merge, W); - if *op == BinOp::And { - builder - .ins() - .brif(lhs_bool, rhs_block, &[], merge, &[lhs_bool]); - } else { - builder - .ins() - .brif(lhs_bool, merge, &[lhs_bool], rhs_block, &[]); - } - self.filled = true; - self.switch_to(builder, rhs_block); - let rhs = self - .compile_expr(builder, module, right) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if !self.filled { - let zero = self.zero(builder); - let rhs_bool = self.bool_word(builder, IntCC::NotEqual, rhs, zero); - self.jump(builder, merge, &[rhs_bool]); - } - self.switch_to(builder, merge); - Some(result) - } - - Expr::BinaryOp { op, left, right } => { - let lhs = self.compile_expr(builder, module, left)?; - let rhs = self.compile_expr(builder, module, right)?; - let lhs = self.word(builder, lhs); - let rhs = self.word(builder, rhs); - - let res = match op { - BinOp::Add => builder.ins().iadd(lhs, rhs), - BinOp::Sub => builder.ins().isub(lhs, rhs), - BinOp::Mul => builder.ins().imul(lhs, rhs), - BinOp::Div | BinOp::Mod => { - // A local or parameter shadows a constant of the same - // name: such a divisor is only known at run time. - let divisor = if mentions_local(right, &self.var_map) { - None - } else { - eval_const(self.consts, right) - }; - self.checked_divrem(builder, module, *op == BinOp::Div, lhs, rhs, divisor) - } - BinOp::Eq => self.bool_word(builder, IntCC::Equal, lhs, rhs), - BinOp::Neq => self.bool_word(builder, IntCC::NotEqual, lhs, rhs), - BinOp::Lt => self.bool_word(builder, IntCC::SignedLessThan, lhs, rhs), - BinOp::Gt => self.bool_word(builder, IntCC::SignedGreaterThan, lhs, rhs), - BinOp::Lte => self.bool_word(builder, IntCC::SignedLessThanOrEqual, lhs, rhs), - BinOp::Gte => { - self.bool_word(builder, IntCC::SignedGreaterThanOrEqual, lhs, rhs) - } - BinOp::BitAnd => builder.ins().band(lhs, rhs), - BinOp::BitOr => builder.ins().bor(lhs, rhs), - BinOp::Shl => builder.ins().ishl(lhs, rhs), - BinOp::Shr => builder.ins().ushr(lhs, rhs), - BinOp::And | BinOp::Or => unreachable!(), - }; - Some(res) - } - - Expr::UnaryOp { op, expr } => { - let val = self.compile_expr(builder, module, expr)?; - let val = self.word(builder, val); - match op { - UnaryOp::Neg => Some(builder.ins().ineg(val)), - // Logical NOT: (val == 0). Bitwise bnot would turn 1 into -2, - // which is still truthy and inverts branch semantics. - UnaryOp::Not => { - let zero = self.zero(builder); - Some(self.bool_word(builder, IntCC::Equal, val, zero)) - } - UnaryOp::Deref => Some(val), - } - } - - Expr::AddressOf { target } => self.compile_expr(builder, module, target), - - Expr::FunctionCall { name, args } | Expr::MacroCall { name, args, .. } => { - let mut arg_vals = Vec::new(); - for arg in args { - let v = self - .compile_expr(builder, module, arg) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - arg_vals.push(v); - } - - let clean_name = name.trim_start_matches('@'); - - // Variant constructors: `Union::Variant(payload...)`. - if clean_name.contains("::") - && let Some(disc) = self.variant_key(clean_name) - { - let tag = builder.ins().iconst(W, disc); - if self.is_payload_variant(clean_name) { - let mut words = vec![tag]; - words.extend(arg_vals.iter().map(|&v| self.word(builder, v))); - return Some(self.alloc_words(builder, module, &words)); - } - return Some(tag); - } - - let mut target_name = if clean_name.contains("::") { - clean_name.rsplit("::").next().unwrap() - } else { - clean_name - }; - // Map Track-level builtin names to their C runtime symbols. - if target_name == "abort" { - target_name = "track_abort"; - } - let symbol = if self.functions.contains_key(name) { - name.as_str() - } else if self.functions.contains_key(clean_name) { - clean_name - } else { - target_name - }; - self.call_named(builder, module, symbol, &arg_vals) - } - - Expr::IfElse { - condition, - then_body, - else_body, - } => { - let cond_val = self.compile_expr(builder, module, condition)?; - let cond_val = self.word(builder, cond_val); - - let then_block = builder.create_block(); - let else_block = builder.create_block(); - let merge_block = builder.create_block(); - let result = builder.append_block_param(merge_block, W); - - builder - .ins() - .brif(cond_val, then_block, &[], else_block, &[]); - self.filled = true; - - self.switch_to(builder, then_block); - let then_val = self.compile_block(builder, module, then_body); - if !self.filled { - let v = match then_val { - Some(v) => self.word(builder, v), - None => self.zero(builder), - }; - self.jump(builder, merge_block, &[v]); - } - - self.switch_to(builder, else_block); - let else_val = self.compile_block(builder, module, else_body); - if !self.filled { - let v = match else_val { - Some(v) => self.word(builder, v), - None => self.zero(builder), - }; - self.jump(builder, merge_block, &[v]); - } - - self.switch_to(builder, merge_block); - Some(result) - } - - Expr::WhileLoop { condition, body } => { - let header_block = builder.create_block(); - let body_block = builder.create_block(); - let exit_block = builder.create_block(); - - self.jump(builder, header_block, &[]); - - self.switch_to(builder, header_block); - let cond_val = self - .compile_expr(builder, module, condition) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if !self.filled { - let cond_val = self.word(builder, cond_val); - builder - .ins() - .brif(cond_val, body_block, &[], exit_block, &[]); - self.filled = true; - } - - self.switch_to(builder, body_block); - self.compile_block(builder, module, body); - self.jump(builder, header_block, &[]); - - self.switch_to(builder, exit_block); - None - } - - Expr::ForIn { var, iter, body } => { - // `a..b` counts; any other iterable is an array - // `[length, elements...]` whose elements are bound in turn. - let (start_val, end_val, arr) = match iter.as_ref() { - Expr::Range { start, end } => { - let s = self - .compile_expr(builder, module, start) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - let e = self - .compile_expr(builder, module, end) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - let s = self.word(builder, s); - let e = self.word(builder, e); - (s, e, None) - } - _ => { - let a = self - .compile_expr(builder, module, iter) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - let a = self.word(builder, a); - let s = builder.ins().iconst(W, 0); - let e = builder.ins().load(W, ir::MemFlags::new(), a, 0); - (s, e, Some(a)) - } - }; - - let loop_scope = self.enter_scope(); - let index_var = self.new_var(); - builder.declare_var(index_var, W); - builder.def_var(index_var, start_val); - let loop_var = match arr { - None => index_var, - Some(_) => { - let v = self.new_var(); - builder.declare_var(v, W); - v - } - }; - self.var_map.insert(var.clone(), loop_var); - - let header_block = builder.create_block(); - let body_block = builder.create_block(); - let exit_block = builder.create_block(); - - self.jump(builder, header_block, &[]); - - self.switch_to(builder, header_block); - let cur_val = builder.use_var(index_var); - let cond_val = builder.ins().icmp(IntCC::SignedLessThan, cur_val, end_val); - builder - .ins() - .brif(cond_val, body_block, &[], exit_block, &[]); - self.filled = true; - - self.switch_to(builder, body_block); - if let Some(a) = arr { - let off = builder.ins().imul_imm(cur_val, 8); - let addr = builder.ins().iadd(a, off); - let elem = builder.ins().load(W, ir::MemFlags::new(), addr, 8); - builder.def_var(loop_var, elem); - } - self.compile_block(builder, module, body); - if !self.filled { - let next_val = builder.ins().iadd_imm(cur_val, 1); - builder.def_var(index_var, next_val); - self.jump(builder, header_block, &[]); - } - - self.switch_to(builder, exit_block); - self.exit_scope(loop_scope); - None - } - - Expr::Return { value } => { - let v = match value.as_deref() { - // Returning a tuple literal must heap-allocate (a stack slot would dangle). - Some(Expr::TupleLiteral { elements }) => { - let mut words = Vec::new(); - for elem in elements { - let v = self - .compile_expr(builder, module, elem) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - words.push(self.word(builder, v)); - } - Some(self.alloc_words(builder, module, &words)) - } - Some(Expr::Variable(name)) - if self.stack_tuples.contains_key(name) - || self.tuple_params.contains_key(name) => - { - let count = self - .stack_tuples - .get(name) - .or_else(|| self.tuple_params.get(name)) - .copied() - .unwrap(); - let src = builder.use_var(self.var_map[name.as_str()]); - Some(self.copy_words_to_heap(builder, module, src, count)) - } - Some(v_expr) => self.compile_expr(builder, module, v_expr), - None => None, - }; - if self.filled { - return None; - } - if self.is_main { - let code = match v { - Some(v) => { - let v = self.word(builder, v); - builder.ins().ireduce(ir::types::I32, v) - } - None => builder.ins().iconst(ir::types::I32, 0), - }; - builder.ins().return_(&[code]); - } else if self.returns_value { - let v = match v { - Some(v) => self.word(builder, v), - None => self.zero(builder), - }; - builder.ins().return_(&[v]); - } else { - builder.ins().return_(&[]); - } - self.filled = true; - None - } - - Expr::LensBlock { - target, - lens_name, - body, - } => { - let lens_scope = self.enter_scope(); - if let Some(&var) = self.var_map.get(target) { - self.var_map.insert(lens_name.clone(), var); - } - let value = self.compile_block(builder, module, body); - self.exit_scope(lens_scope); - value - } - - Expr::TupleLiteral { elements } => { - // Fast, stack-allocated tuples for non-escaping locals. - // Escaping tuples are copied to the heap by `Return`. - let mut words = Vec::new(); - for elem in elements { - let v = self - .compile_expr(builder, module, elem) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - words.push(self.word(builder, v)); - } - let slot = builder.create_sized_stack_slot(StackSlotData::new( - StackSlotKind::ExplicitSlot, - (elements.len().max(1) * 8) as u32, - )); - let ptr = builder.ins().stack_addr(W, slot, 0); - for (i, val) in words.into_iter().enumerate() { - builder - .ins() - .store(ir::MemFlags::new(), val, ptr, (i * 8) as i32); - } - Some(ptr) - } - - Expr::TupleIndex { target, index } => { - let ptr = self.compile_expr(builder, module, target)?; - let offset = (*index * 8) as i32; - Some(builder.ins().load(W, ir::MemFlags::new(), ptr, offset)) - } - - Expr::LetDestructure { pattern, value, .. } => { - // Fast path: let (a,b) = (x, y) without allocating a tuple. - if let Expr::TupleLiteral { elements } = value.as_ref() - && let Pattern::Tuple(pats) = pattern - && pats.len() == elements.len() - { - let mut vals = Vec::new(); - for elem in elements { - let v = self - .compile_expr(builder, module, elem) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - vals.push(v); - } - for (pat, val) in pats.iter().zip(vals) { - self.bind_pattern(builder, pat, val); - } - return None; - } - if let Some(val) = self.compile_expr(builder, module, value) - && !self.filled - { - self.bind_pattern(builder, pattern, val); - } - None - } - - Expr::Match { target, arms } => { - let disc = self.compile_expr(builder, module, target)?; - let disc = self.word(builder, disc); - let merge_block = builder.create_block(); - let result = builder.append_block_param(merge_block, W); - - for arm in arms { - let arm_scope = self.enter_scope(); - let arm_block = builder.create_block(); - let next_arm_block = builder.create_block(); - - let mut matched = - self.compile_pattern_match(builder, module, &arm.pattern, disc); - - if let Some(ref guard) = arm.guard { - let guard_block = builder.create_block(); - builder - .ins() - .brif(matched, guard_block, &[], next_arm_block, &[]); - self.filled = true; - self.switch_to(builder, guard_block); - - self.bind_pattern(builder, &arm.pattern, disc); - matched = match self.compile_expr(builder, module, guard) { - Some(g) => self.word(builder, g), - None => builder.ins().iconst(W, 1), - }; - } else { - self.bind_pattern(builder, &arm.pattern, disc); - } - - builder - .ins() - .brif(matched, arm_block, &[], next_arm_block, &[]); - self.filled = true; - - self.switch_to(builder, arm_block); - let arm_val = self.compile_expr(builder, module, &arm.body); - if !self.filled { - let v = match arm_val { - Some(v) => self.word(builder, v), - None => self.zero(builder), - }; - self.jump(builder, merge_block, &[v]); - } - - self.switch_to(builder, next_arm_block); - self.exit_scope(arm_scope); - } - - let zero = self.zero(builder); - self.jump(builder, merge_block, &[zero]); - self.switch_to(builder, merge_block); - Some(result) - } - - Expr::StructInitialization { ty_name, fields } => { - // Struct values are heap cells: [tag, fields in declaration order]. - let mut values = Vec::new(); - for (fname, fexpr) in fields { - let v = self - .compile_expr(builder, module, fexpr) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - values.push((fname.clone(), self.word(builder, v))); - } - let order: Vec = match self.info.structs.get(ty_name) { - Some(decl) => decl.clone(), - None => fields.iter().map(|(f, _)| f.clone()).collect(), - }; - let mut words = vec![builder.ins().iconst(W, struct_tag(ty_name))]; - for fname in &order { - let v = match values.iter().find(|(f, _)| f == fname) { - Some((_, v)) => *v, - None => builder.ins().iconst(W, 0), - }; - words.push(v); - } - Some(self.alloc_words(builder, module, &words)) - } - - Expr::FieldAccess { target, field } => { - let ptr = self.compile_expr(builder, module, target)?; - Some(self.field_access(builder, module, ptr, field, None)) - } - - Expr::ArrayLiteral { elements } => { - // Arrays are heap cells: [length, elements...]. - let mut words = vec![builder.ins().iconst(W, elements.len() as i64)]; - for elem in elements { - let v = self - .compile_expr(builder, module, elem) - .unwrap_or_else(|| builder.ins().iconst(W, 0)); - if self.filled { - return None; - } - words.push(self.word(builder, v)); - } - Some(self.alloc_words(builder, module, &words)) - } - - Expr::ArrayIndex { target, index } => { - let arr = self.compile_expr(builder, module, target)?; - let idx = self.compile_expr(builder, module, index)?; - self.call_named(builder, module, "track_array_get", &[arr, idx]) - } - - Expr::SliceIndex { target, start, end } => { - let arr = self.compile_expr(builder, module, target)?; - let from = match start { - Some(s) => self.compile_expr(builder, module, s)?, - None => builder.ins().iconst(W, 0), - }; - let to = match end { - Some(e) => self.compile_expr(builder, module, e)?, - None => builder.ins().iconst(W, -1), - }; - self.call_named(builder, module, "track_array_slice", &[arr, from, to]) - } - - Expr::Range { start, end } => { - let s = self.compile_expr(builder, module, start)?; - let e = self.compile_expr(builder, module, end)?; - Some(builder.ins().isub(e, s)) - } - - _ => None, - } - } - - fn track_tuple_binding(&mut self, name: &str, value: &Expr) { - if let Expr::TupleLiteral { elements } = value { - self.stack_tuples.insert(name.to_string(), elements.len()); - } else { - self.stack_tuples.remove(name); - } - self.tuple_params.remove(name); - } - - fn bind_pattern(&mut self, builder: &mut FunctionBuilder, pattern: &Pattern, val: Value) { - match pattern { - Pattern::Ident(name) => { - let var = self.new_var(); - builder.declare_var(var, W); - builder.def_var(var, val); - self.var_map.insert(name.clone(), var); - self.stack_tuples.remove(name); - self.tuple_params.remove(name); - } - Pattern::Wildcard | Pattern::Literal(_) => {} - Pattern::Tuple(pats) => { - for (i, p) in pats.iter().enumerate() { - let elem_val = builder - .ins() - .load(W, ir::MemFlags::new(), val, (i * 8) as i32); - self.bind_pattern(builder, p, elem_val); - } - } - Pattern::Variant { - enum_or_union, - bindings, - .. - } => { - if self.info.payload_unions.contains(enum_or_union) { - for (i, p) in bindings.iter().enumerate() { - let payload = - builder - .ins() - .load(W, ir::MemFlags::new(), val, ((i + 1) * 8) as i32); - self.bind_pattern(builder, p, payload); - } - } else { - for p in bindings { - self.bind_pattern(builder, p, val); - } - } - } - Pattern::Struct { name, fields } => { - let decl = self.info.structs.get(name).cloned().unwrap_or_default(); - for (fname, p) in fields { - if let Some(idx) = decl.iter().position(|f| f == fname) { - let field = - builder - .ins() - .load(W, ir::MemFlags::new(), val, ((idx + 1) * 8) as i32); - self.bind_pattern(builder, p, field); - } - } - } - } - } - - /// Returns a 0/1 word that is non-zero when `pattern` matches `val`. - fn compile_pattern_match( - &mut self, - builder: &mut FunctionBuilder, - module: &mut ObjectModule, - pattern: &Pattern, - val: Value, - ) -> Value { - match pattern { - Pattern::Ident(_) | Pattern::Wildcard => builder.ins().iconst(W, 1), - Pattern::Struct { name, fields } => { - let Some(decl) = self.info.structs.get(name).cloned() else { - return builder.ins().iconst(W, 1); - }; - let tag = builder.ins().load(W, ir::MemFlags::new(), val, 0); - let want = builder.ins().iconst(W, struct_tag(name)); - let mut cond = self.bool_word(builder, IntCC::Equal, tag, want); - for (fname, p) in fields { - if let Some(idx) = decl.iter().position(|f| f == fname) { - let field = - builder - .ins() - .load(W, ir::MemFlags::new(), val, ((idx + 1) * 8) as i32); - let sub = self.compile_pattern_match(builder, module, p, field); - cond = builder.ins().band(cond, sub); - } - } - cond - } - Pattern::Literal(lit_expr) => { - if let Expr::StringLiteral(_) = lit_expr.as_ref() { - let lit = self.compile_expr(builder, module, lit_expr).unwrap(); - let eq = self - .call_named(builder, module, "str_eq", &[val, lit]) - .unwrap(); - let zero = self.zero(builder); - return self.bool_word(builder, IntCC::NotEqual, eq, zero); - } - match self.compile_expr(builder, module, lit_expr) { - Some(lit_val) => { - let lit_val = self.word(builder, lit_val); - self.bool_word(builder, IntCC::Equal, val, lit_val) - } - None => builder.ins().iconst(W, 1), - } - } - Pattern::Variant { - enum_or_union, - variant, - .. - } => { - let key = format!("{}::{}", enum_or_union, variant); - let target_disc = self.variant_key(&key).unwrap_or(0); - let expected = builder.ins().iconst(W, target_disc); - let tag = if self.info.payload_unions.contains(enum_or_union) { - builder.ins().load(W, ir::MemFlags::new(), val, 0) - } else { - val - }; - self.bool_word(builder, IntCC::Equal, tag, expected) - } - Pattern::Tuple(pats) => { - let mut cond = builder.ins().iconst(W, 1); - for (i, p) in pats.iter().enumerate() { - let elem_val = builder - .ins() - .load(W, ir::MemFlags::new(), val, (i * 8) as i32); - let elem_cond = self.compile_pattern_match(builder, module, p, elem_val); - cond = builder.ins().band(cond, elem_cond); - } - cond - } - } - } -} diff --git a/src/lexer/mod.rs b/src/lexer/mod.rs deleted file mode 100644 index a7505f73..00000000 --- a/src/lexer/mod.rs +++ /dev/null @@ -1,213 +0,0 @@ -use logos::Logos; - -#[derive(Logos, Debug, Clone, PartialEq)] -#[logos(skip r"[ \t\r\n]+")] -#[logos(skip r"//[^\n]*")] -pub enum Token { - // Keywords - #[token("import")] - Import, - #[token("use")] - Use, - #[token("let")] - Let, - - #[token("mut")] - Mut, - #[token("with")] - With, - #[token("fn")] - Fn, - #[token("return")] - Return, - #[token("if")] - If, - #[token("else")] - Else, - #[token("while")] - While, - #[token("for")] - For, - #[token("in")] - In, - #[token("true")] - True, - #[token("false")] - False, - #[token("struct")] - Struct, - #[token("enum")] - Enum, - #[token("union")] - Union, - #[token("match")] - Match, - #[token("as")] - As, - #[token("@macro")] - AtMacro, - - #[token("const")] - Const, - #[token("type")] - TypeDef, - #[token("@")] - At, - - // Type keywords - #[token("u8")] - TyU8, - #[token("i8")] - TyI8, - #[token("i32")] - TyI32, - #[token("u32")] - TyU32, - #[token("i64")] - TyI64, - #[token("u64")] - TyU64, - #[token("bool")] - TyBool, - #[token("void")] - TyVoid, - #[token("ptr")] - TyPtr, - - // Literals - #[regex(r"[0-9]+", |lex| lex.slice().parse::().ok())] - Int(i64), - - #[regex(r#""([^"\\]|\\.)*""#, |lex| { - let s = lex.slice(); - Some(unescape_str(&s[1..s.len()-1])) - })] - Str(String), - - #[regex(r"[a-zA-Z_][a-zA-Z0-9_]*", |lex| Some(lex.slice().to_string()))] - Ident(String), - - // Punctuation - #[token("=")] - Eq, - #[token("==")] - EqEq, - #[token("!=")] - Neq, - #[token("!")] - Bang, - #[token("{")] - LBrace, - #[token("}")] - RBrace, - #[token("(")] - LParen, - #[token(")")] - RParen, - #[token("[")] - LBracket, - #[token("]")] - RBracket, - #[token(",")] - Comma, - #[token(":")] - Colon, - #[token("::")] - ColonColon, - #[token("->")] - Arrow, - #[token("=>")] - FatArrow, - #[token(";")] - Semicolon, - #[token("..")] - DotDot, - #[token(".")] - Dot, - #[token("_", priority = 3)] - Underscore, - #[token("&")] - Amp, - #[token("|")] - Pipe, - #[token("*")] - Star, - #[token("+")] - Plus, - #[token("-")] - Minus, - #[token("/")] - Slash, - #[token("%")] - Percent, - #[token("<")] - Lt, - #[token(">")] - Gt, - #[token("<=")] - Lte, - #[token(">=")] - Gte, - #[token("&&")] - AmpAmp, - #[token("||")] - PipePipe, - #[token("<<")] - Shl, - #[token(">>")] - Shr, -} - -pub struct Lexer; - -impl Lexer { - pub fn tokenize(input: &str) -> Result)>, String> { - let mut tokens = Vec::new(); - let mut lex = Token::lexer(input); - - loop { - match lex.next() { - Some(Ok(token)) => { - let span = lex.span(); - tokens.push((token, span)); - } - Some(Err(())) => { - let span = lex.span(); - let ch = input[span.clone()].chars().next().unwrap_or('?'); - return Err(format!( - "Lexer error at {:?}: unexpected character '{}'", - span, ch - )); - } - None => break, - } - } - Ok(tokens) - } -} - -pub fn unescape_str(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut chars = s.chars(); - while let Some(c) = chars.next() { - if c == '\\' { - match chars.next() { - Some('n') => out.push('\n'), - Some('r') => out.push('\r'), - Some('t') => out.push('\t'), - Some('0') => out.push('\0'), - Some('"') => out.push('"'), - Some('\'') => out.push('\''), - Some('\\') => out.push('\\'), - Some(other) => { - out.push('\\'); - out.push(other); - } - None => out.push('\\'), - } - } else { - out.push(c); - } - } - out -} diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index 09bf13db..00000000 --- a/src/lib.rs +++ /dev/null @@ -1,85 +0,0 @@ -pub mod ast; -pub mod checker; -pub mod codegen; -pub mod lexer; -pub mod lsp; -pub mod mono; -pub mod parser; -pub mod yard; - -use std::fs; -use std::path::{Path, PathBuf}; -use std::process; - -/// The Track runtime, shared with the self-hosted compiler (word ABI). -pub const RUNTIME_C_SOURCE: &str = include_str!("../runtime/track_runtime.c"); - -/// Compile source string through Lexer -> Parser -> Monomorphizer -> LinearChecker pipeline. -pub fn compile_source(source: &str) -> Result, String> { - compile_source_with_info(source).map(|(program, _)| program) -} - -/// Like [`compile_source`], also returning the type layouts codegen needs -/// (enum discriminants, payload unions, aliases — including imports). -pub fn compile_source_with_info( - source: &str, -) -> Result<(Vec, codegen::TypeInfo), String> { - let tokens = lexer::Lexer::tokenize(source)?; - let mut p = parser::Parser::new(tokens, source.to_string()); - let program = p.parse_program()?; - let mut program = program; - mono::monomorphize(&mut program)?; - let mut chk = checker::LinearChecker::new(); - chk.check_program(&program)?; - Ok((program, chk.type_info)) -} - -/// Full build: source -> object file -> linked executable in specified directory. -pub fn build_file_in_dir(filename: &str, out_dir: &Path) -> Result { - let source = - fs::read_to_string(filename).map_err(|e| format!("Error reading '{}': {}", filename, e))?; - - let (program, info) = compile_source_with_info(&source)?; - - let mut cg = codegen::CodeGen::new("track_module"); - cg.set_type_info(info); - cg.compile_program(&program); - - let stem = Path::new(filename) - .file_stem() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - - let obj_path = out_dir.join(format!("{}.o", stem)); - let runtime_path = out_dir.join(format!("_track_runtime_{}.c", stem)); - let exe_path = out_dir.join(&stem); - - cg.write_object_file(&obj_path)?; - fs::write(&runtime_path, RUNTIME_C_SOURCE) - .map_err(|e| format!("Failed to write runtime helper: {}", e))?; - - let status = process::Command::new("cc") - .arg("-O3") - .arg(&obj_path) - .arg(&runtime_path) - .arg("-o") - .arg(&exe_path) - .arg("-lm") - .status() - .map_err(|e| format!("Linker error: {}", e))?; - - let _ = fs::remove_file(&obj_path); - let _ = fs::remove_file(&runtime_path); - - if !status.success() { - return Err(format!("Linker failed with exit code: {:?}", status.code())); - } - - Ok(exe_path) -} - -/// Full build placing executable in current directory. -pub fn build_file(filename: &str) -> Result { - build_file_in_dir(filename, Path::new(".")) -} diff --git a/src/lsp/mod.rs b/src/lsp/mod.rs deleted file mode 100644 index 8963f466..00000000 --- a/src/lsp/mod.rs +++ /dev/null @@ -1,594 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - -use tower_lsp::jsonrpc::Result; -use tower_lsp::lsp_types::*; -use tower_lsp::{Client, LanguageServer, LspService, Server}; - -use crate::checker::LinearChecker; -use crate::lexer::Lexer; -use crate::parser::Parser; - -pub struct TrackLsp { - client: Client, - documents: Mutex>, - ast_cache: Mutex>>, - doc_revisions: Mutex>, -} - -impl TrackLsp { - pub fn new(client: Client) -> Self { - Self { - client, - documents: Mutex::new(HashMap::new()), - ast_cache: Mutex::new(HashMap::new()), - doc_revisions: Mutex::new(HashMap::new()), - } - } - - async fn analyze_document_async(&self, uri: Url, text: String, rev: usize) -> Vec { - let uri_clone = uri.clone(); - let (ast_opt, diagnostics) = tokio::task::spawn_blocking(move || { - if uri_clone.path().ends_with(".md") || uri_clone.path().ends_with(".markdown") { - let mut all_diagnostics = Vec::new(); - let blocks = Self::extract_track_blocks_static(&text); - - for (range, block_source) in blocks { - let (_, block_diagnostics) = Self::analyze_source_static(&block_source); - for mut diag in block_diagnostics { - diag.range.start.line += range.start.line; - diag.range.end.line += range.start.line; - all_diagnostics.push(diag); - } - } - (None, all_diagnostics) - } else if uri_clone.path().ends_with(".trk") { - Self::analyze_source_static(&text) - } else { - (None, Vec::new()) - } - }) - .await - .unwrap_or((None, Vec::new())); - - if self.doc_revisions.lock().unwrap().get(&uri) != Some(&rev) { - return Vec::new(); // Superseded by newer edit - } - - if let Some(ast) = ast_opt { - self.ast_cache.lock().unwrap().insert(uri, ast); - } - - diagnostics - } - - fn analyze_source_static(source: &str) -> (Option>, Vec) { - let mut diagnostics = Vec::new(); - - // Try to tokenize - let tokens = match Lexer::tokenize(source) { - Ok(t) => t, - Err(e) => { - diagnostics.push(Diagnostic { - range: Range::new(Position::new(0, 0), Position::new(0, 0)), - severity: Some(DiagnosticSeverity::ERROR), - message: e, - ..Default::default() - }); - return (None, diagnostics); - } - }; - - // Try to parse - let mut parser = Parser::new(tokens, source.to_string()); - let program = match parser.parse_program() { - Ok(p) => p, - Err(e) => { - diagnostics.push(Diagnostic { - range: Range::new(Position::new(0, 0), Position::new(0, 0)), - severity: Some(DiagnosticSeverity::ERROR), - message: e, - ..Default::default() - }); - return (None, diagnostics); - } - }; - - // Monomorphize generics (same as compile_source) then type check - let mut program = program; - if let Err(e) = crate::mono::monomorphize(&mut program) { - diagnostics.push(Diagnostic { - range: Range::new(Position::new(0, 0), Position::new(0, 0)), - severity: Some(DiagnosticSeverity::ERROR), - message: e, - ..Default::default() - }); - return (None, diagnostics); - } - - let mut checker = LinearChecker::new(); - if let Err(e) = checker.check_program(&program) { - diagnostics.push(Diagnostic { - range: Range::new(Position::new(0, 0), Position::new(0, 0)), - severity: Some(DiagnosticSeverity::ERROR), - message: e, - ..Default::default() - }); - } - - (Some(program), diagnostics) - } - - fn extract_track_blocks_static(markdown: &str) -> Vec<(Range, String)> { - let mut blocks = Vec::new(); - let mut in_block = false; - let mut block_start_line = 0; - let mut block_content = String::new(); - - for (line_idx, line) in markdown.lines().enumerate() { - let trimmed = line.trim(); - - if trimmed.starts_with("```track") || trimmed.starts_with("```trk") { - in_block = true; - block_start_line = line_idx + 1; - block_content.clear(); - } else if trimmed == "```" && in_block { - in_block = false; - let range = Range::new( - Position::new(block_start_line as u32, 0), - Position::new(line_idx as u32, 0), - ); - blocks.push((range, block_content.clone())); - } else if in_block { - if !block_content.is_empty() { - block_content.push('\n'); - } - block_content.push_str(line); - } - } - - blocks - } -} - -#[tower_lsp::async_trait] -impl LanguageServer for TrackLsp { - async fn initialize(&self, _: InitializeParams) -> Result { - Ok(InitializeResult { - capabilities: ServerCapabilities { - text_document_sync: Some(TextDocumentSyncCapability::Kind( - TextDocumentSyncKind::FULL, - )), - completion_provider: Some(CompletionOptions { - trigger_characters: Some(vec![".".to_string(), ":".to_string()]), - ..Default::default() - }), - hover_provider: Some(HoverProviderCapability::Simple(true)), - ..Default::default() - }, - ..Default::default() - }) - } - - async fn initialized(&self, _: InitializedParams) { - self.client - .log_message(MessageType::INFO, "Track LSP server initialized") - .await; - } - - async fn did_open(&self, params: DidOpenTextDocumentParams) { - let uri = params.text_document.uri; - let text = params.text_document.text; - - self.documents - .lock() - .unwrap() - .insert(uri.clone(), text.clone()); - - let rev = { - let mut map = self.doc_revisions.lock().unwrap(); - let entry = map.entry(uri.clone()).or_insert(0); - *entry += 1; - *entry - }; - - let diagnostics = self.analyze_document_async(uri.clone(), text, rev).await; - - self.client - .publish_diagnostics(uri, diagnostics, None) - .await; - } - - async fn did_change(&self, params: DidChangeTextDocumentParams) { - let uri = params.text_document.uri; - let text = params - .content_changes - .into_iter() - .next() - .map(|c| c.text) - .unwrap_or_default(); - - self.documents - .lock() - .unwrap() - .insert(uri.clone(), text.clone()); - - let rev = { - let mut map = self.doc_revisions.lock().unwrap(); - let entry = map.entry(uri.clone()).or_insert(0); - *entry += 1; - *entry - }; - - let diagnostics = self.analyze_document_async(uri.clone(), text, rev).await; - - self.client - .publish_diagnostics(uri, diagnostics, None) - .await; - } - - async fn did_save(&self, params: DidSaveTextDocumentParams) { - let uri = params.text_document.uri; - if let Some(text) = params.text { - self.documents - .lock() - .unwrap() - .insert(uri.clone(), text.clone()); - - let rev = { - let mut map = self.doc_revisions.lock().unwrap(); - let entry = map.entry(uri.clone()).or_insert(0); - *entry += 1; - *entry - }; - - let diagnostics = self.analyze_document_async(uri.clone(), text, rev).await; - - self.client - .publish_diagnostics(uri, diagnostics, None) - .await; - } - } - - async fn completion(&self, params: CompletionParams) -> Result> { - let uri = ¶ms.text_document_position.text_document.uri; - let position = params.text_document_position.position; - - let documents = self.documents.lock().unwrap(); - let text = match documents.get(uri) { - Some(t) => t.clone(), - None => return Ok(None), - }; - drop(documents); - - let lines: Vec<&str> = text.lines().collect(); - if position.line as usize >= lines.len() { - return Ok(None); - } - - let line = lines[position.line as usize]; - let cursor_pos = position.character as usize; - - // Get the word being typed - let before_cursor = &line[..cursor_pos.min(line.len())]; - let word_start = before_cursor - .rfind(|c: char| !c.is_alphanumeric() && c != '_') - .map(|i| i + 1) - .unwrap_or(0); - let word = &before_cursor[word_start..]; - - if word.is_empty() { - return Ok(None); - } - - let mut completions = Vec::new(); - - // Keywords - let keywords = vec![ - "import", "use", "let", "mut", "fn", "return", "if", "else", "while", "for", "in", - "struct", "enum", "union", "match", "with", "const", "type", "true", "false", "as", - ]; - - for kw in keywords { - if kw.starts_with(word) { - completions.push(CompletionItem::new_simple( - kw.to_string(), - "Keyword".to_string(), - )); - } - } - - // Types - let types = vec![ - "i8", "u8", "i32", "u32", "i64", "u64", "bool", "void", "ptr", - ]; - - for ty in types { - if ty.starts_with(word) { - completions.push(CompletionItem { - label: ty.to_string(), - kind: Some(CompletionItemKind::TYPE_PARAMETER), - detail: Some("Type".to_string()), - ..Default::default() - }); - } - } - - // Built-in functions - let builtins = vec![ - "print", - "println", - "eprint", - "read", - "file_open", - "file_close", - "file_exists", - "dir_exists", - "file_copy", - "clock_ms", - "exit", - "alloc", - "dealloc", - "env_get", - "os_args_count", - "os_arg", - "process_spawn", - "sys_exec", - "sys_set_memory_limit", - "sys_get_memory_used", - "str_starts_with", - "str_ends_with", - "str_contains", - "str_is_int", - "env_get", - "env_exists", - "abort", - ]; - - for b in builtins { - if b.starts_with(word) { - completions.push(CompletionItem { - label: b.to_string(), - kind: Some(CompletionItemKind::FUNCTION), - detail: Some("Built-in function".to_string()), - ..Default::default() - }); - } - } - - // Macros - let macros = vec!["macro", "now", "compile_error"]; - - for m in macros { - if m.starts_with(word) { - completions.push(CompletionItem { - label: format!("@{}", m), - kind: Some(CompletionItemKind::FUNCTION), - detail: Some("Macro".to_string()), - ..Default::default() - }); - } - } - - // Enum/Union variants from cached AST - let cached_program = self.ast_cache.lock().unwrap().get(uri).cloned(); - let program = match cached_program { - Some(p) => p, - None => { - let tokens = Lexer::tokenize(&text).unwrap_or_default(); - let mut parser = Parser::new(tokens, text.clone()); - parser.parse_program().unwrap_or_default() - } - }; - - for stmt in &program { - match stmt { - crate::ast::Expr::EnumDef { name, variants, .. } => { - for (variant, _) in variants { - let full = format!("{}::{}", name, variant); - if full.starts_with(word) { - completions.push(CompletionItem { - label: full, - kind: Some(CompletionItemKind::ENUM_MEMBER), - detail: Some(format!("Enum variant of {}", name)), - ..Default::default() - }); - } - } - } - crate::ast::Expr::UnionDef { name, variants, .. } => { - for (variant, _) in variants { - let full = format!("{}::{}", name, variant); - if full.starts_with(word) { - completions.push(CompletionItem { - label: full, - kind: Some(CompletionItemKind::ENUM_MEMBER), - detail: Some(format!("Union variant of {}", name)), - ..Default::default() - }); - } - } - } - crate::ast::Expr::FnDef { name, .. } if name.starts_with(word) => { - completions.push(CompletionItem { - label: name.clone(), - kind: Some(CompletionItemKind::FUNCTION), - detail: Some("User-defined function".to_string()), - ..Default::default() - }); - } - _ => {} - } - } - - Ok(Some(CompletionResponse::Array(completions))) - } - - async fn hover(&self, params: HoverParams) -> Result> { - let uri = ¶ms.text_document_position_params.text_document.uri; - let position = params.text_document_position_params.position; - - let documents = self.documents.lock().unwrap(); - let text = match documents.get(uri) { - Some(t) => t.clone(), - None => return Ok(None), - }; - drop(documents); - - let lines: Vec<&str> = text.lines().collect(); - if position.line as usize >= lines.len() { - return Ok(None); - } - - let line = lines[position.line as usize]; - let cursor_pos = position.character as usize; - - // Get the word under cursor - let before_cursor = &line[..cursor_pos.min(line.len())]; - let after_cursor = &line[cursor_pos..]; - let word_start = before_cursor - .rfind(|c: char| !c.is_alphanumeric() && c != '_') - .map(|i| i + 1) - .unwrap_or(0); - let word_end = after_cursor - .find(|c: char| !c.is_alphanumeric() && c != '_') - .map(|i| cursor_pos + i) - .unwrap_or(line.len()); - let word = &line[word_start..word_end]; - - if word.is_empty() { - return Ok(None); - } - - // Check keywords - let keyword_docs = HashMap::from([ - ("let", "Declare a variable\n\n```track\nlet x = 42;\n```"), - ( - "mut", - "Declare a mutable variable\n\n```track\nlet mut x = 42;\n```", - ), - ( - "fn", - "Define a function\n\n```track\nfn add(a: i32, b: i32) -> i32 {\n return a + b;\n}\n```", - ), - ("return", "Return from function"), - ("if", "Conditional expression"), - ("else", "Else branch"), - ("while", "Loop"), - ( - "for", - "For-in loop\n\n```track\nfor i in 0..10 {\n print(i);\n}\n```", - ), - ("in", "Iteration in a for-in loop"), - ("use", "Import items from a module (synonym for `import`)"), - ( - "type", - "Define a type alias\n\n```track\ntype Matrix = [i32; 16];\n```", - ), - ("struct", "Define a struct"), - ( - "enum", - "Define an enum\n\n```track\nenum Color {\n Red,\n Green,\n Blue,\n}\n```", - ), - ( - "union", - "Define a tagged union\n\n```track\nunion Value {\n Int(i32),\n Float(f64),\n}\n```", - ), - ("match", "Pattern matching"), - ("with", "Lexical lens block"), - ("const", "Compile-time constant"), - ("true", "Boolean true"), - ("false", "Boolean false"), - ("as", "Alias import"), - ]); - - if let Some(doc) = keyword_docs.get(word) { - return Ok(Some(Hover { - contents: HoverContents::Markup(MarkupContent { - kind: MarkupKind::Markdown, - value: doc.to_string(), - }), - range: None, - })); - } - - // Check types - let type_docs = HashMap::from([ - ("i8", "8-bit signed integer (copy type)"), - ("u8", "8-bit unsigned integer (copy type)"), - ("i32", "32-bit signed integer (copy type)"), - ("u32", "32-bit unsigned integer (copy type)"), - ("i64", "64-bit signed integer (copy type)"), - ("u64", "64-bit unsigned integer (copy type)"), - ("bool", "Boolean (copy type)"), - ("void", "Unit type (copy type)"), - ( - "ptr", - "Raw pointer (copy type)\n\n```track\nlet p: ptr;\n```", - ), - ]); - - if let Some(doc) = type_docs.get(word) { - return Ok(Some(Hover { - contents: HoverContents::Markup(MarkupContent { - kind: MarkupKind::Markdown, - value: doc.to_string(), - }), - range: None, - })); - } - - // Check built-ins - let builtin_docs = HashMap::from([ - ( - "print", - "Print a value to stdout\n\n```track\nprint(42);\nprint(\"hello\");\n```", - ), - ("read", "Read input\n\n```track\nlet value = read();\n```"), - ]); - - if let Some(doc) = builtin_docs.get(word) { - return Ok(Some(Hover { - contents: HoverContents::Markup(MarkupContent { - kind: MarkupKind::Markdown, - value: doc.to_string(), - }), - range: None, - })); - } - - // Check macros - let macro_docs = HashMap::from([ - ( - "@macro", - "Define a compile-time macro\n\n```track\n@macro double(n: i32) -> i32 {\n return n * 2;\n}\n```", - ), - ("@compile_error", "Trigger a compile-time error"), - ("@now", "Get current timestamp"), - ]); - - if let Some(doc) = macro_docs.get(word) { - return Ok(Some(Hover { - contents: HoverContents::Markup(MarkupContent { - kind: MarkupKind::Markdown, - value: doc.to_string(), - }), - range: None, - })); - } - - Ok(None) - } - - async fn shutdown(&self) -> Result<()> { - Ok(()) - } -} - -pub async fn start_server() { - let stdin = tokio::io::stdin(); - let stdout = tokio::io::stdout(); - - let (service, messages) = LspService::new(TrackLsp::new); - Server::new(stdin, stdout, messages).serve(service).await; -} diff --git a/src/lsp_bin.rs b/src/lsp_bin.rs deleted file mode 100644 index df96f12c..00000000 --- a/src/lsp_bin.rs +++ /dev/null @@ -1,6 +0,0 @@ -use track::lsp; - -#[tokio::main] -async fn main() { - lsp::start_server().await; -} diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 183f0d8a..00000000 --- a/src/main.rs +++ /dev/null @@ -1,125 +0,0 @@ -use std::env; -use std::fs; -use std::path::PathBuf; -use std::process; - -use track::{build_file, compile_source, yard}; - -fn main() { - let args: Vec = env::args().collect(); - - if args.len() < 2 { - print_usage(); - process::exit(1); - } - - match args[1].as_str() { - "build" => { - let file = require_file_arg(&args, 2); - cmd_build(&file); - } - "run" => { - let file = require_file_arg(&args, 2); - cmd_run(&file); - } - "check" => { - let file = require_file_arg(&args, 2); - cmd_check(&file); - } - "yard" => { - let yard_args: Vec = args[2..].to_vec(); - match yard::run(&yard_args) { - Ok(()) => {} - Err(e) => { - eprintln!("yard error: {}", e); - process::exit(1); - } - } - } - "--version" | "-v" | "version" => { - println!("track {}", env!("CARGO_PKG_VERSION")); - } - "--help" | "-h" | "help" => { - print_usage(); - } - // Legacy: if argument ends with .trk, treat as `build` - arg if arg.ends_with(".trk") => { - cmd_build(arg); - } - other => { - eprintln!("Unknown command: '{}'\n", other); - print_usage(); - process::exit(1); - } - } -} - -fn print_usage() { - eprintln!( - "Track v{} — Systems programming with linear types\n", - env!("CARGO_PKG_VERSION") - ); - eprintln!("USAGE:"); - eprintln!(" track build Compile to native executable"); - eprintln!(" track run Compile and run"); - eprintln!(" track check Type-check only (no codegen)"); - eprintln!(" track yard Package manager"); - eprintln!(" track Same as 'track build'"); - eprintln!(" track --version Show version info"); - eprintln!(" track help Show this help"); -} - -fn require_file_arg(args: &[String], idx: usize) -> String { - args.get(idx).cloned().unwrap_or_else(|| { - eprintln!("Error: expected a .trk file path"); - process::exit(1); - }) -} - -// ── commands ───────────────────────────────────────────────────────── - -fn cmd_build(filename: &str) -> PathBuf { - match build_file(filename) { - Ok(exe) => { - println!("✓ Built: {}", exe.display()); - exe - } - Err(e) => { - eprintln!("{}", e); - process::exit(1); - } - } -} - -fn cmd_run(filename: &str) { - let exe = cmd_build(filename); - let exe_path = if exe.is_absolute() { - exe - } else { - env::current_dir().unwrap().join(exe) - }; - - let status = process::Command::new(&exe_path) - .status() - .unwrap_or_else(|e| { - eprintln!("Failed to run '{}': {}", exe_path.display(), e); - process::exit(1); - }); - - process::exit(status.code().unwrap_or(1)); -} - -fn cmd_check(filename: &str) { - let source = fs::read_to_string(filename).unwrap_or_else(|e| { - eprintln!("Error reading '{}': {}", filename, e); - process::exit(1); - }); - - match compile_source(&source) { - Ok(_) => println!("✓ Check passed: {}", filename), - Err(e) => { - eprintln!("{}", e); - process::exit(1); - } - } -} diff --git a/src/mono.rs b/src/mono.rs deleted file mode 100644 index dce63fa0..00000000 --- a/src/mono.rs +++ /dev/null @@ -1,796 +0,0 @@ -//! Compile-time monomorphization pass (v0.6.0). -//! -//! Runs between the parser and the linear checker. Generic function -//! definitions (`fn name(...)`) are treated as templates: -//! -//! 1. Templates are extracted into a table keyed by name. -//! 2. Every call site whose target is a template gets rewritten to a -//! mangled instance name (`identity__i32`), with type parameters -//! inferred from the argument expressions (with let/param scope -//! tracking; annotate with `let x: T = ...` when inference is -//! ambiguous). -//! 3. A concrete clone of the template (types substituted, body walked -//! recursively so nested generic calls also specialize) is appended to -//! the program. The checker and codegen then see only ordinary, -//! fully concrete functions. -//! -//! Substitution rules: a `TrackType::Custom(name)` is replaced when `name` -//! is one of the template's declared type parameters; composite types -//! (Ptr, Ref, Slice, Array, Tuple) substitute recursively. - -use std::collections::HashMap; - -use crate::ast::{Expr, TrackType}; - -struct Template { - type_params: Vec, - params: Vec<(String, TrackType)>, - return_type: Option, - body: Vec, -} - -type Env = HashMap; - -pub fn monomorphize(program: &mut Vec) -> Result<(), String> { - let mut templates: HashMap = HashMap::new(); - for stmt in program.iter() { - if let Expr::FnDef { - name, - generics, - params, - return_type, - body, - } = stmt - { - if generics.is_empty() { - continue; - } - if templates - .insert( - name.clone(), - Template { - type_params: generics.clone(), - params: params.clone(), - return_type: return_type.clone(), - body: body.clone(), - }, - ) - .is_some() - { - return Err(format!( - "Compile Error: duplicate generic function definition '{}'", - name - )); - } - } - } - - if templates.is_empty() { - return Ok(()); - } - - // Map of concrete (non-generic) function return types for inference. - let mut concrete_sigs: HashMap> = HashMap::new(); - for stmt in program.iter() { - if let Expr::FnDef { - name, - generics, - return_type, - .. - } = stmt - && generics.is_empty() - { - concrete_sigs.insert(name.clone(), return_type.clone()); - } - } - - // Generated instances, keyed by mangled name to guarantee one emission each. - let mut generated: HashMap = HashMap::new(); - // In-progress instantiations guard against runaway recursion. - let mut in_progress: Vec = Vec::new(); - - // Walk until fixpoint. Generated instances are collected separately; - // their bodies were already rewritten recursively during generation. - let mut top_env: Env = HashMap::new(); - let mut i = 0; - while i < program.len() { - let is_template = - matches!(&program[i], Expr::FnDef { generics, .. } if !generics.is_empty()); - if is_template { - // Templates stay symbolic — their bodies are never emitted as-is. - i += 1; - continue; - } - walk( - &mut program[i], - &mut top_env, - &templates, - &concrete_sigs, - &mut generated, - &mut in_progress, - )?; - i += 1; - } - - let instances: Vec = generated.into_values().collect(); - program.extend(instances); - Ok(()) -} - -fn walk( - expr: &mut Expr, - env: &mut Env, - templates: &HashMap, - concrete_sigs: &HashMap>, - generated: &mut HashMap, - in_progress: &mut Vec, -) -> Result<(), String> { - match expr { - Expr::FnDef { params, body, .. } | Expr::MacroDef { params, body, .. } => { - // Fresh scope for nested definitions. - let mut inner = env.clone(); - for (n, ty) in params.iter() { - inner.insert(n.clone(), ty.clone()); - } - for stmt in body.iter_mut() { - walk( - stmt, - &mut inner, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - Expr::LetDef { - name, ty, value, .. - } => { - walk(value, env, templates, concrete_sigs, generated, in_progress)?; - let inferred = infer_shallow(value, env, templates, concrete_sigs, generated); - let final_ty = ty.clone().or(inferred); - if let Some(t) = final_ty { - env.insert(name.clone(), t); - } - } - Expr::LetDestructure { pattern, value, .. } => { - walk(value, env, templates, concrete_sigs, generated, in_progress)?; - if let Ok(TrackType::Tuple(elems)) = - infer_tuple_shape(value, env, templates, concrete_sigs, generated) - { - bind_pattern(pattern, &elems, env); - } - } - Expr::Assign { value, .. } => { - walk(value, env, templates, concrete_sigs, generated, in_progress)?; - } - Expr::Return { value } => { - if let Some(v) = value.as_mut() { - walk(v, env, templates, concrete_sigs, generated, in_progress)?; - } - } - Expr::IfElse { - condition, - then_body, - else_body, - } => { - walk( - condition, - env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - for stmt in then_body.iter_mut() { - let mut branch = env.clone(); - walk( - stmt, - &mut branch, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - for stmt in else_body.iter_mut() { - let mut branch = env.clone(); - walk( - stmt, - &mut branch, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - Expr::WhileLoop { condition, body } => { - walk( - condition, - env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - for stmt in body.iter_mut() { - let mut branch = env.clone(); - walk( - stmt, - &mut branch, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - Expr::ForIn { var, iter, body } => { - walk(iter, env, templates, concrete_sigs, generated, in_progress)?; - let mut inner = env.clone(); - if let Some(TrackType::Array(elem, _)) | Some(TrackType::Slice(elem)) = - infer_shallow(iter, env, templates, concrete_sigs, generated) - { - inner.insert(var.clone(), *elem); - } else { - inner.insert(var.clone(), TrackType::I64); - } - for stmt in body.iter_mut() { - walk( - stmt, - &mut inner, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - Expr::LensBlock { body, .. } => { - for stmt in body.iter_mut() { - let mut branch = env.clone(); - walk( - stmt, - &mut branch, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - Expr::Match { target, arms } => { - walk( - target, - env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - for arm in arms.iter_mut() { - if let Some(guard) = arm.guard.as_mut() { - walk(guard, env, templates, concrete_sigs, generated, in_progress)?; - } - let mut branch = env.clone(); - walk( - &mut arm.body, - &mut branch, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - Expr::FunctionCall { name, args } => { - for arg in args.iter_mut() { - walk(arg, env, templates, concrete_sigs, generated, in_progress)?; - } - specialize_call( - name, - args, - env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - Expr::MacroCall { args, body, .. } => { - for arg in args.iter_mut() { - walk(arg, env, templates, concrete_sigs, generated, in_progress)?; - } - if let Some(b) = body.as_mut() { - for stmt in b.iter_mut() { - let mut branch = env.clone(); - walk( - stmt, - &mut branch, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - } - } - Expr::UnaryOp { expr, .. } - | Expr::AddressOf { target: expr } - | Expr::FieldAccess { target: expr, .. } - | Expr::TupleIndex { target: expr, .. } => { - walk(expr, env, templates, concrete_sigs, generated, in_progress)?; - } - Expr::ArrayIndex { target, index } => { - walk( - target, - env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - walk(index, env, templates, concrete_sigs, generated, in_progress)?; - } - Expr::SliceIndex { target, start, end } => { - walk( - target, - env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - for bound in [start, end].into_iter().flatten() { - walk(bound, env, templates, concrete_sigs, generated, in_progress)?; - } - } - Expr::BinaryOp { left, right, .. } => { - walk(left, env, templates, concrete_sigs, generated, in_progress)?; - walk(right, env, templates, concrete_sigs, generated, in_progress)?; - } - Expr::ArrayLiteral { elements } | Expr::TupleLiteral { elements } => { - for e in elements.iter_mut() { - walk(e, env, templates, concrete_sigs, generated, in_progress)?; - } - } - Expr::StructInitialization { fields, .. } => { - for (_, e) in fields.iter_mut() { - walk(e, env, templates, concrete_sigs, generated, in_progress)?; - } - } - _ => {} - } - Ok(()) -} - -/// Resolve the base name of a call (`Stack::push` -> `push`). -fn base_name(name: &str) -> &str { - if let Some(idx) = name.rfind("::") { - &name[idx + 2..] - } else { - name - } -} - -fn specialize_call( - name: &mut String, - args: &[Expr], - env: &Env, - templates: &HashMap, - concrete_sigs: &HashMap>, - generated: &mut HashMap, - in_progress: &mut Vec, -) -> Result<(), String> { - let tpl_name = base_name(name).to_string(); - let Some(tpl) = templates.get(&tpl_name) else { - return Ok(()); - }; - if *name != tpl_name { - // Already specialized at this site. - return Ok(()); - } - - if args.len() != tpl.params.len() { - return Err(format!( - "Compile Error: generic function '{}' expects {} argument(s), got {}", - tpl_name, - tpl.params.len(), - args.len() - )); - } - - // Unify inferred argument types against declared parameter types. - let mut subst: HashMap = HashMap::new(); - for (arg, (_, pty)) in args.iter().zip(tpl.params.iter()) { - let Some(mut concrete) = infer_shallow(arg, env, templates, concrete_sigs, generated) - else { - return Err(format!( - "Compile Error: cannot infer type parameter for an argument of '{}' — annotate it first, e.g. `let x: i64 = ...`", - tpl_name - )); - }; - substitute_ty(&mut concrete, &subst); - unify(pty, &concrete, &tpl.type_params, &mut subst, &tpl_name)?; - } - - for tp in &tpl.type_params { - if !subst.contains_key(tp) { - return Err(format!( - "Compile Error: cannot infer type parameter '{}' in call to '{}'", - tp, tpl_name - )); - } - } - - let mangled = mangle(&tpl_name, &subst); - *name = mangled.clone(); - - if generated.contains_key(&mangled) || in_progress.contains(&mangled) { - return Ok(()); - } - - // Substitute the signature and generate a concrete instance body. - let mut inst_params = tpl.params.clone(); - for (_, ty) in inst_params.iter_mut() { - substitute_ty(ty, &subst); - } - let mut inst_ret = tpl.return_type.clone(); - if let Some(rt) = inst_ret.as_mut() { - substitute_ty(rt, &subst); - } - - in_progress.push(mangled.clone()); - let mut inst_body = tpl.body.clone(); - - let result = (|| -> Result<(), String> { - let mut inst_env: Env = HashMap::new(); - for (n, ty) in inst_params.iter() { - inst_env.insert(n.clone(), ty.clone()); - } - for stmt in inst_body.iter_mut() { - substitute_stmt_types(stmt, &subst); - walk( - stmt, - &mut inst_env, - templates, - concrete_sigs, - generated, - in_progress, - )?; - } - Ok(()) - })(); - in_progress.pop(); - result?; - - generated.insert( - mangled.clone(), - Expr::FnDef { - name: mangled, - generics: Vec::new(), - params: inst_params, - return_type: inst_ret, - body: inst_body, - }, - ); - Ok(()) -} - -fn mangle(base: &str, subst: &HashMap) -> String { - let mut parts: Vec = subst - .iter() - .map(|(k, v)| format!("{}{}", k, type_tag(v))) - .collect(); - parts.sort(); - format!("{}__{}", base, parts.join("_")) -} - -fn type_tag(ty: &TrackType) -> String { - match ty { - TrackType::U8 => "u8".into(), - TrackType::I8 => "i8".into(), - TrackType::I32 => "i32".into(), - TrackType::U32 => "u32".into(), - TrackType::I64 => "i64".into(), - TrackType::U64 => "u64".into(), - TrackType::Bool => "bool".into(), - TrackType::Void => "void".into(), - TrackType::Ptr(inner) => format!("p{}", type_tag(inner)), - TrackType::Ref(inner) => format!("r{}", type_tag(inner)), - TrackType::Slice(inner) => format!("s{}", type_tag(inner)), - TrackType::Array(inner, n) => format!("a{}_{}", type_tag(inner), n), - TrackType::Tuple(elems) => { - let tags: Vec = elems.iter().map(type_tag).collect(); - format!("t{}", tags.join(".")) - } - TrackType::Custom(name) => sanitize(name), - } -} - -fn sanitize(name: &str) -> String { - name.chars() - .map(|c| { - if c.is_alphanumeric() || c == '_' { - c - } else { - '_' - } - }) - .collect() -} - -fn unify( - param: &TrackType, - concrete: &TrackType, - type_params: &[String], - subst: &mut HashMap, - ctx: &str, -) -> Result<(), String> { - match param { - TrackType::Custom(name) => { - if type_params.iter().any(|tp| tp == name) { - if let Some(existing) = subst.get(name) { - if existing != concrete { - return Err(format!( - "Compile Error: conflicting types for '{}' in '{}': {:?} vs {:?}", - name, ctx, existing, concrete - )); - } - } else { - subst.insert(name.clone(), concrete.clone()); - } - } - Ok(()) - } - TrackType::Ptr(inner) => { - if let TrackType::Ptr(c) = concrete { - unify(inner, c, type_params, subst, ctx) - } else { - Ok(()) - } - } - TrackType::Ref(inner) => { - if let TrackType::Ref(c) = concrete { - unify(inner, c, type_params, subst, ctx) - } else { - Ok(()) - } - } - TrackType::Slice(inner) => { - if let TrackType::Slice(c) = concrete { - unify(inner, c, type_params, subst, ctx) - } else { - Ok(()) - } - } - TrackType::Array(inner, _) => { - if let TrackType::Array(c, _) = concrete { - unify(inner, c, type_params, subst, ctx) - } else { - Ok(()) - } - } - TrackType::Tuple(elems) => { - if let TrackType::Tuple(cs) = concrete { - for (p, c) in elems.iter().zip(cs.iter()) { - unify(p, c, type_params, subst, ctx)?; - } - } - Ok(()) - } - _ => Ok(()), - } -} - -fn substitute_ty(ty: &mut TrackType, subst: &HashMap) { - match ty { - TrackType::Custom(name) => { - if let Some(concrete) = subst.get(name) { - *ty = concrete.clone(); - } - } - TrackType::Ptr(inner) => substitute_ty(inner, subst), - TrackType::Ref(inner) => substitute_ty(inner, subst), - TrackType::Slice(inner) => substitute_ty(inner, subst), - TrackType::Array(inner, _) => substitute_ty(inner, subst), - TrackType::Tuple(elems) => { - for e in elems { - substitute_ty(e, subst); - } - } - _ => {} - } -} - -/// Rewrite type annotations inside an instantiated statement tree. -fn substitute_stmt_types(expr: &mut Expr, subst: &HashMap) { - match expr { - Expr::LetDef { ty, value, .. } => { - if let Some(t) = ty.as_mut() { - substitute_ty(t, subst); - } - substitute_stmt_types(value, subst); - } - Expr::Return { value } => { - if let Some(v) = value.as_mut() { - substitute_stmt_types(v, subst); - } - } - Expr::IfElse { - then_body, - else_body, - .. - } => { - for s in then_body.iter_mut().chain(else_body.iter_mut()) { - substitute_stmt_types(s, subst); - } - } - Expr::WhileLoop { body, condition } => { - substitute_stmt_types(condition, subst); - for s in body.iter_mut() { - substitute_stmt_types(s, subst); - } - } - Expr::ForIn { iter, body, .. } => { - substitute_stmt_types(iter, subst); - for s in body.iter_mut() { - substitute_stmt_types(s, subst); - } - } - Expr::LensBlock { body, .. } => { - for s in body.iter_mut() { - substitute_stmt_types(s, subst); - } - } - Expr::Match { target, arms } => { - substitute_stmt_types(target, subst); - for arm in arms.iter_mut() { - if let Some(guard) = arm.guard.as_mut() { - substitute_stmt_types(guard, subst); - } - substitute_stmt_types(&mut arm.body, subst); - } - } - Expr::FunctionCall { args, .. } | Expr::MacroCall { args, .. } => { - for a in args.iter_mut() { - substitute_stmt_types(a, subst); - } - } - Expr::Assign { value, target, .. } => { - substitute_stmt_types(value, subst); - substitute_stmt_types(target, subst); - } - _ => {} - } -} - -fn bind_pattern(pattern: &crate::ast::Pattern, elems: &[TrackType], env: &mut Env) { - use crate::ast::Pattern::*; - match pattern { - Tuple(pats) => { - for (p, t) in pats.iter().zip(elems.iter()) { - bind_pattern(p, std::slice::from_ref(t), env); - } - } - Ident(name) => { - if let Some(t) = elems.first() { - env.insert(name.clone(), t.clone()); - } - } - _ => {} - } -} - -fn infer_tuple_shape( - expr: &Expr, - env: &Env, - templates: &HashMap, - concrete_sigs: &HashMap>, - generated: &HashMap, -) -> Result { - infer_shallow(expr, env, templates, concrete_sigs, generated).ok_or(()) -} - -/// Lightweight structural type inference sufficient for choosing a -/// monomorphization substitution. Deliberately conservative: returns None -/// when unsure rather than guessing wrong. -fn infer_shallow( - expr: &Expr, - env: &Env, - templates: &HashMap, - concrete_sigs: &HashMap>, - generated: &HashMap, -) -> Option { - match expr { - Expr::IntLiteral(_) => Some(TrackType::I32), - Expr::BoolLiteral(_) => Some(TrackType::Bool), - Expr::StringLiteral(_) => Some(TrackType::Ptr(Box::new(TrackType::I32))), - Expr::Variable(name) => env.get(name).cloned(), - Expr::BinaryOp { op, left, .. } => { - use crate::ast::BinOp::*; - if matches!(op, Eq | Neq | Lt | Gt | Lte | Gte | And | Or) { - Some(TrackType::Bool) - } else { - infer_shallow(left, env, templates, concrete_sigs, generated) - } - } - Expr::UnaryOp { op, expr } => match op { - crate::ast::UnaryOp::Not => Some(TrackType::Bool), - crate::ast::UnaryOp::Neg => { - infer_shallow(expr, env, templates, concrete_sigs, generated) - } - crate::ast::UnaryOp::Deref => { - match infer_shallow(expr, env, templates, concrete_sigs, generated) { - Some(TrackType::Ptr(inner)) | Some(TrackType::Ref(inner)) => Some(*inner), - _ => None, - } - } - }, - Expr::AddressOf { target } => { - infer_shallow(target, env, templates, concrete_sigs, generated) - .map(|inner| TrackType::Ref(Box::new(inner))) - } - Expr::ArrayLiteral { elements } => { - let elem = elements - .first() - .and_then(|e| infer_shallow(e, env, templates, concrete_sigs, generated))?; - Some(TrackType::Array(Box::new(elem), elements.len())) - } - Expr::TupleLiteral { elements } => { - let mut tys = Vec::new(); - for e in elements { - tys.push(infer_shallow(e, env, templates, concrete_sigs, generated)?); - } - Some(TrackType::Tuple(tys)) - } - Expr::TupleIndex { target, index } => { - match infer_shallow(target, env, templates, concrete_sigs, generated)? { - TrackType::Tuple(mut elems) => { - if *index < elems.len() { - Some(elems.swap_remove(*index)) - } else { - None - } - } - _ => None, - } - } - Expr::ArrayIndex { target, .. } => { - match infer_shallow(target, env, templates, concrete_sigs, generated)? { - TrackType::Array(inner, _) | TrackType::Slice(inner) => Some(*inner), - _ => None, - } - } - Expr::StructInitialization { ty_name, .. } => Some(TrackType::Custom(ty_name.clone())), - Expr::LetDef { value, .. } => { - infer_shallow(value, env, templates, concrete_sigs, generated) - } - Expr::IfElse { then_body, .. } => then_body - .last() - .and_then(|e| infer_shallow(e, env, templates, concrete_sigs, generated)), - Expr::FunctionCall { name, args } => { - // Already-specialized instance? - if let Expr::FnDef { return_type, .. } = generated.get(name)? { - return return_type.clone(); - } - if let Some(rt) = concrete_sigs.get(name) { - return rt.clone(); - } - // Generic template not yet specialized — infer its return via - // argument-driven substitution (best-effort, falls back to Custom). - let base = base_name(name); - let tpl = templates.get(base)?; - let mut subst: HashMap = HashMap::new(); - for (arg, (_, pty)) in args.iter().zip(tpl.params.iter()) { - let concrete = infer_shallow(arg, env, templates, concrete_sigs, generated)?; - unify(pty, &concrete, &tpl.type_params, &mut subst, base).ok()?; - } - let mut ret = tpl.return_type.clone()?; - substitute_ty(&mut ret, &subst); - Some(ret) - } - _ => None, - } -} diff --git a/src/parser/expr.rs b/src/parser/expr.rs deleted file mode 100644 index ed034f3e..00000000 --- a/src/parser/expr.rs +++ /dev/null @@ -1,631 +0,0 @@ -use super::Parser; -use crate::ast::{BinOp, Expr, UnaryOp}; -use crate::lexer::Token; - -impl Parser { - pub fn parse_expr(&mut self) -> Result { - let left = self.parse_or()?; - // `a[s..]`: leave an open-ended `..` for the index parser. - let open_slice = matches!(self.tokens.get(self.pos + 1), Some((Token::RBracket, _))); - if self.peek() == Some(&Token::DotDot) && !open_slice { - self.advance(); - let right = self.parse_or()?; - Ok(Expr::Range { - start: Box::new(left), - end: Box::new(right), - }) - } else { - Ok(left) - } - } - - fn parse_or(&mut self) -> Result { - let mut left = self.parse_and()?; - while self.peek() == Some(&Token::PipePipe) { - self.advance(); - let right = self.parse_and()?; - left = Expr::BinaryOp { - op: BinOp::Or, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_and(&mut self) -> Result { - let mut left = self.parse_comparison()?; - while self.peek() == Some(&Token::AmpAmp) { - self.advance(); - let right = self.parse_comparison()?; - left = Expr::BinaryOp { - op: BinOp::And, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_comparison(&mut self) -> Result { - let mut left = self.parse_bitwise()?; - loop { - let op = match self.peek() { - Some(Token::EqEq) => BinOp::Eq, - Some(Token::Neq) => BinOp::Neq, - Some(Token::Lt) => BinOp::Lt, - Some(Token::Gt) => BinOp::Gt, - Some(Token::Lte) => BinOp::Lte, - Some(Token::Gte) => BinOp::Gte, - _ => break, - }; - self.advance(); - let right = self.parse_bitwise()?; - left = Expr::BinaryOp { - op, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_bitwise(&mut self) -> Result { - let mut left = self.parse_shift()?; - loop { - let op = match self.peek() { - Some(Token::Amp) - if self - .tokens - .get(self.pos + 1) - .is_some_and(|(t, _)| !matches!(t, Token::Amp)) => - { - BinOp::BitAnd - } - Some(Token::Pipe) - if self - .tokens - .get(self.pos + 1) - .is_some_and(|(t, _)| !matches!(t, Token::Pipe)) => - { - BinOp::BitOr - } - _ => break, - }; - self.advance(); - let right = self.parse_shift()?; - left = Expr::BinaryOp { - op, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_shift(&mut self) -> Result { - let mut left = self.parse_additive()?; - loop { - let op = match self.peek() { - Some(Token::Shl) => BinOp::Shl, - Some(Token::Shr) => BinOp::Shr, - _ => break, - }; - self.advance(); - let right = self.parse_additive()?; - left = Expr::BinaryOp { - op, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_additive(&mut self) -> Result { - let mut left = self.parse_multiplicative()?; - loop { - let op = match self.peek() { - Some(Token::Plus) => BinOp::Add, - Some(Token::Minus) => BinOp::Sub, - _ => break, - }; - self.advance(); - let right = self.parse_multiplicative()?; - left = Expr::BinaryOp { - op, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_multiplicative(&mut self) -> Result { - let mut left = self.parse_unary()?; - loop { - let op = match self.peek() { - Some(Token::Star) => BinOp::Mul, - Some(Token::Slash) => BinOp::Div, - Some(Token::Percent) => BinOp::Mod, - _ => break, - }; - self.advance(); - let right = self.parse_unary()?; - left = Expr::BinaryOp { - op, - left: Box::new(left), - right: Box::new(right), - }; - } - Ok(left) - } - - fn parse_unary(&mut self) -> Result { - match self.peek().cloned() { - Some(Token::Minus) => { - self.advance(); - let expr = self.parse_unary()?; - Ok(Expr::UnaryOp { - op: UnaryOp::Neg, - expr: Box::new(expr), - }) - } - Some(Token::Bang) => { - self.advance(); - let expr = self.parse_unary()?; - Ok(Expr::UnaryOp { - op: UnaryOp::Not, - expr: Box::new(expr), - }) - } - Some(Token::Star) => { - self.advance(); - let expr = self.parse_unary()?; - Ok(Expr::UnaryOp { - op: UnaryOp::Deref, - expr: Box::new(expr), - }) - } - Some(Token::Amp) => { - self.advance(); - // &mut x and &x are both address-of; mut is consumed but not stored - if self.peek() == Some(&Token::Mut) { - self.advance(); - } - let expr = self.parse_unary()?; - Ok(Expr::AddressOf { - target: Box::new(expr), - }) - } - _ => self.parse_postfix(), - } - } - - fn parse_postfix(&mut self) -> Result { - let mut expr = self.parse_primary()?; - - loop { - match self.peek() { - Some(Token::Dot) => { - self.advance(); - match self.peek() { - Some(Token::Int(idx)) => { - let idx = *idx as usize; - self.advance(); - expr = Expr::TupleIndex { - target: Box::new(expr), - index: idx, - }; - } - _ => { - let method_name = self.expect_ident()?; - if self.peek() != Some(&Token::LParen) { - expr = Expr::FieldAccess { - target: Box::new(expr), - field: method_name, - }; - continue; - } - self.expect(&Token::LParen)?; - let mut args = vec![expr]; - if self.peek() != Some(&Token::RParen) { - args.push(self.parse_expr()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - args.push(self.parse_expr()?); - } - } - self.expect(&Token::RParen)?; - expr = Expr::FunctionCall { - name: method_name, - args, - }; - } - } - } - Some(Token::LBracket) => { - // Array index: expr[index] or Slice index: expr[start..end] - self.advance(); - if self.peek() == Some(&Token::DotDot) { - self.advance(); - let end = if self.peek() != Some(&Token::RBracket) { - Some(Box::new(self.parse_expr()?)) - } else { - None - }; - self.expect(&Token::RBracket)?; - expr = Expr::SliceIndex { - target: Box::new(expr), - start: None, - end, - }; - } else { - let start_expr = self.parse_expr()?; - if let Expr::Range { start, end } = start_expr { - self.expect(&Token::RBracket)?; - expr = Expr::SliceIndex { - target: Box::new(expr), - start: Some(start), - end: Some(end), - }; - } else if self.peek() == Some(&Token::DotDot) { - self.advance(); - let end = if self.peek() != Some(&Token::RBracket) { - Some(Box::new(self.parse_expr()?)) - } else { - None - }; - self.expect(&Token::RBracket)?; - expr = Expr::SliceIndex { - target: Box::new(expr), - start: Some(Box::new(start_expr)), - end, - }; - } else { - self.expect(&Token::RBracket)?; - expr = Expr::ArrayIndex { - target: Box::new(expr), - index: Box::new(start_expr), - }; - } - } - } - Some(Token::LParen) => { - // Function call: expr(args) - if let Expr::Variable(ref name) = expr { - let name = name.clone(); - self.advance(); - let mut args = Vec::new(); - if self.peek() != Some(&Token::RParen) { - args.push(self.parse_expr()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - args.push(self.parse_expr()?); - } - } - self.expect(&Token::RParen)?; - expr = Expr::FunctionCall { name, args }; - } else { - break; - } - } - _ => break, - } - } - - Ok(expr) - } - - fn parse_primary(&mut self) -> Result { - match self.peek().cloned() { - Some(Token::Int(val)) => { - self.advance(); - Ok(Expr::IntLiteral(val)) - } - Some(Token::Str(s)) => { - self.advance(); - Ok(Expr::StringLiteral(s)) - } - Some(Token::True) => { - self.advance(); - Ok(Expr::BoolLiteral(true)) - } - Some(Token::False) => { - self.advance(); - Ok(Expr::BoolLiteral(false)) - } - Some(Token::If) => self.parse_if_expr(), - Some(Token::At) => self.parse_macro_call(), - Some(Token::Match) => self.parse_match(), - Some(Token::Ident(_)) => { - let name = self.parse_namespaced_ident()?; - - // Struct init: TypeName { fields } - if self.allow_struct && self.peek() == Some(&Token::LBrace) { - self.advance(); - let mut fields = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - let field_name = self.expect_ident()?; - self.expect(&Token::Colon)?; - let field_val = self.parse_expr()?; - fields.push((field_name, field_val)); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } - } - self.expect(&Token::RBrace)?; - return Ok(Expr::StructInitialization { - ty_name: name, - fields, - }); - } - - Ok(Expr::Variable(name)) - } - Some(Token::LParen) => { - self.advance(); - if self.peek() == Some(&Token::RParen) { - self.advance(); - Ok(Expr::TupleLiteral { - elements: Vec::new(), - }) - } else { - let first = self.parse_expr()?; - if self.peek() == Some(&Token::Comma) { - self.advance(); - let mut elements = vec![first]; - while self.peek() != Some(&Token::RParen) { - elements.push(self.parse_expr()?); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } - } - self.expect(&Token::RParen)?; - Ok(Expr::TupleLiteral { elements }) - } else { - self.expect(&Token::RParen)?; - Ok(first) - } - } - } - Some(Token::LBracket) => { - // Array literal: [expr, expr, ...] - self.advance(); - let mut elements = Vec::new(); - if self.peek() != Some(&Token::RBracket) { - elements.push(self.parse_expr()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - elements.push(self.parse_expr()?); - } - } - self.expect(&Token::RBracket)?; - Ok(Expr::ArrayLiteral { elements }) - } - other => Err(format!("Parser error: unexpected token {:?}", other)), - } - } - - fn parse_if_expr(&mut self) -> Result { - self.advance(); // consume 'if' - self.allow_struct = false; - let condition = self.parse_expr(); - self.allow_struct = true; - let condition = condition?; - self.expect(&Token::LBrace)?; - let mut then_body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - then_body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - let else_body = if self.peek() == Some(&Token::Else) { - self.advance(); - if self.peek() == Some(&Token::If) { - vec![self.parse_if_expr()?] - } else { - self.expect(&Token::LBrace)?; - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - body - } - } else { - Vec::new() - }; - - Ok(Expr::IfElse { - condition: Box::new(condition), - then_body, - else_body, - }) - } - - pub fn parse_namespaced_ident(&mut self) -> Result { - let mut name = self.expect_ident()?; - while self.peek() == Some(&Token::ColonColon) { - self.advance(); - let sub_name = self.expect_ident()?; - name = format!("{}::{}", name, sub_name); - } - Ok(name) - } - - fn parse_macro_call(&mut self) -> Result { - self.advance(); // consume '@' - let name = self.expect_ident()?; - - let mut args = Vec::new(); - let mut body = None; - - if self.peek() == Some(&Token::LParen) { - self.advance(); - if self.peek() != Some(&Token::RParen) { - args.push(self.parse_expr()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - args.push(self.parse_expr()?); - } - } - self.expect(&Token::RParen)?; - } - - if self.peek() == Some(&Token::LBrace) { - self.advance(); - let mut block_body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - block_body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - body = Some(block_body); - } - - Ok(Expr::MacroCall { name, args, body }) - } - - fn parse_match(&mut self) -> Result { - self.advance(); // consume 'match' - let saved_allow = self.allow_struct; - self.allow_struct = false; - let target = self.parse_expr()?; - self.allow_struct = saved_allow; - self.expect(&Token::LBrace)?; - - let mut arms = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - let pattern = self.parse_pattern()?; - - let guard = if self.peek() == Some(&Token::If) { - self.advance(); - Some(self.parse_expr()?) - } else { - None - }; - - self.expect(&Token::FatArrow)?; - let body = self.parse_statement()?; - - arms.push(crate::ast::MatchArm { - pattern, - guard, - body, - }); - - if self.peek() == Some(&Token::Comma) { - self.advance(); - } - } - self.expect(&Token::RBrace)?; - - Ok(Expr::Match { - target: Box::new(target), - arms, - }) - } - - pub fn parse_pattern(&mut self) -> Result { - match self.peek().cloned() { - Some(Token::Underscore) => { - self.advance(); - Ok(crate::ast::Pattern::Wildcard) - } - Some(Token::Int(val)) => { - self.advance(); - Ok(crate::ast::Pattern::Literal(Box::new(Expr::IntLiteral( - val, - )))) - } - Some(Token::True) => { - self.advance(); - Ok(crate::ast::Pattern::Literal(Box::new(Expr::BoolLiteral( - true, - )))) - } - Some(Token::False) => { - self.advance(); - Ok(crate::ast::Pattern::Literal(Box::new(Expr::BoolLiteral( - false, - )))) - } - Some(Token::Str(s)) => { - self.advance(); - Ok(crate::ast::Pattern::Literal(Box::new(Expr::StringLiteral( - s, - )))) - } - Some(Token::LParen) => { - self.advance(); - let mut patterns = Vec::new(); - if self.peek() != Some(&Token::RParen) { - patterns.push(self.parse_pattern()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - if self.peek() == Some(&Token::RParen) { - break; - } - patterns.push(self.parse_pattern()?); - } - } - self.expect(&Token::RParen)?; - Ok(crate::ast::Pattern::Tuple(patterns)) - } - Some(Token::Ident(_)) => { - let name = self.parse_namespaced_ident()?; - if name.contains("::") { - let parts: Vec<&str> = name.split("::").collect(); - let enum_or_union = parts[0].to_string(); - let variant = parts[1].to_string(); - - let bindings = if self.peek() == Some(&Token::LParen) { - self.advance(); - let mut pats = Vec::new(); - if self.peek() != Some(&Token::RParen) { - pats.push(self.parse_pattern()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - if self.peek() == Some(&Token::RParen) { - break; - } - pats.push(self.parse_pattern()?); - } - } - self.expect(&Token::RParen)?; - pats - } else { - Vec::new() - }; - - Ok(crate::ast::Pattern::Variant { - enum_or_union, - variant, - bindings, - }) - } else if self.peek() == Some(&Token::LBrace) { - self.advance(); - let mut fields = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - let fname = self.expect_ident()?; - let pat = if self.peek() == Some(&Token::Colon) { - self.advance(); - self.parse_pattern()? - } else { - crate::ast::Pattern::Ident(fname.clone()) - }; - fields.push((fname, pat)); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } - } - self.expect(&Token::RBrace)?; - Ok(crate::ast::Pattern::Struct { name, fields }) - } else { - Ok(crate::ast::Pattern::Ident(name)) - } - } - other => Err(format!("Expected pattern, got {:?}", other)), - } - } -} diff --git a/src/parser/mod.rs b/src/parser/mod.rs deleted file mode 100644 index 432f8940..00000000 --- a/src/parser/mod.rs +++ /dev/null @@ -1,160 +0,0 @@ -use crate::ast::{Expr, TrackType}; -use crate::lexer::Token; - -pub struct Parser { - tokens: Vec<(Token, std::ops::Range)>, - pos: usize, - pub allow_struct: bool, -} - -impl Parser { - pub fn new(tokens: Vec<(Token, std::ops::Range)>, _source: String) -> Self { - Self { - tokens, - pos: 0, - allow_struct: true, - } - } - - pub fn peek(&self) -> Option<&Token> { - self.tokens.get(self.pos).map(|(t, _)| t) - } - - pub fn advance(&mut self) -> Option<(Token, std::ops::Range)> { - if self.pos < self.tokens.len() { - let tok = self.tokens[self.pos].clone(); - self.pos += 1; - Some(tok) - } else { - None - } - } - - pub fn expect(&mut self, expected: &Token) -> Result<(), String> { - match self.advance() { - Some((ref tok, _)) if tok == expected => Ok(()), - other => Err(format!( - "Parser error: expected {:?}, got {:?}", - expected, - other.map(|(t, _)| t) - )), - } - } - - pub fn expect_ident(&mut self) -> Result { - match self.advance() { - Some((Token::Ident(name), _)) => Ok(name), - other => Err(format!( - "Parser error: expected identifier, got {:?}", - other.map(|(t, _)| t) - )), - } - } - - pub fn parse_type(&mut self) -> Result { - match self.peek().cloned() { - Some(Token::TyU8) => { - self.advance(); - Ok(TrackType::U8) - } - Some(Token::TyI8) => { - self.advance(); - Ok(TrackType::I8) - } - Some(Token::TyI32) => { - self.advance(); - Ok(TrackType::I32) - } - Some(Token::TyU32) => { - self.advance(); - Ok(TrackType::U32) - } - Some(Token::TyI64) => { - self.advance(); - Ok(TrackType::I64) - } - Some(Token::TyU64) => { - self.advance(); - Ok(TrackType::U64) - } - Some(Token::TyBool) => { - self.advance(); - Ok(TrackType::Bool) - } - Some(Token::TyVoid) => { - self.advance(); - Ok(TrackType::Void) - } - Some(Token::TyPtr) => { - self.advance(); - self.expect(&Token::Lt)?; - let inner = self.parse_type()?; - self.expect(&Token::Gt)?; - Ok(TrackType::Ptr(Box::new(inner))) - } - Some(Token::Amp) => { - self.advance(); - let inner = self.parse_type()?; - Ok(TrackType::Ref(Box::new(inner))) - } - Some(Token::Ident(name)) => { - self.advance(); - Ok(TrackType::Custom(name)) - } - Some(Token::LBracket) => { - self.advance(); - if self.peek() == Some(&Token::RBracket) { - self.advance(); - let elem_type = self.parse_type()?; - Ok(TrackType::Slice(Box::new(elem_type))) - } else { - let elem_type = self.parse_type()?; - if self.peek() == Some(&Token::RBracket) { - self.advance(); - Ok(TrackType::Slice(Box::new(elem_type))) - } else { - self.expect(&Token::Semicolon)?; - match self.advance() { - Some((Token::Int(n), _)) => { - self.expect(&Token::RBracket)?; - Ok(TrackType::Array(Box::new(elem_type), n as usize)) - } - other => Err(format!( - "Parser error: expected array size, got {:?}", - other.map(|(t, _)| t) - )), - } - } - } - } - Some(Token::LParen) => { - self.advance(); - let mut types = Vec::new(); - if self.peek() != Some(&Token::RParen) { - types.push(self.parse_type()?); - while self.peek() == Some(&Token::Comma) { - self.advance(); - if self.peek() == Some(&Token::RParen) { - break; - } - types.push(self.parse_type()?); - } - } - self.expect(&Token::RParen)?; - Ok(TrackType::Tuple(types)) - } - other => Err(format!("Parser error: expected type, got {:?}", other)), - } - } - - pub fn parse_program(&mut self) -> Result, String> { - let mut stmts = Vec::new(); - while self.peek().is_some() { - stmts.push(self.parse_statement()?); - } - Ok(stmts) - } -} - -mod expr; -mod stmt; diff --git a/src/parser/stmt.rs b/src/parser/stmt.rs deleted file mode 100644 index ba302fc1..00000000 --- a/src/parser/stmt.rs +++ /dev/null @@ -1,459 +0,0 @@ -use super::Parser; -use crate::ast::Expr; -use crate::lexer::Token; - -impl Parser { - pub fn parse_statement(&mut self) -> Result { - let expr = match self.peek() { - Some(Token::Let) => self.parse_let()?, - Some(Token::With) => self.parse_with()?, - Some(Token::Fn) => self.parse_fn()?, - Some(Token::If) => self.parse_if()?, - Some(Token::While) => self.parse_while()?, - Some(Token::For) => self.parse_for()?, - Some(Token::Return) => self.parse_return()?, - Some(Token::Import) | Some(Token::Use) => self.parse_import()?, - - Some(Token::Const) => self.parse_const()?, - Some(Token::TypeDef) => self.parse_type_alias()?, - Some(Token::Struct) => self.parse_struct()?, - Some(Token::AtMacro) => self.parse_macro_def()?, - Some(Token::Enum) => self.parse_enum()?, - Some(Token::Union) => self.parse_union()?, - _ => { - let expr = self.parse_expr()?; - // Handle assignment: expr = expr - if self.peek() == Some(&Token::Eq) { - self.advance(); - let value = self.parse_expr()?; - Expr::Assign { - target: Box::new(expr), - value: Box::new(value), - } - } else { - expr - } - } - }; - if self.peek() == Some(&Token::Semicolon) { - self.advance(); - } - Ok(expr) - } - - fn parse_let(&mut self) -> Result { - self.advance(); // consume 'let' - let mutable = if self.peek() == Some(&Token::Mut) { - self.advance(); - true - } else { - false - }; - - if self.peek() == Some(&Token::LParen) { - let pattern = self.parse_pattern()?; - self.expect(&Token::Eq)?; - let val = self.parse_expr()?; - Ok(Expr::LetDestructure { - pattern, - mutable, - value: Box::new(val), - }) - } else { - let name = self.expect_ident()?; - let ty = if self.peek() == Some(&Token::Colon) { - self.advance(); - Some(self.parse_type()?) - } else { - None - }; - - self.expect(&Token::Eq)?; - let val = self.parse_expr()?; - Ok(Expr::LetDef { - name, - mutable, - ty, - value: Box::new(val), - }) - } - } - - fn parse_with(&mut self) -> Result { - self.advance(); // consume 'with' - let target = self.expect_ident()?; - self.expect(&Token::Arrow)?; - let lens_name = self.expect_ident()?; - self.expect(&Token::LBrace)?; - - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - Ok(Expr::LensBlock { - target, - lens_name, - body, - }) - } - - fn parse_fn(&mut self) -> Result { - self.advance(); // consume 'fn' - let name = self.expect_ident()?; - - // Optional generic parameters: fn name(...) - let generics = if self.peek() == Some(&Token::Lt) { - self.advance(); - let mut params = Vec::new(); - loop { - params.push(self.expect_ident()?); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } else { - break; - } - } - self.expect(&Token::Gt)?; - params - } else { - Vec::new() - }; - - self.expect(&Token::LParen)?; - - let mut params = Vec::new(); - if self.peek() != Some(&Token::RParen) { - loop { - let param_name = self.expect_ident()?; - self.expect(&Token::Colon)?; - let param_type = self.parse_type()?; - params.push((param_name, param_type)); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } else { - break; - } - } - } - self.expect(&Token::RParen)?; - - // Optional return type - let return_type = if self.peek() == Some(&Token::Arrow) { - self.advance(); - Some(self.parse_type()?) - } else { - None - }; - - self.expect(&Token::LBrace)?; - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - Ok(Expr::FnDef { - name, - generics, - params, - return_type, - body, - }) - } - - fn parse_if(&mut self) -> Result { - self.advance(); // consume 'if' - self.allow_struct = false; - let condition = self.parse_expr(); - self.allow_struct = true; - let condition = condition?; - self.expect(&Token::LBrace)?; - let mut then_body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - then_body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - let else_body = if self.peek() == Some(&Token::Else) { - self.advance(); - if self.peek() == Some(&Token::If) { - // else if => single-element else body with another IfElse - vec![self.parse_if()?] - } else { - self.expect(&Token::LBrace)?; - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - body - } - } else { - Vec::new() - }; - - Ok(Expr::IfElse { - condition: Box::new(condition), - then_body, - else_body, - }) - } - - fn parse_while(&mut self) -> Result { - self.advance(); // consume 'while' - self.allow_struct = false; - let condition = self.parse_expr(); - self.allow_struct = true; - let condition = condition?; - self.expect(&Token::LBrace)?; - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - Ok(Expr::WhileLoop { - condition: Box::new(condition), - body, - }) - } - - fn parse_for(&mut self) -> Result { - self.advance(); // consume 'for' - let var = self.expect_ident()?; - self.expect(&Token::In)?; - self.allow_struct = false; - let iter = self.parse_expr(); - self.allow_struct = true; - let iter = iter?; - self.expect(&Token::LBrace)?; - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) && self.peek().is_some() { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - Ok(Expr::ForIn { - var, - iter: Box::new(iter), - body, - }) - } - - fn parse_return(&mut self) -> Result { - self.advance(); // consume 'return' - let value = if self.peek() == Some(&Token::Semicolon) || self.peek().is_none() { - None - } else { - Some(Box::new(self.parse_expr()?)) - }; - Ok(Expr::Return { value }) - } - - fn parse_import(&mut self) -> Result { - self.advance(); // consume 'import' - // Accept both quoted paths ("std/io") and bare identifiers (std / std::io) - let path = match self.advance() { - Some((Token::Str(s), _)) => s, - Some((Token::Ident(s), _)) => { - let mut p = s; - while self.peek() == Some(&Token::ColonColon) { - self.advance(); - p.push_str("::"); - p.push_str(&self.expect_ident()?); - } - p - } - other => { - return Err(format!( - "Expected string path after import, got {:?}", - other.map(|(t, _)| t) - )); - } - }; - - let alias = if self.peek() == Some(&Token::As) { - self.advance(); - Some(self.expect_ident()?) - } else { - None - }; - - let imports = if self.peek() == Some(&Token::ColonColon) { - self.advance(); - self.expect(&Token::LBrace)?; - let mut items = Vec::new(); - while self.peek() != Some(&Token::RBrace) && self.peek().is_some() { - let item = self.expect_ident()?; - items.push(item); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } else { - break; - } - } - self.expect(&Token::RBrace)?; - Some(items) - } else { - None - }; - - Ok(Expr::Use { - path, - imports, - alias, - }) - } - - fn parse_const(&mut self) -> Result { - self.advance(); // consume 'const' - let name = self.expect_ident()?; - self.expect(&Token::Eq)?; - let value = self.parse_expr()?; - Ok(Expr::ConstDef { - name, - value: Box::new(value), - }) - } - - fn parse_type_alias(&mut self) -> Result { - self.advance(); // consume 'type' - let name = self.expect_ident()?; - self.expect(&Token::Eq)?; - let target = self.parse_type()?; - Ok(Expr::TypeAlias { name, target }) - } - - fn parse_struct(&mut self) -> Result { - self.advance(); // consume 'struct' - let name = self.expect_ident()?; - self.expect(&Token::LBrace)?; - let mut fields = Vec::new(); - while self.peek() != Some(&Token::RBrace) && self.peek().is_some() { - let field_name = self.expect_ident()?; - self.expect(&Token::Colon)?; - let field_type = self.parse_type()?; - fields.push((field_name, field_type)); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } else { - break; - } - } - self.expect(&Token::RBrace)?; - Ok(Expr::StructDef { name, fields }) - } - - fn parse_macro_def(&mut self) -> Result { - self.advance(); // consume '@macro' - let name = self.expect_ident()?; - self.expect(&Token::LParen)?; - let mut params = Vec::new(); - if self.peek() != Some(&Token::RParen) { - let param_name = self.expect_ident()?; - self.expect(&Token::Colon)?; - let param_ty = self.parse_type()?; - params.push((param_name, param_ty)); - while self.peek() == Some(&Token::Comma) { - self.advance(); - let param_name = self.expect_ident()?; - self.expect(&Token::Colon)?; - let param_ty = self.parse_type()?; - params.push((param_name, param_ty)); - } - } - self.expect(&Token::RParen)?; - - let return_type = if self.peek() == Some(&Token::Arrow) { - self.advance(); - Some(self.parse_type()?) - } else { - None - }; - - self.expect(&Token::LBrace)?; - let mut body = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - body.push(self.parse_statement()?); - } - self.expect(&Token::RBrace)?; - - Ok(Expr::MacroDef { - name, - params, - return_type, - body, - }) - } - - fn parse_enum(&mut self) -> Result { - self.advance(); // consume 'enum' - let name = self.expect_ident()?; - - let underlying_type = if self.peek() == Some(&Token::Colon) { - self.advance(); - Some(self.parse_type()?) - } else { - None - }; - - self.expect(&Token::LBrace)?; - let mut variants = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - let variant_name = self.expect_ident()?; - let variant_value = if self.peek() == Some(&Token::Eq) { - self.advance(); - Some(self.parse_expr()?) - } else { - None - }; - variants.push((variant_name, variant_value)); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } - } - self.expect(&Token::RBrace)?; - - Ok(Expr::EnumDef { - name, - underlying_type, - variants, - }) - } - - fn parse_union(&mut self) -> Result { - self.advance(); // consume 'union' - let name = self.expect_ident()?; - - if self.peek() == Some(&Token::LParen) { - self.advance(); - while self.peek() != Some(&Token::RParen) { - self.advance(); - } - self.expect(&Token::RParen)?; - } - - self.expect(&Token::LBrace)?; - let mut variants = Vec::new(); - while self.peek() != Some(&Token::RBrace) { - let variant_name = self.expect_ident()?; - let variant_type = if self.peek() == Some(&Token::LParen) { - self.advance(); - let ty = self.parse_type()?; - self.expect(&Token::RParen)?; - Some(ty) - } else { - None - }; - variants.push((variant_name, variant_type)); - if self.peek() == Some(&Token::Comma) { - self.advance(); - } - } - self.expect(&Token::RBrace)?; - - Ok(Expr::UnionDef { name, variants }) - } -} diff --git a/src/yard/builder.rs b/src/yard/builder.rs deleted file mode 100644 index 5d6a9498..00000000 --- a/src/yard/builder.rs +++ /dev/null @@ -1,627 +0,0 @@ -use std::fs; -use std::path::{Path, PathBuf}; -use std::process; -use std::sync::{Arc, Mutex}; -use std::thread; - -use super::cache::BuildCache; -use super::linker::LinkerEngine; -use super::manifest::Manifest; -use super::resolver; - -pub struct ParallelBuilder; - -struct BuildTask { - trk_file: PathBuf, - rel_path: String, - source: String, - hash: String, - obj_path: PathBuf, - is_cached: bool, -} - -impl ParallelBuilder { - pub fn build(project_root: &Path, manifest: &Manifest) -> Result<(), String> { - println!( - " Building {} v{}", - manifest.package.name, manifest.package.version - ); - - // Resolve dependencies - let deps = resolver::resolve(manifest, project_root)?; - for dep in &deps { - match &dep.source { - resolver::DepSource::Local(path) => { - println!( - " Using dependency: {} v{} (local path: {})", - dep.name, - dep.version, - path.display() - ); - } - resolver::DepSource::Git { url, branch } => { - println!( - " Using dependency: {} v{} (git: {}, branch: {:?})", - dep.name, dep.version, url, branch - ); - } - resolver::DepSource::Registry(version) => { - println!( - " Using dependency: {} v{} (registry version: {})", - dep.name, dep.version, version - ); - } - } - } - - let src_dir = project_root.join(&manifest.build.src); - if !src_dir.exists() { - return Err(format!( - "Source directory '{}' not found", - src_dir.display() - )); - } - - let mut trk_files = find_trk_files(&src_dir)?; - // Exclude Track test files from the main build — they are built - // separately via `yard test` (src/*_test.trk, tests/**/*.trk) - trk_files.retain(|p| { - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - !name.contains("_test") && !p.to_string_lossy().contains("/tests/") - }); - if trk_files.is_empty() { - return Err("No .trk source files found".to_string()); - } - - let target_dir = project_root.join("target"); - fs::create_dir_all(&target_dir) - .map_err(|e| format!("Failed to create target directory: {}", e))?; - - let mut cache = BuildCache::load(&target_dir); - - // An object depends on its own source, on declarations imported from - // other package modules (constants, enum layouts, aliases), and on - // the compiler itself, so the cache key covers all three. - let fingerprint = build_fingerprint(&trk_files)?; - - // Prepare build tasks - let mut tasks = Vec::new(); - for trk_file in trk_files { - let rel_path = trk_file - .strip_prefix(project_root) - .unwrap_or(&trk_file) - .to_string_lossy() - .to_string(); - - let source = fs::read_to_string(&trk_file) - .map_err(|e| format!("Failed to read '{}': {}", trk_file.display(), e))?; - - // Preserve module paths in a separate namespace so equal basenames - // cannot race with each other or overwrite the runtime object. - let module_path = trk_file - .strip_prefix(&src_dir) - .map_err(|e| format!("Invalid source path '{}': {}", trk_file.display(), e))?; - let obj_path = target_dir - .join("objects") - .join(module_path) - .with_extension("o"); - if let Some(parent) = obj_path.parent() { - fs::create_dir_all(parent) - .map_err(|e| format!("Failed to create object directory: {}", e))?; - } - - let hash = BuildCache::compute_hash(&format!("{}\0{}", fingerprint, source)); - let is_cached = cache.is_cached(&rel_path, &hash, &obj_path); - - tasks.push(BuildTask { - trk_file, - rel_path, - source, - hash, - obj_path, - is_cached, - }); - } - - let total_files = tasks.len(); - let cached_count = tasks.iter().filter(|t| t.is_cached).count(); - - let num_workers = thread::available_parallelism() - .map(|n| n.get()) - .unwrap_or(4); - - let shared_tasks = Arc::new(Mutex::new( - tasks.into_iter().enumerate().collect::>(), - )); - let results = Arc::new(Mutex::new(Vec::new())); - - let mut handles = Vec::new(); - - let target_isa = crate::codegen::CodeGen::create_default_isa(); - for _ in 0..num_workers { - let shared_tasks = Arc::clone(&shared_tasks); - let results = Arc::clone(&results); - let target_isa = Arc::clone(&target_isa); - - let handle = thread::spawn(move || { - loop { - let task_option = { - let mut lock = shared_tasks.lock().unwrap(); - lock.pop() - }; - - let (idx, task) = match task_option { - Some(t) => t, - None => break, - }; - - if task.is_cached { - results - .lock() - .unwrap() - .push((idx, Ok((task.rel_path, task.hash, task.obj_path)))); - continue; - } - - // Compile file: Lex -> Parse -> LinearCheck -> Cranelift Codegen - let res = (|| -> Result<(String, String, PathBuf), String> { - let tokens = crate::lexer::Lexer::tokenize(&task.source) - .map_err(|e| format!("{}: {}", task.trk_file.display(), e))?; - - let mut parser = crate::parser::Parser::new(tokens, task.source.clone()); - let mut program = parser - .parse_program() - .map_err(|e| format!("{}: {}", task.trk_file.display(), e))?; - - crate::mono::monomorphize(&mut program) - .map_err(|e| format!("{}: {}", task.trk_file.display(), e))?; - - let mut checker = crate::checker::LinearChecker::new(); - checker - .check_program(&program) - .map_err(|e| format!("{}: {}", task.trk_file.display(), e))?; - - let mod_name = task - .trk_file - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("module"); - let mut codegen = - crate::codegen::CodeGen::new_with_isa(mod_name, target_isa.clone()); - codegen.set_type_info(checker.type_info.clone()); - codegen.compile_program(&program); - - codegen.write_object_file(&task.obj_path)?; - - Ok((task.rel_path, task.hash, task.obj_path)) - })(); - - results.lock().unwrap().push((idx, res)); - } - }); - - handles.push(handle); - } - - for handle in handles { - if handle.join().is_err() { - return Err("Parallel builder worker thread panicked during execution".to_string()); - } - } - - let mut obj_files = Vec::new(); - let mut compiled_results = match Arc::try_unwrap(results) { - Ok(mutex) => mutex.into_inner().unwrap_or_default(), - Err(arc) => arc.lock().unwrap().clone(), - }; - - // Report the first source-order failure, independent of worker timing. - compiled_results.sort_by_key(|(idx, _)| *idx); - for (_, res) in compiled_results { - match res { - Ok((rel_path, hash, obj_path)) => { - cache.update(rel_path, hash); - obj_files.push(obj_path); - } - Err(e) => return Err(e), - } - } - - // Save build cache metadata - cache.save(&target_dir)?; - - // Sort obj_files deterministically for reproducible links - obj_files.sort(); - - let exe_name = Path::new(&manifest.package.name) - .file_name() - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_else(|| manifest.package.name.clone()); - let exe_path = target_dir.join(exe_name); - - LinkerEngine::link_binary(&obj_files, &exe_path, &target_dir)?; - - println!( - "✓ Built {} ({} file{}, {} cached)", - exe_path.display(), - total_files, - if total_files == 1 { "" } else { "s" }, - cached_count - ); - - Ok(()) - } - - pub fn check(project_root: &Path, manifest: &Manifest) -> Result<(), String> { - println!( - " Checking {} v{}", - manifest.package.name, manifest.package.version - ); - - let src_dir = project_root.join(&manifest.build.src); - if !src_dir.exists() { - return Err(format!( - "Source directory '{}' not found", - src_dir.display() - )); - } - - let trk_files = find_trk_files(&src_dir)?; - if trk_files.is_empty() { - return Err("No .trk source files found".to_string()); - } - - let num_workers = thread::available_parallelism() - .map(|n| n.get()) - .unwrap_or(4); - - let shared_files = Arc::new(Mutex::new(trk_files.clone())); - let errors = Arc::new(Mutex::new(Vec::new())); - - let mut handles = Vec::new(); - - for _ in 0..num_workers { - let shared_files = Arc::clone(&shared_files); - let errors = Arc::clone(&errors); - - let handle = thread::spawn(move || { - loop { - let file_option = { - let mut lock = shared_files.lock().unwrap(); - lock.pop() - }; - - let trk_file = match file_option { - Some(f) => f, - None => break, - }; - - let source = match fs::read_to_string(&trk_file) { - Ok(s) => s, - Err(e) => { - errors - .lock() - .unwrap() - .push(format!("{}: {}", trk_file.display(), e)); - continue; - } - }; - - let tokens = match crate::lexer::Lexer::tokenize(&source) { - Ok(t) => t, - Err(e) => { - errors - .lock() - .unwrap() - .push(format!("{}: {}", trk_file.display(), e)); - continue; - } - }; - - let mut parser = crate::parser::Parser::new(tokens, source.clone()); - let mut program = match parser.parse_program() { - Ok(p) => p, - Err(e) => { - errors - .lock() - .unwrap() - .push(format!("{}: {}", trk_file.display(), e)); - continue; - } - }; - - if let Err(e) = crate::mono::monomorphize(&mut program) { - errors - .lock() - .unwrap() - .push(format!("{}: {}", trk_file.display(), e)); - continue; - } - - let mut checker = crate::checker::LinearChecker::new(); - if let Err(e) = checker.check_program(&program) { - errors - .lock() - .unwrap() - .push(format!("{}: {}", trk_file.display(), e)); - } - } - }); - - handles.push(handle); - } - - for handle in handles { - let _ = handle.join(); - } - - let mut errs = Arc::try_unwrap(errors).unwrap().into_inner().unwrap(); - errs.sort(); - - if errs.is_empty() { - println!( - "✓ Check passed ({} file{})", - trk_files.len(), - if trk_files.len() == 1 { "" } else { "s" } - ); - Ok(()) - } else { - for e in &errs { - eprintln!(" ✗ {}", e); - } - Err(format!("{} error(s) found", errs.len())) - } - } - - pub fn test(project_root: &Path, manifest: &Manifest) -> Result<(), String> { - println!( - " Testing {} v{}", - manifest.package.name, manifest.package.version - ); - - // First ensure the package type-checks - Self::check(project_root, manifest)?; - - // Discover Track test files: src/*_test.trk and tests/**/*.trk - let mut test_files: Vec = Vec::new(); - let src_dir = project_root.join(&manifest.build.src); - if src_dir.exists() { - for entry in fs::read_dir(&src_dir) - .map_err(|e| format!("Failed to read src dir '{}': {}", src_dir.display(), e))? - { - let entry = entry.map_err(|e| format!("Directory entry error: {}", e))?; - let p = entry.path(); - if p.is_file() - && p.extension().is_some_and(|ext| ext == "trk") - && p.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.contains("_test")) - { - test_files.push(p); - } else if p.is_dir() { - // allow src/tests/*.trk as well - let _ = collect_trk_files(&p, &mut test_files); - } - } - } - let tests_dir = project_root.join("tests"); - if tests_dir.exists() { - collect_trk_files(&tests_dir, &mut test_files)?; - } - // Also check compiler-style `src/test_*.trk` - // (already covered by _test filter above, but keep explicit) - test_files.sort(); - test_files.dedup(); - - if test_files.is_empty() { - println!(" no Track tests found (src/*_test.trk, tests/**/*.trk)"); - println!("✓ All Track tests passed (0 tests)"); - return Ok(()); - } - - let target_dir = project_root.join("target"); - fs::create_dir_all(&target_dir) - .map_err(|e| format!("Failed to create target directory: {}", e))?; - - let mut failures = 0usize; - for test_file in &test_files { - let rel = test_file - .strip_prefix(project_root) - .unwrap_or(test_file) - .display() - .to_string(); - print!(" Running {} ... ", rel); - // Build the test as a temporary package that links it with the - // rest of src/ (token, lexer) but not the package's own main. - // This lets `import "lexer"` resolve while keeping the test's - // `fn main` as the entry point. - let stem = test_file - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("test"); - let tmp_root = std::env::temp_dir().join(format!( - "track_test_{}_{}_{}", - manifest.package.name, - stem, - std::process::id() - )); - let _ = fs::remove_dir_all(&tmp_root); - if let Err(e) = (|| -> Result<(), String> { - fs::create_dir_all(tmp_root.join("src")) - .map_err(|e| format!("Failed to create temp src dir: {}", e))?; - // Minimal manifest for the temp test package - let tmp_manifest_content = format!( - "[package]\nname = \"{}_test\"\nversion = \"0.1.0\"\nauthors = []\n\n[dependencies]\n\n[build]\nsrc = \"src\"\n", - manifest.package.name - ); - fs::write(tmp_root.join("Track.toml"), tmp_manifest_content) - .map_err(|e| format!("Failed to write temp Track.toml: {}", e))?; - // Copy non-test, non-main src files (token, lexer) into tmp src - let src_dir = project_root.join(&manifest.build.src); - if src_dir.exists() { - for entry in fs::read_dir(&src_dir) - .map_err(|e| format!("Failed to read src dir: {}", e))? - { - let entry = entry.map_err(|e| format!("Dir entry error: {}", e))?; - let p = entry.path(); - if !p.is_file() { - continue; - } - let fname = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); - if fname == "main.trk" || fname.contains("_test") { - continue; - } - if p.extension().is_some_and(|ext| ext == "trk") { - let dest = tmp_root.join("src").join(fname); - fs::copy(&p, &dest) - .map_err(|e| format!("Failed to copy {}: {}", p.display(), e))?; - } - } - } - // Preserve non-source fixtures beside the temporary package so - // native tests can load golden inputs and outputs by a stable, - // project-relative path. `.trk` files remain test entry points - // and are deliberately not staged as fixtures. - let fixture_dir = project_root.join("tests").join("fixtures"); - if fixture_dir.exists() { - copy_test_fixtures(&fixture_dir, &tmp_root.join("tests/fixtures"))?; - } - // Also copy any src subdirs that are not tests (conservative: skip) - // Write the test file itself as src/main.trk (entry point) - let test_src = fs::read_to_string(test_file).map_err(|e| { - format!("Failed to read test file '{}': {}", test_file.display(), e) - })?; - fs::write(tmp_root.join("src/main.trk"), test_src) - .map_err(|e| format!("Failed to write tmp main.trk: {}", e))?; - Ok(()) - })() { - eprintln!("✗ setup failed: {}", e); - failures += 1; - continue; - } - - let tmp_manifest = match Manifest::load(&tmp_root.join("Track.toml")) { - Ok(m) => m, - Err(e) => { - eprintln!("✗ manifest load failed: {}", e); - failures += 1; - continue; - } - }; - if let Err(e) = Self::build(&tmp_root, &tmp_manifest) { - eprintln!("✗ build failed: {}", e); - let _ = fs::remove_dir_all(&tmp_root); - failures += 1; - continue; - } - let exe_path = tmp_root - .join("target") - .join(format!("{}_test", manifest.package.name)); - let status = process::Command::new(&exe_path) - .current_dir(&tmp_root) - .status() - .map_err(|e| format!("Failed to run '{}': {}", exe_path.display(), e)); - let _ = fs::remove_dir_all(&tmp_root); - match status { - Ok(s) if s.success() => println!("✓"), - Ok(s) => { - eprintln!("✗ failed (exit {:?})", s.code()); - failures += 1; - } - Err(e) => { - eprintln!("✗ run failed: {}", e); - failures += 1; - } - } - } - - if failures > 0 { - return Err(format!("{} Track test(s) failed", failures)); - } - println!("✓ All {} Track test(s) passed", test_files.len()); - Ok(()) - } -} - -/// Hash of the compiler executable identity and every package source. -fn build_fingerprint(files: &[PathBuf]) -> Result { - let mut key = String::from(env!("CARGO_PKG_VERSION")); - if let Ok(exe) = std::env::current_exe() - && let Ok(meta) = fs::metadata(exe) - { - let modified = meta - .modified() - .ok() - .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) - .map_or(0, |d| d.as_nanos()); - key.push_str(&format!("\0{}\0{}", meta.len(), modified)); - } - for file in files { - let source = fs::read_to_string(file) - .map_err(|e| format!("Failed to read '{}': {}", file.display(), e))?; - key.push('\0'); - key.push_str(&file.to_string_lossy()); - key.push('\0'); - key.push_str(&BuildCache::compute_hash(&source)); - } - Ok(BuildCache::compute_hash(&key)) -} - -fn copy_test_fixtures(source: &Path, destination: &Path) -> Result<(), String> { - fs::create_dir_all(destination).map_err(|e| { - format!( - "Failed to create fixture directory '{}': {}", - destination.display(), - e - ) - })?; - for entry in fs::read_dir(source).map_err(|e| { - format!( - "Failed to read fixture directory '{}': {}", - source.display(), - e - ) - })? { - let entry = entry.map_err(|e| format!("Fixture directory entry error: {}", e))?; - let path = entry.path(); - let destination_path = destination.join(entry.file_name()); - if path.is_dir() { - copy_test_fixtures(&path, &destination_path)?; - } else if path.extension().is_none_or(|extension| extension != "trk") { - fs::copy(&path, &destination_path).map_err(|e| { - format!( - "Failed to copy fixture '{}' to '{}': {}", - path.display(), - destination_path.display(), - e - ) - })?; - } - } - Ok(()) -} - -fn find_trk_files(dir: &Path) -> Result, String> { - let mut files = Vec::new(); - collect_trk_files(dir, &mut files)?; - files.sort(); - Ok(files) -} - -fn collect_trk_files(dir: &Path, out: &mut Vec) -> Result<(), String> { - let entries = fs::read_dir(dir) - .map_err(|e| format!("Failed to read directory '{}': {}", dir.display(), e))?; - - for entry in entries { - let entry = entry.map_err(|e| format!("Directory entry error: {}", e))?; - let path = entry.path(); - - if path.is_dir() { - collect_trk_files(&path, out)?; - } else if path.extension().is_some_and(|ext| ext == "trk") { - out.push(path); - } - } - - Ok(()) -} diff --git a/src/yard/cache.rs b/src/yard/cache.rs deleted file mode 100644 index 9c50f794..00000000 --- a/src/yard/cache.rs +++ /dev/null @@ -1,56 +0,0 @@ -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; - -#[derive(Debug, serde::Serialize, serde::Deserialize, Default)] -pub struct BuildCache { - pub entries: BTreeMap, // sorted relative path -> content hash -} - -impl BuildCache { - pub fn cache_file_path(target_dir: &Path) -> PathBuf { - target_dir.join(".cache_meta.json") - } - - pub fn load(target_dir: &Path) -> Self { - let cache_path = Self::cache_file_path(target_dir); - if let Ok(data) = fs::read_to_string(&cache_path) - && let Ok(cache) = serde_json::from_str(&data) - { - return cache; - } - Self::default() - } - - pub fn save(&self, target_dir: &Path) -> Result<(), String> { - let cache_path = Self::cache_file_path(target_dir); - let data = serde_json::to_string_pretty(self) - .map_err(|e| format!("Failed to serialize build cache: {}", e))?; - fs::write(&cache_path, data).map_err(|e| format!("Failed to write build cache: {}", e))?; - Ok(()) - } - - pub fn compute_hash(content: &str) -> String { - let mut hash: u64 = 0xcbf29ce484222325; - for byte in content.bytes() { - hash ^= u64::from(byte); - hash = hash.wrapping_mul(0x100000001b3); - } - format!("{:016x}", hash) - } - - pub fn is_cached(&self, rel_path: &str, content_hash: &str, obj_path: &Path) -> bool { - if !obj_path.exists() { - return false; - } - if let Some(cached_hash) = self.entries.get(rel_path) { - cached_hash == content_hash - } else { - false - } - } - - pub fn update(&mut self, rel_path: String, content_hash: String) { - self.entries.insert(rel_path, content_hash); - } -} diff --git a/src/yard/commands.rs b/src/yard/commands.rs deleted file mode 100644 index c3162d23..00000000 --- a/src/yard/commands.rs +++ /dev/null @@ -1,223 +0,0 @@ -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process; - -use super::builder::ParallelBuilder; -use super::manifest::{Dependency, Manifest}; - -// ── yard init ──────────────────────────────────────────────────────── - -pub fn init(args: &[String]) -> Result<(), String> { - let name = args - .first() - .ok_or_else(|| "Usage: track yard init ".to_string())?; - - let project_dir = Path::new(name); - if project_dir.exists() { - return Err(format!("Directory '{}' already exists", name)); - } - - // Create project structure - fs::create_dir_all(project_dir.join("src")) - .map_err(|e| format!("Failed to create directory: {}", e))?; - - // Track.toml - let pkg_name = project_dir - .file_name() - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_else(|| name.to_string()); - let manifest = Manifest::new(&pkg_name); - manifest.save(&project_dir.join("Track.toml"))?; - - // src/main.trk - fs::write( - project_dir.join("src/main.trk"), - "fn main() -> void {\n print(42);\n}\n", - ) - .map_err(|e| format!("Failed to write main.trk: {}", e))?; - - // .gitignore - fs::write(project_dir.join(".gitignore"), "/target\n/yard.lock\n") - .map_err(|e| format!("Failed to write .gitignore: {}", e))?; - - println!("✓ Created project '{}'", name); - println!(" {}/Track.toml", name); - println!(" {}/src/main.trk", name); - println!("\nGet started:"); - println!(" cd {}", name); - println!(" yard build"); - println!(" yard run"); - - Ok(()) -} - -// ── yard build ─────────────────────────────────────────────────────── - -pub fn build(_args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - build_at(&project_root, _args) -} - -pub fn build_at(project_root: &Path, _args: &[String]) -> Result<(), String> { - let manifest = Manifest::load(&project_root.join("Track.toml"))?; - ParallelBuilder::build(project_root, &manifest) -} - -// ── yard run ───────────────────────────────────────────────────────── - -pub fn run_cmd(args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - run_cmd_at(&project_root, args) -} - -pub fn run_cmd_at(project_root: &Path, args: &[String]) -> Result<(), String> { - build_at(project_root, args)?; - - let manifest = Manifest::load(&project_root.join("Track.toml"))?; - let exe_path = project_root.join("target").join(&manifest.package.name); - - let status = process::Command::new(&exe_path) - .status() - .map_err(|e| format!("Failed to run '{}': {}", exe_path.display(), e))?; - - if !status.success() { - return Err(format!("Process exited with code: {:?}", status.code())); - } - - Ok(()) -} - -// ── yard add ───────────────────────────────────────────────────────── - -pub fn add(args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - add_at(&project_root, args) -} - -pub fn add_at(project_root: &Path, args: &[String]) -> Result<(), String> { - if args.is_empty() { - return Err( - "Usage: yard add [--version ] [--path ] [--git ]".to_string(), - ); - } - - let pkg_name = &args[0]; - let manifest_path = project_root.join("Track.toml"); - let mut manifest = Manifest::load(&manifest_path)?; - - // Parse optional flags - let mut version = None; - let mut path = None; - let mut git = None; - let mut i = 1; - while i < args.len() { - match args[i].as_str() { - "--version" | "-v" => { - i += 1; - version = args.get(i).cloned(); - } - "--path" | "-p" => { - i += 1; - path = args.get(i).cloned(); - } - "--git" | "-g" => { - i += 1; - git = args.get(i).cloned(); - } - _ => {} - } - i += 1; - } - - let dep = if path.is_some() || git.is_some() { - Dependency::Detailed { - version, - git, - path, - branch: None, - } - } else { - Dependency::Simple(version.unwrap_or_else(|| "0.1.0".to_string())) - }; - - manifest.dependencies.insert(pkg_name.clone(), dep); - manifest.save(&manifest_path)?; - - println!("✓ Added dependency '{}'", pkg_name); - Ok(()) -} - -// ── yard check ─────────────────────────────────────────────────────── - -pub fn check(_args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - check_at(&project_root, _args) -} - -pub fn check_at(project_root: &Path, _args: &[String]) -> Result<(), String> { - let manifest = Manifest::load(&project_root.join("Track.toml"))?; - ParallelBuilder::check(project_root, &manifest) -} - -// ── yard lint ──────────────────────────────────────────────────────── - -/// Lint the project (type/ownership check without building). -pub fn lint(args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - lint_at(&project_root, args) -} - -pub fn lint_at(project_root: &Path, args: &[String]) -> Result<(), String> { - check_at(project_root, args)?; - println!("✓ No issues found"); - Ok(()) -} - -// ── yard clean ─────────────────────────────────────────────────────── - -pub fn clean(_args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - clean_at(&project_root) -} - -pub fn clean_at(project_root: &Path) -> Result<(), String> { - let target_dir = project_root.join("target"); - if target_dir.exists() { - fs::remove_dir_all(&target_dir) - .map_err(|e| format!("Failed to clean target directory: {}", e))?; - } - println!("✓ Cleaned build target directory"); - Ok(()) -} - -// ── yard test ──────────────────────────────────────────────────────── - -pub fn test(_args: &[String]) -> Result<(), String> { - let project_root = find_project_root()?; - test_at(&project_root, _args) -} - -pub fn test_at(project_root: &Path, _args: &[String]) -> Result<(), String> { - let manifest = Manifest::load(&project_root.join("Track.toml"))?; - super::builder::ParallelBuilder::test(project_root, &manifest) -} - -// ── helpers ────────────────────────────────────────────────────────── - -fn find_project_root() -> Result { - let mut dir = - env::current_dir().map_err(|e| format!("Failed to get current directory: {}", e))?; - - loop { - if dir.join("Track.toml").exists() { - return Ok(dir); - } - if !dir.pop() { - return Err( - "No Track.toml found in current directory or any parent. Run 'yard init ' to create a project." - .to_string(), - ); - } - } -} diff --git a/src/yard/linker.rs b/src/yard/linker.rs deleted file mode 100644 index c28ffefc..00000000 --- a/src/yard/linker.rs +++ /dev/null @@ -1,94 +0,0 @@ -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::Command; - -pub struct LinkerEngine; - -impl LinkerEngine { - /// Detect if fast linkers like `mold` or `lld` are available. - pub fn detect_fast_linker_flag() -> Option<&'static str> { - if Command::new("mold").arg("--version").output().is_ok() { - Some("-fuse-ld=mold") - } else if Command::new("ld.lld").arg("--version").output().is_ok() { - Some("-fuse-ld=lld") - } else { - None - } - } - - /// Compile and cache the C runtime helper object file into target directory. - pub fn get_or_compile_runtime(target_dir: &Path) -> Result { - let runtime_obj_path = target_dir.join("_track_runtime.o"); - let runtime_hash_path = target_dir.join("_track_runtime.hash"); - let runtime_hash = crate::yard::cache::BuildCache::compute_hash(crate::RUNTIME_C_SOURCE); - if runtime_obj_path.exists() - && fs::read_to_string(&runtime_hash_path) - .is_ok_and(|cached_hash| cached_hash.trim() == runtime_hash) - { - return Ok(runtime_obj_path); - } - - let runtime_c_path = target_dir.join("_track_runtime.c"); - let runtime_obj_temp_path = target_dir.join("_track_runtime.o.tmp"); - fs::write(&runtime_c_path, crate::RUNTIME_C_SOURCE) - .map_err(|e| format!("Failed to write runtime helper source: {}", e))?; - - let status = Command::new("cc") - .arg("-c") - .arg(&runtime_c_path) - .arg("-o") - .arg(&runtime_obj_temp_path) - .arg("-O3") - .status() - .map_err(|e| format!("Failed to compile runtime helper: {}", e))?; - - let _ = fs::remove_file(&runtime_c_path); - - if !status.success() { - let _ = fs::remove_file(&runtime_obj_temp_path); - return Err(format!( - "Runtime helper compilation failed with code: {:?}", - status.code() - )); - } - - fs::rename(&runtime_obj_temp_path, &runtime_obj_path) - .map_err(|e| format!("Failed to install runtime helper object: {}", e))?; - fs::write(&runtime_hash_path, runtime_hash) - .map_err(|e| format!("Failed to write runtime helper cache key: {}", e))?; - - Ok(runtime_obj_path) - } - - /// Link all compiled object files + runtime object into the final native executable. - pub fn link_binary( - obj_files: &[PathBuf], - exe_path: &Path, - target_dir: &Path, - ) -> Result<(), String> { - let runtime_obj = Self::get_or_compile_runtime(target_dir)?; - - let mut cmd = Command::new("cc"); - - // Use fast linker flag if available - if let Some(flag) = Self::detect_fast_linker_flag() { - cmd.arg(flag); - } - - for obj in obj_files { - cmd.arg(obj); - } - cmd.arg(&runtime_obj); - cmd.arg("-o").arg(exe_path).arg("-lm"); // PIE: see create_default_isa - - let status = cmd - .status() - .map_err(|e| format!("Linker invocation failed: {}", e))?; - - if !status.success() { - return Err(format!("Linker failed with exit code: {:?}", status.code())); - } - - Ok(()) - } -} diff --git a/src/yard/manifest.rs b/src/yard/manifest.rs deleted file mode 100644 index e27286ea..00000000 --- a/src/yard/manifest.rs +++ /dev/null @@ -1,87 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs; -use std::path::Path; - -#[derive(Debug, Deserialize, Serialize)] -pub struct Manifest { - pub package: Package, - #[serde(default)] - pub dependencies: HashMap, - #[serde(default)] - pub build: BuildConfig, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct Package { - pub name: String, - pub version: String, - #[serde(default)] - pub description: Option, - #[serde(default)] - pub authors: Vec, -} - -#[derive(Debug, Deserialize, Serialize, Clone)] -#[serde(untagged)] -pub enum Dependency { - Simple(String), - Detailed { - #[serde(default)] - version: Option, - #[serde(default)] - git: Option, - #[serde(default)] - path: Option, - #[serde(default)] - branch: Option, - }, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct BuildConfig { - #[serde(default = "default_src")] - pub src: String, - #[serde(default)] - pub target: Option, -} - -impl Default for BuildConfig { - fn default() -> Self { - Self { - src: default_src(), - target: None, - } - } -} - -fn default_src() -> String { - "src".to_string() -} - -impl Manifest { - pub fn load(path: &Path) -> Result { - let content = fs::read_to_string(path) - .map_err(|e| format!("Failed to read '{}': {}", path.display(), e))?; - toml::from_str(&content).map_err(|e| format!("Failed to parse '{}': {}", path.display(), e)) - } - - pub fn save(&self, path: &Path) -> Result<(), String> { - let content = toml::to_string_pretty(self) - .map_err(|e| format!("Failed to serialize manifest: {}", e))?; - fs::write(path, content).map_err(|e| format!("Failed to write '{}': {}", path.display(), e)) - } - - pub fn new(name: &str) -> Self { - Self { - package: Package { - name: name.to_string(), - version: "0.1.0".to_string(), - description: None, - authors: Vec::new(), - }, - dependencies: HashMap::new(), - build: BuildConfig::default(), - } - } -} diff --git a/src/yard/mod.rs b/src/yard/mod.rs deleted file mode 100644 index 168a703d..00000000 --- a/src/yard/mod.rs +++ /dev/null @@ -1,50 +0,0 @@ -pub mod builder; -pub mod cache; -pub mod commands; -pub mod linker; -pub mod manifest; -pub mod resolver; - -pub fn run(args: &[String]) -> Result<(), String> { - if args.is_empty() { - print_usage(); - return Ok(()); - } - match args[0].as_str() { - "init" => commands::init(&args[1..]), - "build" => commands::build(&args[1..]), - "run" => commands::run_cmd(&args[1..]), - "add" => commands::add(&args[1..]), - "check" => commands::check(&args[1..]), - "lint" => commands::lint(&args[1..]), - "clean" => commands::clean(&args[1..]), - "test" => commands::test(&args[1..]), - "--version" | "-v" | "version" => { - println!("yard {}", env!("CARGO_PKG_VERSION")); - Ok(()) - } - "--help" | "-h" | "help" => { - print_usage(); - Ok(()) - } - other => Err(format!("Unknown yard command: '{}'", other)), - } -} - -fn print_usage() { - eprintln!("Yard - Track Package Manager"); - eprintln!(); - eprintln!("USAGE:"); - eprintln!(" yard [options]"); - eprintln!(); - eprintln!("COMMANDS:"); - eprintln!(" init Create a new Track project"); - eprintln!(" build Build the current project"); - eprintln!(" run Build and run the current project"); - eprintln!(" add Add a dependency"); - eprintln!(" check Check the project for errors"); - eprintln!(" lint Lint the project without building"); - eprintln!(" clean Clean target build directory"); - eprintln!(" test Run native Track tests (src/*_test.trk, tests/**/*.trk)"); - eprintln!(" help Show this help"); -} diff --git a/src/yard/resolver.rs b/src/yard/resolver.rs deleted file mode 100644 index f6c42bb9..00000000 --- a/src/yard/resolver.rs +++ /dev/null @@ -1,99 +0,0 @@ -use super::manifest::{Dependency, Manifest}; -use std::path::{Path, PathBuf}; - -#[derive(Debug)] -pub struct ResolvedDep { - pub name: String, - pub version: String, - pub source: DepSource, - pub src_dir: PathBuf, -} - -#[derive(Debug)] -pub enum DepSource { - Local(PathBuf), - Git { url: String, branch: Option }, - Registry(String), -} - -pub fn resolve(manifest: &Manifest, project_root: &Path) -> Result, String> { - let mut resolved = Vec::new(); - - let mut dependencies: Vec<_> = manifest.dependencies.iter().collect(); - dependencies.sort_by_key(|(name, _)| *name); - for (name, dep) in dependencies { - match dep { - Dependency::Simple(version) => { - // Registry dependency — not yet implemented - eprintln!( - " ⚠ Registry dependency '{}@{}' — registry not yet available, skipping", - name, version - ); - resolved.push(ResolvedDep { - name: name.clone(), - version: version.clone(), - source: DepSource::Registry(version.clone()), - src_dir: PathBuf::new(), - }); - } - Dependency::Detailed { - version, - git, - path, - branch, - } => { - if let Some(local_path) = path { - // Local path dependency - let dep_path = project_root.join(local_path); - if !dep_path.exists() { - return Err(format!( - "Path dependency '{}' not found: {}", - name, - dep_path.display() - )); - } - let src_dir = dep_path.join("src"); - resolved.push(ResolvedDep { - name: name.clone(), - version: version.clone().unwrap_or_else(|| "0.0.0".to_string()), - source: DepSource::Local(dep_path), - src_dir, - }); - } else if let Some(url) = git { - // Git dependency — not yet implemented - eprintln!( - " ⚠ Git dependency '{}' ({}) — git fetch not yet available, skipping", - name, url - ); - resolved.push(ResolvedDep { - name: name.clone(), - version: version.clone().unwrap_or_else(|| "0.0.0".to_string()), - source: DepSource::Git { - url: url.clone(), - branch: branch.clone(), - }, - src_dir: PathBuf::new(), - }); - } else if let Some(ver) = version { - eprintln!( - " ⚠ Registry dependency '{}@{}' — registry not yet available, skipping", - name, ver - ); - resolved.push(ResolvedDep { - name: name.clone(), - version: ver.clone(), - source: DepSource::Registry(ver.clone()), - src_dir: PathBuf::new(), - }); - } else { - return Err(format!( - "Dependency '{}' must specify version, path, or git", - name - )); - } - } - } - } - - Ok(resolved) -} diff --git a/src/yard_bin.rs b/src/yard_bin.rs deleted file mode 100644 index 6b645e24..00000000 --- a/src/yard_bin.rs +++ /dev/null @@ -1,13 +0,0 @@ -use std::env; -use std::process; - -fn main() { - let args: Vec = env::args().skip(1).collect(); - match track::yard::run(&args) { - Ok(()) => {} - Err(e) => { - eprintln!("yard error: {}", e); - process::exit(1); - } - } -} diff --git a/tests/PORTING.md b/tests/PORTING.md new file mode 100644 index 00000000..10a9dd0c --- /dev/null +++ b/tests/PORTING.md @@ -0,0 +1,203 @@ +# Porting the cargo test suites to tests/run.sh + +Card S2. Every `#[test]` (and `#[tokio::test]`) in `tests/*.rs`, its class, +and where it lives now. Card S5 deleted the `.rs` suites, the Rust stage0, +yard and LSP, and `Cargo.toml`; the table is the record of where each test +went. + +Classes: + +- **A**: tests trackc, the runtimes, the native backend, the bootstrap or + the programs. Ported. +- **B**: also tested the Rust stage0 (its parser, checker, codegen, or + "both compilers agree" parity). The trackc half is ported, the stage0 + half dropped. Where parity with stage0 was the point, goldens recorded + from stage0 stand in for it (`tests/cases/examples/*.out`). +- **C**: tests yard or the LSP. Covered by `tests/yard/run.sh` (PR #36) + and `tests/lsp/run.sh` (PR #37); the case is named. +- **D**: editor assets. Ported when the assets survive the Rust deletion. + +Totals: 165 tests (162 `#[test]`, 3 `#[tokio::test]` in lsp_tests.rs). +A 80 ported; B 63 (60 trackc halves ported, 3 dropped); C 12 mapped +(9 yard, 3 LSP); D 10 ported. No class-A test is dropped. + +Known differences from the Rust checks: + +- A signal death is checked as exit status 128+N (SIGFPE = 136); a program + calling `exit(136)` would also pass. +- `editor_tests` / `headless_highlight_tests` read JSON with `jq` and run + grammar regexes with `grep -P`; the nvim checks skip without nvim, as + before. + +Run: `tests/run.sh [-j N]` (see its header). Locations are +`tests/sh/.sh::` (bare `lang.sh::x` means +`tests/sh/lang.sh::t_x`); data lives in `tests/cases/` and the existing +`tests//` goldens. + +| Rust test | Class | New location | Note / reason dropped | +|---|---|---|---| +| checker_tests.rs::test_for_over_scalar_is_rejected | B | checker_verdicts rows checker_for_over_scalar_is_rejected + checker_for_over_range_and_array_ok | | +| checker_tests.rs::test_linear_checker_borrow_and_escape | B | checker_verdicts row checker_borrow_and_escape | | +| checker_tests.rs::test_linear_checker_enum_and_union_matching | B | checker_verdicts row checker_enum_and_union_matching | | +| checker_tests.rs::test_linear_checker_escape_error | B | checker_verdicts row checker_escape_error | | +| checker_tests.rs::test_linear_checker_extended_char_str_path_api | B | checker_verdicts row checker_extended_char_str_path_api | | +| checker_tests.rs::test_linear_checker_lens_block_locked_error | B | checker_verdicts row checker_lens_block_locked_error | "frozen" | +| checker_tests.rs::test_linear_checker_lens_block_valid_and_locked | B | checker_verdicts row checker_lens_block_valid_and_locked | | +| checker_tests.rs::test_linear_checker_linear_type_transfer | B | checker_verdicts row checker_linear_type_transfer | | +| checker_tests.rs::test_linear_checker_type_alias_and_os_api | B | checker_verdicts row checker_type_alias_and_os_api | | +| checker_tests.rs::test_linear_checker_typo_suggestion | B | checker_verdicts row checker_typo_suggestion | "Did you mean 'print'?" | +| checker_tests.rs::test_linear_checker_use_after_free_error | B | checker_verdicts row checker_use_after_free_error | | +| checker_tests.rs::test_linear_checker_valid_code | B | checker_verdicts row checker_valid_code | trackc half of a stage0 checker test | +| cli_tests.rs::test_cli_build_and_run_generics | A | cli.sh::cli_build_and_run_generics | stricter: runs the exe, stdout 7 | +| cli_tests.rs::test_cli_check_command | A | cli.sh::cli_check_command | "Check passed" | +| cli_tests.rs::test_cli_check_const_across_functions | A | lang.sh::checker_verdicts row cli_check_const_across_functions | | +| cli_tests.rs::test_cli_check_generics_arity_mismatch | A | lang.sh::checker_verdicts row cli_check_generics_arity_mismatch | stricter: pins E0200 arity text | +| cli_tests.rs::test_cli_check_generics_valid | A | lang.sh::checker_verdicts row cli_check_generics_valid | | +| cli_tests.rs::test_cli_check_invalid_syntax_fails | A | lang.sh::checker_verdicts row cli_check_invalid_syntax_fails | stricter: pins E0100 | +| cli_tests.rs::test_cli_duplicate_function_is_a_diagnostic | A | cli.sh::cli_duplicate_function_is_a_diagnostic | check+build exit 1, E0201 text | +| cli_tests.rs::test_cli_duplicate_function_through_import_is_a_diagnostic | A | cli.sh::cli_duplicate_function_through_import_is_a_diagnostic | | +| cli_tests.rs::test_cli_help | A | tests/sh/cli.sh::cli_help | Rust `track` CLI -> trackc, same commands/messages | +| cli_tests.rs::test_cli_invalid_command | A | cli.sh::cli_invalid_command | "Unknown command" | +| cli_tests.rs::test_cli_version_reports_0_6 | A | cli.sh::cli_version_reports_1_0_0 | asserts 1.0.0 as the Rust test did | +| codegen_semantics_tests.rs::array_index_out_of_bounds_aborts | A | lang.sh::array_index_out_of_bounds_aborts | exit 134 + stderr | +| codegen_semantics_tests.rs::block_bindings_do_not_leak_into_the_enclosing_scope | A | lang.sh::block_bindings_do_not_leak_into_the_enclosing_scope | | +| codegen_semantics_tests.rs::constants_fold_comparisons_and_variants | A | lang.sh::constants_fold_comparisons_and_variants | | +| codegen_semantics_tests.rs::division_by_zero_flushes_and_raises_sigfpe | A | lang.sh::division_by_zero_flushes_and_raises_sigfpe | status 136 (SIGFPE) | +| codegen_semantics_tests.rs::executables_are_position_independent | A | lang.sh::executables_are_position_independent | ET_DYN via od | +| codegen_semantics_tests.rs::for_in_binds_array_elements | A | lang.sh::for_in_binds_array_elements | | +| codegen_semantics_tests.rs::if_and_match_produce_values | A | lang.sh::if_and_match_produce_values | | +| codegen_semantics_tests.rs::int64_min_div_minus_one_flushes_and_raises_sigfpe | A | lang.sh::int64_min_div_minus_one_flushes_and_raises_sigfpe | | +| codegen_semantics_tests.rs::logical_operators_short_circuit_and_normalise | A | lang.sh::logical_operators_short_circuit_and_normalise | sources in cases/lang/.trk | +| codegen_semantics_tests.rs::negative_runtime_results_keep_their_sign | A | lang.sh::negative_runtime_results_keep_their_sign | | +| codegen_semantics_tests.rs::program_arguments_reach_os_args | A | lang.sh::program_arguments_reach_os_args | | +| codegen_semantics_tests.rs::return_inside_match_while_and_nested_if | A | lang.sh::return_inside_match_while_and_nested_if | | +| codegen_semantics_tests.rs::returned_tuple_variables_do_not_dangle | A | lang.sh::returned_tuple_variables_do_not_dangle | | +| codegen_semantics_tests.rs::string_patterns_compare_contents | A | lang.sh::string_patterns_compare_contents | | +| codegen_semantics_tests.rs::structs_and_arrays_have_runtime_values | A | lang.sh::structs_and_arrays_have_runtime_values | | +| codegen_semantics_tests.rs::union_payloads_and_enum_discriminants | A | lang.sh::union_payloads_and_enum_discriminants | | +| codegen_tests.rs::test_codegen_object_file_emission | B | — | dropped: stage0 CodeGen::write_object_file only; `print(42)` build covered by cli/lang build tests | +| codegen_tests.rs::test_codegen_simple_function | B | — | dropped: drives stage0 Cranelift CodeGen API on a hand-built Rust AST; no trackc equivalent (trackc builds are covered by every build test) | +| codegen_tests.rs::test_codegen_string_literals_and_print | B | — | dropped: stage0 object emission only; string print covered by examples/hello in lang.sh::valid_examples_compile_and_run | +| editor_tests.rs::test_nvim_plugin_files | D | tests/sh/tools.sh::t_nvim_plugin_files | luac -p step skips when luac is absent, as in Rust | +| editor_tests.rs::test_vscode_language_configuration | D | tests/sh/tools.sh::t_vscode_language_configuration | repo asset | +| editor_tests.rs::test_vscode_package_json | D | tests/sh/tools.sh::t_vscode_package_json | editor/vscode/package.json survives; JSON via jq | +| editor_tests.rs::test_vscode_textmate_grammar | D | tests/sh/tools.sh::t_vscode_textmate_grammar | repo asset | +| headless_highlight_tests.rs::test_nvim_devicon_svg_not_needed_headless | D | tests/sh/tools.sh::t_nvim_devicon_svg_not_needed_headless | repo asset | +| headless_highlight_tests.rs::test_nvim_headless_filetype_and_syntax | D | tests/sh/tools.sh::t_nvim_headless_filetype_and_syntax | skips without nvim (as in Rust) | +| headless_highlight_tests.rs::test_nvim_headless_lua_syntax_ok | D | tests/sh/tools.sh::t_nvim_headless_lua_syntax_ok | skips without nvim | +| headless_highlight_tests.rs::test_nvim_syntax_highlight_sample_headless | D | tests/sh/tools.sh::t_nvim_syntax_highlight_sample_headless | skips without nvim | +| headless_highlight_tests.rs::test_vscode_grammar_headless_tokenization | D | tests/sh/tools.sh::t_vscode_grammar_headless_tokenization | regexes run under grep -P (PCRE) instead of the regex crate; patterns invalid in PCRE are skipped as before (PCRE accepts lookaheads the regex crate skipped) | +| headless_highlight_tests.rs::test_vscode_grammar_valid_json_headless | D | tests/sh/tools.sh::t_vscode_grammar_valid_json_headless | both grammar copies; exactly-one-JSON-value check | +| integration_tests.rs::test_const_resolution_across_functions | A | lang.sh::const_resolution_across_functions | stdout pinned exactly | +| integration_tests.rs::test_error_predicates_disambiguate_sentinels | A | lang.sh::error_predicates_disambiguate_sentinels | stricter: whole stdout pinned | +| integration_tests.rs::test_explicit_error_handling_convention | A | lang.sh::explicit_error_handling_convention | cases/lang/error_handling.trk | +| integration_tests.rs::test_for_in_loop_execution | A | lang.sh::for_in_loop_execution | stricter: stdout 0..2 pinned | +| integration_tests.rs::test_generics_monomorphization | A | lang.sh::generics_monomorphization | | +| integration_tests.rs::test_invalid_examples_rejection | A | lang.sh::invalid_examples_rejection | trackc check exit 1 + same substrings | +| integration_tests.rs::test_logical_not_operator | A | lang.sh::logical_not_operator | cases/lang/lnot.trk | +| integration_tests.rs::test_memory_boundary_exceeded_crash | A | lang.sh::memory_boundary_exceeded_crash | cases/lang/mem_test.trk | +| integration_tests.rs::test_valid_examples_compilation_and_execution | A | tests/sh/lang.sh::valid_examples_compile_and_run | trackc build + run, exit 0 | +| lexer_tests.rs::test_tokenize_comments_and_whitespace | B | lexer_token_dumps (lex_comments.tokens) | | +| lexer_tests.rs::test_tokenize_invalid_character | B | lang.sh::lexer_invalid_character | trackc: "error[E0001]: unexpected character" at 1:9 (no quoted char) | +| lexer_tests.rs::test_tokenize_keywords | B | lang.sh::lexer_token_dumps (cases/lang/lex_keywords.tokens) | Rust Token enum dropped; `trackc tokens` golden lists the same kinds | +| lexer_tests.rs::test_tokenize_literals_and_idents | B | lexer_token_dumps (lex_literals.tokens) | escapes decoded (\r shown as \015) | +| lexer_tests.rs::test_tokenize_operators_and_punctuation | B | lexer_token_dumps (lex_operators.tokens) | 33 tokens, same order | +| lexer_tests.rs::test_tokenize_types | B | lexer_token_dumps (lex_types.tokens) | | +| logic_and_soundness_strict_tests.rs::test_strict_bitwise_or_vs_logical_or_ast_precedence | B | lang.sh::bitwise_vs_logical_or_precedence | Rust AST half dropped; trackc half checks the grouping by running (prints 1 only for (a|b)||(c&d)) | +| logic_and_soundness_strict_tests.rs::test_strict_borrow_escape_from_lens_block | B | checker_verdicts row strict_borrow_escape_from_lens_block | | +| logic_and_soundness_strict_tests.rs::test_strict_double_move_in_loop_rejection | B | checker_verdicts row strict_double_move_in_loop_rejection | | +| logic_and_soundness_strict_tests.rs::test_strict_mutability_reassignment_rejection | B | checker_verdicts row strict_mutability_reassignment_rejection | same text "Cannot mutate immutable variable 'x'" | +| logic_and_soundness_strict_tests.rs::test_strict_mutable_variable_reassignment_allowed | B | checker_verdicts row strict_mutable_variable_reassignment_allowed | | +| logic_and_soundness_strict_tests.rs::test_strict_unresolved_type_alias_detection | B | checker_verdicts row strict_unresolved_type_alias_detection | Rust AST half dropped; trackc accepts the alias (parses) | +| lsp_tests.rs::test_lsp_completion (#[tokio::test]) | C | PR #37 tests/lsp/cases/basic.in (id 2: same text, position 1:6, label "let") | same source and position | +| lsp_tests.rs::test_lsp_hover (#[tokio::test]) | C | PR #37 tests/lsp/cases/basic.in (id 3: "Print a value to stdout") | same source and position | +| lsp_tests.rs::test_lsp_initialization (#[tokio::test]) | C | PR #37 tests/lsp/cases/basic.in (id 1: completionProvider + hoverProvider in capabilities) | not counted by `grep '#[test]'` | +| native_tests.rs::native_and_c_print_the_expected_output | A | tests/sh/native.sh::t_native_and_c_print_the_expected_output | a signal N is exit 128+N (SIGFPE = 136) | +| native_tests.rs::native_and_track_rt_reject_what_check_rejects | A | tests/sh/native.sh::t_native_and_track_rt_reject_what_check_rejects | | +| native_tests.rs::native_build_needs_no_c_toolchain | A | tests/sh/native.sh::t_native_build_needs_no_c_toolchain | | +| native_tests.rs::native_compiler_reaches_a_fixed_point | A | tests/sh/native.sh::t_native_compiler_reaches_a_fixed_point | stage1 is $TRACKC (seed bootstrap) instead of the yard-built trackc | +| native_tests.rs::native_executables_have_a_non_executable_stack | A | tests/sh/native.sh::t_native_executables_have_a_non_executable_stack | ELF header read with od | +| native_tests.rs::native_flag_is_honoured_in_any_position | A | tests/sh/native.sh::t_native_flag_is_honoured_in_any_position | | +| native_tests.rs::native_identical_string_literals_compare_equal | A | tests/sh/native.sh::t_native_identical_string_literals_compare_equal | | +| native_tests.rs::native_program_without_main_builds | A | tests/sh/native.sh::t_native_program_without_main_builds | | +| native_tests.rs::native_programs_match_the_c_backend | A | tests/sh/native.sh::t_native_programs_match_the_c_backend | | +| native_tests.rs::native_tuples_outlive_their_frame | A | tests/sh/native.sh::t_native_tuples_outlive_their_frame | | +| parser_tests.rs::test_parse_array_type_and_literal | B | parser_sources_parse row parse_array_type_and_literal | | +| parser_tests.rs::test_parse_enum_and_union | B | parser_sources_parse row parse_enum_and_union | | +| parser_tests.rs::test_parse_fn_def | B | lang.sh::parser_sources_parse row parse_fn_def | stage0 AST equality dropped (no trackc AST dump); trackc half: parses with no E0001/E01xx, verdict pinned | +| parser_tests.rs::test_parse_for_in_loop | B | parser_sources_parse row parse_for_in_loop | | +| parser_tests.rs::test_parse_generic_fn_multi_params | B | parser_sources_parse row parse_generic_fn_multi_params | | +| parser_tests.rs::test_parse_generic_fn_no_return | B | parser_sources_parse row parse_generic_fn_no_return | | +| parser_tests.rs::test_parse_generic_fn_single_param | B | parser_sources_parse row parse_generic_fn_single_param | | +| parser_tests.rs::test_parse_let_def | B | parser_sources_parse row parse_let_def | same | +| parser_tests.rs::test_parse_macro_def_and_call | B | parser_sources_parse row parse_macro_def_and_call | | +| parser_tests.rs::test_parse_match | B | parser_sources_parse row parse_match | parses; undeclared 'val' pinned | +| parser_tests.rs::test_parse_slice_type_and_indexing | B | parser_sources_parse row parse_slice_type_and_indexing | parses; E0200 undeclared 'arr' pinned | +| parser_tests.rs::test_parse_struct_and_lens | B | parser_sources_parse row parse_struct_and_lens | | +| parser_tests.rs::test_parse_type_alias | B | parser_sources_parse row parse_type_alias | | +| parser_tests.rs::test_parse_use_and_const | B | parser_sources_parse row parse_use_and_const | parses; E0011 unknown module pinned | +| parser_tests.rs::test_parse_use_statement | B | parser_sources_parse row parse_use_statement | parses; std/io export error pinned | +| performance_tests.rs::test_performance_full_pipeline_throughput | B | lang.sh::performance_full_pipeline_throughput | same 500-fn source through `trackc check` < 5 s | +| performance_tests.rs::test_performance_lexer_throughput | B | lang.sh::performance_lexer_throughput | stage0 lexer timing dropped; same input/5 s cap on `trackc tokens`, >=60000 tokens | +| performance_tests.rs::test_performance_parser_throughput | B | lang.sh::performance_parser_throughput | stage0 parser timing dropped; 1000 fns (distinct names, else E0201) through `trackc check` < 5 s | +| regression_tests.rs::test_regression_complex_match_guards | B | checker_verdicts row regression_complex_match_guards | | +| regression_tests.rs::test_regression_multiple_macro_calls | B | checker_verdicts row regression_multiple_macro_calls | | +| regression_tests.rs::test_regression_nested_expressions | B | lang.sh::checker_verdicts row regression_nested_expressions | trackc half: same accept verdict | +| regression_tests.rs::test_regression_nested_if_else_chain | B | checker_verdicts row regression_nested_if_else_chain | | +| regression_tests.rs::test_regression_nested_lens_blocks | B | checker_verdicts row regression_nested_lens_blocks | | +| regression_tests.rs::test_regression_shadowed_variables | B | checker_verdicts row regression_shadowed_variables | | +| regression_tests.rs::test_regression_top_level_variables_and_deref | B | checker_verdicts row regression_top_level_variables_and_deref | | +| selfhost_tests.rs::autofree_frees_heap_cells | A | tests/sh/lifecycle.sh::t_autofree_frees_heap_cells | `dealloc(l` in C, ASan detect_leaks=0 | +| selfhost_tests.rs::bootstrap_reaches_a_fixed_point | A | tests/sh/selfhost.sh::t_bootstrap_reaches_a_fixed_point | stage1 is $TRACKC (seed bootstrap) instead of yard-built | +| selfhost_tests.rs::build_creates_missing_output_directories | A | tests/sh/selfhost.sh::t_build_creates_missing_output_directories | | +| selfhost_tests.rs::checkers_agree_on_accepted_and_rejected_programs | B | tests/sh/selfhost.sh::t_checkers_agree_on_accepted_and_rejected_programs | Rust checker half dropped; 34 trackc verdicts in tests/cases/verdicts/{accept,reject} | +| selfhost_tests.rs::compiler_sources_are_warning_clean | A | tests/sh/selfhost.sh::t_compiler_sources_are_warning_clean | | +| selfhost_tests.rs::const_divrem_traps_are_e0200_in_both_checkers | B | tests/sh/selfhost.sh::t_const_divrem_traps_are_e0200_in_both_checkers | Rust checker half dropped; 19 cases in tests/cases/const_divrem (exit 1 + stderr prefix) | +| selfhost_tests.rs::diagnostics_point_at_the_source | A | tests/sh/selfhost.sh::t_diagnostics_point_at_the_source | | +| selfhost_tests.rs::duplicate_functions_are_rejected | A | tests/sh/lifecycle.sh::t_duplicate_functions_are_rejected | check+build, one file and import | +| selfhost_tests.rs::examples_behave_the_same_under_both_compilers | B | tests/sh/selfhost.sh::t_examples_behave_the_same_under_both_compilers | stage0 build dropped; stage0 behaviour frozen in tests/cases/examples/*.out/.code (captured from the Rust compiler), trackc compared to it; _err examples must be rejected | +| selfhost_tests.rs::examples_warn_only_where_intended | A | tests/sh/selfhost.sh::t_examples_warn_only_where_intended | | +| selfhost_tests.rs::for_in_exit_and_div_trap_on_both_runtimes | A | tests/sh/lifecycle.sh::t_for_in_exit_and_div_trap_on_both_runtimes | signal checked as status 136 | +| selfhost_tests.rs::handles_free_fresh_values | A | tests/sh/lifecycle.sh::t_handles_free_fresh_values | C+native .out, free fns in C, coll_move exact block, kept-not-freed, ASan | +| selfhost_tests.rs::int64_min_div_minus_one_flushes_on_every_backend | A | tests/sh/lifecycle.sh::t_int64_min_div_minus_one_flushes_on_every_backend | C, --rt=track, --native; status 136 | +| selfhost_tests.rs::life_dumps_match_goldens | A | tests/sh/lifecycle.sh::t_life_dumps_match_goldens | tests/life/*.life goldens, UPDATE_LIFE kept | +| selfhost_tests.rs::life_place_dumps_match_goldens | A | tests/sh/lifecycle.sh::t_life_place_dumps_match_goldens | .place goldens + 5 rule lines | +| selfhost_tests.rs::lifecycle_hard_errors_print_the_catalogue_texts | A | tests/sh/selfhost.sh::t_lifecycle_hard_errors_print_the_catalogue_texts | 19 cases in tests/cases/life_errors | +| selfhost_tests.rs::lifecycle_lookalikes_check_clean | A | tests/sh/selfhost.sh::t_lifecycle_lookalikes_check_clean | 10 cases in tests/cases/life_clean | +| selfhost_tests.rs::lifecycle_warnings_match_the_catalogue | A | tests/sh/selfhost.sh::t_lifecycle_warnings_match_the_catalogue | near misses in tests/cases/life_warn_clean | +| selfhost_tests.rs::native_binaries_carry_a_symbol_table | A | tests/sh/selfhost.sh::t_native_binaries_carry_a_symbol_table | skips without nm, as before | +| selfhost_tests.rs::native_test_suite_passes_under_trackc | A | tests/sh/selfhost.sh::t_native_test_suite_passes_under_trackc | | +| selfhost_tests.rs::non_escaping_tuples_use_stack_slots | A | tests/sh/selfhost.sh::t_non_escaping_tuples_use_stack_slots | | +| selfhost_tests.rs::program_without_main_runs_on_both_runtimes | A | tests/sh/selfhost.sh::t_program_without_main_runs_on_both_runtimes | | +| selfhost_tests.rs::ret_slots_write_caller_cells | A | tests/sh/lifecycle.sh::t_ret_slots_write_caller_cells | `__rs(` in C, 11 rule lines, ASan | +| selfhost_tests.rs::returns_hidden_in_expressions_are_seen | A | tests/sh/lifecycle.sh::t_returns_hidden_in_expressions_are_seen | banned-plan checks, ASan | +| selfhost_tests.rs::runtime_layout_consts_stay_reserved | A | tests/sh/lifecycle.sh::t_runtime_layout_consts_stay_reserved | E0201 under --native | +| selfhost_tests.rs::runtime_object_is_cached_and_builds_stay_identical | A | tests/sh/selfhost.sh::t_runtime_object_is_cached_and_builds_stay_identical | | +| selfhost_tests.rs::stack_cells_run_and_plan | A | tests/sh/lifecycle.sh::t_stack_cells_run_and_plan | .out/.place, `tk_w s0[` in C | +| selfhost_tests.rs::strfield_frees_owned_str_fields | A | tests/sh/lifecycle.sh::t_strfield_frees_owned_str_fields | ` strs ` ownership checks, LSan for 5 | +| selfhost_tests.rs::string_plus_string_is_a_type_error | A | tests/sh/lifecycle.sh::t_string_plus_string_is_a_type_error | 3 rejects + ptr arith accepted | +| selfhost_tests.rs::temps_free_fresh_cell_temporaries | A | tests/sh/lifecycle.sh::t_temps_free_fresh_cell_temporaries | accdeep native, LSan for the 8 all-die programs | +| selfhost_tests.rs::temps_free_fresh_temporaries | A | tests/sh/lifecycle.sh::t_temps_free_fresh_temporaries | counts per block, ASan+LSan for discard/nested/print_loop | +| selfhost_tests.rs::track_runtime_matches_the_c_runtime | A | tests/sh/selfhost.sh::t_track_runtime_matches_the_c_runtime | | +| selfhost_tests.rs::trackc_closes_checker_holes | A | tests/sh/selfhost.sh::t_trackc_closes_checker_holes | 46 cases in tests/cases/trackc_verdicts | +| selfhost_tests.rs::trackc_on_the_track_runtime_self_compiles | A | tests/sh/selfhost.sh::t_trackc_on_the_track_runtime_self_compiles | | +| selfhost_tests.rs::trackc_programs_print_the_expected_output | A | tests/sh/selfhost.sh::t_trackc_programs_print_the_expected_output | 10 cases in tests/cases/run_outputs | +| selfhost_tests.rs::user_names_never_clash_with_runtime_names | A | tests/sh/lifecycle.sh::t_user_names_never_clash_with_runtime_names | C, --rt=track, --native | +| selfhost_tests.rs::warnings_print_sorted_and_only_deny_warnings_fails | A | tests/sh/selfhost.sh::t_warnings_print_sorted_and_only_deny_warnings_fails | | +| soundness_tests.rs::test_soundness_double_move_rejected | B | checker_verdicts row soundness_double_move_rejected | | +| soundness_tests.rs::test_soundness_inconsistent_branch_move_rejected | B | checker_verdicts row soundness_inconsistent_branch_move_rejected | "inconsistent state" | +| soundness_tests.rs::test_soundness_lens_alias_not_visible_after_block | B | checker_verdicts row soundness_lens_alias_not_visible_after_block | | +| soundness_tests.rs::test_soundness_lens_escape_rejected | B | checker_verdicts row soundness_lens_escape_rejected | "Lens ... escape" | +| soundness_tests.rs::test_soundness_lens_released_on_early_return | B | checker_verdicts row soundness_lens_released_on_early_return | | +| soundness_tests.rs::test_soundness_loop_consumed_variable_use_rejected | B | checker_verdicts row soundness_loop_consumed_variable_use_rejected | trackc half; pins trackc's first line (mentions 'v') | +| soundness_tests.rs::test_soundness_loop_reinitialization_accepted | B | checker_verdicts row soundness_loop_reinitialization_accepted | | +| soundness_tests.rs::test_soundness_nested_lens_same_target_rejected | B | checker_verdicts row soundness_nested_lens_same_target_rejected | | +| yard_tests.rs::test_yard_build_errors_follow_source_order | C | PR #36 case `build_errors_follow_source_order` | Rust calls ParallelBuilder directly; PR runs `yard build` 4x and checks a.trk is the first error | +| yard_tests.rs::test_yard_build_generics_project | C | PR #36 case `build_generics_project` | 1:1 | +| yard_tests.rs::test_yard_dependency_resolution_is_sorted | C | PR #36 case `dependency_resolution_is_sorted` | Rust calls resolver::resolve; PR checks the "Using dependency" order of `yard build` | +| yard_tests.rs::test_yard_init_add_check_in_temp_dir | C | PR #36 case `init_add_check_in_temp_dir` | 1:1 | +| yard_tests.rs::test_yard_lint_and_clean | C | PR #36 case `lint_and_clean` | 1:1 | +| yard_tests.rs::test_yard_manifest_serialization | C | PR #36 tests/yard/run.sh case `manifest_serialization` | Rust test hits the Rust Manifest/toml API; PR checks the same fields through `yard init` + `add` round trip | +| yard_tests.rs::test_yard_nested_modules_have_isolated_stable_artifacts | C | PR #36 case `nested_modules_have_isolated_stable_artifacts` | 1:1 | +| yard_tests.rs::test_yard_parallel_build_and_incremental_cache | C | PR #36 case `parallel_build_and_incremental_cache` | 1:1 | +| yard_tests.rs::test_yard_version_reports | C | PR #36 case `version_reports` | 1:1 | diff --git a/tests/cases/const_divrem/div_cmp_ok.trk b/tests/cases/const_divrem/div_cmp_ok.trk new file mode 100644 index 00000000..cac5c45e --- /dev/null +++ b/tests/cases/const_divrem/div_cmp_ok.trk @@ -0,0 +1 @@ +const Q = 7 / (1 < 2); fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_cmp_zero.trk b/tests/cases/const_divrem/div_cmp_zero.trk new file mode 100644 index 00000000..26e3784a --- /dev/null +++ b/tests/cases/const_divrem/div_cmp_zero.trk @@ -0,0 +1 @@ +const Q = 7 / (1 == 2); fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_cmp_zero.want b/tests/cases/const_divrem/div_cmp_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/div_cmp_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/div_min.trk b/tests/cases/const_divrem/div_min.trk new file mode 100644 index 00000000..8f9a085b --- /dev/null +++ b/tests/cases/const_divrem/div_min.trk @@ -0,0 +1 @@ +const M = 0 - 9223372036854775807 - 1; const Q = M / (0 - 1); fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_min.want b/tests/cases/const_divrem/div_min.want new file mode 100644 index 00000000..df878e33 --- /dev/null +++ b/tests/cases/const_divrem/div_min.want @@ -0,0 +1 @@ +error[E0200]: division overflow in a constant expression diff --git a/tests/cases/const_divrem/div_named_cmp_ok.trk b/tests/cases/const_divrem/div_named_cmp_ok.trk new file mode 100644 index 00000000..4a17f0b7 --- /dev/null +++ b/tests/cases/const_divrem/div_named_cmp_ok.trk @@ -0,0 +1 @@ +const Z = 1 != 2; const Q = 7 / Z; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_named_cmp_zero.trk b/tests/cases/const_divrem/div_named_cmp_zero.trk new file mode 100644 index 00000000..611d7f47 --- /dev/null +++ b/tests/cases/const_divrem/div_named_cmp_zero.trk @@ -0,0 +1 @@ +const Z = 1 == 2; const Q = 7 / Z; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_named_cmp_zero.want b/tests/cases/const_divrem/div_named_cmp_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/div_named_cmp_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/div_ok.trk b/tests/cases/const_divrem/div_ok.trk new file mode 100644 index 00000000..50c3b539 --- /dev/null +++ b/tests/cases/const_divrem/div_ok.trk @@ -0,0 +1 @@ +const M = 0 - 9223372036854775807 - 1; const Q = M / 2 + M % 3; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_variant_after_cmp_zero.trk b/tests/cases/const_divrem/div_variant_after_cmp_zero.trk new file mode 100644 index 00000000..6cae0ba2 --- /dev/null +++ b/tests/cases/const_divrem/div_variant_after_cmp_zero.trk @@ -0,0 +1 @@ +const NO = 2 < 1; enum E { A = NO, B } const Q = 7 / E::A; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_variant_after_cmp_zero.want b/tests/cases/const_divrem/div_variant_after_cmp_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/div_variant_after_cmp_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/div_variant_named_cmp_ok.trk b/tests/cases/const_divrem/div_variant_named_cmp_ok.trk new file mode 100644 index 00000000..5f2d13b3 --- /dev/null +++ b/tests/cases/const_divrem/div_variant_named_cmp_ok.trk @@ -0,0 +1 @@ +const ONE = 1 < 2; enum E { A = ONE } const Q = 7 / E::A; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_variant_next_ok.trk b/tests/cases/const_divrem/div_variant_next_ok.trk new file mode 100644 index 00000000..fe18406f --- /dev/null +++ b/tests/cases/const_divrem/div_variant_next_ok.trk @@ -0,0 +1 @@ +const NO = 2 < 1; enum E { A = NO, B } const Q = 7 / E::B; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_variant_ok.trk b/tests/cases/const_divrem/div_variant_ok.trk new file mode 100644 index 00000000..69fd9e6f --- /dev/null +++ b/tests/cases/const_divrem/div_variant_ok.trk @@ -0,0 +1 @@ +enum E { Z, O } const Q = 7 / E::O; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_variant_zero.trk b/tests/cases/const_divrem/div_variant_zero.trk new file mode 100644 index 00000000..07b95afc --- /dev/null +++ b/tests/cases/const_divrem/div_variant_zero.trk @@ -0,0 +1 @@ +enum E { Z, O } const Q = 7 / E::Z; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_variant_zero.want b/tests/cases/const_divrem/div_variant_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/div_variant_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/div_zero.trk b/tests/cases/const_divrem/div_zero.trk new file mode 100644 index 00000000..fe19bc21 --- /dev/null +++ b/tests/cases/const_divrem/div_zero.trk @@ -0,0 +1 @@ +const Q = 7 / 0; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/div_zero.want b/tests/cases/const_divrem/div_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/div_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/enum_div_min.trk b/tests/cases/const_divrem/enum_div_min.trk new file mode 100644 index 00000000..a701d3a4 --- /dev/null +++ b/tests/cases/const_divrem/enum_div_min.trk @@ -0,0 +1 @@ +const M = 0 - 9223372036854775807 - 1; enum E { A = M / (0 - 1) } const Q = 1; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/enum_div_min.want b/tests/cases/const_divrem/enum_div_min.want new file mode 100644 index 00000000..df878e33 --- /dev/null +++ b/tests/cases/const_divrem/enum_div_min.want @@ -0,0 +1 @@ +error[E0200]: division overflow in a constant expression diff --git a/tests/cases/const_divrem/enum_div_zero.trk b/tests/cases/const_divrem/enum_div_zero.trk new file mode 100644 index 00000000..64b60f27 --- /dev/null +++ b/tests/cases/const_divrem/enum_div_zero.trk @@ -0,0 +1 @@ +enum E { A, B = 7 / 0, C } const Q = 1; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/enum_div_zero.want b/tests/cases/const_divrem/enum_div_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/enum_div_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/enum_named_cmp_zero.trk b/tests/cases/const_divrem/enum_named_cmp_zero.trk new file mode 100644 index 00000000..abef38d5 --- /dev/null +++ b/tests/cases/const_divrem/enum_named_cmp_zero.trk @@ -0,0 +1 @@ +const Z = 2 < 1; enum E { A = 7 / Z } const Q = 1; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/enum_named_cmp_zero.want b/tests/cases/const_divrem/enum_named_cmp_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/enum_named_cmp_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/mod_min.trk b/tests/cases/const_divrem/mod_min.trk new file mode 100644 index 00000000..7e1c8389 --- /dev/null +++ b/tests/cases/const_divrem/mod_min.trk @@ -0,0 +1 @@ +const M = 0 - 9223372036854775807 - 1; const Q = M % (0 - 1); fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/mod_min.want b/tests/cases/const_divrem/mod_min.want new file mode 100644 index 00000000..df878e33 --- /dev/null +++ b/tests/cases/const_divrem/mod_min.want @@ -0,0 +1 @@ +error[E0200]: division overflow in a constant expression diff --git a/tests/cases/const_divrem/mod_named_not_zero.trk b/tests/cases/const_divrem/mod_named_not_zero.trk new file mode 100644 index 00000000..dda0766e --- /dev/null +++ b/tests/cases/const_divrem/mod_named_not_zero.trk @@ -0,0 +1 @@ +const Z = !(3 > 2); const Q = 7 % (Z + Z); fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/mod_named_not_zero.want b/tests/cases/const_divrem/mod_named_not_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/mod_named_not_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/mod_not_zero.trk b/tests/cases/const_divrem/mod_not_zero.trk new file mode 100644 index 00000000..9bc27dd1 --- /dev/null +++ b/tests/cases/const_divrem/mod_not_zero.trk @@ -0,0 +1 @@ +const Q = 7 % !1; fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/mod_not_zero.want b/tests/cases/const_divrem/mod_not_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/mod_not_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/const_divrem/mod_zero.trk b/tests/cases/const_divrem/mod_zero.trk new file mode 100644 index 00000000..c168c584 --- /dev/null +++ b/tests/cases/const_divrem/mod_zero.trk @@ -0,0 +1 @@ +const Q = 7 % (1 - 1); fn main() -> void { print(Q); } \ No newline at end of file diff --git a/tests/cases/const_divrem/mod_zero.want b/tests/cases/const_divrem/mod_zero.want new file mode 100644 index 00000000..bedb06c1 --- /dev/null +++ b/tests/cases/const_divrem/mod_zero.want @@ -0,0 +1 @@ +error[E0200]: division by zero in a constant expression diff --git a/tests/cases/examples/arithmetic.code b/tests/cases/examples/arithmetic.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/arithmetic.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/arithmetic.out b/tests/cases/examples/arithmetic.out new file mode 100644 index 00000000..64bb6b74 --- /dev/null +++ b/tests/cases/examples/arithmetic.out @@ -0,0 +1 @@ +30 diff --git a/tests/cases/examples/borrow.code b/tests/cases/examples/borrow.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/borrow.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/borrow.out b/tests/cases/examples/borrow.out new file mode 100644 index 00000000..d81cc071 --- /dev/null +++ b/tests/cases/examples/borrow.out @@ -0,0 +1 @@ +42 diff --git a/tests/cases/examples/error_handling.code b/tests/cases/examples/error_handling.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/error_handling.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/error_handling.out b/tests/cases/examples/error_handling.out new file mode 100644 index 00000000..e790cd6d --- /dev/null +++ b/tests/cases/examples/error_handling.out @@ -0,0 +1,2 @@ +@HOSTNAME_BYTES@ +7 diff --git a/tests/cases/examples/generics.code b/tests/cases/examples/generics.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/generics.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/generics.out b/tests/cases/examples/generics.out new file mode 100644 index 00000000..5f439bb1 --- /dev/null +++ b/tests/cases/examples/generics.out @@ -0,0 +1,7 @@ +5 +10 +1 +2 +1 +2 +100 diff --git a/tests/cases/examples/hello.code b/tests/cases/examples/hello.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/hello.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/hello.out b/tests/cases/examples/hello.out new file mode 100644 index 00000000..d81cc071 --- /dev/null +++ b/tests/cases/examples/hello.out @@ -0,0 +1 @@ +42 diff --git a/tests/cases/examples/linear_auto_free.code b/tests/cases/examples/linear_auto_free.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/linear_auto_free.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/linear_auto_free.out b/tests/cases/examples/linear_auto_free.out new file mode 100644 index 00000000..16bdbac6 --- /dev/null +++ b/tests/cases/examples/linear_auto_free.out @@ -0,0 +1,2 @@ +10 +done diff --git a/tests/cases/examples/macro_test.code b/tests/cases/examples/macro_test.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/macro_test.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/macro_test.out b/tests/cases/examples/macro_test.out new file mode 100644 index 00000000..0c86e125 --- /dev/null +++ b/tests/cases/examples/macro_test.out @@ -0,0 +1,3 @@ +32 +261 +1073938176 diff --git a/tests/cases/examples/net_demo.code b/tests/cases/examples/net_demo.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/net_demo.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/net_demo.out b/tests/cases/examples/net_demo.out new file mode 100644 index 00000000..d00491fd --- /dev/null +++ b/tests/cases/examples/net_demo.out @@ -0,0 +1 @@ +1 diff --git a/tests/cases/examples/slice_and_types.code b/tests/cases/examples/slice_and_types.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/slice_and_types.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/slice_and_types.out b/tests/cases/examples/slice_and_types.out new file mode 100644 index 00000000..c66105fe --- /dev/null +++ b/tests/cases/examples/slice_and_types.out @@ -0,0 +1,5 @@ +42 +-10 +3 +20 +40 diff --git a/tests/cases/examples/stdlib_demo.code b/tests/cases/examples/stdlib_demo.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/stdlib_demo.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/stdlib_demo.out b/tests/cases/examples/stdlib_demo.out new file mode 100644 index 00000000..f3653c95 --- /dev/null +++ b/tests/cases/examples/stdlib_demo.out @@ -0,0 +1,4 @@ +100 +1111 +6 +4242 diff --git a/tests/cases/examples/structs_arrays.code b/tests/cases/examples/structs_arrays.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/structs_arrays.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/structs_arrays.out b/tests/cases/examples/structs_arrays.out new file mode 100644 index 00000000..7d87184e --- /dev/null +++ b/tests/cases/examples/structs_arrays.out @@ -0,0 +1,9 @@ +7 +10 +75 +0 +1 +2 +46 +35 +2 diff --git a/tests/cases/examples/union_enum_test.code b/tests/cases/examples/union_enum_test.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/union_enum_test.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/union_enum_test.out b/tests/cases/examples/union_enum_test.out new file mode 100644 index 00000000..fd6ea5a2 --- /dev/null +++ b/tests/cases/examples/union_enum_test.out @@ -0,0 +1,4 @@ +111 +42 +hello +world diff --git a/tests/cases/examples/use_test.code b/tests/cases/examples/use_test.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/use_test.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/use_test.out b/tests/cases/examples/use_test.out new file mode 100644 index 00000000..09811b6b --- /dev/null +++ b/tests/cases/examples/use_test.out @@ -0,0 +1,5 @@ +111 +222 +30 +333 +70 diff --git a/tests/cases/examples/v030_features_demo.code b/tests/cases/examples/v030_features_demo.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/v030_features_demo.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/v030_features_demo.out b/tests/cases/examples/v030_features_demo.out new file mode 100644 index 00000000..b261da18 --- /dev/null +++ b/tests/cases/examples/v030_features_demo.out @@ -0,0 +1,2 @@ +1 +0 diff --git a/tests/cases/examples/v040_features_demo.code b/tests/cases/examples/v040_features_demo.code new file mode 100644 index 00000000..573541ac --- /dev/null +++ b/tests/cases/examples/v040_features_demo.code @@ -0,0 +1 @@ +0 diff --git a/tests/cases/examples/v040_features_demo.out b/tests/cases/examples/v040_features_demo.out new file mode 100644 index 00000000..45462c77 --- /dev/null +++ b/tests/cases/examples/v040_features_demo.out @@ -0,0 +1,4 @@ +42 +100 +30 +1 diff --git a/tests/cases/lang/argv.trk b/tests/cases/lang/argv.trk new file mode 100644 index 00000000..3fd5712f --- /dev/null +++ b/tests/cases/lang/argv.trk @@ -0,0 +1,5 @@ +fn main() -> void { + print(os_args_count()); + let first = os_arg(1); + print(first); +} diff --git a/tests/cases/lang/constfold.trk b/tests/cases/lang/constfold.trk new file mode 100644 index 00000000..4d08f77d --- /dev/null +++ b/tests/cases/lang/constfold.trk @@ -0,0 +1,8 @@ +const ONE = 1 < 2; +enum E { A = ONE, B } +const Q = E::B + 10; +const N = !ONE || (3 >= 3); +fn main() -> void { + print(ONE); print(E::A); print(E::B); print(Q); print(N); + print(7 / (1 < 2)); +} diff --git a/tests/cases/lang/consts.trk b/tests/cases/lang/consts.trk new file mode 100644 index 00000000..22233d8e --- /dev/null +++ b/tests/cases/lang/consts.trk @@ -0,0 +1,11 @@ +const BASE = 100; +const OFFSET = BASE + 23; + +fn get_offset() -> i64 { + return OFFSET; +} + +fn main() -> void { + print(BASE); + print(get_offset()); +} diff --git a/tests/cases/lang/error_handling.trk b/tests/cases/lang/error_handling.trk new file mode 100644 index 00000000..219e81b5 --- /dev/null +++ b/tests/cases/lang/error_handling.trk @@ -0,0 +1,26 @@ +const ERR_NOT_FOUND = 1; + +fn file_len(path: &ptr) -> (i64, i32) { + let ok = file_exists(path); + if (!ok) { + return (-1, ERR_NOT_FOUND); + } + return (file_size(path), 0); +} + +fn total(path: &ptr, fallback: i64) -> i64 { + let (size, err) = file_len(path); + if (err == ERR_NOT_FOUND) { + print_err("missing input, using fallback"); + return fallback; + } + if (err != 0) { + abort("fatal: unexpected error"); + } + return size; +} + +fn main() -> void { + print(total("/etc/hostname", -7)); + print(total("/definitely/not/here", 7)); +} diff --git a/tests/cases/lang/for_test.trk b/tests/cases/lang/for_test.trk new file mode 100644 index 00000000..489d4887 --- /dev/null +++ b/tests/cases/lang/for_test.trk @@ -0,0 +1,6 @@ +import "std/io"; +fn main() -> void { + for i in 0..3 { + print(i); + } +} diff --git a/tests/cases/lang/gen.trk b/tests/cases/lang/gen.trk new file mode 100644 index 00000000..c018c554 --- /dev/null +++ b/tests/cases/lang/gen.trk @@ -0,0 +1,14 @@ +fn identity(x: T) -> T { return x; } +fn pair(a: T, b: U) -> (T, U) { return (a, b); } +fn main() -> void { + let a: i32 = 5; + print(identity(a)); + let b: i64 = 10; + print(identity(b)); + let p = pair(1, 2); + print(p.0); + print(p.1); + let z = pair(identity(1), identity(2)); + print(z.0); + print(z.1); +} diff --git a/tests/cases/lang/lex_comments.tokens b/tests/cases/lang/lex_comments.tokens new file mode 100644 index 00000000..d1ea3d35 --- /dev/null +++ b/tests/cases/lang/lex_comments.tokens @@ -0,0 +1,6 @@ +'let' +identifier x +'=' +integer 10 +';' +end of file diff --git a/tests/cases/lang/lex_comments.trk b/tests/cases/lang/lex_comments.trk new file mode 100644 index 00000000..2d4ea17a --- /dev/null +++ b/tests/cases/lang/lex_comments.trk @@ -0,0 +1,2 @@ +// This is a comment +let x = 10; // comment after code diff --git a/tests/cases/lang/lex_keywords.tokens b/tests/cases/lang/lex_keywords.tokens new file mode 100644 index 00000000..9401c65d --- /dev/null +++ b/tests/cases/lang/lex_keywords.tokens @@ -0,0 +1,20 @@ +'import' +'let' +'mut' +'with' +'fn' +'return' +'if' +'else' +'while' +'true' +'false' +'struct' +'enum' +'union' +'match' +'as' +'const' +'@' +'@macro' +end of file diff --git a/tests/cases/lang/lex_keywords.trk b/tests/cases/lang/lex_keywords.trk new file mode 100644 index 00000000..f6a6e57e --- /dev/null +++ b/tests/cases/lang/lex_keywords.trk @@ -0,0 +1 @@ +import let mut with fn return if else while true false struct enum union match as const @ @macro \ No newline at end of file diff --git a/tests/cases/lang/lex_literals.tokens b/tests/cases/lang/lex_literals.tokens new file mode 100644 index 00000000..2c72688e --- /dev/null +++ b/tests/cases/lang/lex_literals.tokens @@ -0,0 +1,5 @@ +integer 12345 +string TK_S("hello world\015\n\t") +identifier my_var +identifier _var2 +end of file diff --git a/tests/cases/lang/lex_literals.trk b/tests/cases/lang/lex_literals.trk new file mode 100644 index 00000000..ea22ff97 --- /dev/null +++ b/tests/cases/lang/lex_literals.trk @@ -0,0 +1 @@ +12345 "hello world\r\n\t" my_var _var2 \ No newline at end of file diff --git a/tests/cases/lang/lex_operators.tokens b/tests/cases/lang/lex_operators.tokens new file mode 100644 index 00000000..99f149c2 --- /dev/null +++ b/tests/cases/lang/lex_operators.tokens @@ -0,0 +1,34 @@ +'=' +'==' +'!=' +'!' +'{' +'}' +'(' +')' +'[' +']' +',' +':' +'::' +'->' +'=>' +';' +'.' +'_' +'&' +'|' +'*' +'+' +'-' +'/' +'%' +'<' +'>' +'<=' +'>=' +'&&' +'||' +'<<' +'>>' +end of file diff --git a/tests/cases/lang/lex_operators.trk b/tests/cases/lang/lex_operators.trk new file mode 100644 index 00000000..07805565 --- /dev/null +++ b/tests/cases/lang/lex_operators.trk @@ -0,0 +1 @@ += == != ! { } ( ) [ ] , : :: -> => ; . _ & | * + - / % < > <= >= && || << >> \ No newline at end of file diff --git a/tests/cases/lang/lex_types.tokens b/tests/cases/lang/lex_types.tokens new file mode 100644 index 00000000..1cdab118 --- /dev/null +++ b/tests/cases/lang/lex_types.tokens @@ -0,0 +1,8 @@ +'i32' +'u32' +'i64' +'u64' +'bool' +'void' +'ptr' +end of file diff --git a/tests/cases/lang/lex_types.trk b/tests/cases/lang/lex_types.trk new file mode 100644 index 00000000..6419c4ae --- /dev/null +++ b/tests/cases/lang/lex_types.trk @@ -0,0 +1 @@ +i32 u32 i64 u64 bool void ptr \ No newline at end of file diff --git a/tests/cases/lang/lnot.trk b/tests/cases/lang/lnot.trk new file mode 100644 index 00000000..8294f7f1 --- /dev/null +++ b/tests/cases/lang/lnot.trk @@ -0,0 +1,11 @@ +fn main() -> void { + let ok = file_exists("/etc/hostname"); + if (!ok) { + print(999); + return; + } + let missing = file_exists("/definitely/not/here"); + if (!missing) { + print(42); + } +} diff --git a/tests/cases/lang/logic.trk b/tests/cases/lang/logic.trk new file mode 100644 index 00000000..2d8e3cb2 --- /dev/null +++ b/tests/cases/lang/logic.trk @@ -0,0 +1,13 @@ +fn loud(v: i64) -> i64 { + print(v); + return v; +} +fn main() -> void { + let x: i64 = 1; + let y: i64 = 2; + if x && y { print(10); } else { print(11); } + if loud(0) && loud(5) { print(12); } + if loud(3) || loud(6) { print(13); } + let z = x && y; + print(z); +} diff --git a/tests/cases/lang/mem_test.trk b/tests/cases/lang/mem_test.trk new file mode 100644 index 00000000..e170ed69 --- /dev/null +++ b/tests/cases/lang/mem_test.trk @@ -0,0 +1,4 @@ +fn main() -> void { + sys_set_memory_limit(1000); + let buf = alloc(2000); +} diff --git a/tests/cases/lang/parses.tsv b/tests/cases/lang/parses.tsv new file mode 100644 index 00000000..3ec3e865 --- /dev/null +++ b/tests/cases/lang/parses.tsv @@ -0,0 +1,20 @@ +# name rc first stderr line prefix ("-" = no error line) source +# trackc half of parser_tests.rs: the Rust tests compared stage0 AST +# shapes (no trackc equivalent). Here trackc must parse each source: no +# lexer (E0001) or parser (E01xx) diagnostic, and the verdict after parsing +# is pinned (some sources name undeclared variables or modules). +parse_fn_def 0 - fn add(a: i32, b: i32) -> i32 { return a + b; } +parse_let_def 0 - let mut x: i64 = 100; +parse_slice_type_and_indexing 1 error[E0200]: Undeclared variable 'arr'. let s: []u8 = arr[0..5]; +parse_struct_and_lens 0 - let u = User { age: 30 }; with u -> user { user.set_age(31); } +parse_enum_and_union 0 - enum Status: i32 { Active = 1, Inactive = 0 } union Value { Int(i32), Empty } +parse_match 1 error[E0200]: Undeclared variable 'val'. match val { Value::Int(n) if n > 0 => print(n), _ => print(0) } +parse_macro_def_and_call 0 - @macro bit(n: u32) -> u32 { return 1 << n; } let val = @bit(5); +parse_use_and_const 1 error[E0011]: Unknown module 'std/math' import "std/math" as m :: { abs, max }; const PI = 3; +parse_array_type_and_literal 0 - let arr: [i32; 3] = [1, 2, 3]; let x = arr[0]; +parse_type_alias 0 - type ByteBuf = []u8; +parse_for_in_loop 0 - for i in 0..10 { print(i); } +parse_use_statement 1 error[E0200]: Module 'std/io' does not export 'read_line' use "std/io" as io::{print, read_line}; +parse_generic_fn_single_param 0 - fn identity(x: T) -> T { return x; } +parse_generic_fn_multi_params 0 - fn pair(a: T, b: U) -> (T, U) { return (a, b); } +parse_generic_fn_no_return 0 - fn log(x: T) { print(x); } diff --git a/tests/cases/lang/pred.trk b/tests/cases/lang/pred.trk new file mode 100644 index 00000000..faa044e0 --- /dev/null +++ b/tests/cases/lang/pred.trk @@ -0,0 +1,14 @@ +fn main() -> void { + if (str_is_int("00042")) { + print(str_to_int("00042")); + } + if (!str_is_int("junk")) { + print(111); + } + if (env_exists("PATH")) { + print(222); + } + if (!env_exists("TRACK_DEFINITELY_NOT_SET_9x7")) { + print(333); + } +} diff --git a/tests/cases/lang/returns.trk b/tests/cases/lang/returns.trk new file mode 100644 index 00000000..5a1b23ee --- /dev/null +++ b/tests/cases/lang/returns.trk @@ -0,0 +1,35 @@ +fn pick(x: i64) -> i64 { + match x { + 1 => return 10, + _ => return 20, + } + return 0; +} +fn first_over(limit: i64) -> i64 { + let mut i: i64 = 0; + while i < 100 { + if i * i > limit { + return i; + } + i = i + 1; + } + return -1; +} +fn nested(x: i64) -> i64 { + if x > 0 { + if x > 5 { return 7; } else { return 8; } + } + return 9; +} +fn loop_return(x: i64) -> i64 { + while x > 0 { + return 5; + } + return 6; +} +fn main() -> void { + print(pick(1)); print(pick(4)); + print(first_over(50)); + print(nested(10)); print(nested(2)); print(nested(-1)); + print(loop_return(1)); print(loop_return(0)); +} diff --git a/tests/cases/lang/scopes.trk b/tests/cases/lang/scopes.trk new file mode 100644 index 00000000..82196f72 --- /dev/null +++ b/tests/cases/lang/scopes.trk @@ -0,0 +1,12 @@ +fn main() -> void { + let x = 10; + if true { + let x = 20; + print(x); + } + print(x); + match 1 { + x => print(x), + } + print(x); +} diff --git a/tests/cases/lang/signs.trk b/tests/cases/lang/signs.trk new file mode 100644 index 00000000..074e48a8 --- /dev/null +++ b/tests/cases/lang/signs.trk @@ -0,0 +1,6 @@ +fn main() -> void { + let r = file_remove("/definitely/not/here/x"); + print(r); + let c = str_char_at("abc", 1); + print(c); +} diff --git a/tests/cases/lang/strpat.trk b/tests/cases/lang/strpat.trk new file mode 100644 index 00000000..53058e35 --- /dev/null +++ b/tests/cases/lang/strpat.trk @@ -0,0 +1,8 @@ +fn main() -> void { + let s = str_concat("he", "llo"); + match s { + "world" => print(0), + "hello" => print(1), + _ => print(2), + } +} diff --git a/tests/cases/lang/structs.trk b/tests/cases/lang/structs.trk new file mode 100644 index 00000000..37a632f4 --- /dev/null +++ b/tests/cases/lang/structs.trk @@ -0,0 +1,18 @@ +struct Point { x: i64, y: i64 } +struct Size { w: i64, x: i64 } +fn make(n: i64) -> Point { let p = Point { y: n + 1, x: n }; return p; } +fn main() -> void { + let mut p = make(3); + print(p.x); print(p.y); + p.x = 10; + let s = Size { x: 8, w: 7 }; + print(p.x + s.x); + match p { Point { x: 10, y } => print(y), _ => print(0), } + let mut a = [1, 2, 3, 4]; + a[3] = 40; + let tail = a[2..]; + print(array_len(&tail)); print(tail[1]); + let mut t = (1, 2); + t.1 = 9; + print(t.1); +} diff --git a/tests/cases/lang/tuples.trk b/tests/cases/lang/tuples.trk new file mode 100644 index 00000000..8bc47b10 --- /dev/null +++ b/tests/cases/lang/tuples.trk @@ -0,0 +1,14 @@ +type Pair = (i64, i64); +fn make(a: i64) -> Pair { + let t = (a, a + 1); + return t; +} +fn clobber() -> i64 { + let z = (9, 9, 9, 9, 9, 9, 9, 9); + return z.0; +} +fn main() -> void { + let p = make(5); + let q = clobber(); + print(p.0); print(p.1); print(q); +} diff --git a/tests/cases/lang/unions.trk b/tests/cases/lang/unions.trk new file mode 100644 index 00000000..ba71739c --- /dev/null +++ b/tests/cases/lang/unions.trk @@ -0,0 +1,17 @@ +union Value { Int(i64), Flag(bool), Nothing } +enum Code { A = 5, B, C = 10 } +fn describe(v: Value) -> i64 { + let mut out: i64 = -1; + match v { + Value::Int(n) => out = n, + Value::Flag(f) => out = 1000 + f, + Value::Nothing => out = 0, + } + return out; +} +fn main() -> void { + print(describe(Value::Int(42))); + print(describe(Value::Flag(true))); + print(describe(Value::Nothing)); + print(Code::A); print(Code::B); print(Code::C); +} diff --git a/tests/cases/lang/values.trk b/tests/cases/lang/values.trk new file mode 100644 index 00000000..8624e84e --- /dev/null +++ b/tests/cases/lang/values.trk @@ -0,0 +1,12 @@ +fn sign(x: i64) -> i64 { + let s = if x < 0 { -1 } else if x == 0 { 0 } else { 1 }; + return s; +} +fn name(x: i64) -> i64 { + let v = match x { 1 => 100, 2 => 200, _ => 300, }; + return v; +} +fn main() -> void { + print(sign(-4)); print(sign(0)); print(sign(9)); + print(name(2)); print(name(7)); +} diff --git a/tests/cases/lang/verdicts.tsv b/tests/cases/lang/verdicts.tsv new file mode 100644 index 00000000..efc6715c --- /dev/null +++ b/tests/cases/lang/verdicts.tsv @@ -0,0 +1,42 @@ +# name rc first stderr line prefix ("-" = no error line) source (one line) +# Ported from regression_tests.rs, soundness_tests.rs, +# logic_and_soundness_strict_tests.rs, checker_tests.rs and cli_tests.rs: +# the Rust stage0 verdict each test asserted, now asserted on `trackc check` +# with trackc's exact first diagnostic line. +regression_nested_expressions 0 - fn main() -> void { let x: i64 = ((10 + 20) * (30 - 5)) / (2 % 1 + 5); print(x); } +regression_nested_if_else_chain 0 - fn classify(n: i32) -> i32 { if n < 0 { return -1; } else if n == 0 { return 0; } else if n < 10 { return 1; } else { return 2; } } +regression_multiple_macro_calls 0 - @macro add_one(x: i32) -> i32 { return x + 1; } fn main() -> void { let a = @add_one(10); let b = @add_one(@add_one(20)); print(a + b); } +regression_complex_match_guards 0 - union Number { Int(i32), Big(i64), Zero, } fn check_num(n: Number) -> i32 { match n { Number::Int(val) if val > 100 => print(val), Number::Int(val) => print(val), Number::Big(val) => print(val), Number::Zero => print(0), _ => print(-1), } return 0; } +regression_nested_lens_blocks 0 - fn main() -> void { let mut outer = Outer { inner: Inner { value: 42 } }; with outer -> o { with o -> i { let v = i.value(); } } } +regression_shadowed_variables 0 - fn main() -> void { let x = 10; if true { let x = 20; print(x); } print(x); } +regression_top_level_variables_and_deref 0 - let x = 1; let r = &x; fn main() -> void { print("Hello, Track!"); print(*r); } +soundness_loop_consumed_variable_use_rejected 1 error[E0200]: Cannot consume linear resource 'v' inside a loop. fn main() -> void { let mut v = vec_init(16); while true { let x = v; } let y = v; } +soundness_loop_reinitialization_accepted 0 - fn main() -> void { let mut v = vec_init(16); while true { let tmp = v; v = vec_init(16); } let end = v; } +soundness_lens_escape_rejected 1 error[E0200]: Lens 'lens' cannot be moved, stored, returned, or escape its with block. fn main() -> void { let mut v = vec_init(16); with v -> lens { let leaked = lens; } } +soundness_lens_alias_not_visible_after_block 1 error[E0200]: Undeclared variable 'lens'. fn main() -> void { let mut v = vec_init(16); with v -> lens { vec_push(lens, 1); } vec_push(lens, 2); } +soundness_nested_lens_same_target_rejected 1 error[E0200]: Cannot create lens. 'v' is not Active. fn main() -> void { let mut v = vec_init(16); with v -> a { with v -> b { vec_push(b, 1); } } } +soundness_lens_released_on_early_return 0 - fn f(cond: bool) -> void { let mut v = vec_init(16); with v -> lens { if cond { return; } else { vec_push(lens, 1); } } let x = v; } +soundness_inconsistent_branch_move_rejected 1 error[E0200]: Resource 'v' has inconsistent state after if/else. fn main() -> void { let v = vec_init(16); let cond = true; if cond { let x = v; } else { let y = 10; } let z = v; } +soundness_double_move_rejected 1 error[E0200]: Use-after-free! Resource 'v' is already spent. fn main() -> void { let v = vec_init(16); let x = v; let y = v; } +strict_mutability_reassignment_rejection 1 error[E0200]: Cannot mutate immutable variable 'x' fn main() -> void { let x = 10; x = 20; } +strict_mutable_variable_reassignment_allowed 0 - fn main() -> void { let mut x = 10; x = 20; print(x); } +strict_double_move_in_loop_rejection 1 error[E0200]: Cannot consume linear resource 'r' inside a loop. struct Resource { id: i32 } fn consume(r: Resource) -> void { print(1); } fn main() -> void { let r = Resource { id: 1 }; let mut i = 0; while i < 5 { let consumed = r; i = i + 1; } } +strict_unresolved_type_alias_detection 0 - type Buffer = UnknownType; fn main() -> void { let buf = 10; } +strict_borrow_escape_from_lens_block 0 - struct System { state: i32 } fn main() -> void { let mut sys = System { state: 1 }; with sys -> s { let val = 10; } sys = System { state: 2 }; } +checker_valid_code 0 - fn main() -> void { let x: i32 = 42; let y = x; print(x); print(y); } +checker_linear_type_transfer 0 - fn process(v: Vec) -> void { } fn main() -> void { let v: Vec = vec_init(10); process(v); } +checker_use_after_free_error 1 error[E0200]: Use-after-free! Resource 'v' is already spent. fn consume(v: Vec) -> void {} fn main() -> void { let v: Vec = vec_init(10); consume(v); consume(v); } +checker_lens_block_valid_and_locked 0 - fn main() -> void { let mut u = User { age: 30 }; with u -> user { let a = user.age(); } print(u); } +checker_lens_block_locked_error 1 error[E0200]: Resource 'u' is frozen (either locked in a lens or borrowed). fn use_user(u: User) -> void {} fn main() -> void { let mut u = User { age: 30 }; with u -> user { use_user(u); } } +checker_borrow_and_escape 0 - fn main() -> void { let mut v: Vec = vec_init(10); let ref_v = &mut v; vec_push(ref_v, 1); } +checker_escape_error 1 error[E0200]: Cannot return reference to local variable 'v' (escapes function scope). fn escape() -> &Vec { let v: Vec = vec_init(10); return &v; } +checker_enum_and_union_matching 0 - enum Color { Red, Green, Blue } union Result { Ok(i32), Err } fn main() -> void { let c = Color::Red; match c { Color::Red => print(1), Color::Green => print(2), Color::Blue => print(3), } let r = Result::Ok(42); match r { Result::Ok(val) => print(val), Result::Err => print(0), } } +checker_type_alias_and_os_api 0 - type Buffer = []u8; fn main() -> void { let count = os_args_count(); print(count); let exists = dir_exists("src"); } +checker_extended_char_str_path_api 0 - fn main() -> void { let is_d = char_is_digit(53); let is_a = char_is_alpha(65); let u = char_to_upper(97); let starts = str_starts_with("compiler", "comp"); let sub = str_substr("hello world", 0, 5); let base = path_basename("/bin/track"); let ext = path_ext("main.trk"); let joined = path_join("src", "lib.rs"); } +checker_typo_suggestion 1 error[E0200]: Undefined function 'prnt'. Did you mean 'print'? fn main() -> void { prnt("Hello"); } +checker_for_over_scalar_is_rejected 1 error[E0200]: `for` iterates over a range or an array; use `for i in 0..n` to count. fn main()->i64{ let n=5; for x in n { print(x); } return 0; } +checker_for_over_range_and_array_ok 0 - fn main()->i64{ let a=[1,2]; for x in a { print(x); } for i in 0..3 { print(i); } return 0; } +cli_check_generics_valid 0 - fn identity(x: T) -> T { return x; } fn main() -> void { let a: i32 = 5; print(identity(a)); } +cli_check_generics_arity_mismatch 1 error[E0200]: Function 'pair' expects 2 argument(s) but got 1. fn pair(a: T, b: U) -> (T, U) { return (a, b); } fn main() -> void { let p = pair(1); } +cli_check_const_across_functions 0 - const BASE = 100; const OFF = BASE + 23; fn get() -> i64 { return OFF; } fn main() -> void { print(get()); } +cli_check_invalid_syntax_fails 1 error[E0100]: expected expression, found ';' fn main() -> void { let x = ; } diff --git a/tests/cases/life_clean/clean0.trk b/tests/cases/life_clean/clean0.trk new file mode 100644 index 00000000..96d43c42 --- /dev/null +++ b/tests/cases/life_clean/clean0.trk @@ -0,0 +1,5 @@ +struct Point { x: i64, y: i64 } +struct Outer { p: Point, n: i64 } +fn look(p: &Point) -> i64 { return p.x; } +fn peek(r: &Outer) -> i64 { return look(&r.p) + r.n; } +fn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(peek(&o)); } diff --git a/tests/cases/life_clean/clean1.trk b/tests/cases/life_clean/clean1.trk new file mode 100644 index 00000000..09d6c091 --- /dev/null +++ b/tests/cases/life_clean/clean1.trk @@ -0,0 +1,4 @@ +struct Point { x: i64, y: i64 } +fn eat(v: T) -> i64 { return 1; } +fn peek(r: &Point) -> i64 { return eat(r); } +fn main() -> void { let p = Point { x: 1, y: 2 }; print(peek(&p)); } diff --git a/tests/cases/life_clean/clean2.trk b/tests/cases/life_clean/clean2.trk new file mode 100644 index 00000000..c08b5f09 --- /dev/null +++ b/tests/cases/life_clean/clean2.trk @@ -0,0 +1,5 @@ +struct Point { x: i64, y: i64 } +struct Outer { p: Point, n: i64 } +fn take(p: Point) -> i64 { return p.x; } +fn own(o: Outer) -> i64 { return take(o.p); } +fn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(own(o)); } diff --git a/tests/cases/life_clean/clean3.trk b/tests/cases/life_clean/clean3.trk new file mode 100644 index 00000000..7f9807cc --- /dev/null +++ b/tests/cases/life_clean/clean3.trk @@ -0,0 +1,4 @@ +struct Point { x: i64, y: i64 } +union U { P(&Point), N } +fn wrap(r: &Point) -> U { return U::P(r); } +fn main() -> void { let p = Point { x: 1, y: 2 }; let u = wrap(&p); match u { U::P(r) => print(r.x), U::N => print(0) } } diff --git a/tests/cases/life_clean/clean4.trk b/tests/cases/life_clean/clean4.trk new file mode 100644 index 00000000..0ce4a173 --- /dev/null +++ b/tests/cases/life_clean/clean4.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn pair(r: &Point) -> (&Point, i64) { let b = r; let t = (b, 7); return t; } +fn main() -> void { let p = Point { x: 1, y: 2 }; let t = pair(&p); print(t.1); } diff --git a/tests/cases/life_clean/clean5.trk b/tests/cases/life_clean/clean5.trk new file mode 100644 index 00000000..bac8c487 --- /dev/null +++ b/tests/cases/life_clean/clean5.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn pair() -> (i64, i64) { let p = Point { x: 1, y: 2 }; let t = (&p, 7); let u = t; return (u.1, 8); } +fn main() -> void { let t = pair(); print(t.1); } diff --git a/tests/cases/life_clean/clean6.trk b/tests/cases/life_clean/clean6.trk new file mode 100644 index 00000000..db6fa2fc --- /dev/null +++ b/tests/cases/life_clean/clean6.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn pair() -> (i64, i64) { let p = Point { x: 1, y: 2 }; let b = &p; return (b.x, 7); } +fn main() -> void { let t = pair(); print(t.1); } diff --git a/tests/cases/life_clean/clean7.trk b/tests/cases/life_clean/clean7.trk new file mode 100644 index 00000000..7de6d644 --- /dev/null +++ b/tests/cases/life_clean/clean7.trk @@ -0,0 +1,15 @@ +struct Point { x: i64, y: i64 } +fn id(a: &Point) -> &Point { return a; } +fn main() -> void { + let a = Point { x: 1, y: 2 }; + let c = Point { x: 7, y: 8 }; + let mut r = &a; + let flag: i64 = 1; + if flag > 0 { + let q = &c; + r = q; + } else { + r = id(&c); + } + print(r.x); +} diff --git a/tests/cases/life_clean/clean8.trk b/tests/cases/life_clean/clean8.trk new file mode 100644 index 00000000..3faec0f8 --- /dev/null +++ b/tests/cases/life_clean/clean8.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn two(r: &Point) -> (&Point, &Point) { return (r, r); } +fn main() -> void { let p = Point { x: 1, y: 2 }; let t = two(&p); print(t.0.x); } diff --git a/tests/cases/life_clean/clean9.trk b/tests/cases/life_clean/clean9.trk new file mode 100644 index 00000000..b617472c --- /dev/null +++ b/tests/cases/life_clean/clean9.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn mk(a: Point, b: Point) -> (Point, Point) { return (a, b); } +fn main() -> void { let t = mk(Point { x: 1, y: 2 }, Point { x: 3, y: 4 }); print(t.0.x); } diff --git a/tests/cases/life_errors/00.path b/tests/cases/life_errors/00.path new file mode 100644 index 00000000..21bc846b --- /dev/null +++ b/tests/cases/life_errors/00.path @@ -0,0 +1 @@ +docs/lifecycles/e1_lent_consumed.trk diff --git a/tests/cases/life_errors/00.want b/tests/cases/life_errors/00.want new file mode 100644 index 00000000..ba21a135 --- /dev/null +++ b/tests/cases/life_errors/00.want @@ -0,0 +1 @@ +error[E0211]: 'take' consumes its parameter 'p', but 'r' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'. diff --git a/tests/cases/life_errors/01.path b/tests/cases/life_errors/01.path new file mode 100644 index 00000000..fc32d17d --- /dev/null +++ b/tests/cases/life_errors/01.path @@ -0,0 +1 @@ +docs/lifecycles/e2_escape_tuple.trk diff --git a/tests/cases/life_errors/01.want b/tests/cases/life_errors/01.want new file mode 100644 index 00000000..6adf9964 --- /dev/null +++ b/tests/cases/life_errors/01.want @@ -0,0 +1 @@ +error[E0212]: local 'p' escapes 'pair' inside the returned tuple (element 0); it dies when 'pair' returns. diff --git a/tests/cases/life_errors/02.path b/tests/cases/life_errors/02.path new file mode 100644 index 00000000..be6de320 --- /dev/null +++ b/tests/cases/life_errors/02.path @@ -0,0 +1 @@ +docs/lifecycles/e3_escape_struct.trk diff --git a/tests/cases/life_errors/02.want b/tests/cases/life_errors/02.want new file mode 100644 index 00000000..7bcb0280 --- /dev/null +++ b/tests/cases/life_errors/02.want @@ -0,0 +1 @@ +error[E0212]: local 'p' escapes 'make' through field 'Holder.p'; it dies when 'make' returns. diff --git a/tests/cases/life_errors/03.path b/tests/cases/life_errors/03.path new file mode 100644 index 00000000..7d4f9797 --- /dev/null +++ b/tests/cases/life_errors/03.path @@ -0,0 +1 @@ +docs/lifecycles/e4_outlive_block.trk diff --git a/tests/cases/life_errors/03.want b/tests/cases/life_errors/03.want new file mode 100644 index 00000000..df7ae28d --- /dev/null +++ b/tests/cases/life_errors/03.want @@ -0,0 +1 @@ +error[E0213]: 'r' refers to 'b', which ends at the close of this block (line 9); 'r' is used after it at line 14. diff --git a/tests/cases/life_errors/04.path b/tests/cases/life_errors/04.path new file mode 100644 index 00000000..c544e3ca --- /dev/null +++ b/tests/cases/life_errors/04.path @@ -0,0 +1 @@ +docs/lifecycles/e5_end_twice.trk diff --git a/tests/cases/life_errors/04.want b/tests/cases/life_errors/04.want new file mode 100644 index 00000000..16cf8538 --- /dev/null +++ b/tests/cases/life_errors/04.want @@ -0,0 +1 @@ +error[E0214]: 'p' would be ended twice: fields 'Bag.a' and 'Bag.b' both take ownership of the borrowed 'r'. diff --git a/tests/cases/life_errors/05.trk b/tests/cases/life_errors/05.trk new file mode 100644 index 00000000..59dc5d9d --- /dev/null +++ b/tests/cases/life_errors/05.trk @@ -0,0 +1,8 @@ +fn eatb(s: Str) -> bool { return true; } +fn f(k: i64) -> i64 { + let s = str_concat("a", "b"); + match k { 1 if eatb(s) => return 1, _ => print(0), } + print(s); + return 0; +} +fn main() -> void { print(f(1)); } diff --git a/tests/cases/life_errors/05.want b/tests/cases/life_errors/05.want new file mode 100644 index 00000000..cbc333f2 --- /dev/null +++ b/tests/cases/life_errors/05.want @@ -0,0 +1 @@ +error[E0200]: Resource 's' is spent in some match arms but not in others. diff --git a/tests/cases/life_errors/06.trk b/tests/cases/life_errors/06.trk new file mode 100644 index 00000000..65029914 --- /dev/null +++ b/tests/cases/life_errors/06.trk @@ -0,0 +1,7 @@ +struct Point { x: i64, y: i64 } +fn take(p: Point) -> i64 { return p.x; } +fn peek(r: &Point) -> i64 { + let q = r; + return take(q); +} +fn main() -> void { let p = Point { x: 1, y: 2 }; print(peek(&p)); } diff --git a/tests/cases/life_errors/06.want b/tests/cases/life_errors/06.want new file mode 100644 index 00000000..ba21a135 --- /dev/null +++ b/tests/cases/life_errors/06.want @@ -0,0 +1 @@ +error[E0211]: 'take' consumes its parameter 'p', but 'r' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'. diff --git a/tests/cases/life_errors/07.trk b/tests/cases/life_errors/07.trk new file mode 100644 index 00000000..7bb10a0c --- /dev/null +++ b/tests/cases/life_errors/07.trk @@ -0,0 +1,5 @@ +struct Point { x: i64, y: i64 } +struct Outer { p: Point, n: i64 } +fn take(p: Point) -> i64 { return p.x; } +fn peek(r: &Outer) -> i64 { return take(r.p); } +fn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(peek(&o)); } diff --git a/tests/cases/life_errors/07.want b/tests/cases/life_errors/07.want new file mode 100644 index 00000000..e4f77609 --- /dev/null +++ b/tests/cases/life_errors/07.want @@ -0,0 +1 @@ +error[E0211]: 'take' consumes its parameter 'p', but 'r.p' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'. diff --git a/tests/cases/life_errors/08.trk b/tests/cases/life_errors/08.trk new file mode 100644 index 00000000..e09ea327 --- /dev/null +++ b/tests/cases/life_errors/08.trk @@ -0,0 +1,4 @@ +struct Point { x: i64, y: i64 } +fn take(p: Point) -> i64 { return p.x; } +fn peek(r: &Point) -> i64 { return take(*r); } +fn main() -> void { let p = Point { x: 1, y: 2 }; print(peek(&p)); } diff --git a/tests/cases/life_errors/08.want b/tests/cases/life_errors/08.want new file mode 100644 index 00000000..7e83304f --- /dev/null +++ b/tests/cases/life_errors/08.want @@ -0,0 +1 @@ +error[E0211]: 'take' consumes its parameter 'p', but '*r' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'. diff --git a/tests/cases/life_errors/09.trk b/tests/cases/life_errors/09.trk new file mode 100644 index 00000000..9bff089d --- /dev/null +++ b/tests/cases/life_errors/09.trk @@ -0,0 +1,5 @@ +struct Point { x: i64, y: i64 } +struct Outer { p: Point, n: i64 } +fn eat(v: T) -> i64 { return 1; } +fn peek(r: &Outer) -> i64 { return eat(r.p); } +fn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(peek(&o)); } diff --git a/tests/cases/life_errors/09.want b/tests/cases/life_errors/09.want new file mode 100644 index 00000000..3f67b9b9 --- /dev/null +++ b/tests/cases/life_errors/09.want @@ -0,0 +1 @@ +error[E0211]: 'eat' consumes its parameter 'v', but 'r.p' is only lent to 'peek'. Pass '&' and make 'v: &T', or take ownership in 'peek'. diff --git a/tests/cases/life_errors/10.trk b/tests/cases/life_errors/10.trk new file mode 100644 index 00000000..20190746 --- /dev/null +++ b/tests/cases/life_errors/10.trk @@ -0,0 +1,4 @@ +struct Point { x: i64, y: i64 } +union U { P(&Point), N } +fn mk() -> U { let p = Point { x: 1, y: 2 }; return U::P(&p); } +fn main() -> void { let u = mk(); match u { U::P(r) => print(r.x), U::N => print(0) } } diff --git a/tests/cases/life_errors/10.want b/tests/cases/life_errors/10.want new file mode 100644 index 00000000..8db51884 --- /dev/null +++ b/tests/cases/life_errors/10.want @@ -0,0 +1 @@ +error[E0212]: local 'p' escapes 'mk' inside the returned payload of 'U::P'; it dies when 'mk' returns. diff --git a/tests/cases/life_errors/11.trk b/tests/cases/life_errors/11.trk new file mode 100644 index 00000000..997f9056 --- /dev/null +++ b/tests/cases/life_errors/11.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn pair() -> (&Point, i64) { let p = Point { x: 1, y: 2 }; let b = &p; return (b, 7); } +fn main() -> void { let t = pair(); print(t.1); } diff --git a/tests/cases/life_errors/11.want b/tests/cases/life_errors/11.want new file mode 100644 index 00000000..e3a3a789 --- /dev/null +++ b/tests/cases/life_errors/11.want @@ -0,0 +1 @@ +error[E0212]: local 'p' escapes 'pair' inside the returned tuple (element 0), through 'b'; it dies when 'pair' returns. diff --git a/tests/cases/life_errors/12.trk b/tests/cases/life_errors/12.trk new file mode 100644 index 00000000..2187d031 --- /dev/null +++ b/tests/cases/life_errors/12.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn pair() -> (&Point, i64) { let p = Point { x: 1, y: 2 }; let t = (&p, 7); let u = t; return u; } +fn main() -> void { let t = pair(); print(t.1); } diff --git a/tests/cases/life_errors/12.want b/tests/cases/life_errors/12.want new file mode 100644 index 00000000..926a8088 --- /dev/null +++ b/tests/cases/life_errors/12.want @@ -0,0 +1 @@ +error[E0212]: local 'p' escapes 'pair' through 'u'; it dies when 'pair' returns. diff --git a/tests/cases/life_errors/13.trk b/tests/cases/life_errors/13.trk new file mode 100644 index 00000000..3e123760 --- /dev/null +++ b/tests/cases/life_errors/13.trk @@ -0,0 +1,15 @@ +struct Point { x: i64, y: i64 } +fn id(a: &Point) -> &Point { return a; } +fn main() -> void { + let a = Point { x: 1, y: 2 }; + let mut r = &a; + let flag: i64 = 1; + if flag > 0 { + let b = Point { x: 3, y: 4 }; + r = id(&b); + } else { + let b = Point { x: 5, y: 6 }; + r = id(&b); + } + print(r.x); +} diff --git a/tests/cases/life_errors/13.want b/tests/cases/life_errors/13.want new file mode 100644 index 00000000..df7ae28d --- /dev/null +++ b/tests/cases/life_errors/13.want @@ -0,0 +1 @@ +error[E0213]: 'r' refers to 'b', which ends at the close of this block (line 9); 'r' is used after it at line 14. diff --git a/tests/cases/life_errors/14.trk b/tests/cases/life_errors/14.trk new file mode 100644 index 00000000..e5704b17 --- /dev/null +++ b/tests/cases/life_errors/14.trk @@ -0,0 +1,15 @@ +struct Point { x: i64, y: i64 } +fn main() -> void { + let a = Point { x: 1, y: 2 }; + let mut r = &a; + let flag: i64 = 1; + if flag > 0 { + let b = Point { x: 3, y: 4 }; + let q = &b; + r = q; + } else { + let b = Point { x: 5, y: 6 }; + r = &b; + } + print(r.x); +} diff --git a/tests/cases/life_errors/14.want b/tests/cases/life_errors/14.want new file mode 100644 index 00000000..df7ae28d --- /dev/null +++ b/tests/cases/life_errors/14.want @@ -0,0 +1 @@ +error[E0213]: 'r' refers to 'b', which ends at the close of this block (line 9); 'r' is used after it at line 14. diff --git a/tests/cases/life_errors/15.trk b/tests/cases/life_errors/15.trk new file mode 100644 index 00000000..2aa268f4 --- /dev/null +++ b/tests/cases/life_errors/15.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn dup(r: &Point) -> (Point, Point) { return (r, r); } +fn main() -> void { let p = Point { x: 1, y: 2 }; let t = dup(&p); print(t.0.x); } diff --git a/tests/cases/life_errors/15.want b/tests/cases/life_errors/15.want new file mode 100644 index 00000000..1ddb0b1c --- /dev/null +++ b/tests/cases/life_errors/15.want @@ -0,0 +1 @@ +error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'. diff --git a/tests/cases/life_errors/16.trk b/tests/cases/life_errors/16.trk new file mode 100644 index 00000000..78a41e04 --- /dev/null +++ b/tests/cases/life_errors/16.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn dup(r: &Point) -> i64 { let t: (Point, Point) = (r, r); return t.0.x; } +fn main() -> void { let p = Point { x: 1, y: 2 }; print(dup(&p)); } diff --git a/tests/cases/life_errors/16.want b/tests/cases/life_errors/16.want new file mode 100644 index 00000000..1ddb0b1c --- /dev/null +++ b/tests/cases/life_errors/16.want @@ -0,0 +1 @@ +error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'. diff --git a/tests/cases/life_errors/17.trk b/tests/cases/life_errors/17.trk new file mode 100644 index 00000000..8ea9aba8 --- /dev/null +++ b/tests/cases/life_errors/17.trk @@ -0,0 +1,4 @@ +struct Point { x: i64, y: i64 } +struct Bag { t: (Point, Point) } +fn mk(r: &Point) -> Bag { return Bag { t: (r, r) }; } +fn main() -> void { let p = Point { x: 1, y: 2 }; let b = mk(&p); print(b.t.0.x); } diff --git a/tests/cases/life_errors/17.want b/tests/cases/life_errors/17.want new file mode 100644 index 00000000..1ddb0b1c --- /dev/null +++ b/tests/cases/life_errors/17.want @@ -0,0 +1 @@ +error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'. diff --git a/tests/cases/life_errors/18.trk b/tests/cases/life_errors/18.trk new file mode 100644 index 00000000..9b04ab45 --- /dev/null +++ b/tests/cases/life_errors/18.trk @@ -0,0 +1,3 @@ +struct Point { x: i64, y: i64 } +fn eat(t: (Point, Point)) -> i64 { return 1; } +fn main() -> void { let p = Point { x: 1, y: 2 }; let r = &p; print(eat((r, r))); } diff --git a/tests/cases/life_errors/18.want b/tests/cases/life_errors/18.want new file mode 100644 index 00000000..1ddb0b1c --- /dev/null +++ b/tests/cases/life_errors/18.want @@ -0,0 +1 @@ +error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'. diff --git a/tests/cases/life_warn_clean/clean0.trk b/tests/cases/life_warn_clean/clean0.trk new file mode 100644 index 00000000..ad4abfed --- /dev/null +++ b/tests/cases/life_warn_clean/clean0.trk @@ -0,0 +1,2 @@ +struct P { x: i64, y: i64 } +fn main() -> void { let mut p = P { x: 1, y: 2 }; p.y = 9; print(p.y); } diff --git a/tests/cases/life_warn_clean/clean1.trk b/tests/cases/life_warn_clean/clean1.trk new file mode 100644 index 00000000..ca87722d --- /dev/null +++ b/tests/cases/life_warn_clean/clean1.trk @@ -0,0 +1,3 @@ +struct C { n: i64 } +fn bump(c: &C) -> i64 { with c -> l { l.n = l.n + 1; } return 0; } +fn main() -> void { let c = C { n: 0 }; bump(&c); print(c.n); } diff --git a/tests/cases/life_warn_clean/clean2.trk b/tests/cases/life_warn_clean/clean2.trk new file mode 100644 index 00000000..d03f55c2 --- /dev/null +++ b/tests/cases/life_warn_clean/clean2.trk @@ -0,0 +1,3 @@ +struct V { x: i64 } +fn mk(a: &V) -> V { return V { x: a.x }; } +fn main() -> void { let a = V { x: 1 }; let b = mk(&a); print(b.x); } diff --git a/tests/cases/life_warn_clean/clean3.trk b/tests/cases/life_warn_clean/clean3.trk new file mode 100644 index 00000000..ad40f2d4 --- /dev/null +++ b/tests/cases/life_warn_clean/clean3.trk @@ -0,0 +1,4 @@ +struct P { x: i64 } +fn get(p: &P) -> i64 { return p.x; } +fn eat(p: P) -> P { return p; } +fn main() -> void { let p = P { x: 1 }; print(get(&p)); let q = eat(p); print(q.x); } diff --git a/tests/cases/life_warn_clean/clean4.trk b/tests/cases/life_warn_clean/clean4.trk new file mode 100644 index 00000000..0bd671ed --- /dev/null +++ b/tests/cases/life_warn_clean/clean4.trk @@ -0,0 +1,2 @@ +struct P { x: i64 } +fn main() -> void { let mut p = P { x: 0 }; let mut i = 0; while i < 3 { print(p.x); p.x = i; i = i + 1; } } diff --git a/tests/cases/life_warn_clean/clean5.trk b/tests/cases/life_warn_clean/clean5.trk new file mode 100644 index 00000000..e6bdc438 --- /dev/null +++ b/tests/cases/life_warn_clean/clean5.trk @@ -0,0 +1,3 @@ +struct V { x: i64 } +fn show(a: &V) -> V { print(a.x); return V { x: a.x }; } +fn main() -> void { let a = V { x: 1 }; show(&a); } diff --git a/tests/cases/run_outputs/const_forward_reference.out b/tests/cases/run_outputs/const_forward_reference.out new file mode 100644 index 00000000..2d196b57 --- /dev/null +++ b/tests/cases/run_outputs/const_forward_reference.out @@ -0,0 +1,3 @@ +6 +1 +hi diff --git a/tests/cases/run_outputs/const_forward_reference.trk b/tests/cases/run_outputs/const_forward_reference.trk new file mode 100644 index 00000000..ed8b8a30 --- /dev/null +++ b/tests/cases/run_outputs/const_forward_reference.trk @@ -0,0 +1 @@ +const B = A * 2; const A = 3; const C = 5 > 2; const S = "hi"; fn main() -> void { print(B); print(C); print(S); } \ No newline at end of file diff --git a/tests/cases/run_outputs/match_in_loop_resets_each_time.out b/tests/cases/run_outputs/match_in_loop_resets_each_time.out new file mode 100644 index 00000000..17a2ee5c --- /dev/null +++ b/tests/cases/run_outputs/match_in_loop_resets_each_time.out @@ -0,0 +1,3 @@ +10 +1 +2 diff --git a/tests/cases/run_outputs/match_in_loop_resets_each_time.trk b/tests/cases/run_outputs/match_in_loop_resets_each_time.trk new file mode 100644 index 00000000..ce3eb72f --- /dev/null +++ b/tests/cases/run_outputs/match_in_loop_resets_each_time.trk @@ -0,0 +1 @@ +fn main() -> void { for i in 0..3 { match i { 0 => print(10), _ => print(i), } } } \ No newline at end of file diff --git a/tests/cases/run_outputs/stack_tuple_destructured_and_matched.out b/tests/cases/run_outputs/stack_tuple_destructured_and_matched.out new file mode 100644 index 00000000..c75acbe2 --- /dev/null +++ b/tests/cases/run_outputs/stack_tuple_destructured_and_matched.out @@ -0,0 +1 @@ +127 diff --git a/tests/cases/run_outputs/stack_tuple_destructured_and_matched.trk b/tests/cases/run_outputs/stack_tuple_destructured_and_matched.trk new file mode 100644 index 00000000..3cf616f2 --- /dev/null +++ b/tests/cases/run_outputs/stack_tuple_destructured_and_matched.trk @@ -0,0 +1 @@ +fn main() -> void { let mut s = 0; for i in 0..4 { let t = (i, i * 2); let u = (i, 1); let (a, b) = t; match u { (0, _) => s = s + 100, (x, y) => s = s + x + y, } s = s + a + b; } print(s); } \ No newline at end of file diff --git a/tests/cases/run_outputs/stack_tuple_reassigned_from_itself.out b/tests/cases/run_outputs/stack_tuple_reassigned_from_itself.out new file mode 100644 index 00000000..2050fde7 --- /dev/null +++ b/tests/cases/run_outputs/stack_tuple_reassigned_from_itself.out @@ -0,0 +1,2 @@ +5 +8 diff --git a/tests/cases/run_outputs/stack_tuple_reassigned_from_itself.trk b/tests/cases/run_outputs/stack_tuple_reassigned_from_itself.trk new file mode 100644 index 00000000..db8515b0 --- /dev/null +++ b/tests/cases/run_outputs/stack_tuple_reassigned_from_itself.trk @@ -0,0 +1 @@ +fn main() -> void { let mut p = (1, 2); let mut i = 0; while i < 3 { p = (p.1, p.0 + p.1); i = i + 1; } print(p.0); print(p.1); } \ No newline at end of file diff --git a/tests/cases/run_outputs/tuple_copied_out_of_loop_escapes.out b/tests/cases/run_outputs/tuple_copied_out_of_loop_escapes.out new file mode 100644 index 00000000..1191247b --- /dev/null +++ b/tests/cases/run_outputs/tuple_copied_out_of_loop_escapes.out @@ -0,0 +1,2 @@ +1 +2 diff --git a/tests/cases/run_outputs/tuple_copied_out_of_loop_escapes.trk b/tests/cases/run_outputs/tuple_copied_out_of_loop_escapes.trk new file mode 100644 index 00000000..067bfc79 --- /dev/null +++ b/tests/cases/run_outputs/tuple_copied_out_of_loop_escapes.trk @@ -0,0 +1 @@ +fn main() -> void { let mut keep = (0, 0); for i in 0..3 { let t = (i, i + 1); if i == 1 { keep = t; } else { let (a, b) = t; } } print(keep.0); print(keep.1); } \ No newline at end of file diff --git a/tests/cases/run_outputs/tuple_in_returned_array.out b/tests/cases/run_outputs/tuple_in_returned_array.out new file mode 100644 index 00000000..bb342772 --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_array.out @@ -0,0 +1,2 @@ +200 +5 diff --git a/tests/cases/run_outputs/tuple_in_returned_array.trk b/tests/cases/run_outputs/tuple_in_returned_array.trk new file mode 100644 index 00000000..e24de708 --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_array.trk @@ -0,0 +1 @@ +fn mk(n: i64) -> [](i64, i64) { return [(n, n + 1)]; } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let a = mk(4); print(clobber(100)); let t = a[0]; print(t.1); } \ No newline at end of file diff --git a/tests/cases/run_outputs/tuple_in_returned_struct.out b/tests/cases/run_outputs/tuple_in_returned_struct.out new file mode 100644 index 00000000..7c5b873e --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_struct.out @@ -0,0 +1,2 @@ +200 +8 diff --git a/tests/cases/run_outputs/tuple_in_returned_struct.trk b/tests/cases/run_outputs/tuple_in_returned_struct.trk new file mode 100644 index 00000000..afdf8618 --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_struct.trk @@ -0,0 +1 @@ +struct H { t: (i64, i64) } fn mk(n: i64) -> H { return H { t: (n, n + 1) }; } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let h = mk(7); print(clobber(100)); let t = h.t; print(t.1); } \ No newline at end of file diff --git a/tests/cases/run_outputs/tuple_in_returned_tuple.out b/tests/cases/run_outputs/tuple_in_returned_tuple.out new file mode 100644 index 00000000..918903ba --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_tuple.out @@ -0,0 +1,2 @@ +200 +6 diff --git a/tests/cases/run_outputs/tuple_in_returned_tuple.trk b/tests/cases/run_outputs/tuple_in_returned_tuple.trk new file mode 100644 index 00000000..04dea941 --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_tuple.trk @@ -0,0 +1 @@ +fn mk(n: i64) -> ((i64, i64), i64) { let inner = (n, n * 2); return (inner, 9); } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let t = mk(3); print(clobber(100)); let i = t.0; print(i.1); } \ No newline at end of file diff --git a/tests/cases/run_outputs/tuple_in_returned_union.out b/tests/cases/run_outputs/tuple_in_returned_union.out new file mode 100644 index 00000000..918903ba --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_union.out @@ -0,0 +1,2 @@ +200 +6 diff --git a/tests/cases/run_outputs/tuple_in_returned_union.trk b/tests/cases/run_outputs/tuple_in_returned_union.trk new file mode 100644 index 00000000..3d776fef --- /dev/null +++ b/tests/cases/run_outputs/tuple_in_returned_union.trk @@ -0,0 +1 @@ +union U { P((i64, i64)), N } fn mk(n: i64) -> U { return U::P((n, n + 5)); } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let u = mk(1); print(clobber(100)); match u { U::P(t) => print(t.1), U::N => print(0) } } \ No newline at end of file diff --git a/tests/cases/run_outputs/tuple_literal_in_loop.out b/tests/cases/run_outputs/tuple_literal_in_loop.out new file mode 100644 index 00000000..b2f1f1e5 --- /dev/null +++ b/tests/cases/run_outputs/tuple_literal_in_loop.out @@ -0,0 +1,2 @@ +0 +20 diff --git a/tests/cases/run_outputs/tuple_literal_in_loop.trk b/tests/cases/run_outputs/tuple_literal_in_loop.trk new file mode 100644 index 00000000..5afbad9f --- /dev/null +++ b/tests/cases/run_outputs/tuple_literal_in_loop.trk @@ -0,0 +1 @@ +fn main() -> void { let mut a = [(0, 0), (0, 0), (0, 0)]; for i in 0..3 { a[i] = (i, i * 10); } print(a[0].1); print(a[2].1); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/aborting_branch_skips_merge.trk b/tests/cases/trackc_verdicts/accept/aborting_branch_skips_merge.trk new file mode 100644 index 00000000..a30c4d47 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/aborting_branch_skips_merge.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); let c = true; if c { eat(s); } else { abort("no"); } print(1); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_dup_of_copy_type.trk b/tests/cases/trackc_verdicts/accept/generic_dup_of_copy_type.trk new file mode 100644 index 00000000..a05dbdab --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_dup_of_copy_type.trk @@ -0,0 +1 @@ +fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { let t = dup(3); print(t.0); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_max_of_copy_type.trk b/tests/cases/trackc_verdicts/accept/generic_max_of_copy_type.trk new file mode 100644 index 00000000..561965e9 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_max_of_copy_type.trk @@ -0,0 +1 @@ +fn mx(a: T, b: T) -> T { if a > b { return a; } return b; } fn main() -> void { print(mx(3, 9)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_max_of_linear_type.trk b/tests/cases/trackc_verdicts/accept/generic_max_of_linear_type.trk new file mode 100644 index 00000000..e0897e06 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_max_of_linear_type.trk @@ -0,0 +1 @@ +fn mx(a: T, b: T) -> T { if a > b { return a; } return b; } fn main() -> void { let s = mx(str_concat("a", "b"), str_concat("c", "d")); print(s); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_nested_instantiation_copy.trk b/tests/cases/trackc_verdicts/accept/generic_nested_instantiation_copy.trk new file mode 100644 index 00000000..24a9b886 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_nested_instantiation_copy.trk @@ -0,0 +1 @@ +fn dup(x: T) -> (T, T) { return (x, x); } fn wrap(y: U) -> (U, U) { return dup(y); } fn main() -> void { let t = wrap(7); print(t.1); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_param_used_once.trk b/tests/cases/trackc_verdicts/accept/generic_param_used_once.trk new file mode 100644 index 00000000..868c8a8c --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_param_used_once.trk @@ -0,0 +1 @@ +fn id(x: T) -> T { return x; } fn main() -> void { let s = id(str_concat("a", "b")); print(s); print(id(3)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_pick_with_early_return.trk b/tests/cases/trackc_verdicts/accept/generic_pick_with_early_return.trk new file mode 100644 index 00000000..51c2fc57 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_pick_with_early_return.trk @@ -0,0 +1 @@ +fn pick(c: bool, a: T, b: T) -> T { if c { return a; } return b; } fn main() -> void { let x: i64 = 1; let y: i64 = 2; print(pick(true, x, y)); print(x + y); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/generic_twice_of_copy_type.trk b/tests/cases/trackc_verdicts/accept/generic_twice_of_copy_type.trk new file mode 100644 index 00000000..f5c74f12 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/generic_twice_of_copy_type.trk @@ -0,0 +1 @@ +fn twice(x: T) -> T { let a = x; let b = x; return b; } fn main() -> void { let n: i64 = 4; print(twice(n)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/guard_read_only_then_use.trk b/tests/cases/trackc_verdicts/accept/guard_read_only_then_use.trk new file mode 100644 index 00000000..6a74f434 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/guard_read_only_then_use.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { 1 if readb(&s) => return 1, _ => return eatr(s), } } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/guard_spend_disjoint_enum_variant.trk b/tests/cases/trackc_verdicts/accept/guard_spend_disjoint_enum_variant.trk new file mode 100644 index 00000000..0abc8dab --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/guard_spend_disjoint_enum_variant.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } enum C { R, G, B } fn f(k: C) -> i64 { let s = str_concat("a", "b"); match k { C::R if eatb(s) => return 1, C::G => return eatr(s), _ => return 0, } } fn main() -> void { print(f(C::G)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/guard_spend_irrefutable_always_spent.trk b/tests/cases/trackc_verdicts/accept/guard_spend_irrefutable_always_spent.trk new file mode 100644 index 00000000..f9240891 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/guard_spend_irrefutable_always_spent.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { x if eatb(s) => return 1, _ => print(0), } return 0; } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/guard_spend_skips_disjoint_literal_arm.trk b/tests/cases/trackc_verdicts/accept/guard_spend_skips_disjoint_literal_arm.trk new file mode 100644 index 00000000..0dd03408 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/guard_spend_skips_disjoint_literal_arm.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { 1 if eatb(s) => return 1, 2 => return eatr(s), _ => return 0, } } fn main() -> void { print(f(2)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/guard_two_spends_disjoint_arms.trk b/tests/cases/trackc_verdicts/accept/guard_two_spends_disjoint_arms.trk new file mode 100644 index 00000000..74cd859e --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/guard_two_spends_disjoint_arms.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat2(a: Str, b: Str) -> i64 { return 1; } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); let u = str_concat("c", "d"); match k { 1 if eatb(s) => return eatr(u), 2 if eatb(u) => return eatr(s), 3 => return eat2(s, u), _ => return 0, } } fn main() -> void { print(f(3)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/returning_branch_in_loop.trk b/tests/cases/trackc_verdicts/accept/returning_branch_in_loop.trk new file mode 100644 index 00000000..4318193c --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/returning_branch_in_loop.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn f(s: Str) -> i64 { let mut i = 0; while i < 3 { if i == 2 { eat(s); return i; } i = i + 1; } eat(s); return 0; } fn main() -> void { print(f(str_concat("a", "b"))); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/returning_else_branch_skips_merge.trk b/tests/cases/trackc_verdicts/accept/returning_else_branch_skips_merge.trk new file mode 100644 index 00000000..db125ca6 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/returning_else_branch_skips_merge.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn f(s: Str, c: bool) -> i64 { if c { print(1); } else { eat(s); return 0; } eat(s); return 1; } fn main() -> void { print(f(str_concat("a", "b"), true)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/returning_match_arm_skips_merge.trk b/tests/cases/trackc_verdicts/accept/returning_match_arm_skips_merge.trk new file mode 100644 index 00000000..9ed99411 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/returning_match_arm_skips_merge.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn g(s: Str) -> i64 { return 1; } fn f(s: Str, k: i64) -> i64 { match k { 1 => return g(s), _ => print(0), } eat(s); return 0; } fn main() -> void { print(f(str_concat("a", "b"), 1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/returning_then_branch_skips_merge.trk b/tests/cases/trackc_verdicts/accept/returning_then_branch_skips_merge.trk new file mode 100644 index 00000000..a27e6a29 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/returning_then_branch_skips_merge.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn f(s: Str, c: bool) -> i64 { if c { eat(s); return 1; } eat(s); return 0; } fn main() -> void { print(f(str_concat("a", "b"), true)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/accept/right_struct_ref.trk b/tests/cases/trackc_verdicts/accept/right_struct_ref.trk new file mode 100644 index 00000000..715e0058 --- /dev/null +++ b/tests/cases/trackc_verdicts/accept/right_struct_ref.trk @@ -0,0 +1 @@ +struct A { x: i64, y: i64 } fn gx(p: &A) -> i64 { return p.x; } fn main() -> void { let a = A { x: 1, y: 2 }; print(gx(&a)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/arity_builtin.trk b/tests/cases/trackc_verdicts/reject/arity_builtin.trk new file mode 100644 index 00000000..1842ca64 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/arity_builtin.trk @@ -0,0 +1 @@ +fn main() -> void { print(str_concat("a")); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/arity_too_few.trk b/tests/cases/trackc_verdicts/reject/arity_too_few.trk new file mode 100644 index 00000000..f4b54995 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/arity_too_few.trk @@ -0,0 +1 @@ +fn f(a: i64, b: i64) -> i64 { return a + b; } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/arity_too_many.trk b/tests/cases/trackc_verdicts/reject/arity_too_many.trk new file mode 100644 index 00000000..5a3629c7 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/arity_too_many.trk @@ -0,0 +1 @@ +fn f(a: i64) -> i64 { return a; } fn main() -> void { print(f(1, 2)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/const_cycle.trk b/tests/cases/trackc_verdicts/reject/const_cycle.trk new file mode 100644 index 00000000..bcdec8fe --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/const_cycle.trk @@ -0,0 +1 @@ +const A = B; const B = A; fn main() -> void { print(A); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/const_div_by_zero.trk b/tests/cases/trackc_verdicts/reject/const_div_by_zero.trk new file mode 100644 index 00000000..a5583424 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/const_div_by_zero.trk @@ -0,0 +1 @@ +const D = 7 / 0; fn main() -> void { print(D); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/const_mod_by_zero.trk b/tests/cases/trackc_verdicts/reject/const_mod_by_zero.trk new file mode 100644 index 00000000..fb2b2ee6 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/const_mod_by_zero.trk @@ -0,0 +1 @@ +const D = 7 % 0; fn main() -> void { print(D); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/const_not_constant.trk b/tests/cases/trackc_verdicts/reject/const_not_constant.trk new file mode 100644 index 00000000..70762c8c --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/const_not_constant.trk @@ -0,0 +1 @@ +fn f() -> i64 { return 1; } const D = f(); fn main() -> void { print(D); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/consume_in_match_arm.trk b/tests/cases/trackc_verdicts/reject/consume_in_match_arm.trk new file mode 100644 index 00000000..17a02af3 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/consume_in_match_arm.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); let k = 1; match k { 1 => eat(s), _ => print(0), } print(s); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/consume_in_while_cond.trk b/tests/cases/trackc_verdicts/reject/consume_in_while_cond.trk new file mode 100644 index 00000000..2f2c174b --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/consume_in_while_cond.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> bool { return true; } fn main() -> void { let s = str_concat("a", "b"); while eat(s) { print(1); return; } } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/destructure_int.trk b/tests/cases/trackc_verdicts/reject/destructure_int.trk new file mode 100644 index 00000000..306f8fc4 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/destructure_int.trk @@ -0,0 +1 @@ +fn main() -> void { let (a, b) = 1; print(a); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/destructure_too_many.trk b/tests/cases/trackc_verdicts/reject/destructure_too_many.trk new file mode 100644 index 00000000..4b3e7020 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/destructure_too_many.trk @@ -0,0 +1 @@ +fn main() -> void { let t = (1, 2); let (a, b, c) = t; print(c); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/generic_both_instantiations_checked.trk b/tests/cases/trackc_verdicts/reject/generic_both_instantiations_checked.trk new file mode 100644 index 00000000..dede2f2c --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/generic_both_instantiations_checked.trk @@ -0,0 +1 @@ +fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { let t = dup(3); print(t.0); let u = dup(str_concat("a", "b")); print(u.0); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/generic_nested_instantiation_linear.trk b/tests/cases/trackc_verdicts/reject/generic_nested_instantiation_linear.trk new file mode 100644 index 00000000..e84d5fc6 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/generic_nested_instantiation_linear.trk @@ -0,0 +1 @@ +fn dup(x: T) -> (T, T) { return (x, x); } fn wrap(y: U) -> (U, U) { return dup(y); } fn main() -> void { let t = wrap(str_concat("a", "b")); print(t.0); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/generic_param_is_linear.trk b/tests/cases/trackc_verdicts/reject/generic_param_is_linear.trk new file mode 100644 index 00000000..69bf6efa --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/generic_param_is_linear.trk @@ -0,0 +1 @@ +fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { let t = dup(str_concat("a", "b")); print(t.0); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/generic_twice_of_linear_type.trk b/tests/cases/trackc_verdicts/reject/generic_twice_of_linear_type.trk new file mode 100644 index 00000000..86303d14 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/generic_twice_of_linear_type.trk @@ -0,0 +1 @@ +fn twice(x: T) -> T { let a = x; let b = x; return b; } fn main() -> void { let s = str_concat("a", "b"); print(twice(s)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_consumes_on_diverging_arm.trk b/tests/cases/trackc_verdicts/reject/guard_consumes_on_diverging_arm.trk new file mode 100644 index 00000000..b0d4c0ab --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_consumes_on_diverging_arm.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { 1 if eatb(s) => return 1, _ => print(0), } print(s); return 0; } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_spend_binding_then_use.trk b/tests/cases/trackc_verdicts/reject/guard_spend_binding_then_use.trk new file mode 100644 index 00000000..775d8dae --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_spend_binding_then_use.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { x if eatb(s) => return x, y => return eatr(s), } } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_spend_inconsistent_after_match.trk b/tests/cases/trackc_verdicts/reject/guard_spend_inconsistent_after_match.trk new file mode 100644 index 00000000..a2d3ed61 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_spend_inconsistent_after_match.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { 1 if eatb(s) => print(1), _ => print(0), } return 0; } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_spend_irrefutable_use_after.trk b/tests/cases/trackc_verdicts/reject/guard_spend_irrefutable_use_after.trk new file mode 100644 index 00000000..3a6e2351 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_spend_irrefutable_use_after.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { x if eatb(s) => return 1, _ => print(0), } print(s); return 0; } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_spend_same_enum_variant.trk b/tests/cases/trackc_verdicts/reject/guard_spend_same_enum_variant.trk new file mode 100644 index 00000000..d3f20799 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_spend_same_enum_variant.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } enum C { R, G, B } fn f(k: C) -> i64 { let s = str_concat("a", "b"); match k { C::R if eatb(s) => return 1, C::R => return eatr(s), _ => return 0, } } fn main() -> void { print(f(C::R)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_spend_wild_arm_use_after_free.trk b/tests/cases/trackc_verdicts/reject/guard_spend_wild_arm_use_after_free.trk new file mode 100644 index 00000000..22ac23a6 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_spend_wild_arm_use_after_free.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); match k { 1 if eatb(s) => return 1, _ => return eatr(s), } } fn main() -> void { print(f(1)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/guard_two_spends_wild_uses_one.trk b/tests/cases/trackc_verdicts/reject/guard_two_spends_wild_uses_one.trk new file mode 100644 index 00000000..c9d36491 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/guard_two_spends_wild_uses_one.trk @@ -0,0 +1 @@ +fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat2(a: Str, b: Str) -> i64 { return 1; } fn f(k: i64) -> i64 { let s = str_concat("a", "b"); let u = str_concat("c", "d"); match k { 1 if eatb(s) => return eatr(u), 2 if eatb(u) => return eatr(s), _ => return eatr(s), } } fn main() -> void { print(f(5)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/index_on_int.trk b/tests/cases/trackc_verdicts/reject/index_on_int.trk new file mode 100644 index 00000000..418cf1ed --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/index_on_int.trk @@ -0,0 +1 @@ +fn main() -> void { let x = 1; print(x[0]); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/returning_else_keeps_then_state.trk b/tests/cases/trackc_verdicts/reject/returning_else_keeps_then_state.trk new file mode 100644 index 00000000..219ece2b --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/returning_else_keeps_then_state.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn f(s: Str, c: bool) -> i64 { if c { eat(s); } else { return 0; } eat(s); return 1; } fn main() -> void { print(f(str_concat("a", "b"), true)); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/shadow_in_else_hides_consume.trk b/tests/cases/trackc_verdicts/reject/shadow_in_else_hides_consume.trk new file mode 100644 index 00000000..fac51201 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/shadow_in_else_hides_consume.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); if true { eat(s); } else { let s = 1; } } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/tuple_index_on_int.trk b/tests/cases/trackc_verdicts/reject/tuple_index_on_int.trk new file mode 100644 index 00000000..eae1c7b4 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/tuple_index_on_int.trk @@ -0,0 +1 @@ +fn main() -> void { let x = 1; print(x.0); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/unused_generic_checked_linear.trk b/tests/cases/trackc_verdicts/reject/unused_generic_checked_linear.trk new file mode 100644 index 00000000..0df58214 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/unused_generic_checked_linear.trk @@ -0,0 +1 @@ +fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { print(1); } \ No newline at end of file diff --git a/tests/cases/trackc_verdicts/reject/wrong_struct_ref.trk b/tests/cases/trackc_verdicts/reject/wrong_struct_ref.trk new file mode 100644 index 00000000..8c7d7560 --- /dev/null +++ b/tests/cases/trackc_verdicts/reject/wrong_struct_ref.trk @@ -0,0 +1 @@ +struct A { x: i64, y: i64 } struct B { y: i64, z: i64, x: i64 } fn gx(p: &A) -> i64 { return p.x; } fn main() -> void { let b = B { y: 20, z: 30, x: 10 }; print(gx(&b)); } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/array_index_update.trk b/tests/cases/verdicts/accept/array_index_update.trk new file mode 100644 index 00000000..55790edc --- /dev/null +++ b/tests/cases/verdicts/accept/array_index_update.trk @@ -0,0 +1 @@ +fn main() -> void { let mut a = [1, 2]; a[1] = 7; print(a[1]); } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/borrow_does_not_move.trk b/tests/cases/verdicts/accept/borrow_does_not_move.trk new file mode 100644 index 00000000..086fadb2 --- /dev/null +++ b/tests/cases/verdicts/accept/borrow_does_not_move.trk @@ -0,0 +1 @@ +fn f(x: &Str) -> i64 { return 0; } fn main() -> void { let s = str_concat("a", "b"); f(&s); print(s); } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/consistent_if.trk b/tests/cases/verdicts/accept/consistent_if.trk new file mode 100644 index 00000000..599cb15c --- /dev/null +++ b/tests/cases/verdicts/accept/consistent_if.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); if true { eat(s); } else { eat(s); } } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/const_before_use.trk b/tests/cases/verdicts/accept/const_before_use.trk new file mode 100644 index 00000000..deea75f2 --- /dev/null +++ b/tests/cases/verdicts/accept/const_before_use.trk @@ -0,0 +1 @@ +fn main() -> void { print(LIMIT); } const LIMIT = 10; \ No newline at end of file diff --git a/tests/cases/verdicts/accept/copy_ints.trk b/tests/cases/verdicts/accept/copy_ints.trk new file mode 100644 index 00000000..466c5cf9 --- /dev/null +++ b/tests/cases/verdicts/accept/copy_ints.trk @@ -0,0 +1 @@ +fn main() -> void { let a: i64 = 1; let b = a; print(a); print(b); } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/lens_field_update.trk b/tests/cases/verdicts/accept/lens_field_update.trk new file mode 100644 index 00000000..82aea3e0 --- /dev/null +++ b/tests/cases/verdicts/accept/lens_field_update.trk @@ -0,0 +1 @@ +struct P { x: i64 } fn main() -> void { let mut p = P { x: 1 }; with p -> l { l.x = 5; } print(p.x); } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/mutable_assign.trk b/tests/cases/verdicts/accept/mutable_assign.trk new file mode 100644 index 00000000..71296bd8 --- /dev/null +++ b/tests/cases/verdicts/accept/mutable_assign.trk @@ -0,0 +1 @@ +fn main() -> void { let mut x = 1; x = 2; print(x); } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/reassign_after_move_in_loop.trk b/tests/cases/verdicts/accept/reassign_after_move_in_loop.trk new file mode 100644 index 00000000..349d55b4 --- /dev/null +++ b/tests/cases/verdicts/accept/reassign_after_move_in_loop.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let mut s = str_concat("a", "b"); let mut i: i64 = 0; while i < 2 { eat(s); s = str_concat("x", "y"); i = i + 1; } } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/return_param_ref.trk b/tests/cases/verdicts/accept/return_param_ref.trk new file mode 100644 index 00000000..bb2e1bc5 --- /dev/null +++ b/tests/cases/verdicts/accept/return_param_ref.trk @@ -0,0 +1 @@ +fn f(x: &i64) -> &i64 { return x; } \ No newline at end of file diff --git a/tests/cases/verdicts/accept/struct_field_update.trk b/tests/cases/verdicts/accept/struct_field_update.trk new file mode 100644 index 00000000..5eeb7284 --- /dev/null +++ b/tests/cases/verdicts/accept/struct_field_update.trk @@ -0,0 +1 @@ +struct P { x: i64 } fn main() -> void { let mut p = P { x: 1 }; p.x = 2; print(p.x); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/array_moved_by_value.trk b/tests/cases/verdicts/reject/array_moved_by_value.trk new file mode 100644 index 00000000..0b8c148a --- /dev/null +++ b/tests/cases/verdicts/reject/array_moved_by_value.trk @@ -0,0 +1 @@ +fn main() -> void { let a = [1, 2]; let n = array_len(a); print(a[0]); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/assign_undeclared.trk b/tests/cases/verdicts/reject/assign_undeclared.trk new file mode 100644 index 00000000..699c5ec1 --- /dev/null +++ b/tests/cases/verdicts/reject/assign_undeclared.trk @@ -0,0 +1 @@ +fn main() -> void { y = 3; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/compile_error_macro.trk b/tests/cases/verdicts/reject/compile_error_macro.trk new file mode 100644 index 00000000..5a683273 --- /dev/null +++ b/tests/cases/verdicts/reject/compile_error_macro.trk @@ -0,0 +1 @@ +fn main() -> void { @compile_error("stop"); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/consume_in_loop.trk b/tests/cases/verdicts/reject/consume_in_loop.trk new file mode 100644 index 00000000..3531e8c5 --- /dev/null +++ b/tests/cases/verdicts/reject/consume_in_loop.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); let mut i: i64 = 0; while i < 3 { eat(s); i = i + 1; } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/forbidden_free.trk b/tests/cases/verdicts/reject/forbidden_free.trk new file mode 100644 index 00000000..ce448d51 --- /dev/null +++ b/tests/cases/verdicts/reject/forbidden_free.trk @@ -0,0 +1 @@ +fn main() -> void { let s = str_concat("a", "b"); str_free(s); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/frozen_by_reference.trk b/tests/cases/verdicts/reject/frozen_by_reference.trk new file mode 100644 index 00000000..66769f42 --- /dev/null +++ b/tests/cases/verdicts/reject/frozen_by_reference.trk @@ -0,0 +1 @@ +fn main() -> void { let s = str_concat("a", "b"); let r = &s; let t = s; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/global_const_spent_in_branch.trk b/tests/cases/verdicts/reject/global_const_spent_in_branch.trk new file mode 100644 index 00000000..0259c509 --- /dev/null +++ b/tests/cases/verdicts/reject/global_const_spent_in_branch.trk @@ -0,0 +1 @@ +const K = "hi"; fn main() -> void { if true { let a = K; } else { } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/if_inside_loop_consumes.trk b/tests/cases/verdicts/reject/if_inside_loop_consumes.trk new file mode 100644 index 00000000..2861ecee --- /dev/null +++ b/tests/cases/verdicts/reject/if_inside_loop_consumes.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); let mut i: i64 = 0; while i < 3 { if i == 1 { eat(s); } else { eat(s); } i = i + 1; } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/immutable_assign.trk b/tests/cases/verdicts/reject/immutable_assign.trk new file mode 100644 index 00000000..0e1c43d8 --- /dev/null +++ b/tests/cases/verdicts/reject/immutable_assign.trk @@ -0,0 +1 @@ +fn main() -> void { let x = 1; x = 2; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/immutable_field_update.trk b/tests/cases/verdicts/reject/immutable_field_update.trk new file mode 100644 index 00000000..b9d69861 --- /dev/null +++ b/tests/cases/verdicts/reject/immutable_field_update.trk @@ -0,0 +1 @@ +struct P { x: i64 } fn main() -> void { let p = P { x: 1 }; p.x = 2; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/inconsistent_if.trk b/tests/cases/verdicts/reject/inconsistent_if.trk new file mode 100644 index 00000000..2854c024 --- /dev/null +++ b/tests/cases/verdicts/reject/inconsistent_if.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); if true { eat(s); } else { } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/lens_cannot_escape.trk b/tests/cases/verdicts/reject/lens_cannot_escape.trk new file mode 100644 index 00000000..2a820b5a --- /dev/null +++ b/tests/cases/verdicts/reject/lens_cannot_escape.trk @@ -0,0 +1 @@ +fn main() -> void { let mut v = vec_init(4); with v -> l { let w = l; } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/lens_locks_target.trk b/tests/cases/verdicts/reject/lens_locks_target.trk new file mode 100644 index 00000000..ba4d82d4 --- /dev/null +++ b/tests/cases/verdicts/reject/lens_locks_target.trk @@ -0,0 +1 @@ +fn main() -> void { let mut v = vec_init(4); with v -> l { let w = v; } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/move_then_use.trk b/tests/cases/verdicts/reject/move_then_use.trk new file mode 100644 index 00000000..ffeeb32c --- /dev/null +++ b/tests/cases/verdicts/reject/move_then_use.trk @@ -0,0 +1 @@ +fn main() -> void { let s = str_concat("a", "b"); let t = s; print(s); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/mut_does_not_leak_across_functions.trk b/tests/cases/verdicts/reject/mut_does_not_leak_across_functions.trk new file mode 100644 index 00000000..5895c0ef --- /dev/null +++ b/tests/cases/verdicts/reject/mut_does_not_leak_across_functions.trk @@ -0,0 +1 @@ +fn a() -> void { let mut x = 1; x = 2; } fn b() -> void { let x = 1; x = 3; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/nested_if_second_resource.trk b/tests/cases/verdicts/reject/nested_if_second_resource.trk new file mode 100644 index 00000000..ae53058e --- /dev/null +++ b/tests/cases/verdicts/reject/nested_if_second_resource.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let a = str_concat("a", "b"); let b = str_concat("a", "b"); if true { eat(b); eat(a); } else { if false { eat(a); } else { eat(a); } } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/return_local_ref.trk b/tests/cases/verdicts/reject/return_local_ref.trk new file mode 100644 index 00000000..e8d20898 --- /dev/null +++ b/tests/cases/verdicts/reject/return_local_ref.trk @@ -0,0 +1 @@ +fn f() -> &i64 { let x = 5; return &x; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/shadow_in_then_keeps_outer.trk b/tests/cases/verdicts/reject/shadow_in_then_keeps_outer.trk new file mode 100644 index 00000000..e632236d --- /dev/null +++ b/tests/cases/verdicts/reject/shadow_in_then_keeps_outer.trk @@ -0,0 +1 @@ +fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat("a", "b"); if true { let s = 1; } else { eat(s); } } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/shadowed_binding_is_immutable.trk b/tests/cases/verdicts/reject/shadowed_binding_is_immutable.trk new file mode 100644 index 00000000..4066f358 --- /dev/null +++ b/tests/cases/verdicts/reject/shadowed_binding_is_immutable.trk @@ -0,0 +1 @@ +fn main() -> void { let mut x = 1; let x = 2; x = 3; } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/tuple_index_bounds.trk b/tests/cases/verdicts/reject/tuple_index_bounds.trk new file mode 100644 index 00000000..0a402eb4 --- /dev/null +++ b/tests/cases/verdicts/reject/tuple_index_bounds.trk @@ -0,0 +1 @@ +fn main() -> void { let t = (1, 2); print(t.2); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/typo_suggestion.trk b/tests/cases/verdicts/reject/typo_suggestion.trk new file mode 100644 index 00000000..344d8903 --- /dev/null +++ b/tests/cases/verdicts/reject/typo_suggestion.trk @@ -0,0 +1 @@ +fn compute() -> i64 { return 1; } fn main() -> void { print(computee()); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/undeclared_use.trk b/tests/cases/verdicts/reject/undeclared_use.trk new file mode 100644 index 00000000..85c9090c --- /dev/null +++ b/tests/cases/verdicts/reject/undeclared_use.trk @@ -0,0 +1 @@ +fn main() -> void { print(nope); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/unknown_field_access.trk b/tests/cases/verdicts/reject/unknown_field_access.trk new file mode 100644 index 00000000..12b4cc97 --- /dev/null +++ b/tests/cases/verdicts/reject/unknown_field_access.trk @@ -0,0 +1 @@ +struct P { x: i64 } fn main() -> void { let p = P { x: 1 }; print(p.q); } \ No newline at end of file diff --git a/tests/cases/verdicts/reject/unknown_struct_field.trk b/tests/cases/verdicts/reject/unknown_struct_field.trk new file mode 100644 index 00000000..26289d5e --- /dev/null +++ b/tests/cases/verdicts/reject/unknown_struct_field.trk @@ -0,0 +1 @@ +struct P { x: i64 } fn main() -> void { let p = P { z: 1 }; } \ No newline at end of file diff --git a/tests/checker_tests.rs b/tests/checker_tests.rs deleted file mode 100644 index 5f63a094..00000000 --- a/tests/checker_tests.rs +++ /dev/null @@ -1,212 +0,0 @@ -use track::compile_source; - -#[test] -fn test_linear_checker_valid_code() { - let source = r#" - fn main() -> void { - let x: i32 = 42; - let y = x; // Copy type i32 - print(x); - print(y); - } - "#; - let res = compile_source(source); - assert!(res.is_ok()); -} - -#[test] -fn test_linear_checker_linear_type_transfer() { - let source = r#" - fn process(v: Vec) -> void { - // v is consumed here - } - - fn main() -> void { - let v: Vec = vec_init(10); - process(v); - } - "#; - let res = compile_source(source); - assert!(res.is_ok()); -} - -#[test] -fn test_linear_checker_use_after_free_error() { - let source = r#" - fn consume(v: Vec) -> void {} - - fn main() -> void { - let v: Vec = vec_init(10); - consume(v); - consume(v); // Use after free - } - "#; - let res = compile_source(source); - assert!(res.is_err()); - let err = res.unwrap_err(); - assert!(err.contains("Use-after-free")); -} - -#[test] -fn test_linear_checker_lens_block_valid_and_locked() { - let source = r#" - fn main() -> void { - let mut u = User { age: 30 }; - with u -> user { - let a = user.age(); - } - print(u); - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Expected lens block valid test to compile, got error: {:?}", - res.err() - ); -} - -#[test] -fn test_linear_checker_lens_block_locked_error() { - let source = r#" - fn use_user(u: User) -> void {} - - fn main() -> void { - let mut u = User { age: 30 }; - with u -> user { - use_user(u); // Error: u is frozen while in lens block - } - } - "#; - let res = compile_source(source); - assert!(res.is_err()); - let err = res.unwrap_err(); - assert!( - err.contains("frozen") - || err.contains("locked") - || err.contains("Active") - || err.contains("Locked"), - "Unexpected error message: {}", - err - ); -} - -#[test] -fn test_linear_checker_borrow_and_escape() { - let source = r#" - fn main() -> void { - let mut v: Vec = vec_init(10); - let ref_v = &mut v; - vec_push(ref_v, 1); - } - "#; - let res = compile_source(source); - assert!(res.is_ok()); -} - -#[test] -fn test_linear_checker_escape_error() { - let source = r#" - fn escape() -> &Vec { - let v: Vec = vec_init(10); - return &v; // Error: reference outlives stack frame - } - "#; - let res = compile_source(source); - assert!(res.is_err()); - let err = res.unwrap_err(); - assert!(err.contains("outlives") || err.contains("Cannot return reference")); -} - -#[test] -fn test_linear_checker_enum_and_union_matching() { - let source = r#" - enum Color { Red, Green, Blue } - union Result { Ok(i32), Err } - - fn main() -> void { - let c = Color::Red; - match c { - Color::Red => print(1), - Color::Green => print(2), - Color::Blue => print(3), - } - - let r = Result::Ok(42); - match r { - Result::Ok(val) => print(val), - Result::Err => print(0), - } - } - "#; - let res = compile_source(source); - assert!(res.is_ok()); -} - -#[test] -fn test_linear_checker_type_alias_and_os_api() { - let source = r#" - type Buffer = []u8; - fn main() -> void { - let count = os_args_count(); - print(count); - let exists = dir_exists("src"); - } - "#; - let res = compile_source(source); - assert!(res.is_ok()); -} - -#[test] -fn test_linear_checker_extended_char_str_path_api() { - let source = r#" - fn main() -> void { - let is_d = char_is_digit(53); - let is_a = char_is_alpha(65); - let u = char_to_upper(97); - let starts = str_starts_with("compiler", "comp"); - let sub = str_substr("hello world", 0, 5); - let base = path_basename("/bin/track"); - let ext = path_ext("main.trk"); - let joined = path_join("src", "lib.rs"); - } - "#; - let res = compile_source(source); - assert!(res.is_ok()); -} - -#[test] -fn test_linear_checker_typo_suggestion() { - let source = r#" - fn main() -> void { - prnt("Hello"); - } - "#; - let res = compile_source(source); - assert!(res.is_err()); - let err = res.err().unwrap(); - assert!( - err.contains("Did you mean 'print'?"), - "Expected typo suggestion 'Did you mean 'print'?', got: {}", - err - ); -} - -/// K3c: `for x in n` over a scalar is E0200 as in trackc, not a segfault. -#[test] -fn test_for_over_scalar_is_rejected() { - let err = compile_source("fn main()->i64{ let n=5; for x in n { print(x); } return 0; }") - .unwrap_err(); - assert!( - err.contains("error[E0200]") && err.contains("`for` iterates over a range or an array"), - "{}", - err - ); - // Ranges and arrays still iterate. - assert!( - compile_source( - "fn main()->i64{ let a=[1,2]; for x in a { print(x); } for i in 0..3 { print(i); } return 0; }" - ) - .is_ok() - ); -} diff --git a/tests/cli_tests.rs b/tests/cli_tests.rs deleted file mode 100644 index 0a06cab7..00000000 --- a/tests/cli_tests.rs +++ /dev/null @@ -1,203 +0,0 @@ -use std::env; -use std::fs; -use std::process::Command; - -fn get_track_binary() -> String { - let target_dir = env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "target".to_string()); - let bin_path = format!("{}/debug/track", target_dir); - if std::path::Path::new(&bin_path).exists() { - return bin_path; - } - // Fallback to cargo run --bin track - "cargo".to_string() -} - -fn run_track_cmd(args: &[&str]) -> std::process::Output { - let bin = get_track_binary(); - if bin == "cargo" { - let mut full_args = vec!["run", "--bin", "track", "--"]; - full_args.extend_from_slice(args); - Command::new("cargo").args(&full_args).output().unwrap() - } else { - Command::new(bin).args(args).output().unwrap() - } -} - -#[test] -fn test_cli_help() { - let output = run_track_cmd(&["--help"]); - assert!(output.status.success() || !output.stderr.is_empty()); - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - let combined = format!("{}{}", stdout, stderr); - assert!(combined.contains("USAGE:") || combined.contains("Track")); -} - -#[test] -fn test_cli_check_command() { - let temp_dir = env::temp_dir().join(format!("track_cli_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let trk_file = temp_dir.join("test.trk"); - fs::write(&trk_file, "fn main() -> void { print(42); }").unwrap(); - - let output = run_track_cmd(&["check", trk_file.to_str().unwrap()]); - assert!(output.status.success()); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!(stdout.contains("Check passed")); - - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_cli_invalid_command() { - let output = run_track_cmd(&["nonexistent_command"]); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("Unknown command")); -} - -#[test] -fn test_cli_version_reports_0_6() { - let out = run_track_cmd(&["--version"]); - let stdout = String::from_utf8_lossy(&out.stdout); - let stderr = String::from_utf8_lossy(&out.stderr); - let combined = format!("{}{}", stdout, stderr); - assert!( - combined.contains("1.0.0"), - "version output missing 1.0.0: {}", - combined - ); -} - -/// K3b: a duplicate fn is a diagnostic matching trackc's, not a codegen panic. -#[test] -fn test_cli_duplicate_function_is_a_diagnostic() { - let td = env::temp_dir().join(format!("track_cli_dupfn_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - let f = td.join("dup.trk"); - fs::write( - &f, - "fn place_root() -> i64 { return 1; }\nfn place_root() -> i64 { return 2; }\nfn main() -> i64 { print(place_root()); return 0; }\n", - ) - .unwrap(); - for mode in ["check", "build"] { - let out = Command::new(env!("CARGO_BIN_EXE_track")) - .args([mode, f.to_str().unwrap()]) - .current_dir(&td) - .output() - .unwrap(); - let err = String::from_utf8_lossy(&out.stderr); - assert_eq!(out.status.code(), Some(1), "{}: {}", mode, err); - assert!( - err.contains("error[E0201]: duplicate definition of function 'place_root'") - && !err.contains("panicked"), - "{}: {}", - mode, - err - ); - } - let _ = fs::remove_dir_all(&td); -} - -/// K3c: a fn that clashes with one from an imported module is E0201 too. -#[test] -fn test_cli_duplicate_function_through_import_is_a_diagnostic() { - let td = env::temp_dir().join(format!("track_cli_dupimp_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - fs::write( - td.join("other.trk"), - "fn place_root() -> i64 { return 1; }\n", - ) - .unwrap(); - let f = td.join("main.trk"); - fs::write( - &f, - "import \"other\";\nfn place_root() -> i64 { return 2; }\nfn main() -> i64 { print(place_root()); return 0; }\n", - ) - .unwrap(); - for mode in ["check", "build"] { - let out = Command::new(env!("CARGO_BIN_EXE_track")) - .args([mode, f.to_str().unwrap()]) - .current_dir(&td) - .output() - .unwrap(); - let err = String::from_utf8_lossy(&out.stderr); - assert_eq!(out.status.code(), Some(1), "{}: {}", mode, err); - assert!( - err.contains("error[E0201]: duplicate definition of function 'place_root'"), - "{}: {}", - mode, - err - ); - } - let _ = fs::remove_dir_all(&td); -} - -#[test] -fn test_cli_check_generics_valid() { - let td = env::temp_dir().join(format!("track_cli_gen_ok_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - let f = td.join("ok.trk"); - fs::write(&f, "fn identity(x: T) -> T { return x; } fn main() -> void { let a: i32 = 5; print(identity(a)); }").unwrap(); - let out = run_track_cmd(&["check", f.to_str().unwrap()]); - assert!( - out.status.success(), - "check should pass: {}", - String::from_utf8_lossy(&out.stderr) - ); - let _ = fs::remove_dir_all(&td); -} - -#[test] -fn test_cli_check_generics_arity_mismatch() { - let td = env::temp_dir().join(format!("track_cli_gen_bad_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - let f = td.join("bad.trk"); - fs::write(&f, "fn pair(a: T, b: U) -> (T, U) { return (a, b); } fn main() -> void { let p = pair(1); }").unwrap(); - let out = run_track_cmd(&["check", f.to_str().unwrap()]); - assert!(!out.status.success(), "arity mismatch should fail"); - let _ = fs::remove_dir_all(&td); -} - -#[test] -fn test_cli_check_const_across_functions() { - let td = env::temp_dir().join(format!("track_cli_const_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - let f = td.join("const.trk"); - fs::write(&f, "const BASE = 100; const OFF = BASE + 23; fn get() -> i64 { return OFF; } fn main() -> void { print(get()); }").unwrap(); - let out = run_track_cmd(&["check", f.to_str().unwrap()]); - assert!( - out.status.success(), - "const across functions should check: {}", - String::from_utf8_lossy(&out.stderr) - ); - let _ = fs::remove_dir_all(&td); -} - -#[test] -fn test_cli_build_and_run_generics() { - let td = env::temp_dir().join(format!("track_cli_build_gen_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - let f = td.join("gen.trk"); - fs::write(&f, "fn identity(x: T) -> T { return x; } fn main() -> void { let a: i32 = 7; print(identity(a)); }").unwrap(); - let build = run_track_cmd(&["build", f.to_str().unwrap()]); - assert!( - build.status.success(), - "build generics failed: {}", - String::from_utf8_lossy(&build.stderr) - ); - // executable is produced next to source or cwd — just verify build succeeded - let _ = fs::remove_dir_all(&td); - let _ = fs::remove_file("gen"); -} - -#[test] -fn test_cli_check_invalid_syntax_fails() { - let td = env::temp_dir().join(format!("track_cli_invalid_{}", std::process::id())); - let _ = fs::create_dir_all(&td); - let f = td.join("inv.trk"); - fs::write(&f, "fn main() -> void { let x = ; }").unwrap(); - let out = run_track_cmd(&["check", f.to_str().unwrap()]); - assert!(!out.status.success()); - let _ = fs::remove_dir_all(&td); -} diff --git a/tests/codegen_semantics_tests.rs b/tests/codegen_semantics_tests.rs deleted file mode 100644 index 97f0a011..00000000 --- a/tests/codegen_semantics_tests.rs +++ /dev/null @@ -1,420 +0,0 @@ -// Runtime semantics of the Cranelift backend. Each case builds a program, -// runs it, and compares stdout. These cover miscompilations found while -// bootstrapping the self-hosted compiler. - -use std::env; -use std::fs; -use std::process::Command; -use track::build_file_in_dir; - -fn run(name: &str, source: &str, args: &[&str]) -> String { - let temp_dir = env::temp_dir().join(format!("track_sem_{}_{}", name, std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - fs::create_dir_all(&temp_dir).unwrap(); - let src_file = temp_dir.join(format!("{}.trk", name)); - fs::write(&src_file, source).unwrap(); - let exe = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe).args(args).output().unwrap(); - let _ = fs::remove_dir_all(&temp_dir); - assert!( - output.status.success(), - "{} exited with {:?}: {}", - name, - output.status.code(), - String::from_utf8_lossy(&output.stderr) - ); - String::from_utf8_lossy(&output.stdout).trim().to_string() -} - -/// K3b: executables are PIE (ELF type ET_DYN). Non-PIE put the brk heap a -/// random 0..32 MiB above the image, so `print(count)` sometimes found a -/// heap string at address `count` and printed it (bench/progs/tokenize.trk -/// printed `9036 = bar + 1814332 * (baz - 1);` for 25988585 in ~1 run in 40). -#[test] -fn executables_are_position_independent() { - let temp_dir = env::temp_dir().join(format!("track_sem_pie_{}", std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - fs::create_dir_all(&temp_dir).unwrap(); - let src = temp_dir.join("pie.trk"); - fs::write(&src, "fn main() -> i64 { print(25988585); return 0; }\n").unwrap(); - let exe = build_file_in_dir(src.to_str().unwrap(), &temp_dir).unwrap(); - let image = fs::read(&exe).unwrap(); - let out = Command::new(&exe).output().unwrap(); - let _ = fs::remove_dir_all(&temp_dir); - assert_eq!(u16::from_le_bytes([image[16], image[17]]), 3, "not a PIE"); - assert_eq!(String::from_utf8_lossy(&out.stdout), "25988585\n"); -} - -/// K3b: `for x in a` binds the elements of array `a`, not 0, 1, 2, ... -/// forever; ranges count, empty arrays skip the body, loops nest. -#[test] -fn for_in_binds_array_elements() { - let source = fs::read_to_string( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/native/for_in.trk"), - ) - .unwrap(); - let out = run("for_in", &source, &[]); - assert_eq!( - out, - "10\n20\n30\n3\n2\n3\n4\n10\n20\n30\n110\n120\n130\nab\ncde\n60\n11\n21\n31" - ); -} - -#[test] -fn program_arguments_reach_os_args() { - let out = run( - "argv", - r#" - fn main() -> void { - print(os_args_count()); - let first = os_arg(1); - print(first); - } - "#, - &["hello"], - ); - assert_eq!(out, "2\nhello"); -} - -#[test] -fn logical_operators_short_circuit_and_normalise() { - let out = run( - "logic", - r#" - fn loud(v: i64) -> i64 { - print(v); - return v; - } - fn main() -> void { - let x: i64 = 1; - let y: i64 = 2; - if x && y { print(10); } else { print(11); } - if loud(0) && loud(5) { print(12); } - if loud(3) || loud(6) { print(13); } - let z = x && y; - print(z); - } - "#, - &[], - ); - assert_eq!(out, "10\n0\n3\n13\n1"); -} - -#[test] -fn return_inside_match_while_and_nested_if() { - let out = run( - "returns", - r#" - fn pick(x: i64) -> i64 { - match x { - 1 => return 10, - _ => return 20, - } - return 0; - } - fn first_over(limit: i64) -> i64 { - let mut i: i64 = 0; - while i < 100 { - if i * i > limit { - return i; - } - i = i + 1; - } - return -1; - } - fn nested(x: i64) -> i64 { - if x > 0 { - if x > 5 { return 7; } else { return 8; } - } - return 9; - } - fn loop_return(x: i64) -> i64 { - while x > 0 { - return 5; - } - return 6; - } - fn main() -> void { - print(pick(1)); print(pick(4)); - print(first_over(50)); - print(nested(10)); print(nested(2)); print(nested(-1)); - print(loop_return(1)); print(loop_return(0)); - } - "#, - &[], - ); - assert_eq!(out, "10\n20\n8\n7\n8\n9\n5\n6"); -} - -#[test] -fn if_and_match_produce_values() { - let out = run( - "values", - r#" - fn sign(x: i64) -> i64 { - let s = if x < 0 { -1 } else if x == 0 { 0 } else { 1 }; - return s; - } - fn name(x: i64) -> i64 { - let v = match x { 1 => 100, 2 => 200, _ => 300, }; - return v; - } - fn main() -> void { - print(sign(-4)); print(sign(0)); print(sign(9)); - print(name(2)); print(name(7)); - } - "#, - &[], - ); - assert_eq!(out, "-1\n0\n1\n200\n300"); -} - -#[test] -fn returned_tuple_variables_do_not_dangle() { - let out = run( - "tuples", - r#" - type Pair = (i64, i64); - fn make(a: i64) -> Pair { - let t = (a, a + 1); - return t; - } - fn clobber() -> i64 { - let z = (9, 9, 9, 9, 9, 9, 9, 9); - return z.0; - } - fn main() -> void { - let p = make(5); - let q = clobber(); - print(p.0); print(p.1); print(q); - } - "#, - &[], - ); - assert_eq!(out, "5\n6\n9"); -} - -#[test] -fn string_patterns_compare_contents() { - let out = run( - "strpat", - r#" - fn main() -> void { - let s = str_concat("he", "llo"); - match s { - "world" => print(0), - "hello" => print(1), - _ => print(2), - } - } - "#, - &[], - ); - assert_eq!(out, "1"); -} - -#[test] -fn union_payloads_and_enum_discriminants() { - let out = run( - "unions", - r#" - union Value { Int(i64), Flag(bool), Nothing } - enum Code { A = 5, B, C = 10 } - fn describe(v: Value) -> i64 { - let mut out: i64 = -1; - match v { - Value::Int(n) => out = n, - Value::Flag(f) => out = 1000 + f, - Value::Nothing => out = 0, - } - return out; - } - fn main() -> void { - print(describe(Value::Int(42))); - print(describe(Value::Flag(true))); - print(describe(Value::Nothing)); - print(Code::A); print(Code::B); print(Code::C); - } - "#, - &[], - ); - assert_eq!(out, "42\n1001\n0\n5\n6\n10"); -} - -/// Stage0 folds constants like symbols.trk const_eval: comparisons, `!`, -/// `&&` and `||` give 0/1, and a unit variant is a constant to later ones. -#[test] -fn constants_fold_comparisons_and_variants() { - let out = run( - "constfold", - r#" - const ONE = 1 < 2; - enum E { A = ONE, B } - const Q = E::B + 10; - const N = !ONE || (3 >= 3); - fn main() -> void { - print(ONE); print(E::A); print(E::B); print(Q); print(N); - print(7 / (1 < 2)); - } - "#, - &[], - ); - assert_eq!(out, "1\n1\n2\n12\n1\n7"); -} - -#[test] -fn negative_runtime_results_keep_their_sign() { - let out = run( - "signs", - r#" - fn main() -> void { - let r = file_remove("/definitely/not/here/x"); - print(r); - let c = str_char_at("abc", 1); - print(c); - } - "#, - &[], - ); - assert_eq!(out, "-1\n98"); -} - -#[test] -fn block_bindings_do_not_leak_into_the_enclosing_scope() { - let out = run( - "scopes", - r#" - fn main() -> void { - let x = 10; - if true { - let x = 20; - print(x); - } - print(x); - match 1 { - x => print(x), - } - print(x); - } - "#, - &[], - ); - assert_eq!(out, "20\n10\n1\n10"); -} - -#[test] -fn structs_and_arrays_have_runtime_values() { - let out = run( - "structs", - r#" - struct Point { x: i64, y: i64 } - struct Size { w: i64, x: i64 } - fn make(n: i64) -> Point { let p = Point { y: n + 1, x: n }; return p; } - fn main() -> void { - let mut p = make(3); - print(p.x); print(p.y); - p.x = 10; - let s = Size { x: 8, w: 7 }; - print(p.x + s.x); - match p { Point { x: 10, y } => print(y), _ => print(0), } - let mut a = [1, 2, 3, 4]; - a[3] = 40; - let tail = a[2..]; - print(array_len(&tail)); print(tail[1]); - let mut t = (1, 2); - t.1 = 9; - print(t.1); - } - "#, - &[], - ); - assert_eq!(out, "3\n4\n18\n4\n2\n40\n9"); -} - -#[test] -fn array_index_out_of_bounds_aborts() { - let temp_dir = env::temp_dir().join(format!("track_sem_bounds_{}", std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - fs::create_dir_all(&temp_dir).unwrap(); - let src = temp_dir.join("bounds.trk"); - fs::write(&src, "fn main() -> void { let a = [1, 2]; print(a[2]); }").unwrap(); - let exe = build_file_in_dir(src.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe).output().unwrap(); - let _ = fs::remove_dir_all(&temp_dir); - assert_eq!(output.status.code(), Some(134)); - assert!(String::from_utf8_lossy(&output.stderr).contains("array index out of bounds")); -} - -/// Build and run `source`; return (stdout, terminating signal). -fn run_signal(name: &str, source: &str) -> (String, Option) { - use std::os::unix::process::ExitStatusExt; - let temp_dir = env::temp_dir().join(format!("track_sem_{}_{}", name, std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - fs::create_dir_all(&temp_dir).unwrap(); - let src_file = temp_dir.join(format!("{}.trk", name)); - fs::write(&src_file, source).unwrap(); - let exe = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe).output().unwrap(); - let _ = fs::remove_dir_all(&temp_dir); - ( - String::from_utf8_lossy(&output.stdout).to_string(), - output.status.signal(), - ) -} - -/// K3c: a zero divisor (`/` or `%`, variable or constant) flushes stdout -/// and raises SIGFPE through `track_trap_div`, like trackc's C and native -/// builds, instead of losing the output to Cranelift's SIGILL trap. -#[test] -fn division_by_zero_flushes_and_raises_sigfpe() { - let cases = [ - ( - "divz", - "fn main()->i64{ print(1); let mut i=3; while i>=0 { print(100/i); i=i-1; } return 0; }", - "1\n33\n50\n100\n", - ), - ( - "modz", - "fn main()->i64{ print(7); let z = 0; print(5 % z); return 0; }", - "7\n", - ), - ( - "constz", - "fn main()->i64{ print(2); print(9 / 0); return 0; }", - "2\n", - ), - ( - // A parameter shadowing a constant is the run-time divisor. - "shadowz", - "const TWO = 2; const ONE = 1 < 2; fn d(TWO: i64) -> i64 { return 7 / TWO; } fn e(ONE: i64) -> i64 { return 7 % (ONE + 1); } fn main()->i64{ print(3); print(e(1)); print(d(0)); return 0; }", - "3\n1\n", - ), - ]; - for (name, src, want) in cases { - let (out, sig) = run_signal(name, src); - assert_eq!(out, want, "{}", name); - assert_eq!(sig, Some(8), "{}: expected SIGFPE", name); - } -} - -/// K3c: `INT64_MIN / -1` and `INT64_MIN % -1` trap like a zero divisor -/// (flush, SIGFPE), matching trackc's `tk_div`/`tk_mod`; other -1 divisions -/// still compute. -#[test] -fn int64_min_div_minus_one_flushes_and_raises_sigfpe() { - let ok = run( - "negone", - "fn main()->i64{ let m = -1; print(7 / m); print(7 % m); print(-9223372036854775807 / m); return 0; }", - &[], - ); - assert_eq!(ok, "-7\n0\n9223372036854775807"); - for (name, op) in [("mindiv", "/"), ("minmod", "%")] { - let src = format!( - "fn main()->i64{{ print(3); let m = -1; let a = -9223372036854775807 - 1; print(a {} m); return 0; }}", - op - ); - let (out, sig) = run_signal(name, &src); - assert_eq!(out, "3\n", "{}", name); - assert_eq!(sig, Some(8), "{}: expected SIGFPE", name); - } -} diff --git a/tests/codegen_tests.rs b/tests/codegen_tests.rs deleted file mode 100644 index 857e1ff6..00000000 --- a/tests/codegen_tests.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::env; -use std::fs; -use track::ast::*; -use track::codegen::CodeGen; -use track::compile_source; - -#[test] -fn test_codegen_simple_function() { - let mut cg = CodeGen::new("test_module"); - - let program = vec![Expr::FnDef { - name: "add".to_string(), - generics: Vec::new(), - params: vec![ - ("a".to_string(), TrackType::I32), - ("b".to_string(), TrackType::I32), - ], - return_type: Some(TrackType::I32), - body: vec![Expr::Return { - value: Some(Box::new(Expr::BinaryOp { - op: BinOp::Add, - left: Box::new(Expr::Variable("a".to_string())), - right: Box::new(Expr::Variable("b".to_string())), - })), - }], - }]; - - cg.compile_program(&program); - - let temp_dir = env::temp_dir().join(format!("track_cg_simple_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let obj_path = temp_dir.join("output.o"); - - let res = cg.write_object_file(&obj_path); - assert!(res.is_ok(), "Object file emission failed: {:?}", res.err()); - assert!(obj_path.exists()); - - let bytes = fs::read(&obj_path).unwrap(); - assert!(!bytes.is_empty()); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_codegen_object_file_emission() { - let temp_dir = env::temp_dir().join(format!("track_codegen_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let obj_path = temp_dir.join("output.o"); - - let mut cg = CodeGen::new("test_module"); - - let source = "fn main() -> void { print(42); }"; - let ast = compile_source(source).unwrap(); - cg.compile_program(&ast); - - let res = cg.write_object_file(&obj_path); - assert!(res.is_ok(), "Object file emission failed: {:?}", res.err()); - assert!(obj_path.exists()); - - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_codegen_string_literals_and_print() { - let mut cg = CodeGen::new("test_module"); - - let source = r#" - fn main() -> void { - print("Hello, Cranelift Codegen!"); - } - "#; - let ast = compile_source(source).unwrap(); - cg.compile_program(&ast); - - let temp_dir = env::temp_dir().join(format!("track_cg_str_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let obj_path = temp_dir.join("output.o"); - - let res = cg.write_object_file(&obj_path); - assert!(res.is_ok(), "Object file emission failed: {:?}", res.err()); - assert!(obj_path.exists()); - - let _ = fs::remove_dir_all(&temp_dir); -} diff --git a/tests/editor_tests.rs b/tests/editor_tests.rs deleted file mode 100644 index ffbe0138..00000000 --- a/tests/editor_tests.rs +++ /dev/null @@ -1,139 +0,0 @@ -use serde_json::Value; -use std::fs; -use std::path::Path; -use std::process::Command; - -#[test] -fn test_vscode_package_json() { - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); - let pkg_path = Path::new(&manifest_dir).join("editor/vscode/package.json"); - - assert!( - pkg_path.exists(), - "package.json does not exist at editor/vscode/package.json" - ); - - let content = fs::read_to_string(&pkg_path).expect("Failed to read package.json"); - let v: Value = serde_json::from_str(&content).expect("package.json is invalid JSON"); - - assert_eq!(v["name"], "track-vscode"); - assert_eq!(v["publisher"], "dev-dami"); - // flat simple icon lives inside the extension (was ../../assets/track-icon.svg) - assert_eq!(v["icon"], "images/track-icon.png"); - - let contributes = &v["contributes"]; - let languages = contributes["languages"] - .as_array() - .expect("languages array missing"); - assert!(!languages.is_empty()); - assert_eq!(languages[0]["id"], "track"); -} - -#[test] -fn test_vscode_language_configuration() { - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); - let config_path = Path::new(&manifest_dir).join("editor/vscode/language-configuration.json"); - - assert!( - config_path.exists(), - "language-configuration.json does not exist" - ); - - let content = - fs::read_to_string(&config_path).expect("Failed to read language-configuration.json"); - let v: Value = - serde_json::from_str(&content).expect("language-configuration.json is invalid JSON"); - - assert_eq!(v["comments"]["lineComment"], "//"); - assert!(v["brackets"].is_array()); - assert!(v["autoClosingPairs"].is_array()); -} - -#[test] -fn test_vscode_textmate_grammar() { - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); - let grammar_path = - Path::new(&manifest_dir).join("editor/vscode/syntaxes/track.tmLanguage.json"); - - assert!( - grammar_path.exists(), - "track.tmLanguage.json does not exist" - ); - - let content = fs::read_to_string(&grammar_path).expect("Failed to read tmLanguage.json"); - let v: Value = serde_json::from_str(&content).expect("tmLanguage.json is invalid JSON"); - - assert_eq!(v["scopeName"], "source.track"); - assert_eq!(v["name"], "Track"); - - // keywords may be split across patterns; collect all keyword matches - let keywords_patterns = v["repository"]["keywords"]["patterns"] - .as_array() - .expect("keywords patterns missing"); - let keywords_all: String = keywords_patterns - .iter() - .filter_map(|p| p["match"].as_str()) - .collect::>() - .join(" "); - // also allow struct/enum in typeDefinitions if not in keywords - let type_defs = v["repository"]["typeDefinitions"]["patterns"] - .as_array() - .map(|arr| { - arr.iter() - .filter_map(|p| p["match"].as_str().or(p["begin"].as_str())) - .collect::>() - .join(" ") - }) - .unwrap_or_default(); - let combined = format!("{} {}", keywords_all, type_defs); - - assert!( - combined.contains("import"), - "Grammar keywords missing 'import'" - ); - assert!(combined.contains("fn"), "Grammar keywords missing 'fn'"); - assert!( - combined.contains("struct"), - "Grammar keywords missing 'struct'" - ); -} - -#[test] -fn test_nvim_plugin_files() { - let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); - let vim_path = Path::new(&manifest_dir).join("editor/nvim/track.vim"); - let lua_path = Path::new(&manifest_dir).join("editor/nvim/track.lua"); - - assert!( - vim_path.exists(), - "track.vim does not exist at editor/nvim/track.vim" - ); - assert!( - lua_path.exists(), - "track.lua does not exist at editor/nvim/track.lua" - ); - - let lua_content = fs::read_to_string(&lua_path).expect("Failed to read track.lua"); - assert!( - lua_content.contains("import"), - "track.lua syntax missing 'import'" - ); - // flat simple icon — new design uses 󱐌 / #7aa2f7, keep backward compat check for T if present - assert!( - lua_content.contains("icon = \"T\"") || lua_content.contains("icon = \"󱐌\""), - "track.lua devicons missing icon" - ); - assert!( - lua_content.contains("color = \"#ffffff\"") || lua_content.contains("color = \"#7aa2f7\""), - "track.lua devicons missing color" - ); - - // If luac or luajit is installed on machine, test syntax parsing of track.lua - if let Ok(output) = Command::new("luac").arg("-p").arg(&lua_path).output() { - assert!( - output.status.success(), - "Lua syntax check failed for track.lua: {}", - String::from_utf8_lossy(&output.stderr) - ); - } -} diff --git a/tests/headless_highlight_tests.rs b/tests/headless_highlight_tests.rs deleted file mode 100644 index 8dee34f5..00000000 --- a/tests/headless_highlight_tests.rs +++ /dev/null @@ -1,335 +0,0 @@ -use regex::Regex; -use std::fs; -use std::path::Path; -use std::process::Command; - -// ── VS Code — headless grammar validation (no UI needed) ───────── -// Uses regex crate already in the project to prove each grammar pattern actually matches -// sample Track code — this is the same engine VS Code (TextMate) uses headlessly. - -fn load_grammar() -> serde_json::Value { - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - let p = Path::new(&manifest).join("editor/vscode/syntaxes/track.tmLanguage.json"); - let src = fs::read_to_string(&p).expect("read grammar"); - serde_json::from_str(&src).expect("json valid") -} - -#[test] -fn test_vscode_grammar_headless_tokenization() { - let v = load_grammar(); - // collect every regex from repository - let repo = v["repository"].as_object().unwrap(); - let mut patterns: Vec<(String, String)> = vec![]; - for (key, entry) in repo { - if let Some(arr) = entry["patterns"].as_array() { - for pat in arr { - if let Some(m) = pat["match"].as_str() { - patterns.push((key.clone(), m.to_string())); - } - if let Some(b) = pat["begin"].as_str() { - patterns.push((key.clone(), b.to_string())); - } - } - } - } - assert!(patterns.len() > 10, "too few patterns: {}", patterns.len()); - - // Sample that exercises every major scope - let sample = r#"import "std/io"; -fn main() -> void { - let mut x: i64 = 42; - // TODO fix - let s = "hello \"world\""; - let n = 0xFF; - let b = 0b1010; - if x > 0 { print(s); } - with u -> v { v.set(1); } - @macro bit(n: u32) -> u32 { return 1 << n; } - let p: ptr = alloc(8); - match val { _ => print(0), } -} -"#; - - // For each important construct, find a grammar pattern that matches it in the sample - let checks: Vec<(&str, &str, &[&str])> = vec![ - ("keyword fn", sample, &["fn"]), - ("keyword import", sample, &["import"]), - ("keyword struct/enum", "struct Foo { }", &["struct"]), - ("type i64", sample, &["i64"]), - ("type ptr", sample, &["ptr"]), - ("string", sample, &[r#""std/io""#, r#""hello"#]), - ("comment", sample, &["// TODO"]), - ("hex number", sample, &["0xFF"]), - ("binary number", sample, &["0b1010"]), - ("macro", sample, &["@macro"]), - ("operator ->", sample, &["->"]), - ("operator ::", "a::b", &["::"]), - ]; - - for (label, text, needles) in checks { - let mut matched = false; - for (_, pat) in &patterns { - // skip patterns that are not regex-valid (e.g. contains unescaped) - let re = match Regex::new(pat) { - Ok(r) => r, - Err(_) => continue, - }; - for needle in needles { - // needle is literal; check if some pattern matches it inside text - if re.is_match(needle) && text.contains(needle) { - matched = true; - break; - } - } - if matched { - break; - } - } - assert!( - matched, - "headless VS Code: pattern for {} ({:?}) not matched by any grammar regex", - label, needles - ); - } - - // scopeName must survive - assert_eq!(v["scopeName"], "source.track"); -} - -#[test] -fn test_vscode_grammar_valid_json_headless() { - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - for p in [ - "grammars/track.tmLanguage.json", - "editor/vscode/syntaxes/track.tmLanguage.json", - ] { - let path = Path::new(&manifest).join(p); - let src = fs::read_to_string(&path).unwrap(); - let v: serde_json::Value = serde_json::from_str(&src).unwrap(); - assert_eq!( - v["scopeName"], "source.track", - "scopeName mismatch in {}", - p - ); - assert!(v["repository"].is_object(), "repository missing in {}", p); - // each repository entry must have at least one pattern - let repo = v["repository"].as_object().unwrap(); - for (k, entry) in repo { - let arr = entry["patterns"] - .as_array() - .unwrap_or_else(|| panic!("{} patterns not array", k)); - assert!(!arr.is_empty(), "{} has no patterns", k); - } - } -} - -// ── Neovim — headless filetype + syntax ─────────────────────────── -fn nvim_available() -> bool { - Command::new("nvim") - .arg("--version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - -#[test] -fn test_nvim_headless_filetype_and_syntax() { - if !nvim_available() { - eprintln!("skipping nvim headless test — nvim not found"); - return; - } - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - - // 1) filetype detection + setup() headless - let out = Command::new("nvim") - .args([ - "--headless", - "-u", - "NONE", - "-n", - "-c", - &format!("set rtp+={}/editor/nvim", manifest), - "-c", - "lua require('track').setup()", - "-c", - "edit examples/hello.trk", - "-c", - "lua print('FT='..vim.bo.filetype)", - "-c", - "qa!", - ]) - .output() - .expect("spawn nvim"); - let stdout = String::from_utf8_lossy(&out.stdout); - let stderr = String::from_utf8_lossy(&out.stderr); - let combined = format!("{} {}", stdout, stderr); - assert!( - combined.contains("FT=track"), - "nvim headless filetype not track, got: {}", - combined - ); - - // 2) syntax groups exist after FileType - let out2 = Command::new("nvim") - .args([ - "--headless", - "-u", - "NONE", - "-n", - "-c", - &format!("set rtp+={}/editor/nvim", manifest), - "-c", - "lua require('track').setup()", - "-c", - "edit examples/hello.trk", - "-c", - "doautocmd FileType track", - "-c", - "redir => g:__syn | silent syn list | redir END | silent put =g:__syn | %print | qa!", - ]) - .output() - .expect("spawn nvim syn"); - let combined2 = format!( - "{} {}", - String::from_utf8_lossy(&out2.stdout), - String::from_utf8_lossy(&out2.stderr) - ); - for grp in [ - "trackKeyword", - "trackType", - "trackString", - "trackComment", - "trackNumber", - ] { - assert!( - combined2.contains(grp), - "nvim syntax group {} missing in headless output: {}", - grp, - combined2 - ); - } - - // 3) highlight links - let out3 = Command::new("nvim") - .args([ - "--headless", "-u", "NONE", "-n", - "-c", &format!("set rtp+={}/editor/nvim", manifest), - "-c", "lua require('track').setup()", - "-c", "edit examples/hello.trk", - "-c", "doautocmd FileType track", - "-c", "redir => g:__hl | silent hi trackKeyword | redir END | silent put =g:__hl | %print | qa!", - ]) - .output() - .expect("spawn nvim hi"); - let combined3 = format!( - "{} {}", - String::from_utf8_lossy(&out3.stdout), - String::from_utf8_lossy(&out3.stderr) - ); - assert!( - combined3.contains("trackKeyword") && combined3.contains("Keyword"), - "highlight link for trackKeyword missing: {}", - combined3 - ); -} - -#[test] -fn test_nvim_headless_lua_syntax_ok() { - if !nvim_available() { - eprintln!("skipping — nvim not found"); - return; - } - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - let lua_file = Path::new(&manifest).join("editor/nvim/track.lua"); - let out = Command::new("nvim") - .args([ - "--headless", - "-u", - "NONE", - "-n", - "-c", - &format!("luafile {}", lua_file.display()), - "-c", - "lua print('lua_ok')", - "-c", - "qa!", - ]) - .output() - .expect("nvim luafile"); - let combined = format!( - "{} {}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - assert!( - combined.contains("lua_ok"), - "nvim luafile failed: {}", - combined - ); -} - -#[test] -fn test_nvim_devicon_svg_not_needed_headless() { - // Prove: terminal nvim cannot render SVG — it uses font glyphs. - // The SVG files are only for VS Code (graphical). This test documents the fact - // and ensures the nvim plugin does NOT try to load an SVG. - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - let lua_src = fs::read_to_string(Path::new(&manifest).join("editor/nvim/track.lua")).unwrap(); - assert!( - lua_src.contains("Terminal cannot render") || lua_src.contains("vector images"), - "track.lua should document that SVG/vector is not for nvim" - ); - // must not actually reference an SVG file path (e.g. load .svg); comment mentioning SVG is ok if it says "cannot render" - // ensure no code tries to load SVG — check for 'load.*svg' or 'track-icon.svg' in code (allow comment) - let code_lines: Vec<&str> = lua_src - .lines() - .filter(|l| !l.trim_start().starts_with("--")) - .collect(); - let code = code_lines.join("\n"); - assert!( - !code.contains(".svg"), - "nvim track.lua code should not reference .svg — it uses font glyphs (comment ok)" - ); - let pkg = fs::read_to_string(Path::new(&manifest).join("editor/vscode/package.json")).unwrap(); - assert!( - pkg.contains("track-icon.png"), - "vscode package.json should reference PNG icon" - ); - assert!(Path::new(&manifest).join("assets/track-icon.svg").exists()); -} - -#[test] -fn test_nvim_syntax_highlight_sample_headless() { - if !nvim_available() { - eprintln!("skipping — nvim not found"); - return; - } - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - // Open a sample and ask synID for each keyword to ensure it is highlighted - let sample = "examples/hello.trk"; - let out = Command::new("nvim") - .args([ - "--headless", "-u", "NONE", "-n", - "-c", &format!("set rtp+={}/editor/nvim", manifest), - "-c", "lua require('track').setup()", - "-c", &format!("edit {}", sample), - "-c", "doautocmd FileType track", - "-c", "let g:ids = [] | for lnum in range(1, line('$')) | for col in range(1, strdisplaywidth(getline(lnum))) | call add(g:ids, synIDattr(synID(lnum, col, 1), 'name')) | endfor | endfor | echo join(g:ids, ',')", - "-c", "qa!", - ]) - .output() - .expect("nvim synID"); - let combined = format!( - "{} {}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - // At least one syntax group should be reported for hello.trk (which contains fn, print) - assert!( - combined.contains("trackKeyword") - || combined.contains("trackFunction") - || combined.contains("trackString"), - "nvim headless synID produced no Track syntax: {}", - combined - ); -} diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs deleted file mode 100644 index 9adc1726..00000000 --- a/tests/integration_tests.rs +++ /dev/null @@ -1,362 +0,0 @@ -use std::env; -use std::fs; -use std::path::Path; -use std::process::Command; -use track::{build_file_in_dir, compile_source}; - -#[test] -fn test_valid_examples_compilation_and_execution() { - let temp_dir = env::temp_dir().join(format!("track_test_examples_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - - let examples = vec![ - "hello.trk", - "arithmetic.trk", - "borrow.trk", - "linear_auto_free.trk", - "macro_test.trk", - "union_enum_test.trk", - "use_test.trk", - ]; - - let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); - let examples_dir = Path::new(&manifest_dir).join("examples"); - - for example in examples { - println!("Testing example: {}", example); - let example_path = examples_dir.join(example); - assert!( - example_path.exists(), - "Example file not found: {}", - example_path.display() - ); - - let exe_path = build_file_in_dir(example_path.to_str().unwrap(), &temp_dir) - .unwrap_or_else(|e| panic!("Failed to build {}: {}", example, e)); - - assert!( - exe_path.exists(), - "Executable path does not exist: {}", - exe_path.display() - ); - - let output = Command::new(&exe_path) - .output() - .unwrap_or_else(|e| panic!("Failed to run {}: {}", example, e)); - - assert!( - output.status.success(), - "Execution of {} failed with code {:?}. Stderr:\n{}", - example, - output.status.code(), - String::from_utf8_lossy(&output.stderr) - ); - } - - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_memory_boundary_exceeded_crash() { - let source = r#" - fn main() -> void { - sys_set_memory_limit(1000); - let buf = alloc(2000); - } - "#; - let temp_dir = env::temp_dir().join(format!("track_mem_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("mem_test.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - - assert!( - !output.status.success(), - "Memory boundary exceeded program should fail" - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("Process memory boundary limit exceeded"), - "Expected memory boundary message in stderr, got: {}", - stderr - ); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_invalid_examples_rejection() { - let invalid_examples = vec![ - ("borrow_lock_err.trk", "frozen"), - ("escape_err.trk", "escapes"), - ("manual_free_err.trk", "managed automatically"), - ]; - - let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); - let examples_dir = Path::new(&manifest_dir).join("examples"); - - for (example, expected_err) in invalid_examples { - let example_path = examples_dir.join(example); - let source = fs::read_to_string(&example_path) - .unwrap_or_else(|e| panic!("Failed to read {}: {}", example, e)); - - let res = compile_source(&source); - assert!( - res.is_err(), - "Expected compilation error for {}, but it succeeded", - example - ); - - let err_msg = res.unwrap_err(); - assert!( - err_msg.contains(expected_err), - "Expected error for {} to contain '{}', got:\n{}", - example, - expected_err, - err_msg - ); - } -} - -#[test] -fn test_for_in_loop_execution() { - let source = r#" - import "std/io"; - fn main() -> void { - for i in 0..3 { - print(i); - } - } - "#; - let temp_dir = env::temp_dir().join(format!("track_for_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("for_test.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - - assert!(output.status.success(), "For loop execution failed"); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_explicit_error_handling_convention() { - // v0.5.0: (value, err) tuple returns, explicit propagation, abort(msg) - let source = r#" - const ERR_NOT_FOUND = 1; - - fn file_len(path: &ptr) -> (i64, i32) { - let ok = file_exists(path); - if (!ok) { - return (-1, ERR_NOT_FOUND); - } - return (file_size(path), 0); - } - - fn total(path: &ptr, fallback: i64) -> i64 { - let (size, err) = file_len(path); - if (err == ERR_NOT_FOUND) { - print_err("missing input, using fallback"); - return fallback; - } - if (err != 0) { - abort("fatal: unexpected error"); - } - return size; - } - - fn main() -> void { - print(total("/etc/hostname", -7)); - print(total("/definitely/not/here", 7)); - } - "#; - let temp_dir = env::temp_dir().join(format!("track_err_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("error_handling.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - - assert!(output.status.success(), "Error handling program failed"); - let stdout = String::from_utf8_lossy(&output.stdout); - let lines: Vec<&str> = stdout.lines().collect(); - assert!( - lines.len() >= 2 && lines[0].trim() != "-1" && !lines[0].is_empty(), - "Expected real size for existing file, got: {}", - stdout - ); - assert!( - lines[1].trim() == "7", - "Expected fallback value 7 for missing file, got: {}", - stdout - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("missing input"), - "Expected stderr diagnostic, got: {}", - stderr - ); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_logical_not_operator() { - // Regression: unary ! was compiled as bitwise NOT (bnot), - // making `if (!flag)` with flag == 1 take the wrong branch. - let source = r#" - fn main() -> void { - let ok = file_exists("/etc/hostname"); - if (!ok) { - print(999); - return; - } - let missing = file_exists("/definitely/not/here"); - if (!missing) { - print(42); - } - } - "#; - let temp_dir = env::temp_dir().join(format!("track_lnot_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("lnot.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - - assert!(output.status.success()); - let stdout = String::from_utf8_lossy(&output.stdout); - assert_eq!( - stdout.trim(), - "42", - "Logical NOT miscompiled; got: {}", - stdout - ); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_const_resolution_across_functions() { - // Regression: top-level consts were invisible to non-main functions - // and silently evaluated to 0 at codegen. - let source = r#" - const BASE = 100; - const OFFSET = BASE + 23; - - fn get_offset() -> i64 { - return OFFSET; - } - - fn main() -> void { - print(BASE); - print(get_offset()); - } - "#; - let temp_dir = env::temp_dir().join(format!("track_const_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("consts.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - - assert!(output.status.success()); - let stdout = String::from_utf8_lossy(&output.stdout); - let lines: Vec<&str> = stdout.lines().collect(); - assert_eq!( - lines.first().copied().unwrap_or(""), - "100", - "got: {}", - stdout - ); - assert_eq!( - lines.get(1).copied().unwrap_or(""), - "123", - "got: {}", - stdout - ); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_error_predicates_disambiguate_sentinels() { - // str_is_int / env_exists disambiguate ambiguous sentinel returns - let source = r#" - fn main() -> void { - if (str_is_int("00042")) { - print(str_to_int("00042")); - } - if (!str_is_int("junk")) { - print(111); - } - if (env_exists("PATH")) { - print(222); - } - if (!env_exists("TRACK_DEFINITELY_NOT_SET_9x7")) { - print(333); - } - } - "#; - let temp_dir = env::temp_dir().join(format!("track_pred_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("pred.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - - assert!(output.status.success()); - let stdout = String::from_utf8_lossy(&output.stdout); - let lines: Vec<&str> = stdout.lines().collect(); - assert_eq!( - lines.first().copied().unwrap_or(""), - "42", - "got: {}", - stdout - ); - assert!(lines.contains(&"111"), "got: {}", stdout); - assert!(lines.contains(&"222"), "got: {}", stdout); - assert!(lines.contains(&"333"), "got: {}", stdout); - assert!(!lines.contains(&"999"), "got: {}", stdout); - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_generics_monomorphization() { - let source = r#" - fn identity(x: T) -> T { return x; } - fn pair(a: T, b: U) -> (T, U) { return (a, b); } - fn main() -> void { - let a: i32 = 5; - print(identity(a)); - let b: i64 = 10; - print(identity(b)); - let p = pair(1, 2); - print(p.0); - print(p.1); - let z = pair(identity(1), identity(2)); - print(z.0); - print(z.1); - } - "#; - let temp_dir = env::temp_dir().join(format!("track_gen_test_{}", std::process::id())); - let _ = fs::create_dir_all(&temp_dir); - let src_file = temp_dir.join("gen.trk"); - fs::write(&src_file, source).unwrap(); - - let exe_path = build_file_in_dir(src_file.to_str().unwrap(), &temp_dir).unwrap(); - let output = Command::new(&exe_path).output().unwrap(); - assert!(output.status.success(), "generics test failed"); - let stdout = String::from_utf8_lossy(&output.stdout); - let lines: Vec<&str> = stdout.lines().collect(); - assert_eq!( - lines, - vec!["5", "10", "1", "2", "1", "2"], - "got: {}", - stdout - ); - let _ = fs::remove_dir_all(&temp_dir); -} diff --git a/tests/lexer_tests.rs b/tests/lexer_tests.rs deleted file mode 100644 index c444c02e..00000000 --- a/tests/lexer_tests.rs +++ /dev/null @@ -1,142 +0,0 @@ -use track::lexer::{Lexer, Token}; - -#[test] -fn test_tokenize_keywords() { - let source = "import let mut with fn return if else while true false struct enum union match as const @ @macro"; - let tokens = Lexer::tokenize(source).unwrap(); - let token_kinds: Vec = tokens.into_iter().map(|(t, _)| t).collect(); - - assert_eq!( - token_kinds, - vec![ - Token::Import, - Token::Let, - Token::Mut, - Token::With, - Token::Fn, - Token::Return, - Token::If, - Token::Else, - Token::While, - Token::True, - Token::False, - Token::Struct, - Token::Enum, - Token::Union, - Token::Match, - Token::As, - Token::Const, - Token::At, - Token::AtMacro, - ] - ); -} - -#[test] -fn test_tokenize_types() { - let source = "i32 u32 i64 u64 bool void ptr"; - let tokens = Lexer::tokenize(source).unwrap(); - let token_kinds: Vec = tokens.into_iter().map(|(t, _)| t).collect(); - - assert_eq!( - token_kinds, - vec![ - Token::TyI32, - Token::TyU32, - Token::TyI64, - Token::TyU64, - Token::TyBool, - Token::TyVoid, - Token::TyPtr, - ] - ); -} - -#[test] -fn test_tokenize_literals_and_idents() { - let source = "12345 \"hello world\\r\\n\\t\" my_var _var2"; - let tokens = Lexer::tokenize(source).unwrap(); - let token_kinds: Vec = tokens.into_iter().map(|(t, _)| t).collect(); - - assert_eq!( - token_kinds, - vec![ - Token::Int(12345), - Token::Str("hello world\r\n\t".to_string()), - Token::Ident("my_var".to_string()), - Token::Ident("_var2".to_string()), - ] - ); -} - -#[test] -fn test_tokenize_operators_and_punctuation() { - let source = "= == != ! { } ( ) [ ] , : :: -> => ; . _ & | * + - / % < > <= >= && || << >>"; - let tokens = Lexer::tokenize(source).unwrap(); - let token_kinds: Vec = tokens.into_iter().map(|(t, _)| t).collect(); - - assert_eq!( - token_kinds, - vec![ - Token::Eq, - Token::EqEq, - Token::Neq, - Token::Bang, - Token::LBrace, - Token::RBrace, - Token::LParen, - Token::RParen, - Token::LBracket, - Token::RBracket, - Token::Comma, - Token::Colon, - Token::ColonColon, - Token::Arrow, - Token::FatArrow, - Token::Semicolon, - Token::Dot, - Token::Underscore, - Token::Amp, - Token::Pipe, - Token::Star, - Token::Plus, - Token::Minus, - Token::Slash, - Token::Percent, - Token::Lt, - Token::Gt, - Token::Lte, - Token::Gte, - Token::AmpAmp, - Token::PipePipe, - Token::Shl, - Token::Shr, - ] - ); -} - -#[test] -fn test_tokenize_comments_and_whitespace() { - let source = "// This is a comment\nlet x = 10; // comment after code\n"; - let tokens = Lexer::tokenize(source).unwrap(); - let token_kinds: Vec = tokens.into_iter().map(|(t, _)| t).collect(); - - assert_eq!( - token_kinds, - vec![ - Token::Let, - Token::Ident("x".to_string()), - Token::Eq, - Token::Int(10), - Token::Semicolon, - ] - ); -} - -#[test] -fn test_tokenize_invalid_character() { - let source = "let x = #;"; - let result = Lexer::tokenize(source); - assert!(result.is_err()); - assert!(result.unwrap_err().contains("unexpected character '#'")); -} diff --git a/tests/logic_and_soundness_strict_tests.rs b/tests/logic_and_soundness_strict_tests.rs deleted file mode 100644 index 6c35fbe3..00000000 --- a/tests/logic_and_soundness_strict_tests.rs +++ /dev/null @@ -1,133 +0,0 @@ -use track::ast::{BinOp, Expr, TrackType}; -use track::checker::LinearChecker; -use track::lexer::Lexer; -use track::parser::Parser; - -fn parse(source: &str) -> Vec { - let tokens = Lexer::tokenize(source).expect("Tokenization failed"); - let mut parser = Parser::new(tokens, source.to_string()); - parser.parse_program().expect("Parsing failed") -} - -fn check(source: &str) -> Result<(), String> { - let program = parse(source); - let mut checker = LinearChecker::new(); - checker.check_program(&program) -} - -#[test] -fn test_strict_mutability_reassignment_rejection() { - let source = r#" - fn main() -> void { - let x = 10; - x = 20; - } - "#; - let res = check(source); - assert!( - res.is_err(), - "Expected mutability check failure when reassigning non-mut variable" - ); - assert!( - res.unwrap_err() - .contains("Cannot mutate immutable variable 'x'"), - "Error message must specify immutable variable mutation" - ); -} - -#[test] -fn test_strict_mutable_variable_reassignment_allowed() { - let source = r#" - fn main() -> void { - let mut x = 10; - x = 20; - print(x); - } - "#; - assert!( - check(source).is_ok(), - "Reassigning mut variable should be allowed" - ); -} - -#[test] -fn test_strict_bitwise_or_vs_logical_or_ast_precedence() { - let source = "fn main() -> void { let res = a | b || c & d; }"; - let ast = parse(source); - - if let Expr::FnDef { body, .. } = &ast[0] - && let Expr::LetDef { value, .. } = &body[0] - { - if let Expr::BinaryOp { op, .. } = value.as_ref() { - assert_eq!( - *op, - BinOp::Or, - "Top-level binary operator should be Logical OR (||)" - ); - } else { - panic!("Expected BinaryOp for bitwise vs logical precedence test"); - } - } -} - -#[test] -fn test_strict_double_move_in_loop_rejection() { - let source = r#" - struct Resource { id: i32 } - - fn consume(r: Resource) -> void { - print(1); - } - - fn main() -> void { - let r = Resource { id: 1 }; - let mut i = 0; - while i < 5 { - let consumed = r; - i = i + 1; - } - } - "#; - let res = check(source); - assert!( - res.is_err(), - "Expected error when moving linear resource inside loop without reinitialization" - ); -} - -#[test] -fn test_strict_unresolved_type_alias_detection() { - let source = r#" - type Buffer = UnknownType; - fn main() -> void { - let buf = 10; - } - "#; - let ast = parse(source); - assert_eq!( - ast[0], - Expr::TypeAlias { - name: "Buffer".to_string(), - target: TrackType::Custom("UnknownType".to_string()) - } - ); -} - -#[test] -fn test_strict_borrow_escape_from_lens_block() { - let source = r#" - struct System { state: i32 } - - fn main() -> void { - let mut sys = System { state: 1 }; - with sys -> s { - let val = 10; - } - sys = System { state: 2 }; - } - "#; - assert!( - check(source).is_ok(), - "Lens block should cleanly unlock target after end" - ); -} diff --git a/tests/lsp_tests.rs b/tests/lsp_tests.rs deleted file mode 100644 index 1d7ff544..00000000 --- a/tests/lsp_tests.rs +++ /dev/null @@ -1,92 +0,0 @@ -use tower_lsp::LanguageServer; -use tower_lsp::lsp_types::*; - -use track::lsp::TrackLsp; - -#[tokio::test] -async fn test_lsp_initialization() { - let (service, _) = tower_lsp::LspService::new(TrackLsp::new); - let server = service.inner(); - - let init_params = InitializeParams::default(); - let init_result = server.initialize(init_params).await.unwrap(); - - assert!(init_result.capabilities.completion_provider.is_some()); - assert!(init_result.capabilities.hover_provider.is_some()); -} - -#[tokio::test] -async fn test_lsp_completion() { - let (service, _) = tower_lsp::LspService::new(TrackLsp::new); - let server = service.inner(); - - let uri = Url::parse("file:///test.trk").unwrap(); - let text = "fn main() -> void {\n le\n}".to_string(); - - server - .did_open(DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: uri.clone(), - language_id: "track".to_string(), - version: 1, - text, - }, - }) - .await; - - let completion_params = CompletionParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { uri: uri.clone() }, - position: Position::new(1, 6), - }, - work_done_progress_params: WorkDoneProgressParams::default(), - partial_result_params: PartialResultParams::default(), - context: None, - }; - - let response = server.completion(completion_params).await.unwrap(); - assert!(response.is_some()); - if let Some(CompletionResponse::Array(items)) = response { - assert!(items.iter().any(|item| item.label == "let")); - } else { - panic!("Expected array completion response"); - } -} - -#[tokio::test] -async fn test_lsp_hover() { - let (service, _) = tower_lsp::LspService::new(TrackLsp::new); - let server = service.inner(); - - let uri = Url::parse("file:///test.trk").unwrap(); - let text = "fn main() -> void {\n print(42);\n}".to_string(); - - server - .did_open(DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: uri.clone(), - language_id: "track".to_string(), - version: 1, - text, - }, - }) - .await; - - let hover_params = HoverParams { - text_document_position_params: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { uri: uri.clone() }, - position: Position::new(1, 6), - }, - work_done_progress_params: WorkDoneProgressParams::default(), - }; - - let response = server.hover(hover_params).await.unwrap(); - assert!(response.is_some()); - if let Some(hover) = response { - if let HoverContents::Markup(markup) = hover.contents { - assert!(markup.value.contains("Print a value to stdout")); - } else { - panic!("Expected markup hover contents"); - } - } -} diff --git a/tests/native_tests.rs b/tests/native_tests.rs deleted file mode 100644 index 7fbadc50..00000000 --- a/tests/native_tests.rs +++ /dev/null @@ -1,448 +0,0 @@ -// Native x86-64 backend (`trackc build --native`, compiler/src/ngen.trk). -// -// trackc is built once with `yard` (stage 1). The tests check that native -// executables need no C toolchain, behave like the C backend's, and that -// the natively built compiler reaches a byte-identical fixed point. - -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::OnceLock; - -fn repo() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) -} - -fn scratch(name: &str) -> PathBuf { - let dir = env::temp_dir().join(format!("track_native_{}_{}", name, std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir -} - -fn trackc() -> &'static Path { - static TRACKC: OnceLock = OnceLock::new(); - TRACKC.get_or_init(|| { - let status = Command::new(env!("CARGO_BIN_EXE_yard")) - .arg("build") - .current_dir(repo().join("compiler")) - .output() - .expect("failed to run yard"); - assert!(status.status.success(), "yard build of compiler/ failed"); - let copy = scratch("stage1").join("trackc"); - fs::copy(repo().join("compiler/target/trackc"), ©).unwrap(); - copy - }) -} - -fn run(exe: &Path, args: &[&str], path_env: Option<&str>) -> Output { - let mut cmd = Command::new(exe); - cmd.args(args).current_dir(repo()); - if let Some(p) = path_env { - cmd.env("PATH", p); - } - cmd.output().expect("failed to run") -} - -fn observe(exe: &Path) -> (String, String, Option) { - let out = Command::new(exe).output().unwrap(); - ( - String::from_utf8_lossy(&out.stdout).to_string(), - String::from_utf8_lossy(&out.stderr).to_string(), - out.status.code(), - ) -} - -#[test] -fn native_build_needs_no_c_toolchain() { - let dir = scratch("hello"); - let exe = dir.join("hello"); - let out = run( - trackc(), - &[ - "build", - "--native", - "tests/native_raw/hello_syscall.trk", - "-o", - exe.to_str().unwrap(), - ], - Some("/nonexistent"), - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - let image = fs::read(&exe).unwrap(); - assert_eq!(&image[..4], b"\x7fELF"); - let (stdout, _, code) = observe(&exe); - assert_eq!(stdout, "Hello, native world!\n"); - assert_eq!(code, Some(42)); - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn native_programs_match_the_c_backend() { - let dir = scratch("parity"); - let mut inputs: Vec = Vec::new(); - for sub in ["examples", "tests/native", "bench/progs"] { - for e in fs::read_dir(repo().join(sub)).unwrap() { - let p = e.unwrap().path(); - let stem = p.file_stem().unwrap().to_string_lossy().to_string(); - if p.extension().is_some_and(|x| x == "trk") && !stem.ends_with("_err") { - inputs.push(p); - } - } - } - inputs.sort(); - assert!(inputs.len() > 10); - for p in inputs { - let stem = p.file_stem().unwrap().to_string_lossy().to_string(); - let c_exe = dir.join(format!("{}_c", stem)); - let n_exe = dir.join(format!("{}_n", stem)); - let src = p.to_str().unwrap(); - let c = run( - trackc(), - &["build", src, "-o", c_exe.to_str().unwrap()], - None, - ); - assert!(c.status.success(), "{}: C build failed", stem); - let n = run( - trackc(), - &["build", "--native", src, "-o", n_exe.to_str().unwrap()], - None, - ); - assert!( - n.status.success(), - "{}: native build failed: {}", - stem, - String::from_utf8_lossy(&n.stderr) - ); - let (c_out, _, c_code) = observe(&c_exe); - let (n_out, _, n_code) = observe(&n_exe); - assert_eq!( - (c_out, c_code), - (n_out, n_code), - "{}: behaviour differs", - stem - ); - } - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn native_compiler_reaches_a_fixed_point() { - let dir = scratch("fixpoint"); - let n2 = dir.join("trackc2"); - let n3 = dir.join("trackc3"); - let out = run( - trackc(), - &[ - "build", - "--native", - "compiler/src/main.trk", - "-o", - n2.to_str().unwrap(), - ], - None, - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - let out = run( - &n2, - &[ - "build", - "--native", - "compiler/src/main.trk", - "-o", - n3.to_str().unwrap(), - ], - Some("/nonexistent"), - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - assert!( - fs::read(&n2).unwrap() == fs::read(&n3).unwrap(), - "native stage2 and stage3 differ" - ); - let _ = fs::remove_dir_all(&dir); -} - -fn trk_files(sub: &str) -> Vec { - let mut v: Vec = fs::read_dir(repo().join(sub)) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|x| x == "trk")) - .collect(); - v.sort(); - v -} - -// Every program `trackc check` rejects must be rejected by the native build -// and by `--rt=track`: the embedded runtime must not change how the user -// program is checked (its plain-i64 definitions of str_concat, vec_push... -// used to replace the builtin signatures the ownership checker relies on). -#[test] -fn native_and_track_rt_reject_what_check_rejects() { - let dir = scratch("reject"); - let exe = dir.join("x"); - let exe = exe.to_str().unwrap(); - let mut inputs = trk_files("tests/native_reject"); - inputs.extend( - trk_files("examples") - .into_iter() - .filter(|p| p.to_string_lossy().ends_with("_err.trk")), - ); - assert!(inputs.len() >= 12); - for p in inputs { - let src = p.to_str().unwrap(); - assert!( - !run(trackc(), &["check", src], None).status.success(), - "{}: check accepted it", - src - ); - assert!( - !run(trackc(), &["build", "--native", src, "-o", exe], None) - .status - .success(), - "{}: --native accepted it", - src - ); - assert!( - !run(trackc(), &["build", "--rt=track", src, "-o", exe], None) - .status - .success(), - "{}: --rt=track accepted it", - src - ); - } - let _ = fs::remove_dir_all(&dir); -} - -// Tuples stored in a struct, array, union or tuple, returned, or built in -// a loop outlive the frame that made them (docs/bootstrap.md "Value model"). -#[test] -fn native_tuples_outlive_their_frame() { - let dir = scratch("tuples"); - let expect = [ - ("tup_arr", "200\n5\n"), - ("tup_loop", "0\n20\n"), - ("tup_nested", "200\n6\n"), - ("tup_struct", "200\n8\n"), - ("tup_struct2", "30\nxy\n8\n"), - ("tup_union", "200\n6\n"), - ]; - for (name, want) in expect { - let exe = dir.join(name); - let src = format!("tests/native_tuples/{}.trk", name); - let out = run( - trackc(), - &["build", "--native", &src, "-o", exe.to_str().unwrap()], - None, - ); - assert!( - out.status.success(), - "{}: {}", - name, - String::from_utf8_lossy(&out.stderr) - ); - let (stdout, _, code) = observe(&exe); - assert_eq!((stdout.as_str(), code), (want, Some(0)), "{}", name); - } - let _ = fs::remove_dir_all(&dir); -} - -// Identical string literals are one object, as in the C backend. -#[test] -fn native_identical_string_literals_compare_equal() { - let dir = scratch("strlit"); - let exe = dir.join("s"); - let out = run( - trackc(), - &[ - "build", - "--native", - "tests/native/strlit_eq.trk", - "-o", - exe.to_str().unwrap(), - ], - None, - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - let (stdout, _, _) = observe(&exe); - assert!(stdout.starts_with("1\n"), "{:?}", stdout); - let _ = fs::remove_dir_all(&dir); -} - -// A program with no `main` builds and exits 0, as on the C path. -#[test] -fn native_program_without_main_builds() { - let dir = scratch("nomain"); - for name in ["nomain", "nomain_lib"] { - let exe = dir.join(name); - let src = format!("tests/native/{}.trk", name); - let out = run( - trackc(), - &["build", "--native", &src, "-o", exe.to_str().unwrap()], - None, - ); - assert!( - out.status.success(), - "{}: {}", - name, - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - observe(&exe), - (String::new(), String::new(), Some(0)), - "{}", - name - ); - } - let _ = fs::remove_dir_all(&dir); -} - -// `--native` works after the file and after `-o` too; with no C compiler on -// PATH only the native backend can succeed. -#[test] -fn native_flag_is_honoured_in_any_position() { - let dir = scratch("flagpos"); - let exe = dir.join("h"); - let exe = exe.to_str().unwrap(); - let orders: [&[&str]; 3] = [ - &[ - "build", - "tests/native_raw/hello_syscall.trk", - "--native", - "-o", - exe, - ], - &[ - "build", - "tests/native_raw/hello_syscall.trk", - "-o", - exe, - "--native", - ], - &[ - "build", - "-o", - exe, - "--native", - "tests/native_raw/hello_syscall.trk", - ], - ]; - for args in orders { - let _ = fs::remove_file(exe); - let out = run(trackc(), args, Some("/nonexistent")); - assert!( - out.status.success(), - "{:?}: {}", - args, - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!(observe(Path::new(exe)).2, Some(42), "{:?}", args); - } - let _ = fs::remove_dir_all(&dir); -} - -// Native executables carry PT_GNU_STACK (read/write, not executable). -#[test] -fn native_executables_have_a_non_executable_stack() { - let dir = scratch("gnustack"); - let exe = dir.join("h"); - let out = run( - trackc(), - &[ - "build", - "--native", - "tests/native_raw/hello_syscall.trk", - "-o", - exe.to_str().unwrap(), - ], - None, - ); - assert!(out.status.success()); - let img = fs::read(&exe).unwrap(); - let u16_at = |o: usize| u16::from_le_bytes([img[o], img[o + 1]]) as usize; - let u32_at = |o: usize| u32::from_le_bytes(img[o..o + 4].try_into().unwrap()); - let phoff = u64::from_le_bytes(img[32..40].try_into().unwrap()) as usize; - let (entsize, count) = (u16_at(54), u16_at(56)); - let stack = (0..count) - .map(|i| phoff + i * entsize) - .find(|&h| u32_at(h) == 0x6474_e551) - .expect("no PT_GNU_STACK program header"); - assert_eq!(u32_at(stack + 4), 6, "PT_GNU_STACK flags must be RW"); - let _ = fs::remove_dir_all(&dir); -} - -// K3b: programs both backends once got wrong the same way, so parity alone -// missed them. Each must print `stdout` and end with `code` (or be killed -// by signal `sig`) under the C backend and natively. -const K3B_PROGRAMS: [(&str, &str, Option, Option); 5] = [ - ( - "for_in", - "10\n20\n30\n3\n2\n3\n4\n10\n20\n30\n110\n120\n130\nab\ncde\n60\n11\n21\n31\n", - Some(0), - None, - ), - ("exit_flush", "1\n", Some(3), None), - ("divzero_flush", "1\n", None, Some(8)), - // K3c: INT64_MIN / -1 and % -1 trap like a zero divisor (flush, SIGFPE). - ( - "divmin_flush", - "-7\n0\n-9223372036854775807\n", - None, - Some(8), - ), - ("divmin_mod_flush", "0\n", None, Some(8)), -]; - -#[test] -fn native_and_c_print_the_expected_output() { - use std::os::unix::process::ExitStatusExt; - let dir = scratch("k3b"); - for (stem, stdout, code, sig) in K3B_PROGRAMS { - let src = format!("tests/native/{}.trk", stem); - for mode in ["c", "native"] { - let exe = dir.join(format!("{}_{}", stem, mode)); - let mut args = vec!["build"]; - if mode == "native" { - args.push("--native"); - } - args.extend([src.as_str(), "-o", exe.to_str().unwrap()]); - let out = run(trackc(), &args, None); - assert!( - out.status.success(), - "{} {}: build failed: {}", - stem, - mode, - String::from_utf8_lossy(&out.stderr) - ); - let out = Command::new(&exe).output().unwrap(); - assert_eq!( - ( - String::from_utf8_lossy(&out.stdout).to_string(), - out.status.code(), - out.status.signal() - ), - (stdout.to_string(), code, sig), - "{} {}: wrong behaviour", - stem, - mode - ); - } - } - let _ = fs::remove_dir_all(&dir); -} diff --git a/tests/parser_tests.rs b/tests/parser_tests.rs deleted file mode 100644 index 03654f4d..00000000 --- a/tests/parser_tests.rs +++ /dev/null @@ -1,332 +0,0 @@ -use track::ast::*; -use track::lexer::Lexer; -use track::parser::Parser; - -fn parse(source: &str) -> Vec { - let tokens = Lexer::tokenize(source).unwrap(); - let mut parser = Parser::new(tokens, source.to_string()); - parser.parse_program().unwrap() -} - -#[test] -fn test_parse_fn_def() { - let source = "fn add(a: i32, b: i32) -> i32 { return a + b; }"; - let ast = parse(source); - assert_eq!( - ast, - vec![Expr::FnDef { - name: "add".to_string(), - generics: Vec::new(), - params: vec![ - ("a".to_string(), TrackType::I32), - ("b".to_string(), TrackType::I32) - ], - return_type: Some(TrackType::I32), - body: vec![Expr::Return { - value: Some(Box::new(Expr::BinaryOp { - op: BinOp::Add, - left: Box::new(Expr::Variable("a".to_string())), - right: Box::new(Expr::Variable("b".to_string())), - })) - }] - }] - ); -} - -#[test] -fn test_parse_let_def() { - let source = "let mut x: i64 = 100;"; - let ast = parse(source); - assert_eq!( - ast, - vec![Expr::LetDef { - name: "x".to_string(), - mutable: true, - ty: Some(TrackType::I64), - value: Box::new(Expr::IntLiteral(100)), - }] - ); -} - -#[test] -fn test_parse_slice_type_and_indexing() { - let source = "let s: []u8 = arr[0..5];"; - let ast = parse(source); - assert_eq!( - ast, - vec![Expr::LetDef { - name: "s".to_string(), - mutable: false, - ty: Some(TrackType::Slice(Box::new(TrackType::U8))), - value: Box::new(Expr::SliceIndex { - target: Box::new(Expr::Variable("arr".to_string())), - start: Some(Box::new(Expr::IntLiteral(0))), - end: Some(Box::new(Expr::IntLiteral(5))), - }), - }] - ); -} - -#[test] -fn test_parse_struct_and_lens() { - let source = "let u = User { age: 30 }; with u -> user { user.set_age(31); }"; - let ast = parse(source); - assert_eq!(ast.len(), 2); - assert_eq!( - ast[0], - Expr::LetDef { - name: "u".to_string(), - mutable: false, - ty: None, - value: Box::new(Expr::StructInitialization { - ty_name: "User".to_string(), - fields: vec![("age".to_string(), Expr::IntLiteral(30))] - }) - } - ); - assert_eq!( - ast[1], - Expr::LensBlock { - target: "u".to_string(), - lens_name: "user".to_string(), - body: vec![Expr::FunctionCall { - name: "set_age".to_string(), - args: vec![Expr::Variable("user".to_string()), Expr::IntLiteral(31)] - }] - } - ); -} - -#[test] -fn test_parse_enum_and_union() { - let source = "enum Status: i32 { Active = 1, Inactive = 0 } union Value { Int(i32), Empty }"; - let ast = parse(source); - assert_eq!(ast.len(), 2); - assert_eq!( - ast[0], - Expr::EnumDef { - name: "Status".to_string(), - underlying_type: Some(TrackType::I32), - variants: vec![ - ("Active".to_string(), Some(Expr::IntLiteral(1))), - ("Inactive".to_string(), Some(Expr::IntLiteral(0))) - ] - } - ); - assert_eq!( - ast[1], - Expr::UnionDef { - name: "Value".to_string(), - variants: vec![ - ("Int".to_string(), Some(TrackType::I32)), - ("Empty".to_string(), None) - ] - } - ); -} - -#[test] -fn test_parse_match() { - let source = "match val { Value::Int(n) if n > 0 => print(n), _ => print(0) }"; - let ast = parse(source); - assert_eq!( - ast, - vec![Expr::Match { - target: Box::new(Expr::Variable("val".to_string())), - arms: vec![ - MatchArm { - pattern: Pattern::Variant { - enum_or_union: "Value".to_string(), - variant: "Int".to_string(), - bindings: vec![Pattern::Ident("n".to_string())], - }, - guard: Some(Expr::BinaryOp { - op: BinOp::Gt, - left: Box::new(Expr::Variable("n".to_string())), - right: Box::new(Expr::IntLiteral(0)), - }), - body: Expr::FunctionCall { - name: "print".to_string(), - args: vec![Expr::Variable("n".to_string())] - } - }, - MatchArm { - pattern: Pattern::Wildcard, - guard: None, - body: Expr::FunctionCall { - name: "print".to_string(), - args: vec![Expr::IntLiteral(0)] - } - } - ] - }] - ); -} - -#[test] -fn test_parse_macro_def_and_call() { - let source = "@macro bit(n: u32) -> u32 { return 1 << n; } let val = @bit(5);"; - let ast = parse(source); - assert_eq!(ast.len(), 2); - assert_eq!( - ast[0], - Expr::MacroDef { - name: "bit".to_string(), - params: vec![("n".to_string(), TrackType::U32)], - return_type: Some(TrackType::U32), - body: vec![Expr::Return { - value: Some(Box::new(Expr::BinaryOp { - op: BinOp::Shl, - left: Box::new(Expr::IntLiteral(1)), - right: Box::new(Expr::Variable("n".to_string())) - })) - }] - } - ); - assert_eq!( - ast[1], - Expr::LetDef { - name: "val".to_string(), - mutable: false, - ty: None, - value: Box::new(Expr::MacroCall { - name: "bit".to_string(), - args: vec![Expr::IntLiteral(5)], - body: None, - }) - } - ); -} - -#[test] -fn test_parse_use_and_const() { - let source = "import \"std/math\" as m :: { abs, max }; const PI = 3;"; - let ast = parse(source); - assert_eq!(ast.len(), 2); - assert_eq!( - ast[0], - Expr::Use { - path: "std/math".to_string(), - imports: Some(vec!["abs".to_string(), "max".to_string()]), - alias: Some("m".to_string()), - } - ); - - assert_eq!( - ast[1], - Expr::ConstDef { - name: "PI".to_string(), - value: Box::new(Expr::IntLiteral(3)) - } - ); -} - -#[test] -fn test_parse_array_type_and_literal() { - let source = "let arr: [i32; 3] = [1, 2, 3]; let x = arr[0];"; - let ast = parse(source); - assert_eq!(ast.len(), 2); - assert_eq!( - ast[0], - Expr::LetDef { - name: "arr".to_string(), - mutable: false, - ty: Some(TrackType::Array(Box::new(TrackType::I32), 3)), - value: Box::new(Expr::ArrayLiteral { - elements: vec![ - Expr::IntLiteral(1), - Expr::IntLiteral(2), - Expr::IntLiteral(3) - ] - }) - } - ); - assert_eq!( - ast[1], - Expr::LetDef { - name: "x".to_string(), - mutable: false, - ty: None, - value: Box::new(Expr::ArrayIndex { - target: Box::new(Expr::Variable("arr".to_string())), - index: Box::new(Expr::IntLiteral(0)) - }) - } - ); -} - -#[test] -fn test_parse_type_alias() { - let source = "type ByteBuf = []u8;"; - let ast = parse(source); - assert_eq!( - ast, - vec![Expr::TypeAlias { - name: "ByteBuf".to_string(), - target: TrackType::Slice(Box::new(TrackType::U8)), - }] - ); -} - -#[test] -fn test_parse_for_in_loop() { - let source = "for i in 0..10 { print(i); }"; - let ast = parse(source); - assert_eq!(ast.len(), 1); - assert!(matches!(ast[0], Expr::ForIn { .. })); -} - -#[test] -fn test_parse_use_statement() { - let source = "use \"std/io\" as io::{print, read_line};"; - let ast = parse(source); - assert_eq!(ast.len(), 1); - assert!(matches!(ast[0], Expr::Use { .. })); -} - -#[test] -fn test_parse_generic_fn_single_param() { - let source = "fn identity(x: T) -> T { return x; }"; - let ast = parse(source); - assert_eq!( - ast, - vec![Expr::FnDef { - name: "identity".to_string(), - generics: vec!["T".to_string()], - params: vec![("x".to_string(), TrackType::Custom("T".to_string()))], - return_type: Some(TrackType::Custom("T".to_string())), - body: vec![Expr::Return { - value: Some(Box::new(Expr::Variable("x".to_string()))) - }] - }] - ); -} - -#[test] -fn test_parse_generic_fn_multi_params() { - let source = "fn pair(a: T, b: U) -> (T, U) { return (a, b); }"; - let ast = parse(source); - assert_eq!(ast.len(), 1); - if let Expr::FnDef { - name, - generics, - params, - return_type, - .. - } = &ast[0] - { - assert_eq!(name, "pair"); - assert_eq!(generics, &vec!["T".to_string(), "U".to_string()]); - assert_eq!(params.len(), 2); - assert!(matches!(return_type, Some(TrackType::Tuple(_)))); - } else { - panic!("expected FnDef"); - } -} - -#[test] -fn test_parse_generic_fn_no_return() { - let source = "fn log(x: T) { print(x); }"; - let ast = parse(source); - assert!(matches!(&ast[0], Expr::FnDef { generics, .. } if generics == &vec!["T".to_string()])); -} diff --git a/tests/performance_tests.rs b/tests/performance_tests.rs deleted file mode 100644 index 2da7d94e..00000000 --- a/tests/performance_tests.rs +++ /dev/null @@ -1,73 +0,0 @@ -use std::time::Instant; -use track::compile_source; -use track::lexer::Lexer; -use track::parser::Parser; - -#[test] -fn test_performance_lexer_throughput() { - let statement = "let mut x: i64 = 100 + 200 * 300 / 400;\n"; - let large_source = statement.repeat(5000); // ~200,000 characters, ~75,000 tokens - - let start = Instant::now(); - let tokens = Lexer::tokenize(&large_source).unwrap(); - let elapsed = start.elapsed(); - - println!( - "Lexed {} tokens in {:?} ({:.2} million tokens/sec)", - tokens.len(), - elapsed, - (tokens.len() as f64 / 1_000_000.0) / elapsed.as_secs_f64() - ); - - assert!(tokens.len() >= 60_000); - assert!(elapsed.as_secs() < 5, "Lexer took too long!"); -} - -#[test] -fn test_performance_parser_throughput() { - let fn_def = "fn add(a: i32, b: i32) -> i32 { return a + b; }\n"; - let large_source = fn_def.repeat(1000); // 1,000 function definitions - - let tokens = Lexer::tokenize(&large_source).unwrap(); - let mut parser = Parser::new(tokens, large_source); - - let start = Instant::now(); - let program = parser.parse_program().unwrap(); - let elapsed = start.elapsed(); - - println!( - "Parsed {} functions in {:?} ({:.2} functions/sec)", - program.len(), - elapsed, - program.len() as f64 / elapsed.as_secs_f64() - ); - - assert_eq!(program.len(), 1000); - assert!(elapsed.as_secs() < 5, "Parser took too long!"); -} - -#[test] -fn test_performance_full_pipeline_throughput() { - // Distinct names: a repeated fn is error E0201 (duplicate definition). - let source: String = (0..500) - .map(|i| { - format!( - "fn compute{}(x: i32) -> i32 {{ let y = x + 1; return y * 2; }}\n", - i - ) - }) - .collect(); - - let start = Instant::now(); - let ast = compile_source(&source).unwrap(); - let elapsed = start.elapsed(); - - println!( - "Compiled and checked AST of {} statements in {:?}", - ast.len(), - elapsed - ); - - assert_eq!(ast.len(), 500); - assert!(elapsed.as_secs() < 5, "Pipeline took too long!"); -} diff --git a/tests/regression_tests.rs b/tests/regression_tests.rs deleted file mode 100644 index 297f4e1a..00000000 --- a/tests/regression_tests.rs +++ /dev/null @@ -1,144 +0,0 @@ -use track::compile_source; - -#[test] -fn test_regression_nested_expressions() { - let source = r#" - fn main() -> void { - let x: i64 = ((10 + 20) * (30 - 5)) / (2 % 1 + 5); - print(x); - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Failed to compile nested expression: {:?}", - res.err() - ); -} - -#[test] -fn test_regression_nested_if_else_chain() { - let source = r#" - fn classify(n: i32) -> i32 { - if n < 0 { - return -1; - } else if n == 0 { - return 0; - } else if n < 10 { - return 1; - } else { - return 2; - } - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Failed to compile nested if-else: {:?}", - res.err() - ); -} - -#[test] -fn test_regression_multiple_macro_calls() { - let source = r#" - @macro add_one(x: i32) -> i32 { - return x + 1; - } - - fn main() -> void { - let a = @add_one(10); - let b = @add_one(@add_one(20)); - print(a + b); - } - "#; - let res = compile_source(source); - assert!(res.is_ok(), "Failed macro regression test: {:?}", res.err()); -} - -#[test] -fn test_regression_complex_match_guards() { - let source = r#" - union Number { - Int(i32), - Big(i64), - Zero, - } - - fn check_num(n: Number) -> i32 { - match n { - Number::Int(val) if val > 100 => print(val), - Number::Int(val) => print(val), - Number::Big(val) => print(val), - Number::Zero => print(0), - _ => print(-1), - } - return 0; - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Failed match guards regression test: {:?}", - res.err() - ); -} - -#[test] -fn test_regression_nested_lens_blocks() { - let source = r#" - fn main() -> void { - let mut outer = Outer { inner: Inner { value: 42 } }; - with outer -> o { - with o -> i { - let v = i.value(); - } - } - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Failed nested lens regression test: {:?}", - res.err() - ); -} - -#[test] -fn test_regression_shadowed_variables() { - let source = r#" - fn main() -> void { - let x = 10; - if true { - let x = 20; - print(x); - } - print(x); - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Failed scope shadowing regression test: {:?}", - res.err() - ); -} - -#[test] -fn test_regression_top_level_variables_and_deref() { - let source = r#" - let x = 1; - let r = &x; - - fn main() -> void { - print("Hello, Track!"); - print(*r); - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Failed top-level variables regression test: {:?}", - res.err() - ); -} diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 00000000..94a33abf --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,163 @@ +#!/bin/bash +# Cargo-free test runner for Track (trackc, its runtimes, the native +# backend, the bootstrap and the tools). +# +# tests/run.sh [-j N] [-t SECS] [-k] [-l] [PATTERN...] +# +# -j N run N tests at once (default 1; TEST_JOBS) +# -t SECS per-test timeout (default 600; TEST_TIMEOUT) +# -k keep every test's scratch directory (failed ones are kept +# unless -K is given) +# -K keep nothing, not even a failed test's scratch +# -l list the tests and exit +# PATTERN run only tests whose id (suite/name) contains a PATTERN +# +# Tests are bash functions `t_` in tests/sh/.sh (helpers in +# tests/sh/lib.sh), all listed in tests/sh/ids.txt. Each runs in its own +# process under `timeout`, in an empty scratch directory. The runner prints +# one PASS/FAIL/TIMEOUT line per test, then a summary, and exits non-zero +# if any test failed. +# +# trackc under test: $TRACKC, else build/bootstrap/stage3/trackc (what +# scripts/bootstrap.sh leaves; BOOTSTRAP_DIR is honoured). Scratch goes +# under $TEST_TMP (default /tmp). Needs bash and POSIX tools only. +set -u + +here=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$here/.." && pwd) +export ROOT + +# --exec ID: the timed child; run one test function. +if [ "${1:-}" = --exec ]; then + id=$2 + suite=${id%%/*} + name=${id#*/} + # shellcheck source=/dev/null + . "$here/sh/lib.sh" + # shellcheck source=/dev/null + . "$here/sh/$suite.sh" + ulimit -c 0 2>/dev/null + cd "$T" || exit 1 + "t_$name" + exit $? +fi + +# --one ID: run ID under the timeout, print its line, record the verdict. +if [ "${1:-}" = --one ]; then + id=$2 + safe=$(printf '%s' "$id" | tr '/' '.') + T="$TEST_BASE/t/$safe" + rm -rf "$T" + mkdir -p "$T" + export T + log="$TEST_BASE/log/$safe.log" + start=$(date +%s) + timeout -k 10 "$TEST_TIMEOUT" bash "$0" --exec "$id" >"$log" 2>&1 + rc=$? + secs=$(($(date +%s) - start)) + if [ "$rc" = 0 ]; then + printf 'PASS %s (%ss)\n' "$id" "$secs" + grep '^SKIP:' "$log" | sed "s|^| |" + : >"$TEST_BASE/res/$safe.pass" + [ "$TEST_KEEP" = all ] || rm -rf "$T" + else + if [ "$rc" = 124 ] || [ "$rc" = 137 ]; then + printf 'TIMEOUT %s (after %ss)\n' "$id" "$secs" + else + printf 'FAIL %s (exit %s, %ss)\n' "$id" "$rc" "$secs" + fi + tail -n 40 "$log" | sed 's/^/ | /' + : >"$TEST_BASE/res/$safe.fail" + [ "$TEST_KEEP" = none ] && rm -rf "$T" + fi + exit 0 +fi + +jobs=${TEST_JOBS:-1} +TEST_TIMEOUT=${TEST_TIMEOUT:-600} +TEST_KEEP=failed +list=0 +while getopts 'j:t:kKlh' opt; do + case "$opt" in + j) jobs=$OPTARG ;; + t) TEST_TIMEOUT=$OPTARG ;; + k) TEST_KEEP=all ;; + K) TEST_KEEP=none ;; + l) list=1 ;; + h) sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) exit 2 ;; + esac +done +shift $((OPTIND - 1)) + +ids=$( + for f in "$here"/sh/*.sh; do + suite=$(basename "$f" .sh) + [ "$suite" = lib ] && continue + sed -n 's/^t_\([A-Za-z0-9_]*\)() *{.*/\1/p' "$f" | sed "s|^|$suite/|" + done +) +# tests/sh/ids.txt lists every test. A full run checks the suites against +# it, so a deleted or renamed test is reported instead of silently not run. +manifest="$here/sh/ids.txt" +manifest_diff="" +if [ $# -eq 0 ] && [ "$list" = 0 ]; then + found=$(printf '%s\n' "$ids" | LC_ALL=C sort) + want=$(LC_ALL=C sort "$manifest" 2>/dev/null) + gone=$(LC_ALL=C comm -13 <(printf '%s\n' "$found") <(printf '%s\n' "$want") | grep . || true) + extra=$(LC_ALL=C comm -23 <(printf '%s\n' "$found") <(printf '%s\n' "$want") | grep . || true) + [ -n "$gone" ] && manifest_diff="$manifest_diff$(printf '%s\n' "$gone" | sed 's/^/ in ids.txt, not in any suite: /') +" + [ -n "$extra" ] && manifest_diff="$manifest_diff$(printf '%s\n' "$extra" | sed 's/^/ in a suite, not in ids.txt: /') +" +fi +if [ $# -gt 0 ]; then + ids=$(printf '%s\n' "$ids" | while read -r id; do + for p in "$@"; do + case "$id" in *"$p"*) echo "$id"; break ;; esac + done + done) +fi +[ -n "$ids" ] || { echo "run.sh: no tests match" >&2; exit 2; } +if [ "$list" = 1 ]; then + printf '%s\n' "$ids" + exit 0 +fi + +if [ -z "${TRACKC:-}" ]; then + TRACKC="${BOOTSTRAP_DIR:-$ROOT/build/bootstrap}/stage3/trackc" +fi +case "$TRACKC" in /*) ;; *) TRACKC="$(pwd)/$TRACKC" ;; esac +[ -x "$TRACKC" ] || { echo "run.sh: no trackc at $TRACKC (run scripts/bootstrap.sh or set TRACKC)" >&2; exit 2; } +export TRACKC + +TEST_BASE=$(mktemp -d "${TEST_TMP:-/tmp}/track-tests.XXXXXX") +mkdir -p "$TEST_BASE/t" "$TEST_BASE/log" "$TEST_BASE/res" +# One runtime-object cache for the run (tests that check caching set their +# own TRACKC_CACHE). +TRACKC_CACHE=${TRACKC_CACHE:-$TEST_BASE/cache} +export TEST_BASE TEST_TIMEOUT TEST_KEEP TRACKC_CACHE + +n=$(printf '%s\n' "$ids" | wc -l) +echo "running $n tests with $TRACKC (-j $jobs, timeout ${TEST_TIMEOUT}s)" +start=$(date +%s) +printf '%s\n' "$ids" | xargs -P "$jobs" -I{} bash "$0" --one {} +secs=$(($(date +%s) - start)) + +pass=$(find "$TEST_BASE/res" -name '*.pass' | wc -l) +failed=$(find "$TEST_BASE/res" -name '*.fail' | sed 's|.*/||; s|\.fail$||' | LC_ALL=C sort) +nfail=$(printf '%s' "$failed" | grep -c . || true) +missing=$((n - pass - nfail)) +echo "---" +echo "$pass passed, $nfail failed, $missing missing, ${secs}s" +if [ -n "$manifest_diff" ]; then + echo "test list does not match tests/sh/ids.txt (regenerate: tests/run.sh -l > tests/sh/ids.txt):" + printf '%s' "$manifest_diff" +fi +if [ "$nfail" -gt 0 ] || [ "$missing" -gt 0 ] || [ -n "$manifest_diff" ]; then + printf '%s\n' "$failed" | grep . | sed 's/^/ failed: /' + [ "$TEST_KEEP" = none ] || echo "logs and failed scratch in $TEST_BASE" + exit 1 +fi +rm -rf "$TEST_BASE" +exit 0 diff --git a/tests/selfhost_tests.rs b/tests/selfhost_tests.rs deleted file mode 100644 index 57134fc2..00000000 --- a/tests/selfhost_tests.rs +++ /dev/null @@ -1,3084 +0,0 @@ -// Self-hosted compiler (compiler/) against the Rust bootstrap compiler. -// -// trackc is built once with `yard` (stage 1). The tests then check the -// bootstrap fixed point, that both compilers produce programs with the same -// observable behaviour, and that both checkers accept and reject the same -// programs. - -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::{Command, Output}; -use std::sync::OnceLock; - -fn repo() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) -} - -fn scratch(name: &str) -> PathBuf { - let dir = env::temp_dir().join(format!("track_selfhost_{}_{}", name, std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir -} - -/// Stage 1: trackc built by the Rust compiler. -fn trackc() -> &'static Path { - static TRACKC: OnceLock = OnceLock::new(); - TRACKC.get_or_init(|| { - let status = Command::new(env!("CARGO_BIN_EXE_yard")) - .arg("build") - .current_dir(repo().join("compiler")) - .output() - .expect("failed to run yard"); - assert!( - status.status.success(), - "yard build of compiler/ failed:\n{}{}", - String::from_utf8_lossy(&status.stdout), - String::from_utf8_lossy(&status.stderr) - ); - let built = repo().join("compiler/target/trackc"); - let copy = scratch("stage1").join("trackc"); - fs::copy(&built, ©).unwrap(); - copy - }) -} - -fn run_trackc(args: &[&str], cwd: &Path) -> Output { - Command::new(trackc()) - .args(args) - .current_dir(cwd) - .output() - .expect("failed to run trackc") -} - -#[test] -fn build_creates_missing_output_directories() { - let dir = scratch("newdir"); - let src = dir.join("x.trk"); - fs::write(&src, "fn main() -> void { print(7); }").unwrap(); - let exe = dir.join("some/new/dir/x"); - let out = run_trackc( - &["build", src.to_str().unwrap(), "-o", exe.to_str().unwrap()], - &dir, - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!(run_exe(&exe).0.trim(), "7"); - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn runtime_object_is_cached_and_builds_stay_identical() { - let dir = scratch("rtcache"); - let cache = dir.join("cache"); - let a = dir.join("a.trk"); - let b = dir.join("b.trk"); - fs::write(&a, "fn main() -> void { print(1); }").unwrap(); - fs::write(&b, "fn main() -> void { print(1); }").unwrap(); - let build = |src: &Path, exe: &Path| { - let out = Command::new(trackc()) - .args(["build", src.to_str().unwrap(), "-o", exe.to_str().unwrap()]) - .env("TRACKC_CACHE", &cache) - .current_dir(&dir) - .output() - .unwrap(); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - }; - let objects = || { - fs::read_dir(&cache) - .map(|d| { - d.filter(|e| { - e.as_ref() - .unwrap() - .path() - .extension() - .is_some_and(|x| x == "o") - }) - .count() - }) - .unwrap_or(0) - }; - build(&a, &dir.join("out1/a")); - assert_eq!(objects(), 1, "first build should store one runtime object"); - build(&a, &dir.join("out2/a")); - assert_eq!(objects(), 1, "second build should reuse it"); - assert!(fs::read(dir.join("out1/a")).unwrap() == fs::read(dir.join("out2/a")).unwrap()); - build(&b, &dir.join("out3/b")); - assert_eq!(objects(), 1); - assert_eq!(run_exe(&dir.join("out3/b")).0.trim(), "1"); - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn native_binaries_carry_a_symbol_table() { - if Command::new("nm").arg("--version").output().is_err() { - eprintln!("skipping: nm not found"); - return; - } - let dir = scratch("symbols"); - let src = dir.join("s.trk"); - // recursive, so the inliner keeps it out of line - fs::write( - &src, - "fn sum_down(n: i64) -> i64 {\n if n <= 0 {\n return 0;\n }\n return n + sum_down(n - 1);\n}\nfn main() -> void { print(sum_down(100)); }\n", - ) - .unwrap(); - let exe = dir.join("s"); - let out = run_trackc( - &[ - "build", - "--native", - "-g", - src.to_str().unwrap(), - "-o", - exe.to_str().unwrap(), - ], - &dir, - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!(run_exe(&exe).0.trim(), "5050"); - // without -g: the same loaded image, no sections - let plain = dir.join("plain"); - let out = run_trackc( - &[ - "build", - "--native", - src.to_str().unwrap(), - "-o", - plain.to_str().unwrap(), - ], - &dir, - ); - assert!(out.status.success()); - let (with, without) = (fs::read(&exe).unwrap(), fs::read(&plain).unwrap()); - assert!(with.len() > without.len()); - assert_eq!(with[64..176], without[64..176], "program headers differ"); - assert_eq!( - with[176..without.len()], - without[176..], - "loaded bytes differ" - ); - let nm = Command::new("nm").arg(&exe).output().unwrap(); - let text = String::from_utf8_lossy(&nm.stdout); - assert!( - nm.status.success(), - "nm failed: {}", - String::from_utf8_lossy(&nm.stderr) - ); - let has = |name: &str| { - text.lines().any(|l| { - let f: Vec<&str> = l.split_whitespace().collect(); - f.len() == 3 && f[1] == "T" && f[2] == name - }) - }; - for name in ["main", "sum_down", "_start"] { - assert!(has(name), "nm lacks T {}:\n{}", name, text); - } - let _ = fs::remove_dir_all(&dir); -} - -fn run_exe(exe: &Path) -> (String, Option) { - let out = Command::new(exe).output().unwrap(); - ( - String::from_utf8_lossy(&out.stdout).to_string(), - out.status.code(), - ) -} - -#[test] -fn bootstrap_reaches_a_fixed_point() { - let dir = scratch("bootstrap"); - for stage in ["stage2", "stage3"] { - fs::create_dir_all(dir.join(stage)).unwrap(); - } - let stage2 = dir.join("stage2/trackc"); - let stage3 = dir.join("stage3/trackc"); - let out = run_trackc( - &[ - "build", - "compiler/src/main.trk", - "-o", - stage2.to_str().unwrap(), - ], - &repo(), - ); - assert!( - out.status.success(), - "stage1 failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - let out = Command::new(&stage2) - .args([ - "build", - "compiler/src/main.trk", - "-o", - stage3.to_str().unwrap(), - ]) - .current_dir(repo()) - .output() - .unwrap(); - assert!( - out.status.success(), - "stage2 failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - - let c2 = fs::read(dir.join("stage2/trackc.c")).unwrap(); - let c3 = fs::read(dir.join("stage3/trackc.c")).unwrap(); - assert!(c2 == c3, "stage1 and stage2 emitted different C"); - let b2 = fs::read(&stage2).unwrap(); - let b3 = fs::read(&stage3).unwrap(); - assert!(b2 == b3, "stage2 and stage3 executables differ"); - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn examples_behave_the_same_under_both_compilers() { - let dir = scratch("examples"); - let mut examples: Vec = fs::read_dir(repo().join("examples")) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|e| e == "trk")) - .collect(); - examples.sort(); - assert!(!examples.is_empty()); - for example in examples { - let stem = example.file_stem().unwrap().to_string_lossy().to_string(); - let host = track::build_file_in_dir(example.to_str().unwrap(), &dir); - let native_exe = dir.join(format!("{}_native", stem)); - let native = run_trackc( - &[ - "build", - example.to_str().unwrap(), - "-o", - native_exe.to_str().unwrap(), - ], - &dir, - ); - if stem.ends_with("_err") { - assert!( - host.is_err(), - "{}: host compiler accepted a rejection test", - stem - ); - assert!( - !native.status.success(), - "{}: trackc accepted a rejection test", - stem - ); - continue; - } - let host_exe = host.unwrap_or_else(|e| panic!("{}: host build failed: {}", stem, e)); - assert!( - native.status.success(), - "{}: trackc build failed: {}", - stem, - String::from_utf8_lossy(&native.stderr) - ); - assert_eq!( - run_exe(&host_exe), - run_exe(&native_exe), - "{}: behaviour differs", - stem - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// (name, source, accepted). Both checkers must agree with the expectation. -const VERDICTS: &[(&str, &str, bool)] = &[ - ( - "move_then_use", - "fn main() -> void { let s = str_concat(\"a\", \"b\"); let t = s; print(s); }", - false, - ), - ( - "copy_ints", - "fn main() -> void { let a: i64 = 1; let b = a; print(a); print(b); }", - true, - ), - ( - "borrow_does_not_move", - "fn f(x: &Str) -> i64 { return 0; } fn main() -> void { let s = str_concat(\"a\", \"b\"); f(&s); print(s); }", - true, - ), - ( - "frozen_by_reference", - "fn main() -> void { let s = str_concat(\"a\", \"b\"); let r = &s; let t = s; }", - false, - ), - ( - "lens_locks_target", - "fn main() -> void { let mut v = vec_init(4); with v -> l { let w = v; } }", - false, - ), - ( - "lens_cannot_escape", - "fn main() -> void { let mut v = vec_init(4); with v -> l { let w = l; } }", - false, - ), - ( - "inconsistent_if", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); if true { eat(s); } else { } }", - false, - ), - ( - "consistent_if", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); if true { eat(s); } else { eat(s); } }", - true, - ), - ( - "consume_in_loop", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); let mut i: i64 = 0; while i < 3 { eat(s); i = i + 1; } }", - false, - ), - ( - "return_local_ref", - "fn f() -> &i64 { let x = 5; return &x; }", - false, - ), - ( - "return_param_ref", - "fn f(x: &i64) -> &i64 { return x; }", - true, - ), - ( - "immutable_assign", - "fn main() -> void { let x = 1; x = 2; }", - false, - ), - ( - "mutable_assign", - "fn main() -> void { let mut x = 1; x = 2; print(x); }", - true, - ), - ( - "mut_does_not_leak_across_functions", - "fn a() -> void { let mut x = 1; x = 2; } fn b() -> void { let x = 1; x = 3; }", - false, - ), - ( - "shadowed_binding_is_immutable", - "fn main() -> void { let mut x = 1; let x = 2; x = 3; }", - false, - ), - ("assign_undeclared", "fn main() -> void { y = 3; }", false), - ( - "undeclared_use", - "fn main() -> void { print(nope); }", - false, - ), - ( - "forbidden_free", - "fn main() -> void { let s = str_concat(\"a\", \"b\"); str_free(s); }", - false, - ), - ( - "typo_suggestion", - "fn compute() -> i64 { return 1; } fn main() -> void { print(computee()); }", - false, - ), - ( - "tuple_index_bounds", - "fn main() -> void { let t = (1, 2); print(t.2); }", - false, - ), - ( - "const_before_use", - "fn main() -> void { print(LIMIT); } const LIMIT = 10;", - true, - ), - ( - "compile_error_macro", - "fn main() -> void { @compile_error(\"stop\"); }", - false, - ), - ( - "struct_field_update", - "struct P { x: i64 } fn main() -> void { let mut p = P { x: 1 }; p.x = 2; print(p.x); }", - true, - ), - ( - "immutable_field_update", - "struct P { x: i64 } fn main() -> void { let p = P { x: 1 }; p.x = 2; }", - false, - ), - ( - "lens_field_update", - "struct P { x: i64 } fn main() -> void { let mut p = P { x: 1 }; with p -> l { l.x = 5; } print(p.x); }", - true, - ), - ( - "unknown_struct_field", - "struct P { x: i64 } fn main() -> void { let p = P { z: 1 }; }", - false, - ), - ( - "unknown_field_access", - "struct P { x: i64 } fn main() -> void { let p = P { x: 1 }; print(p.q); }", - false, - ), - ( - "array_moved_by_value", - "fn main() -> void { let a = [1, 2]; let n = array_len(a); print(a[0]); }", - false, - ), - ( - "array_index_update", - "fn main() -> void { let mut a = [1, 2]; a[1] = 7; print(a[1]); }", - true, - ), - // Branch merges only revisit slots a branch wrote (undo-log checker). - ( - "shadow_in_then_keeps_outer", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); if true { let s = 1; } else { eat(s); } }", - false, - ), - ( - "if_inside_loop_consumes", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); let mut i: i64 = 0; while i < 3 { if i == 1 { eat(s); } else { eat(s); } i = i + 1; } }", - false, - ), - ( - "nested_if_second_resource", - "fn eat(s: Str) -> void { } fn main() -> void { let a = str_concat(\"a\", \"b\"); let b = str_concat(\"a\", \"b\"); if true { eat(b); eat(a); } else { if false { eat(a); } else { eat(a); } } }", - false, - ), - ( - "global_const_spent_in_branch", - "const K = \"hi\"; fn main() -> void { if true { let a = K; } else { } }", - false, - ), - ( - "reassign_after_move_in_loop", - "fn eat(s: Str) -> void { } fn main() -> void { let mut s = str_concat(\"a\", \"b\"); let mut i: i64 = 0; while i < 2 { eat(s); s = str_concat(\"x\", \"y\"); i = i + 1; } }", - true, - ), -]; - -#[test] -fn checkers_agree_on_accepted_and_rejected_programs() { - let dir = scratch("verdicts"); - for (name, source, accepted) in VERDICTS { - let host = track::compile_source(source); - assert_eq!( - host.is_ok(), - *accepted, - "{}: host verdict: {:?}", - name, - host.err() - ); - let file = dir.join(format!("{}.trk", name)); - fs::write(&file, source).unwrap(); - let native = run_trackc(&["check", file.to_str().unwrap()], &dir); - assert_eq!( - native.status.success(), - *accepted, - "{}: trackc verdict: {}", - name, - String::from_utf8_lossy(&native.stderr) - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// A constant `/` or `%` that would trap (zero divisor, INT64_MIN / -1) is -/// the same E0200 in both checkers; trackc must not fold it (SIGFPE). -#[test] -fn const_divrem_traps_are_e0200_in_both_checkers() { - let dir = scratch("const_divrem"); - let min = "const M = 0 - 9223372036854775807 - 1;"; - let cases = [ - ( - "div_min", - format!("{} const Q = M / (0 - 1);", min), - Some("division overflow"), - ), - ( - "mod_min", - format!("{} const Q = M % (0 - 1);", min), - Some("division overflow"), - ), - ( - "div_zero", - "const Q = 7 / 0;".to_string(), - Some("division by zero"), - ), - ( - "mod_zero", - "const Q = 7 % (1 - 1);".to_string(), - Some("division by zero"), - ), - ("div_ok", format!("{} const Q = M / 2 + M % 3;", min), None), - ( - "div_cmp_zero", - "const Q = 7 / (1 == 2);".to_string(), - Some("division by zero"), - ), - ( - "mod_not_zero", - "const Q = 7 % !1;".to_string(), - Some("division by zero"), - ), - ("div_cmp_ok", "const Q = 7 / (1 < 2);".to_string(), None), - ( - "div_named_cmp_zero", - "const Z = 1 == 2; const Q = 7 / Z;".to_string(), - Some("division by zero"), - ), - ( - "mod_named_not_zero", - "const Z = !(3 > 2); const Q = 7 % (Z + Z);".to_string(), - Some("division by zero"), - ), - ( - "div_named_cmp_ok", - "const Z = 1 != 2; const Q = 7 / Z;".to_string(), - None, - ), - ( - "div_variant_zero", - "enum E { Z, O } const Q = 7 / E::Z;".to_string(), - Some("division by zero"), - ), - ( - "div_variant_ok", - "enum E { Z, O } const Q = 7 / E::O;".to_string(), - None, - ), - ( - "div_variant_named_cmp_ok", - "const ONE = 1 < 2; enum E { A = ONE } const Q = 7 / E::A;".to_string(), - None, - ), - ( - "div_variant_after_cmp_zero", - "const NO = 2 < 1; enum E { A = NO, B } const Q = 7 / E::A;".to_string(), - Some("division by zero"), - ), - ( - "div_variant_next_ok", - "const NO = 2 < 1; enum E { A = NO, B } const Q = 7 / E::B;".to_string(), - None, - ), - ( - "enum_named_cmp_zero", - "const Z = 2 < 1; enum E { A = 7 / Z } const Q = 1;".to_string(), - Some("division by zero"), - ), - ( - "enum_div_zero", - "enum E { A, B = 7 / 0, C } const Q = 1;".to_string(), - Some("division by zero"), - ), - ( - "enum_div_min", - format!("{} enum E {{ A = M / (0 - 1) }} const Q = 1;", min), - Some("division overflow"), - ), - ]; - for (name, consts, err) in cases { - let source = format!("{} fn main() -> void {{ print(Q); }}", consts); - let want = err.map(|e| format!("error[E0200]: {} in a constant expression", e)); - let host = track::compile_source(&source); - match &want { - Some(w) => assert!( - host.as_ref().is_err_and(|e| e.contains(w.as_str())), - "{}: host: {:?}", - name, - host.err() - ), - None => assert!(host.is_ok(), "{}: host: {:?}", name, host.err()), - } - let file = dir.join(format!("{}.trk", name)); - fs::write(&file, &source).unwrap(); - let native = run_trackc(&["check", file.to_str().unwrap()], &dir); - let stderr = String::from_utf8_lossy(&native.stderr); - match &want { - Some(w) => assert!( - native.status.code() == Some(1) && stderr.starts_with(w.as_str()), - "{}: trackc: {:?}\n{}", - name, - native.status, - stderr - ), - None => assert!(native.status.success(), "{}: trackc: {}", name, stderr), - } - } - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn diagnostics_point_at_the_source() { - let dir = scratch("diagnostics"); - let file = dir.join("moved.trk"); - fs::write( - &file, - "fn main() -> void {\n let s = str_concat(\"a\", \"b\");\n let t = s;\n print(s);\n}\n", - ) - .unwrap(); - let out = run_trackc(&["check", "moved.trk"], &dir); - assert!(!out.status.success()); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.starts_with( - "error[E0200]: Use-after-free! Resource 's' is already spent.\n --> moved.trk:4:11\n" - ), - "unexpected diagnostic:\n{}", - stderr - ); - assert!( - stderr.contains("4 | print(s);"), - "missing source frame:\n{}", - stderr - ); - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn native_test_suite_passes_under_trackc() { - let compiler = repo().join("compiler"); - let mut tests: Vec = fs::read_dir(compiler.join("tests")) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|e| e == "trk")) - .collect(); - tests.sort(); - for test in tests { - let rel = test - .strip_prefix(&compiler) - .unwrap() - .to_str() - .unwrap() - .to_string(); - let out = run_trackc(&["run", &rel], &compiler); - assert!( - out.status.success(), - "{} failed under trackc:\n{}{}", - rel, - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - } -} - -/// Build `src` with trackc once per runtime and return both runs. -fn run_under_both_runtimes( - dir: &Path, - stem: &str, - src: &Path, -) -> ((String, Option), (String, Option)) { - let c_exe = dir.join(format!("{}_crt", stem)); - let t_exe = dir.join(format!("{}_trt", stem)); - let out = run_trackc( - &[ - "build", - src.to_str().unwrap(), - "-o", - c_exe.to_str().unwrap(), - ], - dir, - ); - assert!( - out.status.success(), - "{}: build failed: {}", - stem, - String::from_utf8_lossy(&out.stderr) - ); - let out = run_trackc( - &[ - "build", - "--rt=track", - src.to_str().unwrap(), - "-o", - t_exe.to_str().unwrap(), - ], - dir, - ); - assert!( - out.status.success(), - "{}: --rt=track build failed: {}{}", - stem, - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - (run_exe(&c_exe), run_exe(&t_exe)) -} - -/// The Track runtime (compiler/rt/*.trk) links without libc and behaves -/// like runtime/track_runtime.c on the examples and the runtime smoke test. -#[test] -fn track_runtime_matches_the_c_runtime() { - let dir = scratch("trackrt"); - let mut programs: Vec = fs::read_dir(repo().join("examples")) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|e| e == "trk")) - .filter(|p| { - let s = p.file_stem().unwrap().to_string_lossy().to_string(); - !s.ends_with("_err") && s != "net_demo" - }) - .collect(); - programs.push(repo().join("compiler/rt/tests/rt_smoke.trk")); - for name in [ - "rt_alloc", - "rt_alloc_nz", - "rt_memlimit", - "rt_memlimit_realloc", - "rt_lcache", - "rt_memlimit_lcache", - "sb_spare", - ] { - programs.push(repo().join(format!("tests/native/{}.trk", name))); - } - programs.sort(); - for program in programs { - let stem = program.file_stem().unwrap().to_string_lossy().to_string(); - let (c, t) = run_under_both_runtimes(&dir, &stem, &program); - assert_eq!(c, t, "{}: behaviour differs between runtimes", stem); - } - let _ = fs::remove_dir_all(&dir); -} - -/// A program without `main` runs its top-level statements under both -/// runtimes (the Track runtime's rt_start calls the synthetic main). -#[test] -fn program_without_main_runs_on_both_runtimes() { - let dir = scratch("trackrt_nomain"); - let src = dir.join("nomain.trk"); - fs::write(&src, "let x = 41;\nprint(x + 1);\n").unwrap(); - let (c, t) = run_under_both_runtimes(&dir, "nomain", &src); - assert_eq!(c, ("42\n".to_string(), Some(0))); - assert_eq!(c, t, "behaviour differs between runtimes"); - let _ = fs::remove_dir_all(&dir); -} - -/// trackc linked against the Track runtime (no libc) compiles the compiler -/// to the same C as trackc on the C runtime. -#[test] -fn trackc_on_the_track_runtime_self_compiles() { - let dir = scratch("trackrt_self"); - for stage in ["rt", "a", "b"] { - fs::create_dir_all(dir.join(stage)).unwrap(); - } - let rt_trackc = dir.join("rt/trackc"); - let out = run_trackc( - &[ - "build", - "--rt=track", - "compiler/src/main.trk", - "-o", - rt_trackc.to_str().unwrap(), - ], - &repo(), - ); - assert!( - out.status.success(), - "--rt=track build of trackc failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - let elf = fs::read(&rt_trackc).unwrap(); - assert!( - !elf.windows(7).any(|w| w == b"libc.so"), - "trackc on the Track runtime must not link libc" - ); - let a_exe = dir.join("a/trackc"); - let out = run_trackc( - &[ - "build", - "compiler/src/main.trk", - "-o", - a_exe.to_str().unwrap(), - ], - &repo(), - ); - assert!(out.status.success()); - let b_exe = dir.join("b/trackc"); - let out = Command::new(&rt_trackc) - .args([ - "build", - "compiler/src/main.trk", - "-o", - b_exe.to_str().unwrap(), - ]) - .current_dir(repo()) - .output() - .unwrap(); - assert!( - out.status.success(), - "trackc on the Track runtime failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - let a = fs::read(dir.join("a/trackc.c")).unwrap(); - let b = fs::read(dir.join("b/trackc.c")).unwrap(); - assert!(a == b, "trackc on the Track runtime emitted different C"); - let _ = fs::remove_dir_all(&dir); -} - -// L2 warnings channel, driven by real lifecycle warnings (L6): two unused -// bindings, so the output also shows that diagnostics are sorted by position. -#[test] -fn warnings_print_sorted_and_only_deny_warnings_fails() { - let dir = scratch("warnings"); - let src = dir.join("w.trk"); - fs::write( - &src, - "fn helper() -> i64 { let a = 1; return 2; }\nfn main() -> void { let b = 3; print(helper()); }\n", - ) - .unwrap(); - let path = src.to_str().unwrap(); - let at = |stderr: &str, needle: &str| stderr.find(needle).unwrap_or(usize::MAX); - - for args in [ - vec!["check", path], - vec!["build", path], - vec!["build", "--native", path], - ] { - let out = run_trackc(&args, &dir); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "{:?}: {}", args, stderr); - assert_eq!( - stderr.matches("warning[W0301]").count(), - 2, - "{:?}: {}", - args, - stderr - ); - assert!( - at(&stderr, "w.trk:1:") < at(&stderr, "w.trk:2:"), - "{:?}: warnings not sorted by position:\n{}", - args, - stderr - ); - } - let out = run_trackc(&["check", path], &dir); - assert!( - String::from_utf8_lossy(&out.stdout).contains("(2 warnings)"), - "{}", - String::from_utf8_lossy(&out.stdout) - ); - - let out = run_trackc(&["run", path], &dir); - assert_eq!(out.status.code(), Some(0)); - assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "2"); - assert!(String::from_utf8_lossy(&out.stderr).contains("warning[W0301]")); - - // --deny-warnings in any position turns warnings into a failure. - for args in [ - vec!["check", "--deny-warnings", path], - vec!["check", path, "--deny-warnings"], - vec!["build", "--native", path, "--deny-warnings"], - vec!["run", "--deny-warnings", path], - ] { - let out = run_trackc(&args, &dir); - let stderr = String::from_utf8_lossy(&out.stderr); - assert_eq!(out.status.code(), Some(1), "{:?}: {}", args, stderr); - assert!(stderr.contains("warning[W0301]"), "{:?}: {}", args, stderr); - } - - // `_`-prefixed names are silent, and --deny-warnings then passes. - let quiet = dir.join("quiet.trk"); - fs::write( - &quiet, - "fn helper() -> i64 { let _a = 1; return 2; }\nfn main() -> void { print(helper()); }\n", - ) - .unwrap(); - let out = run_trackc(&["check", "--deny-warnings", quiet.to_str().unwrap()], &dir); - assert!(out.status.success()); - assert!(!String::from_utf8_lossy(&out.stderr).contains("warning")); - - // A pending warning and an error print together, sorted by position. - let bad = dir.join("bad.trk"); - fs::write( - &bad, - "fn first() -> i64 { let u = 1; return 0; }\nfn main() -> void {\n print(nope);\n}\n", - ) - .unwrap(); - let out = run_trackc(&["check", bad.to_str().unwrap()], &dir); - let stderr = String::from_utf8_lossy(&out.stderr); - assert_eq!(out.status.code(), Some(1), "{}", stderr); - let _ = fs::remove_dir_all(&dir); -} - -/// Lifecycle warnings W0301-W0305 (card L6, docs/lifecycles.md §2): each -/// docs/lifecycles/wN example gives exactly its warning, with the §2 text, -/// exits 0, and fails under --deny-warnings. -#[test] -fn lifecycle_warnings_match_the_catalogue() { - let root = repo(); - let cases = [ - ( - "w1_fresh_unread", - "warning[W0301]: 'origin' is created and never read; remove it or name it '_origin'.", - ), - ( - "w2_write_only", - "warning[W0302]: write to 'p.y' is never read; 'p' ends at line 7.", - ), - ( - "w3_mutated_unread", - "warning[W0303]: 'bump' mutates 'c', but 'c' is never read afterwards.", - ), - ( - "w4_discarded_result", - "warning[W0304]: result of 'vadd' is discarded, and 'vadd' has no other effect (it only reads its parameters and returns a fresh value).", - ), - ( - "w5_consume_only_reads", - "warning[W0305]: 'norm1' takes 'p' by value but only reads it; take '&Point' so callers keep it.", - ), - ]; - for (stem, want) in cases { - let rel = format!("docs/lifecycles/{}.trk", stem); - let out = run_trackc(&["check", &rel], &root); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "{}: {}", rel, stderr); - assert!( - stderr.contains(want), - "{}: want {:?}, got:\n{}", - rel, - want, - stderr - ); - assert_eq!(stderr.matches("warning[").count(), 1, "{}: {}", rel, stderr); - let out = run_trackc(&["check", "--deny-warnings", &rel], &root); - assert_eq!(out.status.code(), Some(1), "{}", rel); - } - // Near misses stay warning-free. - let dir = scratch("lifewarn"); - let clean = [ - // read after the write - "struct P { x: i64, y: i64 }\nfn main() -> void { let mut p = P { x: 1, y: 2 }; p.y = 9; print(p.y); }\n", - // mutated, then read - "struct C { n: i64 }\nfn bump(c: &C) -> i64 { with c -> l { l.n = l.n + 1; } return 0; }\nfn main() -> void { let c = C { n: 0 }; bump(&c); print(c.n); }\n", - // pure result used - "struct V { x: i64 }\nfn mk(a: &V) -> V { return V { x: a.x }; }\nfn main() -> void { let a = V { x: 1 }; let b = mk(&a); print(b.x); }\n", - // by-value parameter handed back - "struct P { x: i64 }\nfn get(p: &P) -> i64 { return p.x; }\nfn eat(p: P) -> P { return p; }\nfn main() -> void { let p = P { x: 1 }; print(get(&p)); let q = eat(p); print(q.x); }\n", - // a write read on the next loop iteration - "struct P { x: i64 }\nfn main() -> void { let mut p = P { x: 0 }; let mut i = 0; while i < 3 { print(p.x); p.x = i; i = i + 1; } }\n", - // a discarded call with an effect - "struct V { x: i64 }\nfn show(a: &V) -> V { print(a.x); return V { x: a.x }; }\nfn main() -> void { let a = V { x: 1 }; show(&a); }\n", - ]; - for (i, src) in clean.iter().enumerate() { - let f = dir.join(format!("clean{}.trk", i)); - fs::write(&f, src).unwrap(); - let out = run_trackc(&["check", f.to_str().unwrap()], &dir); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "clean{}: {}", i, stderr); - assert!(!stderr.contains("warning["), "clean{}: {}", i, stderr); - } - let _ = fs::remove_dir_all(&dir); -} - -/// examples/ is warning-free except two intended demonstrations: an unused -/// allocation that is auto-freed, and a struct pattern match on a by-value -/// parameter. -#[test] -fn examples_warn_only_where_intended() { - let root = repo(); - let intended = [ - ("linear_auto_free.trk", "warning[W0301]: 'buf'"), - ("structs_arrays.trk", "warning[W0305]: 'quadrant'"), - ]; - let mut files: Vec = fs::read_dir(root.join("examples")) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|x| x == "trk")) - .collect(); - files.sort(); - for file in files { - let name = file.file_name().unwrap().to_str().unwrap().to_string(); - let rel = format!("examples/{}", name); - let out = run_trackc(&["check", &rel], &root); - let stderr = String::from_utf8_lossy(&out.stderr); - let want: Vec<&str> = intended - .iter() - .filter(|(f, _)| *f == name) - .map(|(_, w)| *w) - .collect(); - assert_eq!( - stderr.matches("warning[").count(), - want.len(), - "{}: {}", - rel, - stderr - ); - for w in want { - assert!(stderr.contains(w), "{}: want {:?}: {}", rel, w, stderr); - } - } -} - -/// The compiler's own sources stay warning-clean (CI runs the same check). -#[test] -fn compiler_sources_are_warning_clean() { - let out = run_trackc( - &["check", "--deny-warnings", "compiler/src/main.trk"], - &repo(), - ); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); -} - -/// (name, source, accepted) for trackc alone: holes the review found where -/// the Rust checker is also wrong (or differs) and trackc must be right. -const TRACKC_VERDICTS: &[(&str, &str, bool)] = &[ - ( - "generic_param_is_linear", - "fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { let t = dup(str_concat(\"a\", \"b\")); print(t.0); }", - false, - ), - ( - "generic_param_used_once", - "fn id(x: T) -> T { return x; } fn main() -> void { let s = id(str_concat(\"a\", \"b\")); print(s); print(id(3)); }", - true, - ), - // Generics are checked per instantiation: T is Copy when bound to i64. - ( - "generic_dup_of_copy_type", - "fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { let t = dup(3); print(t.0); }", - true, - ), - ( - "generic_twice_of_copy_type", - "fn twice(x: T) -> T { let a = x; let b = x; return b; } fn main() -> void { let n: i64 = 4; print(twice(n)); }", - true, - ), - ( - "generic_twice_of_linear_type", - "fn twice(x: T) -> T { let a = x; let b = x; return b; } fn main() -> void { let s = str_concat(\"a\", \"b\"); print(twice(s)); }", - false, - ), - ( - "generic_both_instantiations_checked", - "fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { let t = dup(3); print(t.0); let u = dup(str_concat(\"a\", \"b\")); print(u.0); }", - false, - ), - ( - "generic_nested_instantiation_linear", - "fn dup(x: T) -> (T, T) { return (x, x); } fn wrap(y: U) -> (U, U) { return dup(y); } fn main() -> void { let t = wrap(str_concat(\"a\", \"b\")); print(t.0); }", - false, - ), - ( - "generic_nested_instantiation_copy", - "fn dup(x: T) -> (T, T) { return (x, x); } fn wrap(y: U) -> (U, U) { return dup(y); } fn main() -> void { let t = wrap(7); print(t.1); }", - true, - ), - ( - "generic_pick_with_early_return", - "fn pick(c: bool, a: T, b: T) -> T { if c { return a; } return b; } fn main() -> void { let x: i64 = 1; let y: i64 = 2; print(pick(true, x, y)); print(x + y); }", - true, - ), - ( - "generic_max_of_copy_type", - "fn mx(a: T, b: T) -> T { if a > b { return a; } return b; } fn main() -> void { print(mx(3, 9)); }", - true, - ), - ( - "generic_max_of_linear_type", - "fn mx(a: T, b: T) -> T { if a > b { return a; } return b; } fn main() -> void { let s = mx(str_concat(\"a\", \"b\"), str_concat(\"c\", \"d\")); print(s); }", - true, - ), - ( - "unused_generic_checked_linear", - "fn dup(x: T) -> (T, T) { return (x, x); } fn main() -> void { print(1); }", - false, - ), - // A branch that returns does not take part in the state merge. - ( - "returning_then_branch_skips_merge", - "fn eat(s: Str) -> void { } fn f(s: Str, c: bool) -> i64 { if c { eat(s); return 1; } eat(s); return 0; } fn main() -> void { print(f(str_concat(\"a\", \"b\"), true)); }", - true, - ), - ( - "returning_else_branch_skips_merge", - "fn eat(s: Str) -> void { } fn f(s: Str, c: bool) -> i64 { if c { print(1); } else { eat(s); return 0; } eat(s); return 1; } fn main() -> void { print(f(str_concat(\"a\", \"b\"), true)); }", - true, - ), - ( - "returning_else_keeps_then_state", - "fn eat(s: Str) -> void { } fn f(s: Str, c: bool) -> i64 { if c { eat(s); } else { return 0; } eat(s); return 1; } fn main() -> void { print(f(str_concat(\"a\", \"b\"), true)); }", - false, - ), - ( - "returning_branch_in_loop", - "fn eat(s: Str) -> void { } fn f(s: Str) -> i64 { let mut i = 0; while i < 3 { if i == 2 { eat(s); return i; } i = i + 1; } eat(s); return 0; } fn main() -> void { print(f(str_concat(\"a\", \"b\"))); }", - true, - ), - ( - "aborting_branch_skips_merge", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); let c = true; if c { eat(s); } else { abort(\"no\"); } print(1); }", - true, - ), - ( - "returning_match_arm_skips_merge", - "fn eat(s: Str) -> void { } fn g(s: Str) -> i64 { return 1; } fn f(s: Str, k: i64) -> i64 { match k { 1 => return g(s), _ => print(0), } eat(s); return 0; } fn main() -> void { print(f(str_concat(\"a\", \"b\"), 1)); }", - true, - ), - ( - "const_div_by_zero", - "const D = 7 / 0; fn main() -> void { print(D); }", - false, - ), - ( - "const_mod_by_zero", - "const D = 7 % 0; fn main() -> void { print(D); }", - false, - ), - ( - "const_not_constant", - "fn f() -> i64 { return 1; } const D = f(); fn main() -> void { print(D); }", - false, - ), - ( - "const_cycle", - "const A = B; const B = A; fn main() -> void { print(A); }", - false, - ), - ( - "arity_too_few", - "fn f(a: i64, b: i64) -> i64 { return a + b; } fn main() -> void { print(f(1)); }", - false, - ), - ( - "arity_too_many", - "fn f(a: i64) -> i64 { return a; } fn main() -> void { print(f(1, 2)); }", - false, - ), - ( - "arity_builtin", - "fn main() -> void { print(str_concat(\"a\")); }", - false, - ), - ( - "destructure_int", - "fn main() -> void { let (a, b) = 1; print(a); }", - false, - ), - ( - "tuple_index_on_int", - "fn main() -> void { let x = 1; print(x.0); }", - false, - ), - ( - "index_on_int", - "fn main() -> void { let x = 1; print(x[0]); }", - false, - ), - ( - "destructure_too_many", - "fn main() -> void { let t = (1, 2); let (a, b, c) = t; print(c); }", - false, - ), - ( - "consume_in_match_arm", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); let k = 1; match k { 1 => eat(s), _ => print(0), } print(s); }", - false, - ), - ( - "consume_in_while_cond", - "fn eat(s: Str) -> bool { return true; } fn main() -> void { let s = str_concat(\"a\", \"b\"); while eat(s) { print(1); return; } }", - false, - ), - ( - "wrong_struct_ref", - "struct A { x: i64, y: i64 } struct B { y: i64, z: i64, x: i64 } fn gx(p: &A) -> i64 { return p.x; } fn main() -> void { let b = B { y: 20, z: 30, x: 10 }; print(gx(&b)); }", - false, - ), - ( - "right_struct_ref", - "struct A { x: i64, y: i64 } fn gx(p: &A) -> i64 { return p.x; } fn main() -> void { let a = A { x: 1, y: 2 }; print(gx(&a)); }", - true, - ), - // A guard that consumes runs before the arm body, so its spends count - // even when the body diverges (and on the fall-through to later arms). - ( - "guard_consumes_on_diverging_arm", - "fn eatb(s: Str) -> bool { return true; } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { 1 if eatb(s) => return 1, _ => print(0), } print(s); return 0; } fn main() -> void { print(f(1)); }", - false, - ), - // L5b: a guard's spends happen only where its pattern matched; arm `2` cannot overlap `1`. - ( - "guard_spend_skips_disjoint_literal_arm", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { 1 if eatb(s) => return 1, 2 => return eatr(s), _ => return 0, } } fn main() -> void { print(f(2)); }", - true, - ), - // s is spent on k==1 paths and live on the others. - ( - "guard_spend_inconsistent_after_match", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { 1 if eatb(s) => print(1), _ => print(0), } return 0; } fn main() -> void { print(f(1)); }", - false, - ), - // the guard-failed path reaches `_` with s already spent. - ( - "guard_spend_wild_arm_use_after_free", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { 1 if eatb(s) => return 1, _ => return eatr(s), } } fn main() -> void { print(f(1)); }", - false, - ), - // distinct enum variants cannot overlap. - ( - "guard_spend_disjoint_enum_variant", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } enum C { R, G, B } fn f(k: C) -> i64 { let s = str_concat(\"a\", \"b\"); match k { C::R if eatb(s) => return 1, C::G => return eatr(s), _ => return 0, } } fn main() -> void { print(f(C::G)); }", - true, - ), - // the same variant overlaps: guard-failed path has s spent. - ( - "guard_spend_same_enum_variant", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } enum C { R, G, B } fn f(k: C) -> i64 { let s = str_concat(\"a\", \"b\"); match k { C::R if eatb(s) => return 1, C::R => return eatr(s), _ => return 0, } } fn main() -> void { print(f(C::R)); }", - false, - ), - // a guard on an irrefutable pattern runs on every path to later arms, - // so s is spent on every way out: consistent. - ( - "guard_spend_irrefutable_always_spent", - "fn eatb(s: Str) -> bool { return true; } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { x if eatb(s) => return 1, _ => print(0), } return 0; } fn main() -> void { print(f(1)); }", - true, - ), - // ... and s is gone after the match. - ( - "guard_spend_irrefutable_use_after", - "fn eatb(s: Str) -> bool { return true; } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { x if eatb(s) => return 1, _ => print(0), } print(s); return 0; } fn main() -> void { print(f(1)); }", - false, - ), - // a binding pattern overlaps everything. - ( - "guard_spend_binding_then_use", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { x if eatb(s) => return x, y => return eatr(s), } } fn main() -> void { print(f(1)); }", - false, - ), - // a guard that only reads spends nothing. - ( - "guard_read_only_then_use", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat(s: Str) -> void { } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); match k { 1 if readb(&s) => return 1, _ => return eatr(s), } } fn main() -> void { print(f(1)); }", - true, - ), - // two guards spending different values: arm `3` is disjoint from both. - ( - "guard_two_spends_disjoint_arms", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat2(a: Str, b: Str) -> i64 { return 1; } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); let u = str_concat(\"c\", \"d\"); match k { 1 if eatb(s) => return eatr(u), 2 if eatb(u) => return eatr(s), 3 => return eat2(s, u), _ => return 0, } } fn main() -> void { print(f(3)); }", - true, - ), - // ... but `_` overlaps the guard on `1`, which spent s. - ( - "guard_two_spends_wild_uses_one", - "fn eatb(s: Str) -> bool { return true; } fn eatr(s: Str) -> i64 { return 1; } fn readb(s: &Str) -> bool { return true; } fn eat2(a: Str, b: Str) -> i64 { return 1; } fn f(k: i64) -> i64 { let s = str_concat(\"a\", \"b\"); let u = str_concat(\"c\", \"d\"); match k { 1 if eatb(s) => return eatr(u), 2 if eatb(u) => return eatr(s), _ => return eatr(s), } } fn main() -> void { print(f(5)); }", - false, - ), - ( - "shadow_in_else_hides_consume", - "fn eat(s: Str) -> void { } fn main() -> void { let s = str_concat(\"a\", \"b\"); if true { eat(s); } else { let s = 1; } }", - false, - ), -]; - -#[test] -fn trackc_closes_checker_holes() { - let dir = scratch("trackc_verdicts"); - for (name, source, accepted) in TRACKC_VERDICTS { - let file = dir.join(format!("{}.trk", name)); - fs::write(&file, source).unwrap(); - let native = run_trackc(&["check", file.to_str().unwrap()], &dir); - assert_eq!( - native.status.success(), - *accepted, - "{}: trackc verdict: {}", - name, - String::from_utf8_lossy(&native.stderr) - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Lifecycle hard errors (docs/lifecycles.md §2, card L5), trackc-only: -/// (program, exact first diagnostic line). Paths are under docs/lifecycles/; -/// other entries are inline sources. -const LIFE_ERRORS: &[(&str, &str)] = &[ - ( - "e1_lent_consumed.trk", - "error[E0211]: 'take' consumes its parameter 'p', but 'r' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'.", - ), - ( - "e2_escape_tuple.trk", - "error[E0212]: local 'p' escapes 'pair' inside the returned tuple (element 0); it dies when 'pair' returns.", - ), - ( - "e3_escape_struct.trk", - "error[E0212]: local 'p' escapes 'make' through field 'Holder.p'; it dies when 'make' returns.", - ), - ( - "e4_outlive_block.trk", - "error[E0213]: 'r' refers to 'b', which ends at the close of this block (line 9); 'r' is used after it at line 14.", - ), - ( - "e5_end_twice.trk", - "error[E0214]: 'p' would be ended twice: fields 'Bag.a' and 'Bag.b' both take ownership of the borrowed 'r'.", - ), - ( - "fn eatb(s: Str) -> bool { return true; }\nfn f(k: i64) -> i64 {\n let s = str_concat(\"a\", \"b\");\n match k { 1 if eatb(s) => return 1, _ => print(0), }\n print(s);\n return 0;\n}\nfn main() -> void { print(f(1)); }\n", - "error[E0200]: Resource 's' is spent in some match arms but not in others.", - ), - // I2: through a local alias, E0211 names the lent parameter. - ( - "struct Point { x: i64, y: i64 }\nfn take(p: Point) -> i64 { return p.x; }\nfn peek(r: &Point) -> i64 {\n let q = r;\n return take(q);\n}\nfn main() -> void { let p = Point { x: 1, y: 2 }; print(peek(&p)); }\n", - "error[E0211]: 'take' consumes its parameter 'p', but 'r' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'.", - ), - // L5w: E0211 field of a borrowed struct. - ( - "struct Point { x: i64, y: i64 }\nstruct Outer { p: Point, n: i64 }\nfn take(p: Point) -> i64 { return p.x; }\nfn peek(r: &Outer) -> i64 { return take(r.p); }\nfn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(peek(&o)); }\n", - "error[E0211]: 'take' consumes its parameter 'p', but 'r.p' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'.", - ), - // L5w: E0211 deref of a reference. - ( - "struct Point { x: i64, y: i64 }\nfn take(p: Point) -> i64 { return p.x; }\nfn peek(r: &Point) -> i64 { return take(*r); }\nfn main() -> void { let p = Point { x: 1, y: 2 }; print(peek(&p)); }\n", - "error[E0211]: 'take' consumes its parameter 'p', but '*r' is only lent to 'peek'. Pass '&' and make 'p: &Point', or take ownership in 'peek'.", - ), - // L5w: E0211 generic parameter. - ( - "struct Point { x: i64, y: i64 }\nstruct Outer { p: Point, n: i64 }\nfn eat(v: T) -> i64 { return 1; }\nfn peek(r: &Outer) -> i64 { return eat(r.p); }\nfn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(peek(&o)); }\n", - "error[E0211]: 'eat' consumes its parameter 'v', but 'r.p' is only lent to 'peek'. Pass '&' and make 'v: &T', or take ownership in 'peek'.", - ), - // L5w: E0212 union payload. - ( - "struct Point { x: i64, y: i64 }\nunion U { P(&Point), N }\nfn mk() -> U { let p = Point { x: 1, y: 2 }; return U::P(&p); }\nfn main() -> void { let u = mk(); match u { U::P(r) => print(r.x), U::N => print(0) } }\n", - "error[E0212]: local 'p' escapes 'mk' inside the returned payload of 'U::P'; it dies when 'mk' returns.", - ), - // L5w: E0212 reference alias. - ( - "struct Point { x: i64, y: i64 }\nfn pair() -> (&Point, i64) { let p = Point { x: 1, y: 2 }; let b = &p; return (b, 7); }\nfn main() -> void { let t = pair(); print(t.1); }\n", - "error[E0212]: local 'p' escapes 'pair' inside the returned tuple (element 0), through 'b'; it dies when 'pair' returns.", - ), - // L5w: E0212 literal alias. - ( - "struct Point { x: i64, y: i64 }\nfn pair() -> (&Point, i64) { let p = Point { x: 1, y: 2 }; let t = (&p, 7); let u = t; return u; }\nfn main() -> void { let t = pair(); print(t.1); }\n", - "error[E0212]: local 'p' escapes 'pair' through 'u'; it dies when 'pair' returns.", - ), - // L5w: E0213 through a call. - ( - "struct Point { x: i64, y: i64 }\nfn id(a: &Point) -> &Point { return a; }\nfn main() -> void {\n let a = Point { x: 1, y: 2 };\n let mut r = &a;\n let flag: i64 = 1;\n if flag > 0 {\n let b = Point { x: 3, y: 4 };\n r = id(&b);\n } else {\n let b = Point { x: 5, y: 6 };\n r = id(&b);\n }\n print(r.x);\n}\n", - "error[E0213]: 'r' refers to 'b', which ends at the close of this block (line 9); 'r' is used after it at line 14.", - ), - // L5w: E0213 through an alias. - ( - "struct Point { x: i64, y: i64 }\nfn main() -> void {\n let a = Point { x: 1, y: 2 };\n let mut r = &a;\n let flag: i64 = 1;\n if flag > 0 {\n let b = Point { x: 3, y: 4 };\n let q = &b;\n r = q;\n } else {\n let b = Point { x: 5, y: 6 };\n r = &b;\n }\n print(r.x);\n}\n", - "error[E0213]: 'r' refers to 'b', which ends at the close of this block (line 9); 'r' is used after it at line 14.", - ), - // L5w: E0214 returned tuple. - ( - "struct Point { x: i64, y: i64 }\nfn dup(r: &Point) -> (Point, Point) { return (r, r); }\nfn main() -> void { let p = Point { x: 1, y: 2 }; let t = dup(&p); print(t.0.x); }\n", - "error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'.", - ), - // L5w: E0214 annotated let. - ( - "struct Point { x: i64, y: i64 }\nfn dup(r: &Point) -> i64 { let t: (Point, Point) = (r, r); return t.0.x; }\nfn main() -> void { let p = Point { x: 1, y: 2 }; print(dup(&p)); }\n", - "error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'.", - ), - // L5w: E0214 tuple in an owned struct field. - ( - "struct Point { x: i64, y: i64 }\nstruct Bag { t: (Point, Point) }\nfn mk(r: &Point) -> Bag { return Bag { t: (r, r) }; }\nfn main() -> void { let p = Point { x: 1, y: 2 }; let b = mk(&p); print(b.t.0.x); }\n", - "error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'.", - ), - // L5w: E0214 tuple argument, local reference. - ( - "struct Point { x: i64, y: i64 }\nfn eat(t: (Point, Point)) -> i64 { return 1; }\nfn main() -> void { let p = Point { x: 1, y: 2 }; let r = &p; print(eat((r, r))); }\n", - "error[E0214]: 'p' would be ended twice: elements 0 and 1 of the tuple both take ownership of the borrowed 'r'.", - ), -]; - -#[test] -fn lifecycle_hard_errors_print_the_catalogue_texts() { - let root = repo(); - let dir = scratch("life_errors"); - for (i, (prog, want)) in LIFE_ERRORS.iter().enumerate() { - let path = if prog.ends_with(".trk") { - root.join("docs/lifecycles").join(prog) - } else { - let file = dir.join(format!("inline{}.trk", i)); - fs::write(&file, prog).unwrap(); - file - }; - let out = run_trackc(&["check", path.to_str().unwrap()], &dir); - let stderr = String::from_utf8_lossy(&out.stderr); - assert_eq!(out.status.code(), Some(1), "{}: {}", prog, stderr); - assert_eq!( - stderr.lines().next().unwrap_or(""), - *want, - "{}: unexpected diagnostic:\n{}", - prog, - stderr - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Programs that look like the lifecycle hard errors but are correct -/// (card L5w): `trackc check` must accept them. -const LIFE_CLEAN: &[&str] = &[ - // E0211: lending a field on. - "struct Point { x: i64, y: i64 }\nstruct Outer { p: Point, n: i64 }\nfn look(p: &Point) -> i64 { return p.x; }\nfn peek(r: &Outer) -> i64 { return look(&r.p) + r.n; }\nfn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(peek(&o)); }\n", - // E0211: a generic parameter bound to the reference itself. - "struct Point { x: i64, y: i64 }\nfn eat(v: T) -> i64 { return 1; }\nfn peek(r: &Point) -> i64 { return eat(r); }\nfn main() -> void { let p = Point { x: 1, y: 2 }; print(peek(&p)); }\n", - // E0211: moving a field out of an owned parameter. - "struct Point { x: i64, y: i64 }\nstruct Outer { p: Point, n: i64 }\nfn take(p: Point) -> i64 { return p.x; }\nfn own(o: Outer) -> i64 { return take(o.p); }\nfn main() -> void { let o = Outer { p: Point { x: 1, y: 2 }, n: 3 }; print(own(o)); }\n", - // E0212: a payload holding a parameter's reference. - "struct Point { x: i64, y: i64 }\nunion U { P(&Point), N }\nfn wrap(r: &Point) -> U { return U::P(r); }\nfn main() -> void { let p = Point { x: 1, y: 2 }; let u = wrap(&p); match u { U::P(r) => print(r.x), U::N => print(0) } }\n", - // E0212: an alias of a parameter. - "struct Point { x: i64, y: i64 }\nfn pair(r: &Point) -> (&Point, i64) { let b = r; let t = (b, 7); return t; }\nfn main() -> void { let p = Point { x: 1, y: 2 }; let t = pair(&p); print(t.1); }\n", - // E0212: only a copy leaves. - "struct Point { x: i64, y: i64 }\nfn pair() -> (i64, i64) { let p = Point { x: 1, y: 2 }; let t = (&p, 7); let u = t; return (u.1, 8); }\nfn main() -> void { let t = pair(); print(t.1); }\n", - // E0212: a field read through an alias. - "struct Point { x: i64, y: i64 }\nfn pair() -> (i64, i64) { let p = Point { x: 1, y: 2 }; let b = &p; return (b.x, 7); }\nfn main() -> void { let t = pair(); print(t.1); }\n", - // E0213: alias and call targets that outlive the reference. - "struct Point { x: i64, y: i64 }\nfn id(a: &Point) -> &Point { return a; }\nfn main() -> void {\n let a = Point { x: 1, y: 2 };\n let c = Point { x: 7, y: 8 };\n let mut r = &a;\n let flag: i64 = 1;\n if flag > 0 {\n let q = &c;\n r = q;\n } else {\n r = id(&c);\n }\n print(r.x);\n}\n", - // E0214: a tuple of references. - "struct Point { x: i64, y: i64 }\nfn two(r: &Point) -> (&Point, &Point) { return (r, r); }\nfn main() -> void { let p = Point { x: 1, y: 2 }; let t = two(&p); print(t.0.x); }\n", - // E0214: owned tuple elements from distinct values. - "struct Point { x: i64, y: i64 }\nfn mk(a: Point, b: Point) -> (Point, Point) { return (a, b); }\nfn main() -> void { let t = mk(Point { x: 1, y: 2 }, Point { x: 3, y: 4 }); print(t.0.x); }\n", -]; - -#[test] -fn lifecycle_lookalikes_check_clean() { - let dir = scratch("life_clean"); - for (i, prog) in LIFE_CLEAN.iter().enumerate() { - let file = dir.join(format!("clean{}.trk", i)); - fs::write(&file, prog).unwrap(); - let out = run_trackc(&["check", file.to_str().unwrap()], &dir); - assert!( - out.status.success(), - "clean{} rejected:\n{}\n{}", - i, - prog, - String::from_utf8_lossy(&out.stderr) - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// (name, source, expected stdout) of programs built by trackc. -const RUN_OUTPUTS: &[(&str, &str, &str)] = &[ - ( - "const_forward_reference", - "const B = A * 2; const A = 3; const C = 5 > 2; const S = \"hi\"; fn main() -> void { print(B); print(C); print(S); }", - "6\n1\nhi\n", - ), - ( - "tuple_in_returned_tuple", - "fn mk(n: i64) -> ((i64, i64), i64) { let inner = (n, n * 2); return (inner, 9); } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let t = mk(3); print(clobber(100)); let i = t.0; print(i.1); }", - "200\n6\n", - ), - ( - "tuple_in_returned_struct", - "struct H { t: (i64, i64) } fn mk(n: i64) -> H { return H { t: (n, n + 1) }; } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let h = mk(7); print(clobber(100)); let t = h.t; print(t.1); }", - "200\n8\n", - ), - ( - "tuple_in_returned_union", - "union U { P((i64, i64)), N } fn mk(n: i64) -> U { return U::P((n, n + 5)); } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let u = mk(1); print(clobber(100)); match u { U::P(t) => print(t.1), U::N => print(0) } }", - "200\n6\n", - ), - ( - "tuple_in_returned_array", - "fn mk(n: i64) -> [](i64, i64) { return [(n, n + 1)]; } fn clobber(n: i64) -> i64 { let z = (n, n, n, n); return z.0 + z.3; } fn main() -> void { let a = mk(4); print(clobber(100)); let t = a[0]; print(t.1); }", - "200\n5\n", - ), - ( - "stack_tuple_reassigned_from_itself", - "fn main() -> void { let mut p = (1, 2); let mut i = 0; while i < 3 { p = (p.1, p.0 + p.1); i = i + 1; } print(p.0); print(p.1); }", - "5\n8\n", - ), - ( - "stack_tuple_destructured_and_matched", - "fn main() -> void { let mut s = 0; for i in 0..4 { let t = (i, i * 2); let u = (i, 1); let (a, b) = t; match u { (0, _) => s = s + 100, (x, y) => s = s + x + y, } s = s + a + b; } print(s); }", - "127\n", - ), - ( - "match_in_loop_resets_each_time", - "fn main() -> void { for i in 0..3 { match i { 0 => print(10), _ => print(i), } } }", - "10\n1\n2\n", - ), - ( - "tuple_copied_out_of_loop_escapes", - "fn main() -> void { let mut keep = (0, 0); for i in 0..3 { let t = (i, i + 1); if i == 1 { keep = t; } else { let (a, b) = t; } } print(keep.0); print(keep.1); }", - "1\n2\n", - ), - ( - "tuple_literal_in_loop", - "fn main() -> void { let mut a = [(0, 0), (0, 0), (0, 0)]; for i in 0..3 { a[i] = (i, i * 10); } print(a[0].1); print(a[2].1); }", - "0\n20\n", - ), -]; - -/// A tuple literal that never escapes lives in a stack slot: 20M of them in -/// a loop allocate nothing (heap cells took ~600 MB before), while one that -/// is returned stays a heap cell. -#[test] -fn non_escaping_tuples_use_stack_slots() { - let dir = scratch("stack_tuples"); - let file = dir.join("t3.trk"); - fs::write( - &file, - "fn pair(n: i64) -> (i64, i64) { let r = (n, n + 1); return r; } \ - fn main() -> void { let mut i = 0; let mut acc = 0; while i < 20000000 { let p = (i, 1); acc = acc + p.1; i = i + 1; } print(acc); print(pair(4).1); }", - ) - .unwrap(); - let exe = dir.join("t3"); - let out = run_trackc( - &["build", file.to_str().unwrap(), "-o", exe.to_str().unwrap()], - &dir, - ); - assert!( - out.status.success(), - "build failed: {}", - String::from_utf8_lossy(&out.stderr) - ); - let c = fs::read_to_string(dir.join("t3.c")).unwrap(); - let main_body = &c[c.find("tk_w tk_main(void) {").expect("tk_main")..]; - let main_body = &main_body[..main_body.find("\n}\n").unwrap()]; - assert!( - !main_body.contains("alloc(") && !main_body.contains("alloc_nz("), - "loop tuple must not allocate:\n{}", - main_body - ); - let pair_body = &c[c.find("tk_w tk_pair(tk_w a0) {").expect("tk_pair")..]; - let pair_body = &pair_body[..pair_body.find("\n}\n").unwrap()]; - assert!( - pair_body.contains("alloc(") || pair_body.contains("alloc_nz("), - "returned tuple must be a heap cell:\n{}", - pair_body - ); - // 64 MB of address space is far below what 20M heap cells need. - let run = Command::new("sh") - .arg("-c") - .arg(format!("ulimit -v 65536; exec {}", exe.display())) - .output() - .unwrap(); - assert!(run.status.success(), "t3 failed under a 64 MB limit"); - assert_eq!(String::from_utf8_lossy(&run.stdout), "20000000\n5\n"); - let _ = fs::remove_dir_all(&dir); -} - -#[test] -fn trackc_programs_print_the_expected_output() { - let dir = scratch("run_outputs"); - for (name, source, expected) in RUN_OUTPUTS { - let file = dir.join(format!("{}.trk", name)); - fs::write(&file, source).unwrap(); - let out = run_trackc(&["run", file.to_str().unwrap()], &dir); - assert!( - out.status.success(), - "{}: trackc run failed: {}", - name, - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - String::from_utf8_lossy(&out.stdout), - *expected, - "{}: wrong output", - name - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// `trackc life` dumps per-function lifecycle summaries (card L3). Each -/// program in docs/lifecycles/, bench/progs/ and tests/life/progs/ has a -/// golden dump in tests/life/.life. Set `UPDATE_LIFE=1` to rewrite the goldens. -#[test] -fn life_dumps_match_goldens() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let mut checked = 0; - for sub in ["docs/lifecycles", "bench/progs", "tests/life/progs"] { - let mut files: Vec = fs::read_dir(root.join(sub)) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|x| x == "trk")) - .collect(); - files.sort(); - for file in files { - let rel = file.strip_prefix(&root).unwrap().to_str().unwrap(); - let out = run_trackc(&["life", rel], &root); - assert!( - out.status.success(), - "{}: trackc life failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - let stem = file.file_stem().unwrap().to_str().unwrap(); - let golden = root.join("tests/life").join(format!("{}.life", stem)); - if update { - fs::create_dir_all(golden.parent().unwrap()).unwrap(); - fs::write(&golden, &out.stdout).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!( - String::from_utf8_lossy(&out.stdout), - want, - "{}: lifecycle dump differs from {}", - rel, - golden.display() - ); - checked += 1; - } - } - assert!( - checked >= 22, - "expected at least 22 programs, saw {}", - checked - ); -} - -/// `trackc life --place` dumps the placement plan (card L7, -/// docs/lifecycles.md §3.1): one line per allocation site with its line, -/// kind, PLACE and ENDS. Each program in tests/life/place/ has a golden -/// `.place`; `UPDATE_LIFE=1` rewrites them. place.trk pins one site -/// per rule, so the asserts below name the rule each line checks. -#[test] -fn life_place_dumps_match_goldens() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = root.join("tests/life/place"); - let mut files: Vec = fs::read_dir(&dir) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| p.extension().is_some_and(|x| x == "trk")) - .collect(); - files.sort(); - assert!(!files.is_empty(), "no programs in tests/life/place"); - for file in files { - let rel = file.strip_prefix(&root).unwrap().to_str().unwrap(); - let out = run_trackc(&["life", "--place", rel], &root); - assert!( - out.status.success(), - "{}: trackc life --place failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - let golden = file.with_extension("place"); - if update { - fs::write(&golden, &out.stdout).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!( - String::from_utf8_lossy(&out.stdout), - want, - "{}: placement plan differs from {}", - rel, - golden.display() - ); - } - let got = String::from_utf8_lossy( - &run_trackc(&["life", "--place", "tests/life/place/place.trk"], &root).stdout, - ) - .into_owned(); - for (line, why) in [ - ( - "L20 tuple stack ends L21", - "a tuple only destructured lives on the stack", - ), - ( - "L8 tuple ret-slot ends L8", - "a returned tuple goes to the caller's slot", - ), - ( - "L24 struct heap ends -", - "a value stored into a collection is heap", - ), - ( - "L26 call heap ends -", - "a value passed to an esc param is heap", - ), - ( - "L28 str heap-autofree ends L29", - "a fresh Str that dies in this frame is auto-freed (L13)", - ), - ] { - assert!( - got.contains(line), - "{}: missing `{}` in\n{}", - why, - line, - got - ); - } -} - -/// Stack cells in the C backend (card L8, docs/lifecycles.md §3.2): -/// every program in tests/stack/ builds, prints its `.out`, and -/// plans as its `.place` golden (`UPDATE_LIFE=1` rewrites them). -/// The asserts name the rule each placement line checks, and the emitted -/// C of the stack programs holds their literals in `tk_w sN[k]` slots. -#[test] -fn stack_cells_run_and_plan() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("stack"); - let mut plans = String::new(); - for stem in ["escapes", "mutate", "read_only", "union_match"] { - let rel = format!("tests/stack/{}.trk", stem); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!( - out.status.success(), - "{}: build failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - let want = fs::read_to_string(root.join(format!("tests/stack/{}.out", stem))).unwrap(); - assert_eq!(run_exe(&exe), (want, Some(0)), "{}: output differs", rel); - let c = fs::read_to_string(exe.with_extension("c")).unwrap(); - if stem != "escapes" { - assert!( - c.contains("tk_w s0["), - "{}: no stack slot in emitted C", - rel - ); - } - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/stack/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - plans.push_str(&format!("{}:\n{}", stem, got)); - } - for (line, why) in [ - ( - "L23 struct stack ends L25", - "a struct only lent to a reading callee is stack", - ), - ( - "L24 struct stack ends L25", - "a struct only read through its fields is stack", - ), - ( - "L29 array stack ends L31", - "an array only indexed and lent is stack", - ), - ("L8 struct heap ends -", "a returned struct is heap"), - ( - "L17 struct heap ends -", - "a struct stored into another literal is heap", - ), - ( - "L27 struct heap ends -", - "a struct passed to a `ret` parameter is heap", - ), - ( - "L29 struct heap ends -", - "a struct inside an array literal is heap", - ), - ( - "L17 struct stack ends L23", - "a struct mutated through the slot is stack", - ), - ( - "L21 array stack ends L24", - "an array written by index is stack", - ), - ( - "L13 union stack ends L14", - "a payload union only matched is stack", - ), - ] { - assert!( - plans.contains(line), - "{}: missing `{}` in\n{}", - why, - line, - plans - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Auto-free of heap cells (card L9, docs/lifecycles.md §3.3): every -/// program in tests/autofree/ builds, prints its `.out`, plans as its -/// `.place` golden (`UPDATE_LIFE=1` rewrites them) and frees cells in -/// its emitted C. Where gcc has AddressSanitizer, the programs also run -/// with no use after free and no double free. -#[test] -fn autofree_frees_heap_cells() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("autofree"); - let stems = [ - "die_param", - "early_return", - "moved_field", - "nested", - "returned", - ]; - let mut plans = String::new(); - for stem in stems { - let rel = format!("tests/autofree/{}.trk", stem); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!( - out.status.success(), - "{}: build failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - let want = fs::read_to_string(root.join(format!("tests/autofree/{}.out", stem))).unwrap(); - assert_eq!(run_exe(&exe), (want, Some(0)), "{}: output differs", rel); - let c = fs::read_to_string(exe.with_extension("c")).unwrap(); - assert!(c.contains("dealloc(l"), "{}: no free in emitted C", rel); - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/autofree/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - plans.push_str(&format!("{}:\n{}", stem, got)); - } - for (line, why) in [ - ( - "L23 call heap-autofree deep ends L24", - "a fresh cell passed to a `die` parameter is freed by the caller", - ), - ( - "L21 call stack ends L22", - "a ret-slot result passed to a `die` parameter is a stack slot (L10)", - ), - ( - "L19 struct stack ends L20", - "a stack cell passed to a `die` parameter stays a stack cell", - ), - ( - "L16 call heap-autofree ends L17", - "a cell whose child is moved out frees only itself", - ), - ( - "L22 struct heap-autofree deep ends L27", - "a nested literal reassigned fresh cells runs drop glue", - ), - ("L7 struct heap ends -", "a returned cell is never freed"), - ( - "L13 struct heap ends -", - "a cell stored into a returned cell is never freed", - ), - ] { - assert!( - plans.contains(line), - "{}: missing `{}` in\n{}", - why, - line, - plans - ); - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if !asan { - return; - } - for stem in stems { - let rel = format!("tests/autofree/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let run = Command::new(&exe) - .env("ASAN_OPTIONS", "detect_leaks=0") - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("AddressSanitizer"), - "{}: ASan reports an error:\n{}", - rel, - err - ); - } -} - -/// Auto-free of fresh `Str` values and runtime handles (card L13, -/// docs/lifecycles.md §3.5): every program in tests/handles/ builds with -/// both backends, prints its `.out` (whose last line is -/// `sys_get_memory_used()`, so native and C agree on it), plans as its -/// `.place` golden (`UPDATE_LIFE=1` rewrites them) and frees through -/// the kind's runtime free function. Values that are returned, stored or -/// aliased are never freed. Where gcc has AddressSanitizer, the C builds -/// also run with no memory error. -#[test] -fn handles_free_fresh_values() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("handles"); - let stems = [ - "builder", - "coll_kept", - "coll_local", - "coll_move", - "int_loop", - "str_kept", - "str_local", - ]; - let mut plans = String::new(); - for stem in stems { - let rel = format!("tests/handles/{}.trk", stem); - let want = fs::read_to_string(root.join(format!("tests/handles/{}.out", stem))).unwrap(); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!( - out.status.success(), - "{}: build failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - run_exe(&exe), - (want.clone(), Some(0)), - "{}: C output differs", - rel - ); - let nat = dir.join(format!("{}_nat", stem)); - let out = run_trackc( - &["build", "--native", &rel, "-o", nat.to_str().unwrap()], - &root, - ); - assert!(out.status.success(), "{}: native build failed", rel); - assert_eq!( - run_exe(&nat), - (want, Some(0)), - "{}: native output differs", - rel - ); - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/handles/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - plans.push_str(&format!("{}:\n{}", stem, got)); - let c = fs::read_to_string(exe.with_extension("c")).unwrap(); - for (prog, free) in [ - ("str_local", "track_str_free(l"), - ("int_loop", "track_str_free(l"), - ("builder", "track_sb_free(l"), - ("builder", "track_str_free(l"), - ("coll_local", "track_i64_collection_free(l"), - ("coll_local", "vec_free(l"), - ] { - if prog == stem { - assert!(c.contains(free), "{}: no `{}` in emitted C", rel, free); - } - } - } - // coll_move (card L15): only `rows` moves a fresh row into `prev` as - // its last mention; the looped and the used-after moves keep both. - let moved = plans.split("coll_move:").nth(1).unwrap_or(""); - let moved = moved.split("int_loop:").next().unwrap_or(""); - assert_eq!( - moved, "\nfn rows\n L6 collection heap-autofree ends L15\n", - "coll_move: moves planned:\n{}", - moved - ); - for (line, why) in [ - ( - "L4 str heap-autofree ends L6", - "a str_concat result that dies locally is freed", - ), - ( - "L14 str heap-autofree ends L17", - "a Str reassigned fresh strings is freed", - ), - ( - "L7 str heap-autofree ends L10", - "an int_to_str in a loop is freed each iteration", - ), - ( - "L4 builder heap-autofree ends L12", - "a builder finished into a Str is freed", - ), - ( - "L12 str heap-autofree ends L13", - "the finished Str is freed", - ), - ( - "L3 collection heap-autofree ends L12", - "a collection that dies locally is freed", - ), - ( - "L19 vec heap-autofree ends L27", - "a Vec that dies locally is freed", - ), - ] { - assert!( - plans.contains(line), - "{}: missing `{}` in\n{}", - why, - line, - plans - ); - } - for (prog, kept) in [ - ("str_kept", "L4 "), - ("str_kept", "L12 str"), - ("str_kept", "L14 str"), - ("coll_kept", "L7 "), - ("coll_kept", "L11 "), - ] { - let block = plans.split(&format!("{}:\n", prog)).nth(1).unwrap_or(""); - let block = block.split(":\n").next().unwrap_or(""); - assert!( - !block - .lines() - .any(|l| l.trim_start().starts_with(kept.trim_end()) && l.contains("autofree")), - "{}: a returned, stored or aliased value at `{}` must not be freed:\n{}", - prog, - kept, - block - ); - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if !asan { - let _ = fs::remove_dir_all(&dir); - return; - } - for stem in stems { - let rel = format!("tests/handles/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let run = Command::new(&exe) - .env("ASAN_OPTIONS", "detect_leaks=0") - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("AddressSanitizer"), - "{}: ASan reports an error:\n{}", - rel, - err - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Auto-free of fresh temporaries (card L13b, docs/lifecycles.md §3.5): a -/// fresh Str or handle passed straight to a call that neither keeps, frees -/// nor returns it is freed right after that call; a discarded fresh -/// statement right after itself. Every program in tests/temps/ prints its -/// `.out` with both backends and plans as its `.place` golden -/// (`UPDATE_LIFE=1` rewrites them). Where gcc has AddressSanitizer, the C -/// builds run with no memory error, and the programs whose temporaries all -/// die leak nothing. -#[test] -fn temps_free_fresh_temporaries() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("temps"); - let stems = ["alias", "discard", "kept", "nested", "print_loop"]; - let mut plans = String::new(); - for stem in stems { - let rel = format!("tests/temps/{}.trk", stem); - let want = fs::read_to_string(root.join(format!("tests/temps/{}.out", stem))).unwrap(); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!( - out.status.success(), - "{}: build failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - run_exe(&exe), - (want.clone(), Some(0)), - "{}: C output differs", - rel - ); - let nat = dir.join(format!("{}_nat", stem)); - let out = run_trackc( - &["build", "--native", &rel, "-o", nat.to_str().unwrap()], - &root, - ); - assert!(out.status.success(), "{}: native build failed", rel); - assert_eq!( - run_exe(&nat), - (want, Some(0)), - "{}: native output differs", - rel - ); - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/temps/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - plans.push_str(&format!("{}:\n{}", stem, got)); - } - let block = |prog: &str| -> String { - let b = plans.split(&format!("{}:\n", prog)).nth(1).unwrap_or(""); - b.split(":\n").next().unwrap_or("").to_string() - }; - for (prog, line, count, why) in [ - ( - "print_loop", - "str temp-autofree", - 2, - "int_to_str passed to print and str_len is freed", - ), - ( - "nested", - "str temp-autofree", - 6, - "every nested fresh argument is freed", - ), - ( - "discard", - "str temp-autofree", - 3, - "discarded results and their fresh arguments are freed", - ), - ( - "kept", - "L12 str temp-autofree ends L12", - 1, - "int_to_str lent to str_concat is freed", - ), - ] { - let got = block(prog).matches(line).count(); - assert_eq!(got, count, "{}: `{}` x{} in\n{}", why, line, count, plans); - } - for (prog, kept) in [("kept", "L11 "), ("alias", "temp-autofree")] { - assert!( - !block(prog) - .lines() - .any(|l| l.trim_start().starts_with(kept.trim_end()) && l.contains("temp-autofree")), - "{}: a temporary that is kept or aliased (`{}`) must not be freed:\n{}", - prog, - kept, - plans - ); - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if !asan { - let _ = fs::remove_dir_all(&dir); - return; - } - for stem in stems { - let rel = format!("tests/temps/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let all_die = matches!(stem, "discard" | "nested" | "print_loop"); - let leaks = if all_die { - "detect_leaks=1" - } else { - "detect_leaks=0" - }; - let run = Command::new(&exe) - .env("ASAN_OPTIONS", leaks) - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("Sanitizer"), - "{}: ASan reports an error or a leak:\n{}", - rel, - err - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Fresh cell temporaries (card L13c, docs/lifecycles.md §3.5): a fresh -/// struct, tuple or array passed straight to a call that only lends it -/// lives in a stack cell when it is flat and fits the frame, else it is -/// freed right after that call (with drop glue when its children are -/// fresh). One kept by the callee or returned by the outer call is never -/// freed. Every program in tests/temps_cell/ prints its `.out` with -/// both backends and plans as its `.place` golden (`UPDATE_LIFE=1` -/// rewrites them); where gcc has AddressSanitizer the C builds run clean, -/// with leak checks for the programs whose temporaries all die. L13d adds -/// cells whose Str fields are static or borrowed (only the shell is -/// freed), discarded cell statements, and native inlining (a self tail -/// call's copy, a branch condition) that must still free the temporary. -/// accret: a native accumulator return (`x + f(&fresh)`) keeps its call so -/// the temporary is freed. -/// accpass (card F3b): an accumulator loop whose returns pass a parameter -/// on (unchanged, swapped, a field of it, a local or a literal) never frees -/// a cell a parameter still points at. Its leaks are not checked: `mkn`'s -/// Str field is never freed by the plan, on either backend. -#[test] -fn temps_free_fresh_cell_temporaries() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("temps_cell"); - let stems = [ - "accloop", - "accpass", - "accret", - "alias", - "branch", - "discard", - "kept", - "nested", - "print_loop", - "str_alias", - "str_cell", - "tailr", - ]; - let mut plans = String::new(); - for stem in stems { - let rel = format!("tests/temps_cell/{}.trk", stem); - let want = fs::read_to_string(root.join(format!("tests/temps_cell/{}.out", stem))).unwrap(); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!(out.status.success(), "{}: build failed", rel); - assert_eq!(run_exe(&exe), (want.clone(), Some(0)), "{}: C output", rel); - let nat = dir.join(format!("{}_nat", stem)); - let out = run_trackc( - &["build", "--native", &rel, "-o", nat.to_str().unwrap()], - &root, - ); - assert!(out.status.success(), "{}: native build failed", rel); - assert_eq!(run_exe(&nat), (want, Some(0)), "{}: native output", rel); - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/temps_cell/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - plans.push_str(&format!("{}:\n{}", stem, got)); - } - for (stem, line) in [ - ("print_loop", "L33 call stack ends L33"), - ("print_loop", "L34 struct stack ends L34"), - ("print_loop", "L35 call temp-autofree deep ends L35"), - ("print_loop", "L36 struct temp-autofree deep ends L36"), - ("print_loop", "L37 tuple stack ends L37"), - ("nested", "L26 call stack ends L26"), - ("str_cell", "L18 struct stack ends L18"), - ("str_cell", "L17 call temp-autofree deep ends L17"), - ("discard", "L23 call temp-autofree deep ends L23"), - ("discard", "L24 call temp-autofree deep ends L24"), - ("discard", "L25 call temp-autofree deep ends L25"), - ("str_alias", "L19 call temp-autofree deep ends L19"), - ("str_alias", "L21 call temp-autofree deep ends L21"), - ] { - assert!( - plans.contains(line), - "{}: missing `{}` in\n{}", - stem, - line, - plans - ); - } - // Card F3: accumulator recursion with temporary arguments stays a loop - // on the native backend; a million levels deep would overflow the - // stack as real calls (the C reference may, so it is native only). - let deep = dir.join("accdeep_nat"); - let out = run_trackc( - &[ - "build", - "--native", - "tests/temps_cell/accdeep.trk", - "-o", - deep.to_str().unwrap(), - ], - &root, - ); - assert!(out.status.success(), "accdeep: native build failed"); - let want = fs::read_to_string(root.join("tests/temps_cell/accdeep.out")).unwrap(); - assert_eq!(run_exe(&deep), (want, Some(0)), "accdeep: native output"); - let nested = plans.split("nested:\n").nth(1).unwrap_or(""); - let nested = nested.split(":\n").next().unwrap_or(""); - assert_eq!( - nested.matches("call temp-autofree deep").count(), - 3, - "every nested fresh cell is freed:\n{}", - plans - ); - for stem in ["kept", "alias"] { - let block = plans.split(&format!("{}:\n", stem)).nth(1).unwrap_or(""); - let block = block.split(":\n").next().unwrap_or(""); - assert!( - !block.contains("temp-autofree") && !block.contains("stack"), - "{}: a cell that is kept or aliased must stay on the heap:\n{}", - stem, - plans - ); - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if !asan { - let _ = fs::remove_dir_all(&dir); - return; - } - for stem in stems { - let rel = format!("tests/temps_cell/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let all_die = matches!( - stem, - "nested" - | "print_loop" - | "branch" - | "discard" - | "str_cell" - | "tailr" - | "accret" - | "accloop" - ); - // str_alias keeps `keep.name` alive to the end of main and drop glue never - // frees Str, so LSan may report that one string depending on what the C - // compiler leaves on the stack; it is checked for errors, not leaks. - let leaks = if all_die { - "detect_leaks=1" - } else { - "detect_leaks=0" - }; - let run = Command::new(&exe) - .env("ASAN_OPTIONS", leaks) - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("Sanitizer"), - "{}: ASan reports an error or a leak:\n{}", - rel, - err - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Owned Str fields (card L13e, docs/lifecycles.md §3.6): drop glue frees -/// a struct cell's Str field only when every construction reaching the -/// free fills it with a fresh Str and no use moves it out. Every program -/// in tests/strfield/ prints its `.out` with both backends and plans -/// as its `.place` golden (`UPDATE_LIFE=1` rewrites them). `temp` -/// and `local` own their strings (`deep strs`) and run leak-clean under -/// LSan, as do `result` (a call result's fields, card L15 LT_SFRES) and -/// `movelocal` (a fresh Str local moved into a field, LT_SFMOVE); a -/// literal, a parameter's, an aliased, a moved-out, a stored or a maybe -/// static Str field (`keep`) is never freed (ASan clean, leaks not -/// checked: those strings may live on). -#[test] -fn strfield_frees_owned_str_fields() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("strfield"); - let stems = [ - "alias", - "keep", - "literal", - "local", - "moved", - "movelocal", - "param", - "result", - "temp", - ]; - for stem in stems { - let rel = format!("tests/strfield/{}.trk", stem); - let want = fs::read_to_string(root.join(format!("tests/strfield/{}.out", stem))).unwrap(); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!(out.status.success(), "{}: build failed", rel); - assert_eq!(run_exe(&exe), (want.clone(), Some(0)), "{}: C output", rel); - let nat = dir.join(format!("{}_nat", stem)); - let out = run_trackc( - &["build", "--native", &rel, "-o", nat.to_str().unwrap()], - &root, - ); - assert!(out.status.success(), "{}: native build failed", rel); - assert_eq!(run_exe(&nat), (want, Some(0)), "{}: native output", rel); - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/strfield/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - let owns = got.contains(" strs "); - match stem { - "temp" | "local" | "result" | "movelocal" => { - assert!(owns, "{}: no owned Str field in\n{}", stem, got) - } - "param" => { - // Only main's `keep` owns its string: the cells built from - // the parameter in build_local/build_temp do not. - let callee = got.split("fn main").next().unwrap_or(""); - assert!( - !callee.contains(" strs "), - "param: callee frees a parameter's Str:\n{}", - got - ); - } - _ => assert!( - !owns, - "{}: a Str field it does not own is freed:\n{}", - stem, got - ), - } - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if !asan { - let _ = fs::remove_dir_all(&dir); - return; - } - for stem in stems { - let rel = format!("tests/strfield/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let leaks = if matches!(stem, "temp" | "local" | "literal" | "result" | "movelocal") { - "detect_leaks=1" - } else { - "detect_leaks=0" - }; - let run = Command::new(&exe) - .env("ASAN_OPTIONS", leaks) - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("Sanitizer"), - "{}: ASan reports an error or a leak:\n{}", - rel, - err - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// Returns hidden inside expressions (card F1): `if` and `match` are -/// expressions, so a `return` can sit in a `let` or assignment value, a -/// call argument, a condition, a match target, an operand or a literal -/// field. The walkers deciding that every return of a function is fresh -/// (LT_HFN, LT_SFRES, LT_GFN, LT_RSFN) must see each one, or the plan -/// frees a static Str or field. Every program in tests/returns/ prints its -/// `.out` with both backends, never gets the plan its hidden return -/// rules out, and, where gcc has AddressSanitizer, runs clean. -#[test] -fn returns_hidden_in_expressions_are_seen() { - let root = repo(); - let dir = scratch("returns"); - let cases = [ - ("str_let", "str temp-autofree"), - ("str_hidden", "str temp-autofree"), - ("sfres_cond", "deep strs"), - ("sfres_hidden", "deep strs"), - ("glue_hidden", "temp-autofree"), - ("retslot_hidden", "ret-slot"), - ]; - for (stem, banned) in cases { - let rel = format!("tests/returns/{}.trk", stem); - let want = fs::read_to_string(root.join(format!("tests/returns/{}.out", stem))).unwrap(); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!(out.status.success(), "{}: build failed", rel); - assert_eq!(run_exe(&exe), (want.clone(), Some(0)), "{}: C output", rel); - let nat = dir.join(format!("{}_nat", stem)); - let out = run_trackc( - &["build", "--native", &rel, "-o", nat.to_str().unwrap()], - &root, - ); - assert!(out.status.success(), "{}: native build failed", rel); - assert_eq!(run_exe(&nat), (want, Some(0)), "{}: native output", rel); - let plan = run_trackc(&["life", "--place", &rel], &root); - assert!( - plan.status.success() && !plan.stdout.is_empty(), - "{}: life --place failed: {:?}\n{}", - rel, - plan.status, - String::from_utf8_lossy(&plan.stderr) - ); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - assert!( - !got.contains(banned), - "{}: a hidden return rules out `{}`:\n{}", - rel, - banned, - got - ); - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if asan { - for (stem, _) in cases { - let rel = format!("tests/returns/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let run = Command::new(&exe) - .env("ASAN_OPTIONS", "detect_leaks=0") - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("Sanitizer"), - "{}: ASan reports an error:\n{}", - rel, - err - ); - } - } - let _ = fs::remove_dir_all(&dir); -} - -/// Caller return slots in the C backend (card L10, docs/lifecycles.md -/// §3.2): every program in tests/retslot/ builds, prints its `.out` -/// and plans as its `.place` golden (`UPDATE_LIFE=1` rewrites them). -/// The ret-slot functions get a `__rs` entry that writes the caller's -/// cell. Where gcc has AddressSanitizer, the programs also run with no -/// memory error. -#[test] -fn ret_slots_write_caller_cells() { - let root = repo(); - let update = env::var("UPDATE_LIFE").is_ok(); - let dir = scratch("retslot"); - let stems = [ - "alias_ref", - "alias_val", - "both", - "collection", - "nested", - "recursion", - ]; - let mut plans = String::new(); - for stem in stems { - let rel = format!("tests/retslot/{}.trk", stem); - let exe = dir.join(stem); - let out = run_trackc(&["build", &rel, "-o", exe.to_str().unwrap()], &root); - assert!( - out.status.success(), - "{}: build failed: {}", - rel, - String::from_utf8_lossy(&out.stderr) - ); - let want = fs::read_to_string(root.join(format!("tests/retslot/{}.out", stem))).unwrap(); - assert_eq!(run_exe(&exe), (want, Some(0)), "{}: output differs", rel); - let c = fs::read_to_string(exe.with_extension("c")).unwrap(); - assert!( - c.contains("__rs("), - "{}: no ret-slot entry in emitted C", - rel - ); - let plan = run_trackc(&["life", "--place", &rel], &root); - let got = String::from_utf8_lossy(&plan.stdout).into_owned(); - let golden = root.join(format!("tests/retslot/{}.place", stem)); - if update { - fs::write(&golden, &got).unwrap(); - } - let want = fs::read_to_string(&golden) - .unwrap_or_else(|_| panic!("missing golden {}", golden.display())); - assert_eq!(got, want, "{}: placement plan differs", rel); - plans.push_str(&format!("{}:\n{}", stem, got)); - } - for (line, why) in [ - ( - "L12 struct stack ends L22", - "a local reassigned only ret-slot results is a stack cell", - ), - ( - "L16 call stack ends L22", - "`acc = f(&acc)` writes acc's own cell", - ), - ( - "L14 call stack ends L20", - "`acc = f(acc)` writes acc's own cell", - ), - ( - "L13 call heap ends -", - "a ret-slot result stored into a collection is heap", - ), - ( - "L20 call stack ends L22", - "a ret-slot result in a stack slot", - ), - ( - "L21 call heap-autofree deep ends L26", - "a local also reassigned a heap-only cell stays heap-autofree", - ), - ( - "L25 call heap-autofree ends L26", - "a ret-slot result written into an autofree local's cell", - ), - ( - "L12 call heap ends -", - "a ret-slot result returned onward through a local is heap", - ), - ( - "L10 call stack ends L11", - "a recursive ret-slot call writes a slot of its caller's frame", - ), - ( - "L18 call ret-slot ends L18", - "a `return f(..)` passes the caller's slot through", - ), - ( - "L18 call stack ends L19", - "the outer call of `f(g(x))` writes a stack slot", - ), - ] { - assert!( - plans.contains(line), - "{}: missing `{}` in\n{}", - why, - line, - plans - ); - } - let asan = Command::new("gcc") - .args(["-fsanitize=address", "-x", "c", "-", "-o"]) - .arg(dir.join("probe")) - .stdin(std::process::Stdio::piped()) - .spawn() - .and_then(|mut child| { - use std::io::Write; - child - .stdin - .take() - .unwrap() - .write_all(b"int main(void){return 0;}")?; - child.wait() - }) - .map(|s| s.success()) - .unwrap_or(false); - if !asan { - return; - } - for stem in stems { - let rel = format!("tests/retslot/{}.trk", stem); - let exe = dir.join(format!("{}_asan", stem)); - let out = Command::new(trackc()) - .args(["build", &rel, "-o", exe.to_str().unwrap()]) - .env("CC", "gcc -fsanitize=address -g") - .env("TRACKC_CACHE", dir.join("cache")) - .current_dir(&root) - .output() - .unwrap(); - assert!(out.status.success(), "{}: ASan build failed", rel); - let run = Command::new(&exe) - .env("ASAN_OPTIONS", "detect_leaks=0") - .output() - .unwrap(); - let err = String::from_utf8_lossy(&run.stderr); - assert!( - run.status.success() && !err.contains("AddressSanitizer"), - "{}: ASan reports an error:\n{}", - rel, - err - ); - } - let _ = fs::remove_dir_all(&dir); -} - -/// K3a: a user program may define any name a runtime uses internally (the -/// Track runtime's `sum`, `write`, `O_RDONLY`...; the C prelude's `tk_w`, -/// `tk_shl`...). Every runtime, and the native backend, runs it unchanged; -/// the two programs that used to clash with compiler/rt/vec.trk's `sum` -/// build natively. -#[test] -fn user_names_never_clash_with_runtime_names() { - let root = repo(); - let dir = scratch("names"); - let cases = [ - ("tests/names/rt_clash", vec!["", "--rt=track", "--native"]), - ("tests/stack/read_only", vec!["--native"]), - ("tests/autofree/die_param", vec!["--native"]), - ]; - for (stem, modes) in cases { - let rel = format!("{}.trk", stem); - let want = fs::read_to_string(root.join(format!("{}.out", stem))).unwrap(); - for mode in modes { - let exe = dir.join(format!("{}{}", stem.replace('/', "_"), mode)); - let mut args = vec!["build"]; - if !mode.is_empty() { - args.push(mode); - } - args.extend([rel.as_str(), "-o", exe.to_str().unwrap()]); - let out = run_trackc(&args, &root); - assert!( - out.status.success(), - "{} {}: build failed: {}", - rel, - mode, - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - run_exe(&exe), - (want.clone(), Some(0)), - "{} {}: output differs", - rel, - mode - ); - } - } - let _ = fs::remove_dir_all(&dir); -} - -/// K3a: two definitions of one function are E0201 (trackc), whether in one -/// file or across imports. -/// ngen's inline allocator reads the runtime-state layout constants by -/// name, so a program may not redefine them under `--native`: a user -/// `RT_BASE` (and friends) is E0201, not a binary that segfaults. -#[test] -fn runtime_layout_consts_stay_reserved() { - let dir = scratch("layoutconst"); - for name in [ - "RT_BASE", - "RS_USED", - "RS_HEAP", - "RS_LIMIT", - "RS_HEAP_END", - "RS_FREE", - ] { - let file = format!("{}.trk", name); - fs::write( - dir.join(&file), - format!( - "const {} = 5;\nstruct P {{ x: i64 }}\nfn mk(i: i64) -> P {{ return P {{ x: i }}; }}\nfn main() -> i64 {{ let p = mk(3); print(p.x); return 0; }}\n", - name - ), - ) - .unwrap(); - let exe = dir.join(name); - let out = run_trackc( - &["build", "--native", &file, "-o", exe.to_str().unwrap()], - &dir, - ); - let err = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success() && err.contains("E0201"), - "{}: user const accepted under --native: {}", - name, - err - ); - } -} - -#[test] -fn duplicate_functions_are_rejected() { - let dir = scratch("dupfn"); - fs::write( - dir.join("other.trk"), - "fn place_root() -> i64 { return 7; }\n", - ) - .unwrap(); - fs::write( - dir.join("one.trk"), - "fn place_root() -> i64 { return 1; }\nfn place_root() -> i64 { return 2; }\nfn main() -> i64 { print(place_root()); return 0; }\n", - ) - .unwrap(); - fs::write( - dir.join("two.trk"), - "import \"other\";\nfn place_root() -> i64 { return 2; }\nfn main() -> i64 { print(place_root()); return 0; }\n", - ) - .unwrap(); - for file in ["one.trk", "two.trk"] { - for mode in ["check", "build"] { - let out = run_trackc(&[mode, file], &dir); - let err = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success() - && err.contains("error[E0201]: duplicate definition of function 'place_root'"), - "{} {}: duplicate accepted: {}", - mode, - file, - err - ); - } - } - let _ = fs::remove_dir_all(&dir); -} - -/// K3a: strings are pointers (SPEC §11) and concatenation is -/// `str_concat(&a, &b)` (docs/stdlib.md); `a + b` on two strings would add -/// the pointers, so trackc rejects it. -#[test] -fn string_plus_string_is_a_type_error() { - let dir = scratch("strplus"); - let bad = [ - "fn main() -> i64 { let a = \"ab\"; let b = \"cd\"; let c = a + b; print(c); return 0; }\n", - "fn main() -> i64 { print(\"ab\" + \"cd\"); return 0; }\n", - "fn main() -> i64 { let a = \"ab\"; let s = str_concat(&a, &a); let t = s + a; print(t); return 0; }\n", - ]; - for (i, src) in bad.iter().enumerate() { - let file = format!("bad{}.trk", i); - fs::write(dir.join(&file), src).unwrap(); - let out = run_trackc(&["check", &file], &dir); - let err = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success() && err.contains("str_concat"), - "{}: string + string accepted: {}", - src, - err - ); - } - // Pointer arithmetic (string + integer, string - string) stays legal. - fs::write( - dir.join("ok.trk"), - "fn main() -> i64 { let a = \"abcd\"; let n = 2; let p = a + n; print(p - a); return 0; }\n", - ) - .unwrap(); - let out = run_trackc(&["check", "ok.trk"], &dir); - assert!( - out.status.success(), - "string + int rejected: {}", - String::from_utf8_lossy(&out.stderr) - ); - let _ = fs::remove_dir_all(&dir); -} - -/// K3b: `for x in a` binds the elements of array `a` (`&a` borrows it), -/// `for i in s..e` counts; an empty array runs the body zero times. On -/// both runtimes, `exit(3)` and a division-by-zero trap keep what was -/// printed. A scalar iterable is a type error. -#[test] -fn for_in_exit_and_div_trap_on_both_runtimes() { - use std::os::unix::process::ExitStatusExt; - let dir = scratch("k3b"); - let (c, t) = run_under_both_runtimes(&dir, "for_in", &repo().join("tests/native/for_in.trk")); - let want = "10\n20\n30\n3\n2\n3\n4\n10\n20\n30\n110\n120\n130\nab\ncde\n60\n11\n21\n31\n"; - assert_eq!(c, (want.to_string(), Some(0)), "for_in: C runtime"); - assert_eq!(t, c, "for_in: Track runtime differs"); - let (c, t) = run_under_both_runtimes( - &dir, - "exit_flush", - &repo().join("tests/native/exit_flush.trk"), - ); - assert_eq!(c, ("1\n".to_string(), Some(3)), "exit_flush: C runtime"); - assert_eq!(t, c, "exit_flush: Track runtime differs"); - run_under_both_runtimes( - &dir, - "divzero_flush", - &repo().join("tests/native/divzero_flush.trk"), - ); - for exe in ["divzero_flush_crt", "divzero_flush_trt"] { - let out = Command::new(dir.join(exe)).output().unwrap(); - assert_eq!( - ( - String::from_utf8_lossy(&out.stdout).to_string(), - out.status.signal() - ), - ("1\n".to_string(), Some(8)), - "{}: output lost on SIGFPE", - exe - ); - } - fs::write( - dir.join("forint.trk"), - "fn main() -> i64 { let n = 3; for i in n { print(i); } return 0; }\n", - ) - .unwrap(); - let out = run_trackc(&["check", "forint.trk"], &dir); - let err = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success() && err.contains("`for` iterates over a range or an array"), - "for over an integer accepted: {}", - err - ); - // F3: a range bound as a value segfaulted on both backends; it is E0200. - fs::write( - dir.join("rangeval.trk"), - "fn main() -> void { let r = (0-1)..3; for i in r { print(i); } }\n", - ) - .unwrap(); - let out = run_trackc(&["check", "rangeval.trk"], &dir); - let err = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success() && err.contains("A range `a..b` is not a value"), - "range bound as a value accepted: {}", - err - ); - let _ = fs::remove_dir_all(&dir); -} - -/// K3c: `INT64_MIN / -1` (and `% -1`) traps like a zero divisor on every -/// backend and runtime: what was printed is flushed, then SIGFPE. Native -/// once took the hardware idiv fault and lost the buffered output. -#[test] -fn int64_min_div_minus_one_flushes_on_every_backend() { - use std::os::unix::process::ExitStatusExt; - let dir = scratch("k3c_divmin"); - for (stem, want) in [ - ("divmin_flush", "-7\n0\n-9223372036854775807\n"), - ("divmin_mod_flush", "0\n"), - ] { - let src = repo().join(format!("tests/native/{}.trk", stem)); - for mode in ["", "--rt=track", "--native"] { - let exe = dir.join(format!("{}{}", stem, mode.replace(['-', '='], "_"))); - let mut args = vec!["build"]; - if !mode.is_empty() { - args.push(mode); - } - args.extend([src.to_str().unwrap(), "-o", exe.to_str().unwrap()]); - let out = run_trackc(&args, &dir); - assert!(out.status.success(), "{} {}: build failed", stem, mode); - let out = Command::new(&exe).output().unwrap(); - assert_eq!( - ( - String::from_utf8_lossy(&out.stdout).to_string(), - out.status.signal() - ), - (want.to_string(), Some(8)), - "{} {}: output lost or wrong signal", - stem, - mode - ); - } - } - let _ = fs::remove_dir_all(&dir); -} diff --git a/tests/sh/cli.sh b/tests/sh/cli.sh new file mode 100644 index 00000000..18c90f94 --- /dev/null +++ b/tests/sh/cli.sh @@ -0,0 +1,66 @@ +# trackc CLI behaviour, ported from tests/cli_tests.rs (which drove the +# Rust `track` binary; trackc has the same commands and messages). + +t_cli_help() { + trackc --help + rc_ok "--help" + has "$OUT$ERR" "USAGE:" "help text" +} + +t_cli_check_command() { + write "$T/test.trk" 'fn main() -> void { print(42); }' + trackc_in "$T" check test.trk + rc_ok "check" + has "$OUT" "Check passed" "stdout" +} + +t_cli_invalid_command() { + trackc nonexistent_command + rc_fail "unknown command" + has "$ERR" "Unknown command" "stderr" +} + +t_cli_version_reports_1_0_0() { + trackc --version + rc_ok "--version" + has "$OUT$ERR" "1.0.0" "version" +} + +t_cli_duplicate_function_is_a_diagnostic() { + write "$T/dup.trk" 'fn place_root() -> i64 { return 1; } +fn place_root() -> i64 { return 2; } +fn main() -> i64 { print(place_root()); return 0; } +' + local mode + for mode in check build; do + trackc_in "$T" "$mode" dup.trk + rc_is 1 "$mode" + has "$ERR" "error[E0201]: duplicate definition of function 'place_root'" "$mode" + lacks "$ERR" "panicked" "$mode" + done +} + +t_cli_duplicate_function_through_import_is_a_diagnostic() { + write "$T/other.trk" 'fn place_root() -> i64 { return 1; } +' + write "$T/main.trk" 'import "other"; +fn place_root() -> i64 { return 2; } +fn main() -> i64 { print(place_root()); return 0; } +' + local mode + for mode in check build; do + trackc_in "$T" "$mode" main.trk + rc_is 1 "$mode" + has "$ERR" "error[E0201]: duplicate definition of function 'place_root'" "$mode" + done +} + +# Build with no -o: the executable is written next to the source's stem. +t_cli_build_and_run_generics() { + write "$T/gen.trk" 'fn identity(x: T) -> T { return x; } fn main() -> void { let a: i32 = 7; print(identity(a)); }' + trackc_in "$T" build gen.trk + rc_ok "build generics" + [ -x "$T/gen" ] || fail "no executable gen" + observe "$T/gen" + stdout_is '7\n' "run" +} diff --git a/tests/sh/ids.txt b/tests/sh/ids.txt new file mode 100644 index 00000000..e57d3dbd --- /dev/null +++ b/tests/sh/ids.txt @@ -0,0 +1,97 @@ +cli/cli_help +cli/cli_check_command +cli/cli_invalid_command +cli/cli_version_reports_1_0_0 +cli/cli_duplicate_function_is_a_diagnostic +cli/cli_duplicate_function_through_import_is_a_diagnostic +cli/cli_build_and_run_generics +lang/checker_verdicts +lang/parser_sources_parse +lang/bitwise_vs_logical_or_precedence +lang/lexer_token_dumps +lang/lexer_invalid_character +lang/valid_examples_compile_and_run +lang/memory_boundary_exceeded_crash +lang/invalid_examples_rejection +lang/for_in_loop_execution +lang/explicit_error_handling_convention +lang/logical_not_operator +lang/const_resolution_across_functions +lang/error_predicates_disambiguate_sentinels +lang/generics_monomorphization +lang/executables_are_position_independent +lang/for_in_binds_array_elements +lang/program_arguments_reach_os_args +lang/logical_operators_short_circuit_and_normalise +lang/return_inside_match_while_and_nested_if +lang/if_and_match_produce_values +lang/returned_tuple_variables_do_not_dangle +lang/string_patterns_compare_contents +lang/union_payloads_and_enum_discriminants +lang/constants_fold_comparisons_and_variants +lang/negative_runtime_results_keep_their_sign +lang/block_bindings_do_not_leak_into_the_enclosing_scope +lang/structs_and_arrays_have_runtime_values +lang/array_index_out_of_bounds_aborts +lang/division_by_zero_flushes_and_raises_sigfpe +lang/int64_min_div_minus_one_flushes_and_raises_sigfpe +lang/performance_lexer_throughput +lang/performance_parser_throughput +lang/performance_full_pipeline_throughput +lifecycle/life_dumps_match_goldens +lifecycle/life_place_dumps_match_goldens +lifecycle/stack_cells_run_and_plan +lifecycle/autofree_frees_heap_cells +lifecycle/handles_free_fresh_values +lifecycle/temps_free_fresh_temporaries +lifecycle/temps_free_fresh_cell_temporaries +lifecycle/strfield_frees_owned_str_fields +lifecycle/returns_hidden_in_expressions_are_seen +lifecycle/ret_slots_write_caller_cells +lifecycle/user_names_never_clash_with_runtime_names +lifecycle/runtime_layout_consts_stay_reserved +lifecycle/duplicate_functions_are_rejected +lifecycle/string_plus_string_is_a_type_error +lifecycle/for_in_exit_and_div_trap_on_both_runtimes +lifecycle/int64_min_div_minus_one_flushes_on_every_backend +native/native_build_needs_no_c_toolchain +native/native_programs_match_the_c_backend +native/native_compiler_reaches_a_fixed_point +native/native_and_track_rt_reject_what_check_rejects +native/native_tuples_outlive_their_frame +native/native_identical_string_literals_compare_equal +native/native_program_without_main_builds +native/native_flag_is_honoured_in_any_position +native/native_executables_have_a_non_executable_stack +native/native_and_c_print_the_expected_output +selfhost/build_creates_missing_output_directories +selfhost/runtime_object_is_cached_and_builds_stay_identical +selfhost/native_binaries_carry_a_symbol_table +selfhost/bootstrap_reaches_a_fixed_point +selfhost/examples_behave_the_same_under_both_compilers +selfhost/checkers_agree_on_accepted_and_rejected_programs +selfhost/const_divrem_traps_are_e0200_in_both_checkers +selfhost/diagnostics_point_at_the_source +selfhost/native_test_suite_passes_under_trackc +selfhost/track_runtime_matches_the_c_runtime +selfhost/program_without_main_runs_on_both_runtimes +selfhost/trackc_on_the_track_runtime_self_compiles +selfhost/warnings_print_sorted_and_only_deny_warnings_fails +selfhost/lifecycle_warnings_match_the_catalogue +selfhost/examples_warn_only_where_intended +selfhost/compiler_sources_are_warning_clean +selfhost/trackc_closes_checker_holes +selfhost/lifecycle_hard_errors_print_the_catalogue_texts +selfhost/lifecycle_lookalikes_check_clean +selfhost/non_escaping_tuples_use_stack_slots +selfhost/trackc_programs_print_the_expected_output +tools/vscode_package_json +tools/vscode_language_configuration +tools/vscode_textmate_grammar +tools/nvim_plugin_files +tools/vscode_grammar_headless_tokenization +tools/vscode_grammar_valid_json_headless +tools/nvim_headless_filetype_and_syntax +tools/nvim_headless_lua_syntax_ok +tools/nvim_devicon_svg_not_needed_headless +tools/nvim_syntax_highlight_sample_headless diff --git a/tests/sh/lang.sh b/tests/sh/lang.sh new file mode 100644 index 00000000..8152a242 --- /dev/null +++ b/tests/sh/lang.sh @@ -0,0 +1,271 @@ +# Language-level tests ported from the Rust stage0 suites +# (integration_tests.rs, codegen_semantics_tests.rs, regression_tests.rs, +# soundness_tests.rs, logic_and_soundness_strict_tests.rs, checker_tests.rs, +# lexer_tests.rs, parser_tests.rs, performance_tests.rs). The Rust tests +# drove stage0's library; these drive trackc with the same sources and the +# same (or stricter) expectations. Data lives in tests/cases/lang/. + +LANG_CASES="$ROOT/tests/cases/lang" + +# verdict_table FILE: every row `namercprefixsource` must get +# exit `rc` from `trackc check`; prefix "-" means stderr has no error line, +# else stderr's first line starts with prefix. With PARSE=1, stderr must +# also hold no lexer (E0001) or parser (E01xx) diagnostic. +verdict_table() { + local name rc prefix src n=0 + while IFS=$'\t' read -r name rc prefix src; do + case "$name" in '#'* | '') continue ;; esac + n=$((n + 1)) + printf '%s' "$src" >"$T/$name.trk" + trackc_in "$T" check "$name.trk" + rc_is "$rc" "$name" + if [ "$prefix" = - ]; then + lacks "$ERR" "error[" "$name" + else + starts "$ERR" "$prefix" "$name" + fi + if [ "${PARSE:-0}" = 1 ]; then + lacks "$ERR" "error[E0001]" "$name: lexer error" + lacks "$ERR" "error[E01" "$name: parse error" + fi + done <"$1" + [ "$n" -gt 0 ] || fail "no rows in $1" + note "$n verdicts" +} + +t_checker_verdicts() { verdict_table "$LANG_CASES/verdicts.tsv"; } + +t_parser_sources_parse() { PARSE=1 verdict_table "$LANG_CASES/parses.tsv"; } + +# parse_bitwise_vs_logical_precedence: `a | b || c & d` is +# `(a | b) || (c & d)`; with a=2, b=c=d=0 only that grouping prints 1 +# (`a | ((b || c) & d)` gives 2, `((a | b) || c) & d` gives 0). +t_bitwise_vs_logical_or_precedence() { + write "$T/p.trk" 'fn main() -> void { let a = 2; let b = 0; let c = 0; let d = 0; let res = a | b || c & d; print(res); }' + build "$T/p.trk" "$T/p" + observe "$T/p" + rc_ok "run" + stdout_is '1\n' "precedence" +} + +# lexer_tests.rs: `trackc tokens` dumps match goldens that list the same +# token kinds the Rust tests asserted. +t_lexer_token_dumps() { + local s + for s in lex_keywords lex_types lex_literals lex_operators lex_comments; do + trackc tokens "$LANG_CASES/$s.trk" + rc_ok "$s" + out_is "$LANG_CASES/$s.tokens" "$s" + done +} + +t_lexer_invalid_character() { + write "$T/e.trk" 'let x = #;' + trackc_in "$T" tokens e.trk + rc_is 1 "tokens" + starts "$ERR" "error[E0001]: unexpected character + --> e.trk:1:9" "diagnostic" + trackc_in "$T" check e.trk + rc_is 1 "check" + starts "$ERR" "error[E0001]: unexpected character" "check diagnostic" +} + +# integration_tests.rs ------------------------------------------------------ + +t_valid_examples_compile_and_run() { + local e + for e in hello arithmetic borrow linear_auto_free macro_test union_enum_test use_test; do + [ -f "$ROOT/examples/$e.trk" ] || fail "example not found: $e" + build "$ROOT/examples/$e.trk" "$T/$e" + cap_in "$ROOT/examples" "$T/$e" + rc_ok "$e: run" + done +} + +t_memory_boundary_exceeded_crash() { + build "$LANG_CASES/mem_test.trk" "$T/m" + observe "$T/m" + rc_fail "memory boundary exceeded program should fail" + has "$ERR" "Process memory boundary limit exceeded" "stderr" +} + +t_invalid_examples_rejection() { + local e want + while read -r e want; do + trackc check "$ROOT/examples/$e.trk" + rc_is 1 "$e" + has "$ERR" "$want" "$e" + done <<'CASES' +borrow_lock_err frozen +escape_err escapes +manual_free_err managed automatically +CASES +} + +t_for_in_loop_execution() { + build "$LANG_CASES/for_test.trk" "$T/f" + observe "$T/f" + rc_ok "for loop" + stdout_is '0\n1\n2\n' "for loop" +} + +t_explicit_error_handling_convention() { + build "$LANG_CASES/error_handling.trk" "$T/e" + observe "$T/e" + rc_ok "run" + local first second + first=$(sed -n 1p "$T/.out") + second=$(sed -n 2p "$T/.out") + if [ -e /etc/hostname ]; then + [ -n "$first" ] && [ "$first" != -1 ] || fail "want a real size for /etc/hostname, got [$first]" + fi + eq "$second" 7 "fallback for the missing file" + has "$ERR" "missing input" "stderr" +} + +t_logical_not_operator() { + build "$LANG_CASES/lnot.trk" "$T/l" + observe "$T/l" + rc_ok "run" + if [ -e /etc/hostname ]; then stdout_is '42\n' "logical not"; fi +} + +t_const_resolution_across_functions() { + build "$LANG_CASES/consts.trk" "$T/c" + observe "$T/c" + rc_ok "run" + stdout_is '100\n123\n' "consts" +} + +t_error_predicates_disambiguate_sentinels() { + build "$LANG_CASES/pred.trk" "$T/p" + observe "$T/p" + rc_ok "run" + stdout_is '42\n111\n222\n333\n' "predicates" +} + +t_generics_monomorphization() { + build "$LANG_CASES/gen.trk" "$T/g" + observe "$T/g" + rc_ok "run" + stdout_is '5\n10\n1\n2\n1\n2\n' "generics" +} + +# codegen_semantics_tests.rs ------------------------------------------------ + +t_executables_are_position_independent() { + write "$T/pie.trk" 'fn main() -> i64 { print(25988585); return 0; } +' + build "$T/pie.trk" "$T/pie" + eq "$(u16_at "$T/pie" 16)" 3 "ELF type must be ET_DYN (PIE)" + observe "$T/pie" + stdout_is '25988585\n' "stdout" +} + +t_for_in_binds_array_elements() { + build "$ROOT/tests/native/for_in.trk" "$T/f" + observe "$T/f" + rc_ok "run" + stdout_is '10\n20\n30\n3\n2\n3\n4\n10\n20\n30\n110\n120\n130\nab\ncde\n60\n11\n21\n31\n' "for_in" +} + +t_program_arguments_reach_os_args() { + build "$LANG_CASES/argv.trk" "$T/a" + observe "$T/a" hello + rc_ok "run" + stdout_is '2\nhello\n' "argv" +} + +# sem_case STEM WANT: build tests/cases/lang/STEM.trk, run, exit 0, stdout. +sem_case() { + build "$LANG_CASES/$1.trk" "$T/$1" + observe "$T/$1" + rc_ok "$1: run" + stdout_is "$2" "$1" +} + +t_logical_operators_short_circuit_and_normalise() { sem_case logic '10\n0\n3\n13\n1\n'; } +t_return_inside_match_while_and_nested_if() { sem_case returns '10\n20\n8\n7\n8\n9\n5\n6\n'; } +t_if_and_match_produce_values() { sem_case values '-1\n0\n1\n200\n300\n'; } +t_returned_tuple_variables_do_not_dangle() { sem_case tuples '5\n6\n9\n'; } +t_string_patterns_compare_contents() { sem_case strpat '1\n'; } +t_union_payloads_and_enum_discriminants() { sem_case unions '42\n1001\n0\n5\n6\n10\n'; } +t_constants_fold_comparisons_and_variants() { sem_case constfold '1\n1\n2\n12\n1\n7\n'; } +t_negative_runtime_results_keep_their_sign() { sem_case signs '-1\n98\n'; } +t_block_bindings_do_not_leak_into_the_enclosing_scope() { sem_case scopes '20\n10\n1\n10\n'; } +t_structs_and_arrays_have_runtime_values() { sem_case structs '3\n4\n18\n4\n2\n40\n9\n'; } + +t_array_index_out_of_bounds_aborts() { + write "$T/b.trk" 'fn main() -> void { let a = [1, 2]; print(a[2]); }' + build "$T/b.trk" "$T/b" + observe "$T/b" + rc_is 134 "abort status" + has "$ERR" "array index out of bounds" "stderr" +} + +# sigfpe_case NAME SOURCE WANT: stdout is flushed, then SIGFPE (136). +sigfpe_case() { + write "$T/$1.trk" "$2" + build "$T/$1.trk" "$T/$1" + observe "$T/$1" + stdout_is "$3" "$1" + rc_is 136 "$1: expected SIGFPE" +} + +t_division_by_zero_flushes_and_raises_sigfpe() { + sigfpe_case divz 'fn main()->i64{ print(1); let mut i=3; while i>=0 { print(100/i); i=i-1; } return 0; }' '1\n33\n50\n100\n' + sigfpe_case modz 'fn main()->i64{ print(7); let z = 0; print(5 % z); return 0; }' '7\n' + sigfpe_case constz 'fn main()->i64{ print(2); print(9 / 0); return 0; }' '2\n' + sigfpe_case shadowz 'const TWO = 2; const ONE = 1 < 2; fn d(TWO: i64) -> i64 { return 7 / TWO; } fn e(ONE: i64) -> i64 { return 7 % (ONE + 1); } fn main()->i64{ print(3); print(e(1)); print(d(0)); return 0; }' '3\n1\n' +} + +t_int64_min_div_minus_one_flushes_and_raises_sigfpe() { + write "$T/negone.trk" 'fn main()->i64{ let m = -1; print(7 / m); print(7 % m); print(-9223372036854775807 / m); return 0; }' + build "$T/negone.trk" "$T/negone" + observe "$T/negone" + rc_ok "negone" + stdout_is '-7\n0\n9223372036854775807\n' "negone" + sigfpe_case mindiv 'fn main()->i64{ print(3); let m = -1; let a = -9223372036854775807 - 1; print(a / m); return 0; }' '3\n' + sigfpe_case minmod 'fn main()->i64{ print(3); let m = -1; let a = -9223372036854775807 - 1; print(a % m); return 0; }' '3\n' +} + +# performance_tests.rs: same inputs and the same 5 s ceilings, on trackc. + +now_ms() { echo $(($(date +%s%N) / 1000000)); } + +t_performance_lexer_throughput() { + local i start ms ntok + for i in $(seq 5000); do echo 'let mut x: i64 = 100 + 200 * 300 / 400;'; done >"$T/big.trk" + start=$(now_ms) + trackc tokens "$T/big.trk" + ms=$(($(now_ms) - start)) + rc_ok "tokens" + ntok=$(($(wc -l <"$T/.out") - 1)) + note "lexed $ntok tokens in ${ms}ms" + [ "$ntok" -ge 60000 ] || fail "only $ntok tokens" + [ "$ms" -lt 5000 ] || fail "lexer took ${ms}ms" +} + +# Rust parsed 1000 copies of one fn; trackc check also resolves names, so +# the copies get distinct names (a repeated fn is E0201). +t_performance_parser_throughput() { + local i start ms + for i in $(seq 0 999); do echo "fn add$i(a: i32, b: i32) -> i32 { return a + b; }"; done >"$T/p.trk" + start=$(now_ms) + trackc check "$T/p.trk" + ms=$(($(now_ms) - start)) + rc_ok "check" + note "checked 1000 functions in ${ms}ms" + [ "$ms" -lt 5000 ] || fail "parser took ${ms}ms" +} + +t_performance_full_pipeline_throughput() { + local i start ms + for i in $(seq 0 499); do echo "fn compute$i(x: i32) -> i32 { let y = x + 1; return y * 2; }"; done >"$T/c.trk" + start=$(now_ms) + trackc check "$T/c.trk" + ms=$(($(now_ms) - start)) + rc_ok "check" + note "checked 500 functions in ${ms}ms" + [ "$ms" -lt 5000 ] || fail "pipeline took ${ms}ms" +} diff --git a/tests/sh/lib.sh b/tests/sh/lib.sh new file mode 100644 index 00000000..98c92939 --- /dev/null +++ b/tests/sh/lib.sh @@ -0,0 +1,240 @@ +# Shared helpers for the cargo-free test runner (tests/run.sh). +# +# A suite is tests/sh/.sh; each `t_() { ... }` in it is one +# test. The runner sources this file and the suite, then calls the test in +# a fresh bash process with: +# +# ROOT the repository root (absolute) +# TRACKC the trackc under test (absolute) +# T a private, empty scratch directory (cwd at start) +# +# A test passes when its function returns 0. Every assertion helper calls +# `fail`, which prints the message and exits 1, so the first broken check +# ends the test (as an assert! did in the Rust suites). +# +# `cap CMD...` runs a command with its output in files: stdout in $T/.out, +# stderr in $T/.err, the exit status in RC. OUT and ERR hold the same text +# (trailing newlines stripped, as $(...) does); use `out_is` / `cmp` on the +# files when trailing newlines matter. + +set -u + +fail() { + printf 'FAIL: %s\n' "$*" >&2 + exit 1 +} + +note() { printf '%s\n' "$*" >&2; } + +cap() { + "$@" >"$T/.out" 2>"$T/.err" + RC=$? + OUT=$(cat "$T/.out") + ERR=$(cat "$T/.err") + return 0 +} + +# cap_in DIR CMD...: cap with DIR as the working directory. +cap_in() { + local dir=$1 + shift + (cd "$dir" && "$@") >"$T/.out" 2>"$T/.err" + RC=$? + OUT=$(cat "$T/.out") + ERR=$(cat "$T/.err") + return 0 +} + +# Show the captured streams after a failure message. +ctx() { + printf -- '--- rc=%s\n--- stdout:\n%s\n--- stderr:\n%s\n' "$RC" "$(head -c 4000 "$T/.out")" "$(head -c 4000 "$T/.err")" +} + +trackc() { cap "$TRACKC" "$@"; } +trackc_in() { + local dir=$1 + shift + cap_in "$dir" "$TRACKC" "$@" +} + +# Assertions -------------------------------------------------------------- + +eq() { # eq GOT WANT MSG + [ "$1" = "$2" ] || fail "$3: got [$1], want [$2]" +} + +ne() { # ne GOT UNWANTED MSG + [ "$1" != "$2" ] || fail "$3: got [$1]" +} + +rc_is() { # rc_is WANT MSG (against the last cap) + [ "$RC" = "$1" ] || fail "$2: exit $RC, want $1 +$(ctx)" +} + +rc_ok() { rc_is 0 "$1"; } + +rc_fail() { # rc_fail MSG: any non-zero exit + [ "$RC" != 0 ] || fail "$1: exit 0, want failure +$(ctx)" +} + +has() { # has HAYSTACK NEEDLE MSG + case "$1" in + *"$2"*) ;; + *) fail "$3: missing [$2] in: +$1" ;; + esac +} + +lacks() { # lacks HAYSTACK NEEDLE MSG + case "$1" in + *"$2"*) fail "$3: unexpected [$2] in: +$1" ;; + *) ;; + esac +} + +starts() { # starts HAYSTACK PREFIX MSG + case "$1" in + "$2"*) ;; + *) fail "$3: does not start with [$2]: +$1" ;; + esac +} + +# count HAYSTACK NEEDLE: non-overlapping occurrences (str::matches().count()). +count() { + local hay=$1 needle=$2 n=0 + [ -n "$needle" ] || { echo 0; return; } + while :; do + case "$hay" in + *"$needle"*) n=$((n + 1)); hay=${hay#*"$needle"} ;; + *) break ;; + esac + done + echo "$n" +} + +# pos HAYSTACK NEEDLE: byte offset of the first match, or a huge number. +pos() { + case "$1" in + *"$2"*) local pre=${1%%"$2"*}; echo "${#pre}" ;; + *) echo 999999999 ;; + esac +} + +# out_is FILE MSG: the last captured stdout equals FILE byte for byte. +out_is() { + cmp -s "$T/.out" "$1" || fail "$2: stdout differs from $1 +$(diff "$1" "$T/.out" | head -n 40)" +} + +# same_file A B MSG +same_file() { + cmp -s "$1" "$2" || fail "$3: $1 and $2 differ" +} + +# Programs ---------------------------------------------------------------- + +# observe EXE [ARGS...]: run EXE from $T; stdout in $T/.out, stderr $T/.err, +# status RC (a signal is 128+N, so SIGFPE is 136). +observe() { cap "$@"; } + +# same_run A B MSG: two observed runs (stdout file + code) must agree. +# Usage: observe a; save_run a; observe b; save_run b; same_run a b msg +save_run() { + cp "$T/.out" "$T/.run_$1.out" + echo "$RC" >"$T/.run_$1.rc" +} +same_run() { + # 126/127 mean the program never ran (missing or not executable): two + # missing binaries must not count as agreeing. + case "$(cat "$T/.run_$1.rc") $(cat "$T/.run_$2.rc")" in + 126\ *|127\ *|*\ 126|*\ 127) fail "$3: a program did not run (exit 126/127)" ;; + esac + cmp -s "$T/.run_$1.out" "$T/.run_$2.out" \ + || fail "$3: stdout differs +$(diff "$T/.run_$1.out" "$T/.run_$2.out" | head -n 40)" + [ "$(cat "$T/.run_$1.rc")" = "$(cat "$T/.run_$2.rc")" ] \ + || fail "$3: exit $(cat "$T/.run_$1.rc") vs $(cat "$T/.run_$2.rc")" +} + +# build SRC EXE [FLAGS...]: trackc build, must succeed. +build() { + local src=$1 exe=$2 + shift 2 + trackc build "$@" "$src" -o "$exe" + rc_ok "build $* $src" + is_exe "$exe" "build $* $src" +} + +# is_exe PATH MSG: PATH must be an executable file (a build that exits 0 +# without writing its output is a failure). +is_exe() { [ -f "$1" ] && [ -x "$1" ] || fail "$2: no executable at $1"; } + +build_native() { build "$1" "$2" --native; } + +# write FILE TEXT: write TEXT verbatim (printf %s, no added newline). +write() { printf '%s' "$2" >"$1"; } + +# trk_files DIR: sorted *.trk paths in DIR (one per line). +trk_files() { + local f + for f in "$1"/*.trk; do + [ -e "$f" ] && echo "$f" + done | LC_ALL=C sort +} + +stem() { local b=${1##*/}; echo "${b%.*}"; } + +# Toolchain probes ---------------------------------------------------------- + +# have_asan: gcc can build and run an AddressSanitizer program (cached). +have_asan() { + if [ -z "${TRACK_HAVE_ASAN:-}" ]; then + TRACK_HAVE_ASAN=no + if command -v gcc >/dev/null 2>&1; then + local d + d=$(mktemp -d "$T/.asan.XXXX") + printf 'int main(void){return 0;}\n' >"$d/a.c" + if gcc -fsanitize=address "$d/a.c" -o "$d/a" >/dev/null 2>&1 && "$d/a" >/dev/null 2>&1; then + TRACK_HAVE_ASAN=yes + fi + rm -rf "$d" + fi + export TRACK_HAVE_ASAN + fi + [ "$TRACK_HAVE_ASAN" = yes ] +} + +have() { command -v "$1" >/dev/null 2>&1; } + +skip() { + note "SKIP: $*" + exit 0 +} + +# Binary files -------------------------------------------------------------- + +# u8_at/u16_at/u32_at/u64_at FILE OFFSET: little-endian unsigned integer. +u8_at() { od -An -v -t u1 -j "$2" -N 1 "$1" | tr -d ' \n'; } +u16_at() { od -An -v -t u2 --endian=little -j "$2" -N 2 "$1" | tr -d ' \n'; } +u32_at() { od -An -v -t u4 --endian=little -j "$2" -N 4 "$1" | tr -d ' \n'; } +u64_at() { od -An -v -t u8 --endian=little -j "$2" -N 8 "$1" | tr -d ' \n'; } + +fsize() { wc -c <"$1" | tr -d ' '; } + +# grep_bytes FILE STRING: FILE contains STRING as raw bytes. +grep_bytes() { LC_ALL=C grep -qaF -- "$2" "$1"; } + +# in_repo CMD...: cap with the repository root as the working directory. +in_repo() { cap_in "$ROOT" "$@"; } + +# stdout_is TEXT MSG: the last captured stdout is exactly TEXT (printf +# escapes such as \n are expanded; trailing newlines count). +stdout_is() { + printf -- "$1" >"$T/.want" + cmp -s "$T/.out" "$T/.want" || fail "$2: stdout differs +$(diff "$T/.want" "$T/.out" | head -n 40)" +} diff --git a/tests/sh/lifecycle.sh b/tests/sh/lifecycle.sh new file mode 100644 index 00000000..e958b683 --- /dev/null +++ b/tests/sh/lifecycle.sh @@ -0,0 +1,525 @@ +# Lifecycle dumps, placement plans, auto-free and the K3 regressions. +# Port of tests/selfhost_tests.rs from life_dumps_match_goldens through +# int64_min_div_minus_one_flushes_on_every_backend. trackc runs from the +# repository root and built programs run from it too, as under cargo. +# UPDATE_LIFE=1 rewrites the .life and .place goldens. + +# golden GOT_FILE GOLDEN MSG: GOT_FILE equals GOLDEN byte for byte +# (UPDATE_LIFE=1 first copies GOT_FILE over GOLDEN). +golden() { + if [ -n "${UPDATE_LIFE+x}" ]; then + mkdir -p "$(dirname "$2")" + cp "$1" "$2" + fi + [ -f "$2" ] || fail "missing golden $2" + cmp -s "$1" "$2" || fail "$3: differs from $2 +$(diff "$2" "$1" | head -n 40)" +} + +# run_want EXE WANT_FILE MSG: EXE (run from the repo root) prints exactly +# WANT_FILE and exits 0. +run_want() { + in_repo "$1" + out_is "$2" "$3" + rc_is 0 "$3" +} + +# plan REL: `trackc life --place REL` into $T/plan.got; appended to +# $T/plans as ":\n" (the Rust `plans` string). +plan() { + in_repo "$TRACKC" life --place "$1" + cp "$T/.out" "$T/plan.got" + { printf '%s:\n' "$(stem "$1")"; cat "$T/plan.got"; } >>"$T/plans" +} + +# plans_text: the accumulated plans, trailing newline kept. +plans_text() { + local s + s=$(cat "$T/plans"; echo .) + printf '%s' "${s%.}" +} + +# block PLANS PROG: the text after the first "PROG:\n", cut at the next ":\n". +block() { + local b + case "$1" in + *"$2:"$'\n'*) b=${1#*"$2:"$'\n'} ;; + *) b= ;; + esac + printf '%s' "${b%%:$'\n'*}" +} + +# need_lines PLANS: each stdin line "LINE|WHY" must occur in PLANS. +need_lines() { + local line why + while IFS='|' read -r line why; do + has "$1" "$line" "$why" + done +} + +# no_line_starting BLOCK PREFIX WORD MSG: no line of BLOCK, left-trimmed, +# starts with PREFIX (right-trimmed) and contains WORD. +no_line_starting() { + local l t p=${2%"${2##*[! ]}"} + while IFS= read -r l; do + t=${l#"${l%%[! ]*}"} + case "$t" in + "$p"*) case "$l" in *"$3"*) fail "$4: [$l] in: +$1" ;; esac ;; + esac + done <<<"$1" +} + +# asan_cc: gcc builds an AddressSanitizer program (the Rust probe: compile +# only, from stdin). +asan_cc() { + printf 'int main(void){return 0;}' | gcc -fsanitize=address -x c - -o "$T/probe" >/dev/null 2>&1 +} + +# asan_run REL LEAKS NEEDLE: build REL with CC="gcc -fsanitize=address -g" +# (private cache), run it with ASAN_OPTIONS=LEAKS; it must exit 0 and its +# stderr must not contain NEEDLE. +asan_run() { + local rel=$1 exe + exe="$T/$(stem "$rel")_asan" + in_repo env CC="gcc -fsanitize=address -g" TRACKC_CACHE="$T/asan-cache" "$TRACKC" build "$rel" -o "$exe" + rc_ok "$rel: ASan build failed" + in_repo env ASAN_OPTIONS="$2" "$exe" + rc_ok "$rel: ASan run ($2)" + lacks "$ERR" "$3" "$rel: ASan reports an error or a leak" +} + +# c_and_native DIR STEM: build tests/DIR/STEM.trk with both backends; each +# prints tests/DIR/STEM.out and exits 0. +c_and_native() { + local rel="tests/$1/$2.trk" want="$ROOT/tests/$1/$2.out" + in_repo "$TRACKC" build "$rel" -o "$T/$2" + rc_ok "$rel: build failed" + run_want "$T/$2" "$want" "$rel: C output differs" + in_repo "$TRACKC" build --native "$rel" -o "$T/$2_nat" + rc_ok "$rel: native build failed" + run_want "$T/$2_nat" "$want" "$rel: native output differs" +} + +t_life_dumps_match_goldens() { + local checked=0 sub f rel + for sub in docs/lifecycles bench/progs tests/life/progs; do + for f in $(trk_files "$ROOT/$sub"); do + rel=${f#"$ROOT/"} + in_repo "$TRACKC" life "$rel" + rc_ok "$rel: trackc life failed" + golden "$T/.out" "$ROOT/tests/life/$(stem "$f").life" "$rel: lifecycle dump" + checked=$((checked + 1)) + done + done + [ "$checked" -ge 22 ] || fail "expected at least 22 programs, saw $checked" +} + +t_life_place_dumps_match_goldens() { + local f rel n=0 + for f in $(trk_files "$ROOT/tests/life/place"); do + rel=${f#"$ROOT/"} + n=$((n + 1)) + in_repo "$TRACKC" life --place "$rel" + rc_ok "$rel: trackc life --place failed" + golden "$T/.out" "${f%.trk}.place" "$rel: placement plan" + done + [ "$n" -gt 0 ] || fail "no programs in tests/life/place" + in_repo "$TRACKC" life --place tests/life/place/place.trk + need_lines "$OUT" <<'LINES' +L20 tuple stack ends L21|a tuple only destructured lives on the stack +L8 tuple ret-slot ends L8|a returned tuple goes to the caller's slot +L24 struct heap ends -|a value stored into a collection is heap +L26 call heap ends -|a value passed to an esc param is heap +L28 str heap-autofree ends L29|a fresh Str that dies in this frame is auto-freed (L13) +LINES +} + +t_stack_cells_run_and_plan() { + local s rel + for s in escapes mutate read_only union_match; do + rel="tests/stack/$s.trk" + in_repo "$TRACKC" build "$rel" -o "$T/$s" + rc_ok "$rel: build failed" + run_want "$T/$s" "$ROOT/tests/stack/$s.out" "$rel: output differs" + if [ "$s" != escapes ]; then + grep -qF 'tk_w s0[' "$T/$s.c" || fail "$rel: no stack slot in emitted C" + fi + plan "$rel" + golden "$T/plan.got" "$ROOT/tests/stack/$s.place" "$rel: placement plan" + done + need_lines "$(plans_text)" <<'LINES' +L23 struct stack ends L25|a struct only lent to a reading callee is stack +L24 struct stack ends L25|a struct only read through its fields is stack +L29 array stack ends L31|an array only indexed and lent is stack +L8 struct heap ends -|a returned struct is heap +L17 struct heap ends -|a struct stored into another literal is heap +L27 struct heap ends -|a struct passed to a `ret` parameter is heap +L29 struct heap ends -|a struct inside an array literal is heap +L17 struct stack ends L23|a struct mutated through the slot is stack +L21 array stack ends L24|an array written by index is stack +L13 union stack ends L14|a payload union only matched is stack +LINES +} + +t_autofree_frees_heap_cells() { + local stems="die_param early_return moved_field nested returned" s rel + for s in $stems; do + rel="tests/autofree/$s.trk" + in_repo "$TRACKC" build "$rel" -o "$T/$s" + rc_ok "$rel: build failed" + run_want "$T/$s" "$ROOT/tests/autofree/$s.out" "$rel: output differs" + grep -qF 'dealloc(l' "$T/$s.c" || fail "$rel: no free in emitted C" + plan "$rel" + golden "$T/plan.got" "$ROOT/tests/autofree/$s.place" "$rel: placement plan" + done + need_lines "$(plans_text)" <<'LINES' +L23 call heap-autofree deep ends L24|a fresh cell passed to a `die` parameter is freed by the caller +L21 call stack ends L22|a ret-slot result passed to a `die` parameter is a stack slot (L10) +L19 struct stack ends L20|a stack cell passed to a `die` parameter stays a stack cell +L16 call heap-autofree ends L17|a cell whose child is moved out frees only itself +L22 struct heap-autofree deep ends L27|a nested literal reassigned fresh cells runs drop glue +L7 struct heap ends -|a returned cell is never freed +L13 struct heap ends -|a cell stored into a returned cell is never freed +LINES + asan_cc || skip "gcc has no AddressSanitizer" + for s in $stems; do + asan_run "tests/autofree/$s.trk" detect_leaks=0 AddressSanitizer + done +} + +t_handles_free_fresh_values() { + local stems="builder coll_kept coll_local coll_move int_loop str_kept str_local" s rel prog free kept plans moved + for s in $stems; do + rel="tests/handles/$s.trk" + c_and_native handles "$s" + plan "$rel" + golden "$T/plan.got" "$ROOT/tests/handles/$s.place" "$rel: placement plan" + while read -r prog free; do + if [ "$prog" = "$s" ]; then + grep -qF "$free" "$T/$s.c" || fail "$rel: no \`$free\` in emitted C" + fi + done <<'FREES' +str_local track_str_free(l +int_loop track_str_free(l +builder track_sb_free(l +builder track_str_free(l +coll_local track_i64_collection_free(l +coll_local vec_free(l +FREES + done + plans=$(plans_text) + # coll_move (card L15): only `rows` moves a fresh row into `prev` as + # its last mention; the looped and the used-after moves keep both. + moved= + case "$plans" in *coll_move:*) moved=${plans#*coll_move:} ;; esac + moved=${moved%%int_loop:*} + eq "$moved" $'\nfn rows\n L6 collection heap-autofree ends L15\n' "coll_move: moves planned" + need_lines "$plans" <<'LINES' +L4 str heap-autofree ends L6|a str_concat result that dies locally is freed +L14 str heap-autofree ends L17|a Str reassigned fresh strings is freed +L7 str heap-autofree ends L10|an int_to_str in a loop is freed each iteration +L4 builder heap-autofree ends L12|a builder finished into a Str is freed +L12 str heap-autofree ends L13|the finished Str is freed +L3 collection heap-autofree ends L12|a collection that dies locally is freed +L19 vec heap-autofree ends L27|a Vec that dies locally is freed +LINES + while IFS='|' read -r prog kept; do + no_line_starting "$(block "$plans" "$prog")" "$kept" autofree \ + "$prog: a returned, stored or aliased value at \`$kept\` must not be freed" + done <<'KEPT' +str_kept|L4 +str_kept|L12 str +str_kept|L14 str +coll_kept|L7 +coll_kept|L11 +KEPT + asan_cc || skip "gcc has no AddressSanitizer" + for s in $stems; do + asan_run "tests/handles/$s.trk" detect_leaks=0 AddressSanitizer + done +} + +t_temps_free_fresh_temporaries() { + local stems="alias discard kept nested print_loop" s rel plans prog line n why kept leaks + for s in $stems; do + rel="tests/temps/$s.trk" + c_and_native temps "$s" + plan "$rel" + golden "$T/plan.got" "$ROOT/tests/temps/$s.place" "$rel: placement plan" + done + plans=$(plans_text) + while IFS='|' read -r prog line n why; do + eq "$(count "$(block "$plans" "$prog")" "$line")" "$n" "$why: \`$line\` x$n" + done <<'COUNTS' +print_loop|str temp-autofree|2|int_to_str passed to print and str_len is freed +nested|str temp-autofree|6|every nested fresh argument is freed +discard|str temp-autofree|3|discarded results and their fresh arguments are freed +kept|L12 str temp-autofree ends L12|1|int_to_str lent to str_concat is freed +COUNTS + while IFS='|' read -r prog kept; do + no_line_starting "$(block "$plans" "$prog")" "$kept" temp-autofree \ + "$prog: a temporary that is kept or aliased (\`$kept\`) must not be freed" + done <<'KEPT' +kept|L11 +alias|temp-autofree +KEPT + asan_cc || skip "gcc has no AddressSanitizer" + for s in $stems; do + case "$s" in discard | nested | print_loop) leaks=detect_leaks=1 ;; *) leaks=detect_leaks=0 ;; esac + asan_run "tests/temps/$s.trk" "$leaks" Sanitizer + done +} + +t_temps_free_fresh_cell_temporaries() { + local stems="accloop accpass accret alias branch discard kept nested print_loop str_alias str_cell tailr" + local s rel plans b leaks + for s in $stems; do + rel="tests/temps_cell/$s.trk" + c_and_native temps_cell "$s" + plan "$rel" + golden "$T/plan.got" "$ROOT/tests/temps_cell/$s.place" "$rel: placement plan" + done + plans=$(plans_text) + need_lines "$plans" <<'LINES' +L33 call stack ends L33|print_loop +L34 struct stack ends L34|print_loop +L35 call temp-autofree deep ends L35|print_loop +L36 struct temp-autofree deep ends L36|print_loop +L37 tuple stack ends L37|print_loop +L26 call stack ends L26|nested +L18 struct stack ends L18|str_cell +L17 call temp-autofree deep ends L17|str_cell +L23 call temp-autofree deep ends L23|discard +L24 call temp-autofree deep ends L24|discard +L25 call temp-autofree deep ends L25|discard +L19 call temp-autofree deep ends L19|str_alias +L21 call temp-autofree deep ends L21|str_alias +LINES + # Card F3: accumulator recursion with temporary arguments stays a loop + # natively; a million levels deep would overflow as real calls. + in_repo "$TRACKC" build --native tests/temps_cell/accdeep.trk -o "$T/accdeep_nat" + rc_ok "accdeep: native build failed" + run_want "$T/accdeep_nat" "$ROOT/tests/temps_cell/accdeep.out" "accdeep: native output" + eq "$(count "$(block "$plans" nested)" "call temp-autofree deep")" 3 "every nested fresh cell is freed" + for s in kept alias; do + b=$(block "$plans" "$s") + lacks "$b" temp-autofree "$s: a cell that is kept or aliased must stay on the heap" + lacks "$b" stack "$s: a cell that is kept or aliased must stay on the heap" + done + asan_cc || skip "gcc has no AddressSanitizer" + for s in $stems; do + # str_alias keeps `keep.name` alive to the end of main and drop glue + # never frees Str, so it is checked for errors, not leaks. + case "$s" in + nested | print_loop | branch | discard | str_cell | tailr | accret | accloop) leaks=detect_leaks=1 ;; + *) leaks=detect_leaks=0 ;; + esac + asan_run "tests/temps_cell/$s.trk" "$leaks" Sanitizer + done +} + +t_strfield_frees_owned_str_fields() { + local stems="alias keep literal local moved movelocal param result temp" s rel got leaks + for s in $stems; do + rel="tests/strfield/$s.trk" + c_and_native strfield "$s" + in_repo "$TRACKC" life --place "$rel" + cp "$T/.out" "$T/plan.got" + golden "$T/plan.got" "$ROOT/tests/strfield/$s.place" "$rel: placement plan" + got=$(cat "$T/plan.got") + case "$s" in + temp | local | result | movelocal) has "$got" " strs " "$s: no owned Str field" ;; + param) + # Only main's `keep` owns its string. + lacks "${got%%fn main*}" " strs " "param: callee frees a parameter's Str" ;; + *) lacks "$got" " strs " "$s: a Str field it does not own is freed" ;; + esac + done + asan_cc || skip "gcc has no AddressSanitizer" + for s in $stems; do + case "$s" in temp | local | literal | result | movelocal) leaks=detect_leaks=1 ;; *) leaks=detect_leaks=0 ;; esac + asan_run "tests/strfield/$s.trk" "$leaks" Sanitizer + done +} + +t_returns_hidden_in_expressions_are_seen() { + local s banned rel + local cases='str_let|str temp-autofree +str_hidden|str temp-autofree +sfres_cond|deep strs +sfres_hidden|deep strs +glue_hidden|temp-autofree +retslot_hidden|ret-slot' + while IFS='|' read -r s banned; do + rel="tests/returns/$s.trk" + c_and_native returns "$s" + in_repo "$TRACKC" life --place "$rel" + rc_ok "$rel: life --place failed" + [ -s "$T/.out" ] || fail "$rel: life --place printed nothing" + lacks "$OUT" "$banned" "$rel: a hidden return rules out \`$banned\`" + done <<<"$cases" + asan_cc || skip "gcc has no AddressSanitizer" + while IFS='|' read -r s banned; do + asan_run "tests/returns/$s.trk" detect_leaks=0 Sanitizer + done <<<"$cases" +} + +t_ret_slots_write_caller_cells() { + local stems="alias_ref alias_val both collection nested recursion" s rel + for s in $stems; do + rel="tests/retslot/$s.trk" + in_repo "$TRACKC" build "$rel" -o "$T/$s" + rc_ok "$rel: build failed" + run_want "$T/$s" "$ROOT/tests/retslot/$s.out" "$rel: output differs" + grep -qF '__rs(' "$T/$s.c" || fail "$rel: no ret-slot entry in emitted C" + plan "$rel" + golden "$T/plan.got" "$ROOT/tests/retslot/$s.place" "$rel: placement plan" + done + need_lines "$(plans_text)" <<'LINES' +L12 struct stack ends L22|a local reassigned only ret-slot results is a stack cell +L16 call stack ends L22|`acc = f(&acc)` writes acc's own cell +L14 call stack ends L20|`acc = f(acc)` writes acc's own cell +L13 call heap ends -|a ret-slot result stored into a collection is heap +L20 call stack ends L22|a ret-slot result in a stack slot +L21 call heap-autofree deep ends L26|a local also reassigned a heap-only cell stays heap-autofree +L25 call heap-autofree ends L26|a ret-slot result written into an autofree local's cell +L12 call heap ends -|a ret-slot result returned onward through a local is heap +L10 call stack ends L11|a recursive ret-slot call writes a slot of its caller's frame +L18 call ret-slot ends L18|a `return f(..)` passes the caller's slot through +L18 call stack ends L19|the outer call of `f(g(x))` writes a stack slot +LINES + asan_cc || skip "gcc has no AddressSanitizer" + for s in $stems; do + asan_run "tests/retslot/$s.trk" detect_leaks=0 AddressSanitizer + done +} + +# K3a: a user program may define any name a runtime uses internally. +t_user_names_never_clash_with_runtime_names() { + local s modes mode exe + while IFS='|' read -r s modes; do + for mode in $modes; do + [ "$mode" = c ] && mode= + exe="$T/$(printf '%s' "$s" | tr / _)$mode" + # shellcheck disable=SC2086 + in_repo "$TRACKC" build $mode "$s.trk" -o "$exe" + rc_ok "$s.trk $mode: build failed" + run_want "$exe" "$ROOT/$s.out" "$s.trk $mode: output differs" + done + done <<'CASES' +tests/names/rt_clash|c --rt=track --native +tests/stack/read_only|--native +tests/autofree/die_param|--native +CASES +} + +# A user `RT_BASE` (and friends) under --native is E0201, not a segfault. +t_runtime_layout_consts_stay_reserved() { + local name + for name in RT_BASE RS_USED RS_HEAP RS_LIMIT RS_HEAP_END RS_FREE; do + printf 'const %s = 5;\nstruct P { x: i64 }\nfn mk(i: i64) -> P { return P { x: i }; }\nfn main() -> i64 { let p = mk(3); print(p.x); return 0; }\n' "$name" >"$T/$name.trk" + trackc build --native "$name.trk" -o "$T/$name" + rc_fail "$name: user const accepted under --native" + has "$ERR" E0201 "$name: user const accepted under --native" + done +} + +t_duplicate_functions_are_rejected() { + local file mode + write "$T/other.trk" $'fn place_root() -> i64 { return 7; }\n' + write "$T/one.trk" $'fn place_root() -> i64 { return 1; }\nfn place_root() -> i64 { return 2; }\nfn main() -> i64 { print(place_root()); return 0; }\n' + write "$T/two.trk" $'import "other";\nfn place_root() -> i64 { return 2; }\nfn main() -> i64 { print(place_root()); return 0; }\n' + for file in one.trk two.trk; do + for mode in check build; do + trackc "$mode" "$file" + rc_fail "$mode $file: duplicate accepted" + has "$ERR" "error[E0201]: duplicate definition of function 'place_root'" "$mode $file: duplicate accepted" + done + done +} + +# K3a: `a + b` on two strings would add the pointers, so trackc rejects it. +t_string_plus_string_is_a_type_error() { + local i=0 src + while IFS= read -r src; do + printf '%s\n' "$src" >"$T/bad$i.trk" + trackc check "bad$i.trk" + rc_fail "$src: string + string accepted" + has "$ERR" str_concat "$src: string + string accepted" + i=$((i + 1)) + done <<'BAD' +fn main() -> i64 { let a = "ab"; let b = "cd"; let c = a + b; print(c); return 0; } +fn main() -> i64 { print("ab" + "cd"); return 0; } +fn main() -> i64 { let a = "ab"; let s = str_concat(&a, &a); let t = s + a; print(t); return 0; } +BAD + [ "$i" = 3 ] || fail "ran $i bad cases" + # Pointer arithmetic (string + integer, string - string) stays legal. + write "$T/ok.trk" $'fn main() -> i64 { let a = "abcd"; let n = 2; let p = a + n; print(p - a); return 0; }\n' + trackc check ok.trk + rc_ok "string + int rejected" +} + +# build_both_rt STEM SRC: build SRC with the C and the Track runtime into +# $T/STEM_crt and $T/STEM_trt (trackc runs in $T, as run_under_both_runtimes). +build_both_rt() { + trackc build "$2" -o "$T/$1_crt" + rc_ok "$1: build failed" + trackc build --rt=track "$2" -o "$T/$1_trt" + rc_ok "$1: --rt=track build failed" +} + +# K3b: for-in, exit(3) and a division trap keep what was printed on both +# runtimes; a scalar iterable and a range value are type errors. +t_for_in_exit_and_div_trap_on_both_runtimes() { + local exe + build_both_rt for_in "$ROOT/tests/native/for_in.trk" + for exe in for_in_crt for_in_trt; do + observe "$T/$exe" + stdout_is '10\n20\n30\n3\n2\n3\n4\n10\n20\n30\n110\n120\n130\nab\ncde\n60\n11\n21\n31\n' "$exe" + rc_is 0 "$exe" + done + build_both_rt exit_flush "$ROOT/tests/native/exit_flush.trk" + for exe in exit_flush_crt exit_flush_trt; do + observe "$T/$exe" + stdout_is '1\n' "$exe" + rc_is 3 "$exe" + done + build_both_rt divzero_flush "$ROOT/tests/native/divzero_flush.trk" + for exe in divzero_flush_crt divzero_flush_trt; do + observe "$T/$exe" + stdout_is '1\n' "$exe: output lost on SIGFPE" + rc_is 136 "$exe: SIGFPE" + done + write "$T/forint.trk" $'fn main() -> i64 { let n = 3; for i in n { print(i); } return 0; }\n' + trackc check forint.trk + rc_fail "for over an integer accepted" + has "$ERR" '`for` iterates over a range or an array' "for over an integer accepted" + # F3: a range bound as a value segfaulted on both backends; it is E0200. + write "$T/rangeval.trk" $'fn main() -> void { let r = (0-1)..3; for i in r { print(i); } }\n' + trackc check rangeval.trk + rc_fail "range bound as a value accepted" + has "$ERR" 'A range `a..b` is not a value' "range bound as a value accepted" +} + +# K3c: INT64_MIN / -1 (and % -1) flushes, then SIGFPE, on every backend. +t_int64_min_div_minus_one_flushes_on_every_backend() { + local s want mode exe + while IFS='|' read -r s want; do + for mode in c --rt=track --native; do + exe="$T/$s$(printf '%s' "$mode" | tr -- '-=' '__')" + if [ "$mode" = c ]; then + trackc build "$ROOT/tests/native/$s.trk" -o "$exe" + else + trackc build "$mode" "$ROOT/tests/native/$s.trk" -o "$exe" + fi + rc_ok "$s $mode: build failed" + observe "$exe" + stdout_is "$want" "$s $mode: output lost" + rc_is 136 "$s $mode: wrong signal" + done + done <<'CASES' +divmin_flush|-7\n0\n-9223372036854775807\n +divmin_mod_flush|0\n +CASES +} diff --git a/tests/sh/native.sh b/tests/sh/native.sh new file mode 100644 index 00000000..822ecc0a --- /dev/null +++ b/tests/sh/native.sh @@ -0,0 +1,153 @@ +# Native x86-64 backend (`trackc build --native`, compiler/src/ngen.trk). +# Port of tests/native_tests.rs: native executables need no C toolchain, +# behave like the C backend's, and the natively built compiler reaches a +# byte-identical fixed point. Commands run from the repository root. + +t_native_build_needs_no_c_toolchain() { + in_repo env PATH=/nonexistent "$TRACKC" build --native tests/native_raw/hello_syscall.trk -o "$T/hello" + rc_ok "native build with no PATH" + eq "$(head -c 4 "$T/hello" | od -An -c | tr -d ' ')" '177ELF' "ELF magic" + observe "$T/hello" + stdout_is 'Hello, native world!\n' "stdout" + rc_is 42 "exit code" +} + +t_native_programs_match_the_c_backend() { + local n=0 p s + for p in $(trk_files "$ROOT/examples") $(trk_files "$ROOT/tests/native") $(trk_files "$ROOT/bench/progs"); do + s=$(stem "$p") + case "$s" in *_err) continue ;; esac + n=$((n + 1)) + in_repo "$TRACKC" build "$p" -o "$T/${s}_c" + rc_ok "$s: C build" + in_repo "$TRACKC" build --native "$p" -o "$T/${s}_n" + rc_ok "$s: native build" + is_exe "$T/${s}_c" "$s: C build" + is_exe "$T/${s}_n" "$s: native build" + in_repo "$T/${s}_c"; save_run c + in_repo "$T/${s}_n"; save_run n + same_run c n "$s: behaviour differs" + rm -f "$T/${s}_c" "$T/${s}_n" + done + [ "$n" -gt 10 ] || fail "only $n inputs" +} + +t_native_compiler_reaches_a_fixed_point() { + in_repo "$TRACKC" build --native compiler/src/main.trk -o "$T/trackc2" + rc_ok "n2 build" + in_repo env PATH=/nonexistent "$T/trackc2" build --native compiler/src/main.trk -o "$T/trackc3" + rc_ok "n3 build with no PATH" + same_file "$T/trackc2" "$T/trackc3" "native stage2 and stage3" +} + +# Every program `trackc check` rejects must be rejected by the native build +# and by `--rt=track` too. +t_native_and_track_rt_reject_what_check_rejects() { + local n=0 p + for p in $(trk_files "$ROOT/tests/native_reject") $(trk_files "$ROOT/examples" | grep '_err\.trk$'); do + n=$((n + 1)) + in_repo "$TRACKC" check "$p" + rc_fail "$p: check accepted it" + in_repo "$TRACKC" build --native "$p" -o "$T/x" + rc_fail "$p: --native accepted it" + in_repo "$TRACKC" build --rt=track "$p" -o "$T/x" + rc_fail "$p: --rt=track accepted it" + done + [ "$n" -ge 12 ] || fail "only $n inputs" +} + +# Tuples stored in a struct, array, union or tuple, returned, or built in a +# loop outlive the frame that made them. +t_native_tuples_outlive_their_frame() { + local name want + while IFS='|' read -r name want; do + in_repo "$TRACKC" build --native "tests/native_tuples/$name.trk" -o "$T/$name" + rc_ok "$name: build" + observe "$T/$name" + rc_is 0 "$name" + stdout_is "$want" "$name" + done <<'CASES' +tup_arr|200\n5\n +tup_loop|0\n20\n +tup_nested|200\n6\n +tup_struct|200\n8\n +tup_struct2|30\nxy\n8\n +tup_union|200\n6\n +CASES +} + +t_native_identical_string_literals_compare_equal() { + in_repo "$TRACKC" build --native tests/native/strlit_eq.trk -o "$T/s" + rc_ok "build" + observe "$T/s" + starts "$OUT +" "1 +" "stdout" +} + +t_native_program_without_main_builds() { + local name + for name in nomain nomain_lib; do + in_repo "$TRACKC" build --native "tests/native/$name.trk" -o "$T/$name" + rc_ok "$name: build" + observe "$T/$name" + rc_is 0 "$name" + eq "$(fsize "$T/.out"):$(fsize "$T/.err")" "0:0" "$name: output" + done +} + +# `--native` after the file and after `-o` too; with no C compiler on PATH +# only the native backend can succeed. +t_native_flag_is_honoured_in_any_position() { + local src=tests/native_raw/hello_syscall.trk e="$T/h" order + for order in "build $src --native -o $e" "build $src -o $e --native" "build -o $e --native $src"; do + rm -f "$e" + # shellcheck disable=SC2086 + in_repo env PATH=/nonexistent "$TRACKC" $order + rc_ok "$order" + observe "$e" + rc_is 42 "$order" + done +} + +# PT_GNU_STACK present with flags RW (6), not executable. +t_native_executables_have_a_non_executable_stack() { + in_repo "$TRACKC" build --native tests/native_raw/hello_syscall.trk -o "$T/h" + rc_ok "build" + local img="$T/h" phoff entsize count i h found= + phoff=$(u64_at "$img" 32) + entsize=$(u16_at "$img" 54) + count=$(u16_at "$img" 56) + for i in $(seq 0 $((count - 1))); do + h=$((phoff + i * entsize)) + if [ "$(u32_at "$img" "$h")" = $((0x6474e551)) ]; then + found=$h + break + fi + done + [ -n "$found" ] || fail "no PT_GNU_STACK program header" + eq "$(u32_at "$img" $((found + 4)))" 6 "PT_GNU_STACK flags must be RW" +} + +# K3b/K3c: programs both backends once got wrong the same way. Each prints +# the expected stdout and ends with the status (136 = SIGFPE) on both. +t_native_and_c_print_the_expected_output() { + local stem want code + while IFS='|' read -r stem want code; do + in_repo "$TRACKC" build "tests/native/$stem.trk" -o "$T/${stem}_c" + rc_ok "$stem c: build" + in_repo "$TRACKC" build --native "tests/native/$stem.trk" -o "$T/${stem}_native" + rc_ok "$stem native: build" + for exe in "$T/${stem}_c" "$T/${stem}_native"; do + observe "$exe" + stdout_is "$want" "${exe##*/}" + rc_is "$code" "${exe##*/}: status" + done + done <<'CASES' +for_in|10\n20\n30\n3\n2\n3\n4\n10\n20\n30\n110\n120\n130\nab\ncde\n60\n11\n21\n31\n|0 +exit_flush|1\n|3 +divzero_flush|1\n|136 +divmin_flush|-7\n0\n-9223372036854775807\n|136 +divmin_mod_flush|0\n|136 +CASES +} diff --git a/tests/sh/selfhost.sh b/tests/sh/selfhost.sh new file mode 100644 index 00000000..005907cc --- /dev/null +++ b/tests/sh/selfhost.sh @@ -0,0 +1,416 @@ +# Self-hosted compiler (compiler/), part 1. Port of tests/selfhost_tests.rs +# up to trackc_programs_print_the_expected_output. The Rust suite compared +# trackc with the Rust stage0 compiler; here trackc is checked alone, against +# the same expectations (stage0 behaviour of examples/ is frozen in +# tests/cases/examples/.out and .code). Case tables live in +# tests/cases//. + +CASES="$ROOT/tests/cases" + +t_build_creates_missing_output_directories() { + write "$T/x.trk" "fn main() -> void { print(7); }" + trackc build "$T/x.trk" -o "$T/some/new/dir/x" + rc_ok "build into a missing directory" + observe "$T/some/new/dir/x" + eq "$OUT" 7 "output" +} + +t_runtime_object_is_cached_and_builds_stay_identical() { + local cache="$T/cache" + write "$T/a.trk" "fn main() -> void { print(1); }" + write "$T/b.trk" "fn main() -> void { print(1); }" + objects() { find "$cache" -maxdepth 1 -type f -name '*.o' 2>/dev/null | wc -l | tr -d ' '; } + cap env TRACKC_CACHE="$cache" "$TRACKC" build "$T/a.trk" -o "$T/out1/a" + rc_ok "build 1" + eq "$(objects)" 1 "first build should store one runtime object" + cap env TRACKC_CACHE="$cache" "$TRACKC" build "$T/a.trk" -o "$T/out2/a" + rc_ok "build 2" + eq "$(objects)" 1 "second build should reuse it" + same_file "$T/out1/a" "$T/out2/a" "cached builds" + cap env TRACKC_CACHE="$cache" "$TRACKC" build "$T/b.trk" -o "$T/out3/b" + rc_ok "build 3" + eq "$(objects)" 1 "third build" + observe "$T/out3/b" + eq "$OUT" 1 "output" +} + +t_native_binaries_carry_a_symbol_table() { + have nm || skip "nm not found" + # recursive, so the inliner keeps it out of line + write "$T/s.trk" 'fn sum_down(n: i64) -> i64 { + if n <= 0 { + return 0; + } + return n + sum_down(n - 1); +} +fn main() -> void { print(sum_down(100)); } +' + trackc build --native -g "$T/s.trk" -o "$T/s" + rc_ok "build -g" + observe "$T/s" + eq "$OUT" 5050 "output" + # without -g: the same loaded image, no sections + trackc build --native "$T/s.trk" -o "$T/plain" + rc_ok "build" + local lw lp + lw=$(fsize "$T/s") + lp=$(fsize "$T/plain") + [ "$lw" -gt "$lp" ] || fail "-g image ($lw) not larger than plain ($lp)" + cmp -s -i 64 -n 112 "$T/s" "$T/plain" || fail "program headers differ" + cmp -s -i 176 -n $((lp - 176)) "$T/s" "$T/plain" || fail "loaded bytes differ" + cap nm "$T/s" + rc_ok "nm" + local name + for name in main sum_down _start; do + printf '%s\n' "$OUT" | awk -v n="$name" 'NF == 3 && $2 == "T" && $3 == n { f = 1 } END { exit !f }' \ + || fail "nm lacks T $name: +$OUT" + done +} + +t_bootstrap_reaches_a_fixed_point() { + mkdir -p "$T/stage2" "$T/stage3" + in_repo "$TRACKC" build compiler/src/main.trk -o "$T/stage2/trackc" + rc_ok "stage1" + in_repo "$T/stage2/trackc" build compiler/src/main.trk -o "$T/stage3/trackc" + rc_ok "stage2" + same_file "$T/stage2/trackc.c" "$T/stage3/trackc.c" "stage1 and stage2 emitted C" + same_file "$T/stage2/trackc" "$T/stage3/trackc" "stage2 and stage3 executables" +} + +# Stage0 behaviour is frozen in tests/cases/examples (captured from the Rust +# compiler): trackc rejects every _err example and reproduces the rest. +t_examples_behave_the_same_under_both_compilers() { + local p s hb n=0 + for p in $(trk_files "$ROOT/examples"); do + s=$(stem "$p") + n=$((n + 1)) + trackc build "$p" -o "$T/${s}_native" + case "$s" in + *_err) + rc_fail "$s: trackc accepted a rejection test" + continue + ;; + esac + rc_ok "$s: trackc build" + [ -f "$CASES/examples/$s.out" ] || fail "$s: no golden tests/cases/examples/$s.out" + observe "$T/${s}_native" + # @HOSTNAME_BYTES@ stands for the size of /etc/hostname (0 if it is + # missing), which error_handling prints and which differs per machine. + hb=0 + [ -f /etc/hostname ] && hb=$(wc -c "$T/.want_$s" + out_is "$T/.want_$s" "$s: behaviour differs from stage0" + rc_is "$(cat "$CASES/examples/$s.code")" "$s: exit code differs from stage0" + rm -f "$T/${s}_native" + done + [ "$n" -gt 0 ] || fail "no examples" +} + +# verdict_dir DIR: DIR/accept/*.trk must check clean, DIR/reject/*.trk not. +verdict_dir() { + local f n=0 + for f in $(trk_files "$1/accept"); do + n=$((n + 1)) + trackc check "$f" + [ "$RC" = 0 ] || fail "$(stem "$f"): trackc rejected an accepted program +$(ctx)" + done + for f in $(trk_files "$1/reject"); do + n=$((n + 1)) + trackc check "$f" + [ "$RC" != 0 ] || fail "$(stem "$f"): trackc accepted a rejected program +$(ctx)" + done + echo "$n" +} + +t_checkers_agree_on_accepted_and_rejected_programs() { + local n + n=$(verdict_dir "$CASES/verdicts") || exit 1 + eq "$n" 34 "verdict count" +} + +# A constant `/` or `%` that would trap is E0200; trackc must not fold it. +t_const_divrem_traps_are_e0200_in_both_checkers() { + local f s n=0 + for f in $(trk_files "$CASES/const_divrem"); do + s=$(stem "$f") + n=$((n + 1)) + trackc check "$f" + if [ -f "$CASES/const_divrem/$s.want" ]; then + rc_is 1 "$s" + starts "$ERR" "$(cat "$CASES/const_divrem/$s.want")" "$s" + else + rc_ok "$s" + fi + done + eq "$n" 19 "case count" +} + +t_diagnostics_point_at_the_source() { + write "$T/moved.trk" 'fn main() -> void { + let s = str_concat("a", "b"); + let t = s; + print(s); +} +' + trackc_in "$T" check moved.trk + rc_fail "check" + starts "$ERR" "error[E0200]: Use-after-free! Resource 's' is already spent. + --> moved.trk:4:11 +" "diagnostic" + has "$ERR" "4 | print(s);" "source frame" +} + +t_native_test_suite_passes_under_trackc() { + local p rel n=0 + for p in $(trk_files "$ROOT/compiler/tests"); do + rel=tests/${p##*/} + n=$((n + 1)) + cap_in "$ROOT/compiler" "$TRACKC" run "$rel" + rc_ok "$rel failed under trackc" + done + [ "$n" -gt 0 ] || fail "no compiler/tests" +} + +# run_both_runtimes STEM SRC: build with the C runtime and --rt=track, run +# both; saved runs "crt" and "trt". +run_both_runtimes() { + trackc build "$2" -o "$T/$1_crt" + rc_ok "$1: build" + trackc build --rt=track "$2" -o "$T/$1_trt" + rc_ok "$1: --rt=track build" + is_exe "$T/$1_crt" "$1: build" + is_exe "$T/$1_trt" "$1: --rt=track build" + observe "$T/$1_crt" + save_run crt + observe "$T/$1_trt" + save_run trt +} + +# The Track runtime (compiler/rt/*.trk) links without libc and behaves like +# runtime/track_runtime.c on the examples and the runtime smoke tests. +t_track_runtime_matches_the_c_runtime() { + local p s + for p in $( (trk_files "$ROOT/examples" | grep -v -e '_err\.trk$' -e '/net_demo\.trk$' + echo "$ROOT/compiler/rt/tests/rt_smoke.trk" + for s in rt_alloc rt_alloc_nz rt_memlimit rt_memlimit_realloc rt_lcache rt_memlimit_lcache sb_spare; do + echo "$ROOT/tests/native/$s.trk" + done) | LC_ALL=C sort); do + [ -f "$p" ] || fail "missing $p" + s=$(stem "$p") + run_both_runtimes "$s" "$p" + same_run crt trt "$s: behaviour differs between runtimes" + rm -f "$T/${s}_crt" "$T/${s}_trt" + done +} + +t_program_without_main_runs_on_both_runtimes() { + write "$T/nomain.trk" 'let x = 41; +print(x + 1); +' + run_both_runtimes nomain "$T/nomain.trk" + printf '42\n' >"$T/.want42" + same_file "$T/.run_crt.out" "$T/.want42" "C runtime stdout" + eq "$(cat "$T/.run_crt.rc")" 0 "C runtime exit" + same_run crt trt "behaviour differs between runtimes" +} + +# trackc linked against the Track runtime (no libc) compiles the compiler to +# the same C as trackc on the C runtime. +t_trackc_on_the_track_runtime_self_compiles() { + mkdir -p "$T/rt" "$T/a" "$T/b" + in_repo "$TRACKC" build --rt=track compiler/src/main.trk -o "$T/rt/trackc" + rc_ok "--rt=track build of trackc" + if grep_bytes "$T/rt/trackc" libc.so; then + fail "trackc on the Track runtime must not link libc" + fi + in_repo "$TRACKC" build compiler/src/main.trk -o "$T/a/trackc" + rc_ok "C-runtime build of trackc" + in_repo "$T/rt/trackc" build compiler/src/main.trk -o "$T/b/trackc" + rc_ok "trackc on the Track runtime" + same_file "$T/a/trackc.c" "$T/b/trackc.c" "trackc on the Track runtime emitted C" +} + +# Warnings channel: two unused bindings, sorted by position; only +# --deny-warnings fails. +t_warnings_print_sorted_and_only_deny_warnings_fails() { + write "$T/w.trk" 'fn helper() -> i64 { let a = 1; return 2; } +fn main() -> void { let b = 3; print(helper()); } +' + local path="$T/w.trk" args + for args in "check $path" "build $path" "build --native $path"; do + # shellcheck disable=SC2086 + trackc_in "$T" $args + rc_ok "$args" + eq "$(count "$ERR" "warning[W0301]")" 2 "$args: W0301 count" + [ "$(pos "$ERR" "w.trk:1:")" -lt "$(pos "$ERR" "w.trk:2:")" ] \ + || fail "$args: warnings not sorted by position: +$ERR" + done + trackc_in "$T" check "$path" + has "$OUT" "(2 warnings)" "check summary" + + trackc_in "$T" run "$path" + rc_is 0 "run" + eq "$OUT" 2 "run output" + has "$ERR" "warning[W0301]" "run warnings" + + for args in "check --deny-warnings $path" "check $path --deny-warnings" \ + "build --native $path --deny-warnings" "run --deny-warnings $path"; do + # shellcheck disable=SC2086 + trackc_in "$T" $args + rc_is 1 "$args" + has "$ERR" "warning[W0301]" "$args" + done + + write "$T/quiet.trk" 'fn helper() -> i64 { let _a = 1; return 2; } +fn main() -> void { print(helper()); } +' + trackc_in "$T" check --deny-warnings "$T/quiet.trk" + rc_ok "quiet --deny-warnings" + lacks "$ERR" "warning" "quiet" + + write "$T/bad.trk" 'fn first() -> i64 { let u = 1; return 0; } +fn main() -> void { + print(nope); +} +' + trackc_in "$T" check "$T/bad.trk" + rc_is 1 "warning plus error" +} + +# Lifecycle warnings W0301-W0305: each docs/lifecycles/wN example gives +# exactly its warning, exits 0, and fails under --deny-warnings. +t_lifecycle_warnings_match_the_catalogue() { + local stem want rel f + while IFS='|' read -r stem want; do + rel=docs/lifecycles/$stem.trk + in_repo "$TRACKC" check "$rel" + rc_ok "$rel" + has "$ERR" "$want" "$rel" + eq "$(count "$ERR" "warning[")" 1 "$rel: warning count" + in_repo "$TRACKC" check --deny-warnings "$rel" + rc_is 1 "$rel --deny-warnings" + done <<'CASES' +w1_fresh_unread|warning[W0301]: 'origin' is created and never read; remove it or name it '_origin'. +w2_write_only|warning[W0302]: write to 'p.y' is never read; 'p' ends at line 7. +w3_mutated_unread|warning[W0303]: 'bump' mutates 'c', but 'c' is never read afterwards. +w4_discarded_result|warning[W0304]: result of 'vadd' is discarded, and 'vadd' has no other effect (it only reads its parameters and returns a fresh value). +w5_consume_only_reads|warning[W0305]: 'norm1' takes 'p' by value but only reads it; take '&Point' so callers keep it. +CASES + # Near misses stay warning-free. + local n=0 + for f in $(trk_files "$CASES/life_warn_clean"); do + n=$((n + 1)) + trackc check "$f" + rc_ok "$(stem "$f")" + lacks "$ERR" "warning[" "$(stem "$f")" + done + eq "$n" 6 "near-miss count" +} + +# examples/ is warning-free except two intended demonstrations. +t_examples_warn_only_where_intended() { + local p name want + for p in $(trk_files "$ROOT/examples"); do + name=${p##*/} + case "$name" in + linear_auto_free.trk) want="warning[W0301]: 'buf'" ;; + structs_arrays.trk) want="warning[W0305]: 'quadrant'" ;; + *) want= ;; + esac + in_repo "$TRACKC" check "examples/$name" + if [ -n "$want" ]; then + eq "$(count "$ERR" "warning[")" 1 "examples/$name: warning count" + has "$ERR" "$want" "examples/$name" + else + eq "$(count "$ERR" "warning[")" 0 "examples/$name: warning count" + fi + done +} + +t_compiler_sources_are_warning_clean() { + in_repo "$TRACKC" check --deny-warnings compiler/src/main.trk + rc_ok "check --deny-warnings compiler/src/main.trk" +} + +# Holes where the Rust checker is also wrong (or differs): trackc alone. +t_trackc_closes_checker_holes() { + local n + n=$(verdict_dir "$CASES/trackc_verdicts") || exit 1 + eq "$n" 46 "verdict count" +} + +# Lifecycle hard errors: exit 1 and the exact first diagnostic line. A case +# is NN.trk (inline source) or NN.path (a repo path), with NN.want. +t_lifecycle_hard_errors_print_the_catalogue_texts() { + local w base src n=0 + for w in "$CASES"/life_errors/*.want; do + base=${w%.want} + if [ -f "$base.path" ]; then + src="$ROOT/$(cat "$base.path")" + else + src="$base.trk" + fi + n=$((n + 1)) + trackc_in "$T" check "$src" + rc_is 1 "$src" + eq "$(head -n 1 "$T/.err")" "$(cat "$w")" "$src: first diagnostic line" + done + eq "$n" 19 "case count" +} + +# Look-alikes of the lifecycle hard errors that are correct. +t_lifecycle_lookalikes_check_clean() { + local f n=0 + for f in $(trk_files "$CASES/life_clean"); do + n=$((n + 1)) + trackc_in "$T" check "$f" + rc_ok "$(stem "$f") rejected" + done + eq "$n" 10 "case count" +} + +# body FILE START: the text from the first line containing START up to the +# next line that is exactly "}". +c_body() { + awk -v s="$2" 'f && $0 == "}" { exit } !f && index($0, s) { f = 1; print substr($0, index($0, s)); next } f { print }' "$1" +} + +# A tuple literal that never escapes lives in a stack slot: 20M of them in a +# loop allocate nothing, while one that is returned stays a heap cell. +t_non_escaping_tuples_use_stack_slots() { + write "$T/t3.trk" 'fn pair(n: i64) -> (i64, i64) { let r = (n, n + 1); return r; } fn main() -> void { let mut i = 0; let mut acc = 0; while i < 20000000 { let p = (i, 1); acc = acc + p.1; i = i + 1; } print(acc); print(pair(4).1); }' + trackc_in "$T" build "$T/t3.trk" -o "$T/t3" + rc_ok "build" + local main_body pair_body + grep -qF 'tk_w tk_main(void) {' "$T/t3.c" || fail "no tk_main in t3.c" + grep -qF 'tk_w tk_pair(tk_w a0) {' "$T/t3.c" || fail "no tk_pair in t3.c" + main_body=$(c_body "$T/t3.c" 'tk_w tk_main(void) {') + pair_body=$(c_body "$T/t3.c" 'tk_w tk_pair(tk_w a0) {') + lacks "$main_body" "alloc(" "loop tuple must not allocate" + lacks "$main_body" "alloc_nz(" "loop tuple must not allocate" + case "$pair_body" in + *"alloc("* | *"alloc_nz("*) ;; + *) fail "returned tuple must be a heap cell: +$pair_body" ;; + esac + # 64 MB of address space is far below what 20M heap cells need. + cap sh -c "ulimit -v 65536; exec \"$T/t3\"" + rc_ok "t3 under a 64 MB limit" + stdout_is '20000000\n5\n' "t3" +} + +t_trackc_programs_print_the_expected_output() { + local f s n=0 + for f in $(trk_files "$CASES/run_outputs"); do + s=$(stem "$f") + n=$((n + 1)) + trackc_in "$T" run "$f" + rc_ok "$s: trackc run" + out_is "$CASES/run_outputs/$s.out" "$s: wrong output" + done + eq "$n" 10 "case count" +} diff --git a/tests/sh/tools.sh b/tests/sh/tools.sh new file mode 100644 index 00000000..07fc6658 --- /dev/null +++ b/tests/sh/tools.sh @@ -0,0 +1,202 @@ +# Editor assets: the VS Code extension, the TextMate grammar and the +# Neovim plugin. Port of tests/editor_tests.rs and +# tests/headless_highlight_tests.rs. JSON is read with jq; grammar regexes +# run under `grep -P` (PCRE, close to the Oniguruma engine TextMate uses). +# The nvim and luac checks skip when the tool is missing, as the Rust +# tests did. + +need_jq() { have jq || fail "jq is required to read the editor JSON files"; } + +# json_ok FILE: FILE holds exactly one valid JSON value (as serde_json +# required). Call it before jqv, whose failures inside $(...) cannot end +# the test. +json_ok() { + [ "$(jq -s length "$1" 2>"$T/.jqerr")" = 1 ] || fail "$1 is invalid JSON: $(cat "$T/.jqerr")" +} + +# jqv FILE FILTER: one raw jq result. +jqv() { + jq -r "$2" "$1" 2>"$T/.jqerr" || fail "$1: invalid JSON or bad filter: $(cat "$T/.jqerr")" +} + +GRAMMAR=editor/vscode/syntaxes/track.tmLanguage.json + +t_vscode_package_json() { + need_jq + local p="$ROOT/editor/vscode/package.json" + [ -f "$p" ] || fail "package.json does not exist at editor/vscode/package.json" + json_ok "$p" + eq "$(jqv "$p" .name)" track-vscode "name" + eq "$(jqv "$p" .publisher)" dev-dami "publisher" + eq "$(jqv "$p" .icon)" images/track-icon.png "icon" + eq "$(jqv "$p" '.contributes.languages | type')" array "languages array missing" + ne "$(jqv "$p" '.contributes.languages | length')" 0 "languages empty" + eq "$(jqv "$p" '.contributes.languages[0].id')" track "languages[0].id" +} + +t_vscode_language_configuration() { + need_jq + local p="$ROOT/editor/vscode/language-configuration.json" + [ -f "$p" ] || fail "language-configuration.json does not exist" + json_ok "$p" + eq "$(jqv "$p" .comments.lineComment)" "//" "lineComment" + eq "$(jqv "$p" '.brackets | type')" array "brackets" + eq "$(jqv "$p" '.autoClosingPairs | type')" array "autoClosingPairs" +} + +t_vscode_textmate_grammar() { + need_jq + local p="$ROOT/$GRAMMAR" combined + [ -f "$p" ] || fail "track.tmLanguage.json does not exist" + json_ok "$p" + eq "$(jqv "$p" .scopeName)" source.track "scopeName" + eq "$(jqv "$p" .name)" Track "name" + eq "$(jqv "$p" '.repository.keywords.patterns | type')" array "keywords patterns missing" + combined="$(jqv "$p" '[.repository.keywords.patterns[] | .match // empty] | join(" ")') $(jqv "$p" '[(.repository.typeDefinitions.patterns // [])[] | .match // .begin // empty] | join(" ")')" + has "$combined" import "Grammar keywords missing 'import'" + has "$combined" fn "Grammar keywords missing 'fn'" + has "$combined" struct "Grammar keywords missing 'struct'" +} + +t_nvim_plugin_files() { + local vim="$ROOT/editor/nvim/track.vim" lua="$ROOT/editor/nvim/track.lua" src + [ -f "$vim" ] || fail "track.vim does not exist at editor/nvim/track.vim" + [ -f "$lua" ] || fail "track.lua does not exist at editor/nvim/track.lua" + src=$(cat "$lua") + has "$src" import "track.lua syntax missing 'import'" + case "$src" in + *'icon = "T"'* | *'icon = "󱐌"'*) ;; + *) fail "track.lua devicons missing icon" ;; + esac + case "$src" in + *'color = "#ffffff"'* | *'color = "#7aa2f7"'*) ;; + *) fail "track.lua devicons missing color" ;; + esac + if have luac; then + cap luac -p "$lua" + rc_ok "Lua syntax check failed for track.lua" + fi +} + +# Every major construct in a sample is matched by some grammar regex. +t_vscode_grammar_headless_tokenization() { + need_jq + local p="$ROOT/$GRAMMAR" pats n sample label text needles needle pat matched r + json_ok "$p" + pats="$T/patterns" + jqv "$p" '.repository | to_entries[] | (.value.patterns // [])[] | (.match // empty), (.begin // empty)' >"$pats" + n=$(wc -l <"$pats") + [ "$n" -gt 10 ] || fail "too few patterns: $n" + sample='import "std/io"; +fn main() -> void { + let mut x: i64 = 42; + // TODO fix + let s = "hello \"world\""; + let n = 0xFF; + let b = 0b1010; + if x > 0 { print(s); } + with u -> v { v.set(1); } + @macro bit(n: u32) -> u32 { return 1 << n; } + let p: ptr = alloc(8); + match val { _ => print(0), } +} +' + # label | text (S = the sample) | needles separated by TAB + while IFS='|' read -r label text needles; do + [ "$text" = S ] && text=$sample + matched=0 + while IFS= read -r pat; do + IFS=$'\t' + for needle in $needles; do + printf '%s' "$needle" | grep -qP -- "$pat" 2>/dev/null + r=$? + # r=2: not a valid PCRE pattern, skipped (as the Rust test skipped invalid regexes) + if [ "$r" = 0 ]; then + case "$text" in *"$needle"*) matched=1 ;; esac + fi + [ "$matched" = 1 ] && break + done + unset IFS + [ "$matched" = 1 ] && break + done <"$pats" + [ "$matched" = 1 ] || fail "headless VS Code: pattern for $label ($needles) not matched by any grammar regex" + done <|S|-> +operator ::|a::b|:: +CASES + eq "$(jqv "$p" .scopeName)" source.track "scopeName" +} + +t_vscode_grammar_valid_json_headless() { + need_jq + local rel p bad + for rel in grammars/track.tmLanguage.json "$GRAMMAR"; do + p="$ROOT/$rel" + json_ok "$p" + eq "$(jqv "$p" .scopeName)" source.track "scopeName mismatch in $rel" + eq "$(jqv "$p" '.repository | type')" object "repository missing in $rel" + bad=$(jqv "$p" '.repository | to_entries[] | select((.value.patterns | type) != "array" or (.value.patterns | length) == 0) | .key') + [ -z "$bad" ] || fail "$rel: repository entries without patterns: $bad" + done +} + +nvim_cmd() { # nvim_cmd EXTRA-COMMANDS...: nvim headless with the plugin loaded + local args=(--headless -u NONE -n -c "set rtp+=$ROOT/editor/nvim" -c "lua require('track').setup()" -c "edit examples/hello.trk") + local c + for c in "$@"; do args+=(-c "$c"); done + in_repo nvim "${args[@]}" +} + +t_nvim_headless_filetype_and_syntax() { + have nvim || skip "nvim not found" + local grp + nvim_cmd "lua print('FT='..vim.bo.filetype)" "qa!" + has "$OUT $ERR" "FT=track" "nvim headless filetype not track" + nvim_cmd "doautocmd FileType track" "redir => g:__syn | silent syn list | redir END | silent put =g:__syn | %print | qa!" + for grp in trackKeyword trackType trackString trackComment trackNumber; do + has "$OUT $ERR" "$grp" "nvim syntax group $grp missing in headless output" + done + nvim_cmd "doautocmd FileType track" "redir => g:__hl | silent hi trackKeyword | redir END | silent put =g:__hl | %print | qa!" + has "$OUT $ERR" trackKeyword "highlight link for trackKeyword missing" + has "$OUT $ERR" Keyword "highlight link for trackKeyword missing" +} + +t_nvim_headless_lua_syntax_ok() { + have nvim || skip "nvim not found" + in_repo nvim --headless -u NONE -n -c "luafile $ROOT/editor/nvim/track.lua" -c "lua print('lua_ok')" -c "qa!" + has "$OUT $ERR" lua_ok "nvim luafile failed" +} + +# Terminal nvim cannot render SVG: the plugin documents that and its code +# never loads an .svg; the VS Code extension uses the PNG icon. +t_nvim_devicon_svg_not_needed_headless() { + local lua="$ROOT/editor/nvim/track.lua" src code + src=$(cat "$lua") + case "$src" in + *"Terminal cannot render"* | *"vector images"*) ;; + *) fail "track.lua should document that SVG/vector is not for nvim" ;; + esac + code=$(grep -v '^[[:space:]]*--' "$lua") + lacks "$code" ".svg" "nvim track.lua code should not reference .svg" + grep -qF track-icon.png "$ROOT/editor/vscode/package.json" || fail "vscode package.json should reference PNG icon" + [ -f "$ROOT/assets/track-icon.svg" ] || fail "assets/track-icon.svg missing" +} + +t_nvim_syntax_highlight_sample_headless() { + have nvim || skip "nvim not found" + nvim_cmd "doautocmd FileType track" "let g:ids = [] | for lnum in range(1, line('\$')) | for col in range(1, strdisplaywidth(getline(lnum))) | call add(g:ids, synIDattr(synID(lnum, col, 1), 'name')) | endfor | endfor | echo join(g:ids, ',')" "qa!" + case "$OUT $ERR" in + *trackKeyword* | *trackFunction* | *trackString*) ;; + *) fail "nvim headless synID produced no Track syntax: $OUT $ERR" ;; + esac +} diff --git a/tests/soundness_tests.rs b/tests/soundness_tests.rs deleted file mode 100644 index 21777fd7..00000000 --- a/tests/soundness_tests.rs +++ /dev/null @@ -1,165 +0,0 @@ -use track::compile_source; - -#[test] -fn test_soundness_loop_consumed_variable_use_rejected() { - let source = r#" - fn main() -> void { - let mut v = vec_init(16); - while true { - let x = v; - } - let y = v; - } - "#; - let res = compile_source(source); - assert!( - res.is_err(), - "Expected rejection for use of loop-consumed variable after loop" - ); - let err = res.unwrap_err(); - assert!( - err.contains("v"), - "Error message should mention variable 'v': {}", - err - ); -} - -#[test] -fn test_soundness_loop_reinitialization_accepted() { - let source = r#" - fn main() -> void { - let mut v = vec_init(16); - while true { - let tmp = v; - v = vec_init(16); - } - let end = v; - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Expected valid compilation for loop reinitialization, got: {:?}", - res.err() - ); -} - -#[test] -fn test_soundness_lens_escape_rejected() { - let source = r#" - fn main() -> void { - let mut v = vec_init(16); - with v -> lens { - let leaked = lens; - } - } - "#; - let res = compile_source(source); - assert!(res.is_err(), "Expected rejection for lens escape attempt"); - let err = res.unwrap_err(); - assert!( - err.contains("Lens") && err.contains("escape"), - "Error message should identify lens escape: {}", - err - ); -} - -#[test] -fn test_soundness_lens_alias_not_visible_after_block() { - let source = r#" - fn main() -> void { - let mut v = vec_init(16); - with v -> lens { - vec_push(lens, 1); - } - vec_push(lens, 2); - } - "#; - let res = compile_source(source); - assert!( - res.is_err(), - "Expected rejection when lens alias is used after its with block" - ); -} - -#[test] -fn test_soundness_nested_lens_same_target_rejected() { - let source = r#" - fn main() -> void { - let mut v = vec_init(16); - with v -> a { - with v -> b { - vec_push(b, 1); - } - } - } - "#; - let res = compile_source(source); - assert!( - res.is_err(), - "Expected rejection for nested lens over already locked target" - ); -} - -#[test] -fn test_soundness_lens_released_on_early_return() { - let source = r#" - fn f(cond: bool) -> void { - let mut v = vec_init(16); - with v -> lens { - if cond { - return; - } else { - vec_push(lens, 1); - } - } - let x = v; - } - "#; - let res = compile_source(source); - assert!( - res.is_ok(), - "Expected checker to release lens after early-return branch, got: {:?}", - res.err() - ); -} - -#[test] -fn test_soundness_inconsistent_branch_move_rejected() { - let source = r#" - fn main() -> void { - let v = vec_init(16); - let cond = true; - if cond { - let x = v; - } else { - let y = 10; - } - let z = v; - } - "#; - let res = compile_source(source); - assert!( - res.is_err(), - "Expected rejection for inconsistent ownership branch move" - ); - let err = res.unwrap_err(); - assert!( - err.contains("inconsistent state"), - "Error message should mention inconsistent state: {}", - err - ); -} - -#[test] -fn test_soundness_double_move_rejected() { - let source = r#" - fn main() -> void { - let v = vec_init(16); - let x = v; - let y = v; - } - "#; - let res = compile_source(source); - assert!(res.is_err(), "Expected rejection for double move"); -} diff --git a/tests/yard_tests.rs b/tests/yard_tests.rs deleted file mode 100644 index 13ecba8e..00000000 --- a/tests/yard_tests.rs +++ /dev/null @@ -1,268 +0,0 @@ -use std::env; -use std::fs; -use track::yard::commands; -use track::yard::manifest::Manifest; - -#[test] -fn test_yard_manifest_serialization() { - let mut manifest = Manifest::new("test_proj"); - manifest.package.version = "1.2.3".to_string(); - let toml_str = toml::to_string_pretty(&manifest).unwrap(); - assert!(toml_str.contains("name = \"test_proj\"")); - assert!(toml_str.contains("version = \"1.2.3\"")); - - let loaded: Manifest = toml::from_str(&toml_str).unwrap(); - assert_eq!(loaded.package.name, "test_proj"); - assert_eq!(loaded.package.version, "1.2.3"); -} - -#[test] -fn test_yard_init_add_check_in_temp_dir() { - let temp_dir = env::temp_dir().join(format!("track_test_yard_{}", std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - - let proj_dir = temp_dir.join("my_app"); - - // Test yard init - let init_res = commands::init(&[proj_dir.to_str().unwrap().to_string()]); - assert!(init_res.is_ok(), "yard init failed: {:?}", init_res.err()); - - assert!(proj_dir.join("Track.toml").exists()); - assert!(proj_dir.join("src/main.trk").exists()); - assert!(proj_dir.join(".gitignore").exists()); - - // Test yard check_at - let check_res = commands::check_at(&proj_dir, &[]); - assert!( - check_res.is_ok(), - "yard check failed: {:?}", - check_res.err() - ); - - // Test yard add_at - let add_res = commands::add_at( - &proj_dir, - &[ - "some_dep".to_string(), - "--version".to_string(), - "0.2.0".to_string(), - ], - ); - assert!(add_res.is_ok(), "yard add failed: {:?}", add_res.err()); - - let updated_manifest = Manifest::load(&proj_dir.join("Track.toml")).unwrap(); - assert!(updated_manifest.dependencies.contains_key("some_dep")); - - // Cleanup - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_yard_parallel_build_and_incremental_cache() { - let temp_dir = env::temp_dir().join(format!("track_test_parallel_{}", std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - - let proj_dir = temp_dir.join("multi_app"); - - // Init project - let init_res = commands::init(&[proj_dir.to_str().unwrap().to_string()]); - assert!(init_res.is_ok(), "yard init failed: {:?}", init_res.err()); - - // Add extra source files to test parallel building - fs::write( - proj_dir.join("src/helper1.trk"), - "fn helper1() -> i32 { return 10; }\n", - ) - .unwrap(); - - fs::write( - proj_dir.join("src/helper2.trk"), - "fn helper2() -> i32 { return 20; }\n", - ) - .unwrap(); - - // Initial parallel build - let build_res = commands::build_at(&proj_dir, &[]); - assert!( - build_res.is_ok(), - "yard build failed: {:?}", - build_res.err() - ); - assert!(proj_dir.join("target/multi_app").exists()); - assert!(proj_dir.join("target/.cache_meta.json").exists()); - - // Second build (should hit cache) - let rebuild_res = commands::build_at(&proj_dir, &[]); - assert!( - rebuild_res.is_ok(), - "yard rebuild failed: {:?}", - rebuild_res.err() - ); - - let _ = fs::remove_dir_all(&temp_dir); -} - -#[test] -fn test_yard_lint_and_clean() { - let td = env::temp_dir().join(format!("track_yard_lint_{}", std::process::id())); - let _ = fs::remove_dir_all(&td); - let proj = td.join("lint_app"); - commands::init(&[proj.to_str().unwrap().to_string()]).unwrap(); - // lint should succeed on fresh project - let lint = commands::lint_at(&proj, &[]); - assert!(lint.is_ok(), "lint failed: {:?}", lint.err()); - // build then clean - let build = commands::build_at(&proj, &[]); - assert!(build.is_ok(), "build failed: {:?}", build.err()); - assert!(proj.join("target").exists()); - let clean = commands::clean_at(&proj); - assert!(clean.is_ok()); - assert!(!proj.join("target").exists()); - let _ = fs::remove_dir_all(&td); -} - -#[test] -fn test_yard_version_reports() { - let out = std::process::Command::new(env!("CARGO_BIN_EXE_yard")) - .arg("--version") - .output(); - if let Ok(o) = out { - let s = format!( - "{}{}", - String::from_utf8_lossy(&o.stdout), - String::from_utf8_lossy(&o.stderr) - ); - assert!(s.contains("1.0.0"), "yard version missing 1.0.0: {}", s); - } else { - // fallback via cargo run - let o = std::process::Command::new("cargo") - .args(["run", "--bin", "yard", "--", "--version"]) - .output() - .unwrap(); - let s = format!( - "{}{}", - String::from_utf8_lossy(&o.stdout), - String::from_utf8_lossy(&o.stderr) - ); - assert!(s.contains("1.0.0"), "yard version missing: {}", s); - } -} - -#[test] -fn test_yard_build_generics_project() { - let td = env::temp_dir().join(format!("track_yard_gen_{}", std::process::id())); - let _ = fs::remove_dir_all(&td); - let proj = td.join("gen_app"); - commands::init(&[proj.to_str().unwrap().to_string()]).unwrap(); - fs::write( - proj.join("src/main.trk"), - "fn identity(x: T) -> T { return x; } fn main() -> void { let a: i32 = 9; print(identity(a)); }", - ).unwrap(); - let build = commands::build_at(&proj, &[]); - assert!(build.is_ok(), "generics build failed: {:?}", build.err()); - assert!(proj.join("target/gen_app").exists()); - let check = commands::check_at(&proj, &[]); - assert!(check.is_ok(), "generics check failed: {:?}", check.err()); - let lint = commands::lint_at(&proj, &[]); - assert!(lint.is_ok()); - let _ = fs::remove_dir_all(&td); -} - -#[test] -fn test_yard_nested_modules_have_isolated_stable_artifacts() { - let root = env::temp_dir().join(format!("track_yard_artifacts_{}", std::process::id())); - let _ = fs::remove_dir_all(&root); - let manifest = Manifest::new("artifacts"); - fs::create_dir_all(root.join("src/left")).unwrap(); - fs::create_dir_all(root.join("src/right")).unwrap(); - for (path, source) in [ - ("main.trk", "fn main() -> void { print(42); }"), - ("left/helper.trk", "fn left_helper() -> i32 { return 10; }"), - ( - "right/helper.trk", - "fn right_helper() -> i32 { return 20; }", - ), - ( - "_track_runtime.trk", - "fn user_runtime() -> i32 { return 30; }", - ), - ] { - fs::write(root.join("src").join(path), source).unwrap(); - } - - let build = || track::yard::builder::ParallelBuilder::build(&root, &manifest).unwrap(); - build(); - let objects: Vec<_> = [ - "main.o", - "left/helper.o", - "right/helper.o", - "_track_runtime.o", - ] - .iter() - .map(|name| root.join("target/objects").join(name)) - .collect(); - let original_objects: Vec<_> = objects.iter().map(|path| fs::read(path).unwrap()).collect(); - assert_ne!(original_objects[1], original_objects[2]); - assert!(root.join("target/_track_runtime.o").exists()); - let metadata_path = root.join("target/.cache_meta.json"); - let metadata = fs::read(&metadata_path).unwrap(); - - // Warm builds must preserve objects as well as serialized metadata. - let modified: Vec<_> = objects - .iter() - .map(|p| fs::metadata(p).unwrap().modified().unwrap()) - .collect(); - build(); - assert_eq!(metadata, fs::read(&metadata_path).unwrap()); - for (path, before) in objects.iter().zip(modified) { - assert_eq!(fs::metadata(path).unwrap().modified().unwrap(), before); - } - - // A clean build must recreate the same artifact names and metadata. - fs::remove_dir_all(root.join("target")).unwrap(); - build(); - assert_eq!(metadata, fs::read(&metadata_path).unwrap()); - for path in &objects { - assert!(path.is_file(), "missing {}", path.display()); - } - let output = std::process::Command::new(root.join("target/artifacts")) - .output() - .unwrap(); - assert!(output.status.success()); - assert_eq!(String::from_utf8(output.stdout).unwrap().trim(), "42"); - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn test_yard_build_errors_follow_source_order() { - let root = env::temp_dir().join(format!("track_yard_error_order_{}", std::process::id())); - fs::create_dir_all(root.join("src")).unwrap(); - for name in ["z.trk", "a.trk"] { - fs::write(root.join("src").join(name), "fn invalid( {").unwrap(); - } - let manifest = Manifest::new("errors"); - for _ in 0..4 { - let error = track::yard::builder::ParallelBuilder::build(&root, &manifest).unwrap_err(); - assert!(error.contains("a.trk"), "unexpected first error: {error}"); - } - fs::remove_dir_all(root).unwrap(); -} - -#[test] -fn test_yard_dependency_resolution_is_sorted() { - use track::yard::{manifest::Dependency, resolver}; - let mut manifest = Manifest::new("ordered"); - for name in ["zebra", "alpha", "middle"] { - manifest - .dependencies - .insert(name.into(), Dependency::Simple("1.0".into())); - } - let dependencies = resolver::resolve(&manifest, std::path::Path::new(".")).unwrap(); - assert_eq!( - dependencies - .iter() - .map(|dep| dep.name.as_str()) - .collect::>(), - ["alpha", "middle", "zebra"] - ); -}