diff --git a/.gitattributes b/.gitattributes index 3564612..6768c72 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,9 @@ *.wave text eol=lf linguist-language=Wave *.rs text eol=lf +*.toml text eol=lf +vex.ws text eol=lf +vex.lock text eol=lf +vex.toolchain.lock text eol=lf *.ps1 linguist-vendored *.sh linguist-vendored Makefile linguist-vendored diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index a03365e..b707132 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -40,25 +40,33 @@ jobs: with: repository: wavefnd/Wave ref: e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b - path: .asmobj-bootstrap-source + path: .hir-fixture-source persist-credentials: false - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' - - name: Install pinned compiler prerequisites + - name: Install build tools and verified Vex v0.0.3-beta run: | sudo apt-get update - sudo apt-get install --no-install-recommends -y wget software-properties-common ninja-build nasm - wget --tries=3 --timeout=30 https://apt.llvm.org/llvm.sh -O "$RUNNER_TEMP/llvm.sh" - sudo bash "$RUNNER_TEMP/llvm.sh" 21 - sudo apt-get install --no-install-recommends -y llvm-21-dev lld-21 - printf '%s\n' \ - 'LLVM_SYS_211_PREFIX=/usr/lib/llvm-21' \ - 'LLVM_CONFIG_PATH=/usr/lib/llvm-21/bin/llvm-config' \ - 'AR=/usr/lib/llvm-21/bin/llvm-ar' >> "$GITHUB_ENV" - echo "/usr/lib/llvm-21/bin" >> "$GITHUB_PATH" - rustup toolchain install 1.89.0 --profile minimal + sudo apt-get install --no-install-recommends -y ninja-build nasm llvm + echo "AR=/usr/bin/llvm-ar" >> "$GITHUB_ENV" + python3 -m pip install --disable-pip-version-check meson==1.8.5 rustup toolchain install stable --profile minimal + rustup toolchain install 1.89.0 --profile minimal + curl --fail --location --retry 3 \ + https://github.com/wavefnd/Vex/releases/download/v0.0.3-beta/vex-v0.0.3-beta-x86_64-unknown-linux-gnu.tar.gz \ + --output "$RUNNER_TEMP/vex.tar.gz" + echo "0b2fb97b74b38711d41bf4f58a7b1d15af392cc13271575cd517ac0f67fd8059 $RUNNER_TEMP/vex.tar.gz" | sha256sum --check + mkdir -p "$RUNNER_TEMP/vex-bin" + tar -xzf "$RUNNER_TEMP/vex.tar.gz" -C "$RUNNER_TEMP/vex-bin" --strip-components=1 + echo "$RUNNER_TEMP/vex-bin" >> "$GITHUB_PATH" + - name: Resolve one nightly compiler for this entire build + run: | + python3 tools/wave_nightly.py --cache-dir "$RUNNER_TEMP/wave-nightly" \ + --output "$RUNNER_TEMP/wave-toolchain.json" + python3 tools/vex_module.py --prepare --vex "$(command -v vex)" \ + --toolchain "$RUNNER_TEMP/wave-toolchain.json" \ + --build-dir "$RUNNER_TEMP/vex-prepare" --state-dir "$RUNNER_TEMP/vex-state" - name: Build each archive from the same complete source module run: | for target in \ @@ -69,15 +77,16 @@ jobs: aarch64-pc-windows-msvc \ x86_64-apple-darwin \ aarch64-apple-darwin; do - python3 tools/build_asmobj.py --wave-source .asmobj-bootstrap-source \ - --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ - --out-dir ".ci-asmobj/$target" --target "$target" --allow-network + python3 tools/vex_module.py --module asmobj --vex "$(command -v vex)" \ + --toolchain "$RUNNER_TEMP/wave-toolchain.json" --state-dir "$RUNNER_TEMP/vex-state" \ + --build-dir "$RUNNER_TEMP/vex-asmobj-$target" --profile release \ + --output-dir ".ci-asmobj/$target" --target "$target" done - name: Compare native Linux O0 and O2 with the independent oracle run: | - python3 tools/build_asmobj.py --wave-source .asmobj-bootstrap-source \ - --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ - --out-dir "$RUNNER_TEMP/asmobj-o0" --opt-level 0 + python3 tools/vex_module.py --module asmobj --vex "$(command -v vex)" \ + --toolchain "$RUNNER_TEMP/wave-toolchain.json" --state-dir "$RUNNER_TEMP/vex-state" \ + --build-dir "$RUNNER_TEMP/vex-asmobj-o0" --output-dir "$RUNNER_TEMP/asmobj-o0" cc -shared -Wl,--whole-archive "$RUNNER_TEMP/asmobj-o0/libwhale_asmobj.a" \ -Wl,--no-whole-archive -o "$RUNNER_TEMP/asmobj-o0.so" cc -shared -Wl,--whole-archive .ci-asmobj/x86_64-unknown-linux-gnu/libwhale_asmobj.a \ @@ -92,9 +101,12 @@ jobs: run: | cargo fetch --locked for optimization in 0 2; do - python3 tools/build_wave_ir.py --wave-source .asmobj-bootstrap-source \ - --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ - --out-dir "$RUNNER_TEMP/wave-ir-o$optimization" --opt-level "$optimization" + profile=dev + if [ "$optimization" = 2 ]; then profile=release; fi + python3 tools/vex_module.py --module ir --vex "$(command -v vex)" \ + --toolchain "$RUNNER_TEMP/wave-toolchain.json" --state-dir "$RUNNER_TEMP/vex-state" \ + --build-dir "$RUNNER_TEMP/vex-ir-o$optimization" --profile "$profile" \ + --output-dir "$RUNNER_TEMP/wave-ir-o$optimization" cc -shared -Wl,--whole-archive "$RUNNER_TEMP/wave-ir-o$optimization/libwhale_wave_ir.a" \ -Wl,--no-whole-archive -o "$RUNNER_TEMP/wave-ir-o$optimization.so" ir_python="$(command -v python3)" @@ -131,11 +143,14 @@ jobs: run: | for optimization in 0 2; do for module in common amd64 aarch64 riscv64 loongarch64; do - python3 tools/build_wave_assembler.py --module "$module" \ - --wave-source .asmobj-bootstrap-source \ - --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ - --out-dir "$RUNNER_TEMP/assembler-$module-o$optimization" \ - --opt-level "$optimization" + package="$module" + if [ "$module" = common ]; then package=assembler; fi + profile=dev + if [ "$optimization" = 2 ]; then profile=release; fi + python3 tools/vex_module.py --module "$package" --vex "$(command -v vex)" \ + --toolchain "$RUNNER_TEMP/wave-toolchain.json" --state-dir "$RUNNER_TEMP/vex-state" \ + --build-dir "$RUNNER_TEMP/vex-$package-o$optimization" --profile "$profile" \ + --output-dir "$RUNNER_TEMP/assembler-$module-o$optimization" done export WHALE_WAVE_ASSEMBLER_DIR="$RUNNER_TEMP/assembler-common-o$optimization" export WHALE_WAVE_AMD64_DIR="$RUNNER_TEMP/assembler-amd64-o$optimization" @@ -227,21 +242,20 @@ jobs: python3 tools/check_wave_module_selection.py \ --ir-dir "$WHALE_WAVE_IR_DIR" --assembler-dir "$WHALE_WAVE_ASSEMBLER_DIR" \ --target-dir "$RUNNER_TEMP/wave-selection-target" - - name: Reproduce the pinned typed HIR fixture + - name: Reproduce the historical typed HIR fixture run: | - python3 tools/check_wave_hir_fixture.py --wave-source .asmobj-bootstrap-source \ + cargo +1.89.0 fetch --locked --manifest-path .hir-fixture-source/Cargo.toml + python3 tools/check_wave_hir_fixture.py --wave-source .hir-fixture-source \ --target-dir "$RUNNER_TEMP/wave-hir-fixture" --rust-toolchain 1.89.0 - name: Build, test and install the Meson source product run: | - python3 -m pip install --disable-pip-version-check meson==1.8.5 cargo fetch --locked meson setup "$RUNNER_TEMP/whale-meson" \ - -Dwave-source="$GITHUB_WORKSPACE/.asmobj-bootstrap-source" \ - -Dwave-bootstrap-dir="$RUNNER_TEMP/asmobj-bootstrap" -Dsocket-cli=true + -Dwave-cache-dir="$RUNNER_TEMP/wave-nightly" -Dwave-offline=true -Dsocket-cli=true + meson compile -C "$RUNNER_TEMP/whale-meson" + before="$(stat -c '%Y:%s' "$RUNNER_TEMP/whale-meson/whale")" meson compile -C "$RUNNER_TEMP/whale-meson" - warm_build="$(meson compile -C "$RUNNER_TEMP/whale-meson")" - printf '%s\n' "$warm_build" - printf '%s\n' "$warm_build" | grep -F 'ninja: no work to do.' + test "$before" = "$(stat -c '%Y:%s' "$RUNNER_TEMP/whale-meson/whale")" meson test -C "$RUNNER_TEMP/whale-meson" --print-errorlogs DESTDIR="$RUNNER_TEMP/whale-meson-install" meson install -C "$RUNNER_TEMP/whale-meson" "$RUNNER_TEMP/whale-meson-install/usr/local/bin/whale" --version diff --git a/.gitignore b/.gitignore index 52f98a6..245a517 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ target/ .ci-wave/ __pycache__/ /docs/ + +/.vex/ diff --git a/BUILDING.md b/BUILDING.md index 2f29fd7..700ae2a 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1,160 +1,90 @@ -# Building Whale with Meson +# Building Whale -Meson builds the Wave IR, shared assembler, selected ISA modules and `asmobj`, -then uses Cargo for Rust data transport, files, object formats and CLI components. -IR and assembler production algorithms run in Wave. Rust references require the -explicit `rust-reference` feature and are for comparison tests. -Generated files and Cargo outputs stay in the selected build directory. +Meson automates the complete build. Vex builds Wave packages and static libraries; +Cargo builds the remaining Rust components and data bindings. Linked binaries +need none of these tools at runtime. The initial full native host is Linux x86_64 GNU. ## Build, test and install -Install Meson 1.8 or newer, Ninja, Python 3.12 or newer, Git, Rust 1.86 or newer, -and a native linker. Building `asmobj` also requires LLVM 21 development -libraries, `ar`, and installed Rust **1.89.0** for the pinned Wave compiler. -The initial executable host for the linked module is **Linux x86_64 GNU**. -Whale's Rust MSRV and the Wave bootstrap's Rust version are separate requirements. -`whale build-info --json` reports linked module identities and build fingerprints. - -Provide a Wave Git repository containing commit -`e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b`. The helper reads that commit with -`git archive` and leaves the checkout untouched, including any local changes. -Run these commands from the Whale source root: +Install Vex **v0.0.3-beta or newer**, Meson **1.8.5+**, Ninja, Python **3.13+**, +Rust **1.86+** and a native linker. Fetch Cargo dependencies once, then build: ```sh -# Fetch Rust dependencies separately when they are not cached. cargo fetch --locked -# Adjust this prefix to the installed LLVM 21 location. -export LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 -meson setup /tmp/whale-build \ - -Dwave-source=/absolute/path/to/Wave \ - -Dwave-bootstrap-dir=/tmp/whale-bootstrap \ - -Dwave-rust-toolchain=1.89 +meson setup /tmp/whale-build --buildtype=release -Dsocket-cli=true meson compile -C /tmp/whale-build meson test -C /tmp/whale-build --print-errorlogs /tmp/whale-build/whale build-info --json DESTDIR=/tmp/whale-install meson install -C /tmp/whale-build -/tmp/whale-install/usr/local/bin/whale --version ``` -Use the installed alias `1.89` above only if it reports exactly Rust 1.89.0; -the option defaults to `1.89.0`. All four assembler architectures are selected -by default. `--buildtype=release` selects optimized Rust output, and -`-Dsocket-cli=true` includes experimental AST JSON lowering. +Each compilation queries Wave's moving `nightly` release once. The helper verifies +its published archive and metadata SHA256, records the source commit, and selects +one immutable compiler/std/runtime generation for every module in that build. +A later build checks for a newer nightly. Failed downloads or compilation preserve +previous products; an online failure is reported rather than silently using old code. +No local Wave checkout, LLVM development libraries or compiler bootstrap is needed. -Cargo resolution is locked and offline by default. `-Dcargo-offline=false` -permits host dependency downloads; `-Dwave-allow-network=true` separately permits -locked Wave compiler dependency downloads. Setup does not run Cargo or bootstrap -the compiler. Compilation schedules the pinned compiler and matching std, the -complete `asmobj` archive, and then the Whale executable. +Use `-Dwave-cache-dir=/absolute/cache` to share verified generations. After one +online build, `meson configure /tmp/whale-build -Dwave-offline=true` reuses that +cache without network access. Compiler, std and runtime files are rechecked before +reuse. `wave-toolchain.json` in the build directory records its exact selection; +`whale build-info --json` records the linked archive/compiler identities. -Each build directory has its own Cargo output and executable. Meson tracks Cargo -dependency files, local Rust sources and manifests, and the explicit `asmobj` -source list and artifact metadata. A compiler/std cache can be shared through -`wave-bootstrap-dir`; cache identities and hashes are validated before reuse. -Do not use the source tree's `target/` as a Meson build directory. +Cargo is locked and offline by default; `-Dcargo-offline=false` allows missing +Rust dependencies to download. `-Dvex=/absolute/path/to/vex` selects Vex explicitly. +Use a separate build directory outside the source tree's `target/`. ## Reuse built modules or run Cargo checks -The helpers read the pinned Wave commit without changing its checkout: - -| Helper | Module | -| --- | --- | -| `tools/build_asmobj.py` | Assembly-to-object mapping | -| `tools/build_wave_ir.py` | IR, passes, interpreter and bytecode | -| `tools/build_wave_assembler.py --module common` | Shared assembler | -| `tools/build_wave_assembler.py --module amd64` | Selected ISA; also `aarch64`, `riscv64`, `loongarch64` | - -Each accepts `--wave-source`, `--out-dir`, `--bootstrap-dir` and -`--rust-toolchain` as in this example: - -```sh -python3 tools/build_wave_ir.py --wave-source /absolute/path/to/Wave \ - --out-dir /tmp/whale-ir --bootstrap-dir /tmp/whale-bootstrap --rust-toolchain 1.89 -``` - -Prebuilt Meson products require `-Dasmobj-dir=...`, `-Dwave-ir-dir=...`, -`-Dwave-assembler-dir=...` and `-Dwave-ARCH-dir=...` for every selected ISA. -Unselected ISA archives are not linked. Meson requires all selected modules; -ambient environment variables cannot replace its explicit selections. - -For direct native Cargo checks, select those same archives explicitly: +Meson accepts prebuilt directories through `asmobj-dir`, `wave-ir-dir`, +`wave-assembler-dir` and `wave-ARCH-dir` for each selected ISA. Each directory +must contain its archive, `module.meta` and `provenance.json` from the current +source and Rust binding ABI. Unselected ISAs are not linked. -```sh -export WHALE_ASMOBJ_DIR=/path/to/asmobj -export WHALE_WAVE_IR_DIR=/path/to/ir -export WHALE_WAVE_ASSEMBLER_DIR=/path/to/common -export WHALE_WAVE_AMD64_DIR=/path/to/amd64 -export WHALE_WAVE_AARCH64_DIR=/path/to/aarch64 -export WHALE_WAVE_RISCV64_DIR=/path/to/riscv64 -export WHALE_WAVE_LOONGARCH64_DIR=/path/to/loongarch64 -cargo test --workspace --all-features --locked -``` - -Source, ABI, archive and pinned compiler/std fingerprints are checked before -linking; rebuild the affected archive after changing its boundary or Wave source. -Failed compilation or archiving preserves the previous complete publication. -Cargo never bootstraps or downloads Wave automatically. A linked executable -needs no `wavec` at runtime. The numeric core uses two 64-bit words for 128-bit -integers and exact IEEE rounding without host floating-point arithmetic. - -For deliberate Rust reference checks, omit the `WHALE_WAVE_*` variables and use -`cargo test --workspace --all-features --locked`, or select `--features rust-reference` -on the component being tested. For a reference CLI: +For direct Cargo checks, select the Meson products explicitly: ```sh -cargo build --no-default-features \ - --features asm-amd64,socket-cli,native-linker,rust-reference +export WHALE_ASMOBJ_DIR=/tmp/whale-build/assembler/asmobj +export WHALE_WAVE_IR_DIR=/tmp/whale-build/ir +export WHALE_WAVE_ASSEMBLER_DIR=/tmp/whale-build/assembler +export WHALE_WAVE_AMD64_DIR=/tmp/whale-build/assembler/amd64 +export WHALE_WAVE_AARCH64_DIR=/tmp/whale-build/assembler/aarch64 +export WHALE_WAVE_RISCV64_DIR=/tmp/whale-build/assembler/riscv64 +export WHALE_WAVE_LOONGARCH64_DIR=/tmp/whale-build/assembler/loongarch64 +cargo test --workspace --all-features --locked --offline ``` -Supplying a Wave archive selects Wave even with `rust-reference` enabled. -Missing production archives fail with setup instructions. `asmobj` has no Rust -implementation; reference CLI assembly-to-object checks still need its archive. +Cargo verifies source, ABI, archive and provenance fingerprints before linking; +it never downloads or invokes Wave. Rebuild affected modules after source changes. +For deliberate reference tests, omit the Wave variables and select +`rust-reference` explicitly, for example `cargo test -p ir --features rust-reference`. +`asmobj` has no Rust implementation. Supplying an archive always selects Wave. ## Select assembler outputs and host machines -Architecture selection controls generated code independently of the machine -running Whale. For an AArch64-only product: +All four assemblers are enabled by default. For an AArch64-only output product: ```sh -meson setup /tmp/whale-aarch64 -Dwave-source=/absolute/path/to/Wave \ +meson setup /tmp/whale-aarch64 \ -Dasm-amd64=false -Dasm-riscv64=false -Dasm-loongarch64=false -meson compile -C /tmp/whale-aarch64 ``` -Also set `-Dasm-aarch64=false` for a product without concrete assemblers. -`meson configure BUILD_DIR -DOPTION=VALUE` changes an existing selection. +Also disable `asm-aarch64` for a product without assemblers. `native-linker=false` +removes native executable linking. These selections describe generated code, +independently of the host running Whale. -A Meson cross file and `-Dcargo-host-target=RUST_TRIPLE` describe the final -Whale executable host. The Rust target must agree with Meson's host machine. -Cross compilation additionally needs the matching Rust target, linker, and -module archive. The build helper's `--target` defaults to -`x86_64-unknown-linux-gnu`; producing an object for another target does not -establish that Whale runs on that host. COFF and Mach-O cross archives need -LLVM ar: set `AR=/absolute/path/to/llvm-ar`. The helper explicitly selects the -linker's archive format; GNU ar cannot produce these cross-format indexes. -The initial linked native host remains Linux x86_64 GNU. - -Native runtime tests run directly. Cross runtime tests require an explicit +A Meson cross file plus `-Dcargo-host-target=RUST_TRIPLE` describes the executable +host. Cross builds also need the Rust target and linker. Vex produces matching +ELF, COFF or Mach-O archives; cross-produced objects do not establish native +execution support. Cross runtime tests require explicit `-Dhost-runner='["wrapper", "argument"]'`; otherwise they are omitted. -Arguments are passed without shell interpretation. Record omitted checks as -omitted, without treating them as executed native tests. ## Add an architecture in the source tree -Keep an architecture's registers, operands, parser, instructions and encoder in -separate files under `assembler//`. Shared helpers contain only -behavior needed by multiple architectures. IR target lowering belongs beside -its target implementation. - -A contribution normally updates these explicit points: - -1. Target identity and data layout in `target-spec/` when required. -2. Source/build lists and the architecture's Meson selection option. -3. Product composition in `src/builtins.rs` and deliberate CLI aliases. -4. Relocation translation in `assembler/asmobj/` and object format support. -5. Encoding, rejection, object and CLI tests, plus capability documentation. - -Official and contributed architectures use the same layout. Small central enum, -dispatch and build-list edits are expected. Run -`python3 tools/check_module_layers.py` to check dependency direction. See the [contribution guide](CONTRIBUTING.md#2-repository-structure-and-module-boundaries) -for source responsibilities and checks. +Place Wave code under `assembler/ARCH/src/`, split by registers, operands, +parsing, instructions and encoding. Put Rust transport bindings under +`bindings/rust/ARCH/`. Add its Vex workspace member and Meson selection, update +`target-spec`, CLI composition and `asmobj` relocation mappings as needed, and +test bytes, rejected inputs and object metadata. Shared modules must not import +concrete ISAs. See [CONTRIBUTING.md](CONTRIBUTING.md#2-repository-structure-and-module-boundaries). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 70dcd23..fb0aa9f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ and review comments should be in English. Follow the ## 1. Development setup -Use [BUILDING.md](BUILDING.md) for Meson, the pinned Wave compiler, dependencies +Use [BUILDING.md](BUILDING.md) for Meson, the verified Wave nightly, dependencies and installation. Rust's MSRV is **1.86.0**; CI uses Python **3.13**. Use Meson for the native product and its tests. Direct Cargo checks need the @@ -18,11 +18,12 @@ at runtime. | Sources | Responsibility | | --- | --- | -| `assembler//` | ISA registers, operands, grammar and encoding, with explicit Rust data bridges | -| `assembler/*.wave`, `assembler/src/` | Shared Wave source, numeric and output helpers; Rust assembly data | -| `assembler/asmobj/` | Complete Wave assembly-to-object module | -| `toolchain/`, `backend-api/` | Rust composition, backend interfaces and external data calls to `asmobj` | -| `ir/`, `target-spec/` | Wave IR model, text, verification, numeric semantics, passes and execution; Rust data transport and target contracts | +| `assembler/ARCH/src/` | Wave ISA registers, operands, parser and encoder | +| `assembler/src/` | Shared Wave source, numeric and output helpers | +| `assembler/asmobj/src/` | Complete Wave assembly-to-object module | +| `ir/src/` | Wave IR, verification, lowering, interpreter and bytecode | +| `bindings/rust/` | Rust data bindings and explicit comparison references | +| `toolchain/`, `backend-api/`, `target-spec/` | Product composition and target contracts | | `object/`, `linker/` | Rust object formats, relocations and executable layout | | `reverse/` | Rust image inspection; decoder and CFG currently unavailable | | `src/`, `tests/` | CLI and integration tests | @@ -30,15 +31,15 @@ at runtime. Split source files by role. Shared modules must not import a concrete ISA. `asmobj` contains only Wave sources; its Rust data boundary lives in -`toolchain/src/assembly_object.rs`. Object serialization belongs to `object`. +`bindings/rust/asmobj/src/lib.rs`. Object serialization belongs to `object`. Rust reference algorithms are selected explicitly with `rust-reference` for comparison tests. Keep Wave blocks readable with four-space indentation and one statement per line. ### Adding an assembler or IR target -1. Add architecture sources under `assembler//`, or the owning IR backend. +1. Add architecture sources under `assembler//src/`, or the owning IR backend. 2. Update `target-spec`, explicit dispatch and `src/builtins.rs` as needed. -3. Update Meson/Cargo source selections and Wave `asmobj` relocation mappings. +3. Update Vex/Meson/Cargo source selections and Wave `asmobj` relocation mappings. 4. Test emitted bytes, metadata, rejected inputs and CLI behavior. Official and contributed architectures follow the same process. Central enum, diff --git a/Cargo.lock b/Cargo.lock index abc1076..fa6d597 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,6 +18,14 @@ dependencies = [ "diagnostic", ] +[[package]] +name = "asmobj" +version = "0.1.0" +dependencies = [ + "assembler", + "object", +] + [[package]] name = "assembler" version = "0.1.0" @@ -291,6 +299,7 @@ dependencies = [ name = "toolchain" version = "0.1.0" dependencies = [ + "asmobj", "assembler", "backend-api", "diagnostic", diff --git a/Cargo.toml b/Cargo.toml index c1ee33d..e3687e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,18 +1,20 @@ [workspace] members = [ "diagnostic", - "assembler", - "assembler/amd64", - "assembler/aarch64", - "assembler/riscv64", - "assembler/loongarch64", + "bindings/rust/assembler", + "bindings/rust/amd64", + "bindings/rust/aarch64", + "bindings/rust/riscv64", + "bindings/rust/loongarch64", "backend-api", "toolchain", + "bindings/rust/asmobj", "examples/external-target", "reverse", "target-spec", "object", - "linker", "ir", + "linker", + "bindings/rust/ir", ] [workspace.package] @@ -36,11 +38,11 @@ native-linker = ["dep:linker"] rust-reference = ["assembler/rust-reference", "ir/rust-reference", "toolchain/rust-reference", "amd64?/rust-reference", "aarch64?/rust-reference", "riscv64?/rust-reference", "loongarch64?/rust-reference"] [dependencies] -assembler = { path = "assembler" } -amd64 = { path = "assembler/amd64", optional = true } -aarch64 = { path = "assembler/aarch64", optional = true } -riscv64 = { path = "assembler/riscv64", optional = true } -loongarch64 = { path = "assembler/loongarch64", optional = true } +assembler = { path = "bindings/rust/assembler" } +amd64 = { path = "bindings/rust/amd64", optional = true } +aarch64 = { path = "bindings/rust/aarch64", optional = true } +riscv64 = { path = "bindings/rust/riscv64", optional = true } +loongarch64 = { path = "bindings/rust/loongarch64", optional = true } toolchain = { path = "toolchain" } reverse = { path = "reverse" } linker = { path = "linker", optional = true } @@ -48,7 +50,7 @@ backend-api = { path = "backend-api" } diagnostic = { path = "diagnostic" } target-spec = { path = "target-spec" } object = { path = "object" } -ir = { path = "ir", version = "0.1.0", default-features = false } +ir = { path = "bindings/rust/ir", version = "0.1.0", default-features = false } serde_json = "1" serde = { version = "1", features = ["derive"] } same-file = "1" diff --git a/NOTICE b/NOTICE index dbbca07..4f6ea28 100644 --- a/NOTICE +++ b/NOTICE @@ -14,3 +14,7 @@ attribution for the community policy adapted from the Contributor Covenant. The repository AI-use policy and permission contact are recorded in ai.txt. This notice does not replace the applicable license texts. + +The generation lease in tools/vex_module.py is adapted from wavefnd/Vex's +MPL-2.0 tools/meson_consumer.py at v0.0.3-beta: +https://github.com/wavefnd/Vex/blob/v0.0.3-beta/tools/meson_consumer.py diff --git a/README.md b/README.md index 2371666..d74dc9a 100644 --- a/README.md +++ b/README.md @@ -99,9 +99,7 @@ On the initial Linux x86_64 GNU host: git clone https://github.com/wavefnd/Whale.git cd Whale cargo fetch --locked -export LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 -meson setup /tmp/whale-build --buildtype=release \ - -Dwave-source=/absolute/path/to/Wave +meson setup /tmp/whale-build --buildtype=release meson compile -C /tmp/whale-build meson test -C /tmp/whale-build --print-errorlogs /tmp/whale-build/whale --version @@ -254,8 +252,8 @@ Equal-width integer/float `bitcast` reinterprets those bits. Numeric `fext`, with the [defined rounding and range traps](ir/CASTS.md). Bitcasts cannot recover pointer or function-pointer authority from numerical bits. ```sh -cargo run --locked -- ir run ir/tests/fixtures/float-storage-v7.wir --function @f0 --arg 0x7c01 -cargo run --locked -- ir run ir/tests/fixtures/float-storage-v7.wir --function @f3 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/float-storage-v7.wir --function @f0 --arg 0x7c01 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/float-storage-v7.wir --function @f3 ``` These print `f16 0x7c01` and `u64 9218868437227405603`. Floating storage obeys @@ -298,15 +296,15 @@ exposes this mapping and `FloatBits::compare` evaluates equal-width predicates. Runtime execution preserves instruction/trap order, including unused comparisons. ```sh -cargo run --locked -- ir run ir/tests/fixtures/float-comparisons-v7.wir --function @f0 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000 -cargo run --locked -- ir run ir/tests/fixtures/float-comparisons-v7.wir --function @f1 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/float-comparisons-v7.wir --function @f0 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/float-comparisons-v7.wir --function @f1 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000 ``` These print `bool true` (generic inequality) and `bool false` (ordered inequality). ### Execute tracked stack memory -Save [the complete memory fixture](ir/tests/fixtures/tracked-memory-v4.wir) +Save [the complete memory fixture](bindings/rust/ir/tests/fixtures/tracked-memory-v4.wir) as `tracked-memory.wir`. It copies an initialized pointer and then reads its pointee. Pointer bits and capability metadata travel separately. @@ -340,13 +338,13 @@ below. Foreign-memory adapters and native shadow metadata are future work. ### Addressable globals, explicit retirement and pointer offsets -[The executable storage fixture](ir/tests/fixtures/runtime-storage-v6.wir) covers +[The executable storage fixture](bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir) covers mutable/read-only/uninitialized globals, calls, expired aliases and byte differences: ```sh -cargo run --locked -- ir run ir/tests/fixtures/runtime-storage-v6.wir --function @f1 -cargo run --locked -- ir run ir/tests/fixtures/runtime-storage-v6.wir --function @f3 -cargo run --locked -- ir run ir/tests/fixtures/runtime-storage-v6.wir --function @f7 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir --function @f1 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir --function @f3 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir --function @f7 ``` These print `u32 12`, `u32 42` and `i128 16`. `@f4` traps on an uninitialized @@ -548,7 +546,7 @@ The printer emits typed IR format 8 with semantics version 1. AST JSON writes format 5. Definitions and references use explicit `@fN`, `@gN`, `%vN` and `%bN` identities; names are quoted annotations, and each function records its entry block. Name/string fields escape quotes, backslashes, control characters and -Unicode line separators. See the [identity fixture](ir/tests/fixtures/text-identities-v3.wir) +Unicode line separators. See the [identity fixture](bindings/rust/ir/tests/fixtures/text-identities-v3.wir) for repeated block names and IDs scoped to different functions. The verifier checks cast operands, opcode categories and width direction, and @@ -561,8 +559,8 @@ pointer metadata. These commands are available in the default build: ```sh -cargo run --locked -- ir verify ir/tests/fixtures/calls-v3.wir -cargo run --locked -- ir print ir/tests/fixtures/calls-v3.wir -o canonical.wir +cargo run --locked -- ir verify bindings/rust/ir/tests/fixtures/calls-v3.wir +cargo run --locked -- ir print bindings/rust/ir/tests/fixtures/calls-v3.wir -o canonical.wir ``` `ir print` and `ir lower` stream output under `--max-output N` (default 64 MiB). @@ -628,12 +626,12 @@ versions rejected. ### Typed function calls -The [complete call input](ir/tests/fixtures/ast-v2-calls.json) lowers a local +The [complete call input](bindings/rust/ir/tests/fixtures/ast-v2-calls.json) lowers a local function, a stored function pointer, an indirect call, and a SysV64 external -call. Its [printed IR](ir/tests/fixtures/calls-v3.wir) is checked by a regression test. +call. Its [printed IR](bindings/rust/ir/tests/fixtures/calls-v3.wir) is checked by a regression test. ```sh -cargo run --locked --features socket-cli -- ir lower ir/tests/fixtures/ast-v2-calls.json +cargo run --locked --features socket-cli -- ir lower bindings/rust/ir/tests/fixtures/ast-v2-calls.json ``` Declarations carry `FunctionId`, parameter/result types, calling convention, @@ -646,12 +644,12 @@ defined runtime trap contract in the interpreter; native dispatch remains future This IR support does not implement machine ABI lowering or carry identities through object emission and linking yet. -The [executable call fixture](ir/tests/fixtures/interpreted-calls-v4.wir) covers +The [executable call fixture](bindings/rust/ir/tests/fixtures/interpreted-calls-v4.wir) covers caller-owned pointers, nested calls, recursion and callable returns: ```sh -cargo run --locked -- ir run ir/tests/fixtures/interpreted-calls-v4.wir --function @f3 -cargo run --locked -- ir run ir/tests/fixtures/interpreted-calls-v4.wir --function @f6 --arg 4 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/interpreted-calls-v4.wir --function @f3 +cargo run --locked -- ir run bindings/rust/ir/tests/fixtures/interpreted-calls-v4.wir --function @f6 --arg 4 ``` These print `u32 42` and `u32 4`. `InterpreterOptions::max_call_depth` limits @@ -694,16 +692,16 @@ existing object files. `assembler/asmobj/` contains the complete Wave implementation of assembly-to-object validation and mapping, split into model, section, symbol, relocation and entry files. It replaces the former Rust `asmobj` crate. The external Rust data boundary -in `toolchain/src/assembly_object.rs` supplies buffers and converts the returned +in `bindings/rust/asmobj/src/lib.rs` supplies buffers and converts the returned records; object-file layout and serialization remain the separate Rust `object` module's responsibility. [Meson](BUILDING.md) compiles and links this module as part of the product. Cargo development builds select a prebuilt archive with `WHALE_ASMOBJ_DIR`. There is one implementation of its policies: an absent module returns an explicit -unavailable error. The IR module also runs in Wave when built with its pinned +unavailable error. The IR module also runs in Wave when built with its verified archive: parsing, verification, numeric semantics, constant evaluation, passes -and execution live in role-specific `ir/*.wave` sources. Rust supplies owned +and execution live in role-specific `ir/src/` sources. Rust supplies owned data, allocation and I/O; its reference implementation supports migration tests. ### Assembly symbol metadata and library resolution diff --git a/assembler/README.md b/assembler/README.md index 80de035..4456edc 100644 --- a/assembler/README.md +++ b/assembler/README.md @@ -1,58 +1,20 @@ # Assembly modules -The `assembler` crate owns output sections/symbols/relocations, limits and source -diagnostics. `extension::Assembler` accepts source directly, so implementations -can use their own syntax. `fixed` supplies bounded two-pass source, label and -section handling for four-byte instruction sets. AMD64 keeps its existing parser -and relaxation engine. Its complete existing [instruction and source reference](amd64/README.md) -is preserved in the AMD64 crate. Each ISA is an independent crate under this directory. - -Each new ISA follows the same responsibility boundaries: - -```text -src/lib.rs Public assembler entry point and trait implementations -src/parser.rs ISA operand syntax and register validation -src/tables.rs Register aliases, opcode/form tables and relocation IDs -src/encoder.rs Instruction selection, aliases and relocation resolution -src/encoding/branch.rs Checked branch ranges and immediate bit layouts -src/encoding/ Other instruction formats and ISA-specific families -tests/encodings.rs Independent LLVM encodings, owned by each ISA crate -``` - -A64 separates arithmetic and load/store encoding into `encoding/arithmetic.rs` -and `encoding/memory.rs`. RV64I and LoongArch64 put register/immediate format -packing in `encoding/formats.rs`. The shared fixed-width source front end handles -sections, labels, directives and resource limits; ISA crates own operand syntax -and machine instruction encoding. Parser and displacement-boundary unit tests -live beside their implementations. Root integration tests cover registration, -CLI behavior and the assembly-to-object boundary. - -`Assembler::object_target()` identifies native output. The -[`asmobj`](asmobj/) module under this directory is implemented entirely in Wave. -Its model, section, symbol, relocation and entry files validate assembly metadata -and map relocation namespaces to the selected object identity. Rust-owned buffer -conversion lives outside the module in `toolchain/src/assembly_object.rs`; the -separate Rust `object` module serializes its result. The CLI composes assemblers -through `toolchain::Registry` in `src/builtins.rs`. - -Build the complete product with [Meson](../BUILDING.md). For Cargo development, -set `WHALE_ASMOBJ_DIR` to an archive built by `tools/build_asmobj.py` before the -assembly-to-object examples and integration tests below. Without the module, -these commands return an explicit unavailable error. The initial linked module -host is Linux x86_64 GNU; assembler output architectures remain independent. - -```sh -cargo run -- asm --aarch64 examples/isa/aarch64.s -o /tmp/aarch64.o -cargo run -- asm --riscv64 examples/isa/riscv64.s -o /tmp/riscv64.o -cargo run -- asm --loongarch64 examples/isa/loongarch64.s -o /tmp/loongarch64.o -``` - -`--arm64` aliases `--aarch64`. `--arch ID` selects a registered assembler directly -(e.g. `--arch riscv64`); extending the built-in registry does not require another -CLI switch. Architecture switches are mutually exclusive. -Existing AMD64 syntax and flags retain their behavior. `--ast` and `--token` -expose only the AMD64 parser; byte dumps, tracing, statistics, input limits and -atomic output publication work for all four native assemblers. +Wave production code lives in `src/` within each module. Shared source and +numeric helpers are in `assembler/src/`; each ISA owns its parser, operands, +registers and encoding files under `assembler/ARCH/src/`. AMD64 additionally +separates `parser/` and `encoder/`. The complete AMD64 +[instruction reference](amd64/README.md) remains here. + +Rust data bindings and explicit comparison references live under +`bindings/rust/{assembler,amd64,aarch64,riscv64,loongarch64,asmobj}/`. +The complete [asmobj](asmobj/) Wave module maps assembly records to object +records; the separate Rust `object` module serializes them. The CLI composes +assemblers through `toolchain::Registry` in `src/builtins.rs`. + +Build with [Meson and Vex](../BUILDING.md). Direct Cargo checks require the +selected Wave archive directories described there. Missing modules report an +explicit error; Rust comparison algorithms require `rust-reference`. ## Initial 64-bit instruction subsets diff --git a/assembler/aarch64/build.rs b/assembler/aarch64/build.rs deleted file mode 100644 index 40043f7..0000000 --- a/assembler/aarch64/build.rs +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -const CFG: &str = "whale_wave_aarch64"; - -const ENV: &str = "WHALE_WAVE_AARCH64_DIR"; - -const LIBRARY: &str = "whale_wave_aarch64"; - -const METADATA: &str = "wave-aarch64.meta"; - -const ROOT_UP: usize = 2; - -const SOURCES: &[&str] = &[ - "assembler/model.wave", - "assembler/declarations.wave", - "assembler/fixed_model.wave", - "assembler/fixed_declarations.wave", - "assembler/aarch64/registers.wave", - "assembler/aarch64/parser.wave", - "assembler/aarch64/operands.wave", - "assembler/aarch64/encoding.wave", - "assembler/aarch64/encoder.wave", - "assembler/aarch64/entry.wave", -]; - -const ABI_SOURCES: &[&str] = &[ - "assembler/aarch64/src/wave.rs", - "assembler/aarch64/src/lib.rs", - "assembler/aarch64/src/encoder.rs", - "assembler/aarch64/src/parser.rs", -]; -include!("../build_support.rs"); diff --git a/assembler/aarch64/meson.build b/assembler/aarch64/meson.build index 8011949..ce53e83 100644 --- a/assembler/aarch64/meson.build +++ b/assembler/aarch64/meson.build @@ -1,50 +1,26 @@ # SPDX-License-Identifier: MPL-2.0 wave_aarch64_dependencies = [] wave_aarch64_directory = get_option('wave-aarch64-dir') -if wave_aarch64_directory == '' and wave_source != '' +if wave_aarch64_directory == '' and not get_option('rust-reference') wave_aarch64_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_wave_aarch64.lib' : 'libwhale_wave_aarch64.a' - arguments = ['--module', 'aarch64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif wave_aarch64_module = custom_target('wave-aarch64', - output: [archive_name, 'wave-aarch64.meta', 'provenance.json'], - command: [python, files('../../tools/build_wave_assembler.py'), arguments], - depend_files: files( - '../model.wave', - '../declarations.wave', - '../fixed_model.wave', - '../fixed_declarations.wave', - 'registers.wave', - 'parser.wave', - 'operands.wave', - 'encoding.wave', - 'encoder.wave', - 'entry.wave', - 'src/wave.rs', - 'src/lib.rs', - 'src/encoder.rs', - 'src/parser.rs', - '../../tools/build_wave_assembler.py', - '../../tools/wave_bootstrap.py', - '../build_support.rs', - ), - depends: wave_bootstrap, console: true) + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../../tools/vex_module.py'), '--module', 'aarch64', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/aarch64', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../../tools/vex_module.py', '../../tools/wave_modules.py'), + build_always_stale: true, console: true) wave_aarch64_dependencies += [wave_aarch64_module] elif wave_aarch64_directory != '' if not fs.is_absolute(wave_aarch64_directory) error('-Dwave-aarch64-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_wave_aarch64.lib' : 'libwhale_wave_aarch64.a' - foreach artifact : [archive_name, 'wave-aarch64.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(wave_aarch64_directory / artifact) error('Missing Wave aarch64 artifact: ' + (wave_aarch64_directory / artifact)) endif diff --git a/assembler/aarch64/parser.wave b/assembler/aarch64/parser.wave deleted file mode 100644 index ffcea54..0000000 --- a/assembler/aarch64/parser.wave +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Typed register parsing and diagnostic selection stay in the A64 module. -fun a64_fail(result: ptr, code: u64) -> bool { - var empty: FixedText; - empty.data = null; - empty.count = 0; - return asm_fixed_fail(result, code, empty, 0); -} - -fun a64_register(text: FixedText, output: ptr, result: ptr) -> bool { - if (!asm_fixed_charge(result, text.count)) { - return false; - } - var trimmed: FixedText = asm_fixed_trim(text); - if (!a64_register_bytes(trimmed.data, trimmed.count, output)) { - asm_fixed_fail(result, 1000, trimmed, 0); - result.display = 1; - return false; - } - return true; -} - -fun a64_same(left: ptr, right: ptr, result: ptr) -> bool { - if (left.width != right.width) { - return a64_fail(result, 1001); // Register widths must match. - } - return true; -} - -fun a64_no_sp(register: ptr, result: ptr) -> bool { - if (register.sp != 0) { - return a64_fail(result, 1002); // SP is not valid in this operand. - } - return true; -} - -fun a64_mnemonic(instruction: ptr, key: u64, length: u64) -> bool { - return asm_fixed_word(instruction.mnemonic, key, length, instruction.fold); -} diff --git a/assembler/aarch64/encoder.wave b/assembler/aarch64/src/encoder.wave similarity index 87% rename from assembler/aarch64/encoder.wave rename to assembler/aarch64/src/encoder.wave index 59ffc3e..03bc876 100644 --- a/assembler/aarch64/encoder.wave +++ b/assembler/aarch64/src/encoder.wave @@ -1,4 +1,49 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_aarch64::encoding")::{ + a64_address_word, + a64_arithmetic, + a64_compare_word, + a64_conditional_word, + a64_direct_word, + a64_logical, + a64_memory_encoding, + a64_mov_immediate, + a64_shift_encoding, + a64_wide_word, +}; +import("whale_wave_aarch64::operands")::{A64Shift, a64_shift}; +import("whale_wave_aarch64::parser")::{ + a64_fail, + a64_mnemonic, + a64_no_sp, + a64_register, + a64_same, +}; +import("whale_wave_aarch64::registers")::{A64Register, a64_sf}; +import("whale_wave_assembler::fixed::model")::{ + FixedContext, + FixedInstruction, + FixedResult, + FixedText, +}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_count") fun asm_fixed_count(instruction: ptr, count: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_displacement") fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, + output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_pc_relative") fun asm_fixed_pc_relative(context: ptr, text: FixedText, + code: u64, output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_try_integer") fun asm_fixed_try_integer(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_unsigned") fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_word") fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + // A64 instruction selection; all operand decisions and bit encodings are native. fun a64_condition(instruction: ptr, output: ptr) -> bool { var name: FixedText = instruction.mnemonic; @@ -166,7 +211,7 @@ fun a64_opcode(instruction: ptr) -> u64 { return 18446744073709551615; } -fun a64_encode(instruction: ptr, context: ptr, +pub fun a64_encode(instruction: ptr, context: ptr, result: ptr) -> bool { if (!asm_fixed_charge(result, instruction.mnemonic.count + 1)) { return false; @@ -381,7 +426,7 @@ fun a64_encode(instruction: ptr, context: ptr, return false; } -export(c) fun whale_aarch64_encode(instruction: ptr, +pub export(c) fun whale_aarch64_encode(instruction: ptr, context: ptr, result: ptr) -> i32 { if (result == null) { return 2; diff --git a/assembler/aarch64/encoding.wave b/assembler/aarch64/src/encoding.wave similarity index 83% rename from assembler/aarch64/encoding.wave rename to assembler/aarch64/src/encoding.wave index 1d09970..1076d06 100644 --- a/assembler/aarch64/encoding.wave +++ b/assembler/aarch64/src/encoding.wave @@ -1,17 +1,32 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_aarch64::operands")::{A64Memory, A64Shift, a64_memory, a64_shift}; +import("whale_wave_aarch64::parser")::{a64_fail, a64_no_sp, a64_register, a64_same}; +import("whale_wave_aarch64::registers")::{A64Register, a64_sf}; +import("whale_wave_assembler::fixed::model")::{FixedInstruction, FixedResult, FixedText}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_fixed_count") fun asm_fixed_count(instruction: ptr, count: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_try_integer") fun asm_fixed_try_integer(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_unsigned") fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_number_fits_signed") fun asm_number_fits_signed(value: ptr, bits: u64) -> bool; +extern(c, "asm_number_fits_unsigned") fun asm_number_fits_unsigned(value: ptr, bits: u64) -> bool; + // Bit-field placement for validated A64 operands. -fun a64_direct_word(link: bool, immediate: u64) -> u64 { +pub fun a64_direct_word(link: bool, immediate: u64) -> u64 { if (link) { return 2483027968 | immediate; // BL } return 335544320 | immediate; // B } -fun a64_conditional_word(condition: u64, immediate: u64) -> u64 { +pub fun a64_conditional_word(condition: u64, immediate: u64) -> u64 { return 1409286144 | (immediate << 5) | condition; // B.cond } -fun a64_compare_word(nonzero: bool, wide: bool, register: u64, immediate: u64) -> u64 { +pub fun a64_compare_word(nonzero: bool, wide: bool, register: u64, immediate: u64) -> u64 { var word: u64 = 872415232 | (immediate << 5) | register; // CBZ if (nonzero) { word = word | 16777216; @@ -22,7 +37,7 @@ fun a64_compare_word(nonzero: bool, wide: bool, register: u64, immediate: u64) - return word; } -fun a64_address_word(register: u64, immediate: u64) -> u64 { +pub fun a64_address_word(register: u64, immediate: u64) -> u64 { return 268435456 | ((immediate & 3) << 29) | ((immediate >> 2) << 5) | register; // ADR } @@ -36,12 +51,12 @@ fun a64_wide_base(operation: u64) -> u64 { return 1384120320; // MOVZ } -fun a64_wide_word(register: ptr, operation: u64, lane: u64, immediate: u64) -> u64 { +pub fun a64_wide_word(register: ptr, operation: u64, lane: u64, immediate: u64) -> u64 { return a64_wide_base(operation) | a64_sf(register) | (lane << 21) | (immediate << 5) | register.index; } -fun a64_mov_immediate(register: ptr, value: ptr, +pub fun a64_mov_immediate(register: ptr, value: ptr, result: ptr) -> bool { if (!asm_number_fits_signed(value, register.width) && !asm_number_fits_unsigned(value, register.width)) { @@ -78,7 +93,7 @@ fun a64_mov_immediate(register: ptr, value: ptr, return a64_fail(result, 1017); // Multi-instruction constants require MOVZ/MOVK. } -fun a64_arithmetic(instruction: ptr, compare: bool, sub: bool, +pub fun a64_arithmetic(instruction: ptr, compare: bool, sub: bool, flags: bool, result: ptr) -> bool { var rd: A64Register; var rn: A64Register; @@ -169,7 +184,7 @@ fun a64_arithmetic(instruction: ptr, compare: bool, sub: bool, return true; } -fun a64_logical(instruction: ptr, operation: u64, +pub fun a64_logical(instruction: ptr, operation: u64, result: ptr) -> bool { if (instruction.count < 3 || instruction.count > 4) { return a64_fail(result, 1012); @@ -196,7 +211,7 @@ fun a64_logical(instruction: ptr, operation: u64, return true; } -fun a64_shift_encoding(instruction: ptr, operation: u64, +pub fun a64_shift_encoding(instruction: ptr, operation: u64, result: ptr) -> bool { if (!asm_fixed_count(instruction, 3, result)) { return false; @@ -235,7 +250,7 @@ fun a64_shift_encoding(instruction: ptr, operation: u64, return true; } -fun a64_memory_encoding(instruction: ptr, load: bool, +pub fun a64_memory_encoding(instruction: ptr, load: bool, size_kind: u64, unscaled: bool, sign_extend: bool, result: ptr) -> bool { if (!asm_fixed_count(instruction, 2, result)) { return false; diff --git a/assembler/aarch64/entry.wave b/assembler/aarch64/src/entry.wave similarity index 63% rename from assembler/aarch64/entry.wave rename to assembler/aarch64/src/entry.wave index c5d0de3..8ff2b15 100644 --- a/assembler/aarch64/entry.wave +++ b/assembler/aarch64/src/entry.wave @@ -1,6 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_aarch64::encoder")::{a64_encode}; +import("whale_wave_assembler::fixed::model")::{ + FixedInput, + FixedInstruction, + FixedResult, + FixedState, +}; + +extern(c, "asm_fixed_commit") fun asm_fixed_commit(state: ptr, word: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_next") fun asm_fixed_next(state: ptr, instruction: ptr, + result: ptr) -> i32; +extern(c, "asm_fixed_prepare") fun asm_fixed_prepare(packet: ptr, state: ptr, + result: ptr) -> bool; + // Source preparation, instruction selection and publication stay in native code. -export(c) fun whale_aarch64_assemble(packet: ptr, result: ptr) -> i32 { +pub export(c) fun whale_aarch64_assemble(packet: ptr, result: ptr) -> i32 { if (result == null) { return 2; } @@ -43,6 +58,6 @@ export(c) fun whale_aarch64_assemble(packet: ptr, result: ptr u64 { +pub export(c) fun whale_aarch64_module_identity() -> u64 { return 6289348675458121985; } diff --git a/assembler/aarch64/src/lib.wave b/assembler/aarch64/src/lib.wave new file mode 100644 index 0000000..4013c62 --- /dev/null +++ b/assembler/aarch64/src/lib.wave @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit role modules; Vex compiles this package without source concatenation. +import("./encoder.wave" as encoder); +import("./encoding.wave" as encoding); +import("./entry.wave" as entry); +import("./operands.wave" as operands); +import("./parser.wave" as parser); +import("./registers.wave" as registers); diff --git a/assembler/aarch64/operands.wave b/assembler/aarch64/src/operands.wave similarity index 70% rename from assembler/aarch64/operands.wave rename to assembler/aarch64/src/operands.wave index 3c1f7ed..e1e7d30 100644 --- a/assembler/aarch64/operands.wave +++ b/assembler/aarch64/src/operands.wave @@ -1,16 +1,32 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_aarch64::parser")::{a64_fail, a64_register}; +import("whale_wave_aarch64::registers")::{A64Register}; +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_integer") fun asm_fixed_integer(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_operands") fun asm_fixed_operands(text: FixedText, output: ptr, capacity: u64, + count: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_space") fun asm_fixed_space(text: FixedText, at: u64) -> u64; +extern(c, "asm_fixed_trim") fun asm_fixed_trim(text: FixedText) -> FixedText; +extern(c, "asm_fixed_unsigned") fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_word") fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; + // Shift modifiers and base-plus-offset addresses are parsed without allocation. -struct A64Shift { +pub struct A64Shift { kind: u64; amount: u64; } -struct A64Memory { +pub struct A64Memory { base: A64Register; offset: AsmWide; } -fun a64_shift(text: FixedText, width: u64, output: ptr, +pub fun a64_shift(text: FixedText, width: u64, output: ptr, result: ptr) -> bool { if (!asm_fixed_charge(result, text.count)) { return false; @@ -70,7 +86,7 @@ fun a64_shift(text: FixedText, width: u64, output: ptr, return asm_fixed_unsigned(words[1], bits, &output.amount, result); } -fun a64_memory(text: FixedText, output: ptr, result: ptr) -> bool { +pub fun a64_memory(text: FixedText, output: ptr, result: ptr) -> bool { if (text.count < 2 || text.data[0] != 91 || text.data[text.count - 1] != 93) { return a64_fail(result, 1005); // Writeback and non-bracketed memory are unsupported. } diff --git a/assembler/aarch64/src/parser.wave b/assembler/aarch64/src/parser.wave new file mode 100644 index 0000000..d24c142 --- /dev/null +++ b/assembler/aarch64/src/parser.wave @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MPL-2.0 +import("whale_wave_aarch64::registers")::{A64Register, a64_register_bytes}; +import("whale_wave_assembler::fixed::model")::{FixedInstruction, FixedResult, FixedText}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_trim") fun asm_fixed_trim(text: FixedText) -> FixedText; +extern(c, "asm_fixed_word") fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; + +// Typed register parsing and diagnostic selection stay in the A64 module. +pub fun a64_fail(result: ptr, code: u64) -> bool { + var empty: FixedText; + empty.data = null; + empty.count = 0; + return asm_fixed_fail(result, code, empty, 0); +} + +pub fun a64_register(text: FixedText, output: ptr, result: ptr) -> bool { + if (!asm_fixed_charge(result, text.count)) { + return false; + } + var trimmed: FixedText = asm_fixed_trim(text); + if (!a64_register_bytes(trimmed.data, trimmed.count, output)) { + asm_fixed_fail(result, 1000, trimmed, 0); + result.display = 1; + return false; + } + return true; +} + +pub fun a64_same(left: ptr, right: ptr, result: ptr) -> bool { + if (left.width != right.width) { + return a64_fail(result, 1001); // Register widths must match. + } + return true; +} + +pub fun a64_no_sp(register: ptr, result: ptr) -> bool { + if (register.sp != 0) { + return a64_fail(result, 1002); // SP is not valid in this operand. + } + return true; +} + +pub fun a64_mnemonic(instruction: ptr, key: u64, length: u64) -> bool { + return asm_fixed_word(instruction.mnemonic, key, length, instruction.fold); +} diff --git a/assembler/aarch64/registers.wave b/assembler/aarch64/src/registers.wave similarity index 93% rename from assembler/aarch64/registers.wave rename to assembler/aarch64/src/registers.wave index ecddec2..f340ee8 100644 --- a/assembler/aarch64/registers.wave +++ b/assembler/aarch64/src/registers.wave @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 // Register 31 retains its distinct stack-pointer and zero-register roles. -struct A64Register { +pub struct A64Register { index: u64; width: u64; sp: u64; @@ -32,7 +32,7 @@ fun a64_keyword(bytes: ptr, count: u64, key: u64, length: u64, fold: bool) - return true; } -fun a64_register_bytes(bytes: ptr, count: u64, output: ptr) -> bool { +pub fun a64_register_bytes(bytes: ptr, count: u64, output: ptr) -> bool { output.index = 0; output.width = 64; output.sp = 0; @@ -95,7 +95,7 @@ fun a64_register_bytes(bytes: ptr, count: u64, output: ptr) -> return true; } -fun a64_sf(register: ptr) -> u64 { +pub fun a64_sf(register: ptr) -> u64 { if (register.width == 64) { return 2147483648; } diff --git a/assembler/aarch64/vex.ws b/assembler/aarch64/vex.ws new file mode 100644 index 0000000..f485b4f --- /dev/null +++ b/assembler/aarch64/vex.ws @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_wave_aarch64", + version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + dependencies = [{ name = "whale_wave_assembler", path = ".." }], + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/assembler/amd64/build.rs b/assembler/amd64/build.rs deleted file mode 100644 index 5a9abc8..0000000 --- a/assembler/amd64/build.rs +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -const CFG: &str = "whale_wave_amd64"; - -const ENV: &str = "WHALE_WAVE_AMD64_DIR"; - -const LIBRARY: &str = "whale_wave_amd64"; - -const METADATA: &str = "wave-amd64.meta"; - -const ROOT_UP: usize = 2; - -const SOURCES: &[&str] = &[ - "assembler/model.wave", - "assembler/declarations.wave", - "assembler/ast_model.wave", - "assembler/amd64/parser_model.wave", - "assembler/amd64/registers.wave", - "assembler/amd64/expressions.wave", - "assembler/amd64/operands.wave", - "assembler/amd64/directives.wave", - "assembler/amd64/parser.wave", - "assembler/amd64/encoder_model.wave", - "assembler/amd64/namespace.wave", - "assembler/amd64/layout.wave", - "assembler/amd64/address.wave", - "assembler/amd64/emit.wave", - "assembler/amd64/integer.wave", - "assembler/amd64/sse.wave", - "assembler/amd64/branch.wave", - "assembler/amd64/directives_encode.wave", - "assembler/amd64/encoder.wave", -]; - -const ABI_SOURCES: &[&str] = &[ - "assembler/amd64/src/ast_model.rs", - "assembler/amd64/src/parser_wave.rs", - "assembler/amd64/src/encoder_wave.rs", - "assembler/amd64/src/encoder_namespace_errors.rs", - "assembler/amd64/src/tables.rs", - "assembler/amd64/src/encoder.rs", - "assembler/amd64/src/encoding/address.rs", - "assembler/amd64/src/encoding/modrm.rs", - "assembler/amd64/src/encoding/rex.rs", - "assembler/amd64/src/encoding/sib.rs", - "assembler/amd64/src/lib.rs", -]; -include!("../build_support.rs"); diff --git a/assembler/amd64/meson.build b/assembler/amd64/meson.build index e054f9f..e35af66 100644 --- a/assembler/amd64/meson.build +++ b/assembler/amd64/meson.build @@ -1,66 +1,26 @@ # SPDX-License-Identifier: MPL-2.0 wave_amd64_dependencies = [] wave_amd64_directory = get_option('wave-amd64-dir') -if wave_amd64_directory == '' and wave_source != '' +if wave_amd64_directory == '' and not get_option('rust-reference') wave_amd64_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_wave_amd64.lib' : 'libwhale_wave_amd64.a' - arguments = ['--module', 'amd64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif wave_amd64_module = custom_target('wave-amd64', - output: [archive_name, 'wave-amd64.meta', 'provenance.json'], - command: [python, files('../../tools/build_wave_assembler.py'), arguments], - depend_files: files( - 'src/lib.rs', - '../model.wave', - '../declarations.wave', - '../ast_model.wave', - 'parser_model.wave', - 'registers.wave', - 'expressions.wave', - 'operands.wave', - 'directives.wave', - 'parser.wave', - 'encoder_model.wave', - 'namespace.wave', - 'layout.wave', - 'address.wave', - 'emit.wave', - 'integer.wave', - 'sse.wave', - 'branch.wave', - 'directives_encode.wave', - 'encoder.wave', - 'src/ast_model.rs', - 'src/parser_wave.rs', - 'src/encoder_wave.rs', - 'src/encoder_namespace_errors.rs', - 'src/tables.rs', - 'src/encoder.rs', - 'src/encoding/address.rs', - 'src/encoding/modrm.rs', - 'src/encoding/rex.rs', - 'src/encoding/sib.rs', - '../../tools/build_wave_assembler.py', - '../../tools/wave_bootstrap.py', - '../build_support.rs', - ), - depends: wave_bootstrap, console: true) + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../../tools/vex_module.py'), '--module', 'amd64', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/amd64', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../../tools/vex_module.py', '../../tools/wave_modules.py'), + build_always_stale: true, console: true) wave_amd64_dependencies += [wave_amd64_module] elif wave_amd64_directory != '' if not fs.is_absolute(wave_amd64_directory) error('-Dwave-amd64-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_wave_amd64.lib' : 'libwhale_wave_amd64.a' - foreach artifact : [archive_name, 'wave-amd64.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(wave_amd64_directory / artifact) error('Missing Wave amd64 artifact: ' + (wave_amd64_directory / artifact)) endif diff --git a/assembler/amd64/address.wave b/assembler/amd64/src/encoder/address.wave similarity index 93% rename from assembler/amd64/address.wave rename to assembler/amd64/src/encoder/address.wave index e97e835..c59f34f 100644 --- a/assembler/amd64/address.wave +++ b/assembler/amd64/src/encoder/address.wave @@ -1,6 +1,15 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::model")::{ + AmdAddress, + AmdEncodeInput, + AmdEncodeResult, + AmdOperand, + amd_fail, + amd_register, +}; + // AMD64 ModRM/SIB addressing, shared with the public low-level address API. -fun amd_address(p: ptr, mem: ptr, mode: u64, +pub fun amd_address(p: ptr, mem: ptr, mode: u64, symbols: bool, output: ptr, result: ptr) -> bool { output.mode = 0; output.rm = 0; diff --git a/assembler/amd64/branch.wave b/assembler/amd64/src/encoder/branch.wave similarity index 90% rename from assembler/amd64/branch.wave rename to assembler/amd64/src/encoder/branch.wave index ee9006a..99439cc 100644 --- a/assembler/amd64/branch.wave +++ b/assembler/amd64/src/encoder/branch.wave @@ -1,6 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::emit")::{amd_emit, amd_relocation}; +import("whale_wave_amd64::encoder::model")::{AmdOperand, AmdWriter, amd_fail}; + // Layout-aware direct transfers; local LOOP is resolved after convergence. -fun amd_relative(target: u64, source: u64, length: u64, width: u64, +pub fun amd_relative(target: u64, source: u64, length: u64, width: u64, displacement: ptr) -> bool { if (length > 18446744073709551615 - source) { return false; @@ -26,7 +29,7 @@ fun amd_relative(target: u64, source: u64, length: u64, width: u64, return true; } -fun amd_direct_branch(w: ptr, operation: u64, operand: ptr, +pub fun amd_direct_branch(w: ptr, operation: u64, operand: ptr, node_index: u64, iteration: u64) -> bool { if (operand.kind != 2 && operand.kind != 3) { return amd_fail(w.result, 40); diff --git a/assembler/amd64/directives_encode.wave b/assembler/amd64/src/encoder/directives_encode.wave similarity index 90% rename from assembler/amd64/directives_encode.wave rename to assembler/amd64/src/encoder/directives_encode.wave index ba5590c..3b45076 100644 --- a/assembler/amd64/directives_encode.wave +++ b/assembler/amd64/src/encoder/directives_encode.wave @@ -1,4 +1,22 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::emit")::{amd_emit, amd_fill, amd_relocation}; +import("whale_wave_amd64::encoder::model")::{ + AmdWriter, + amd_charge, + amd_fail, + amd_fits, + amd_word, +}; +import("whale_wave_amd64::encoder::namespace")::{amd_evaluated_expression, amd_namespace_fail}; +import("whale_wave_assembler::ast")::{AsmDirectiveValue, AsmExpr, AsmItem}; +import("whale_wave_assembler::model")::{AsmOutputGrowth}; + +extern(c, "asm_output_align") fun asm_output_align(materialized: u64, section: u64, alignment: u64, + limit: u64, logical: u64, output: ptr) -> i32; +extern(c, "asm_output_grow") fun asm_output_grow(materialized: u64, section: u64, extra: u64, + limit: u64, logical: u64, output: ptr) -> i32; +extern(c, "asm_power_two") fun asm_power_two(value: u64) -> bool; + // Sparse storage and checked data directives share the final section writer. fun amd_directive_number(w: ptr, node: u64, value: ptr, output: ptr) -> bool { @@ -35,7 +53,7 @@ fun amd_reservation(w: ptr, node: u64, unit: u64, return true; } -fun amd_directive(w: ptr, node: u64) -> bool { +pub fun amd_directive(w: ptr, node: u64) -> bool { var alignment: AsmExpr; var growth: AsmOutputGrowth; var padded: u64; diff --git a/assembler/amd64/emit.wave b/assembler/amd64/src/encoder/emit.wave similarity index 80% rename from assembler/amd64/emit.wave rename to assembler/amd64/src/encoder/emit.wave index 9fe69ad..8c5c05d 100644 --- a/assembler/amd64/emit.wave +++ b/assembler/amd64/src/encoder/emit.wave @@ -1,6 +1,19 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::address")::{amd_address}; +import("whale_wave_amd64::encoder::model")::{ + AmdAddress, + AmdOperand, + AmdWriter, + amd_charge, + amd_fail, +}; +import("whale_wave_assembler::model")::{AsmOutputGrowth}; + +extern(c, "asm_output_grow") fun asm_output_grow(materialized: u64, section: u64, extra: u64, + limit: u64, logical: u64, output: ptr) -> i32; + // Bounded byte and relocation emission shared by every instruction family. -fun amd_emit(w: ptr, value: u64, width: u64) -> bool { +pub fun amd_emit(w: ptr, value: u64, width: u64) -> bool { var growth: AsmOutputGrowth; var status: i32 = asm_output_grow(w.materialized, w.count, width, w.p.max_output, 0, &growth); if (status != 0) { @@ -26,7 +39,7 @@ fun amd_emit(w: ptr, value: u64, width: u64) -> bool { return true; } -fun amd_fill(w: ptr, count: u64, value: u64) -> bool { +pub fun amd_fill(w: ptr, count: u64, value: u64) -> bool { var growth: AsmOutputGrowth; var status: i32 = asm_output_grow(w.materialized, w.count, count, w.p.max_output, 0, &growth); if (status != 0) { @@ -55,7 +68,7 @@ fun amd_fill(w: ptr, count: u64, value: u64) -> bool { return true; } -fun amd_relocation(w: ptr, symbol: u64, kind: u64, addend: u64, +pub fun amd_relocation(w: ptr, symbol: u64, kind: u64, addend: u64, offset: u64) -> bool { if (w.result.relocation_count >= w.p.relocation_capacity) { return amd_fail(w.result, 3); @@ -71,14 +84,14 @@ fun amd_relocation(w: ptr, symbol: u64, kind: u64, addend: u64, return true; } -fun amd_prefix(w: ptr, width: u64) -> bool { +pub fun amd_prefix(w: ptr, width: u64) -> bool { if (width == 16) { return amd_emit(w, 102, 1); } return true; } -fun amd_rex(w: ptr, width: u64, r: u64, x: u64, b: u64, +pub fun amd_rex(w: ptr, width: u64, r: u64, x: u64, b: u64, flags: u64) -> bool { var bits: u64 = (r << 2) | (x << 1) | b; if (width == 64) { @@ -93,11 +106,11 @@ fun amd_rex(w: ptr, width: u64, r: u64, x: u64, b: u64, return true; } -fun amd_modrm(w: ptr, mode: u64, reg: u64, rm: u64) -> bool { +pub fun amd_modrm(w: ptr, mode: u64, reg: u64, rm: u64) -> bool { return amd_emit(w, ((mode & 3) << 6) | ((reg & 7) << 3) | (rm & 7), 1); } -fun amd_register_pair(w: ptr, opcode: u64, dst: ptr, +pub fun amd_register_pair(w: ptr, opcode: u64, dst: ptr, src: ptr) -> bool { if (dst.kind != 0 || src.kind != 0 || dst.width == 128 || src.width == 128) { return amd_fail(w.result, 5); @@ -111,7 +124,7 @@ fun amd_register_pair(w: ptr, opcode: u64, dst: ptr, && amd_emit(w, opcode, 1) && amd_modrm(w, 3, src.code, dst.code); } -fun amd_memory(w: ptr, opcode: u64, two: u64, reg: ptr, +pub fun amd_memory(w: ptr, opcode: u64, two: u64, reg: ptr, mem: ptr, width: u64, trailing: u64) -> bool { var address: AmdAddress; if (!amd_address(w.p, mem, 64, true, &address, w.result)) { @@ -151,14 +164,14 @@ fun amd_memory(w: ptr, opcode: u64, two: u64, reg: ptr, return amd_emit(w, address.displacement, address.width); } -fun amd_mem_width(w: ptr, mem: ptr, width: u64) -> bool { +pub fun amd_mem_width(w: ptr, mem: ptr, width: u64) -> bool { if (mem.memwidth != 18446744073709551615 && mem.memwidth != width) { return amd_fail(w.result, 8); } return true; } -fun amd_reg_mem(w: ptr, opcode: u64, two: u64, reg: ptr, +pub fun amd_reg_mem(w: ptr, opcode: u64, two: u64, reg: ptr, mem: ptr) -> bool { if (reg.kind != 0 || reg.width == 128 || mem.kind != 4) { return amd_fail(w.result, 5); @@ -167,7 +180,7 @@ fun amd_reg_mem(w: ptr, opcode: u64, two: u64, reg: ptr, && amd_memory(w, opcode, two, reg, mem, reg.width, 0); } -export(c) fun whale_amd64_bits(op: u64, a: u64, b: u64, c: u64, d: u64) -> u64 { +pub export(c) fun whale_amd64_bits(op: u64, a: u64, b: u64, c: u64, d: u64) -> u64 { if (op == 0) { return ((a & 3) << 6) | ((b & 7) << 3) | (c & 7); } diff --git a/assembler/amd64/src/encoder/encoder.wave b/assembler/amd64/src/encoder/encoder.wave new file mode 100644 index 0000000..5745794 --- /dev/null +++ b/assembler/amd64/src/encoder/encoder.wave @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::address")::{amd_address}; +import("whale_wave_amd64::encoder::model")::{ + AmdAddress, + AmdEncodeInput, + AmdEncodeResult, + AmdOperand, + AmdWriter, + amd_charge, + amd_fail, + amd_mnemonic, +}; +import("whale_wave_amd64::encoder::layout")::{amd_layout}; +import("whale_wave_assembler::ast")::{AsmItem, AsmName, AsmOperand}; + +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + +// Typed AST adaptation and complete integer/scalar-SSE instruction dispatch. + + + + +fun amd_result_reset(result: ptr) { + result.status = 0; + result.error = 0; + result.node = 0; + result.previous = 18446744073709551615; + result.argument = 18446744073709551615; + result.section_count = 0; + result.symbol_count = 0; + result.output_symbols = 0; + result.relocation_count = 0; + result.bytes = 0; + result.iterations = 0; + result.work = 0; +} + +fun amd_input_valid(p: ptr, result: ptr) -> bool { + if (p == null || p.item_count == 18446744073709551615 + || p.name_count == 18446744073709551615 + || p.section_capacity < p.item_count + 1 || p.symbol_capacity < p.name_count + 1 + || p.table_capacity < 2 || p.symbol_capacity > p.table_capacity / 2 + || (p.table_capacity & (p.table_capacity - 1)) != 0 + || !asm_span_valid(p.names as ptr, p.name_count, 16) + || !asm_span_valid(p.items as ptr, p.item_count, 80) + || !asm_span_valid(p.operands as ptr, p.operand_count, 88) + || !asm_span_valid(p.values as ptr, p.value_count, 56) + || !asm_span_valid(p.sections as ptr, p.section_capacity, 48) + || !asm_span_valid(p.symbols as ptr, p.symbol_capacity, 184) + || !asm_span_valid(p.table as ptr, p.table_capacity, 8) + || !asm_span_valid(p.nodes as ptr, p.item_count, 64) + || !asm_span_valid(p.queue as ptr, p.symbol_capacity, 8) + || !asm_span_valid(p.relocations as ptr, p.relocation_capacity, 48) + || !asm_span_valid(p.bytes, p.byte_capacity, 1)) { + return amd_fail(result, 3); + } + var index: u64 = 0; + var item: AsmItem; + while (index < p.name_count) { + if (!amd_charge(p, result)) { + return false; + } + if (!asm_span_valid(p.names[index].bytes, p.names[index].count, 1)) { + return amd_fail(result, 3); + } + index += 1; + } + index = 0; + while (index < p.item_count) { + if (!amd_charge(p, result)) { + return false; + } + item = p.items[index]; + if (item.kind > 8 || item.name >= p.name_count) { + return amd_fail(result, 3); + } + if (item.kind == 0 && (item.first > p.operand_count + || item.count > p.operand_count - item.first)) { + return amd_fail(result, 3); + } + if (item.kind == 2 && (item.first > p.value_count || item.count > p.value_count - item.first)) { + return amd_fail(result, 3); + } + index += 1; + } + return true; +} + +pub export(c) fun whale_amd64_encode(p: ptr, emission: u64, + result: ptr) -> i32 { + if (result == null) { + return 1; + } + if (emission == 0) { + amd_result_reset(result); + } + if (emission > 1 || !amd_input_valid(p, result)) { + amd_fail(result, 3); + return 1; + } + var writer: AmdWriter; + writer.p = p; + writer.result = result; + writer.section = 0; + writer.count = 0; + writer.materialized = 0; + writer.measuring = 1 - emission; + if (!amd_layout(&writer, emission)) { + if (result.status == 0) { + amd_fail(result, 3); + } + return result.status as i32; + } + return 0; +} + +pub export(c) fun whale_amd64_address(names: ptr, name_count: u64, + raw: ptr, mode: u64, output: ptr, result: ptr) -> i32 { + if (raw == null || output == null || result == null + || !asm_span_valid(names as ptr, name_count, 16)) { + return 1; + } + amd_result_reset(result); + var p: AmdEncodeInput; + p.names = names; + p.name_count = name_count; + var mem: AmdOperand; + mem.mode = raw.mode; + mem.memwidth = raw.width; + mem.base = raw.base; + mem.index = raw.index; + mem.scale = raw.scale; + mem.disp = raw.disp as i64; + mem.symbol = raw.symbol; + var at: u64 = 0; + while (at < name_count) { + if (!asm_span_valid(names[at].bytes, names[at].count, 1)) { + return 1; + } + at += 1; + } + if (!amd_address(&p, &mem, mode, false, output, result)) { + return result.status as i32; + } + return 0; +} + +pub export(c) fun whale_amd64_condition(name: ptr, output: ptr) -> i32 { + if (name == null || output == null || !asm_span_valid(name.bytes, name.count, 1)) { + return 2; + } + output[0] = 0; + var p: AmdEncodeInput; + p.names = name; + p.name_count = 1; + var operation: u64 = amd_mnemonic(&p, 0); + if (operation >= 64 && operation <= 79) { + output[0] = operation - 64; + return 0; + } + return 1; +} + +// Distinct compiled identity used by product composition checks. +pub export(c) fun whale_amd64_module_identity() -> u64 { + return 6289348675458125057; +} diff --git a/assembler/amd64/encoder.wave b/assembler/amd64/src/encoder/instruction.wave similarity index 61% rename from assembler/amd64/encoder.wave rename to assembler/amd64/src/encoder/instruction.wave index d4bac1b..8583504 100644 --- a/assembler/amd64/encoder.wave +++ b/assembler/amd64/src/encoder/instruction.wave @@ -1,5 +1,36 @@ // SPDX-License-Identifier: MPL-2.0 -// Typed AST adaptation and complete integer/scalar-SSE instruction dispatch. +import("whale_wave_amd64::encoder::branch")::{amd_direct_branch}; +import("whale_wave_amd64::encoder::emit")::{ + amd_emit, + amd_modrm, + amd_prefix, + amd_reg_mem, + amd_register_pair, + amd_rex, +}; +import("whale_wave_amd64::encoder::model")::{ + AmdEncodeInput, + AmdEncodeResult, + AmdOperand, + AmdWriter, + amd_fail, + amd_fits, + amd_mnemonic, + amd_register, + amd_signed64, +}; +import("whale_wave_amd64::encoder::integer")::{ + amd_binary, + amd_extension, + amd_group, + amd_imul, + amd_mov, + amd_shift, +}; +import("whale_wave_amd64::encoder::namespace")::{amd_expression}; +import("whale_wave_amd64::encoder::sse")::{amd_scalar_sse}; +import("whale_wave_assembler::ast")::{AsmExpr, AsmItem, AsmOperand}; + fun amd_operand(p: ptr, scope: u64, raw: ptr, output: ptr, result: ptr) -> bool { output.kind = raw.kind; @@ -67,7 +98,7 @@ fun amd_operand(p: ptr, scope: u64, raw: ptr, return true; } -fun amd_encode_instruction(w: ptr, node: u64, iteration: u64) -> bool { +pub fun amd_encode_instruction(w: ptr, node: u64, iteration: u64) -> bool { var item: AsmItem = w.p.items[node]; var operation: u64 = amd_mnemonic(w.p, item.name); if (operation == 255) { @@ -243,149 +274,3 @@ fun amd_encode_instruction(w: ptr, node: u64, iteration: u64) -> bool } return amd_fail(w.result, 44); } - -fun amd_result_reset(result: ptr) { - result.status = 0; - result.error = 0; - result.node = 0; - result.previous = 18446744073709551615; - result.argument = 18446744073709551615; - result.section_count = 0; - result.symbol_count = 0; - result.output_symbols = 0; - result.relocation_count = 0; - result.bytes = 0; - result.iterations = 0; - result.work = 0; -} - -fun amd_input_valid(p: ptr, result: ptr) -> bool { - if (p == null || p.item_count == 18446744073709551615 - || p.name_count == 18446744073709551615 - || p.section_capacity < p.item_count + 1 || p.symbol_capacity < p.name_count + 1 - || p.table_capacity < 2 || p.symbol_capacity > p.table_capacity / 2 - || (p.table_capacity & (p.table_capacity - 1)) != 0 - || !asm_span_valid(p.names as ptr, p.name_count, 16) - || !asm_span_valid(p.items as ptr, p.item_count, 80) - || !asm_span_valid(p.operands as ptr, p.operand_count, 88) - || !asm_span_valid(p.values as ptr, p.value_count, 56) - || !asm_span_valid(p.sections as ptr, p.section_capacity, 48) - || !asm_span_valid(p.symbols as ptr, p.symbol_capacity, 184) - || !asm_span_valid(p.table as ptr, p.table_capacity, 8) - || !asm_span_valid(p.nodes as ptr, p.item_count, 64) - || !asm_span_valid(p.queue as ptr, p.symbol_capacity, 8) - || !asm_span_valid(p.relocations as ptr, p.relocation_capacity, 48) - || !asm_span_valid(p.bytes, p.byte_capacity, 1)) { - return amd_fail(result, 3); - } - var index: u64 = 0; - var item: AsmItem; - while (index < p.name_count) { - if (!amd_charge(p, result)) { - return false; - } - if (!asm_span_valid(p.names[index].bytes, p.names[index].count, 1)) { - return amd_fail(result, 3); - } - index += 1; - } - index = 0; - while (index < p.item_count) { - if (!amd_charge(p, result)) { - return false; - } - item = p.items[index]; - if (item.kind > 8 || item.name >= p.name_count) { - return amd_fail(result, 3); - } - if (item.kind == 0 && (item.first > p.operand_count - || item.count > p.operand_count - item.first)) { - return amd_fail(result, 3); - } - if (item.kind == 2 && (item.first > p.value_count || item.count > p.value_count - item.first)) { - return amd_fail(result, 3); - } - index += 1; - } - return true; -} - -export(c) fun whale_amd64_encode(p: ptr, emission: u64, - result: ptr) -> i32 { - if (result == null) { - return 1; - } - if (emission == 0) { - amd_result_reset(result); - } - if (emission > 1 || !amd_input_valid(p, result)) { - amd_fail(result, 3); - return 1; - } - var writer: AmdWriter; - writer.p = p; - writer.result = result; - writer.section = 0; - writer.count = 0; - writer.materialized = 0; - writer.measuring = 1 - emission; - if (!amd_layout(&writer, emission)) { - if (result.status == 0) { - amd_fail(result, 3); - } - return result.status as i32; - } - return 0; -} - -export(c) fun whale_amd64_address(names: ptr, name_count: u64, - raw: ptr, mode: u64, output: ptr, result: ptr) -> i32 { - if (raw == null || output == null || result == null - || !asm_span_valid(names as ptr, name_count, 16)) { - return 1; - } - amd_result_reset(result); - var p: AmdEncodeInput; - p.names = names; - p.name_count = name_count; - var mem: AmdOperand; - mem.mode = raw.mode; - mem.memwidth = raw.width; - mem.base = raw.base; - mem.index = raw.index; - mem.scale = raw.scale; - mem.disp = raw.disp as i64; - mem.symbol = raw.symbol; - var at: u64 = 0; - while (at < name_count) { - if (!asm_span_valid(names[at].bytes, names[at].count, 1)) { - return 1; - } - at += 1; - } - if (!amd_address(&p, &mem, mode, false, output, result)) { - return result.status as i32; - } - return 0; -} - -export(c) fun whale_amd64_condition(name: ptr, output: ptr) -> i32 { - if (name == null || output == null || !asm_span_valid(name.bytes, name.count, 1)) { - return 2; - } - output[0] = 0; - var p: AmdEncodeInput; - p.names = name; - p.name_count = 1; - var operation: u64 = amd_mnemonic(&p, 0); - if (operation >= 64 && operation <= 79) { - output[0] = operation - 64; - return 0; - } - return 1; -} - -// Distinct compiled identity used by product composition checks. -export(c) fun whale_amd64_module_identity() -> u64 { - return 6289348675458125057; -} diff --git a/assembler/amd64/integer.wave b/assembler/amd64/src/encoder/integer.wave similarity index 92% rename from assembler/amd64/integer.wave rename to assembler/amd64/src/encoder/integer.wave index 5426b26..111f18d 100644 --- a/assembler/amd64/integer.wave +++ b/assembler/amd64/src/encoder/integer.wave @@ -1,4 +1,23 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::emit")::{ + amd_emit, + amd_mem_width, + amd_memory, + amd_modrm, + amd_prefix, + amd_reg_mem, + amd_register_pair, + amd_relocation, + amd_rex, +}; +import("whale_wave_amd64::encoder::model")::{ + AmdOperand, + AmdWriter, + amd_fail, + amd_fits, + amd_signed64, +}; + // Integer instruction forms. Register and memory policies are shared helpers. fun amd_memory_immediate(w: ptr, mem: ptr, imm: ptr, operation: u64) -> bool { @@ -40,7 +59,7 @@ fun amd_memory_immediate(w: ptr, mem: ptr, imm: ptr, a: ptr, b: ptr) -> bool { +pub fun amd_mov(w: ptr, a: ptr, b: ptr) -> bool { if (a.kind == 0 && a.width != 128) { if (b.kind == 1) { if (!amd_fits(b.low, b.high, a.width, false)) { @@ -101,7 +120,7 @@ fun amd_mov(w: ptr, a: ptr, b: ptr) -> bool { return amd_fail(w.result, 24); } -fun amd_binary(w: ptr, a: ptr, b: ptr, +pub fun amd_binary(w: ptr, a: ptr, b: ptr, opcode: u64, extension: u64) -> bool { if (a.kind == 0 && a.width != 128) { if (b.kind == 0) { @@ -157,7 +176,7 @@ fun amd_binary(w: ptr, a: ptr, b: ptr, return amd_fail(w.result, 26); } -fun amd_group(w: ptr, operand: ptr, width: u64, +pub fun amd_group(w: ptr, operand: ptr, width: u64, rex_width: u64, opcode: u64, two: u64, extension: u64) -> bool { if (!amd_prefix(w, width)) { return false; @@ -184,7 +203,7 @@ fun amd_group(w: ptr, operand: ptr, width: u64, return amd_fail(w.result, 28); } -fun amd_extension(w: ptr, operation: u64, a: ptr, +pub fun amd_extension(w: ptr, operation: u64, a: ptr, b: ptr) -> bool { if (a.kind != 0 || a.width == 128) { return amd_fail(w.result, 5); @@ -233,7 +252,7 @@ fun amd_extension(w: ptr, operation: u64, a: ptr, return amd_emit(w, opcode, 1) && amd_modrm(w, 3, a.code, b.code); } -fun amd_imul(w: ptr, a: ptr, b: ptr, +pub fun amd_imul(w: ptr, a: ptr, b: ptr, c: ptr, count: u64) -> bool { if (a.kind != 0 || a.width == 8 || a.width == 128) { return amd_fail(w.result, 32); @@ -273,7 +292,7 @@ fun amd_imul(w: ptr, a: ptr, b: ptr, && amd_emit(w, 15, 1) && amd_emit(w, 175, 1) && amd_modrm(w, 3, a.code, b.code); } -fun amd_shift(w: ptr, operation: u64, a: ptr, +pub fun amd_shift(w: ptr, operation: u64, a: ptr, b: ptr) -> bool { if (a.kind != 0 || a.width == 128) { return amd_fail(w.result, 5); diff --git a/assembler/amd64/layout.wave b/assembler/amd64/src/encoder/layout.wave similarity index 95% rename from assembler/amd64/layout.wave rename to assembler/amd64/src/encoder/layout.wave index 33a9bb6..682d6e9 100644 --- a/assembler/amd64/layout.wave +++ b/assembler/amd64/src/encoder/layout.wave @@ -1,4 +1,29 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::branch")::{amd_relative}; +import("whale_wave_amd64::encoder::directives_encode")::{amd_directive}; +import("whale_wave_amd64::encoder::model")::{ + AmdEncodeInput, + AmdEncodeResult, + AmdNode, + AmdRelocation, + AmdSection, + AmdSymbol, + AmdWriter, + amd_charge, + amd_fail, + amd_mnemonic, + amd_word, +}; +import("whale_wave_amd64::encoder::instruction")::{amd_encode_instruction}; +import("whale_wave_amd64::encoder::namespace")::{ + amd_constants, + amd_evaluated_expression, + amd_intern, + amd_name_compare, + amd_namespace_fail, +}; +import("whale_wave_assembler::ast")::{AsmExpr, AsmItem}; + // Layout reaches a checked fixed point before publishing grouped section bytes. fun amd_raw_name_equal(p: ptr, left: u64, right: u64, result: ptr) -> bool { @@ -344,7 +369,7 @@ fun amd_layout_pass(w: ptr, iteration: u64) -> bool { return amd_validate_symbols(w); } -fun amd_layout(w: ptr, emission: u64) -> bool { +pub fun amd_layout(w: ptr, emission: u64) -> bool { var expected: u64; var stable: bool; var index: u64; diff --git a/assembler/amd64/encoder_model.wave b/assembler/amd64/src/encoder/model.wave similarity index 94% rename from assembler/amd64/encoder_model.wave rename to assembler/amd64/src/encoder/model.wave index d172934..83fb8fe 100644 --- a/assembler/amd64/encoder_model.wave +++ b/assembler/amd64/src/encoder/model.wave @@ -1,6 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::parser::registers")::{Amd64Register, amd64_register}; +import("whale_wave_assembler::ast")::{AsmDirectiveValue, AsmItem, AsmName, AsmOperand}; + // Callback-free, caller-owned encoder transport. Missing indexes use u64::MAX. -struct AmdSection { +pub struct AmdSection { name: u64; kind: u64; align: u64; @@ -9,7 +12,7 @@ struct AmdSection { zero_fill: u64; } -struct AmdSymbol { +pub struct AmdSymbol { prefix: u64; name: u64; flags: u64; @@ -35,7 +38,7 @@ struct AmdSymbol { next: u64; } -struct AmdNode { +pub struct AmdNode { scope: u64; symbol: u64; section: u64; @@ -46,7 +49,7 @@ struct AmdNode { force_near: u64; } -struct AmdRelocation { +pub struct AmdRelocation { section: u64; offset: u64; symbol: u64; @@ -55,7 +58,7 @@ struct AmdRelocation { node: u64; } -struct AmdEncodeInput { +pub struct AmdEncodeInput { names: ptr; name_count: u64; items: ptr; @@ -81,7 +84,7 @@ struct AmdEncodeInput { max_work: u64; } -struct AmdEncodeResult { +pub struct AmdEncodeResult { status: u64; error: u64; node: u64; @@ -96,7 +99,7 @@ struct AmdEncodeResult { work: u64; } -struct AmdWriter { +pub struct AmdWriter { p: ptr; result: ptr; section: u64; @@ -105,7 +108,7 @@ struct AmdWriter { measuring: u64; } -struct AmdOperand { +pub struct AmdOperand { kind: u64; code: u64; width: u64; @@ -121,7 +124,7 @@ struct AmdOperand { symbol: u64; } -struct AmdAddress { +pub struct AmdAddress { mode: u64; rm: u64; sib: u64; @@ -131,13 +134,13 @@ struct AmdAddress { rex_x: u64; } -fun amd_fail(result: ptr, error: u64) -> bool { +pub fun amd_fail(result: ptr, error: u64) -> bool { result.status = 1; result.error = error; return false; } -fun amd_charge(p: ptr, result: ptr) -> bool { +pub fun amd_charge(p: ptr, result: ptr) -> bool { if (result.work >= p.max_work) { return amd_fail(result, 1); } @@ -145,7 +148,7 @@ fun amd_charge(p: ptr, result: ptr) -> bool { return true; } -fun amd_word(names: ptr, count: u64, name: u64, word: u64, length: u64) -> bool { +pub fun amd_word(names: ptr, count: u64, name: u64, word: u64, length: u64) -> bool { if (name >= count || names[name].count != length) { return false; } @@ -159,7 +162,7 @@ fun amd_word(names: ptr, count: u64, name: u64, word: u64, length: u64) return true; } -fun amd_fits(low: u64, high: u64, width: u64, signed_only: bool) -> bool { +pub fun amd_fits(low: u64, high: u64, width: u64, signed_only: bool) -> bool { if (width == 64) { if (high == 18446744073709551615) { return (low as i64) < 0; @@ -180,12 +183,12 @@ fun amd_fits(low: u64, high: u64, width: u64, signed_only: bool) -> bool { return high == 0 && low <= maximum; } -fun amd_signed64(low: u64, high: u64) -> bool { +pub fun amd_signed64(low: u64, high: u64) -> bool { return (high == 0 && low <= 9223372036854775807) || (high == 18446744073709551615 && low >= 9223372036854775808); } -fun amd_register(p: ptr, name: u64, output: ptr) -> bool { +pub fun amd_register(p: ptr, name: u64, output: ptr) -> bool { if (name >= p.name_count) { return false; } @@ -199,7 +202,7 @@ fun amd_register(p: ptr, name: u64, output: ptr) -> return true; } -fun amd_mnemonic(p: ptr, name: u64) -> u64 { +pub fun amd_mnemonic(p: ptr, name: u64) -> u64 { // mov if (amd_word(p.names, p.name_count, name, 7761773, 3)) { return 0; diff --git a/assembler/amd64/namespace.wave b/assembler/amd64/src/encoder/namespace.wave similarity index 93% rename from assembler/amd64/namespace.wave rename to assembler/amd64/src/encoder/namespace.wave index d950658..a6b6cb2 100644 --- a/assembler/amd64/namespace.wave +++ b/assembler/amd64/src/encoder/namespace.wave @@ -1,6 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::model")::{ + AmdEncodeInput, + AmdEncodeResult, + AmdNode, + AmdSymbol, + amd_charge, + amd_fail, + amd_signed64, +}; +import("whale_wave_assembler::ast")::{AsmExpr, AsmItem}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_number_add_checked") fun asm_number_add_checked(a: ptr, b: ptr, + output: ptr) -> bool; + // Canonical scoped names and nonrecursive constant dependency evaluation. -fun amd_namespace_fail(result: ptr, error: u64, +pub fun amd_namespace_fail(result: ptr, error: u64, argument: u64, previous: u64) -> bool { result.error = error; result.argument = argument; @@ -27,7 +42,7 @@ fun amd_name_octet(p: ptr, prefix: u64, name: u64, at: u64) -> u return p.names[name].bytes[at]; } -fun amd_name_compare(p: ptr, left: u64, right: u64, +pub fun amd_name_compare(p: ptr, left: u64, right: u64, result: ptr) -> i32 { var av: u8; var bv: u8; @@ -59,7 +74,7 @@ fun amd_name_compare(p: ptr, left: u64, right: u64, return 0; } -fun amd_intern(p: ptr, prefix: u64, name: u64, +pub fun amd_intern(p: ptr, prefix: u64, name: u64, result: ptr) -> u64 { var existing: u64; var index: u64; @@ -166,7 +181,7 @@ fun amd_expression_add(a_low: u64, a_high: u64, b_low: u64, b_high: u64, && output.low >= 9223372036854775808); } -fun amd_expression(p: ptr, scope: u64, expression: ptr, +pub fun amd_expression(p: ptr, scope: u64, expression: ptr, output: ptr, result: ptr) -> bool { var value: AsmWide; output[0] = expression[0]; @@ -195,7 +210,7 @@ fun amd_expression(p: ptr, scope: u64, expression: ptr, return true; } -fun amd_evaluated_expression(p: ptr, scope: u64, +pub fun amd_evaluated_expression(p: ptr, scope: u64, expression: ptr, output: ptr, result: ptr) -> bool { if (!amd_expression(p, scope, expression, output, result)) { return false; @@ -206,7 +221,7 @@ fun amd_evaluated_expression(p: ptr, scope: u64, return true; } -fun amd_constants(p: ptr, result: ptr) -> bool { +pub fun amd_constants(p: ptr, result: ptr) -> bool { var item: ptr; var node: ptr; var symbol: u64; diff --git a/assembler/amd64/sse.wave b/assembler/amd64/src/encoder/sse.wave similarity index 83% rename from assembler/amd64/sse.wave rename to assembler/amd64/src/encoder/sse.wave index dd699f1..604e307 100644 --- a/assembler/amd64/sse.wave +++ b/assembler/amd64/src/encoder/sse.wave @@ -1,6 +1,15 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::encoder::emit")::{ + amd_emit, + amd_mem_width, + amd_memory, + amd_modrm, + amd_rex, +}; +import("whale_wave_amd64::encoder::model")::{AmdOperand, AmdWriter, amd_fail}; + // Legacy scalar SSE; no packed or AVX encoding is implied. -fun amd_scalar_sse(w: ptr, operation: u64, a: ptr, +pub fun amd_scalar_sse(w: ptr, operation: u64, a: ptr, b: ptr) -> bool { var width: u64 = 32; var prefix: u64 = 243; diff --git a/assembler/amd64/src/lib.wave b/assembler/amd64/src/lib.wave new file mode 100644 index 0000000..f953a61 --- /dev/null +++ b/assembler/amd64/src/lib.wave @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit role modules; Vex compiles this package without source concatenation. +import("./encoder/address.wave" as encoder_address); +import("./encoder/branch.wave" as encoder_branch); +import("./parser/directives.wave" as parser_directives); +import("./encoder/directives_encode.wave" as encoder_directives_encode); +import("./encoder/emit.wave" as encoder_emit); +import("./encoder/encoder.wave" as encoder_encoder); +import("./encoder/model.wave" as encoder_model); +import("./parser/expressions.wave" as parser_expressions); +import("./encoder/instruction.wave" as encoder_instruction); +import("./encoder/integer.wave" as encoder_integer); +import("./encoder/layout.wave" as encoder_layout); +import("./encoder/namespace.wave" as encoder_namespace); +import("./parser/operands.wave" as parser_operands); +import("./parser/driver.wave" as parser_driver); +import("./parser/model.wave" as parser_model); +import("./parser/registers.wave" as parser_registers); +import("./encoder/sse.wave" as encoder_sse); diff --git a/assembler/amd64/directives.wave b/assembler/amd64/src/parser/directives.wave similarity index 90% rename from assembler/amd64/directives.wave rename to assembler/amd64/src/parser/directives.wave index 477b80b..1ef3985 100644 --- a/assembler/amd64/directives.wave +++ b/assembler/amd64/src/parser/directives.wave @@ -1,6 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::parser::expressions")::{ + amd64_expr_clear, + amd64_finish_statement, + amd64_parse_backend, + amd64_parse_charge, + amd64_parse_expression, + amd64_parse_fail, + amd64_parse_name, + amd64_token_is, + amd64_token_kind, +}; +import("whale_wave_amd64::parser::model")::{AsmParser}; +import("whale_wave_amd64::parser::registers")::{amd64_name_is}; +import("whale_wave_assembler::ast")::{AsmDirectiveValue, AsmItem, AsmName}; + // Directives retain their expression and byte payloads for later assembly passes. -fun amd64_directive_tag(name: ptr) -> u64 { +pub fun amd64_directive_tag(name: ptr) -> u64 { if (amd64_name_is(name, 119225648511347, 6, 1)) { // symbol return 1; } @@ -35,7 +50,7 @@ fun amd64_parse_comma(p: ptr) -> bool { return true; } -fun amd64_parse_directive(p: ptr, item: ptr) -> bool { +pub fun amd64_parse_directive(p: ptr, item: ptr) -> bool { var start: u64 = p.position; var tag: u64 = amd64_directive_tag(&p.packet.tokens[start].text); p.position += 1; diff --git a/assembler/amd64/parser.wave b/assembler/amd64/src/parser/driver.wave similarity index 86% rename from assembler/amd64/parser.wave rename to assembler/amd64/src/parser/driver.wave index d94a8e0..a8cac2b 100644 --- a/assembler/amd64/parser.wave +++ b/assembler/amd64/src/parser/driver.wave @@ -1,4 +1,29 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::parser::directives")::{amd64_directive_tag, amd64_parse_directive}; +import("whale_wave_amd64::parser::expressions")::{ + amd64_expr_clear, + amd64_finish_statement, + amd64_parse_backend, + amd64_parse_charge, + amd64_parse_expression, + amd64_parse_fail, + amd64_parse_name, + amd64_token_is, + amd64_token_kind, +}; +import("whale_wave_amd64::parser::operands")::{amd64_emit_operand, amd64_parse_operand}; +import("whale_wave_amd64::parser::model")::{ + AsmParseInput, + AsmParseOutput, + AsmParseResult, + AsmParseToken, + AsmParser, +}; +import("whale_wave_amd64::parser::registers")::{amd64_name_is}; +import("whale_wave_assembler::ast")::{AsmItem, AsmName, AsmOperand}; + +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + // Complete AMD64 statement grammar with caller-owned transactional output. fun amd64_item_clear(item: ptr) { item.kind = 0; @@ -71,7 +96,7 @@ fun amd64_parse_constant(p: ptr, item: ptr) -> bool { return true; } -export(c) fun whale_amd64_parse(packet: ptr, output: ptr, +pub export(c) fun whale_amd64_parse(packet: ptr, output: ptr, result: ptr) -> i32 { if (result == null) { return 2; diff --git a/assembler/amd64/expressions.wave b/assembler/amd64/src/parser/expressions.wave similarity index 84% rename from assembler/amd64/expressions.wave rename to assembler/amd64/src/parser/expressions.wave index 347d581..47d5c44 100644 --- a/assembler/amd64/expressions.wave +++ b/assembler/amd64/src/parser/expressions.wave @@ -1,19 +1,28 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::parser::model")::{AsmParseToken, AsmParser}; +import("whale_wave_amd64::parser::registers")::{amd64_lower_byte, amd64_name_is}; +import("whale_wave_assembler::ast")::{AsmExpr, AsmName}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_number_add_checked") fun asm_number_add_checked(a: ptr, b: ptr, + output: ptr) -> bool; +extern(c, "asm_number_neg_checked") fun asm_number_neg_checked(value: ptr, output: ptr) -> bool; + // Single-symbol, checked signed-128 expressions; no host numeric callbacks. -fun amd64_parse_fail(p: ptr, error: u64, index: u64) -> bool { +pub fun amd64_parse_fail(p: ptr, error: u64, index: u64) -> bool { p.result.status = 1; p.result.error = error; p.result.index = index; return false; } -fun amd64_parse_backend(p: ptr) -> bool { +pub fun amd64_parse_backend(p: ptr) -> bool { p.result.status = 2; p.result.index = p.position; return false; } -fun amd64_parse_charge(p: ptr, count: u64) -> bool { +pub fun amd64_parse_charge(p: ptr, count: u64) -> bool { if (count > p.packet.max_work - p.result.work) { p.result.status = 3; p.result.index = p.position; @@ -23,19 +32,19 @@ fun amd64_parse_charge(p: ptr, count: u64) -> bool { return true; } -fun amd64_token_kind(p: ptr, at: u64) -> u64 { +pub fun amd64_token_kind(p: ptr, at: u64) -> u64 { if (at >= p.packet.count) { return 18446744073709551615; } return p.packet.tokens[at].kind; } -fun amd64_token_is(p: ptr, at: u64, key: u64, count: u64) -> bool { +pub fun amd64_token_is(p: ptr, at: u64, key: u64, count: u64) -> bool { return at < p.packet.count && p.packet.tokens[at].kind == 0 && amd64_name_is(&p.packet.tokens[at].text, key, count, 1); } -fun amd64_parse_name(p: ptr, token: u64, lower: bool, output: ptr) -> bool { +pub fun amd64_parse_name(p: ptr, token: u64, lower: bool, output: ptr) -> bool { if (token >= p.packet.count || p.packet.tokens[token].kind != 0) { return amd64_parse_backend(p); } @@ -69,7 +78,7 @@ fun amd64_parse_name(p: ptr, token: u64, lower: bool, output: ptr) { +pub fun amd64_expr_clear(expression: ptr) { expression.kind = 0; expression.name = 18446744073709551615; expression.low = 0; @@ -103,7 +112,7 @@ fun amd64_expr_add(p: ptr, left: ptr, right: ptr, a } // Stop mode0: newline; mode1: comma or newline. -fun amd64_parse_expression(p: ptr, stop: u64, output: ptr) -> bool { +pub fun amd64_parse_expression(p: ptr, stop: u64, output: ptr) -> bool { var have: bool = false; var expect_term: bool = true; var negative: bool = false; @@ -192,7 +201,7 @@ fun amd64_parse_expression(p: ptr, stop: u64, output: ptr) - return true; } -fun amd64_finish_statement(p: ptr) -> bool { +pub fun amd64_finish_statement(p: ptr) -> bool { if (p.position < p.packet.count && amd64_token_kind(p, p.position) != 11) { return amd64_parse_fail(p, 7, p.position); } diff --git a/assembler/amd64/parser_model.wave b/assembler/amd64/src/parser/model.wave similarity index 79% rename from assembler/amd64/parser_model.wave rename to assembler/amd64/src/parser/model.wave index acfb3b6..c8b2e16 100644 --- a/assembler/amd64/parser_model.wave +++ b/assembler/amd64/src/parser/model.wave @@ -1,5 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 -struct AsmParseToken { +import("whale_wave_assembler::ast")::{AsmDirectiveValue, AsmItem, AsmName, AsmOperand}; + +pub struct AsmParseToken { kind: u64; position: u64; end: u64; @@ -13,14 +15,14 @@ struct AsmParseSpan { end: u64; } -struct AsmParseInput { +pub struct AsmParseInput { tokens: ptr; count: u64; mode: u64; max_work: u64; } -struct AsmParseOutput { +pub struct AsmParseOutput { items: ptr; item_capacity: u64; spans: ptr; @@ -35,7 +37,7 @@ struct AsmParseOutput { byte_capacity: u64; } -struct AsmParseResult { +pub struct AsmParseResult { status: u64; error: u64; index: u64; @@ -48,7 +50,7 @@ struct AsmParseResult { work: u64; } -struct AsmParser { +pub struct AsmParser { packet: ptr; output: ptr; result: ptr; diff --git a/assembler/amd64/operands.wave b/assembler/amd64/src/parser/operands.wave similarity index 88% rename from assembler/amd64/operands.wave rename to assembler/amd64/src/parser/operands.wave index 6152239..0a7c5f7 100644 --- a/assembler/amd64/operands.wave +++ b/assembler/amd64/src/parser/operands.wave @@ -1,4 +1,22 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_amd64::parser::expressions")::{ + amd64_parse_backend, + amd64_parse_charge, + amd64_parse_expression, + amd64_parse_fail, + amd64_parse_name, + amd64_token_kind, +}; +import("whale_wave_amd64::parser::model")::{AsmParseToken, AsmParser}; +import("whale_wave_amd64::parser::registers")::{Amd64Register, amd64_name_is, amd64_register}; +import("whale_wave_assembler::ast")::{AsmExpr, AsmName, AsmOperand}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_number_add_checked") fun asm_number_add_checked(a: ptr, b: ptr, + output: ptr) -> bool; +extern(c, "asm_number_fits_signed") fun asm_number_fits_signed(value: ptr, bits: u64) -> bool; +extern(c, "asm_number_neg_checked") fun asm_number_neg_checked(value: ptr, output: ptr) -> bool; + // Operand grammar keeps register recognition separate from encoding constraints. fun amd64_operand_clear(operand: ptr) { operand.kind = 0; @@ -165,7 +183,7 @@ fun amd64_parse_memory(p: ptr, output: ptr) -> bool { return false; } -fun amd64_parse_operand(p: ptr, output: ptr) -> bool { +pub fun amd64_parse_operand(p: ptr, output: ptr) -> bool { amd64_operand_clear(output); var kind: u64 = amd64_token_kind(p, p.position); if (kind == 0) { @@ -214,7 +232,7 @@ fun amd64_parse_operand(p: ptr, output: ptr) -> bool { return true; } -fun amd64_emit_operand(p: ptr, operand: ptr) -> bool { +pub fun amd64_emit_operand(p: ptr, operand: ptr) -> bool { if (p.packet.mode != 0) { if (p.result.operands >= p.output.operand_capacity) { return amd64_parse_backend(p); diff --git a/assembler/amd64/registers.wave b/assembler/amd64/src/parser/registers.wave similarity index 96% rename from assembler/amd64/registers.wave rename to assembler/amd64/src/parser/registers.wave index b0f033e..2c5bdc8 100644 --- a/assembler/amd64/registers.wave +++ b/assembler/amd64/src/parser/registers.wave @@ -1,6 +1,10 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::ast")::{AsmName}; + +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + // Register classification is shared by parsing and native encoding. -struct Amd64Register { +pub struct Amd64Register { kind: u64; code: u64; width: u64; @@ -8,14 +12,14 @@ struct Amd64Register { rex8: u64; } -fun amd64_lower_byte(value: u8) -> u8 { +pub fun amd64_lower_byte(value: u8) -> u8 { if (value >= 65 && value <= 90) { return value + 32; } return value; } -fun amd64_name_is(name: ptr, key: u64, count: u64, fold: u64) -> bool { +pub fun amd64_name_is(name: ptr, key: u64, count: u64, fold: u64) -> bool { if (name.count != count) { return false; } @@ -33,7 +37,7 @@ fun amd64_name_is(name: ptr, key: u64, count: u64, fold: u64) -> bool { return true; } -fun amd64_register(name: ptr, fold: u64, output: ptr) -> bool { +pub fun amd64_register(name: ptr, fold: u64, output: ptr) -> bool { if (name == null || output == null || fold > 1 || name.count > 8) { return false; } @@ -571,7 +575,7 @@ fun amd64_register(name: ptr, fold: u64, output: ptr) -> return false; } -export(c) fun whale_amd64_register(name: ptr, fold: u64, +pub export(c) fun whale_amd64_register(name: ptr, fold: u64, output: ptr) -> i32 { if (name == null || output == null || fold > 1 || !asm_span_valid(name.bytes, name.count, 1)) { diff --git a/assembler/amd64/vex.ws b/assembler/amd64/vex.ws new file mode 100644 index 0000000..3cc6c48 --- /dev/null +++ b/assembler/amd64/vex.ws @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_wave_amd64", + version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + dependencies = [{ name = "whale_wave_assembler", path = ".." }], + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/assembler/asmobj/README.md b/assembler/asmobj/README.md index a686b52..b770a7c 100644 --- a/assembler/asmobj/README.md +++ b/assembler/asmobj/README.md @@ -5,15 +5,15 @@ implementation, or language-specific `wave/` subdirectory. | Source | Role | | --- | --- | -| `model.wave` | Private borrowed input/output records and resource checks | -| `sections.wave` | Section role and sparse-storage mapping | -| `symbols.wave` | Symbol mapping, name lookup and undefined-symbol creation | -| `relocations.wave` | Bounded namespace/target dispatch and relocation records | -| `relocations/*.wave` | ISA-owned ELF, COFF and Mach-O translation rules | -| `entry.wave` | Validate the complete conversion before publishing output | +| `src/model.wave` | Private borrowed input/output records and resource checks | +| `src/sections.wave` | Section role and sparse-storage mapping | +| `src/symbols.wave` | Symbol mapping, name lookup and undefined-symbol creation | +| `src/relocations.wave` | Bounded namespace/target dispatch and relocation records | +| `src/relocations/*.wave` | ISA-owned ELF, COFF and Mach-O translation rules | +| `src/lib.wave` | Validate the complete conversion before publishing output | -Meson builds these explicit sources as one module. The calling Rust code in -`toolchain/src/assembly_object.rs` transfers data across the language boundary; +Meson asks Vex to build this package as one static library. The calling Rust code in +`bindings/rust/asmobj/src/lib.rs` transfers data across the language boundary; `object/` owns generic object validation and file serialization. There is no Rust copy of asmobj's mapping rules. An executable built without this module reports that assembly-to-object conversion is unavailable. @@ -29,4 +29,4 @@ It borrows immutable input only for the duration of a call. See [BUILDING.md](../../BUILDING.md) for build commands. Independent native checks are in `tools/check_asmobj.py`; public Rust-call integration tests are in -`toolchain/tests/assembly_object.rs`. +`bindings/rust/asmobj/tests/assembly_object.rs`. diff --git a/assembler/asmobj/meson.build b/assembler/asmobj/meson.build index b03b55d..5daf08a 100644 --- a/assembler/asmobj/meson.build +++ b/assembler/asmobj/meson.build @@ -1,41 +1,28 @@ # SPDX-License-Identifier: MPL-2.0 asmobj_dependencies = [] +asmobj_directory = get_option('asmobj-dir') if asmobj_directory == '' asmobj_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - if not target_os.has_key(host_machine.system()) - error('Set cargo-host-target for this executable host.') - endif - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_asmobj.lib' : 'libwhale_asmobj.a' - arguments = ['--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif - asmobj_module = custom_target('asmobj', - output: [archive_name, 'asmobj.meta', 'provenance.json'], - command: [python, files('../../tools/build_asmobj.py'), arguments], - depend_files: files('model.wave', 'sections.wave', 'symbols.wave', - 'relocations/amd64.wave', 'relocations/aarch64.wave', - 'relocations/riscv64.wave', 'relocations/loongarch64.wave', - 'relocations.wave', 'entry.wave', - '../../toolchain/src/assembly_object.rs', - '../../tools/build_asmobj.py', '../../tools/wave_bootstrap.py'), - depends: wave_bootstrap, console: true) + asmobj_module = custom_target('wave-asmobj', + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../../tools/vex_module.py'), '--module', 'asmobj', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/asmobj', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../../tools/vex_module.py', '../../tools/wave_modules.py'), + build_always_stale: true, console: true) asmobj_dependencies += [asmobj_module] -else +elif asmobj_directory != '' if not fs.is_absolute(asmobj_directory) error('-Dasmobj-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_asmobj.lib' : 'libwhale_asmobj.a' - foreach artifact : [archive_name, 'asmobj.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(asmobj_directory / artifact) - error('Missing asmobj module artifact: ' + (asmobj_directory / artifact)) + error('Missing Wave asmobj artifact: ' + (asmobj_directory / artifact)) endif endforeach endif diff --git a/assembler/asmobj/entry.wave b/assembler/asmobj/src/lib.wave similarity index 93% rename from assembler/asmobj/entry.wave rename to assembler/asmobj/src/lib.wave index 57de4ce..eeb8b76 100644 --- a/assembler/asmobj/entry.wave +++ b/assembler/asmobj/src/lib.wave @@ -1,4 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjRelocation, AsmobjResult, AsmobjSection, AsmobjState, AsmobjSymbol, AsmobjTarget, asmobj_array_valid, asmobj_charge, asmobj_target_valid}; +import("whale_asmobj::relocations")::{asmobj_emit_relocation, asmobj_relocation_kind, asmobj_relocation_valid}; +import("whale_asmobj::sections")::{asmobj_emit_section, asmobj_section_valid}; +import("whale_asmobj::symbols")::{asmobj_emit_undefined, asmobj_find_name, asmobj_register_symbol, asmobj_symbol_valid}; + // Whole-module entry. Input and output records cannot alias, inputs remain // immutable during the call, and only scratch/result may change on failure. // Status: 1 target, 2 symbol section, 3 namespace, 4 namespace mismatch, diff --git a/assembler/asmobj/model.wave b/assembler/asmobj/src/model.wave similarity index 77% rename from assembler/asmobj/model.wave rename to assembler/asmobj/src/model.wave index a33666f..31268e9 100644 --- a/assembler/asmobj/model.wave +++ b/assembler/asmobj/src/model.wave @@ -1,14 +1,14 @@ // SPDX-License-Identifier: MPL-2.0 // Private borrowed records between asmobj and its caller. This is not a target // extension API: adding an ISA changes the owning source files and build list. -struct AsmobjTarget { +pub struct AsmobjTarget { format: u64; machine: u64; address_bits: u64; endian: u64; } -struct AsmobjSection { +pub struct AsmobjSection { name: ptr; name_len: u64; kind: u64; @@ -18,7 +18,7 @@ struct AsmobjSection { zero_fill: u64; } -struct AsmobjSymbol { +pub struct AsmobjSymbol { name: ptr; name_len: u64; kind: u64; @@ -29,7 +29,7 @@ struct AsmobjSymbol { visibility: u64; } -struct AsmobjRelocation { +pub struct AsmobjRelocation { section: u64; offset: u64; name: ptr; @@ -41,13 +41,13 @@ struct AsmobjRelocation { addend: i64; } -struct AsmobjResult { +pub struct AsmobjResult { status: u64; index: u64; symbol_count: u64; } -struct AsmobjState { +pub struct AsmobjState { symbols: ptr; symbol_count: u64; relocations: ptr; @@ -58,7 +58,7 @@ struct AsmobjState { status: i32; } -fun asmobj_charge(state: ptr, amount: u64) -> bool { +pub fun asmobj_charge(state: ptr, amount: u64) -> bool { if (amount > state.work) { state.status = 9; return false; @@ -67,17 +67,17 @@ fun asmobj_charge(state: ptr, amount: u64) -> bool { return true; } -fun asmobj_span_valid(data: ptr, count: u64) -> bool { +pub fun asmobj_span_valid(data: ptr, count: u64) -> bool { return (count == 0 || data != null) && count <= 9223372036854775807 && count <= 18446744073709551615 - (data as u64); } -fun asmobj_array_valid(data: ptr, count: u64, width: u64) -> bool { +pub fun asmobj_array_valid(data: ptr, count: u64, width: u64) -> bool { return count <= 9223372036854775807 / width && asmobj_span_valid(data, count * width); } -fun asmobj_target_valid(target: ptr) -> bool { +pub fun asmobj_target_valid(target: ptr) -> bool { return target != null && target.format <= 2 && target.machine <= 3 && target.address_bits == 64 && target.endian == 0 && (target.format == 0 || target.machine <= 1); diff --git a/assembler/asmobj/relocations.wave b/assembler/asmobj/src/relocations.wave similarity index 74% rename from assembler/asmobj/relocations.wave rename to assembler/asmobj/src/relocations.wave index 17c83b1..2c99dd0 100644 --- a/assembler/asmobj/relocations.wave +++ b/assembler/asmobj/src/relocations.wave @@ -1,4 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjRelocation, AsmobjState, AsmobjTarget, asmobj_span_valid}; +import("whale_asmobj::relocations::aarch64")::{asmobj_aarch64_relocation}; +import("whale_asmobj::relocations::amd64")::{asmobj_amd64_control}; +import("whale_asmobj::relocations::loongarch64")::{asmobj_loongarch64_relocation}; +import("whale_asmobj::relocations::riscv64")::{asmobj_riscv64_relocation}; +import("whale_asmobj::symbols")::{asmobj_names_equal}; + // Namespace and format selection belongs to the assembler/object bridge. // Generic object validation and serialization remain owned by the object module. fun asmobj_literal_equal(state: ptr, data: ptr, count: u64, @@ -6,7 +13,7 @@ fun asmobj_literal_equal(state: ptr, data: ptr, count: u64, return asmobj_names_equal(state, data, count, literal, literal_len); } -fun asmobj_relocation_kind(state: ptr, target: ptr, +pub fun asmobj_relocation_kind(state: ptr, target: ptr, relocation: ptr, undefined: u64, kind: ptr, code: ptr) -> i32 { kind[0] = relocation.kind; code[0] = 0; @@ -45,14 +52,14 @@ fun asmobj_relocation_kind(state: ptr, target: ptr, return asmobj_loongarch64_relocation(target, relocation, code); } -fun asmobj_relocation_valid(relocation: ptr, section_count: u64) -> bool { +pub fun asmobj_relocation_valid(relocation: ptr, section_count: u64) -> bool { return relocation.section < section_count && relocation.kind <= 6 && relocation.code <= 4294967295 && asmobj_span_valid(relocation.name, relocation.name_len) && asmobj_span_valid(relocation.namespace, relocation.namespace_len); } -fun asmobj_emit_relocation(source: ptr, kind: u64, code: u64, +pub fun asmobj_emit_relocation(source: ptr, kind: u64, code: u64, output: ptr) { output[0] = deref source; output.kind = kind; diff --git a/assembler/asmobj/relocations/aarch64.wave b/assembler/asmobj/src/relocations/aarch64.wave similarity index 84% rename from assembler/asmobj/relocations/aarch64.wave rename to assembler/asmobj/src/relocations/aarch64.wave index 33f2eda..256c26e 100644 --- a/assembler/asmobj/relocations/aarch64.wave +++ b/assembler/asmobj/src/relocations/aarch64.wave @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjRelocation, AsmobjTarget}; + // AArch64 ELF IDs and the supported COFF/Mach-O translations. -fun asmobj_aarch64_relocation(target: ptr, relocation: ptr, +pub fun asmobj_aarch64_relocation(target: ptr, relocation: ptr, kind: ptr, code: ptr) -> i32 { if (target.format == 0) { code[0] = relocation.code; diff --git a/assembler/asmobj/relocations/amd64.wave b/assembler/asmobj/src/relocations/amd64.wave similarity index 71% rename from assembler/asmobj/relocations/amd64.wave rename to assembler/asmobj/src/relocations/amd64.wave index 64e9cb7..4533429 100644 --- a/assembler/asmobj/relocations/amd64.wave +++ b/assembler/asmobj/src/relocations/amd64.wave @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjTarget}; + // Legacy near-control transfers select PC-relative or Mach-O branch forms. -fun asmobj_amd64_control(target: ptr, undefined: u64, +pub fun asmobj_amd64_control(target: ptr, undefined: u64, kind: ptr, code: ptr) -> i32 { if (target.format == 2) { kind[0] = 8; diff --git a/assembler/asmobj/relocations/loongarch64.wave b/assembler/asmobj/src/relocations/loongarch64.wave similarity index 57% rename from assembler/asmobj/relocations/loongarch64.wave rename to assembler/asmobj/src/relocations/loongarch64.wave index 2b118e2..e076e98 100644 --- a/assembler/asmobj/relocations/loongarch64.wave +++ b/assembler/asmobj/src/relocations/loongarch64.wave @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjRelocation, AsmobjTarget}; + // LoongArch relocation numbers are preserved for ELF only. -fun asmobj_loongarch64_relocation(target: ptr, relocation: ptr, +pub fun asmobj_loongarch64_relocation(target: ptr, relocation: ptr, code: ptr) -> i32 { if (target.format != 0) { return 6; diff --git a/assembler/asmobj/relocations/riscv64.wave b/assembler/asmobj/src/relocations/riscv64.wave similarity index 60% rename from assembler/asmobj/relocations/riscv64.wave rename to assembler/asmobj/src/relocations/riscv64.wave index 9900de1..db21c0b 100644 --- a/assembler/asmobj/relocations/riscv64.wave +++ b/assembler/asmobj/src/relocations/riscv64.wave @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjRelocation, AsmobjTarget}; + // RISC-V relocation numbers are preserved for ELF; other formats are unsupported. -fun asmobj_riscv64_relocation(target: ptr, relocation: ptr, +pub fun asmobj_riscv64_relocation(target: ptr, relocation: ptr, code: ptr) -> i32 { if (target.format != 0) { return 6; diff --git a/assembler/asmobj/sections.wave b/assembler/asmobj/src/sections.wave similarity index 71% rename from assembler/asmobj/sections.wave rename to assembler/asmobj/src/sections.wave index 61d97a1..206cd5a 100644 --- a/assembler/asmobj/sections.wave +++ b/assembler/asmobj/src/sections.wave @@ -1,7 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjSection, asmobj_span_valid}; + // Section order is the object section map. Byte payloads remain borrowed until // the caller reconstructs its ObjectFile; sparse BSS is never materialized. -fun asmobj_section_valid(section: ptr) -> bool { +pub fun asmobj_section_valid(section: ptr) -> bool { return section.kind <= 3 && asmobj_span_valid(section.name, section.name_len) && asmobj_span_valid(section.data, section.data_len); } @@ -12,7 +14,7 @@ fun asmobj_section_kind(kind: u64) -> u64 { return kind; } -fun asmobj_emit_section(source: ptr, output: ptr) { +pub fun asmobj_emit_section(source: ptr, output: ptr) { output[0] = deref source; output.kind = asmobj_section_kind(source.kind); } diff --git a/assembler/asmobj/symbols.wave b/assembler/asmobj/src/symbols.wave similarity index 86% rename from assembler/asmobj/symbols.wave rename to assembler/asmobj/src/symbols.wave index 03e4121..c2daa94 100644 --- a/assembler/asmobj/symbols.wave +++ b/assembler/asmobj/src/symbols.wave @@ -1,4 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_asmobj::model")::{AsmobjRelocation, AsmobjState, AsmobjSymbol, asmobj_charge, asmobj_span_valid}; + // Each hash slot is {source kind, source index, undefined flag, byte hash}. // Source kind 1 borrows an input symbol, 2 the first relocation needing a symbol. fun asmobj_name_hash(state: ptr, name: ptr, count: u64, @@ -14,7 +16,7 @@ fun asmobj_name_hash(state: ptr, name: ptr, count: u64, return true; } -fun asmobj_names_equal(state: ptr, left: ptr, left_len: u64, +pub fun asmobj_names_equal(state: ptr, left: ptr, left_len: u64, right: ptr, right_len: u64) -> bool { if (left_len != right_len) { return false; } if (!asmobj_charge(state, left_len)) { return false; } @@ -26,7 +28,7 @@ fun asmobj_names_equal(state: ptr, left: ptr, left_len: u64, return true; } -fun asmobj_find_name(state: ptr, name: ptr, count: u64, +pub fun asmobj_find_name(state: ptr, name: ptr, count: u64, output: ptr) -> bool { var hash: u64 = 0; if (!asmobj_name_hash(state, name, count, &hash)) { return false; } @@ -68,12 +70,12 @@ fun asmobj_find_name(state: ptr, name: ptr, count: u64, return false; } -fun asmobj_symbol_valid(symbol: ptr) -> bool { +pub fun asmobj_symbol_valid(symbol: ptr) -> bool { return symbol.kind <= 2 && symbol.binding <= 1 && symbol.visibility <= 1 && asmobj_span_valid(symbol.name, symbol.name_len); } -fun asmobj_register_symbol(state: ptr, index: u64) -> bool { +pub fun asmobj_register_symbol(state: ptr, index: u64) -> bool { var symbol: ptr = &state.symbols[index]; var slot: u64 = 0; if (!asmobj_find_name(state, symbol.name, symbol.name_len, &slot)) { return false; } @@ -86,7 +88,7 @@ fun asmobj_register_symbol(state: ptr, index: u64) -> bool { return true; } -fun asmobj_emit_undefined(relocation: ptr, output: ptr) { +pub fun asmobj_emit_undefined(relocation: ptr, output: ptr) { output.name = relocation.name; output.name_len = relocation.name_len; output.kind = 0; diff --git a/assembler/asmobj/vex.ws b/assembler/asmobj/vex.ws new file mode 100644 index 0000000..1fe4299 --- /dev/null +++ b/assembler/asmobj/vex.ws @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_asmobj", + version = "0.1.0", + targets = { + lib = { output = "static", mode = "freestanding", relocation = "pic" } + }, + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/assembler/build.rs b/assembler/build.rs deleted file mode 100644 index 54c14c0..0000000 --- a/assembler/build.rs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -const CFG: &str = "whale_wave_assembler"; - -const ENV: &str = "WHALE_WAVE_ASSEMBLER_DIR"; - -const LIBRARY: &str = "whale_wave_assembler"; - -const METADATA: &str = "wave-assembler.meta"; - -const ROOT_UP: usize = 1; - -const SOURCES: &[&str] = &[ - "assembler/model.wave", - "assembler/unicode.wave", - "assembler/numeric.wave", - "assembler/output.wave", - "assembler/lexer.wave", - "assembler/fixed_model.wave", - "assembler/fixed_text.wave", - "assembler/fixed_numbers.wave", - "assembler/fixed_operands.wave", - "assembler/fixed_namespace.wave", - "assembler/fixed_relative.wave", - "assembler/fixed_scalar.wave", - "assembler/fixed_source.wave", - "assembler/fixed_driver.wave", -]; - -const ABI_SOURCES: &[&str] = &[ - "assembler/src/tokens.rs", - "assembler/src/tokens_wave.rs", - "assembler/src/fixed.rs", - "assembler/src/fixed_wave.rs", - "assembler/src/lib.rs", -]; -include!("build_support.rs"); diff --git a/assembler/build_support.rs b/assembler/build_support.rs deleted file mode 100644 index 4609fc4..0000000 --- a/assembler/build_support.rs +++ /dev/null @@ -1,142 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Internal Cargo artifact guard, shared only by the explicit assembler crates. -use std::{collections::BTreeMap, env, fs, io::Read, path::PathBuf}; - -const PIN: &str = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"; - -fn update(hash: u64, bytes: &[u8]) -> u64 { - bytes.iter().fold(hash, |h, byte| (h ^ u64::from(*byte)).wrapping_mul(0x100000001b3)) -} - -fn hash(bytes: &[u8]) -> String { - format!("{:016x}", update(0xcbf29ce484222325, bytes)) -} - -fn hash_file(path: &std::path::Path, maximum: Option) -> String { - let mut file = fs::File::open(path) - .unwrap_or_else(|_| panic!("missing Wave assembler artifact {}", path.display())); - let mut value = 0xcbf29ce484222325; - let mut seen = 0; - let mut buffer = [0; 16384]; - loop { - let count = file.read(&mut buffer).expect("cannot read Wave assembler artifact"); - if count == 0 { - return format!("{value:016x}"); - } - seen += count as u64; - if maximum.is_some_and(|limit| seen > limit) { - panic!("oversized Wave assembler artifact {}", path.display()); - } - value = update(value, &buffer[..count]); - } -} - -fn main() { - println!("cargo:rustc-check-cfg=cfg({CFG})"); - println!("cargo:rerun-if-env-changed={ENV}"); - println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUST_REFERENCE"); - let Some(directory) = env::var_os(ENV) else { - assert!(env::var_os("CARGO_FEATURE_RUST_REFERENCE").is_some(), - "{CFG} requires its Wave module; build with Meson or select rust-reference explicitly for comparison"); - return; - }; - if CFG != "whale_wave_assembler" { - assert!( - env::var_os("WHALE_WAVE_ASSEMBLER_DIR").is_some(), - "Wave ISA modules require WHALE_WAVE_ASSEMBLER_DIR for shared assembler utilities" - ); - } - let directory = PathBuf::from(directory) - .canonicalize() - .expect("Wave assembler artifact directory must exist"); - let target = env::var("TARGET").expect("Cargo target required"); - let archive = directory.join(if target.contains("msvc") { - format!("{LIBRARY}.lib") - } else { - format!("lib{LIBRARY}.a") - }); - let metadata = directory.join(METADATA); - let provenance = directory.join("provenance.json"); - for path in [&archive, &metadata, &provenance] { - println!("cargo:rerun-if-changed={}", path.display()); - } - let mut text = String::new(); - fs::File::open(&metadata) - .expect("missing assembler metadata; build with tools/build_wave_assembler.py") - .take(4097) - .read_to_string(&mut text) - .expect("invalid Wave assembler metadata"); - assert!(text.len() <= 4096, "oversized Wave assembler metadata"); - let mut fields = BTreeMap::new(); - for line in text.lines() { - let (key, value) = line.split_once('=').expect("malformed Wave assembler metadata"); - assert!( - [ - "schema", - "target", - "wave_revision", - "opt_level", - "source_fnv64", - "abi_fnv64", - "archive_fnv64", - "provenance_fnv64" - ] - .contains(&key) - && fields.insert(key, value).is_none(), - "invalid Wave assembler metadata fields" - ); - } - assert_eq!(fields.len(), 8, "incomplete Wave assembler metadata"); - assert_eq!(fields.get("schema"), Some(&"1"), "unsupported Wave assembler metadata"); - assert_eq!(fields.get("target"), Some(&target.as_str()), "Wave assembler target mismatch"); - assert_eq!( - fields.get("wave_revision"), - Some(&PIN), - "Wave assembler compiler revision mismatch" - ); - assert!( - [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), - "unsupported Wave assembler optimization level" - ); - let mut root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); - for _ in 0..ROOT_UP { - assert!(root.pop(), "invalid assembler source root"); - } - let mut source = Vec::new(); - for (index, name) in SOURCES.iter().enumerate() { - let path = root.join(name); - println!("cargo:rerun-if-changed={}", path.display()); - if index != 0 { - source.push(b'\n'); - } - source.extend(fs::read(path).expect("missing Wave assembler source")); - } - assert_eq!( - fields.get("source_fnv64"), - Some(&hash(&source).as_str()), - "stale Wave assembler archive" - ); - let mut abi = Vec::new(); - for (index, name) in ABI_SOURCES.iter().enumerate() { - let path = root.join(name); - println!("cargo:rerun-if-changed={}", path.display()); - if index != 0 { - abi.push(b'\n'); - } - abi.extend(fs::read(path).expect("missing Wave assembler ABI source")); - } - assert_eq!(fields.get("abi_fnv64"), Some(&hash(&abi).as_str()), "stale Wave assembler ABI"); - assert_eq!( - fields.get("archive_fnv64"), - Some(&hash_file(&archive, None).as_str()), - "corrupt Wave assembler archive" - ); - assert_eq!( - fields.get("provenance_fnv64"), - Some(&hash_file(&provenance, Some(16 * 1024)).as_str()), - "corrupt Wave assembler provenance" - ); - println!("cargo:rustc-link-search=native={}", directory.display()); - println!("cargo:rustc-link-lib=static={LIBRARY}"); - println!("cargo:rustc-cfg={CFG}"); -} diff --git a/assembler/declarations.wave b/assembler/declarations.wave deleted file mode 100644 index 7eb8b0f..0000000 --- a/assembler/declarations.wave +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Internal link declarations for shared assembler source utilities. -extern(c) fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; -extern(c) fun asm_power_two(value: u64) -> bool; -extern(c) fun asm_align_up(size: u64, align: u64, output: ptr) -> bool; -extern(c) fun asm_number_add_checked(a: ptr, b: ptr, - output: ptr) -> bool; -extern(c) fun asm_number_neg_checked(value: ptr, output: ptr) -> bool; -extern(c) fun asm_number_sub_checked(a: ptr, b: ptr, - output: ptr) -> bool; -extern(c) fun asm_number_fits_signed(value: ptr, bits: u64) -> bool; -extern(c) fun asm_number_fits_unsigned(value: ptr, bits: u64) -> bool; -extern(c) fun asm_unicode_alphanumeric(cp: u64) -> bool; -extern(c) fun asm_output_grow(materialized: u64, section: u64, extra: u64, - limit: u64, logical: u64, output: ptr) -> i32; -extern(c) fun asm_output_align(materialized: u64, section: u64, alignment: u64, - limit: u64, logical: u64, output: ptr) -> i32; diff --git a/assembler/fixed_declarations.wave b/assembler/fixed_declarations.wave deleted file mode 100644 index 374d95a..0000000 --- a/assembler/fixed_declarations.wave +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Ordinary internal links to the shared fixed-width source helpers. -extern(c) fun asm_fixed_trim(text: FixedText) -> FixedText; -extern(c) fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; -extern(c) fun asm_fixed_equal(left: FixedText, right: FixedText, fold: u64) -> bool; -extern(c) fun asm_fixed_fail(result: ptr, code: u64, - text: FixedText, detail: u64) -> bool; -extern(c) fun asm_fixed_count(instruction: ptr, count: u64, - result: ptr) -> bool; -extern(c) fun asm_fixed_integer(text: FixedText, output: ptr, - result: ptr) -> bool; -extern(c) fun asm_fixed_try_integer(text: FixedText, output: ptr, - result: ptr) -> bool; -extern(c) fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, - result: ptr) -> bool; -extern(c) fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, - result: ptr) -> bool; -extern(c) fun asm_fixed_i64(text: FixedText, output: ptr, - result: ptr) -> bool; -extern(c) fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, - output: ptr, result: ptr) -> bool; -extern(c) fun asm_fixed_pc_relative(context: ptr, text: FixedText, - code: u64, output: ptr, result: ptr) -> bool; -extern(c) fun asm_fixed_operands(text: FixedText, output: ptr, capacity: u64, - count: ptr, result: ptr) -> bool; -extern(c) fun asm_fixed_result_init(result: ptr, max_work: u64); -extern(c) fun asm_fixed_charge(result: ptr, units: u64) -> bool; -extern(c) fun asm_fixed_space(text: FixedText, at: u64) -> u64; -extern(c) fun asm_fixed_prepare(packet: ptr, state: ptr, - result: ptr) -> bool; -// next: 1 requests one instruction, 0 completes, -1 reports failure. -extern(c) fun asm_fixed_next(state: ptr, instruction: ptr, - result: ptr) -> i32; -extern(c) fun asm_fixed_commit(state: ptr, word: u64, - result: ptr) -> bool; -extern(c) fun asm_fixed_identifier(text: FixedText, result: ptr) -> bool; -extern(c) fun asm_fixed_symbol(state: ptr, name: FixedText, kind: u64, - result: ptr) -> u64; -extern(c) fun asm_fixed_section(state: ptr, name: FixedText, - result: ptr) -> bool; -extern(c) fun asm_fixed_record(state: ptr, record: ptr, - result: ptr) -> bool; -extern(c) fun asm_fixed_finish(state: ptr, result: ptr) -> bool; -extern(c) fun asm_fixed_lookup(context: ptr, name: FixedText, - result: ptr) -> u64; -extern(c) fun asm_fixed_expression(context: ptr, text: FixedText, - number: ptr, symbol: ptr, addend: ptr, result: ptr) -> bool; diff --git a/assembler/loongarch64/build.rs b/assembler/loongarch64/build.rs deleted file mode 100644 index 55bda5a..0000000 --- a/assembler/loongarch64/build.rs +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -const CFG: &str = "whale_wave_loongarch64"; - -const ENV: &str = "WHALE_WAVE_LOONGARCH64_DIR"; - -const LIBRARY: &str = "whale_wave_loongarch64"; - -const METADATA: &str = "wave-loongarch64.meta"; - -const ROOT_UP: usize = 2; - -const SOURCES: &[&str] = &[ - "assembler/model.wave", - "assembler/declarations.wave", - "assembler/fixed_model.wave", - "assembler/fixed_declarations.wave", - "assembler/loongarch64/model.wave", - "assembler/loongarch64/registers.wave", - "assembler/loongarch64/tables.wave", - "assembler/loongarch64/operands.wave", - "assembler/loongarch64/formats.wave", - "assembler/loongarch64/branch.wave", - "assembler/loongarch64/encoder.wave", - "assembler/loongarch64/entry.wave", -]; - -const ABI_SOURCES: &[&str] = &[ - "assembler/loongarch64/src/wave.rs", - "assembler/loongarch64/src/lib.rs", - "assembler/loongarch64/src/encoder.rs", - "assembler/loongarch64/src/parser.rs", -]; -include!("../build_support.rs"); diff --git a/assembler/loongarch64/meson.build b/assembler/loongarch64/meson.build index 43c8113..9002ad0 100644 --- a/assembler/loongarch64/meson.build +++ b/assembler/loongarch64/meson.build @@ -1,52 +1,26 @@ # SPDX-License-Identifier: MPL-2.0 wave_loongarch64_dependencies = [] wave_loongarch64_directory = get_option('wave-loongarch64-dir') -if wave_loongarch64_directory == '' and wave_source != '' +if wave_loongarch64_directory == '' and not get_option('rust-reference') wave_loongarch64_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_wave_loongarch64.lib' : 'libwhale_wave_loongarch64.a' - arguments = ['--module', 'loongarch64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif wave_loongarch64_module = custom_target('wave-loongarch64', - output: [archive_name, 'wave-loongarch64.meta', 'provenance.json'], - command: [python, files('../../tools/build_wave_assembler.py'), arguments], - depend_files: files( - '../model.wave', - '../declarations.wave', - '../fixed_model.wave', - '../fixed_declarations.wave', - 'model.wave', - 'registers.wave', - 'tables.wave', - 'operands.wave', - 'formats.wave', - 'branch.wave', - 'encoder.wave', - 'entry.wave', - 'src/wave.rs', - 'src/lib.rs', - 'src/encoder.rs', - 'src/parser.rs', - '../../tools/build_wave_assembler.py', - '../../tools/wave_bootstrap.py', - '../build_support.rs', - ), - depends: wave_bootstrap, console: true) + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../../tools/vex_module.py'), '--module', 'loongarch64', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/loongarch64', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../../tools/vex_module.py', '../../tools/wave_modules.py'), + build_always_stale: true, console: true) wave_loongarch64_dependencies += [wave_loongarch64_module] elif wave_loongarch64_directory != '' if not fs.is_absolute(wave_loongarch64_directory) error('-Dwave-loongarch64-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_wave_loongarch64.lib' : 'libwhale_wave_loongarch64.a' - foreach artifact : [archive_name, 'wave-loongarch64.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(wave_loongarch64_directory / artifact) error('Missing Wave loongarch64 artifact: ' + (wave_loongarch64_directory / artifact)) endif diff --git a/assembler/loongarch64/branch.wave b/assembler/loongarch64/src/branch.wave similarity index 63% rename from assembler/loongarch64/branch.wave rename to assembler/loongarch64/src/branch.wave index 21d5c9e..f9f54ac 100644 --- a/assembler/loongarch64/branch.wave +++ b/assembler/loongarch64/src/branch.wave @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 // Scaled B16/B21/B26 immediate packing. Callers validate byte displacements first. -fun loong_b26(opcode: u64, immediate: u64) -> u64 { +pub fun loong_b26(opcode: u64, immediate: u64) -> u64 { return opcode | ((immediate & 65535) << 10) | (immediate >> 16); } -fun loong_b21(opcode: u64, rj: u64, immediate: u64) -> u64 { +pub fun loong_b21(opcode: u64, rj: u64, immediate: u64) -> u64 { return opcode | (rj << 5) | ((immediate & 65535) << 10) | (immediate >> 16); } -fun loong_b16(opcode: u64, rj: u64, rd: u64, immediate: u64) -> u64 { +pub fun loong_b16(opcode: u64, rj: u64, rd: u64, immediate: u64) -> u64 { return opcode | rd | (rj << 5) | (immediate << 10); } diff --git a/assembler/loongarch64/encoder.wave b/assembler/loongarch64/src/encoder.wave similarity index 77% rename from assembler/loongarch64/encoder.wave rename to assembler/loongarch64/src/encoder.wave index 3537096..b86fecc 100644 --- a/assembler/loongarch64/encoder.wave +++ b/assembler/loongarch64/src/encoder.wave @@ -1,4 +1,32 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedContext, + FixedInstruction, + FixedResult, + FixedText, +}; +import("whale_wave_loongarch64::branch")::{loong_b16, loong_b21, loong_b26}; +import("whale_wave_loongarch64::formats")::{loong_immediate, loong_three, loong_upper}; +import("whale_wave_loongarch64::model")::{LoongOpcode}; +import("whale_wave_loongarch64::operands")::{loong_jirl_offset, loong_upper_immediate}; +import("whale_wave_loongarch64::registers")::{loong_register}; +import("whale_wave_loongarch64::tables")::{loong_lookup}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_count") fun asm_fixed_count(instruction: ptr, count: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_displacement") fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, + output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_pc_relative") fun asm_fixed_pc_relative(context: ptr, text: FixedText, + code: u64, output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_signed") fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_unsigned") fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + // Complete current LP64S integer subset. Every register and field decision is native. fun loong_encode(instruction: ptr, context: ptr, result: ptr) -> bool { @@ -127,7 +155,7 @@ fun loong_encode(instruction: ptr, context: ptr, return true; } -export(c) fun whale_loongarch64_encode(instruction: ptr, +pub export(c) fun whale_loongarch64_encode(instruction: ptr, context: ptr, result: ptr) -> i32 { if (instruction == null || context == null || result == null) { return 2; diff --git a/assembler/loongarch64/entry.wave b/assembler/loongarch64/src/entry.wave similarity index 56% rename from assembler/loongarch64/entry.wave rename to assembler/loongarch64/src/entry.wave index e61e811..4f4cb0b 100644 --- a/assembler/loongarch64/entry.wave +++ b/assembler/loongarch64/src/entry.wave @@ -1,6 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedInput, + FixedInstruction, + FixedResult, + FixedState, +}; +import("whale_wave_loongarch64::encoder")::{whale_loongarch64_encode}; + +extern(c, "asm_fixed_commit") fun asm_fixed_commit(state: ptr, word: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_next") fun asm_fixed_next(state: ptr, instruction: ptr, + result: ptr) -> i32; +extern(c, "asm_fixed_prepare") fun asm_fixed_prepare(packet: ptr, state: ptr, + result: ptr) -> bool; + // Native source execution stays in Wave across the shared driver and ISA kernel. -export(c) fun whale_loongarch64_assemble(packet: ptr, +pub export(c) fun whale_loongarch64_assemble(packet: ptr, result: ptr) -> i32 { if (packet == null || result == null) { return 2; @@ -28,6 +43,6 @@ export(c) fun whale_loongarch64_assemble(packet: ptr, } // Distinct compiled identity used by product composition checks. -export(c) fun whale_loongarch64_module_identity() -> u64 { +pub export(c) fun whale_loongarch64_module_identity() -> u64 { return 6289348675458842881; } diff --git a/assembler/loongarch64/formats.wave b/assembler/loongarch64/src/formats.wave similarity index 54% rename from assembler/loongarch64/formats.wave rename to assembler/loongarch64/src/formats.wave index 6e1d377..cf839e3 100644 --- a/assembler/loongarch64/formats.wave +++ b/assembler/loongarch64/src/formats.wave @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 // Fixed-width little-endian integer instruction fields. -fun loong_three(opcode: u64, rd: u64, rj: u64, rk: u64) -> u64 { +pub fun loong_three(opcode: u64, rd: u64, rj: u64, rk: u64) -> u64 { return opcode | rd | (rj << 5) | (rk << 10); } -fun loong_immediate(opcode: u64, rd: u64, rj: u64, immediate: u64) -> u64 { +pub fun loong_immediate(opcode: u64, rd: u64, rj: u64, immediate: u64) -> u64 { return opcode | rd | (rj << 5) | (immediate << 10); } -fun loong_upper(opcode: u64, rd: u64, immediate: u64) -> u64 { +pub fun loong_upper(opcode: u64, rd: u64, immediate: u64) -> u64 { return opcode | rd | ((immediate & 1048575) << 5); } diff --git a/assembler/loongarch64/src/lib.wave b/assembler/loongarch64/src/lib.wave new file mode 100644 index 0000000..abbb31c --- /dev/null +++ b/assembler/loongarch64/src/lib.wave @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit role modules; Vex compiles this package without source concatenation. +import("./branch.wave" as branch); +import("./encoder.wave" as encoder); +import("./entry.wave" as entry); +import("./formats.wave" as formats); +import("./model.wave" as model); +import("./operands.wave" as operands); +import("./registers.wave" as registers); +import("./tables.wave" as tables); diff --git a/assembler/loongarch64/model.wave b/assembler/loongarch64/src/model.wave similarity index 88% rename from assembler/loongarch64/model.wave rename to assembler/loongarch64/src/model.wave index 4b60b60..09991a4 100644 --- a/assembler/loongarch64/model.wave +++ b/assembler/loongarch64/src/model.wave @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 // LoongArch64 instruction classification; integer fields contain no host addresses. -struct LoongOpcode { +pub struct LoongOpcode { form: u64; opcode: u64; bits: u64; diff --git a/assembler/loongarch64/operands.wave b/assembler/loongarch64/src/operands.wave similarity index 51% rename from assembler/loongarch64/operands.wave rename to assembler/loongarch64/src/operands.wave index 57c621a..8457629 100644 --- a/assembler/loongarch64/operands.wave +++ b/assembler/loongarch64/src/operands.wave @@ -1,6 +1,15 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_assembler::model")::{AsmWide}; + +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_integer") fun asm_fixed_integer(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c, "asm_number_fits_signed") fun asm_number_fits_signed(value: ptr, bits: u64) -> bool; + // LoongArch-specific immediate diagnostics preserve source evaluation order. -fun loong_upper_immediate(text: FixedText, output: ptr, +pub fun loong_upper_immediate(text: FixedText, output: ptr, result: ptr) -> bool { var number: AsmWide; if (!asm_fixed_integer(text, &number, result)) { @@ -13,7 +22,7 @@ fun loong_upper_immediate(text: FixedText, output: ptr, return true; } -fun loong_jirl_offset(text: FixedText, output: ptr, result: ptr) -> bool { +pub fun loong_jirl_offset(text: FixedText, output: ptr, result: ptr) -> bool { var number: AsmWide; if (!asm_fixed_integer(text, &number, result)) { return false; diff --git a/assembler/loongarch64/registers.wave b/assembler/loongarch64/src/registers.wave similarity index 90% rename from assembler/loongarch64/registers.wave rename to assembler/loongarch64/src/registers.wave index aeb5ed9..b5bca44 100644 --- a/assembler/loongarch64/registers.wave +++ b/assembler/loongarch64/src/registers.wave @@ -1,4 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; + +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_trim") fun asm_fixed_trim(text: FixedText) -> FixedText; +extern(c, "asm_fixed_word") fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; + // ABI aliases and canonical numeric registers; dollar prefixes are optional. fun loong_register_error(text: FixedText, result: ptr) -> bool { asm_fixed_fail(result, 3000, text, 0); @@ -6,7 +13,7 @@ fun loong_register_error(text: FixedText, result: ptr) -> bool { return false; } -fun loong_register(raw: FixedText, output: ptr, result: ptr) -> bool { +pub fun loong_register(raw: FixedText, output: ptr, result: ptr) -> bool { var text: FixedText = asm_fixed_trim(raw); if (text.count != 0 && text.data[0] == 36) { text.data = &text.data[1]; diff --git a/assembler/loongarch64/tables.wave b/assembler/loongarch64/src/tables.wave similarity index 97% rename from assembler/loongarch64/tables.wave rename to assembler/loongarch64/src/tables.wave index 7c488ff..c1ad49d 100644 --- a/assembler/loongarch64/tables.wave +++ b/assembler/loongarch64/src/tables.wave @@ -1,6 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedText}; +import("whale_wave_loongarch64::model")::{LoongOpcode}; + +extern(c, "asm_fixed_word") fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; + // Complete current integer opcode inventory and operand forms. -fun loong_lookup(text: FixedText, fold: u64, output: ptr) -> bool { +pub fun loong_lookup(text: FixedText, fold: u64, output: ptr) -> bool { if (asm_fixed_word(text, 511879439457, 5, fold)) { // add.w output.form = 0; output.opcode = 1048576; diff --git a/assembler/loongarch64/vex.ws b/assembler/loongarch64/vex.ws new file mode 100644 index 0000000..cc9d6c6 --- /dev/null +++ b/assembler/loongarch64/vex.ws @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_wave_loongarch64", + version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + dependencies = [{ name = "whale_wave_assembler", path = ".." }], + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/assembler/meson.build b/assembler/meson.build index 9e82762..eb43228 100644 --- a/assembler/meson.build +++ b/assembler/meson.build @@ -3,55 +3,26 @@ subdir('asmobj') wave_assembler_all_dependencies = [] wave_assembler_dependencies = [] wave_assembler_directory = get_option('wave-assembler-dir') -if wave_assembler_directory == '' and wave_source != '' +if wave_assembler_directory == '' and not get_option('rust-reference') wave_assembler_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_wave_assembler.lib' : 'libwhale_wave_assembler.a' - arguments = ['--module', 'common', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif wave_assembler_module = custom_target('wave-assembler', - output: [archive_name, 'wave-assembler.meta', 'provenance.json'], - command: [python, files('../tools/build_wave_assembler.py'), arguments], - depend_files: files( - 'src/lib.rs', - 'model.wave', - 'unicode.wave', - 'numeric.wave', - 'output.wave', - 'lexer.wave', - 'fixed_model.wave', - 'fixed_text.wave', - 'fixed_numbers.wave', - 'fixed_operands.wave', - 'fixed_namespace.wave', - 'fixed_relative.wave', - 'fixed_scalar.wave', - 'fixed_source.wave', - 'fixed_driver.wave', - 'src/tokens.rs', - 'src/tokens_wave.rs', - 'src/fixed.rs', - 'src/fixed_wave.rs', - '../tools/build_wave_assembler.py', - '../tools/wave_bootstrap.py', - 'build_support.rs', - ), - depends: wave_bootstrap, console: true) + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../tools/vex_module.py'), '--module', 'assembler', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/assembler', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../tools/vex_module.py', '../tools/wave_modules.py'), + build_always_stale: true, console: true) wave_assembler_dependencies += [wave_assembler_module] elif wave_assembler_directory != '' if not fs.is_absolute(wave_assembler_directory) error('-Dwave-assembler-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_wave_assembler.lib' : 'libwhale_wave_assembler.a' - foreach artifact : [archive_name, 'wave-assembler.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(wave_assembler_directory / artifact) error('Missing Wave assembler artifact: ' + (wave_assembler_directory / artifact)) endif @@ -74,6 +45,3 @@ wave_loongarch64_directory = '' if get_option('asm-loongarch64') subdir('loongarch64') endif -if wave_assembler_directory == '' and (wave_amd64_directory != '' or wave_aarch64_directory != '' or wave_riscv64_directory != '' or wave_loongarch64_directory != '') - error('Wave ISA modules require -Dwave-assembler-dir or a Wave source build.') -endif diff --git a/assembler/riscv64/build.rs b/assembler/riscv64/build.rs deleted file mode 100644 index d8053fc..0000000 --- a/assembler/riscv64/build.rs +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -const CFG: &str = "whale_wave_riscv64"; - -const ENV: &str = "WHALE_WAVE_RISCV64_DIR"; - -const LIBRARY: &str = "whale_wave_riscv64"; - -const METADATA: &str = "wave-riscv64.meta"; - -const ROOT_UP: usize = 2; - -const SOURCES: &[&str] = &[ - "assembler/model.wave", - "assembler/declarations.wave", - "assembler/fixed_model.wave", - "assembler/fixed_declarations.wave", - "assembler/riscv64/registers.wave", - "assembler/riscv64/operands.wave", - "assembler/riscv64/encoding.wave", - "assembler/riscv64/encoder.wave", - "assembler/riscv64/parser.wave", - "assembler/riscv64/entry.wave", -]; - -const ABI_SOURCES: &[&str] = &[ - "assembler/riscv64/src/wave.rs", - "assembler/riscv64/src/lib.rs", - "assembler/riscv64/src/encoder.rs", - "assembler/riscv64/src/parser.rs", -]; -include!("../build_support.rs"); diff --git a/assembler/riscv64/meson.build b/assembler/riscv64/meson.build index b9bca78..c71d36a 100644 --- a/assembler/riscv64/meson.build +++ b/assembler/riscv64/meson.build @@ -1,50 +1,26 @@ # SPDX-License-Identifier: MPL-2.0 wave_riscv64_dependencies = [] wave_riscv64_directory = get_option('wave-riscv64-dir') -if wave_riscv64_directory == '' and wave_source != '' +if wave_riscv64_directory == '' and not get_option('rust-reference') wave_riscv64_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_wave_riscv64.lib' : 'libwhale_wave_riscv64.a' - arguments = ['--module', 'riscv64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif wave_riscv64_module = custom_target('wave-riscv64', - output: [archive_name, 'wave-riscv64.meta', 'provenance.json'], - command: [python, files('../../tools/build_wave_assembler.py'), arguments], - depend_files: files( - '../model.wave', - '../declarations.wave', - '../fixed_model.wave', - '../fixed_declarations.wave', - 'registers.wave', - 'operands.wave', - 'encoding.wave', - 'encoder.wave', - 'parser.wave', - 'entry.wave', - 'src/wave.rs', - 'src/lib.rs', - 'src/encoder.rs', - 'src/parser.rs', - '../../tools/build_wave_assembler.py', - '../../tools/wave_bootstrap.py', - '../build_support.rs', - ), - depends: wave_bootstrap, console: true) + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../../tools/vex_module.py'), '--module', 'riscv64', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/riscv64', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../../tools/vex_module.py', '../../tools/wave_modules.py'), + build_always_stale: true, console: true) wave_riscv64_dependencies += [wave_riscv64_module] elif wave_riscv64_directory != '' if not fs.is_absolute(wave_riscv64_directory) error('-Dwave-riscv64-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_wave_riscv64.lib' : 'libwhale_wave_riscv64.a' - foreach artifact : [archive_name, 'wave-riscv64.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(wave_riscv64_directory / artifact) error('Missing Wave riscv64 artifact: ' + (wave_riscv64_directory / artifact)) endif diff --git a/assembler/riscv64/encoder.wave b/assembler/riscv64/src/encoder.wave similarity index 93% rename from assembler/riscv64/encoder.wave rename to assembler/riscv64/src/encoder.wave index 9468a83..9ccc910 100644 --- a/assembler/riscv64/encoder.wave +++ b/assembler/riscv64/src/encoder.wave @@ -1,4 +1,35 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedContext, + FixedInstruction, + FixedResult, + FixedText, +}; +import("whale_wave_riscv64::encoding")::{ + rv_branch_bits, + rv_i, + rv_jump_bits, + rv_r, + rv_store, + rv_upper, +}; +import("whale_wave_riscv64::operands")::{rv_fence, rv_memory, rv_reg}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_count") fun asm_fixed_count(instruction: ptr, count: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_displacement") fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, + output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_pc_relative") fun asm_fixed_pc_relative(context: ptr, text: FixedText, + code: u64, output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_signed") fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_unsigned") fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_word") fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; + // The supported RV64I instruction inventory; no extension is inferred. struct RvOpcode { form: u64; @@ -539,7 +570,7 @@ fun rv_branch(context: ptr, text: FixedText, f3: u64, rs1: u64, return true; } -fun rv_encode(instruction: ptr, context: ptr, +pub fun rv_encode(instruction: ptr, context: ptr, result: ptr) -> bool { var operation: RvOpcode; if (!asm_fixed_charge(result, instruction.mnemonic.count)) { diff --git a/assembler/riscv64/encoding.wave b/assembler/riscv64/src/encoding.wave similarity index 69% rename from assembler/riscv64/encoding.wave rename to assembler/riscv64/src/encoding.wave index 56a8574..eedb7aa 100644 --- a/assembler/riscv64/encoding.wave +++ b/assembler/riscv64/src/encoding.wave @@ -1,30 +1,30 @@ // SPDX-License-Identifier: MPL-2.0 // RV64I field packing after operand validation; results are exactly 32 bits. -fun rv_r(opcode: u64, f3: u64, f7: u64, rd: u64, rs1: u64, rs2: u64) -> u64 { +pub fun rv_r(opcode: u64, f3: u64, f7: u64, rd: u64, rs1: u64, rs2: u64) -> u64 { return (opcode | (rd << 7) | (f3 << 12) | (rs1 << 15) | (rs2 << 20) | (f7 << 25)) & 4294967295; } -fun rv_i(opcode: u64, f3: u64, rd: u64, rs1: u64, immediate: u64) -> u64 { +pub fun rv_i(opcode: u64, f3: u64, rd: u64, rs1: u64, immediate: u64) -> u64 { return (opcode | (rd << 7) | (f3 << 12) | (rs1 << 15) | (immediate << 20)) & 4294967295; } -fun rv_store(f3: u64, rs1: u64, rs2: u64, immediate: u64) -> u64 { +pub fun rv_store(f3: u64, rs1: u64, rs2: u64, immediate: u64) -> u64 { return (35 | ((immediate & 31) << 7) | (f3 << 12) | (rs1 << 15) | (rs2 << 20) | ((immediate >> 5) << 25)) & 4294967295; } -fun rv_upper(opcode: u64, rd: u64, immediate: u64) -> u64 { +pub fun rv_upper(opcode: u64, rd: u64, immediate: u64) -> u64 { return (opcode | (rd << 7) | ((immediate & 1048575) << 12)) & 4294967295; } -fun rv_jump_bits(rd: u64, displacement: u64) -> u64 { +pub fun rv_jump_bits(rd: u64, displacement: u64) -> u64 { return (111 | (rd << 7) | (((displacement >> 20) & 1) << 31) | (((displacement >> 1) & 1023) << 21) | (((displacement >> 11) & 1) << 20) | (((displacement >> 12) & 255) << 12)) & 4294967295; } -fun rv_branch_bits(f3: u64, rs1: u64, rs2: u64, displacement: u64) -> u64 { +pub fun rv_branch_bits(f3: u64, rs1: u64, rs2: u64, displacement: u64) -> u64 { return (99 | (((displacement >> 11) & 1) << 7) | (((displacement >> 1) & 15) << 8) | (f3 << 12) | (rs1 << 15) | (rs2 << 20) | (((displacement >> 5) & 63) << 25) | (((displacement >> 12) & 1) << 31)) & 4294967295; diff --git a/assembler/riscv64/entry.wave b/assembler/riscv64/src/entry.wave similarity index 66% rename from assembler/riscv64/entry.wave rename to assembler/riscv64/src/entry.wave index 6124387..d42e8f5 100644 --- a/assembler/riscv64/entry.wave +++ b/assembler/riscv64/src/entry.wave @@ -1,6 +1,24 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedContext, + FixedInput, + FixedInstruction, + FixedResult, + FixedState, +}; +import("whale_wave_riscv64::encoder")::{rv_encode}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_commit") fun asm_fixed_commit(state: ptr, word: u64, + result: ptr) -> bool; +extern(c, "asm_fixed_next") fun asm_fixed_next(state: ptr, instruction: ptr, + result: ptr) -> i32; +extern(c, "asm_fixed_prepare") fun asm_fixed_prepare(packet: ptr, state: ptr, + result: ptr) -> bool; +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + // The source driver is appended once its shared prepare/next/commit ABI is ready. -export(c) fun whale_riscv64_instruction(instruction: ptr, +pub export(c) fun whale_riscv64_instruction(instruction: ptr, context: ptr, result: ptr) -> i32 { if (result == null) { return 2; @@ -28,7 +46,7 @@ export(c) fun whale_riscv64_instruction(instruction: ptr, return 0; } -export(c) fun whale_riscv64_entry(packet: ptr, result: ptr) -> i32 { +pub export(c) fun whale_riscv64_entry(packet: ptr, result: ptr) -> i32 { if (packet == null || result == null) { return 2; } @@ -64,6 +82,6 @@ export(c) fun whale_riscv64_entry(packet: ptr, result: ptr u64 { +pub export(c) fun whale_riscv64_module_identity() -> u64 { return 6289348675459241473; } diff --git a/assembler/riscv64/src/lib.wave b/assembler/riscv64/src/lib.wave new file mode 100644 index 0000000..4013c62 --- /dev/null +++ b/assembler/riscv64/src/lib.wave @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit role modules; Vex compiles this package without source concatenation. +import("./encoder.wave" as encoder); +import("./encoding.wave" as encoding); +import("./entry.wave" as entry); +import("./operands.wave" as operands); +import("./parser.wave" as parser); +import("./registers.wave" as registers); diff --git a/assembler/riscv64/operands.wave b/assembler/riscv64/src/operands.wave similarity index 75% rename from assembler/riscv64/operands.wave rename to assembler/riscv64/src/operands.wave index c405361..b8511ba 100644 --- a/assembler/riscv64/operands.wave +++ b/assembler/riscv64/src/operands.wave @@ -1,6 +1,16 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_riscv64::registers")::{rv_name, rv_register}; + +extern(c, "asm_fixed_charge") fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c, "asm_fixed_fail") fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c, "asm_fixed_signed") fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c, "asm_fixed_trim") fun asm_fixed_trim(text: FixedText) -> FixedText; + // Register, offset(base), and FENCE operands. Numeric policy is shared source. -fun rv_reg(text: FixedText, output: ptr, result: ptr) -> bool { +pub fun rv_reg(text: FixedText, output: ptr, result: ptr) -> bool { if (!asm_fixed_charge(result, text.count)) { return false; } @@ -13,7 +23,7 @@ fun rv_reg(text: FixedText, output: ptr, result: ptr) -> bool return true; } -fun rv_memory(text: FixedText, base: ptr, immediate: ptr, +pub fun rv_memory(text: FixedText, base: ptr, immediate: ptr, result: ptr) -> bool { var opening: u64 = 0; while (opening < text.count && text.data[opening] != 40) { @@ -55,7 +65,7 @@ fun rv_memory(text: FixedText, base: ptr, immediate: ptr, return asm_fixed_signed(offset, 12, immediate, result); } -fun rv_fence(text: FixedText, output: ptr, result: ptr) -> bool { +pub fun rv_fence(text: FixedText, output: ptr, result: ptr) -> bool { output[0] = 0; if (rv_name(text.data, text.count, 48, 1, false)) { return true; diff --git a/assembler/riscv64/parser.wave b/assembler/riscv64/src/parser.wave similarity index 66% rename from assembler/riscv64/parser.wave rename to assembler/riscv64/src/parser.wave index 67383c0..e828fe6 100644 --- a/assembler/riscv64/parser.wave +++ b/assembler/riscv64/src/parser.wave @@ -1,6 +1,15 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_riscv64::encoding")::{rv_branch_bits, rv_jump_bits}; +import("whale_wave_riscv64::operands")::{rv_fence, rv_memory, rv_reg}; + +extern(c, "asm_fixed_displacement") fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, + output: ptr, result: ptr) -> bool; +extern(c, "asm_fixed_result_init") fun asm_fixed_result_init(result: ptr, max_work: u64); +extern(c, "asm_span_valid") fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; + // Direct operand/branch boundaries keep native tests independent of source layout. -export(c) fun whale_riscv64_operand(mode: u64, text: ptr, +pub export(c) fun whale_riscv64_operand(mode: u64, text: ptr, result: ptr) -> i32 { if (result == null) { return 2; @@ -28,7 +37,7 @@ export(c) fun whale_riscv64_operand(mode: u64, text: ptr, return 0; } -export(c) fun whale_riscv64_branch(jump: u64, f3: u64, rs1: u64, rs2: u64, +pub export(c) fun whale_riscv64_branch(jump: u64, f3: u64, rs1: u64, rs2: u64, value: i64, result: ptr) -> i32 { if (result == null) { return 2; diff --git a/assembler/riscv64/registers.wave b/assembler/riscv64/src/registers.wave similarity index 96% rename from assembler/riscv64/registers.wave rename to assembler/riscv64/src/registers.wave index 9054f1c..46dd5d1 100644 --- a/assembler/riscv64/registers.wave +++ b/assembler/riscv64/src/registers.wave @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 // Exact ASCII register spellings after shared Unicode whitespace trimming. -fun rv_name(data: ptr, count: u64, word: u64, length: u64, fold: bool) -> bool { +pub fun rv_name(data: ptr, count: u64, word: u64, length: u64, fold: bool) -> bool { if (count != length) { return false; } @@ -18,7 +18,7 @@ fun rv_name(data: ptr, count: u64, word: u64, length: u64, fold: bool) -> bo return true; } -fun rv_register(data: ptr, count: u64, output: ptr) -> bool { +pub fun rv_register(data: ptr, count: u64, output: ptr) -> bool { // zero if (rv_name(data, count, 1869768058, 4, true)) { output[0] = 0; diff --git a/assembler/riscv64/vex.ws b/assembler/riscv64/vex.ws new file mode 100644 index 0000000..5ab758d --- /dev/null +++ b/assembler/riscv64/vex.ws @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_wave_riscv64", + version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + dependencies = [{ name = "whale_wave_assembler", path = ".." }], + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/assembler/ast_model.wave b/assembler/src/ast.wave similarity index 83% rename from assembler/ast_model.wave rename to assembler/src/ast.wave index 5799e62..594c005 100644 --- a/assembler/ast_model.wave +++ b/assembler/src/ast.wave @@ -1,18 +1,18 @@ // SPDX-License-Identifier: MPL-2.0 // Borrowed structural AST records shared by AMD64 parsing and encoding. -struct AsmName { +pub struct AsmName { bytes: ptr; count: u64; } -struct AsmExpr { +pub struct AsmExpr { kind: u64; name: u64; low: u64; high: u64; } -struct AsmOperand { +pub struct AsmOperand { kind: u64; name: u64; low: u64; @@ -26,7 +26,7 @@ struct AsmOperand { symbol: u64; } -struct AsmItem { +pub struct AsmItem { kind: u64; name: u64; aux: u64; @@ -36,7 +36,7 @@ struct AsmItem { count: u64; } -struct AsmDirectiveValue { +pub struct AsmDirectiveValue { kind: u64; expression: AsmExpr; bytes: ptr; diff --git a/assembler/fixed_driver.wave b/assembler/src/fixed/driver.wave similarity index 93% rename from assembler/fixed_driver.wave rename to assembler/src/fixed/driver.wave index 863ba64..cfed236 100644 --- a/assembler/fixed_driver.wave +++ b/assembler/src/fixed/driver.wave @@ -1,4 +1,34 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedInput, + FixedInstruction, + FixedRecord, + FixedRelocation, + FixedResult, + FixedSection, + FixedState, + FixedText, +}; +import("whale_wave_assembler::fixed::namespace")::{asm_fixed_finish}; +import("whale_wave_assembler::fixed::relative")::{asm_fixed_expression}; +import("whale_wave_assembler::fixed::source")::{asm_fixed_source}; +import("whale_wave_assembler::fixed::text")::{ + asm_fixed_charge, + asm_fixed_fail, + asm_fixed_result_init, + asm_fixed_slice, + asm_fixed_space, + asm_fixed_trim, + asm_fixed_word, +}; +import("whale_wave_assembler::model")::{AsmWide}; +import("whale_wave_assembler::helpers::numeric")::{ + asm_number_fits_signed, + asm_number_fits_unsigned, + asm_power_two, + asm_span_valid, +}; + // Shared native preparation and publication; the owning ISA supplies each word. fun asm_fixed_packet_valid(packet: ptr, result: ptr) -> bool { if (packet == null || packet.mode > 1 || packet.hash_comments > 1 @@ -28,7 +58,7 @@ fun asm_fixed_packet_valid(packet: ptr, result: ptr) -> return true; } -export(c) fun asm_fixed_prepare(packet: ptr, state: ptr, +pub export(c) fun asm_fixed_prepare(packet: ptr, state: ptr, result: ptr) -> bool { if (result == null || packet == null || state == null) { return false; @@ -161,7 +191,7 @@ fun asm_fixed_data(state: ptr, record: ptr, return true; } -export(c) fun asm_fixed_next(state: ptr, instruction: ptr, +pub export(c) fun asm_fixed_next(state: ptr, instruction: ptr, result: ptr) -> i32 { if (state == null || instruction == null || result == null || state.packet == null) { return -1; @@ -243,7 +273,7 @@ export(c) fun asm_fixed_next(state: ptr, instruction: ptr, word: u64, +pub export(c) fun asm_fixed_commit(state: ptr, word: u64, result: ptr) -> bool { if (state == null || result == null || state.packet == null) { return false; @@ -386,7 +416,7 @@ fun asm_fixed_probe_line(text: FixedText, definitions: ptr, globals: ptr, hash_comments: u64, +pub export(c) fun whale_fixed_probe(source: ptr, hash_comments: u64, result: ptr) -> i32 { if (result == null || source == null) { return 2; diff --git a/assembler/fixed_model.wave b/assembler/src/fixed/model.wave similarity index 89% rename from assembler/fixed_model.wave rename to assembler/src/fixed/model.wave index b34c09a..d9d01aa 100644 --- a/assembler/fixed_model.wave +++ b/assembler/src/fixed/model.wave @@ -1,18 +1,18 @@ // SPDX-License-Identifier: MPL-2.0 // Borrowed fixed-width source records. Only the owning ISA selects opcodes. -struct FixedText { +pub struct FixedText { data: ptr; count: u64; } -struct FixedInstruction { +pub struct FixedInstruction { mnemonic: FixedText; operands: ptr; count: u64; fold: u64; } -struct FixedSymbol { +pub struct FixedSymbol { name: FixedText; section: u64; offset: u64; @@ -22,7 +22,7 @@ struct FixedSymbol { flags: u64; } -struct FixedRelocation { +pub struct FixedRelocation { section: u64; offset: u64; symbol: u64; @@ -30,7 +30,7 @@ struct FixedRelocation { addend: i64; } -struct FixedContext { +pub struct FixedContext { source: FixedText; namespace: FixedText; symbols: ptr; @@ -44,7 +44,7 @@ struct FixedContext { relocation_capacity: u64; } -struct FixedResult { +pub struct FixedResult { status: u64; error: u64; start: u64; @@ -67,7 +67,7 @@ struct FixedResult { max_work: u64; } -struct FixedSection { +pub struct FixedSection { name: FixedText; kind: u64; align: u64; @@ -75,7 +75,7 @@ struct FixedSection { first: u64; } -struct FixedRecord { +pub struct FixedRecord { section: u64; offset: u64; start: u64; @@ -89,13 +89,13 @@ struct FixedRecord { mnemonic: FixedText; } -struct FixedGlobal { +pub struct FixedGlobal { start: u64; end: u64; line: u64; } -struct FixedInput { +pub struct FixedInput { source: FixedText; namespace: FixedText; hash_comments: u64; @@ -123,7 +123,7 @@ struct FixedInput { byte_capacity: u64; } -struct FixedState { +pub struct FixedState { packet: ptr; context: FixedContext; section_count: u64; diff --git a/assembler/fixed_namespace.wave b/assembler/src/fixed/namespace.wave similarity index 92% rename from assembler/fixed_namespace.wave rename to assembler/src/fixed/namespace.wave index 5e1f043..d7bcb77 100644 --- a/assembler/fixed_namespace.wave +++ b/assembler/src/fixed/namespace.wave @@ -1,4 +1,25 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedContext, + FixedGlobal, + FixedRecord, + FixedResult, + FixedSection, + FixedState, + FixedSymbol, + FixedText, +}; +import("whale_wave_assembler::fixed::numbers")::{asm_fixed_identifier}; +import("whale_wave_assembler::fixed::text")::{ + asm_fixed_charge, + asm_fixed_equal, + asm_fixed_fail, + asm_fixed_word, +}; +import("whale_wave_assembler::model")::{AsmOutputGrowth}; +import("whale_wave_assembler::helpers::numeric")::{asm_power_two, asm_span_valid}; +import("whale_wave_assembler::helpers::output")::{asm_output_grow}; + // Indexed ASCII symbols; no concrete ISA or opcode is referenced here. fun asm_fixed_hash(text: FixedText, result: ptr) -> u64 { var hash: u64 = 14695981039346656037; @@ -51,7 +72,7 @@ fun asm_fixed_slot(context: ptr, name: FixedText, return context.table_capacity; } -export(c) fun asm_fixed_lookup(context: ptr, name: FixedText, +pub export(c) fun asm_fixed_lookup(context: ptr, name: FixedText, result: ptr) -> u64 { var slot: u64 = 0; if (context.symbol_count == 0) { @@ -67,7 +88,7 @@ export(c) fun asm_fixed_lookup(context: ptr, name: FixedText, return context.table[slot]; } -export(c) fun whale_fixed_context_index(context: ptr, +pub export(c) fun whale_fixed_context_index(context: ptr, result: ptr) -> i32 { var at: u64 = 0; var slot: u64 = 0; @@ -111,7 +132,7 @@ export(c) fun whale_fixed_context_index(context: ptr, return result.status as i32; } -export(c) fun asm_fixed_symbol(state: ptr, name: FixedText, kind: u64, +pub export(c) fun asm_fixed_symbol(state: ptr, name: FixedText, kind: u64, result: ptr) -> u64 { var slot: u64 = 0; var index: u64 = 0; @@ -232,7 +253,7 @@ fun asm_fixed_section_equal(left: FixedText, right: FixedText) -> bool { return asm_fixed_equal(left, right, 0); } -export(c) fun asm_fixed_section(state: ptr, name: FixedText, +pub export(c) fun asm_fixed_section(state: ptr, name: FixedText, result: ptr) -> bool { var index: u64 = 0; var kind: u64 = 1; @@ -283,7 +304,7 @@ export(c) fun asm_fixed_section(state: ptr, name: FixedText, return true; } -export(c) fun asm_fixed_record(state: ptr, record: ptr, +pub export(c) fun asm_fixed_record(state: ptr, record: ptr, result: ptr) -> bool { var section: ptr = &state.packet.sections[state.selected]; var growth: AsmOutputGrowth; @@ -366,7 +387,7 @@ fun asm_fixed_sift(state: ptr, start: u64, end: u64, } } -export(c) fun asm_fixed_finish(state: ptr, result: ptr) -> bool { +pub export(c) fun asm_fixed_finish(state: ptr, result: ptr) -> bool { var at: u64 = 0; var end: u64 = state.symbol_count; var temporary: u64 = 0; diff --git a/assembler/fixed_numbers.wave b/assembler/src/fixed/numbers.wave similarity index 86% rename from assembler/fixed_numbers.wave rename to assembler/src/fixed/numbers.wave index 79873b1..d6094cb 100644 --- a/assembler/fixed_numbers.wave +++ b/assembler/src/fixed/numbers.wave @@ -1,6 +1,22 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_assembler::fixed::text")::{ + asm_fixed_charge, + asm_fixed_fail, + asm_fixed_slice, + asm_fixed_trim, +}; +import("whale_wave_assembler::lexer")::{asm_lex_digit}; +import("whale_wave_assembler::model")::{AsmWide}; +import("whale_wave_assembler::helpers::numeric")::{ + asm_number_fits_signed, + asm_number_fits_unsigned, + asm_number_neg_checked, + asm_span_valid, +}; + // Preserve the fixed-width assembly grammar's checked signed-i128 literals. -export(c) fun asm_fixed_integer(text: FixedText, output: ptr, +pub export(c) fun asm_fixed_integer(text: FixedText, output: ptr, result: ptr) -> bool { var value: FixedText = text; var negative: bool = false; @@ -100,7 +116,7 @@ export(c) fun asm_fixed_integer(text: FixedText, output: ptr, return true; } -export(c) fun asm_fixed_try_integer(text: FixedText, output: ptr, +pub export(c) fun asm_fixed_try_integer(text: FixedText, output: ptr, result: ptr) -> bool { var old_text: FixedText = result.text; var detail: u64 = result.detail; @@ -121,7 +137,7 @@ export(c) fun asm_fixed_try_integer(text: FixedText, output: ptr, return false; } -export(c) fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, +pub export(c) fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, result: ptr) -> bool { var value: AsmWide; var one: u64 = 1; @@ -142,7 +158,7 @@ export(c) fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, return true; } -export(c) fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, +pub export(c) fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, result: ptr) -> bool { var value: AsmWide; if (output == null) { @@ -162,7 +178,7 @@ export(c) fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, return true; } -export(c) fun asm_fixed_i64(text: FixedText, output: ptr, +pub export(c) fun asm_fixed_i64(text: FixedText, output: ptr, result: ptr) -> bool { var value: AsmWide; if (output == null) { @@ -179,7 +195,7 @@ export(c) fun asm_fixed_i64(text: FixedText, output: ptr, return true; } -export(c) fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, +pub export(c) fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, output: ptr, result: ptr) -> bool { var scaled: i64 = 0; var one: u64 = 1; @@ -202,7 +218,7 @@ export(c) fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, return true; } -export(c) fun asm_fixed_identifier(text: FixedText, result: ptr) -> bool { +pub export(c) fun asm_fixed_identifier(text: FixedText, result: ptr) -> bool { var at: u64 = 0; var octet: u64 = 0; if (!asm_span_valid(text.data, text.count, 1)) { diff --git a/assembler/fixed_operands.wave b/assembler/src/fixed/operands.wave similarity index 92% rename from assembler/fixed_operands.wave rename to assembler/src/fixed/operands.wave index 4b4cdf4..9c0ed91 100644 --- a/assembler/fixed_operands.wave +++ b/assembler/src/fixed/operands.wave @@ -1,4 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_assembler::fixed::text")::{ + asm_fixed_charge, + asm_fixed_fail, + asm_fixed_slice, + asm_fixed_trim, +}; +import("whale_wave_assembler::helpers::numeric")::{asm_span_valid}; + // Balanced operand splitting uses a small fast stack and bounded rescans only // beyond 64 nesting levels. A count probe never needs an allocation callback. fun asm_fixed_operands_inner(text: FixedText, output: ptr, capacity: u64, @@ -124,7 +133,7 @@ fun asm_fixed_operands_inner(text: FixedText, output: ptr, capacity: return true; } -export(c) fun asm_fixed_operands(text: FixedText, output: ptr, capacity: u64, +pub export(c) fun asm_fixed_operands(text: FixedText, output: ptr, capacity: u64, count: ptr, result: ptr) -> bool { var needed: u64 = 0; if (count == null || (output == null && capacity != 0)) { diff --git a/assembler/fixed_relative.wave b/assembler/src/fixed/relative.wave similarity index 82% rename from assembler/fixed_relative.wave rename to assembler/src/fixed/relative.wave index 55f51d6..be2dc86 100644 --- a/assembler/fixed_relative.wave +++ b/assembler/src/fixed/relative.wave @@ -1,6 +1,33 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{ + FixedContext, + FixedRelocation, + FixedResult, + FixedSymbol, + FixedText, +}; +import("whale_wave_assembler::fixed::namespace")::{asm_fixed_lookup}; +import("whale_wave_assembler::fixed::numbers")::{ + asm_fixed_identifier, + asm_fixed_integer, + asm_fixed_try_integer, +}; +import("whale_wave_assembler::fixed::text")::{ + asm_fixed_charge, + asm_fixed_fail, + asm_fixed_slice, + asm_fixed_trim, +}; +import("whale_wave_assembler::model")::{AsmWide}; +import("whale_wave_assembler::helpers::numeric")::{ + asm_number_add_checked, + asm_number_fits_signed, + asm_number_sub_checked, + asm_span_valid, +}; + // Resolve one optional symbol/addend, retaining opaque ISA relocation codes. -export(c) fun asm_fixed_expression(context: ptr, text: FixedText, +pub export(c) fun asm_fixed_expression(context: ptr, text: FixedText, number: ptr, symbol: ptr, addend: ptr, result: ptr) -> bool { var value: FixedText = text; var name: FixedText; @@ -59,7 +86,7 @@ export(c) fun asm_fixed_expression(context: ptr, text: FixedText, return result.status == 0; } -export(c) fun asm_fixed_pc_relative(context: ptr, text: FixedText, +pub export(c) fun asm_fixed_pc_relative(context: ptr, text: FixedText, code: u64, output: ptr, result: ptr) -> bool { var number: AsmWide; var addition: AsmWide; @@ -122,7 +149,7 @@ export(c) fun asm_fixed_pc_relative(context: ptr, text: FixedText, return true; } -export(c) fun whale_fixed_relative(context: ptr, text: ptr, +pub export(c) fun whale_fixed_relative(context: ptr, text: ptr, code: u64, result: ptr) -> i32 { var value: i64 = 0; if (result == null || context == null || text == null) { diff --git a/assembler/fixed_scalar.wave b/assembler/src/fixed/scalar.wave similarity index 72% rename from assembler/fixed_scalar.wave rename to assembler/src/fixed/scalar.wave index 1d9c663..d90b7c1 100644 --- a/assembler/fixed_scalar.wave +++ b/assembler/src/fixed/scalar.wave @@ -1,6 +1,16 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedResult, FixedText}; +import("whale_wave_assembler::fixed::numbers")::{ + asm_fixed_displacement, + asm_fixed_integer, + asm_fixed_signed, + asm_fixed_unsigned, +}; +import("whale_wave_assembler::fixed::operands")::{asm_fixed_operands}; +import("whale_wave_assembler::model")::{AsmWide}; + // Pointer-only C wrappers keep host transport independent of struct ABI lowering. -export(c) fun whale_fixed_scalar(mode: u64, text: ptr, bits: u64, +pub export(c) fun whale_fixed_scalar(mode: u64, text: ptr, bits: u64, value: i64, alignment: i64, result: ptr) -> i32 { var number: AsmWide; var word: u64 = 0; @@ -33,7 +43,7 @@ export(c) fun whale_fixed_scalar(mode: u64, text: ptr, bits: u64, return result.status as i32; } -export(c) fun whale_fixed_operands(text: ptr, output: ptr, +pub export(c) fun whale_fixed_operands(text: ptr, output: ptr, capacity: u64, count: ptr, result: ptr) -> i32 { if (result == null || text == null) { return 2; diff --git a/assembler/fixed_source.wave b/assembler/src/fixed/source.wave similarity index 92% rename from assembler/fixed_source.wave rename to assembler/src/fixed/source.wave index 3f9e6cd..5267c8c 100644 --- a/assembler/fixed_source.wave +++ b/assembler/src/fixed/source.wave @@ -1,4 +1,23 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedRecord, FixedResult, FixedState, FixedText}; +import("whale_wave_assembler::fixed::namespace")::{ + asm_fixed_record, + asm_fixed_section, + asm_fixed_symbol, +}; +import("whale_wave_assembler::fixed::numbers")::{asm_fixed_identifier, asm_fixed_integer}; +import("whale_wave_assembler::fixed::operands")::{asm_fixed_operands}; +import("whale_wave_assembler::fixed::text")::{ + asm_fixed_charge, + asm_fixed_fail, + asm_fixed_slice, + asm_fixed_space, + asm_fixed_trim, + asm_fixed_word, +}; +import("whale_wave_assembler::model")::{AsmWide}; +import("whale_wave_assembler::helpers::numeric")::{asm_number_fits_unsigned, asm_power_two}; + // First-pass fixed-width source grammar, shared by each owning ISA module. fun asm_fixed_source_operands(state: ptr, text: FixedText, first: ptr, count: ptr, result: ptr) -> bool { @@ -230,7 +249,7 @@ fun asm_fixed_source_statement(state: ptr, text: FixedText, return asm_fixed_source_record(state, mnemonic, tail, result); } -fun asm_fixed_source(state: ptr, result: ptr) -> bool { +pub fun asm_fixed_source(state: ptr, result: ptr) -> bool { var source: FixedText = state.packet.source; var line_start: u64 = 0; var line_end: u64 = 0; diff --git a/assembler/fixed_text.wave b/assembler/src/fixed/text.wave similarity index 82% rename from assembler/fixed_text.wave rename to assembler/src/fixed/text.wave index 0767a0f..c82424b 100644 --- a/assembler/fixed_text.wave +++ b/assembler/src/fixed/text.wave @@ -1,6 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::fixed::model")::{FixedInstruction, FixedResult, FixedText}; +import("whale_wave_assembler::helpers::numeric")::{asm_span_valid}; + // Unicode White_Space is the property used by Rust str::trim/split_whitespace. -export(c) fun asm_fixed_space(text: FixedText, at: u64) -> u64 { +pub export(c) fun asm_fixed_space(text: FixedText, at: u64) -> u64 { if (at >= text.count) { return 0; } @@ -26,7 +29,7 @@ export(c) fun asm_fixed_space(text: FixedText, at: u64) -> u64 { return 0; } -fun asm_fixed_slice(text: FixedText, start: u64, end: u64) -> FixedText { +pub fun asm_fixed_slice(text: FixedText, start: u64, end: u64) -> FixedText { var output: FixedText; output.data = text.data; output.count = 0; @@ -37,7 +40,7 @@ fun asm_fixed_slice(text: FixedText, start: u64, end: u64) -> FixedText { return output; } -export(c) fun asm_fixed_trim(text: FixedText) -> FixedText { +pub export(c) fun asm_fixed_trim(text: FixedText) -> FixedText { var start: u64 = 0; var end: u64 = text.count; var width: u64 = 0; @@ -68,7 +71,7 @@ export(c) fun asm_fixed_trim(text: FixedText) -> FixedText { return asm_fixed_slice(text, start, end); } -export(c) fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool { +pub export(c) fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool { if (text.count != count || count > 8 || fold > 1 || !asm_span_valid(text.data, text.count, 1)) { return false; @@ -88,7 +91,7 @@ export(c) fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) return true; } -export(c) fun asm_fixed_equal(left: FixedText, right: FixedText, fold: u64) -> bool { +pub export(c) fun asm_fixed_equal(left: FixedText, right: FixedText, fold: u64) -> bool { if (left.count != right.count || fold > 1 || !asm_span_valid(left.data, left.count, 1) || !asm_span_valid(right.data, right.count, 1)) { @@ -116,7 +119,7 @@ export(c) fun asm_fixed_equal(left: FixedText, right: FixedText, fold: u64) -> b return true; } -export(c) fun asm_fixed_result_init(result: ptr, max_work: u64) { +pub export(c) fun asm_fixed_result_init(result: ptr, max_work: u64) { result.status = 0; result.error = 0; result.start = 0; @@ -140,7 +143,7 @@ export(c) fun asm_fixed_result_init(result: ptr, max_work: u64) { result.max_work = max_work; } -export(c) fun asm_fixed_fail(result: ptr, code: u64, +pub export(c) fun asm_fixed_fail(result: ptr, code: u64, text: FixedText, detail: u64) -> bool { if (result.status == 0) { result.status = 1; @@ -151,7 +154,7 @@ export(c) fun asm_fixed_fail(result: ptr, code: u64, return false; } -export(c) fun asm_fixed_charge(result: ptr, units: u64) -> bool { +pub export(c) fun asm_fixed_charge(result: ptr, units: u64) -> bool { if (result.status != 0) { return false; } @@ -162,7 +165,7 @@ export(c) fun asm_fixed_charge(result: ptr, units: u64) -> bool { return true; } -export(c) fun asm_fixed_count(instruction: ptr, count: u64, +pub export(c) fun asm_fixed_count(instruction: ptr, count: u64, result: ptr) -> bool { if (result.status != 0) { return false; diff --git a/assembler/numeric.wave b/assembler/src/helpers/numeric.wave similarity index 80% rename from assembler/numeric.wave rename to assembler/src/helpers/numeric.wave index 9cf0970..97fbdeb 100644 --- a/assembler/numeric.wave +++ b/assembler/src/helpers/numeric.wave @@ -1,16 +1,18 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::model")::{AsmWide}; + // Exact checked signed arithmetic over two caller-owned words. -export(c) fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool { +pub export(c) fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool { return width != 0 && count <= 9223372036854775807 / width && (count == 0 || data != null) && count * width <= 18446744073709551615 - (data as u64); } -export(c) fun asm_power_two(value: u64) -> bool { +pub export(c) fun asm_power_two(value: u64) -> bool { return value != 0 && (value & (value - 1)) == 0; } -export(c) fun asm_align_up(size: u64, align: u64, output: ptr) -> bool { +pub export(c) fun asm_align_up(size: u64, align: u64, output: ptr) -> bool { if (!asm_power_two(align) || output == null || size > 18446744073709551615 - (align - 1)) { return false; } @@ -18,7 +20,7 @@ export(c) fun asm_align_up(size: u64, align: u64, output: ptr) -> bool { return true; } -export(c) fun asm_number_add_checked(a: ptr, b: ptr, +pub export(c) fun asm_number_add_checked(a: ptr, b: ptr, output: ptr) -> bool { if (a == null || b == null || output == null) { return false; @@ -38,7 +40,7 @@ export(c) fun asm_number_add_checked(a: ptr, b: ptr, return true; } -export(c) fun asm_number_neg_checked(value: ptr, output: ptr) -> bool { +pub export(c) fun asm_number_neg_checked(value: ptr, output: ptr) -> bool { if (value == null || output == null || (value.low == 0 && value.high == 9223372036854775808)) { return false; @@ -50,7 +52,7 @@ export(c) fun asm_number_neg_checked(value: ptr, output: ptr) return true; } -export(c) fun asm_number_sub_checked(a: ptr, b: ptr, +pub export(c) fun asm_number_sub_checked(a: ptr, b: ptr, output: ptr) -> bool { if (a == null || b == null || output == null) { return false; @@ -69,7 +71,7 @@ export(c) fun asm_number_sub_checked(a: ptr, b: ptr, return true; } -export(c) fun asm_number_fits_signed(value: ptr, bits: u64) -> bool { +pub export(c) fun asm_number_fits_signed(value: ptr, bits: u64) -> bool { if (value == null || bits == 0 || bits > 128) { return false; } @@ -87,7 +89,7 @@ export(c) fun asm_number_fits_signed(value: ptr, bits: u64) -> bool { return value.high < top || value.high >= all - top + 1; } -export(c) fun asm_number_fits_unsigned(value: ptr, bits: u64) -> bool { +pub export(c) fun asm_number_fits_unsigned(value: ptr, bits: u64) -> bool { if (value == null || bits == 0 || bits > 128) { return false; } diff --git a/assembler/output.wave b/assembler/src/helpers/output.wave similarity index 78% rename from assembler/output.wave rename to assembler/src/helpers/output.wave index a45f47d..ed9e6eb 100644 --- a/assembler/output.wave +++ b/assembler/src/helpers/output.wave @@ -1,7 +1,10 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::model")::{AsmOutputGrowth}; +import("whale_wave_assembler::helpers::numeric")::{asm_align_up, asm_power_two}; + // Output accounting is independent of instruction syntax and relocation kinds. // Logical growth reserves sparse storage without allocating materialized bytes. -export(c) fun asm_output_grow(materialized: u64, section: u64, extra: u64, +pub export(c) fun asm_output_grow(materialized: u64, section: u64, extra: u64, limit: u64, logical: u64, output: ptr) -> i32 { if (output == null || logical > 1 || materialized > limit) { return 3; @@ -24,7 +27,7 @@ export(c) fun asm_output_grow(materialized: u64, section: u64, extra: u64, return 0; } -export(c) fun asm_output_align(materialized: u64, section: u64, alignment: u64, +pub export(c) fun asm_output_align(materialized: u64, section: u64, alignment: u64, limit: u64, logical: u64, output: ptr) -> i32 { var padded: u64 = 0; if (!asm_power_two(alignment)) { diff --git a/assembler/unicode.wave b/assembler/src/helpers/unicode.wave similarity index 99% rename from assembler/unicode.wave rename to assembler/src/helpers/unicode.wave index 17965b9..e118528 100644 --- a/assembler/unicode.wave +++ b/assembler/src/helpers/unicode.wave @@ -848,7 +848,7 @@ const ASM_ALPHANUMERIC: array = [ 201552, 210041 ]; -export(c) fun asm_unicode_alphanumeric(cp: u64) -> bool { +pub export(c) fun asm_unicode_alphanumeric(cp: u64) -> bool { var low: u64 = 0; var high: u64 = 844; while (low < high) { diff --git a/assembler/lexer.wave b/assembler/src/lexer.wave similarity index 96% rename from assembler/lexer.wave rename to assembler/src/lexer.wave index 7be4a22..0d94707 100644 --- a/assembler/lexer.wave +++ b/assembler/src/lexer.wave @@ -1,4 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_assembler::model")::{AsmLexCursor, AsmLexResult, AsmToken}; +import("whale_wave_assembler::helpers::numeric")::{asm_span_valid}; +import("whale_wave_assembler::helpers::unicode")::{asm_unicode_alphanumeric}; + // Tokenization is native; allocation and public Rust enum construction are adapters. fun asm_lex_error(c: ptr, status: u64, reason: u64, start: u64, line: u64, column: u64, detail: u64) -> bool { @@ -90,7 +94,7 @@ fun asm_lex_identifier(cp: u64) -> bool { return cp == 95 || cp == 46 || asm_unicode_alphanumeric(cp); } -fun asm_lex_digit(cp: u64, radix: u64) -> u64 { +pub fun asm_lex_digit(cp: u64, radix: u64) -> u64 { if (cp >= 48 && cp <= 57 && cp - 48 < radix) { return cp - 48; } @@ -208,7 +212,7 @@ fun asm_lex_string(c: ptr, token: ptr, mode: u64, return true; } -export(c) fun whale_asm_lex(source: ptr, length: u64, max_tokens: u64, +pub export(c) fun whale_asm_lex(source: ptr, length: u64, max_tokens: u64, max_decoded: u64, max_work: u64, mode: u64, scratch_tokens: ptr, token_capacity: u64, scratch_decoded: ptr, decoded_capacity: u64, @@ -425,6 +429,6 @@ export(c) fun whale_asm_lex(source: ptr, length: u64, max_tokens: u64, } // Distinct compiled identity used by product composition checks. -export(c) fun whale_assembler_module_identity() -> u64 { +pub export(c) fun whale_assembler_module_identity() -> u64 { return 6289348675458126593; } diff --git a/assembler/src/lib.wave b/assembler/src/lib.wave new file mode 100644 index 0000000..9292191 --- /dev/null +++ b/assembler/src/lib.wave @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit role modules; Vex compiles this package without source concatenation. +import("./fixed/driver.wave" as fixed_driver); +import("./fixed/model.wave" as fixed_model); +import("./fixed/namespace.wave" as fixed_namespace); +import("./fixed/numbers.wave" as fixed_numbers); +import("./fixed/operands.wave" as fixed_operands); +import("./fixed/relative.wave" as fixed_relative); +import("./fixed/scalar.wave" as fixed_scalar); +import("./fixed/source.wave" as fixed_source); +import("./fixed/text.wave" as fixed_text); +import("./lexer.wave" as lexer); +import("./model.wave" as model); +import("./helpers/numeric.wave" as helpers_numeric); +import("./helpers/output.wave" as helpers_output); +import("./helpers/unicode.wave" as helpers_unicode); diff --git a/assembler/model.wave b/assembler/src/model.wave similarity index 85% rename from assembler/model.wave rename to assembler/src/model.wave index dbe296e..21ff999 100644 --- a/assembler/model.wave +++ b/assembler/src/model.wave @@ -1,11 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 // Internal borrowed records shared by assembler source modules. -struct AsmWide { +pub struct AsmWide { low: u64; high: u64; } -struct AsmToken { +pub struct AsmToken { kind: u64; start: u64; end: u64; @@ -19,7 +19,7 @@ struct AsmToken { high: u64; } -struct AsmLexResult { +pub struct AsmLexResult { status: u64; reason: u64; start: u64; @@ -32,7 +32,7 @@ struct AsmLexResult { work: u64; } -struct AsmLexCursor { +pub struct AsmLexCursor { source: ptr; length: u64; at: u64; @@ -45,7 +45,7 @@ struct AsmLexCursor { } -struct AsmOutputGrowth { +pub struct AsmOutputGrowth { materialized: u64; section: u64; } diff --git a/assembler/vex.ws b/assembler/vex.ws new file mode 100644 index 0000000..b2eecfb --- /dev/null +++ b/assembler/vex.ws @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_wave_assembler", + version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/backend-api/Cargo.toml b/backend-api/Cargo.toml index 6fd7ff2..107d478 100644 --- a/backend-api/Cargo.toml +++ b/backend-api/Cargo.toml @@ -5,6 +5,6 @@ edition = "2021" rust-version.workspace = true [dependencies] -ir = { path = "../ir" } +ir = { path = "../bindings/rust/ir" } target-spec = { path = "../target-spec" } diagnostic = { path = "../diagnostic" } diff --git a/assembler/aarch64/Cargo.toml b/bindings/rust/aarch64/Cargo.toml similarity index 67% rename from assembler/aarch64/Cargo.toml rename to bindings/rust/aarch64/Cargo.toml index baadf05..d6c667c 100644 --- a/assembler/aarch64/Cargo.toml +++ b/bindings/rust/aarch64/Cargo.toml @@ -9,5 +9,5 @@ default = [] rust-reference = ["assembler/rust-reference"] [dependencies] -assembler = { path = ".." } -target-spec = { path = "../../target-spec" } +assembler = { path = "../assembler" } +target-spec = { path = "../../../target-spec" } diff --git a/bindings/rust/aarch64/build.rs b/bindings/rust/aarch64/build.rs new file mode 100644 index 0000000..d50e693 --- /dev/null +++ b/bindings/rust/aarch64/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "aarch64"; + +const CFG: &str = "whale_wave_aarch64"; + +const ENV: &str = "WHALE_WAVE_AARCH64_DIR"; + +const LIBRARY: &str = "whale_wave_aarch64"; + +const SOURCE_ROOTS: &[&str] = &["assembler/aarch64", "assembler"]; +include!("../build_support.rs"); diff --git a/assembler/aarch64/src/encoder.rs b/bindings/rust/aarch64/src/encoder.rs similarity index 100% rename from assembler/aarch64/src/encoder.rs rename to bindings/rust/aarch64/src/encoder.rs diff --git a/assembler/aarch64/src/encoding/arithmetic.rs b/bindings/rust/aarch64/src/encoding/arithmetic.rs similarity index 100% rename from assembler/aarch64/src/encoding/arithmetic.rs rename to bindings/rust/aarch64/src/encoding/arithmetic.rs diff --git a/assembler/aarch64/src/encoding/branch.rs b/bindings/rust/aarch64/src/encoding/branch.rs similarity index 100% rename from assembler/aarch64/src/encoding/branch.rs rename to bindings/rust/aarch64/src/encoding/branch.rs diff --git a/assembler/aarch64/src/encoding/memory.rs b/bindings/rust/aarch64/src/encoding/memory.rs similarity index 100% rename from assembler/aarch64/src/encoding/memory.rs rename to bindings/rust/aarch64/src/encoding/memory.rs diff --git a/assembler/aarch64/src/encoding/mod.rs b/bindings/rust/aarch64/src/encoding/mod.rs similarity index 100% rename from assembler/aarch64/src/encoding/mod.rs rename to bindings/rust/aarch64/src/encoding/mod.rs diff --git a/assembler/aarch64/src/lib.rs b/bindings/rust/aarch64/src/lib.rs similarity index 100% rename from assembler/aarch64/src/lib.rs rename to bindings/rust/aarch64/src/lib.rs diff --git a/assembler/aarch64/src/parser.rs b/bindings/rust/aarch64/src/parser.rs similarity index 100% rename from assembler/aarch64/src/parser.rs rename to bindings/rust/aarch64/src/parser.rs diff --git a/assembler/aarch64/src/tables.rs b/bindings/rust/aarch64/src/tables.rs similarity index 100% rename from assembler/aarch64/src/tables.rs rename to bindings/rust/aarch64/src/tables.rs diff --git a/assembler/aarch64/src/wave.rs b/bindings/rust/aarch64/src/wave.rs similarity index 100% rename from assembler/aarch64/src/wave.rs rename to bindings/rust/aarch64/src/wave.rs diff --git a/assembler/aarch64/tests/encodings.rs b/bindings/rust/aarch64/tests/encodings.rs similarity index 100% rename from assembler/aarch64/tests/encodings.rs rename to bindings/rust/aarch64/tests/encodings.rs diff --git a/assembler/aarch64/tests/fixtures/encodings.tsv b/bindings/rust/aarch64/tests/fixtures/encodings.tsv similarity index 100% rename from assembler/aarch64/tests/fixtures/encodings.tsv rename to bindings/rust/aarch64/tests/fixtures/encodings.tsv diff --git a/assembler/aarch64/tests/fixtures/mov_wide.tsv b/bindings/rust/aarch64/tests/fixtures/mov_wide.tsv similarity index 100% rename from assembler/aarch64/tests/fixtures/mov_wide.tsv rename to bindings/rust/aarch64/tests/fixtures/mov_wide.tsv diff --git a/assembler/amd64/Cargo.toml b/bindings/rust/amd64/Cargo.toml similarity index 70% rename from assembler/amd64/Cargo.toml rename to bindings/rust/amd64/Cargo.toml index df5d2d4..b58e5b6 100644 --- a/assembler/amd64/Cargo.toml +++ b/bindings/rust/amd64/Cargo.toml @@ -9,7 +9,7 @@ default = [] rust-reference = ["assembler/rust-reference"] [dependencies] -assembler = { path = ".." } +assembler = { path = "../assembler" } [dev-dependencies] -diagnostic = { path = "../../diagnostic" } +diagnostic = { path = "../../../diagnostic" } diff --git a/bindings/rust/amd64/build.rs b/bindings/rust/amd64/build.rs new file mode 100644 index 0000000..738d62c --- /dev/null +++ b/bindings/rust/amd64/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "amd64"; + +const CFG: &str = "whale_wave_amd64"; + +const ENV: &str = "WHALE_WAVE_AMD64_DIR"; + +const LIBRARY: &str = "whale_wave_amd64"; + +const SOURCE_ROOTS: &[&str] = &["assembler/amd64", "assembler"]; +include!("../build_support.rs"); diff --git a/assembler/amd64/src/ast_model.rs b/bindings/rust/amd64/src/ast_model.rs similarity index 100% rename from assembler/amd64/src/ast_model.rs rename to bindings/rust/amd64/src/ast_model.rs diff --git a/assembler/amd64/src/encoder.rs b/bindings/rust/amd64/src/encoder.rs similarity index 100% rename from assembler/amd64/src/encoder.rs rename to bindings/rust/amd64/src/encoder.rs diff --git a/assembler/amd64/src/encoder_namespace_errors.rs b/bindings/rust/amd64/src/encoder_namespace_errors.rs similarity index 100% rename from assembler/amd64/src/encoder_namespace_errors.rs rename to bindings/rust/amd64/src/encoder_namespace_errors.rs diff --git a/assembler/amd64/src/encoder_reference.rs b/bindings/rust/amd64/src/encoder_reference.rs similarity index 100% rename from assembler/amd64/src/encoder_reference.rs rename to bindings/rust/amd64/src/encoder_reference.rs diff --git a/assembler/amd64/src/encoder_wave.rs b/bindings/rust/amd64/src/encoder_wave.rs similarity index 100% rename from assembler/amd64/src/encoder_wave.rs rename to bindings/rust/amd64/src/encoder_wave.rs diff --git a/assembler/amd64/src/encoding/address.rs b/bindings/rust/amd64/src/encoding/address.rs similarity index 100% rename from assembler/amd64/src/encoding/address.rs rename to bindings/rust/amd64/src/encoding/address.rs diff --git a/assembler/amd64/src/encoding/address_reference.rs b/bindings/rust/amd64/src/encoding/address_reference.rs similarity index 100% rename from assembler/amd64/src/encoding/address_reference.rs rename to bindings/rust/amd64/src/encoding/address_reference.rs diff --git a/assembler/amd64/src/encoding/mod.rs b/bindings/rust/amd64/src/encoding/mod.rs similarity index 100% rename from assembler/amd64/src/encoding/mod.rs rename to bindings/rust/amd64/src/encoding/mod.rs diff --git a/assembler/amd64/src/encoding/modrm.rs b/bindings/rust/amd64/src/encoding/modrm.rs similarity index 100% rename from assembler/amd64/src/encoding/modrm.rs rename to bindings/rust/amd64/src/encoding/modrm.rs diff --git a/assembler/amd64/src/encoding/rex.rs b/bindings/rust/amd64/src/encoding/rex.rs similarity index 100% rename from assembler/amd64/src/encoding/rex.rs rename to bindings/rust/amd64/src/encoding/rex.rs diff --git a/assembler/amd64/src/encoding/sib.rs b/bindings/rust/amd64/src/encoding/sib.rs similarity index 100% rename from assembler/amd64/src/encoding/sib.rs rename to bindings/rust/amd64/src/encoding/sib.rs diff --git a/assembler/amd64/src/lib.rs b/bindings/rust/amd64/src/lib.rs similarity index 100% rename from assembler/amd64/src/lib.rs rename to bindings/rust/amd64/src/lib.rs diff --git a/assembler/amd64/src/parser.rs b/bindings/rust/amd64/src/parser.rs similarity index 100% rename from assembler/amd64/src/parser.rs rename to bindings/rust/amd64/src/parser.rs diff --git a/assembler/amd64/src/parser_reference.rs b/bindings/rust/amd64/src/parser_reference.rs similarity index 100% rename from assembler/amd64/src/parser_reference.rs rename to bindings/rust/amd64/src/parser_reference.rs diff --git a/assembler/amd64/src/parser_wave.rs b/bindings/rust/amd64/src/parser_wave.rs similarity index 100% rename from assembler/amd64/src/parser_wave.rs rename to bindings/rust/amd64/src/parser_wave.rs diff --git a/assembler/amd64/src/tables.rs b/bindings/rust/amd64/src/tables.rs similarity index 100% rename from assembler/amd64/src/tables.rs rename to bindings/rust/amd64/src/tables.rs diff --git a/assembler/amd64/test/competitor_test.asm b/bindings/rust/amd64/test/competitor_test.asm similarity index 100% rename from assembler/amd64/test/competitor_test.asm rename to bindings/rust/amd64/test/competitor_test.asm diff --git a/assembler/amd64/test/fixtures.tsv b/bindings/rust/amd64/test/fixtures.tsv similarity index 100% rename from assembler/amd64/test/fixtures.tsv rename to bindings/rust/amd64/test/fixtures.tsv diff --git a/assembler/amd64/test/full_test.asm b/bindings/rust/amd64/test/full_test.asm similarity index 100% rename from assembler/amd64/test/full_test.asm rename to bindings/rust/amd64/test/full_test.asm diff --git a/assembler/amd64/test/massive/test_001.asm b/bindings/rust/amd64/test/massive/test_001.asm similarity index 100% rename from assembler/amd64/test/massive/test_001.asm rename to bindings/rust/amd64/test/massive/test_001.asm diff --git a/assembler/amd64/test/massive/test_002.asm b/bindings/rust/amd64/test/massive/test_002.asm similarity index 100% rename from assembler/amd64/test/massive/test_002.asm rename to bindings/rust/amd64/test/massive/test_002.asm diff --git a/assembler/amd64/test/massive/test_003.asm b/bindings/rust/amd64/test/massive/test_003.asm similarity index 100% rename from assembler/amd64/test/massive/test_003.asm rename to bindings/rust/amd64/test/massive/test_003.asm diff --git a/assembler/amd64/test/massive/test_004.asm b/bindings/rust/amd64/test/massive/test_004.asm similarity index 100% rename from assembler/amd64/test/massive/test_004.asm rename to bindings/rust/amd64/test/massive/test_004.asm diff --git a/assembler/amd64/test/massive/test_005.asm b/bindings/rust/amd64/test/massive/test_005.asm similarity index 100% rename from assembler/amd64/test/massive/test_005.asm rename to bindings/rust/amd64/test/massive/test_005.asm diff --git a/assembler/amd64/test/massive/test_006.asm b/bindings/rust/amd64/test/massive/test_006.asm similarity index 100% rename from assembler/amd64/test/massive/test_006.asm rename to bindings/rust/amd64/test/massive/test_006.asm diff --git a/assembler/amd64/test/massive/test_007.asm b/bindings/rust/amd64/test/massive/test_007.asm similarity index 100% rename from assembler/amd64/test/massive/test_007.asm rename to bindings/rust/amd64/test/massive/test_007.asm diff --git a/assembler/amd64/test/massive/test_008.asm b/bindings/rust/amd64/test/massive/test_008.asm similarity index 100% rename from assembler/amd64/test/massive/test_008.asm rename to bindings/rust/amd64/test/massive/test_008.asm diff --git a/assembler/amd64/test/massive/test_009.asm b/bindings/rust/amd64/test/massive/test_009.asm similarity index 100% rename from assembler/amd64/test/massive/test_009.asm rename to bindings/rust/amd64/test/massive/test_009.asm diff --git a/assembler/amd64/test/massive/test_010.asm b/bindings/rust/amd64/test/massive/test_010.asm similarity index 100% rename from assembler/amd64/test/massive/test_010.asm rename to bindings/rust/amd64/test/massive/test_010.asm diff --git a/assembler/amd64/test/mem_test.asm b/bindings/rust/amd64/test/mem_test.asm similarity index 100% rename from assembler/amd64/test/mem_test.asm rename to bindings/rust/amd64/test/mem_test.asm diff --git a/assembler/amd64/test/msg.asm b/bindings/rust/amd64/test/msg.asm similarity index 100% rename from assembler/amd64/test/msg.asm rename to bindings/rust/amd64/test/msg.asm diff --git a/assembler/amd64/test/test1.asm b/bindings/rust/amd64/test/test1.asm similarity index 100% rename from assembler/amd64/test/test1.asm rename to bindings/rust/amd64/test/test1.asm diff --git a/assembler/amd64/tests/address_modes.rs b/bindings/rust/amd64/tests/address_modes.rs similarity index 100% rename from assembler/amd64/tests/address_modes.rs rename to bindings/rust/amd64/tests/address_modes.rs diff --git a/assembler/amd64/tests/amd64_extension_conditions.rs b/bindings/rust/amd64/tests/amd64_extension_conditions.rs similarity index 100% rename from assembler/amd64/tests/amd64_extension_conditions.rs rename to bindings/rust/amd64/tests/amd64_extension_conditions.rs diff --git a/assembler/amd64/tests/amd64_scalar_forms.rs b/bindings/rust/amd64/tests/amd64_scalar_forms.rs similarity index 100% rename from assembler/amd64/tests/amd64_scalar_forms.rs rename to bindings/rust/amd64/tests/amd64_scalar_forms.rs diff --git a/assembler/amd64/tests/bss_storage.rs b/bindings/rust/amd64/tests/bss_storage.rs similarity index 100% rename from assembler/amd64/tests/bss_storage.rs rename to bindings/rust/amd64/tests/bss_storage.rs diff --git a/assembler/amd64/tests/diagnostic_boundary.rs b/bindings/rust/amd64/tests/diagnostic_boundary.rs similarity index 100% rename from assembler/amd64/tests/diagnostic_boundary.rs rename to bindings/rust/amd64/tests/diagnostic_boundary.rs diff --git a/assembler/amd64/tests/expression_overflow.rs b/bindings/rust/amd64/tests/expression_overflow.rs similarity index 100% rename from assembler/amd64/tests/expression_overflow.rs rename to bindings/rust/amd64/tests/expression_overflow.rs diff --git a/assembler/amd64/tests/forward_constants.rs b/bindings/rust/amd64/tests/forward_constants.rs similarity index 100% rename from assembler/amd64/tests/forward_constants.rs rename to bindings/rust/amd64/tests/forward_constants.rs diff --git a/assembler/amd64/tests/historical_fixtures.rs b/bindings/rust/amd64/tests/historical_fixtures.rs similarity index 100% rename from assembler/amd64/tests/historical_fixtures.rs rename to bindings/rust/amd64/tests/historical_fixtures.rs diff --git a/assembler/amd64/tests/input_validation.rs b/bindings/rust/amd64/tests/input_validation.rs similarity index 100% rename from assembler/amd64/tests/input_validation.rs rename to bindings/rust/amd64/tests/input_validation.rs diff --git a/assembler/amd64/tests/literals_and_memory_widths.rs b/bindings/rust/amd64/tests/literals_and_memory_widths.rs similarity index 100% rename from assembler/amd64/tests/literals_and_memory_widths.rs rename to bindings/rust/amd64/tests/literals_and_memory_widths.rs diff --git a/assembler/amd64/tests/resource_and_relaxation.rs b/bindings/rust/amd64/tests/resource_and_relaxation.rs similarity index 100% rename from assembler/amd64/tests/resource_and_relaxation.rs rename to bindings/rust/amd64/tests/resource_and_relaxation.rs diff --git a/assembler/amd64/tests/scalar_sse.rs b/bindings/rust/amd64/tests/scalar_sse.rs similarity index 100% rename from assembler/amd64/tests/scalar_sse.rs rename to bindings/rust/amd64/tests/scalar_sse.rs diff --git a/assembler/amd64/tests/sections_and_alignment.rs b/bindings/rust/amd64/tests/sections_and_alignment.rs similarity index 100% rename from assembler/amd64/tests/sections_and_alignment.rs rename to bindings/rust/amd64/tests/sections_and_alignment.rs diff --git a/assembler/amd64/tests/source_spans.rs b/bindings/rust/amd64/tests/source_spans.rs similarity index 100% rename from assembler/amd64/tests/source_spans.rs rename to bindings/rust/amd64/tests/source_spans.rs diff --git a/assembler/amd64/tests/statement_boundaries.rs b/bindings/rust/amd64/tests/statement_boundaries.rs similarity index 100% rename from assembler/amd64/tests/statement_boundaries.rs rename to bindings/rust/amd64/tests/statement_boundaries.rs diff --git a/assembler/amd64/tests/symbol_metadata.rs b/bindings/rust/amd64/tests/symbol_metadata.rs similarity index 100% rename from assembler/amd64/tests/symbol_metadata.rs rename to bindings/rust/amd64/tests/symbol_metadata.rs diff --git a/bindings/rust/asmobj/Cargo.toml b/bindings/rust/asmobj/Cargo.toml new file mode 100644 index 0000000..6361161 --- /dev/null +++ b/bindings/rust/asmobj/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "asmobj" +version = "0.1.0" +edition = "2021" +rust-version.workspace = true + +[dependencies] +assembler = { path = "../assembler" } +object = { path = "../../../object" } diff --git a/bindings/rust/asmobj/build.rs b/bindings/rust/asmobj/build.rs new file mode 100644 index 0000000..82cbeb4 --- /dev/null +++ b/bindings/rust/asmobj/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "asmobj"; + +const CFG: &str = "whale_asmobj"; + +const ENV: &str = "WHALE_ASMOBJ_DIR"; + +const LIBRARY: &str = "whale_asmobj"; + +const SOURCE_ROOTS: &[&str] = &["assembler/asmobj"]; +include!("../build_support.rs"); diff --git a/toolchain/src/assembly_object.rs b/bindings/rust/asmobj/src/lib.rs similarity index 100% rename from toolchain/src/assembly_object.rs rename to bindings/rust/asmobj/src/lib.rs diff --git a/toolchain/tests/assembly_object.rs b/bindings/rust/asmobj/tests/assembly_object.rs similarity index 99% rename from toolchain/tests/assembly_object.rs rename to bindings/rust/asmobj/tests/assembly_object.rs index 7dc63cb..3b71f64 100644 --- a/toolchain/tests/assembly_object.rs +++ b/bindings/rust/asmobj/tests/assembly_object.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 //! Independent public-contract cases for the complete Wave asmobj conversion. -use toolchain::assembly_object; +use asmobj as assembly_object; #[cfg(not(whale_asmobj))] #[test] diff --git a/assembler/Cargo.toml b/bindings/rust/assembler/Cargo.toml similarity index 62% rename from assembler/Cargo.toml rename to bindings/rust/assembler/Cargo.toml index 80deb6f..139c258 100644 --- a/assembler/Cargo.toml +++ b/bindings/rust/assembler/Cargo.toml @@ -9,5 +9,5 @@ default = [] rust-reference = [] [dependencies] -target-spec = { path = "../target-spec" } -diagnostic = { path = "../diagnostic" } +target-spec = { path = "../../../target-spec" } +diagnostic = { path = "../../../diagnostic" } diff --git a/bindings/rust/assembler/build.rs b/bindings/rust/assembler/build.rs new file mode 100644 index 0000000..7187e04 --- /dev/null +++ b/bindings/rust/assembler/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "assembler"; + +const CFG: &str = "whale_wave_assembler"; + +const ENV: &str = "WHALE_WAVE_ASSEMBLER_DIR"; + +const LIBRARY: &str = "whale_wave_assembler"; + +const SOURCE_ROOTS: &[&str] = &["assembler"]; +include!("../build_support.rs"); diff --git a/assembler/src/assembler.rs b/bindings/rust/assembler/src/assembler.rs similarity index 100% rename from assembler/src/assembler.rs rename to bindings/rust/assembler/src/assembler.rs diff --git a/assembler/src/ast.rs b/bindings/rust/assembler/src/ast.rs similarity index 100% rename from assembler/src/ast.rs rename to bindings/rust/assembler/src/ast.rs diff --git a/assembler/src/diagnostic.rs b/bindings/rust/assembler/src/diagnostic.rs similarity index 100% rename from assembler/src/diagnostic.rs rename to bindings/rust/assembler/src/diagnostic.rs diff --git a/assembler/src/error.rs b/bindings/rust/assembler/src/error.rs similarity index 100% rename from assembler/src/error.rs rename to bindings/rust/assembler/src/error.rs diff --git a/assembler/src/extension.rs b/bindings/rust/assembler/src/extension.rs similarity index 100% rename from assembler/src/extension.rs rename to bindings/rust/assembler/src/extension.rs diff --git a/assembler/src/fixed.rs b/bindings/rust/assembler/src/fixed.rs similarity index 100% rename from assembler/src/fixed.rs rename to bindings/rust/assembler/src/fixed.rs diff --git a/assembler/src/fixed_reference.rs b/bindings/rust/assembler/src/fixed_reference.rs similarity index 100% rename from assembler/src/fixed_reference.rs rename to bindings/rust/assembler/src/fixed_reference.rs diff --git a/assembler/src/fixed_wave.rs b/bindings/rust/assembler/src/fixed_wave.rs similarity index 100% rename from assembler/src/fixed_wave.rs rename to bindings/rust/assembler/src/fixed_wave.rs diff --git a/assembler/src/lib.rs b/bindings/rust/assembler/src/lib.rs similarity index 100% rename from assembler/src/lib.rs rename to bindings/rust/assembler/src/lib.rs diff --git a/assembler/src/tokens.rs b/bindings/rust/assembler/src/tokens.rs similarity index 100% rename from assembler/src/tokens.rs rename to bindings/rust/assembler/src/tokens.rs diff --git a/assembler/src/tokens_reference.rs b/bindings/rust/assembler/src/tokens_reference.rs similarity index 100% rename from assembler/src/tokens_reference.rs rename to bindings/rust/assembler/src/tokens_reference.rs diff --git a/assembler/src/tokens_wave.rs b/bindings/rust/assembler/src/tokens_wave.rs similarity index 100% rename from assembler/src/tokens_wave.rs rename to bindings/rust/assembler/src/tokens_wave.rs diff --git a/assembler/src/traits.rs b/bindings/rust/assembler/src/traits.rs similarity index 100% rename from assembler/src/traits.rs rename to bindings/rust/assembler/src/traits.rs diff --git a/assembler/src/unicode_reference.rs b/bindings/rust/assembler/src/unicode_reference.rs similarity index 100% rename from assembler/src/unicode_reference.rs rename to bindings/rust/assembler/src/unicode_reference.rs diff --git a/bindings/rust/build_support.rs b/bindings/rust/build_support.rs new file mode 100644 index 0000000..d51b213 --- /dev/null +++ b/bindings/rust/build_support.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MPL-2.0 +// Cargo links previously verified Vex results; it never prepares a compiler. +use std::{ + collections::BTreeMap, + env, fs, + io::Read, + path::{Path, PathBuf}, +}; + +fn update(value: u64, bytes: &[u8]) -> u64 { + bytes.iter().fold(value, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3)) +} + +fn file_hash(path: &Path, maximum: Option) -> String { + let mut file = fs::File::open(path) + .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display())); + assert!(file.metadata().unwrap().is_file(), "module artifact must be a regular file"); + let mut hash = 0xcbf29ce484222325; + let mut buffer = [0; 16384]; + let mut seen = 0u64; + loop { + let count = file.read(&mut buffer).expect("cannot read module artifact"); + if count == 0 { + return format!("{hash:016x}"); + } + seen += count as u64; + assert!(maximum.is_none_or(|limit| seen <= limit), "oversized module artifact"); + hash = update(hash, &buffer[..count]); + } +} + +fn collect(directory: &Path, extension: &str, files: &mut Vec) { + println!("cargo:rerun-if-changed={}", directory.display()); + for entry in fs::read_dir(directory).expect("missing module source directory") { + let path = entry.expect("cannot inspect module source").path(); + let kind = fs::symlink_metadata(&path).expect("cannot inspect module source").file_type(); + assert!(!kind.is_symlink(), "module sources must not contain links"); + if kind.is_dir() { + collect(&path, extension, files); + } else if path.extension().is_some_and(|value| value == extension) { + files.push(path); + } + } +} + +fn source_hash(root: &Path, mut paths: Vec) -> String { + paths.sort(); + paths.dedup(); + let mut hash = 0xcbf29ce484222325; + for path in paths { + println!("cargo:rerun-if-changed={}", path.display()); + let name = path + .strip_prefix(root) + .unwrap() + .to_str() + .expect("module paths require UTF-8") + .replace('\\', "/"); + hash = update(hash, name.as_bytes()); + hash = update(hash, &[0]); + hash = update( + hash, + &fs::read(&path).unwrap_or_else(|_| panic!("missing module input {}", path.display())), + ); + hash = update(hash, &[0]); + } + format!("{hash:016x}") +} + +fn main() { + println!("cargo:rustc-check-cfg=cfg({CFG})"); + println!("cargo:rerun-if-env-changed={ENV}"); + println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUST_REFERENCE"); + let Some(directory) = env::var_os(ENV) else { + assert!(MODULE == "asmobj" || env::var_os("CARGO_FEATURE_RUST_REFERENCE").is_some(), + "{MODULE} requires its Wave module; build with Meson/Vex or explicitly select rust-reference"); + return; + }; + let directory = + PathBuf::from(directory).canonicalize().expect("Wave artifact directory must exist"); + if matches!(MODULE, "amd64" | "aarch64" | "riscv64" | "loongarch64") { + assert!( + env::var_os("WHALE_WAVE_ASSEMBLER_DIR").is_some(), + "Wave ISA modules require WHALE_WAVE_ASSEMBLER_DIR for shared utilities" + ); + } + let manifest = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); + let root = manifest.join("../../..").canonicalize().unwrap(); + let target = env::var("TARGET").unwrap(); + let archive = directory.join(if target.contains("msvc") { + format!("{LIBRARY}.lib") + } else { + format!("lib{LIBRARY}.a") + }); + let metadata = directory.join("module.meta"); + let provenance = directory.join("provenance.json"); + for path in [&archive, &metadata, &provenance] { + println!("cargo:rerun-if-changed={}", path.display()); + } + let mut text = String::new(); + fs::File::open(&metadata) + .expect("missing Vex module metadata; build with Meson") + .take(4097) + .read_to_string(&mut text) + .expect("invalid Vex module metadata"); + assert!(text.len() <= 4096, "oversized Vex module metadata"); + let mut fields = BTreeMap::new(); + for line in text.lines() { + let (key, value) = line.split_once('=').expect("malformed Vex module metadata"); + assert!( + [ + "schema", + "target", + "wave_revision", + "opt_level", + "source_fnv64", + "abi_fnv64", + "archive_fnv64", + "provenance_fnv64" + ] + .contains(&key) + && fields.insert(key, value).is_none(), + "invalid Vex module metadata fields" + ); + } + assert_eq!(fields.len(), 8, "incomplete Vex module metadata"); + assert_eq!(fields.get("schema"), Some(&"3"), "unsupported Vex module metadata"); + assert_eq!( + fields.get("target"), + Some(&target.as_str()), + "Wave module executable-host target mismatch" + ); + let revision = fields.get("wave_revision").expect("missing compiler revision"); + assert!( + revision.len() == 40 + && revision.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)), + "invalid Wave nightly revision" + ); + assert!( + [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), + "unsupported Wave optimization level" + ); + let mut sources = vec![root.join("vex.ws"), root.join("vex.lock")]; + for directory in SOURCE_ROOTS { + collect(&root.join(directory).join("src"), "wave", &mut sources); + sources.push(root.join(directory).join("vex.ws")); + } + assert_eq!( + fields.get("source_fnv64"), + Some(&source_hash(&root, sources).as_str()), + "stale Wave source or Vex graph" + ); + let mut abi = vec![manifest.join("Cargo.toml")]; + collect(&manifest.join("src"), "rs", &mut abi); + assert_eq!( + fields.get("abi_fnv64"), + Some(&source_hash(&root, abi).as_str()), + "stale Rust/Wave ABI" + ); + assert_eq!( + fields.get("archive_fnv64"), + Some(&file_hash(&archive, None).as_str()), + "corrupt Wave archive" + ); + assert_eq!( + fields.get("provenance_fnv64"), + Some(&file_hash(&provenance, Some(16384)).as_str()), + "corrupt Wave provenance" + ); + println!("cargo:rustc-link-search=native={}", directory.display()); + println!("cargo:rustc-link-lib=static={LIBRARY}"); + println!("cargo:rustc-cfg={CFG}"); +} diff --git a/ir/Cargo.toml b/bindings/rust/ir/Cargo.toml similarity index 76% rename from ir/Cargo.toml rename to bindings/rust/ir/Cargo.toml index 540a7df..bbb9daa 100644 --- a/ir/Cargo.toml +++ b/bindings/rust/ir/Cargo.toml @@ -10,7 +10,7 @@ rust-reference = [] socket = ["dep:serde", "dep:serde_json"] [dependencies] -diagnostic = { path = "../diagnostic" } -target-spec = { path = "../target-spec" } +diagnostic = { path = "../../../diagnostic" } +target-spec = { path = "../../../target-spec" } serde_json = { version = "1", optional = true } serde = { version = "1", features = ["derive"], optional = true } diff --git a/bindings/rust/ir/build.rs b/bindings/rust/ir/build.rs new file mode 100644 index 0000000..fc9b449 --- /dev/null +++ b/bindings/rust/ir/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "ir"; + +const CFG: &str = "whale_wave_ir"; + +const ENV: &str = "WHALE_WAVE_IR_DIR"; + +const LIBRARY: &str = "whale_wave_ir"; + +const SOURCE_ROOTS: &[&str] = &["ir"]; +include!("../build_support.rs"); diff --git a/ir/examples/bytecode_workspace_probe.rs b/bindings/rust/ir/examples/bytecode_workspace_probe.rs similarity index 100% rename from ir/examples/bytecode_workspace_probe.rs rename to bindings/rust/ir/examples/bytecode_workspace_probe.rs diff --git a/ir/src/block.rs b/bindings/rust/ir/src/block.rs similarity index 100% rename from ir/src/block.rs rename to bindings/rust/ir/src/block.rs diff --git a/ir/src/builder.rs b/bindings/rust/ir/src/builder.rs similarity index 100% rename from ir/src/builder.rs rename to bindings/rust/ir/src/builder.rs diff --git a/ir/src/builder/body.rs b/bindings/rust/ir/src/builder/body.rs similarity index 100% rename from ir/src/builder/body.rs rename to bindings/rust/ir/src/builder/body.rs diff --git a/ir/src/builder/namespace.rs b/bindings/rust/ir/src/builder/namespace.rs similarity index 100% rename from ir/src/builder/namespace.rs rename to bindings/rust/ir/src/builder/namespace.rs diff --git a/ir/src/builder/wave.rs b/bindings/rust/ir/src/builder/wave.rs similarity index 100% rename from ir/src/builder/wave.rs rename to bindings/rust/ir/src/builder/wave.rs diff --git a/ir/src/bytecode.rs b/bindings/rust/ir/src/bytecode.rs similarity index 100% rename from ir/src/bytecode.rs rename to bindings/rust/ir/src/bytecode.rs diff --git a/ir/src/const_expr.rs b/bindings/rust/ir/src/const_expr.rs similarity index 100% rename from ir/src/const_expr.rs rename to bindings/rust/ir/src/const_expr.rs diff --git a/ir/src/constant.rs b/bindings/rust/ir/src/constant.rs similarity index 100% rename from ir/src/constant.rs rename to bindings/rust/ir/src/constant.rs diff --git a/ir/src/constant_wave.rs b/bindings/rust/ir/src/constant_wave.rs similarity index 100% rename from ir/src/constant_wave.rs rename to bindings/rust/ir/src/constant_wave.rs diff --git a/ir/src/diagnostic.rs b/bindings/rust/ir/src/diagnostic.rs similarity index 100% rename from ir/src/diagnostic.rs rename to bindings/rust/ir/src/diagnostic.rs diff --git a/ir/src/effects.rs b/bindings/rust/ir/src/effects.rs similarity index 100% rename from ir/src/effects.rs rename to bindings/rust/ir/src/effects.rs diff --git a/ir/src/effects_wave.rs b/bindings/rust/ir/src/effects_wave.rs similarity index 100% rename from ir/src/effects_wave.rs rename to bindings/rust/ir/src/effects_wave.rs diff --git a/ir/src/float.rs b/bindings/rust/ir/src/float.rs similarity index 100% rename from ir/src/float.rs rename to bindings/rust/ir/src/float.rs diff --git a/ir/src/float/arithmetic.rs b/bindings/rust/ir/src/float/arithmetic.rs similarity index 100% rename from ir/src/float/arithmetic.rs rename to bindings/rust/ir/src/float/arithmetic.rs diff --git a/ir/src/float/arithmetic_reference.rs b/bindings/rust/ir/src/float/arithmetic_reference.rs similarity index 100% rename from ir/src/float/arithmetic_reference.rs rename to bindings/rust/ir/src/float/arithmetic_reference.rs diff --git a/ir/src/float/conversions_reference.rs b/bindings/rust/ir/src/float/conversions_reference.rs similarity index 100% rename from ir/src/float/conversions_reference.rs rename to bindings/rust/ir/src/float/conversions_reference.rs diff --git a/ir/src/float/wave.rs b/bindings/rust/ir/src/float/wave.rs similarity index 100% rename from ir/src/float/wave.rs rename to bindings/rust/ir/src/float/wave.rs diff --git a/ir/src/fold_integer.rs b/bindings/rust/ir/src/fold_integer.rs similarity index 100% rename from ir/src/fold_integer.rs rename to bindings/rust/ir/src/fold_integer.rs diff --git a/ir/src/fold_integer_wave.rs b/bindings/rust/ir/src/fold_integer_wave.rs similarity index 100% rename from ir/src/fold_integer_wave.rs rename to bindings/rust/ir/src/fold_integer_wave.rs diff --git a/ir/src/function.rs b/bindings/rust/ir/src/function.rs similarity index 100% rename from ir/src/function.rs rename to bindings/rust/ir/src/function.rs diff --git a/ir/src/global_storage.rs b/bindings/rust/ir/src/global_storage.rs similarity index 100% rename from ir/src/global_storage.rs rename to bindings/rust/ir/src/global_storage.rs diff --git a/ir/src/instr.rs b/bindings/rust/ir/src/instr.rs similarity index 100% rename from ir/src/instr.rs rename to bindings/rust/ir/src/instr.rs diff --git a/ir/src/interpreter/integer.rs b/bindings/rust/ir/src/interpreter/integer.rs similarity index 100% rename from ir/src/interpreter/integer.rs rename to bindings/rust/ir/src/interpreter/integer.rs diff --git a/ir/src/interpreter/integer_reference.rs b/bindings/rust/ir/src/interpreter/integer_reference.rs similarity index 100% rename from ir/src/interpreter/integer_reference.rs rename to bindings/rust/ir/src/interpreter/integer_reference.rs diff --git a/ir/src/interpreter/memory.rs b/bindings/rust/ir/src/interpreter/memory.rs similarity index 100% rename from ir/src/interpreter/memory.rs rename to bindings/rust/ir/src/interpreter/memory.rs diff --git a/ir/src/interpreter/memory/generated.rs b/bindings/rust/ir/src/interpreter/memory/generated.rs similarity index 98% rename from ir/src/interpreter/memory/generated.rs rename to bindings/rust/ir/src/interpreter/memory/generated.rs index 6b0c6cf..cde3e2a 100644 --- a/ir/src/interpreter/memory/generated.rs +++ b/bindings/rust/ir/src/interpreter/memory/generated.rs @@ -418,9 +418,9 @@ fn parse(source: &str) -> Vec { #[test] fn retained_memory_sequences_match_independent_cells_and_authority_tokens() { - run(&parse(include_str!("../../../../fuzz/corpus/memory/authority.ops"))); - run(&parse(include_str!("../../../../fuzz/corpus/memory/lifetime.ops"))); - run(&parse(include_str!("../../../../fuzz/corpus/memory/explicit-lifetime.ops"))); + run(&parse(include_str!("../../../../../../fuzz/corpus/memory/authority.ops"))); + run(&parse(include_str!("../../../../../../fuzz/corpus/memory/lifetime.ops"))); + run(&parse(include_str!("../../../../../../fuzz/corpus/memory/explicit-lifetime.ops"))); } fn generated(seed: u64, count: usize) -> Vec { diff --git a/ir/src/interpreter/memory_reference.rs b/bindings/rust/ir/src/interpreter/memory_reference.rs similarity index 100% rename from ir/src/interpreter/memory_reference.rs rename to bindings/rust/ir/src/interpreter/memory_reference.rs diff --git a/ir/src/interpreter/memory_wave.rs b/bindings/rust/ir/src/interpreter/memory_wave.rs similarity index 100% rename from ir/src/interpreter/memory_wave.rs rename to bindings/rust/ir/src/interpreter/memory_wave.rs diff --git a/ir/src/interpreter/mod.rs b/bindings/rust/ir/src/interpreter/mod.rs similarity index 100% rename from ir/src/interpreter/mod.rs rename to bindings/rust/ir/src/interpreter/mod.rs diff --git a/ir/src/interpreter/runtime_wave.rs b/bindings/rust/ir/src/interpreter/runtime_wave.rs similarity index 100% rename from ir/src/interpreter/runtime_wave.rs rename to bindings/rust/ir/src/interpreter/runtime_wave.rs diff --git a/ir/src/interpreter/scalar.rs b/bindings/rust/ir/src/interpreter/scalar.rs similarity index 100% rename from ir/src/interpreter/scalar.rs rename to bindings/rust/ir/src/interpreter/scalar.rs diff --git a/ir/src/layout.rs b/bindings/rust/ir/src/layout.rs similarity index 100% rename from ir/src/layout.rs rename to bindings/rust/ir/src/layout.rs diff --git a/ir/src/lib.rs b/bindings/rust/ir/src/lib.rs similarity index 100% rename from ir/src/lib.rs rename to bindings/rust/ir/src/lib.rs diff --git a/ir/src/limits.rs b/bindings/rust/ir/src/limits.rs similarity index 100% rename from ir/src/limits.rs rename to bindings/rust/ir/src/limits.rs diff --git a/ir/src/lower_ast/binding.rs b/bindings/rust/ir/src/lower_ast/binding.rs similarity index 100% rename from ir/src/lower_ast/binding.rs rename to bindings/rust/ir/src/lower_ast/binding.rs diff --git a/ir/src/lower_ast/error.rs b/bindings/rust/ir/src/lower_ast/error.rs similarity index 100% rename from ir/src/lower_ast/error.rs rename to bindings/rust/ir/src/lower_ast/error.rs diff --git a/ir/src/lower_ast/frontend.rs b/bindings/rust/ir/src/lower_ast/frontend.rs similarity index 100% rename from ir/src/lower_ast/frontend.rs rename to bindings/rust/ir/src/lower_ast/frontend.rs diff --git a/ir/src/lower_ast/interchange.rs b/bindings/rust/ir/src/lower_ast/interchange.rs similarity index 100% rename from ir/src/lower_ast/interchange.rs rename to bindings/rust/ir/src/lower_ast/interchange.rs diff --git a/ir/src/lower_ast/limits.rs b/bindings/rust/ir/src/lower_ast/limits.rs similarity index 100% rename from ir/src/lower_ast/limits.rs rename to bindings/rust/ir/src/lower_ast/limits.rs diff --git a/ir/src/lower_ast/mod.rs b/bindings/rust/ir/src/lower_ast/mod.rs similarity index 100% rename from ir/src/lower_ast/mod.rs rename to bindings/rust/ir/src/lower_ast/mod.rs diff --git a/ir/src/lower_ast/o0.rs b/bindings/rust/ir/src/lower_ast/o0.rs similarity index 100% rename from ir/src/lower_ast/o0.rs rename to bindings/rust/ir/src/lower_ast/o0.rs diff --git a/ir/src/lower_ast/o0/storage.rs b/bindings/rust/ir/src/lower_ast/o0/storage.rs similarity index 100% rename from ir/src/lower_ast/o0/storage.rs rename to bindings/rust/ir/src/lower_ast/o0/storage.rs diff --git a/ir/src/lower_ast/support.rs b/bindings/rust/ir/src/lower_ast/support.rs similarity index 100% rename from ir/src/lower_ast/support.rs rename to bindings/rust/ir/src/lower_ast/support.rs diff --git a/ir/src/lower_ast/wave_hir.rs b/bindings/rust/ir/src/lower_ast/wave_hir.rs similarity index 100% rename from ir/src/lower_ast/wave_hir.rs rename to bindings/rust/ir/src/lower_ast/wave_hir.rs diff --git a/ir/src/lower_ast/wave_limits.rs b/bindings/rust/ir/src/lower_ast/wave_limits.rs similarity index 100% rename from ir/src/lower_ast/wave_limits.rs rename to bindings/rust/ir/src/lower_ast/wave_limits.rs diff --git a/ir/src/lower_ast/wave_lower.rs b/bindings/rust/ir/src/lower_ast/wave_lower.rs similarity index 100% rename from ir/src/lower_ast/wave_lower.rs rename to bindings/rust/ir/src/lower_ast/wave_lower.rs diff --git a/ir/src/module.rs b/bindings/rust/ir/src/module.rs similarity index 100% rename from ir/src/module.rs rename to bindings/rust/ir/src/module.rs diff --git a/ir/src/parser/instruction.rs b/bindings/rust/ir/src/parser/instruction.rs similarity index 100% rename from ir/src/parser/instruction.rs rename to bindings/rust/ir/src/parser/instruction.rs diff --git a/ir/src/parser/lexer.rs b/bindings/rust/ir/src/parser/lexer.rs similarity index 100% rename from ir/src/parser/lexer.rs rename to bindings/rust/ir/src/parser/lexer.rs diff --git a/ir/src/parser/mod.rs b/bindings/rust/ir/src/parser/mod.rs similarity index 100% rename from ir/src/parser/mod.rs rename to bindings/rust/ir/src/parser/mod.rs diff --git a/ir/src/parser/syntax.rs b/bindings/rust/ir/src/parser/syntax.rs similarity index 100% rename from ir/src/parser/syntax.rs rename to bindings/rust/ir/src/parser/syntax.rs diff --git a/ir/src/parser/wave_expression.rs b/bindings/rust/ir/src/parser/wave_expression.rs similarity index 100% rename from ir/src/parser/wave_expression.rs rename to bindings/rust/ir/src/parser/wave_expression.rs diff --git a/ir/src/parser/wave_header.rs b/bindings/rust/ir/src/parser/wave_header.rs similarity index 100% rename from ir/src/parser/wave_header.rs rename to bindings/rust/ir/src/parser/wave_header.rs diff --git a/ir/src/parser/wave_instruction.rs b/bindings/rust/ir/src/parser/wave_instruction.rs similarity index 100% rename from ir/src/parser/wave_instruction.rs rename to bindings/rust/ir/src/parser/wave_instruction.rs diff --git a/ir/src/parser/wave_lexer.rs b/bindings/rust/ir/src/parser/wave_lexer.rs similarity index 100% rename from ir/src/parser/wave_lexer.rs rename to bindings/rust/ir/src/parser/wave_lexer.rs diff --git a/ir/src/parser/wave_literal.rs b/bindings/rust/ir/src/parser/wave_literal.rs similarity index 100% rename from ir/src/parser/wave_literal.rs rename to bindings/rust/ir/src/parser/wave_literal.rs diff --git a/ir/src/parser/wave_module.rs b/bindings/rust/ir/src/parser/wave_module.rs similarity index 100% rename from ir/src/parser/wave_module.rs rename to bindings/rust/ir/src/parser/wave_module.rs diff --git a/ir/src/parser/wave_text.rs b/bindings/rust/ir/src/parser/wave_text.rs similarity index 100% rename from ir/src/parser/wave_text.rs rename to bindings/rust/ir/src/parser/wave_text.rs diff --git a/ir/src/parser/wave_type.rs b/bindings/rust/ir/src/parser/wave_type.rs similarity index 100% rename from ir/src/parser/wave_type.rs rename to bindings/rust/ir/src/parser/wave_type.rs diff --git a/ir/src/pass.rs b/bindings/rust/ir/src/pass.rs similarity index 100% rename from ir/src/pass.rs rename to bindings/rust/ir/src/pass.rs diff --git a/ir/src/pass_dispose.rs b/bindings/rust/ir/src/pass_dispose.rs similarity index 100% rename from ir/src/pass_dispose.rs rename to bindings/rust/ir/src/pass_dispose.rs diff --git a/ir/src/pass_wave.rs b/bindings/rust/ir/src/pass_wave.rs similarity index 100% rename from ir/src/pass_wave.rs rename to bindings/rust/ir/src/pass_wave.rs diff --git a/ir/src/printer.rs b/bindings/rust/ir/src/printer.rs similarity index 100% rename from ir/src/printer.rs rename to bindings/rust/ir/src/printer.rs diff --git a/ir/src/printer_reference.rs b/bindings/rust/ir/src/printer_reference.rs similarity index 100% rename from ir/src/printer_reference.rs rename to bindings/rust/ir/src/printer_reference.rs diff --git a/ir/src/printer_tests.rs b/bindings/rust/ir/src/printer_tests.rs similarity index 100% rename from ir/src/printer_tests.rs rename to bindings/rust/ir/src/printer_tests.rs diff --git a/ir/src/printer_wave.rs b/bindings/rust/ir/src/printer_wave.rs similarity index 100% rename from ir/src/printer_wave.rs rename to bindings/rust/ir/src/printer_wave.rs diff --git a/ir/src/source.rs b/bindings/rust/ir/src/source.rs similarity index 100% rename from ir/src/source.rs rename to bindings/rust/ir/src/source.rs diff --git a/ir/src/source_wave.rs b/bindings/rust/ir/src/source_wave.rs similarity index 100% rename from ir/src/source_wave.rs rename to bindings/rust/ir/src/source_wave.rs diff --git a/ir/src/types.rs b/bindings/rust/ir/src/types.rs similarity index 100% rename from ir/src/types.rs rename to bindings/rust/ir/src/types.rs diff --git a/ir/src/value.rs b/bindings/rust/ir/src/value.rs similarity index 100% rename from ir/src/value.rs rename to bindings/rust/ir/src/value.rs diff --git a/ir/src/verifier.rs b/bindings/rust/ir/src/verifier.rs similarity index 100% rename from ir/src/verifier.rs rename to bindings/rust/ir/src/verifier.rs diff --git a/ir/src/verifier/calls.rs b/bindings/rust/ir/src/verifier/calls.rs similarity index 100% rename from ir/src/verifier/calls.rs rename to bindings/rust/ir/src/verifier/calls.rs diff --git a/ir/src/verifier/cfg.rs b/bindings/rust/ir/src/verifier/cfg.rs similarity index 100% rename from ir/src/verifier/cfg.rs rename to bindings/rust/ir/src/verifier/cfg.rs diff --git a/ir/src/verifier/constants.rs b/bindings/rust/ir/src/verifier/constants.rs similarity index 100% rename from ir/src/verifier/constants.rs rename to bindings/rust/ir/src/verifier/constants.rs diff --git a/ir/src/verifier/index.rs b/bindings/rust/ir/src/verifier/index.rs similarity index 100% rename from ir/src/verifier/index.rs rename to bindings/rust/ir/src/verifier/index.rs diff --git a/ir/src/verifier/operands.rs b/bindings/rust/ir/src/verifier/operands.rs similarity index 100% rename from ir/src/verifier/operands.rs rename to bindings/rust/ir/src/verifier/operands.rs diff --git a/ir/src/verifier/wave_cfg.rs b/bindings/rust/ir/src/verifier/wave_cfg.rs similarity index 100% rename from ir/src/verifier/wave_cfg.rs rename to bindings/rust/ir/src/verifier/wave_cfg.rs diff --git a/ir/src/verifier/wave_constants.rs b/bindings/rust/ir/src/verifier/wave_constants.rs similarity index 100% rename from ir/src/verifier/wave_constants.rs rename to bindings/rust/ir/src/verifier/wave_constants.rs diff --git a/ir/src/verifier/wave_index.rs b/bindings/rust/ir/src/verifier/wave_index.rs similarity index 100% rename from ir/src/verifier/wave_index.rs rename to bindings/rust/ir/src/verifier/wave_index.rs diff --git a/ir/src/verifier/wave_semantics.rs b/bindings/rust/ir/src/verifier/wave_semantics.rs similarity index 100% rename from ir/src/verifier/wave_semantics.rs rename to bindings/rust/ir/src/verifier/wave_semantics.rs diff --git a/ir/src/verifier/wave_shape.rs b/bindings/rust/ir/src/verifier/wave_shape.rs similarity index 100% rename from ir/src/verifier/wave_shape.rs rename to bindings/rust/ir/src/verifier/wave_shape.rs diff --git a/ir/src/verifier/wave_ssa.rs b/bindings/rust/ir/src/verifier/wave_ssa.rs similarity index 100% rename from ir/src/verifier/wave_ssa.rs rename to bindings/rust/ir/src/verifier/wave_ssa.rs diff --git a/ir/src/wave_layout.rs b/bindings/rust/ir/src/wave_layout.rs similarity index 100% rename from ir/src/wave_layout.rs rename to bindings/rust/ir/src/wave_layout.rs diff --git a/ir/src/zero/mod.rs b/bindings/rust/ir/src/zero/mod.rs similarity index 100% rename from ir/src/zero/mod.rs rename to bindings/rust/ir/src/zero/mod.rs diff --git a/ir/src/zero/pass.rs b/bindings/rust/ir/src/zero/pass.rs similarity index 100% rename from ir/src/zero/pass.rs rename to bindings/rust/ir/src/zero/pass.rs diff --git a/ir/tests/ast_resource_limits.rs b/bindings/rust/ir/tests/ast_resource_limits.rs similarity index 99% rename from ir/tests/ast_resource_limits.rs rename to bindings/rust/ir/tests/ast_resource_limits.rs index bd1f185..1e28d98 100644 --- a/ir/tests/ast_resource_limits.rs +++ b/bindings/rust/ir/tests/ast_resource_limits.rs @@ -161,6 +161,7 @@ fn deep_ast_encode_child() { #[cfg(target_os = "linux")] fn child(name: &str) { let output = std::process::Command::new("sh") + .env_clear() .arg("-c") .arg("ulimit -c 0; ulimit -v 51200; exec \"$@\"") .arg("ast-test") diff --git a/ir/tests/builder_checked.rs b/bindings/rust/ir/tests/builder_checked.rs similarity index 100% rename from ir/tests/builder_checked.rs rename to bindings/rust/ir/tests/builder_checked.rs diff --git a/ir/tests/bytecode_execution.rs b/bindings/rust/ir/tests/bytecode_execution.rs similarity index 100% rename from ir/tests/bytecode_execution.rs rename to bindings/rust/ir/tests/bytecode_execution.rs diff --git a/ir/tests/bytecode_output_ceiling.rs b/bindings/rust/ir/tests/bytecode_output_ceiling.rs similarity index 100% rename from ir/tests/bytecode_output_ceiling.rs rename to bindings/rust/ir/tests/bytecode_output_ceiling.rs diff --git a/ir/tests/call_lowering.rs b/bindings/rust/ir/tests/call_lowering.rs similarity index 100% rename from ir/tests/call_lowering.rs rename to bindings/rust/ir/tests/call_lowering.rs diff --git a/ir/tests/call_validation.rs b/bindings/rust/ir/tests/call_validation.rs similarity index 100% rename from ir/tests/call_validation.rs rename to bindings/rust/ir/tests/call_validation.rs diff --git a/ir/tests/cast_checked_validation.rs b/bindings/rust/ir/tests/cast_checked_validation.rs similarity index 100% rename from ir/tests/cast_checked_validation.rs rename to bindings/rust/ir/tests/cast_checked_validation.rs diff --git a/ir/tests/casts.rs b/bindings/rust/ir/tests/casts.rs similarity index 100% rename from ir/tests/casts.rs rename to bindings/rust/ir/tests/casts.rs diff --git a/ir/tests/cfg_validation.rs b/bindings/rust/ir/tests/cfg_validation.rs similarity index 100% rename from ir/tests/cfg_validation.rs rename to bindings/rust/ir/tests/cfg_validation.rs diff --git a/ir/tests/constant_expression_preservation.rs b/bindings/rust/ir/tests/constant_expression_preservation.rs similarity index 100% rename from ir/tests/constant_expression_preservation.rs rename to bindings/rust/ir/tests/constant_expression_preservation.rs diff --git a/ir/tests/constant_expression_validation.rs b/bindings/rust/ir/tests/constant_expression_validation.rs similarity index 100% rename from ir/tests/constant_expression_validation.rs rename to bindings/rust/ir/tests/constant_expression_validation.rs diff --git a/ir/tests/constant_validation.rs b/bindings/rust/ir/tests/constant_validation.rs similarity index 100% rename from ir/tests/constant_validation.rs rename to bindings/rust/ir/tests/constant_validation.rs diff --git a/ir/tests/diagnostic_boundary.rs b/bindings/rust/ir/tests/diagnostic_boundary.rs similarity index 100% rename from ir/tests/diagnostic_boundary.rs rename to bindings/rust/ir/tests/diagnostic_boundary.rs diff --git a/ir/tests/extension_layout.rs b/bindings/rust/ir/tests/extension_layout.rs similarity index 100% rename from ir/tests/extension_layout.rs rename to bindings/rust/ir/tests/extension_layout.rs diff --git a/ir/tests/fixtures/README.md b/bindings/rust/ir/tests/fixtures/README.md similarity index 100% rename from ir/tests/fixtures/README.md rename to bindings/rust/ir/tests/fixtures/README.md diff --git a/ir/tests/fixtures/amd64_layout.c b/bindings/rust/ir/tests/fixtures/amd64_layout.c similarity index 100% rename from ir/tests/fixtures/amd64_layout.c rename to bindings/rust/ir/tests/fixtures/amd64_layout.c diff --git a/ir/tests/fixtures/ast-v2-calls.json b/bindings/rust/ir/tests/fixtures/ast-v2-calls.json similarity index 100% rename from ir/tests/fixtures/ast-v2-calls.json rename to bindings/rust/ir/tests/fixtures/ast-v2-calls.json diff --git a/ir/tests/fixtures/ast-v2-float.json b/bindings/rust/ir/tests/fixtures/ast-v2-float.json similarity index 100% rename from ir/tests/fixtures/ast-v2-float.json rename to bindings/rust/ir/tests/fixtures/ast-v2-float.json diff --git a/ir/tests/fixtures/ast-v2-u128.json b/bindings/rust/ir/tests/fixtures/ast-v2-u128.json similarity index 100% rename from ir/tests/fixtures/ast-v2-u128.json rename to bindings/rust/ir/tests/fixtures/ast-v2-u128.json diff --git a/ir/tests/fixtures/bytecode/constant_source.wbc b/bindings/rust/ir/tests/fixtures/bytecode/constant_source.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/constant_source.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/constant_source.wbc diff --git a/ir/tests/fixtures/bytecode/empty.wbc b/bindings/rust/ir/tests/fixtures/bytecode/empty.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/empty.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/empty.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_block_count.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_block_count.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_block_count.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_block_count.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_block_owner.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_block_owner.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_block_owner.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_block_owner.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_count_overflow.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_count_overflow.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_count_overflow.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_count_overflow.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_destination.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_destination.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_destination.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_destination.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_directory_overlap.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_directory_overlap.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_directory_overlap.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_directory_overlap.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_early_terminal.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_early_terminal.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_early_terminal.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_early_terminal.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_entry.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_entry.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_entry.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_entry.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_flags.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_flags.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_flags.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_flags.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_function_id.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_function_id.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_function_id.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_function_id.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_header.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_header.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_header.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_header.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_layout.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_layout.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_layout.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_layout.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_length.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_length.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_length.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_length.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_nondominating_return.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_nondominating_return.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_nondominating_return.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_nondominating_return.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_opcode.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_opcode.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_opcode.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_opcode.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_phi_slot.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_slot.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_phi_slot.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_slot.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_phi_type.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_type.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_phi_type.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_phi_type.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_return_slot.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_return_slot.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_return_slot.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_return_slot.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_return_type.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_return_type.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_return_type.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_return_type.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_semantics.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_semantics.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_semantics.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_semantics.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_signature.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_signature.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_signature.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_signature.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_site.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_site.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_site.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_site.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_ssa_id.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_ssa_id.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_ssa_id.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_ssa_id.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_stride.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_stride.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_stride.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_stride.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_table_count.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_table_count.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_table_count.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_table_count.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_text_overlap.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_text_overlap.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_text_overlap.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_text_overlap.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_trailing.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_trailing.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_trailing.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_trailing.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_truncated.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_truncated.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_truncated.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_truncated.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_type_cycle.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_type_cycle.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_type_cycle.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_type_cycle.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_type_kind.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_type_kind.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_type_kind.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_type_kind.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_utf8.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_utf8.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_utf8.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_utf8.wbc diff --git a/ir/tests/fixtures/bytecode/invalid_version.wbc b/bindings/rust/ir/tests/fixtures/bytecode/invalid_version.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/invalid_version.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/invalid_version.wbc diff --git a/ir/tests/fixtures/bytecode/phi_diamond.wbc b/bindings/rust/ir/tests/fixtures/bytecode/phi_diamond.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/phi_diamond.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/phi_diamond.wbc diff --git a/ir/tests/fixtures/bytecode/return42.wbc b/bindings/rust/ir/tests/fixtures/bytecode/return42.wbc similarity index 100% rename from ir/tests/fixtures/bytecode/return42.wbc rename to bindings/rust/ir/tests/fixtures/bytecode/return42.wbc diff --git a/ir/tests/fixtures/calls-v3.wir b/bindings/rust/ir/tests/fixtures/calls-v3.wir similarity index 100% rename from ir/tests/fixtures/calls-v3.wir rename to bindings/rust/ir/tests/fixtures/calls-v3.wir diff --git a/ir/tests/fixtures/float-arithmetic.txt b/bindings/rust/ir/tests/fixtures/float-arithmetic.txt similarity index 100% rename from ir/tests/fixtures/float-arithmetic.txt rename to bindings/rust/ir/tests/fixtures/float-arithmetic.txt diff --git a/ir/tests/fixtures/float-comparisons-v7.wir b/bindings/rust/ir/tests/fixtures/float-comparisons-v7.wir similarity index 100% rename from ir/tests/fixtures/float-comparisons-v7.wir rename to bindings/rust/ir/tests/fixtures/float-comparisons-v7.wir diff --git a/ir/tests/fixtures/float-conversions.txt b/bindings/rust/ir/tests/fixtures/float-conversions.txt similarity index 100% rename from ir/tests/fixtures/float-conversions.txt rename to bindings/rust/ir/tests/fixtures/float-conversions.txt diff --git a/ir/tests/fixtures/float-storage-v7.wir b/bindings/rust/ir/tests/fixtures/float-storage-v7.wir similarity index 100% rename from ir/tests/fixtures/float-storage-v7.wir rename to bindings/rust/ir/tests/fixtures/float-storage-v7.wir diff --git a/ir/tests/fixtures/initialization-loop-v4.wir b/bindings/rust/ir/tests/fixtures/initialization-loop-v4.wir similarity index 100% rename from ir/tests/fixtures/initialization-loop-v4.wir rename to bindings/rust/ir/tests/fixtures/initialization-loop-v4.wir diff --git a/ir/tests/fixtures/integer-operations-v3.wir b/bindings/rust/ir/tests/fixtures/integer-operations-v3.wir similarity index 100% rename from ir/tests/fixtures/integer-operations-v3.wir rename to bindings/rust/ir/tests/fixtures/integer-operations-v3.wir diff --git a/ir/tests/fixtures/interpreted-calls-v4.wir b/bindings/rust/ir/tests/fixtures/interpreted-calls-v4.wir similarity index 100% rename from ir/tests/fixtures/interpreted-calls-v4.wir rename to bindings/rust/ir/tests/fixtures/interpreted-calls-v4.wir diff --git a/ir/tests/fixtures/interpreter-loop-v3.wir b/bindings/rust/ir/tests/fixtures/interpreter-loop-v3.wir similarity index 100% rename from ir/tests/fixtures/interpreter-loop-v3.wir rename to bindings/rust/ir/tests/fixtures/interpreter-loop-v3.wir diff --git a/ir/tests/fixtures/runtime-diagnostics-v7.wir b/bindings/rust/ir/tests/fixtures/runtime-diagnostics-v7.wir similarity index 100% rename from ir/tests/fixtures/runtime-diagnostics-v7.wir rename to bindings/rust/ir/tests/fixtures/runtime-diagnostics-v7.wir diff --git a/ir/tests/fixtures/runtime-storage-v6.wir b/bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir similarity index 100% rename from ir/tests/fixtures/runtime-storage-v6.wir rename to bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir diff --git a/ir/tests/fixtures/text-identities-v3.wir b/bindings/rust/ir/tests/fixtures/text-identities-v3.wir similarity index 100% rename from ir/tests/fixtures/text-identities-v3.wir rename to bindings/rust/ir/tests/fixtures/text-identities-v3.wir diff --git a/ir/tests/fixtures/tracked-memory-v4.wir b/bindings/rust/ir/tests/fixtures/tracked-memory-v4.wir similarity index 100% rename from ir/tests/fixtures/tracked-memory-v4.wir rename to bindings/rust/ir/tests/fixtures/tracked-memory-v4.wir diff --git a/ir/tests/fixtures/wave-casts-v3.wir b/bindings/rust/ir/tests/fixtures/wave-casts-v3.wir similarity index 100% rename from ir/tests/fixtures/wave-casts-v3.wir rename to bindings/rust/ir/tests/fixtures/wave-casts-v3.wir diff --git a/ir/tests/fixtures/wave-control-v3.wir b/bindings/rust/ir/tests/fixtures/wave-control-v3.wir similarity index 100% rename from ir/tests/fixtures/wave-control-v3.wir rename to bindings/rust/ir/tests/fixtures/wave-control-v3.wir diff --git a/ir/tests/fixtures/wave_typed_hir_scalar.json b/bindings/rust/ir/tests/fixtures/wave_typed_hir_scalar.json similarity index 100% rename from ir/tests/fixtures/wave_typed_hir_scalar.json rename to bindings/rust/ir/tests/fixtures/wave_typed_hir_scalar.json diff --git a/ir/tests/float_arithmetic.rs b/bindings/rust/ir/tests/float_arithmetic.rs similarity index 100% rename from ir/tests/float_arithmetic.rs rename to bindings/rust/ir/tests/float_arithmetic.rs diff --git a/ir/tests/float_comparisons.rs b/bindings/rust/ir/tests/float_comparisons.rs similarity index 100% rename from ir/tests/float_comparisons.rs rename to bindings/rust/ir/tests/float_comparisons.rs diff --git a/ir/tests/float_conversions.rs b/bindings/rust/ir/tests/float_conversions.rs similarity index 100% rename from ir/tests/float_conversions.rs rename to bindings/rust/ir/tests/float_conversions.rs diff --git a/ir/tests/float_storage.rs b/bindings/rust/ir/tests/float_storage.rs similarity index 100% rename from ir/tests/float_storage.rs rename to bindings/rust/ir/tests/float_storage.rs diff --git a/ir/tests/frontend_error_order.rs b/bindings/rust/ir/tests/frontend_error_order.rs similarity index 100% rename from ir/tests/frontend_error_order.rs rename to bindings/rust/ir/tests/frontend_error_order.rs diff --git a/ir/tests/frontend_operators.rs b/bindings/rust/ir/tests/frontend_operators.rs similarity index 100% rename from ir/tests/frontend_operators.rs rename to bindings/rust/ir/tests/frontend_operators.rs diff --git a/ir/tests/frontend_storage.rs b/bindings/rust/ir/tests/frontend_storage.rs similarity index 100% rename from ir/tests/frontend_storage.rs rename to bindings/rust/ir/tests/frontend_storage.rs diff --git a/ir/tests/generated_memory_execution.rs b/bindings/rust/ir/tests/generated_memory_execution.rs similarity index 100% rename from ir/tests/generated_memory_execution.rs rename to bindings/rust/ir/tests/generated_memory_execution.rs diff --git a/ir/tests/gep_validation.rs b/bindings/rust/ir/tests/gep_validation.rs similarity index 100% rename from ir/tests/gep_validation.rs rename to bindings/rust/ir/tests/gep_validation.rs diff --git a/ir/tests/identity_validation.rs b/bindings/rust/ir/tests/identity_validation.rs similarity index 100% rename from ir/tests/identity_validation.rs rename to bindings/rust/ir/tests/identity_validation.rs diff --git a/ir/tests/initialized_lowering.rs b/bindings/rust/ir/tests/initialized_lowering.rs similarity index 100% rename from ir/tests/initialized_lowering.rs rename to bindings/rust/ir/tests/initialized_lowering.rs diff --git a/ir/tests/integer_folding.rs b/bindings/rust/ir/tests/integer_folding.rs similarity index 100% rename from ir/tests/integer_folding.rs rename to bindings/rust/ir/tests/integer_folding.rs diff --git a/ir/tests/interchange.rs b/bindings/rust/ir/tests/interchange.rs similarity index 100% rename from ir/tests/interchange.rs rename to bindings/rust/ir/tests/interchange.rs diff --git a/ir/tests/interpreted_calls.rs b/bindings/rust/ir/tests/interpreted_calls.rs similarity index 100% rename from ir/tests/interpreted_calls.rs rename to bindings/rust/ir/tests/interpreted_calls.rs diff --git a/ir/tests/interpreted_floats.rs b/bindings/rust/ir/tests/interpreted_floats.rs similarity index 100% rename from ir/tests/interpreted_floats.rs rename to bindings/rust/ir/tests/interpreted_floats.rs diff --git a/ir/tests/interpreter.rs b/bindings/rust/ir/tests/interpreter.rs similarity index 100% rename from ir/tests/interpreter.rs rename to bindings/rust/ir/tests/interpreter.rs diff --git a/ir/tests/lowering_validation.rs b/bindings/rust/ir/tests/lowering_validation.rs similarity index 100% rename from ir/tests/lowering_validation.rs rename to bindings/rust/ir/tests/lowering_validation.rs diff --git a/ir/tests/o0_preservation.rs b/bindings/rust/ir/tests/o0_preservation.rs similarity index 100% rename from ir/tests/o0_preservation.rs rename to bindings/rust/ir/tests/o0_preservation.rs diff --git a/ir/tests/operand_validation.rs b/bindings/rust/ir/tests/operand_validation.rs similarity index 100% rename from ir/tests/operand_validation.rs rename to bindings/rust/ir/tests/operand_validation.rs diff --git a/ir/tests/pass_effects.rs b/bindings/rust/ir/tests/pass_effects.rs similarity index 100% rename from ir/tests/pass_effects.rs rename to bindings/rust/ir/tests/pass_effects.rs diff --git a/ir/tests/public_semantic_boundaries.rs b/bindings/rust/ir/tests/public_semantic_boundaries.rs similarity index 100% rename from ir/tests/public_semantic_boundaries.rs rename to bindings/rust/ir/tests/public_semantic_boundaries.rs diff --git a/ir/tests/resource_limits.rs b/bindings/rust/ir/tests/resource_limits.rs similarity index 100% rename from ir/tests/resource_limits.rs rename to bindings/rust/ir/tests/resource_limits.rs diff --git a/ir/tests/runtime_diagnostics.rs b/bindings/rust/ir/tests/runtime_diagnostics.rs similarity index 100% rename from ir/tests/runtime_diagnostics.rs rename to bindings/rust/ir/tests/runtime_diagnostics.rs diff --git a/ir/tests/runtime_storage.rs b/bindings/rust/ir/tests/runtime_storage.rs similarity index 100% rename from ir/tests/runtime_storage.rs rename to bindings/rust/ir/tests/runtime_storage.rs diff --git a/ir/tests/source_metadata.rs b/bindings/rust/ir/tests/source_metadata.rs similarity index 100% rename from ir/tests/source_metadata.rs rename to bindings/rust/ir/tests/source_metadata.rs diff --git a/ir/tests/switch_validation.rs b/bindings/rust/ir/tests/switch_validation.rs similarity index 100% rename from ir/tests/switch_validation.rs rename to bindings/rust/ir/tests/switch_validation.rs diff --git a/ir/tests/target_validation.rs b/bindings/rust/ir/tests/target_validation.rs similarity index 100% rename from ir/tests/target_validation.rs rename to bindings/rust/ir/tests/target_validation.rs diff --git a/ir/tests/text_parser.rs b/bindings/rust/ir/tests/text_parser.rs similarity index 100% rename from ir/tests/text_parser.rs rename to bindings/rust/ir/tests/text_parser.rs diff --git a/ir/tests/text_printer.rs b/bindings/rust/ir/tests/text_printer.rs similarity index 100% rename from ir/tests/text_printer.rs rename to bindings/rust/ir/tests/text_printer.rs diff --git a/ir/tests/tracked_memory.rs b/bindings/rust/ir/tests/tracked_memory.rs similarity index 100% rename from ir/tests/tracked_memory.rs rename to bindings/rust/ir/tests/tracked_memory.rs diff --git a/ir/tests/type_layout.rs b/bindings/rust/ir/tests/type_layout.rs similarity index 98% rename from ir/tests/type_layout.rs rename to bindings/rust/ir/tests/type_layout.rs index eb79dc0..842b97f 100644 --- a/ir/tests/type_layout.rs +++ b/bindings/rust/ir/tests/type_layout.rs @@ -161,7 +161,9 @@ fn deep_layout_child() { fn deep_layout_override_is_safe_in_a_capped_child_process() { let exe = std::env::current_exe().unwrap(); let mut cmd = std::process::Command::new("sh"); - cmd.arg("-c") + // Isolate the 50 MiB ceiling from Cargo's inherited build environment. + cmd.env_clear() + .arg("-c") .arg("ulimit -c 0; ulimit -v 51200; exec \"$@\"") .arg("layout-test") .arg(exe) diff --git a/ir/tests/verification_scaling.rs b/bindings/rust/ir/tests/verification_scaling.rs similarity index 100% rename from ir/tests/verification_scaling.rs rename to bindings/rust/ir/tests/verification_scaling.rs diff --git a/ir/tests/verifier_validation.rs b/bindings/rust/ir/tests/verifier_validation.rs similarity index 100% rename from ir/tests/verifier_validation.rs rename to bindings/rust/ir/tests/verifier_validation.rs diff --git a/ir/tests/wave_ast_lowering.rs b/bindings/rust/ir/tests/wave_ast_lowering.rs similarity index 100% rename from ir/tests/wave_ast_lowering.rs rename to bindings/rust/ir/tests/wave_ast_lowering.rs diff --git a/ir/tests/wave_typed_hir.rs b/bindings/rust/ir/tests/wave_typed_hir.rs similarity index 100% rename from ir/tests/wave_typed_hir.rs rename to bindings/rust/ir/tests/wave_typed_hir.rs diff --git a/assembler/loongarch64/Cargo.toml b/bindings/rust/loongarch64/Cargo.toml similarity index 68% rename from assembler/loongarch64/Cargo.toml rename to bindings/rust/loongarch64/Cargo.toml index e018d6b..c37a533 100644 --- a/assembler/loongarch64/Cargo.toml +++ b/bindings/rust/loongarch64/Cargo.toml @@ -9,5 +9,5 @@ default = [] rust-reference = ["assembler/rust-reference"] [dependencies] -assembler = { path = ".." } -target-spec = { path = "../../target-spec" } +assembler = { path = "../assembler" } +target-spec = { path = "../../../target-spec" } diff --git a/bindings/rust/loongarch64/build.rs b/bindings/rust/loongarch64/build.rs new file mode 100644 index 0000000..8539ffd --- /dev/null +++ b/bindings/rust/loongarch64/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "loongarch64"; + +const CFG: &str = "whale_wave_loongarch64"; + +const ENV: &str = "WHALE_WAVE_LOONGARCH64_DIR"; + +const LIBRARY: &str = "whale_wave_loongarch64"; + +const SOURCE_ROOTS: &[&str] = &["assembler/loongarch64", "assembler"]; +include!("../build_support.rs"); diff --git a/assembler/loongarch64/src/encoder.rs b/bindings/rust/loongarch64/src/encoder.rs similarity index 100% rename from assembler/loongarch64/src/encoder.rs rename to bindings/rust/loongarch64/src/encoder.rs diff --git a/assembler/loongarch64/src/encoding/branch.rs b/bindings/rust/loongarch64/src/encoding/branch.rs similarity index 100% rename from assembler/loongarch64/src/encoding/branch.rs rename to bindings/rust/loongarch64/src/encoding/branch.rs diff --git a/assembler/loongarch64/src/encoding/formats.rs b/bindings/rust/loongarch64/src/encoding/formats.rs similarity index 100% rename from assembler/loongarch64/src/encoding/formats.rs rename to bindings/rust/loongarch64/src/encoding/formats.rs diff --git a/assembler/loongarch64/src/encoding/mod.rs b/bindings/rust/loongarch64/src/encoding/mod.rs similarity index 100% rename from assembler/loongarch64/src/encoding/mod.rs rename to bindings/rust/loongarch64/src/encoding/mod.rs diff --git a/assembler/loongarch64/src/lib.rs b/bindings/rust/loongarch64/src/lib.rs similarity index 100% rename from assembler/loongarch64/src/lib.rs rename to bindings/rust/loongarch64/src/lib.rs diff --git a/assembler/loongarch64/src/parser.rs b/bindings/rust/loongarch64/src/parser.rs similarity index 100% rename from assembler/loongarch64/src/parser.rs rename to bindings/rust/loongarch64/src/parser.rs diff --git a/assembler/loongarch64/src/tables.rs b/bindings/rust/loongarch64/src/tables.rs similarity index 100% rename from assembler/loongarch64/src/tables.rs rename to bindings/rust/loongarch64/src/tables.rs diff --git a/assembler/loongarch64/src/wave.rs b/bindings/rust/loongarch64/src/wave.rs similarity index 100% rename from assembler/loongarch64/src/wave.rs rename to bindings/rust/loongarch64/src/wave.rs diff --git a/assembler/loongarch64/tests/encodings.rs b/bindings/rust/loongarch64/tests/encodings.rs similarity index 100% rename from assembler/loongarch64/tests/encodings.rs rename to bindings/rust/loongarch64/tests/encodings.rs diff --git a/assembler/loongarch64/tests/fixtures/encodings.tsv b/bindings/rust/loongarch64/tests/fixtures/encodings.tsv similarity index 100% rename from assembler/loongarch64/tests/fixtures/encodings.tsv rename to bindings/rust/loongarch64/tests/fixtures/encodings.tsv diff --git a/assembler/riscv64/Cargo.toml b/bindings/rust/riscv64/Cargo.toml similarity index 67% rename from assembler/riscv64/Cargo.toml rename to bindings/rust/riscv64/Cargo.toml index 4a6bb51..4e8582f 100644 --- a/assembler/riscv64/Cargo.toml +++ b/bindings/rust/riscv64/Cargo.toml @@ -9,5 +9,5 @@ default = [] rust-reference = ["assembler/rust-reference"] [dependencies] -assembler = { path = ".." } -target-spec = { path = "../../target-spec" } +assembler = { path = "../assembler" } +target-spec = { path = "../../../target-spec" } diff --git a/bindings/rust/riscv64/build.rs b/bindings/rust/riscv64/build.rs new file mode 100644 index 0000000..efa9ab5 --- /dev/null +++ b/bindings/rust/riscv64/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +const MODULE: &str = "riscv64"; + +const CFG: &str = "whale_wave_riscv64"; + +const ENV: &str = "WHALE_WAVE_RISCV64_DIR"; + +const LIBRARY: &str = "whale_wave_riscv64"; + +const SOURCE_ROOTS: &[&str] = &["assembler/riscv64", "assembler"]; +include!("../build_support.rs"); diff --git a/assembler/riscv64/src/encoder.rs b/bindings/rust/riscv64/src/encoder.rs similarity index 100% rename from assembler/riscv64/src/encoder.rs rename to bindings/rust/riscv64/src/encoder.rs diff --git a/assembler/riscv64/src/encoder_reference.rs b/bindings/rust/riscv64/src/encoder_reference.rs similarity index 100% rename from assembler/riscv64/src/encoder_reference.rs rename to bindings/rust/riscv64/src/encoder_reference.rs diff --git a/assembler/riscv64/src/encoding/branch.rs b/bindings/rust/riscv64/src/encoding/branch.rs similarity index 100% rename from assembler/riscv64/src/encoding/branch.rs rename to bindings/rust/riscv64/src/encoding/branch.rs diff --git a/assembler/riscv64/src/encoding/branch_reference.rs b/bindings/rust/riscv64/src/encoding/branch_reference.rs similarity index 100% rename from assembler/riscv64/src/encoding/branch_reference.rs rename to bindings/rust/riscv64/src/encoding/branch_reference.rs diff --git a/assembler/riscv64/src/encoding/formats.rs b/bindings/rust/riscv64/src/encoding/formats.rs similarity index 100% rename from assembler/riscv64/src/encoding/formats.rs rename to bindings/rust/riscv64/src/encoding/formats.rs diff --git a/assembler/riscv64/src/encoding/mod.rs b/bindings/rust/riscv64/src/encoding/mod.rs similarity index 100% rename from assembler/riscv64/src/encoding/mod.rs rename to bindings/rust/riscv64/src/encoding/mod.rs diff --git a/assembler/riscv64/src/encoding_reference.rs b/bindings/rust/riscv64/src/encoding_reference.rs similarity index 100% rename from assembler/riscv64/src/encoding_reference.rs rename to bindings/rust/riscv64/src/encoding_reference.rs diff --git a/assembler/riscv64/src/lib.rs b/bindings/rust/riscv64/src/lib.rs similarity index 100% rename from assembler/riscv64/src/lib.rs rename to bindings/rust/riscv64/src/lib.rs diff --git a/assembler/riscv64/src/parser.rs b/bindings/rust/riscv64/src/parser.rs similarity index 100% rename from assembler/riscv64/src/parser.rs rename to bindings/rust/riscv64/src/parser.rs diff --git a/assembler/riscv64/src/parser_reference.rs b/bindings/rust/riscv64/src/parser_reference.rs similarity index 100% rename from assembler/riscv64/src/parser_reference.rs rename to bindings/rust/riscv64/src/parser_reference.rs diff --git a/assembler/riscv64/src/tables.rs b/bindings/rust/riscv64/src/tables.rs similarity index 100% rename from assembler/riscv64/src/tables.rs rename to bindings/rust/riscv64/src/tables.rs diff --git a/assembler/riscv64/src/wave.rs b/bindings/rust/riscv64/src/wave.rs similarity index 100% rename from assembler/riscv64/src/wave.rs rename to bindings/rust/riscv64/src/wave.rs diff --git a/assembler/riscv64/tests/encodings.rs b/bindings/rust/riscv64/tests/encodings.rs similarity index 100% rename from assembler/riscv64/tests/encodings.rs rename to bindings/rust/riscv64/tests/encodings.rs diff --git a/assembler/riscv64/tests/fixtures/encodings.tsv b/bindings/rust/riscv64/tests/fixtures/encodings.tsv similarity index 100% rename from assembler/riscv64/tests/fixtures/encodings.tsv rename to bindings/rust/riscv64/tests/fixtures/encodings.tsv diff --git a/assembler/riscv64/tests/standard_sections.rs b/bindings/rust/riscv64/tests/standard_sections.rs similarity index 100% rename from assembler/riscv64/tests/standard_sections.rs rename to bindings/rust/riscv64/tests/standard_sections.rs diff --git a/build.rs b/build.rs index b56963d..2cf0d90 100644 --- a/build.rs +++ b/build.rs @@ -26,7 +26,7 @@ fn provenance(directory: &Path) -> Value { assert!(bytes.len() <= 16384, "oversized module provenance"); let original: Value = serde_json::from_slice(&bytes).expect("invalid module provenance"); let mut portable = Map::new(); - // Exclude the bootstrap cache path: it is not part of the built product. + // Exclude the toolchain cache path: it is not part of the built product. for key in [ "wave_revision", "target", @@ -36,8 +36,11 @@ fn provenance(directory: &Path) -> Value { "archive_sha256", "compiler_sha256", "std_sha256", - "bootstrap_rust_version", - "required_llvm_major", + "compiler_version", + "nightly_archive_sha256", + "vex_version", + "vex_sha256", + "vex_provenance_sha256", ] { let value = original.get(key).unwrap_or_else(|| panic!("missing provenance {key}")); portable.insert(key.into(), value.clone()); diff --git a/examples/external-target/Cargo.toml b/examples/external-target/Cargo.toml index d950c1c..0c744c5 100644 --- a/examples/external-target/Cargo.toml +++ b/examples/external-target/Cargo.toml @@ -6,8 +6,8 @@ rust-version.workspace = true publish = false [dependencies] -assembler = { path = "../../assembler" } -ir = { path = "../../ir" } +assembler = { path = "../../bindings/rust/assembler" } +ir = { path = "../../bindings/rust/ir" } target-spec = { path = "../../target-spec" } backend-api = { path = "../../backend-api" } toolchain = { path = "../../toolchain" } diff --git a/ir/build.rs b/ir/build.rs deleted file mode 100644 index 14b2e81..0000000 --- a/ir/build.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -use std::{collections::BTreeMap, env, fs, io::Read, path::PathBuf}; - -const PIN: &str = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"; - -const SOURCES: &[&str] = &[ - "model.wave", - "layout.wave", - "lexer.wave", - "header.wave", - "type_parser.wave", - "literal.wave", - "expression_parser.wave", - "instruction_parser.wave", - "module_parser.wave", - "lower_hir.wave", - "lower_model.wave", - "lower_output.wave", - "lower_expression.wave", - "lower_storage.wave", - "lower_statement.wave", - "lower_driver.wave", - "builder.wave", - "builder_namespace.wave", - "builder_body.wave", - "verify.wave", - "verifier_index.wave", - "verifier_ssa.wave", - "printer.wave", - "cfg.wave", - "shape.wave", - "source.wave", - "memory.wave", - "lower_limits.wave", - "wide.wave", - "integer.wave", - "float_model.wave", - "float_arithmetic.wave", - "float_convert.wave", - "effects.wave", - "passes.wave", - "fold_integer.wave", - "constant.wave", - "constant_dependencies.wave", - "runtime_model.wave", - "runtime_prepare.wave", - "runtime_execute.wave", - "runtime_driver.wave", - "bytecode_model.wave", - "bytecode_inventory.wave", - "bytecode_loader.wave", - "bytecode_verify_types.wave", - "bytecode_verify_instructions.wave", - "bytecode_verify_flow.wave", - "bytecode_verify.wave", - "bytecode_writer.wave", - "bytecode_runtime.wave", - "entry.wave", -]; - -const ABI_SOURCES: &[&str] = &[ - "src/wave_layout.rs", - "src/interpreter/integer.rs", - "src/float/wave.rs", - "src/effects_wave.rs", - "src/pass_wave.rs", - "src/fold_integer_wave.rs", - "src/constant_wave.rs", - "src/interpreter/runtime_wave.rs", - "src/bytecode.rs", - "src/verifier/wave_constants.rs", - "src/source_wave.rs", - "src/interpreter/memory_wave.rs", - "src/lower_ast/wave_limits.rs", - "src/parser/wave_lexer.rs", - "src/parser/wave_header.rs", - "src/parser/wave_text.rs", - "src/parser/wave_type.rs", - "src/parser/wave_literal.rs", - "src/parser/wave_expression.rs", - "src/parser/wave_instruction.rs", - "src/parser/wave_module.rs", - "src/lower_ast/wave_hir.rs", - "src/lower_ast/wave_lower.rs", - "src/builder/wave.rs", - "src/builder/namespace.rs", - "src/builder/body.rs", - "src/verifier/wave_semantics.rs", - "src/verifier/wave_index.rs", - "src/verifier/wave_ssa.rs", - "src/printer_wave.rs", - "src/verifier/wave_cfg.rs", - "src/verifier/wave_shape.rs", - "src/lib.rs", - "src/function.rs", - "src/global_storage.rs", -]; - -fn update(hash: u64, bytes: &[u8]) -> u64 { - bytes.iter().fold(hash, |h, byte| (h ^ u64::from(*byte)).wrapping_mul(0x100000001b3)) -} - -fn hash(bytes: &[u8]) -> String { - format!("{:016x}", update(0xcbf29ce484222325, bytes)) -} - -fn hash_file(path: &std::path::Path, maximum: Option) -> String { - let mut file = fs::File::open(path) - .unwrap_or_else(|_| panic!("missing Wave IR artifact {}", path.display())); - let mut value = 0xcbf29ce484222325; - let mut seen = 0; - let mut buffer = [0; 16384]; - loop { - let count = file.read(&mut buffer).expect("cannot read Wave IR artifact"); - if count == 0 { - return format!("{value:016x}"); - } - seen += count as u64; - if maximum.is_some_and(|limit| seen > limit) { - panic!("oversized Wave IR artifact {}", path.display()); - } - value = update(value, &buffer[..count]); - } -} - -fn main() { - println!("cargo:rustc-check-cfg=cfg(whale_wave_ir)"); - println!("cargo:rerun-if-env-changed=WHALE_WAVE_IR_DIR"); - println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUST_REFERENCE"); - let Some(directory) = env::var_os("WHALE_WAVE_IR_DIR") else { - assert!(env::var_os("CARGO_FEATURE_RUST_REFERENCE").is_some(), - "IR requires its Wave module; build with Meson or select rust-reference explicitly for comparison"); - return; - }; - let directory = PathBuf::from(directory).canonicalize().expect("WHALE_WAVE_IR_DIR must exist"); - let target = env::var("TARGET").expect("Cargo target required"); - let archive = directory.join(if target.contains("msvc") { - "whale_wave_ir.lib" - } else { - "libwhale_wave_ir.a" - }); - let metadata = directory.join("wave-ir.meta"); - let provenance = directory.join("provenance.json"); - for path in [&archive, &metadata, &provenance] { - println!("cargo:rerun-if-changed={}", path.display()); - } - let mut text = String::new(); - fs::File::open(&metadata) - .expect("missing wave-ir.meta; build with tools/build_wave_ir.py") - .take(4097) - .read_to_string(&mut text) - .expect("invalid Wave IR metadata"); - assert!(text.len() <= 4096, "oversized Wave IR metadata"); - let mut fields = BTreeMap::new(); - for line in text.lines() { - let (key, value) = line.split_once('=').expect("malformed Wave IR metadata"); - assert!( - [ - "schema", - "target", - "wave_revision", - "opt_level", - "source_fnv64", - "abi_fnv64", - "archive_fnv64", - "provenance_fnv64" - ] - .contains(&key) - && fields.insert(key, value).is_none(), - "invalid Wave IR metadata fields" - ); - } - assert_eq!(fields.len(), 8, "incomplete Wave IR metadata"); - assert_eq!(fields.get("schema"), Some(&"1"), "unsupported Wave IR metadata"); - assert_eq!(fields.get("target"), Some(&target.as_str()), "Wave IR target mismatch"); - assert_eq!(fields.get("wave_revision"), Some(&PIN), "Wave IR compiler revision mismatch"); - assert!( - [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), - "unsupported Wave IR optimization level" - ); - let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); - let mut source = Vec::new(); - for (index, name) in SOURCES.iter().enumerate() { - let path = root.join(name); - println!("cargo:rerun-if-changed={}", path.display()); - if index != 0 { - source.push(b'\n'); - } - source.extend(fs::read(path).expect("missing Wave IR source")); - } - assert_eq!(fields.get("source_fnv64"), Some(&hash(&source).as_str()), "stale Wave IR archive"); - let mut abi = Vec::new(); - for (index, name) in ABI_SOURCES.iter().enumerate() { - let path = root.join(name); - println!("cargo:rerun-if-changed={}", path.display()); - if index != 0 { - abi.push(b'\n'); - } - abi.extend(fs::read(path).expect("missing Wave IR ABI source")); - } - assert_eq!(fields.get("abi_fnv64"), Some(&hash(&abi).as_str()), "stale Wave IR ABI"); - assert_eq!( - fields.get("archive_fnv64"), - Some(&hash_file(&archive, None).as_str()), - "corrupt Wave IR archive" - ); - assert_eq!( - fields.get("provenance_fnv64"), - Some(&hash_file(&provenance, Some(16 * 1024)).as_str()), - "corrupt Wave IR provenance" - ); - println!("cargo:rustc-link-search=native={}", directory.display()); - println!("cargo:rustc-link-lib=static=whale_wave_ir"); - println!("cargo:rustc-cfg=whale_wave_ir"); -} diff --git a/ir/lower_storage.wave b/ir/lower_storage.wave deleted file mode 100644 index 46a127f..0000000 --- a/ir/lower_storage.wave +++ /dev/null @@ -1,226 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Frontend aggregates denote addresses; scalar expressions denote SSA values. -// Copying an aggregate snapshots the RHS before touching a possibly aliasing LHS. -fun ir_lower_alloca(p: ptr, ty: u64, align: u64, node: u64, output: ptr) -> bool { - var pointer: u64 = 0; - var value: u64 = 0; - if (!ir_lower_pointer(p.core, ty, node, &pointer) - || !ir_lower_value(p, pointer, node, &value) - || !ir_lower_emit(p, 18, value, ty, align, 0, 0, 0, 0, null, 0, true, node)) { return false; } - output[0] = value; return true; -} - -fun ir_lower_read(p: ptr, pointer: u64, ty: u64, node: u64, - output: ptr) -> bool { - if (ir_lower_aggregate(p.core, ty)) { output.value = pointer; output.ty = ty; return true; } - if (!ir_lower_layout(p.core, ty, node)) { return false; } - var value: u64 = 0; - if (!ir_lower_value(p, ty, node, &value) - || !ir_lower_emit(p, 21, value, ty, pointer, p.core.layouts[ty].allocation_align, - 0, 0, 0, null, 0, false, node)) { return false; } - output.value = value; output.ty = ty; return true; -} - -fun ir_lower_write(p: ptr, pointer: u64, value: u64, ty: u64, node: u64) -> bool { - if (!ir_lower_layout(p.core, ty, node)) { return false; } - var align: u64 = p.core.layouts[ty].align; - if (!ir_lower_aggregate(p.core, ty)) { - return ir_lower_emit(p, 23, 18446744073709551615, ty, - value, pointer, align, 0, 0, null, 0, false, node); - } - if (pointer == value) { return true; } - var temporary: u64 = 0; - var byte_pointer: u64 = 0; - var aggregate_pointer: u64 = 0; - var destination: u64 = 0; - var source: u64 = 0; - var snapshot: u64 = 0; - var size: u64 = 0; - if (!ir_lower_alloca(p, ty, align, node, &temporary) - || !ir_lower_pointer(p.core, 9, node, &byte_pointer) - || !ir_lower_pointer(p.core, ty, node, &aggregate_pointer) - || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, pointer, node, &destination) - || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, value, node, &source) - || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, temporary, node, &snapshot) - || !ir_lower_immediate(p, 12, p.core.layouts[ty].size, 0, node, &size) - || !ir_lower_emit(p, 25, 18446744073709551615, 18446744073709551615, - snapshot, source, size, align, 0, null, 0, false, node) - || !ir_lower_emit(p, 25, 18446744073709551615, 18446744073709551615, - destination, snapshot, size, align, 0, null, 0, false, node)) { return false; } - return true; -} - -fun ir_lower_field_pointer(p: ptr, base: u64, ordinal: u64, ty: u64, - node: u64, output: ptr) -> bool { - var zero: u64 = 0; - var index: u64 = 0; - var pointer: u64 = 0; - var destination: u64 = 0; - var indices: array; - if (!ir_lower_immediate(p, 12, 0, 0, node, &zero) - || !ir_lower_immediate(p, 12, ordinal, 0, node, &index) - || !ir_lower_pointer(p.core, ty, node, &pointer) - || !ir_lower_value(p, pointer, node, &destination)) { return false; } - indices[0] = zero; indices[1] = index; - if (!ir_lower_emit(p, 24, destination, pointer, base, 0, 0, 0, 0, - &indices[0], 2, false, node)) { return false; } - output[0] = destination; return true; -} - -fun ir_lower_place(p: ptr, node: u64, depth: u64, - output: ptr) -> bool { - if (!ir_lower_node(p.core, node, depth)) { return false; } - var n: ptr = &p.core.nodes[node]; - if (n.tag == 0) { - var saved: u64 = p.core.annotation; p.core.annotation = n.a; - var success: bool = ir_lower_place(p, n.b, depth + 1, output) - && ir_lower_complete_source(p, n.a, node); - p.core.annotation = saved; return success; - } - if (n.tag == 15) { - var binding: IrLowerBinding; - if (!ir_lower_name(p.core, n.a, node) || !ir_lower_local_binding(p, n.a, node, &binding)) { return false; } - if (binding.kind != 0) { return ir_lower_fail(p.core, 12, node, 0, 0, n.a); } - output.value = binding.value; output.ty = binding.ty; return true; - } - var base: IrLowerValue; - if (n.tag == 6) { - if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } - if (p.core.types[base.ty].kind != 17 || p.core.types[base.ty].child == 0) { - return ir_lower_fail(p.core, 7, node, 0, 0, 0); - } - output.value = base.value; output.ty = p.core.types[base.ty].child; return true; - } - if (n.tag == 3) { - var expected: u64 = 0; - if (!ir_lower_type(p.core, n.b, 0, &expected)) { return false; } - if (p.core.nodes[n.b].tag != 107 || !ir_lower_name(p.core, n.c, node)) { - return ir_lower_fail(p.core, 7, node, 0, 0, 0); - } - var layout: ptr = &p.core.nodes[n.b]; - var ordinal: u64 = 0; - while (ordinal < layout.b) { - if (!ir_lower_charge(p.core, 1, node)) { return false; } - if (p.core.nodes[p.core.edges[layout.a + ordinal]].a == n.c) { break; } - ordinal += 1; - } - if (ordinal == layout.b) { return ir_lower_fail(p.core, 18, node, 0, 0, 3); } - var ty: u64 = p.core.type_edges[p.core.types[expected].first + ordinal]; - if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } - if (base.ty != expected) { return ir_lower_fail(p.core, 6, node, expected, base.ty, 0); } - var pointer: u64 = 0; - if (!ir_lower_field_pointer(p, base.value, ordinal, ty, node, &pointer)) { return false; } - output.value = pointer; output.ty = ty; return true; - } - if (n.tag == 4) { - if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } - if (p.core.types[base.ty].kind != 19) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } - var element: u64 = p.core.types[base.ty].child; - var length: u64 = p.core.types[base.ty].auxiliary; - var index: IrLowerValue; - if (!ir_lower_expression(p, n.b, depth + 1, false, &index)) { return false; } - if (!ir_lower_integer(index.ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } - var zero: u64 = 0; - var bad: u64 = 0; - if (ir_lower_signed(index.ty)) { - if (!ir_lower_immediate(p, index.ty, 0, 0, node, &zero) - || !ir_lower_value(p, 1, node, &bad) - || !ir_lower_emit(p, 11, bad, index.ty, 6, index.value, zero, 0, 0, null, 0, false, node) - || !ir_lower_emit(p, 30, 18446744073709551615, 1, - bad, 1, 0, 0, 0, null, 0, false, node)) { return false; } - } - var converted: u64 = 0; - var limit: u64 = 0; - if (!ir_lower_cast_value(p, 0, index.ty, 13, index.value, node, &converted) - || !ir_lower_immediate(p, 13, length, 0, node, &limit) - || !ir_lower_value(p, 1, node, &bad) - || !ir_lower_emit(p, 11, bad, 13, 5, converted, limit, 0, 0, null, 0, false, node) - || !ir_lower_emit(p, 30, 18446744073709551615, 1, - bad, 1, 0, 0, 0, null, 0, false, node) - || !ir_lower_immediate(p, 12, 0, 0, node, &zero)) { return false; } - var pointer: u64 = 0; - var destination: u64 = 0; - var indices: array; - if (!ir_lower_pointer(p.core, element, node, &pointer) - || !ir_lower_value(p, pointer, node, &destination)) { return false; } - indices[0] = zero; indices[1] = converted; - if (!ir_lower_emit(p, 24, destination, pointer, base.value, 0, 0, 0, 0, - &indices[0], 2, false, node)) { return false; } - output.value = destination; output.ty = element; return true; - } - return ir_lower_fail(p.core, 7, node, 0, 0, 0); -} - -fun ir_lower_field_map(p: ptr, layout: u64, node: u64) -> bool { - var t: ptr = &p.core.nodes[layout]; - var at: u64 = 0; - while (at < t.b) { - if (!ir_lower_charge(p.core, 1, node)) { return false; } - if (p.field_binding_count >= p.field_binding_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } - var name: u64 = p.core.nodes[p.core.edges[t.a + at]].a; - var id: u64 = p.field_binding_count; - p.field_bindings[id].name = name; p.field_bindings[id].ordinal = at; - p.field_bindings[id].previous = p.field_slots[name]; p.field_bindings[id].used = 0; - p.field_slots[name] = id; p.field_binding_count += 1; at += 1; - } - return true; -} - -fun ir_lower_aggregate_literal(p: ptr, node: u64, depth: u64, - output: ptr) -> bool { - var n: ptr = &p.core.nodes[node]; - var ty: u64 = 0; - if (!ir_lower_type(p.core, n.a, 0, &ty) || !ir_lower_layout(p.core, ty, node)) { return false; } - var align: u64 = p.core.layouts[ty].align; - var pointer: u64 = 0; - if (!ir_lower_alloca(p, ty, align, node, &pointer) - || !ir_lower_emit(p, 22, 18446744073709551615, ty, - pointer, align, 0, 0, 0, null, 0, false, node) - || !ir_lower_edges(p.core, n.b, n.c, node)) { return false; } - var at: u64 = 0; - var actual: IrLowerValue; - var destination: u64 = 0; - if (n.tag == 1 && p.core.types[ty].kind == 20 && p.core.nodes[n.a].tag == 107) { - if (n.c != p.core.types[ty].count) { return ir_lower_fail(p.core, 18, node, 0, 0, 4); } - var saved: u64 = p.field_binding_count; - if (!ir_lower_field_map(p, n.a, node)) { return false; } - while (at < n.c) { - var init: u64 = p.core.edges[n.b + at]; - if (!ir_lower_node(p.core, init, depth + 1) || p.core.nodes[init].tag != 24) { - return ir_lower_fail(p.core, 3, init, 0, 0, 0); - } - var name: u64 = p.core.nodes[init].a; - if (!ir_lower_name(p.core, name, init)) { return false; } - var binding: u64 = p.field_slots[name]; - if (binding == 18446744073709551615 || binding < saved) { - return ir_lower_fail(p.core, 18, init, 0, 0, 6); - } - if (p.field_bindings[binding].used != 0) { return ir_lower_fail(p.core, 18, init, 0, 0, 5); } - p.field_bindings[binding].used = 1; - var ordinal: u64 = p.field_bindings[binding].ordinal; - var expected: u64 = p.core.type_edges[p.core.types[ty].first + ordinal]; - if (!ir_lower_expression(p, p.core.nodes[init].b, depth + 1, false, &actual)) { return false; } - if (actual.ty != expected) { return ir_lower_fail(p.core, 6, init, expected, actual.ty, 0); } - if (!ir_lower_field_pointer(p, pointer, ordinal, expected, node, &destination) - || !ir_lower_write(p, destination, actual.value, expected, node)) { return false; } - at += 1; - } - while (p.field_binding_count > saved) { - p.field_binding_count -= 1; - var last: u64 = p.field_binding_count; - p.field_slots[p.field_bindings[last].name] = p.field_bindings[last].previous; - } - } else if (n.tag == 2 && p.core.types[ty].kind == 19) { - var element: u64 = p.core.types[ty].child; - if (!ir_lower_scalar(p.core, element)) { return ir_lower_fail(p.core, 18, node, 0, 0, 7); } - if (n.c != p.core.types[ty].auxiliary) { return ir_lower_fail(p.core, 18, node, 0, 0, 8); } - while (at < n.c) { - if (!ir_lower_expression(p, p.core.edges[n.b + at], depth + 1, false, &actual)) { return false; } - if (actual.ty != element) { return ir_lower_fail(p.core, 6, node, element, actual.ty, 0); } - if (!ir_lower_field_pointer(p, pointer, at, element, node, &destination) - || !ir_lower_write(p, destination, actual.value, element, node)) { return false; } - at += 1; - } - } else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } - output.value = pointer; output.ty = ty; return true; -} diff --git a/ir/meson.build b/ir/meson.build index 1930e87..1d7ea3e 100644 --- a/ir/meson.build +++ b/ir/meson.build @@ -1,124 +1,28 @@ # SPDX-License-Identifier: MPL-2.0 wave_ir_dependencies = [] wave_ir_directory = get_option('wave-ir-dir') -if wave_ir_directory == '' and wave_source != '' +if wave_ir_directory == '' and not get_option('rust-reference') wave_ir_directory = meson.current_build_dir() - module_target = cargo_host_target - if module_target == '' - target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} - module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] - endif archive_name = module_target.contains('msvc') ? 'whale_wave_ir.lib' : 'libwhale_wave_ir.a' - arguments = ['--wave-source', wave_source, '--out-dir', '@OUTDIR@', - '--bootstrap-dir', wave_cache, '--target', module_target, - '--rust-toolchain', get_option('wave-rust-toolchain')] - if get_option('wave-allow-network') - arguments += ['--allow-network'] - endif wave_ir_module = custom_target('wave-ir', - output: [archive_name, 'wave-ir.meta', 'provenance.json'], - command: [python, files('../tools/build_wave_ir.py'), arguments], - depend_files: files( - 'src/lib.rs', - 'model.wave', - 'layout.wave', - 'lexer.wave', - 'header.wave', - 'type_parser.wave', - 'literal.wave', - 'expression_parser.wave', - 'instruction_parser.wave', - 'module_parser.wave', - 'lower_hir.wave', - 'lower_model.wave', - 'lower_output.wave', - 'lower_expression.wave', - 'lower_storage.wave', - 'lower_statement.wave', - 'lower_driver.wave', - 'builder.wave', - 'builder_namespace.wave', - 'builder_body.wave', - 'verify.wave', - 'verifier_index.wave', - 'verifier_ssa.wave', - 'printer.wave', - 'cfg.wave', - 'shape.wave', - 'source.wave', - 'memory.wave', - 'lower_limits.wave', - 'wide.wave', - 'integer.wave', - 'float_model.wave', - 'float_arithmetic.wave', - 'float_convert.wave', - 'effects.wave', - 'passes.wave', - 'fold_integer.wave', - 'constant.wave', - 'constant_dependencies.wave', - 'runtime_model.wave', - 'runtime_prepare.wave', - 'runtime_execute.wave', - 'runtime_driver.wave', - 'bytecode_model.wave', - 'bytecode_inventory.wave', - 'bytecode_loader.wave', - 'bytecode_verify_types.wave', - 'bytecode_verify_instructions.wave', - 'bytecode_verify_flow.wave', - 'bytecode_verify.wave', - 'bytecode_writer.wave', - 'bytecode_runtime.wave', - 'entry.wave', - 'src/wave_layout.rs', - 'src/interpreter/integer.rs', - 'src/float/wave.rs', - 'src/effects_wave.rs', - 'src/pass_wave.rs', - 'src/fold_integer_wave.rs', - 'src/constant_wave.rs', - 'src/interpreter/runtime_wave.rs', - 'src/bytecode.rs', - 'src/verifier/wave_constants.rs', - 'src/source_wave.rs', - 'src/interpreter/memory_wave.rs', - 'src/lower_ast/wave_limits.rs', - 'src/parser/wave_lexer.rs', - 'src/parser/wave_header.rs', - 'src/parser/wave_text.rs', - 'src/parser/wave_type.rs', - 'src/parser/wave_literal.rs', - 'src/builder/wave.rs', - 'src/builder/namespace.rs', - 'src/builder/body.rs', - 'src/parser/wave_expression.rs', - 'src/parser/wave_instruction.rs', - 'src/parser/wave_module.rs', - 'src/lower_ast/wave_hir.rs', - 'src/lower_ast/wave_lower.rs', - 'src/verifier/wave_semantics.rs', - 'src/verifier/wave_index.rs', - 'src/verifier/wave_ssa.rs', - 'src/printer_wave.rs', - 'src/verifier/wave_cfg.rs', - 'src/verifier/wave_shape.rs', - 'src/function.rs', - 'src/global_storage.rs', - '../tools/build_wave_ir.py', - '../tools/wave_bootstrap.py', - ), - depends: wave_bootstrap, console: true) + output: [archive_name, 'module.meta', 'provenance.json'], + command: [python, files('../tools/vex_module.py'), '--module', 'ir', + '--vex', vex, '--toolchain', wave_toolchain, + '--build-dir', meson.project_build_root() / 'vex/ir', '--state-dir', wave_state, + '--output-dir', '@OUTDIR@', '--depfile', '@DEPFILE@', + '--target', module_target, '--profile', wave_profile], + depfile: 'module.d', depends: wave_prepared, + depend_files: files('vex.ws', '../tools/vex_module.py', '../tools/wave_modules.py'), + build_always_stale: true, console: true) wave_ir_dependencies += [wave_ir_module] elif wave_ir_directory != '' if not fs.is_absolute(wave_ir_directory) error('-Dwave-ir-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_wave_ir.lib' : 'libwhale_wave_ir.a' - foreach artifact : [archive_name, 'wave-ir.meta', 'provenance.json'] + foreach artifact : [archive_name, 'module.meta', 'provenance.json'] if not fs.is_file(wave_ir_directory / artifact) - error('Missing Wave IR module artifact: ' + (wave_ir_directory / artifact)) + error('Missing Wave ir artifact: ' + (wave_ir_directory / artifact)) endif endforeach endif diff --git a/ir/builder_body.wave b/ir/src/builder/body.wave similarity index 98% rename from ir/builder_body.wave rename to ir/src/builder/body.wave index 38bd1d6..7ae963f 100644 --- a/ir/builder_body.wave +++ b/ir/src/builder/body.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::lexer")::{ir_lex_utf8}; +import("whale_wave_ir::model")::{ir_span_valid}; + // Complete instruction/terminator bodies. Typed atoms and UTF-8 bytes are // validated before a single model field is published. Linked block records // retain insertion order and entry-hoisted allocations independently of Rust. @@ -151,7 +154,7 @@ fun ir_body_schema(r: ptr, op: u64) -> bool { // mode0 validates/probes; mode1 publishes. hoist1 inserts an alloca at the end // of the existing alloca prefix, even when entry already has a terminator. -export(c) fun whale_ir_builder_body(state: ptr, blocks: ptr, block_count: u64, +pub export(c) fun whale_ir_builder_body(state: ptr, blocks: ptr, block_count: u64, block: u64, op: u64, hoist: u64, atoms: ptr, atom_count: u64, bytes: ptr, byte_count: u64, depth: u64, const_depth: u64, node_limit: u64, byte_limit: u64, work_limit: u64, mode: u64, @@ -239,7 +242,7 @@ export(c) fun whale_ir_builder_body(state: ptr, blocks: ptr, id: u64, +pub export(c) fun whale_ir_builder_global(state: ptr, id: u64, globals: ptr, global_capacity: u64, atoms: ptr, atom_count: u64, bytes: ptr, byte_count: u64, depth: u64, const_depth: u64, node_limit: u64, byte_limit: u64, diff --git a/ir/builder.wave b/ir/src/builder/module.wave similarity index 92% rename from ir/builder.wave rename to ir/src/builder/module.wave index a028252..280b2db 100644 --- a/ir/builder.wave +++ b/ir/src/builder/module.wave @@ -1,20 +1,22 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; + // Exact typed construction model. Memory is owned by the caller; Wave validates // a transaction completely before publishing identities, types or block state. // Type tags match the typed IR inventory, never storage-size equivalence classes. -struct IrBuilderType { kind: u64; depth: u64; children: u64; auxiliary: u64; } +pub struct IrBuilderType { kind: u64; depth: u64; children: u64; auxiliary: u64; } -struct IrBuilderValue { id: u64; first_type: u64; type_count: u64; } +pub struct IrBuilderValue { id: u64; first_type: u64; type_count: u64; } struct IrBuilderBlock { id: u64; terminated: u64; non_phi: u64; } -struct IrBuilderState { next_value: u64; next_block: u64; type_count: u64; instruction_count: u64; namespace_nodes: u64; namespace_bytes: u64; next_function: u64; next_global: u64; work: u64; } +pub struct IrBuilderState { next_value: u64; next_block: u64; type_count: u64; instruction_count: u64; namespace_nodes: u64; namespace_bytes: u64; next_function: u64; next_global: u64; work: u64; } -struct IrBuilderResult { status: u64; detail: u64; value: u64; work: u64; } +pub struct IrBuilderResult { status: u64; detail: u64; value: u64; work: u64; } // 1 invalid transport/model; 2 depth; 3 nodes; 4 work; 5 identity overflow; // 6 unknown block; 7 terminated block; 8 unknown value; 9 phi order. -fun ir_builder_type_check(types: ptr, count: u64, depth_limit: u64, +pub fun ir_builder_type_check(types: ptr, count: u64, depth_limit: u64, node_limit: u64, work_limit: u64, result: ptr) -> i32 { if (!ir_span_valid(types as ptr, count, 32) || count == 0) { return 1; } if (count > node_limit) { return 3; } @@ -50,7 +52,7 @@ fun ir_builder_type_check(types: ptr, count: u64, depth_limit: u6 return 0; } -export(c) fun whale_ir_builder_type(types: ptr, count: u64, +pub export(c) fun whale_ir_builder_type(types: ptr, count: u64, depth_limit: u64, node_limit: u64, work_limit: u64, result: ptr) -> i32 { if (result == null) { return 1; } @@ -62,7 +64,7 @@ export(c) fun whale_ir_builder_type(types: ptr, count: u64, // mode 0 probes without mutation; mode 1 publishes the complete append. // kind 0 appends a typed value; kind 1 appends a basic block. -export(c) fun whale_ir_builder_allocate(state: ptr, kind: u64, +pub export(c) fun whale_ir_builder_allocate(state: ptr, kind: u64, types: ptr, count: u64, depth_limit: u64, node_limit: u64, work_limit: u64, mode: u64, output_types: ptr, type_capacity: u64, output_values: ptr, value_capacity: u64, @@ -133,7 +135,7 @@ export(c) fun whale_ir_builder_allocate(state: ptr, kind: u64, // NullFunction, FunctionAddr, Call, TrapIf; Br, CBr/Switch, Ret/Trap. // check_only skips publication. Op 34 checks identities, 35 checks insertion; // op 36 inserts an entry-hoisted alloca before its existing terminator. -export(c) fun whale_ir_builder_order(state: ptr, node_limit: u64, blocks: ptr, block_count: u64, +pub export(c) fun whale_ir_builder_order(state: ptr, node_limit: u64, blocks: ptr, block_count: u64, first_block: u64, first_value: u64, value_end: u64, block: u64, op: u64, operands: ptr, operand_count: u64, targets: ptr, target_count: u64, check_only: u64, diff --git a/ir/builder_namespace.wave b/ir/src/builder/namespace.wave similarity index 96% rename from ir/builder_namespace.wave rename to ir/src/builder/namespace.wave index 3af94a8..b1ced28 100644 --- a/ir/builder_namespace.wave +++ b/ir/src/builder/namespace.wave @@ -1,4 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::builder::module")::{ + IrBuilderResult, + IrBuilderState, + IrBuilderType, + IrBuilderValue, + ir_builder_type_check, +}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; + // Module-owned function/global namespaces. String/type memory stays in the // caller's immutable arena; Wave owns identity, equality and collision rules. struct IrBuilderNamespace { @@ -55,7 +64,7 @@ fun ir_builder_namespace_signature(types: ptr, count: u64) -> i32 // Namespace errors: 10 duplicate global name, 11 link collision, 12 conflicting // function declaration, 16 link-name contract, 17 malformed callable signature, // 18 unsupported SysV64 aggregate signature. detail=1 means existing declaration. -export(c) fun whale_ir_builder_namespace(state: ptr, +pub export(c) fun whale_ir_builder_namespace(state: ptr, entries: ptr, entry_count: u64, candidate: ptr, mode: u64, legacy: u64, depth_limit: u64, node_limit: u64, byte_limit: u64, work_limit: u64, output: ptr, output_capacity: u64, @@ -209,7 +218,7 @@ fun ir_builder_namespace_literal(kind: u64, literal: u64, low: u64, high: u64) - // Queries do not publish definition state. Marking occurs only when a complete // FunctionBuilder is committed, so dropping an unfinished builder remains safe. -export(c) fun whale_ir_builder_definition(entries: ptr, count: u64, +pub export(c) fun whale_ir_builder_definition(entries: ptr, count: u64, id: u64, parameter_count: u64, mode: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 1; } result.status = 0; result.detail = 0; result.value = 0; result.work = 0; @@ -235,7 +244,7 @@ export(c) fun whale_ir_builder_definition(entries: ptr, coun result.status = 13; return 13; } -export(c) fun whale_ir_builder_function_lookup(entries: ptr, count: u64, +pub export(c) fun whale_ir_builder_function_lookup(entries: ptr, count: u64, name: ptr, name_count: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 1; } result.status = 0; result.detail = 0; result.value = 0; result.work = 0; @@ -266,7 +275,7 @@ fun ir_builder_subtree_end(types: ptr, count: u64, begin: u64, } // 21 non-function pointer, 22 argument count, 23 argument type (detail=index). -export(c) fun whale_ir_builder_call(types: ptr, type_count: u64, +pub export(c) fun whale_ir_builder_call(types: ptr, type_count: u64, values: ptr, value_count: u64, first_value: u64, entries: ptr, entry_count: u64, indirect: u64, callee: u64, arguments: ptr, argument_count: u64, check_arguments: u64, @@ -340,7 +349,7 @@ export(c) fun whale_ir_builder_call(types: ptr, type_count: u64, return 0; } -export(c) fun whale_ir_builder_signature(types: ptr, count: u64, +pub export(c) fun whale_ir_builder_signature(types: ptr, count: u64, depth: u64, nodes: u64, work: u64, result: ptr) -> i32 { if (result == null) { return 1; } result.status = 0; result.detail = 0; result.value = 0; result.work = 0; @@ -352,7 +361,7 @@ export(c) fun whale_ir_builder_signature(types: ptr, count: u64, result.status = status as u64; return status; } -export(c) fun whale_ir_builder_pointer(types: ptr, type_count: u64, +pub export(c) fun whale_ir_builder_pointer(types: ptr, type_count: u64, values: ptr, value_count: u64, first_value: u64, lhs: u64, rhs: u64, pair: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 1; } @@ -383,7 +392,7 @@ export(c) fun whale_ir_builder_pointer(types: ptr, type_count: u6 return 0; } -export(c) fun whale_ir_builder_function_capacity(state: ptr, +pub export(c) fun whale_ir_builder_function_capacity(state: ptr, entries: ptr, count: u64, id: u64, node_limit: u64, work_limit: u64, result: ptr) -> i32 { if (result == null) { return 1; } diff --git a/ir/bytecode_inventory.wave b/ir/src/bytecode/inventory.wave similarity index 92% rename from ir/bytecode_inventory.wave rename to ir/src/bytecode/inventory.wave index 78da2c4..de8c281 100644 --- a/ir/bytecode_inventory.wave +++ b/ir/src/bytecode/inventory.wave @@ -1,4 +1,24 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + ir_bytecode_charge, + ir_bytecode_fail, +}; +import("whale_wave_ir::bytecode::verify_types")::{ir_bytecode_value_type}; +import("whale_wave_ir::interpreter::model")::{ + IrRuntimeBlock, + IrRuntimeFunction, + IrRuntimeInstruction, +}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyType, + ir_verify_cast, + ir_verify_float, + ir_verify_integer, +}; + // Whole-program executable admission. Structural verification runs first, so // every index below already names a validated record. Unreachable bodies are // deliberately checked as well: a file never advertises a partly executable VM. @@ -119,7 +139,7 @@ fun ir_bytecode_executable_instruction(program: ptr, return true; } -fun ir_bytecode_inventory(program: ptr, +pub fun ir_bytecode_inventory(program: ptr, limits: ptr, result: ptr) -> bool { var global: u64 = 0; var function_index: u64 = 0; diff --git a/ir/bytecode_loader.wave b/ir/src/bytecode/loader.wave similarity index 76% rename from ir/bytecode_loader.wave rename to ir/src/bytecode/loader.wave index 621620d..4648d58 100644 --- a/ir/bytecode_loader.wave +++ b/ir/src/bytecode/loader.wave @@ -1,4 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + ir_bytecode_charge, + ir_bytecode_count, + ir_bytecode_data, + ir_bytecode_fail, + ir_bytecode_native_stride, + ir_bytecode_result_init, + ir_bytecode_stride, +}; +import("whale_wave_ir::bytecode::verify")::{ir_bytecode_verify_impl}; +import("whale_wave_ir::bytecode::workspace")::{ir_bytecode_sizes}; +import("whale_wave_ir::model")::{ir_span_valid}; +import("whale_wave_ir::interpreter::model")::{IrRuntimeGlobal, IrRuntimeInstruction}; + // Canonical little-endian decoding. Lengths are checked before allocation or reads. fun ir_bytecode_read(data: ptr, at: u64) -> u64 { var value: u64 = 0; @@ -10,58 +27,9 @@ fun ir_bytecode_read(data: ptr, at: u64) -> u64 { return value; } -fun ir_bytecode_sizes(counts: ptr, limits: ptr, - result: ptr) -> bool { - var values: ptr = counts as ptr; - var total: u64 = 0; - var records: u64 = 0; - var table: u64 = 1; - while (table <= 16) { - var count: u64 = values[table - 1]; - var stride: u64 = ir_bytecode_native_stride(table); - if (count > limits.max_decoded_bytes / stride - || count * stride > limits.max_decoded_bytes - total) { - return ir_bytecode_fail(result, 2, 2, table, count); - } - total += count * stride; - if (table != 11) { - if (records > limits.max_records || count > limits.max_records - records) { - return ir_bytecode_fail(result, 2, 3, table, count); - } - records += count; - } - table += 1; - } - // A linear bound for CFG, SSA, source indexes and initialized type scratch. - var words: u64 = 256; - table = 1; - while (table <= 16) { - var factor: u64 = 32; - if (table == 4) { factor = 96; } - if (table == 6) { factor = 48; } - if (table == 7) { factor = 32; } - if (table == 15) { factor = 0; } - if (table == 11) { factor = 0; } - var count: u64 = values[table - 1]; - if (factor != 0 && count > (18446744073709551615 - words) / factor) { - return ir_bytecode_fail(result, 2, 4, table, count); - } - words += count * factor; - table += 1; - } - if (words > limits.max_workspace_bytes / 8 - || total > limits.max_workspace_bytes - words * 8) { - return ir_bytecode_fail(result, 2, 4, 0, words); - } - result.decoded_bytes = total; - result.scratch_words = words; - // Probe/query excludes semantic metadata; full admission adds its retained - // and transient clone allowance before reporting a successful estimate. - result.estimated_workspace_bytes = total + words * 8; - return true; -} -export(c) fun whale_ir_bytecode_probe(data: ptr, count: u64, + +pub export(c) fun whale_ir_bytecode_probe(data: ptr, count: u64, limits: ptr, result: ptr) -> i32 { if (result == null) { return 4; } ir_bytecode_result_init(result); @@ -111,7 +79,7 @@ export(c) fun whale_ir_bytecode_probe(data: ptr, count: u64, return 0; } -export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, +pub export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, program: ptr, scratch: ptr, capacity: u64, limits: ptr, result: ptr) -> i32 { // Reuse loop storage at O0; file-controlled iterations must not grow the stack. diff --git a/ir/bytecode_model.wave b/ir/src/bytecode/model.wave similarity index 76% rename from ir/bytecode_model.wave rename to ir/src/bytecode/model.wave index 2f597fa..5b3742b 100644 --- a/ir/bytecode_model.wave +++ b/ir/src/bytecode/model.wave @@ -1,14 +1,23 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::interpreter::model")::{ + IrRuntimeBlock, + IrRuntimeFunction, + IrRuntimeGlobal, + IrRuntimeInstruction, +}; +import("whale_wave_ir::source")::{IrSourceMapping, IrSourceOriginal}; +import("whale_wave_ir::verifier::module")::{IrVerifyType}; + // Portable file fields are encoded individually. These pointers are transport, // never file contents or executable pointer authority. -struct IrBytecodeSite { +pub struct IrBytecodeSite { function: u64; block: u64; instruction: u64; value: u64; } -struct IrBytecodeText { +pub struct IrBytecodeText { first: u64; count: u64; } @@ -18,7 +27,7 @@ struct IrBytecodeFile { text: u64; } -struct IrBytecodeCounts { +pub struct IrBytecodeCounts { types: u64; edges: u64; functions: u64; @@ -37,7 +46,7 @@ struct IrBytecodeCounts { constant_globals: u64; } -struct IrBytecodeProgram { +pub struct IrBytecodeProgram { types: ptr; type_count: u64; edges: ptr; @@ -72,7 +81,7 @@ struct IrBytecodeProgram { constant_global_count: u64; } -struct IrBytecodeLimits { +pub struct IrBytecodeLimits { max_input_bytes: u64; max_decoded_bytes: u64; max_records: u64; @@ -81,7 +90,7 @@ struct IrBytecodeLimits { max_workspace_bytes: u64; } -struct IrBytecodeResult { +pub struct IrBytecodeResult { status: u64; code: u64; table: u64; @@ -93,7 +102,7 @@ struct IrBytecodeResult { counts: IrBytecodeCounts; } -fun ir_bytecode_fail(result: ptr, status: u64, +pub fun ir_bytecode_fail(result: ptr, status: u64, code: u64, table: u64, index: u64) -> bool { result.status = status; result.code = code; @@ -102,7 +111,7 @@ fun ir_bytecode_fail(result: ptr, status: u64, return false; } -fun ir_bytecode_charge(result: ptr, limits: ptr, +pub fun ir_bytecode_charge(result: ptr, limits: ptr, amount: u64) -> bool { if (result.work > limits.max_work || amount > limits.max_work - result.work) { return ir_bytecode_fail(result, 3, 1, result.table, result.index); @@ -111,7 +120,7 @@ fun ir_bytecode_charge(result: ptr, limits: ptr) { +pub fun ir_bytecode_result_init(result: ptr) { var words: ptr = result as ptr; var i: u64 = 0; while (i < 24) { @@ -120,7 +129,7 @@ fun ir_bytecode_result_init(result: ptr) { } } -fun ir_bytecode_stride(table: u64) -> u64 { +pub fun ir_bytecode_stride(table: u64) -> u64 { if (table == 1) { return 40; } if (table == 3) { return 88; } if (table == 4 || table == 9) { return 32; } @@ -133,18 +142,18 @@ fun ir_bytecode_stride(table: u64) -> u64 { return 8; } -fun ir_bytecode_native_stride(table: u64) -> u64 { +pub fun ir_bytecode_native_stride(table: u64) -> u64 { if (table == 5) { return 168; } if (table == 8) { return 216; } return ir_bytecode_stride(table); } -fun ir_bytecode_count(program: ptr, table: u64) -> u64 { +pub fun ir_bytecode_count(program: ptr, table: u64) -> u64 { var words: ptr = program as ptr; return words[(table - 1) * 2 + 1]; } -fun ir_bytecode_data(program: ptr, table: u64) -> ptr { +pub fun ir_bytecode_data(program: ptr, table: u64) -> ptr { var words: ptr = program as ptr; return words[(table - 1) * 2] as ptr; } diff --git a/ir/bytecode_runtime.wave b/ir/src/bytecode/runtime.wave similarity index 77% rename from ir/bytecode_runtime.wave rename to ir/src/bytecode/runtime.wave index d87da30..5660225 100644 --- a/ir/bytecode_runtime.wave +++ b/ir/src/bytecode/runtime.wave @@ -1,7 +1,17 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, +}; +import("whale_wave_ir::bytecode::verify")::{whale_ir_bytecode_verify}; +import("whale_wave_ir::interpreter::driver")::{whale_ir_runtime_step}; +import("whale_wave_ir::interpreter::model")::{IrRuntimeDriver}; +import("whale_wave_ir::interpreter::prepare")::{ir_runtime_backend}; + // Bytecode admission precedes the existing tracked-memory execution engine. // Disk records never supply runtime layout plans or executable authority. -export(c) fun whale_ir_bytecode_runtime_step(program: ptr, +pub export(c) fun whale_ir_bytecode_runtime_step(program: ptr, driver: ptr, scratch: ptr, capacity: u64, limits: ptr, admission: ptr) -> i32 { if (program == null || driver == null || driver.result == null diff --git a/ir/bytecode_verify.wave b/ir/src/bytecode/verify.wave similarity index 91% rename from ir/bytecode_verify.wave rename to ir/src/bytecode/verify.wave index a1ddece..271beb5 100644 --- a/ir/bytecode_verify.wave +++ b/ir/src/bytecode/verify.wave @@ -1,4 +1,53 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::inventory")::{ir_bytecode_inventory}; +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + IrBytecodeSite, + IrBytecodeText, + ir_bytecode_charge, + ir_bytecode_count, + ir_bytecode_data, + ir_bytecode_fail, + ir_bytecode_native_stride, + ir_bytecode_result_init, +}; +import("whale_wave_ir::bytecode::verify_flow")::{ + ir_bytecode_function_flow, + ir_bytecode_has_destination, + ir_bytecode_target, + ir_bytecode_unique, +}; +import("whale_wave_ir::bytecode::verify_types")::{ + IrBytecodeDefinition, + IrBytecodeScratch, + IrBytecodeType, + IrBytecodeVerifier, + ir_bytecode_layouts, + ir_bytecode_metadata, + ir_bytecode_same, + ir_bytecode_take, + ir_bytecode_verify_types, +}; +import("whale_wave_ir::bytecode::workspace")::{ir_bytecode_sizes}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; +import("whale_wave_ir::interpreter::model")::{ + IrRuntimeBlock, + IrRuntimeFunction, + IrRuntimeGlobal, + IrRuntimeInstruction, +}; +import("whale_wave_ir::source")::{ + IrSourceBlock, + IrSourceFile, + IrSourceOriginal, + IrSourceResult, + IrSourceSlot, + whale_ir_verify_sources, +}; +import("whale_wave_ir::verifier::module")::{IrVerifyOperand, ir_verify_literal}; + // Complete admission precedes runtime effects. The exported query checks native // spans and computes bounded initialized scratch before traversing any table. fun ir_bytecode_verify_structure(context: ptr, @@ -254,7 +303,7 @@ fun ir_bytecode_verify_sources(context: ptr) -> bool { return true; } -fun ir_bytecode_verify_impl(program: ptr, words: ptr, capacity: u64, +pub fun ir_bytecode_verify_impl(program: ptr, words: ptr, capacity: u64, limits: ptr, result: ptr) -> i32 { if (program == null || limits == null || !ir_span_valid(words as ptr, capacity, 8)) { ir_bytecode_fail(result, 4, 1, 0, 0); @@ -332,7 +381,7 @@ fun ir_bytecode_verify_impl(program: ptr, words: ptr, ca return 0; } -export(c) fun whale_ir_bytecode_verify(program: ptr, words: ptr, capacity: u64, +pub export(c) fun whale_ir_bytecode_verify(program: ptr, words: ptr, capacity: u64, limits: ptr, result: ptr) -> i32 { if (result == null) { return 4; } ir_bytecode_result_init(result); diff --git a/ir/bytecode_verify_flow.wave b/ir/src/bytecode/verify_flow.wave similarity index 91% rename from ir/bytecode_verify_flow.wave rename to ir/src/bytecode/verify_flow.wave index c068227..0f645ab 100644 --- a/ir/bytecode_verify_flow.wave +++ b/ir/src/bytecode/verify_flow.wave @@ -1,7 +1,45 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + ir_bytecode_charge, + ir_bytecode_fail, +}; +import("whale_wave_ir::bytecode::verify_instructions")::{ + ir_bytecode_instruction, + ir_bytecode_operands, +}; +import("whale_wave_ir::bytecode::verify_types")::{ + IrBytecodeDefinition, + IrBytecodeVerifier, + ir_bytecode_take, +}; +import("whale_wave_ir::verifier::cfg")::{ + IrCfgBlock, + IrCfgResult, + whale_ir_cfg_idom, + whale_ir_cfg_rpo, +}; +import("whale_wave_ir::interpreter::model")::{ + IrRuntimeBlock, + IrRuntimeFunction, + IrRuntimeInstruction, +}; +import("whale_wave_ir::source")::{IrSourceSlot, ir_source_put, ir_source_slot}; +import("whale_wave_ir::verifier::ssa")::{ + IrSsaBlock, + IrSsaInstruction, + IrSsaPredecessor, + IrSsaResult, + IrSsaUse, + whale_ir_verify_ssa, +}; +import("whale_wave_ir::verifier::module")::{ir_verify_literal, ir_verify_unsigned}; + // All definition, predecessor and dominator facts are derived here, never read // from the file. The shared Wave CFG and SSA cores consume only these facts. -fun ir_bytecode_unique(table: ptr, capacity: u64, kind: u64, +pub fun ir_bytecode_unique(table: ptr, capacity: u64, kind: u64, a: u64, b: u64, c: u64, context: ptr) -> bool { var result: ptr = context.result; var at: u64 = ir_source_slot(table, capacity, kind, a, b, c, @@ -12,13 +50,13 @@ fun ir_bytecode_unique(table: ptr, capacity: u64, kind: u64, return true; } -fun ir_bytecode_has_destination(inst: ptr) -> bool { +pub fun ir_bytecode_has_destination(inst: ptr) -> bool { var op: u64 = inst.op; return op == 0 || (op >= 2 && op <= 19) || op == 21 || op == 24 || op == 27 || op == 28 || (op == 29 && inst.dst != 18446744073709551615); } -fun ir_bytecode_target(function: ptr, target: u64, +pub fun ir_bytecode_target(function: ptr, target: u64, context: ptr) -> bool { if (target < function.first_block || target - function.first_block >= function.block_count) { return ir_bytecode_fail(context.result, 1, 61, 5, context.result.index); @@ -51,7 +89,7 @@ fun ir_bytecode_cfg_status(context: ptr, cfg: ptr, function_index: u64, +pub fun ir_bytecode_function_flow(context: ptr, function_index: u64, identities: ptr, identity_capacity: u64) -> bool { var p: ptr = context.program; var limits: ptr = context.limits; diff --git a/ir/bytecode_verify_instructions.wave b/ir/src/bytecode/verify_instructions.wave similarity index 93% rename from ir/bytecode_verify_instructions.wave rename to ir/src/bytecode/verify_instructions.wave index e8d3134..ba7cac5 100644 --- a/ir/bytecode_verify_instructions.wave +++ b/ir/src/bytecode/verify_instructions.wave @@ -1,4 +1,30 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + ir_bytecode_charge, + ir_bytecode_fail, +}; +import("whale_wave_ir::bytecode::verify_types")::{ + IrBytecodeDefinition, + IrBytecodeVerifier, + ir_bytecode_same, + ir_bytecode_semantic, + ir_bytecode_semantic_init, + ir_bytecode_storable, +}; +import("whale_wave_ir::interpreter::model")::{IrRuntimeFunction, IrRuntimeInstruction}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyInstruction, + IrVerifyOperand, + IrVerifyResult, + IrVerifyType, + ir_verify_integer, + ir_verify_literal, + whale_ir_verify_semantics, +}; + // The bytecode uses runtime opcode numbers; verifier operations have a separate // namespace. Every operand is validated before either core sees its index. fun ir_bytecode_operand(context: ptr, function: ptr, @@ -18,7 +44,7 @@ fun ir_bytecode_operand(context: ptr, function: ptr, function: ptr, +pub fun ir_bytecode_operands(context: ptr, function: ptr, inst: ptr) -> u64 { var op: u64 = inst.op; var count: u64 = 0; @@ -105,7 +131,7 @@ fun ir_bytecode_destination(context: ptr, function: ptr, function: ptr, +pub fun ir_bytecode_instruction(context: ptr, function: ptr, inst: ptr) -> bool { var program: ptr = context.program; var limits: ptr = context.limits; diff --git a/ir/bytecode_verify_types.wave b/ir/src/bytecode/verify_types.wave similarity index 91% rename from ir/bytecode_verify_types.wave rename to ir/src/bytecode/verify_types.wave index 1ace6b7..a63386b 100644 --- a/ir/bytecode_verify_types.wave +++ b/ir/src/bytecode/verify_types.wave @@ -1,12 +1,34 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + IrBytecodeText, + ir_bytecode_charge, + ir_bytecode_count, + ir_bytecode_fail, +}; +import("whale_wave_ir::model")::{ir_align_up}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyOperand, + IrVerifyResult, + IrVerifyType, + ir_verify_equal, + ir_verify_graph_valid, + ir_verify_integer, + ir_verify_signature, + ir_verify_storable, + ir_verify_width, +}; + // Type and text validation is shared by emission and hostile-file admission. -struct IrBytecodeScratch { +pub struct IrBytecodeScratch { words: ptr; capacity: u64; used: u64; } -fun ir_bytecode_take(scratch: ptr, count: u64, +pub fun ir_bytecode_take(scratch: ptr, count: u64, result: ptr) -> ptr { if (scratch.used > scratch.capacity || count > scratch.capacity - scratch.used) { ir_bytecode_fail(result, 4, 3, 0, count); @@ -17,7 +39,7 @@ fun ir_bytecode_take(scratch: ptr, count: u64, return data; } -fun ir_bytecode_semantic(result: ptr, limits: ptr, +pub fun ir_bytecode_semantic(result: ptr, limits: ptr, semantic: ptr, valid: bool) -> bool { if (!ir_bytecode_charge(result, limits, semantic.work)) { return false; } if (semantic.status == 8) { @@ -29,7 +51,7 @@ fun ir_bytecode_semantic(result: ptr, limits: ptr) { +pub fun ir_bytecode_semantic_init(semantic: ptr) { semantic.status = 0; semantic.index = 0; semantic.expected = 0; @@ -38,7 +60,7 @@ fun ir_bytecode_semantic_init(semantic: ptr) { semantic.work = 0; } -fun ir_bytecode_same(program: ptr, a: u64, b: u64, +pub fun ir_bytecode_same(program: ptr, a: u64, b: u64, limits: ptr, result: ptr) -> bool { if (a >= program.type_count || b >= program.type_count) { return ir_bytecode_fail(result, 1, 10, result.table, result.index); @@ -50,7 +72,7 @@ fun ir_bytecode_same(program: ptr, a: u64, b: u64, return ir_bytecode_semantic(result, limits, &semantic, valid); } -fun ir_bytecode_storable(program: ptr, ty: u64, +pub fun ir_bytecode_storable(program: ptr, ty: u64, limits: ptr, result: ptr) -> bool { var semantic: IrVerifyResult; ir_bytecode_semantic_init(&semantic); @@ -59,7 +81,7 @@ fun ir_bytecode_storable(program: ptr, ty: u64, return ir_bytecode_semantic(result, limits, &semantic, valid); } -fun ir_bytecode_value_type(program: ptr, ty: u64) -> bool { +pub fun ir_bytecode_value_type(program: ptr, ty: u64) -> bool { var node: ptr = &program.types[ty]; if (node.kind >= 1 && node.kind <= 18) { return true; } return node.kind == 21 && node.count == 2 @@ -107,7 +129,7 @@ fun ir_bytecode_utf8(data: ptr, count: u64, return true; } -fun ir_bytecode_verify_types(program: ptr, scratch: ptr, +pub fun ir_bytecode_verify_types(program: ptr, scratch: ptr, limits: ptr, result: ptr) -> bool { // Reuse loop storage at O0; file-controlled iterations must not grow the stack. var semantic: IrVerifyResult; @@ -194,7 +216,7 @@ fun ir_bytecode_verify_types(program: ptr, scratch: ptr; limits: ptr; result: ptr; @@ -233,7 +255,7 @@ fun ir_bytecode_owned(context: ptr, amount: u64) -> bool { return true; } -fun ir_bytecode_metadata(context: ptr) -> bool { +pub fun ir_bytecode_metadata(context: ptr) -> bool { if (!ir_bytecode_owned(context, context.program.text_byte_count)) { return false; } var table: u64 = 9; while (table <= 16) { @@ -254,7 +276,7 @@ fun ir_bytecode_metadata(context: ptr) -> bool { return true; } -fun ir_bytecode_layouts(context: ptr) -> bool { +pub fun ir_bytecode_layouts(context: ptr) -> bool { // Reuse loop storage at O0; file-controlled iterations must not grow the stack. var program: ptr; var limits: ptr; diff --git a/ir/src/bytecode/workspace.wave b/ir/src/bytecode/workspace.wave new file mode 100644 index 0000000..97c8832 --- /dev/null +++ b/ir/src/bytecode/workspace.wave @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeCounts, + IrBytecodeLimits, + IrBytecodeResult, + ir_bytecode_fail, + ir_bytecode_native_stride, +}; + +pub fun ir_bytecode_sizes(counts: ptr, limits: ptr, + result: ptr) -> bool { + var values: ptr = counts as ptr; + var total: u64 = 0; + var records: u64 = 0; + var table: u64 = 1; + while (table <= 16) { + var count: u64 = values[table - 1]; + var stride: u64 = ir_bytecode_native_stride(table); + if (count > limits.max_decoded_bytes / stride + || count * stride > limits.max_decoded_bytes - total) { + return ir_bytecode_fail(result, 2, 2, table, count); + } + total += count * stride; + if (table != 11) { + if (records > limits.max_records || count > limits.max_records - records) { + return ir_bytecode_fail(result, 2, 3, table, count); + } + records += count; + } + table += 1; + } + // A linear bound for CFG, SSA, source indexes and initialized type scratch. + var words: u64 = 256; + table = 1; + while (table <= 16) { + var factor: u64 = 32; + if (table == 4) { factor = 96; } + if (table == 6) { factor = 48; } + if (table == 7) { factor = 32; } + if (table == 15) { factor = 0; } + if (table == 11) { factor = 0; } + var count: u64 = values[table - 1]; + if (factor != 0 && count > (18446744073709551615 - words) / factor) { + return ir_bytecode_fail(result, 2, 4, table, count); + } + words += count * factor; + table += 1; + } + if (words > limits.max_workspace_bytes / 8 + || total > limits.max_workspace_bytes - words * 8) { + return ir_bytecode_fail(result, 2, 4, 0, words); + } + result.decoded_bytes = total; + result.scratch_words = words; + // Probe/query excludes semantic metadata; full admission adds its retained + // and transient clone allowance before reporting a successful estimate. + result.estimated_workspace_bytes = total + words * 8; + return true; +} diff --git a/ir/bytecode_writer.wave b/ir/src/bytecode/writer.wave similarity index 91% rename from ir/bytecode_writer.wave rename to ir/src/bytecode/writer.wave index 2602e4c..12bdb70 100644 --- a/ir/bytecode_writer.wave +++ b/ir/src/bytecode/writer.wave @@ -1,4 +1,19 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::bytecode::model")::{ + IrBytecodeLimits, + IrBytecodeProgram, + IrBytecodeResult, + ir_bytecode_charge, + ir_bytecode_count, + ir_bytecode_data, + ir_bytecode_fail, + ir_bytecode_result_init, + ir_bytecode_stride, +}; +import("whale_wave_ir::bytecode::verify")::{whale_ir_bytecode_verify}; +import("whale_wave_ir::model")::{ir_span_valid}; +import("whale_wave_ir::interpreter::model")::{IrRuntimeGlobal}; + // Canonical little-endian emission has no allocation or host callbacks. All // validation, capacity and work checks precede the first output byte. fun ir_bytecode_put_word(output: ptr, offset: u64, word: u64) { @@ -120,7 +135,7 @@ fun ir_bytecode_publish(program: ptr, output: ptr, } } -export(c) fun whale_ir_bytecode_write(program: ptr, output: ptr, +pub export(c) fun whale_ir_bytecode_write(program: ptr, output: ptr, capacity: u64, required: ptr, scratch: ptr, scratch_capacity: u64, limits: ptr, result: ptr) -> i32 { if (result == null) { diff --git a/ir/constant_dependencies.wave b/ir/src/constants/dependencies.wave similarity index 96% rename from ir/constant_dependencies.wave rename to ir/src/constants/dependencies.wave index 5c5e95a..b4da346 100644 --- a/ir/constant_dependencies.wave +++ b/ir/src/constants/dependencies.wave @@ -1,4 +1,15 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::verifier::cfg")::{ir_cfg_charge}; +import("whale_wave_ir::constants::evaluate")::{IrConstNode}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; +import("whale_wave_ir::source")::{ir_source_mix}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyResult, + IrVerifyType, + ir_verify_equal, + ir_verify_graph_valid, +}; + // Stable indexed dependency scheduling. Imported global indices are borrowed, // so each function visits only its own constants and references. @@ -104,7 +115,7 @@ fun ir_const_schedule_slot( return capacity; } -export(c) fun whale_ir_const_schedule( +pub export(c) fun whale_ir_const_schedule( p: ptr, result: ptr ) -> i32 { @@ -360,7 +371,7 @@ export(c) fun whale_ir_const_schedule( return 0; } -export(c) fun whale_ir_const_value_equal( +pub export(c) fun whale_ir_const_value_equal( left_kind: u64, left_low: u64, left_high: u64, diff --git a/ir/constant.wave b/ir/src/constants/evaluate.wave similarity index 95% rename from ir/constant.wave rename to ir/src/constants/evaluate.wave index 30bc3a5..f5fee61 100644 --- a/ir/constant.wave +++ b/ir/src/constants/evaluate.wave @@ -1,7 +1,28 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::verifier::cfg")::{ir_cfg_charge}; +import("whale_wave_ir::numeric::float_arithmetic")::{ir_float_arithmetic}; +import("whale_wave_ir::numeric::float_model")::{ + IrFloatFormat, + ir_float_format, + ir_float_predicate, + ir_float_sign, +}; +import("whale_wave_ir::numeric::integer")::{IrIntegerResult, whale_ir_integer}; +import("whale_wave_ir::model")::{ir_span_valid}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyResult, + IrVerifyType, + ir_verify_equal, + ir_verify_float, + ir_verify_integer, + ir_verify_literal, + ir_verify_signed, + ir_verify_unsigned, +}; + // Typed constant validation and lazy evaluation; only reference values cross // the resumable data boundary. All arithmetic and error ordering stay in Wave. -struct IrConstNode { +pub struct IrConstNode { kind: u64; op: u64; ty: u64; @@ -90,7 +111,7 @@ fun ir_const_charge(p: ptr) -> bool { return ir_cfg_charge(&p.state.work, p.max_work); } -fun ir_const_value_valid(kind: u64, literal: u64, low: u64, high: u64) -> bool { +pub fun ir_const_value_valid(kind: u64, literal: u64, low: u64, high: u64) -> bool { if (!ir_verify_literal(kind, literal, low, high)) { return false; } @@ -264,7 +285,7 @@ fun ir_const_number( return 0; } -export(c) fun whale_ir_const_step(p: ptr, result: ptr) -> i32 { +pub export(c) fun whale_ir_const_step(p: ptr, result: ptr) -> i32 { if (result == null) { return 8; } @@ -535,7 +556,7 @@ export(c) fun whale_ir_const_step(p: ptr, result: ptr i32 { +pub export(c) fun whale_ir_const_literal(kind: u64, literal: u64, low: u64, high: u64) -> i32 { if (kind > 21 || literal > 6) { return 2; } diff --git a/ir/effects.wave b/ir/src/effects.wave similarity index 93% rename from ir/effects.wave rename to ir/src/effects.wave index e461778..0025fea 100644 --- a/ir/effects.wave +++ b/ir/src/effects.wave @@ -37,7 +37,7 @@ fun ir_effect_mask(op: u64, sub: u64, pointer: u64) -> u64 { return 0; } -export(c) fun whale_ir_effects( +pub export(c) fun whale_ir_effects( op: u64, sub: u64, pointer: u64, @@ -64,7 +64,7 @@ export(c) fun whale_ir_effects( return 0; } -export(c) fun whale_ir_effects_removable(mask: u64) -> i32 { +pub export(c) fun whale_ir_effects_removable(mask: u64) -> i32 { if (mask > 63) { return 2; } diff --git a/ir/entry.wave b/ir/src/entry.wave similarity index 89% rename from ir/entry.wave rename to ir/src/entry.wave index 2b65df3..46b649e 100644 --- a/ir/entry.wave +++ b/ir/src/entry.wave @@ -1,7 +1,17 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::layout")::{ir_layout_node}; +import("whale_wave_ir::model")::{ + IrLayoutResult, + IrStorage, + IrTypeLayout, + IrTypeNode, + ir_span_valid, + ir_storage_valid, +}; + // Status: 1 invalid graph/type, 2 depth, 3 overflow, 4 capacity, // 5 invalid transport/target, 6 work budget. Only result is written on error. -export(c) fun whale_ir_layout(storage: ptr, nodes: ptr, node_count: u64, +pub export(c) fun whale_ir_layout(storage: ptr, nodes: ptr, node_count: u64, edges: ptr, edge_count: u64, root: u64, max_depth: u64, max_work: u64, scratch: ptr, scratch_count: u64, scratch_offsets: ptr, scratch_offset_count: u64, output: ptr, output_count: u64, @@ -63,6 +73,6 @@ export(c) fun whale_ir_layout(storage: ptr, nodes: ptr, n } // Distinct compiled identity used by product composition checks. -export(c) fun whale_ir_module_identity() -> u64 { +pub export(c) fun whale_ir_module_identity() -> u64 { return 6289348675458650625; } diff --git a/ir/runtime_driver.wave b/ir/src/interpreter/driver.wave similarity index 89% rename from ir/runtime_driver.wave rename to ir/src/interpreter/driver.wave index 64d91ab..2f3458e 100644 --- a/ir/runtime_driver.wave +++ b/ir/src/interpreter/driver.wave @@ -1,4 +1,14 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; +import("whale_wave_ir::interpreter::execute")::{ + ir_runtime_admit, + ir_runtime_execute_one, + ir_runtime_globals, + ir_runtime_resume, +}; +import("whale_wave_ir::interpreter::model")::{IrRuntimeDriver}; +import("whale_wave_ir::interpreter::prepare")::{ir_runtime_backend, ir_runtime_initialize}; + // A resume acknowledges one effect or buffer request, never re-executes it. fun ir_runtime_transport_valid(p: ptr) -> bool { return ir_span_valid(p.types as ptr, p.type_count, 40) @@ -33,7 +43,7 @@ fun ir_runtime_transport_valid(p: ptr) -> bool { && p.callable_count <= p.function_count && p.work <= p.max_work; } -export(c) fun whale_ir_runtime_step(p: ptr) -> i32 { +pub export(c) fun whale_ir_runtime_step(p: ptr) -> i32 { if (p == null || p.result == null) { return 4; } diff --git a/ir/runtime_execute.wave b/ir/src/interpreter/execute.wave similarity index 94% rename from ir/runtime_execute.wave rename to ir/src/interpreter/execute.wave index 6a6bdee..f591a76 100644 --- a/ir/runtime_execute.wave +++ b/ir/src/interpreter/execute.wave @@ -1,4 +1,38 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::numeric::float_convert")::{whale_ir_float}; +import("whale_wave_ir::numeric::float_model")::{IrFloatRequest, IrFloatResult}; +import("whale_wave_ir::numeric::integer")::{ + IrIntegerResult, + ir_integer_signed, + ir_integer_width, + whale_ir_integer, + whale_ir_integer_bits, +}; +import("whale_wave_ir::interpreter::memory")::{IrMemGep}; +import("whale_wave_ir::interpreter::model")::{ + IrRuntimeBlock, + IrRuntimeDriver, + IrRuntimeEvent, + IrRuntimeFrame, + IrRuntimeFunction, + IrRuntimeGlobal, + IrRuntimeInstruction, + IrRuntimeSlot, + IrRuntimeValue, +}; +import("whale_wave_ir::interpreter::prepare")::{ + ir_runtime_backend, + ir_runtime_charge, + ir_runtime_clear_value, + ir_runtime_equal, + ir_runtime_error, + ir_runtime_find, + ir_runtime_literal, + ir_runtime_make_scalar, +}; +import("whale_wave_ir::verifier::module")::{ir_verify_float, ir_verify_signed, ir_verify_width}; +import("whale_wave_ir::numeric::wide")::{IrWide, ir_wide_from, ir_wide_trim}; + // Native execution uses generation-tagged SSA slots and explicit one-shot effects. fun ir_runtime_step_charge(p: ptr, site: u64) -> bool { p.pending_site = site; @@ -73,7 +107,7 @@ fun ir_runtime_buffers(p: ptr, frames: u64, slots: u64, return false; } -fun ir_runtime_admit(p: ptr, target: u64, entry: bool) -> bool { +pub fun ir_runtime_admit(p: ptr, target: u64, entry: bool) -> bool { if (target >= p.function_count || p.prepared[target] == 0) { return ir_runtime_backend(p); } @@ -246,7 +280,7 @@ fun ir_runtime_numeric(p: ptr, inst: ptr, return true; } -fun ir_runtime_resume(p: ptr) -> bool { +pub fun ir_runtime_resume(p: ptr) -> bool { var pending: u64 = p.pending; if (pending == 0) { if (p.resume != 0) { @@ -337,7 +371,7 @@ fun ir_runtime_resume(p: ptr) -> bool { return ir_runtime_backend(p); } -fun ir_runtime_globals(p: ptr) -> bool { +pub fun ir_runtime_globals(p: ptr) -> bool { if (p.cursor >= p.global_count) { p.result.global = 18446744073709551615; p.pending_site = 18446744073709551615; @@ -424,7 +458,7 @@ fun ir_runtime_phis(p: ptr, frame: ptr) -> bool return true; } -fun ir_runtime_execute_one(p: ptr) -> bool { +pub fun ir_runtime_execute_one(p: ptr) -> bool { if (p.frame_count == 0) { return ir_runtime_backend(p); } diff --git a/ir/memory.wave b/ir/src/interpreter/memory.wave similarity index 99% rename from ir/memory.wave rename to ir/src/interpreter/memory.wave index 18a9c5c..9740f8a 100644 --- a/ir/memory.wave +++ b/ir/src/interpreter/memory.wave @@ -1,6 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; +import("whale_wave_ir::source")::{ir_source_mix}; + // Tracked identities are integers; native pointers address only caller buffers. -struct IrMemPointer { +pub struct IrMemPointer { address: u64; present: u64; arena: u64; @@ -67,7 +70,7 @@ struct IrMemPart { authority: IrMemAuthority; } -struct IrMemGep { +pub struct IrMemGep { kind: u64; amount: u64; low: u64; @@ -398,7 +401,7 @@ fun ir_mem_metadata_build(a: ptr, start: u64, end: u64, // Operations:0 allocate,1 seal-global,2 retire-stack,3 load,4 store,5 uninit, // 6 memcpy,7 memset,8 gep,9 equal,10 difference,11 retire-frame. -export(c) fun whale_ir_memory(state: ptr, limits: ptr, +pub export(c) fun whale_ir_memory(state: ptr, limits: ptr, allocations: ptr, allocation_capacity: u64, q: ptr, new_fragments: ptr, new_capacity: u64, output_parts: ptr, output_part_capacity: u64, r: ptr) -> i32 { diff --git a/ir/runtime_model.wave b/ir/src/interpreter/model.wave similarity index 89% rename from ir/runtime_model.wave rename to ir/src/interpreter/model.wave index 580bf69..6f036ee 100644 --- a/ir/runtime_model.wave +++ b/ir/src/interpreter/model.wave @@ -1,6 +1,10 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::interpreter::memory")::{IrMemGep, IrMemPointer}; +import("whale_wave_ir::model")::{IrStorage, IrTypeLayout, IrTypeNode}; +import("whale_wave_ir::verifier::module")::{IrVerifyType}; + // Caller-owned IR records and execution storage; no native address is a value ID. -struct IrRuntimeValue { +pub struct IrRuntimeValue { kind: u64; ty: u64; literal: u64; @@ -14,12 +18,12 @@ struct IrRuntimeValue { origin: u64; } -struct IrRuntimeSlot { +pub struct IrRuntimeSlot { generation: u64; value: IrRuntimeValue; } -struct IrRuntimeFrame { +pub struct IrRuntimeFrame { function: u64; block: u64; predecessor: u64; @@ -32,7 +36,7 @@ struct IrRuntimeFrame { call_site: u64; } -struct IrRuntimeFunction { +pub struct IrRuntimeFunction { id: u64; signature: u64; entry: u64; @@ -46,14 +50,14 @@ struct IrRuntimeFunction { linkage: u64; } -struct IrRuntimeBlock { +pub struct IrRuntimeBlock { id: u64; function: u64; first: u64; count: u64; } -struct IrRuntimeInstruction { +pub struct IrRuntimeInstruction { op: u64; sub: u64; ty: u64; @@ -77,7 +81,7 @@ struct IrRuntimeInstruction { plan_count: u64; } -struct IrRuntimeGlobal { +pub struct IrRuntimeGlobal { id: u64; ty: u64; size: u64; @@ -88,7 +92,7 @@ struct IrRuntimeGlobal { value: IrRuntimeValue; } -struct IrRuntimeEvent { +pub struct IrRuntimeEvent { kind: u64; ty: u64; size: u64; @@ -117,7 +121,7 @@ struct IrRuntimeResult { event: IrRuntimeEvent; } -struct IrRuntimeDriver { +pub struct IrRuntimeDriver { types: ptr; type_count: u64; type_edges: ptr; diff --git a/ir/runtime_prepare.wave b/ir/src/interpreter/prepare.wave similarity index 93% rename from ir/runtime_prepare.wave rename to ir/src/interpreter/prepare.wave index 616e763..25d9db1 100644 --- a/ir/runtime_prepare.wave +++ b/ir/src/interpreter/prepare.wave @@ -1,6 +1,31 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::constants::evaluate")::{ir_const_value_valid}; +import("whale_wave_ir::layout")::{ir_layout_node}; +import("whale_wave_ir::interpreter::memory")::{IrMemGep}; +import("whale_wave_ir::model")::{IrTypeNode, ir_power_two, ir_storage_valid}; +import("whale_wave_ir::interpreter::model")::{ + IrRuntimeBlock, + IrRuntimeDriver, + IrRuntimeFunction, + IrRuntimeGlobal, + IrRuntimeInstruction, + IrRuntimeValue, +}; +import("whale_wave_ir::source")::{ir_source_mix}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyResult, + IrVerifyType, + ir_verify_cast, + ir_verify_equal, + ir_verify_float, + ir_verify_integer, + ir_verify_signed, + ir_verify_unsigned, + ir_verify_width, +}; + // Preparation and admission are native decisions over caller-owned, bounded records. -fun ir_runtime_error(p: ptr, error: u64, site: u64, +pub fun ir_runtime_error(p: ptr, error: u64, site: u64, detail: u64, extra: u64) -> bool { p.result.status = 3; p.result.error = error; @@ -11,14 +36,14 @@ fun ir_runtime_error(p: ptr, error: u64, site: u64, return false; } -fun ir_runtime_backend(p: ptr) -> bool { +pub fun ir_runtime_backend(p: ptr) -> bool { p.result.status = 4; p.result.site = p.pending_site; p.result.steps = p.steps; return false; } -fun ir_runtime_charge(p: ptr) -> bool { +pub fun ir_runtime_charge(p: ptr) -> bool { if (p.work >= p.max_work) { return ir_runtime_error(p, 18, p.pending_site, p.max_work, 0); } @@ -26,7 +51,7 @@ fun ir_runtime_charge(p: ptr) -> bool { return true; } -fun ir_runtime_equal(p: ptr, a: u64, b: u64) -> bool { +pub fun ir_runtime_equal(p: ptr, a: u64, b: u64) -> bool { if (a >= p.type_count || b >= p.type_count) { ir_runtime_backend(p); return false; @@ -80,7 +105,7 @@ fun ir_runtime_callable(p: ptr, signature: u64) -> bool { return true; } -fun ir_runtime_find(p: ptr, id: u64) -> u64 { +pub fun ir_runtime_find(p: ptr, id: u64) -> u64 { var mask: u64 = p.function_table_capacity - 1; var index: u64 = ir_source_mix(id) & mask; var count: u64 = 0; @@ -370,7 +395,7 @@ fun ir_runtime_prepare_function(p: ptr, function: u64) -> bool return true; } -fun ir_runtime_clear_value(value: ptr) { +pub fun ir_runtime_clear_value(value: ptr) { value.kind = 0; value.ty = 18446744073709551615; value.literal = 0; @@ -393,7 +418,7 @@ fun ir_runtime_clear_value(value: ptr) { value.origin = 1; } -fun ir_runtime_literal(kind: u64) -> u64 { +pub fun ir_runtime_literal(kind: u64) -> u64 { if (kind == 1) { return 3; } @@ -406,7 +431,7 @@ fun ir_runtime_literal(kind: u64) -> u64 { return kind - 10; } -fun ir_runtime_make_scalar(p: ptr, ty: u64, low: u64, high: u64, +pub fun ir_runtime_make_scalar(p: ptr, ty: u64, low: u64, high: u64, value: ptr) { ir_runtime_clear_value(value); value.kind = 1; @@ -416,7 +441,7 @@ fun ir_runtime_make_scalar(p: ptr, ty: u64, low: u64, high: u64 value.high = high; } -fun ir_runtime_initialize(p: ptr) -> bool { +pub fun ir_runtime_initialize(p: ptr) -> bool { p.pending_site = 18446744073709551615; p.pending_head = 18446744073709551615; p.result.global = 18446744073709551615; diff --git a/ir/layout.wave b/ir/src/layout.wave similarity index 96% rename from ir/layout.wave rename to ir/src/layout.wave index 9fb24fb..6bc6d3a 100644 --- a/ir/layout.wave +++ b/ir/src/layout.wave @@ -1,4 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{IrStorage, IrTypeLayout, IrTypeNode, ir_align_up}; + // Walk the root in source order, preserving the reference layout's first-error // precedence. Every node and edge visit consumes work, including repeated DAG // references. The aggregate depth bound also bounds native call-stack use. @@ -19,7 +21,7 @@ fun ir_layout_scalar(kind: u64, storage: ptr, layout: ptr, node_count: u64, +pub fun ir_layout_node(index: u64, nodes: ptr, node_count: u64, edges: ptr, edge_count: u64, storage: ptr, remaining_depth: u64, scratch: ptr, offsets: ptr, work: ptr) -> i32 { if (work[0] == 0) { return 6; } diff --git a/ir/src/lib.wave b/ir/src/lib.wave new file mode 100644 index 0000000..7f52a90 --- /dev/null +++ b/ir/src/lib.wave @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MPL-2.0 +// Explicit role modules; Vex compiles this package without source concatenation. +import("./builder/module.wave" as builder_module); +import("./builder/body.wave" as builder_body); +import("./builder/namespace.wave" as builder_namespace); +import("./bytecode/inventory.wave" as bytecode_inventory); +import("./bytecode/loader.wave" as bytecode_loader); +import("./bytecode/model.wave" as bytecode_model); +import("./bytecode/runtime.wave" as bytecode_runtime); +import("./bytecode/verify.wave" as bytecode_verify); +import("./bytecode/verify_flow.wave" as bytecode_verify_flow); +import("./bytecode/verify_instructions.wave" as bytecode_verify_instructions); +import("./bytecode/verify_types.wave" as bytecode_verify_types); +import("./bytecode/workspace.wave" as bytecode_workspace); +import("./bytecode/writer.wave" as bytecode_writer); +import("./verifier/cfg.wave" as verifier_cfg); +import("./constants/evaluate.wave" as constants_evaluate); +import("./constants/dependencies.wave" as constants_dependencies); +import("./effects.wave" as effects); +import("./entry.wave" as entry); +import("./parser/expressions.wave" as parser_expressions); +import("./numeric/float_arithmetic.wave" as numeric_float_arithmetic); +import("./numeric/float_convert.wave" as numeric_float_convert); +import("./numeric/float_model.wave" as numeric_float_model); +import("./passes/integer.wave" as passes_integer); +import("./parser/header.wave" as parser_header); +import("./parser/instructions.wave" as parser_instructions); +import("./numeric/integer.wave" as numeric_integer); +import("./layout.wave" as layout); +import("./parser/lexer.wave" as parser_lexer); +import("./parser/literal.wave" as parser_literal); +import("./lowering/driver.wave" as lowering_driver); +import("./lowering/expression.wave" as lowering_expression); +import("./lowering/hir.wave" as lowering_hir); +import("./lowering/limits.wave" as lowering_limits); +import("./lowering/model.wave" as lowering_model); +import("./lowering/output.wave" as lowering_output); +import("./lowering/signature.wave" as lowering_signature); +import("./lowering/statement.wave" as lowering_statement); +import("./lowering/storage.wave" as lowering_storage); +import("./lowering/values.wave" as lowering_values); +import("./interpreter/memory.wave" as interpreter_memory); +import("./model.wave" as model); +import("./parser/module.wave" as parser_module); +import("./passes/driver.wave" as passes_driver); +import("./printer.wave" as printer); +import("./interpreter/driver.wave" as interpreter_driver); +import("./interpreter/execute.wave" as interpreter_execute); +import("./interpreter/model.wave" as interpreter_model); +import("./interpreter/prepare.wave" as interpreter_prepare); +import("./verifier/shape.wave" as verifier_shape); +import("./source.wave" as source); +import("./parser/types.wave" as parser_types); +import("./verifier/index.wave" as verifier_index); +import("./verifier/ssa.wave" as verifier_ssa); +import("./verifier/module.wave" as verifier_module); +import("./numeric/wide.wave" as numeric_wide); diff --git a/ir/lower_driver.wave b/ir/src/lowering/driver.wave similarity index 84% rename from ir/lower_driver.wave rename to ir/src/lowering/driver.wave index df9ccf3..1a85b80 100644 --- a/ir/lower_driver.wave +++ b/ir/src/lowering/driver.wave @@ -1,59 +1,48 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::lowering::expression")::{ir_lower_mismatch, ir_lower_preserve_constant}; +import("whale_wave_ir::lowering::model")::{ + IrLowerNode, + IrLowerString, + IrLowerValue, + ir_lower_charge, + ir_lower_edges, + ir_lower_fail, + ir_lower_initialize, + ir_lower_layout, + ir_lower_name, + ir_lower_node, + ir_lower_type, + ir_lower_type_intern, +}; +import("whale_wave_ir::lowering::output")::{ + IrLowerDeclaration, + IrLowerDriver, + IrLowerFunction, + ir_lower_bind, + ir_lower_block, + ir_lower_complete_source, + ir_lower_emit, + ir_lower_evaluate_request, + ir_lower_expand, + ir_lower_restore, + ir_lower_term, + ir_lower_value, +}; +import("whale_wave_ir::lowering::signature")::{ + ir_lower_scalar_signature, + ir_lower_signature_validate, +}; +import("whale_wave_ir::lowering::statement")::{ir_lower_statements}; +import("whale_wave_ir::lowering::storage")::{ir_lower_alloca}; +import("whale_wave_ir::model")::{ir_span_valid}; + // The complete AST lowering transaction has no host callbacks. The first pass // counts flat output; the second publishes records into exactly sized buffers. -fun ir_lower_signature_type(p: ptr, ty: u64, depth: u64, node: u64) -> bool { - if (!ir_lower_charge(p.core, 1, node)) { return false; } - if (depth > p.core.max_depth) { return ir_lower_fail(p.core, 2, node, 0, 0, 0); } - if (ty >= p.core.type_count) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } - var t: ptr = &p.core.types[ty]; - if (t.kind == 0) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } - if (t.kind == 18) { return ir_lower_signature_validate(p, ty, depth + 1, node); } - if (t.kind == 17) { - if (t.child == 0) { return true; } - return ir_lower_signature_type(p, t.child, depth + 1, node); - } - if (t.kind == 19) { return ir_lower_signature_type(p, t.child, depth + 1, node); } - var at: u64 = 0; - if (t.kind == 20 || t.kind == 21) { - while (at < t.count) { - if (!ir_lower_signature_type(p, p.core.type_edges[t.first + at], depth + 1, node)) { return false; } - at += 1; - } - } - return true; -} -fun ir_lower_signature_validate(p: ptr, ty: u64, depth: u64, node: u64) -> bool { - if (depth > p.core.max_depth) { return ir_lower_fail(p.core, 2, node, 0, 0, 0); } - if (ty >= p.core.type_count || p.core.types[ty].kind != 18) { - return ir_lower_fail(p.core, 21, node, 0, 0, 1); - } - var t: ptr = &p.core.types[ty]; - if (t.child != 0) { - if (t.auxiliary == 1 && ir_lower_aggregate(p.core, t.child)) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } - if (!ir_lower_signature_type(p, t.child, depth + 1, node)) { return false; } - } - var at: u64 = 0; - while (at < t.count) { - var param: u64 = p.core.type_edges[t.first + at]; - if (t.auxiliary == 1 && ir_lower_aggregate(p.core, param)) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } - if (!ir_lower_signature_type(p, param, depth + 1, node)) { return false; } - at += 1; - } - return true; -} -fun ir_lower_scalar_signature(p: ptr, ty: u64, node: u64) -> bool { - var signature: ptr = &p.core.types[ty]; - if (ir_lower_aggregate(p.core, signature.child)) { return ir_lower_fail(p.core, 18, node, 0, 0, 9); } - var at: u64 = 0; - while (at < signature.count) { - var kind: u64 = p.core.types[p.core.type_edges[signature.first + at]].kind; - if (kind == 20 || kind == 21) { return ir_lower_fail(p.core, 18, node, 0, 0, 9); } - at += 1; - } - return true; -} + + + fun ir_lower_function_signature(p: ptr, node: u64, output: ptr) -> bool { var n: ptr = &p.core.nodes[node]; @@ -318,7 +307,7 @@ fun ir_lower_driver_initialize(p: ptr) -> bool { return true; } -export(c) fun whale_ir_lower_o0(p: ptr, root: u64) -> i32 { +pub export(c) fun whale_ir_lower_o0(p: ptr, root: u64) -> i32 { if (p == null || p.core == null || p.core.result == null) { return 3; } var success: bool = ir_lower_driver_initialize(p) && ir_lower_program(p, root); p.core.result.work = p.core.work; diff --git a/ir/lower_expression.wave b/ir/src/lowering/expression.wave similarity index 64% rename from ir/lower_expression.wave rename to ir/src/lowering/expression.wave index 777daf5..adb06e2 100644 --- a/ir/lower_expression.wave +++ b/ir/src/lowering/expression.wave @@ -1,8 +1,53 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::literal")::{IrLiteralResult, whale_ir_parse_literal}; +import("whale_wave_ir::lowering::model")::{ + IrLowerBinding, + IrLowerNode, + IrLowerType, + IrLowerValue, + ir_lower_charge, + ir_lower_edges, + ir_lower_fail, + ir_lower_float, + ir_lower_integer, + ir_lower_layout, + ir_lower_name, + ir_lower_node, + ir_lower_pointer, + ir_lower_scalar, + ir_lower_signed, + ir_lower_type, + ir_lower_width, +}; +import("whale_wave_ir::lowering::output")::{ + IrLowerConstant, + IrLowerDriver, + ir_lower_binding, + ir_lower_block, + ir_lower_complete_source, + ir_lower_emit, + ir_lower_expand, + ir_lower_local_binding, + ir_lower_source, + ir_lower_source_charge, + ir_lower_term, + ir_lower_type_size, + ir_lower_value, +}; +import("whale_wave_ir::lowering::signature")::{ir_lower_signature_validate}; +import("whale_wave_ir::lowering::storage")::{ + ir_lower_alloca, + ir_lower_field_map, + ir_lower_field_pointer, + ir_lower_read, + ir_lower_write, +}; +import("whale_wave_ir::lowering::values")::{ir_lower_cast_value, ir_lower_immediate}; + // Scalar and preserved-constant expression lowering. Typed constexpr payloads // stay independent from runtime instructions and are evaluated by the core // constant engine after a successful lowering transaction. -fun ir_lower_mismatch(p: ptr, node: u64, expected: u64, actual: u64) -> bool { +pub fun ir_lower_mismatch(p: ptr, node: u64, expected: u64, actual: u64) -> bool { ir_lower_fail(p.core, 6, node, expected, actual, 0); if (node < p.core.node_count && p.core.nodes[node].tag == 0) { p.core.result.annotation = p.core.nodes[node].a; @@ -88,7 +133,7 @@ fun ir_lower_compare(p: ptr, op: u64, ty: u64, node: u64, output: return true; } -fun ir_lower_preserve_constant(p: ptr, node: u64, depth: u64, +pub fun ir_lower_preserve_constant(p: ptr, node: u64, depth: u64, output: ptr) -> bool { if (!ir_lower_node(p.core, node, depth) || !ir_lower_source_charge(p, 1, node)) { return false; } @@ -151,25 +196,9 @@ fun ir_lower_preserve_constant(p: ptr, node: u64, depth: u64, output.value = node; output.ty = ty; return true; } -fun ir_lower_immediate(p: ptr, ty: u64, low: u64, high: u64, - node: u64, output: ptr) -> bool { - var id: u64 = 0; - if (!ir_lower_value(p, ty, node, &id)) { return false; } - var category: u64 = 3; - if (ty == 1) { category = 1; } - else if (ir_lower_signed(ty)) { category = 2; } - else if (ir_lower_float(ty)) { category = 4; } - if (!ir_lower_emit(p, 4, id, ty, 2, low, high, category, 0, null, 0, false, node)) { return false; } - output[0] = id; return true; -} -fun ir_lower_cast_value(p: ptr, op: u64, src_ty: u64, dst_ty: u64, - value: u64, node: u64, output: ptr) -> bool { - var id: u64 = 0; - if (!ir_lower_value(p, dst_ty, node, &id) - || !ir_lower_emit(p, 14, id, dst_ty, op, src_ty, value, 0, 0, null, 0, false, node)) { return false; } - output[0] = id; return true; -} + + fun ir_lower_call(p: ptr, node: u64, depth: u64, output: ptr) -> bool { @@ -219,7 +248,7 @@ fun ir_lower_call(p: ptr, node: u64, depth: u64, p.core.temporary_count = saved; output.value = value; output.ty = sig.child; return true; } -fun ir_lower_expression(p: ptr, node: u64, depth: u64, +pub fun ir_lower_expression(p: ptr, node: u64, depth: u64, allow_void: bool, output: ptr) -> bool { if (!ir_lower_node(p.core, node, depth)) { return false; } var n: ptr = &p.core.nodes[node]; @@ -354,3 +383,146 @@ fun ir_lower_expression(p: ptr, node: u64, depth: u64, } else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } output.value = value; output.ty = ty; return true; } + +pub fun ir_lower_place(p: ptr, node: u64, depth: u64, + output: ptr) -> bool { + if (!ir_lower_node(p.core, node, depth)) { return false; } + var n: ptr = &p.core.nodes[node]; + if (n.tag == 0) { + var saved: u64 = p.core.annotation; p.core.annotation = n.a; + var success: bool = ir_lower_place(p, n.b, depth + 1, output) + && ir_lower_complete_source(p, n.a, node); + p.core.annotation = saved; return success; + } + if (n.tag == 15) { + var binding: IrLowerBinding; + if (!ir_lower_name(p.core, n.a, node) || !ir_lower_local_binding(p, n.a, node, &binding)) { return false; } + if (binding.kind != 0) { return ir_lower_fail(p.core, 12, node, 0, 0, n.a); } + output.value = binding.value; output.ty = binding.ty; return true; + } + var base: IrLowerValue; + if (n.tag == 6) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } + if (p.core.types[base.ty].kind != 17 || p.core.types[base.ty].child == 0) { + return ir_lower_fail(p.core, 7, node, 0, 0, 0); + } + output.value = base.value; output.ty = p.core.types[base.ty].child; return true; + } + if (n.tag == 3) { + var expected: u64 = 0; + if (!ir_lower_type(p.core, n.b, 0, &expected)) { return false; } + if (p.core.nodes[n.b].tag != 107 || !ir_lower_name(p.core, n.c, node)) { + return ir_lower_fail(p.core, 7, node, 0, 0, 0); + } + var layout: ptr = &p.core.nodes[n.b]; + var ordinal: u64 = 0; + while (ordinal < layout.b) { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (p.core.nodes[p.core.edges[layout.a + ordinal]].a == n.c) { break; } + ordinal += 1; + } + if (ordinal == layout.b) { return ir_lower_fail(p.core, 18, node, 0, 0, 3); } + var ty: u64 = p.core.type_edges[p.core.types[expected].first + ordinal]; + if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } + if (base.ty != expected) { return ir_lower_fail(p.core, 6, node, expected, base.ty, 0); } + var pointer: u64 = 0; + if (!ir_lower_field_pointer(p, base.value, ordinal, ty, node, &pointer)) { return false; } + output.value = pointer; output.ty = ty; return true; + } + if (n.tag == 4) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } + if (p.core.types[base.ty].kind != 19) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + var element: u64 = p.core.types[base.ty].child; + var length: u64 = p.core.types[base.ty].auxiliary; + var index: IrLowerValue; + if (!ir_lower_expression(p, n.b, depth + 1, false, &index)) { return false; } + if (!ir_lower_integer(index.ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + var zero: u64 = 0; + var bad: u64 = 0; + if (ir_lower_signed(index.ty)) { + if (!ir_lower_immediate(p, index.ty, 0, 0, node, &zero) + || !ir_lower_value(p, 1, node, &bad) + || !ir_lower_emit(p, 11, bad, index.ty, 6, index.value, zero, 0, 0, null, 0, false, node) + || !ir_lower_emit(p, 30, 18446744073709551615, 1, + bad, 1, 0, 0, 0, null, 0, false, node)) { return false; } + } + var converted: u64 = 0; + var limit: u64 = 0; + if (!ir_lower_cast_value(p, 0, index.ty, 13, index.value, node, &converted) + || !ir_lower_immediate(p, 13, length, 0, node, &limit) + || !ir_lower_value(p, 1, node, &bad) + || !ir_lower_emit(p, 11, bad, 13, 5, converted, limit, 0, 0, null, 0, false, node) + || !ir_lower_emit(p, 30, 18446744073709551615, 1, + bad, 1, 0, 0, 0, null, 0, false, node) + || !ir_lower_immediate(p, 12, 0, 0, node, &zero)) { return false; } + var pointer: u64 = 0; + var destination: u64 = 0; + var indices: array; + if (!ir_lower_pointer(p.core, element, node, &pointer) + || !ir_lower_value(p, pointer, node, &destination)) { return false; } + indices[0] = zero; indices[1] = converted; + if (!ir_lower_emit(p, 24, destination, pointer, base.value, 0, 0, 0, 0, + &indices[0], 2, false, node)) { return false; } + output.value = destination; output.ty = element; return true; + } + return ir_lower_fail(p.core, 7, node, 0, 0, 0); +} + +fun ir_lower_aggregate_literal(p: ptr, node: u64, depth: u64, + output: ptr) -> bool { + var n: ptr = &p.core.nodes[node]; + var ty: u64 = 0; + if (!ir_lower_type(p.core, n.a, 0, &ty) || !ir_lower_layout(p.core, ty, node)) { return false; } + var align: u64 = p.core.layouts[ty].align; + var pointer: u64 = 0; + if (!ir_lower_alloca(p, ty, align, node, &pointer) + || !ir_lower_emit(p, 22, 18446744073709551615, ty, + pointer, align, 0, 0, 0, null, 0, false, node) + || !ir_lower_edges(p.core, n.b, n.c, node)) { return false; } + var at: u64 = 0; + var actual: IrLowerValue; + var destination: u64 = 0; + if (n.tag == 1 && p.core.types[ty].kind == 20 && p.core.nodes[n.a].tag == 107) { + if (n.c != p.core.types[ty].count) { return ir_lower_fail(p.core, 18, node, 0, 0, 4); } + var saved: u64 = p.field_binding_count; + if (!ir_lower_field_map(p, n.a, node)) { return false; } + while (at < n.c) { + var init: u64 = p.core.edges[n.b + at]; + if (!ir_lower_node(p.core, init, depth + 1) || p.core.nodes[init].tag != 24) { + return ir_lower_fail(p.core, 3, init, 0, 0, 0); + } + var name: u64 = p.core.nodes[init].a; + if (!ir_lower_name(p.core, name, init)) { return false; } + var binding: u64 = p.field_slots[name]; + if (binding == 18446744073709551615 || binding < saved) { + return ir_lower_fail(p.core, 18, init, 0, 0, 6); + } + if (p.field_bindings[binding].used != 0) { return ir_lower_fail(p.core, 18, init, 0, 0, 5); } + p.field_bindings[binding].used = 1; + var ordinal: u64 = p.field_bindings[binding].ordinal; + var expected: u64 = p.core.type_edges[p.core.types[ty].first + ordinal]; + if (!ir_lower_expression(p, p.core.nodes[init].b, depth + 1, false, &actual)) { return false; } + if (actual.ty != expected) { return ir_lower_fail(p.core, 6, init, expected, actual.ty, 0); } + if (!ir_lower_field_pointer(p, pointer, ordinal, expected, node, &destination) + || !ir_lower_write(p, destination, actual.value, expected, node)) { return false; } + at += 1; + } + while (p.field_binding_count > saved) { + p.field_binding_count -= 1; + var last: u64 = p.field_binding_count; + p.field_slots[p.field_bindings[last].name] = p.field_bindings[last].previous; + } + } else if (n.tag == 2 && p.core.types[ty].kind == 19) { + var element: u64 = p.core.types[ty].child; + if (!ir_lower_scalar(p.core, element)) { return ir_lower_fail(p.core, 18, node, 0, 0, 7); } + if (n.c != p.core.types[ty].auxiliary) { return ir_lower_fail(p.core, 18, node, 0, 0, 8); } + while (at < n.c) { + if (!ir_lower_expression(p, p.core.edges[n.b + at], depth + 1, false, &actual)) { return false; } + if (actual.ty != element) { return ir_lower_fail(p.core, 6, node, element, actual.ty, 0); } + if (!ir_lower_field_pointer(p, pointer, at, element, node, &destination) + || !ir_lower_write(p, destination, actual.value, element, node)) { return false; } + at += 1; + } + } else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + output.value = pointer; output.ty = ty; return true; +} diff --git a/ir/lower_hir.wave b/ir/src/lowering/hir.wave similarity index 98% rename from ir/lower_hir.wave rename to ir/src/lowering/hir.wave index e3aaa61..ba4dcdc 100644 --- a/ir/lower_hir.wave +++ b/ir/src/lowering/hir.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::literal")::{IrLiteralResult, whale_ir_parse_literal}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; + // Pinned Wave TypedProgram scalar adapter. Resolved numeric facts and stable // expression identities cross this boundary explicitly; syntax never infers a // type. All checks finish before the caller publishes a frontend Program. @@ -203,7 +206,7 @@ fun ir_hir_statements(p: ptr, first: u64, count: u64, depth: u64) return true; } -export(c) fun whale_ir_adapt_wave_hir(nodes: ptr, node_count: u64, +pub export(c) fun whale_ir_adapt_wave_hir(nodes: ptr, node_count: u64, edges: ptr, edge_count: u64, functions: u64, function_count: u64, output: ptr, bindings: ptr, identities: ptr, identity_capacity: u64, diff --git a/ir/lower_limits.wave b/ir/src/lowering/limits.wave similarity index 95% rename from ir/lower_limits.wave rename to ir/src/lowering/limits.wave index 3edb960..eb4c8ad 100644 --- a/ir/lower_limits.wave +++ b/ir/src/lowering/limits.wave @@ -1,4 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::verifier::cfg")::{ir_cfg_charge}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; +import("whale_wave_ir::source")::{ir_source_mix}; + // Streaming AST admission, feature gates, numeric syntax and source identities. struct IrAstInspectState { nodes: u64; strings: u64; features: u64; numbers: u64; sources: u64; work: u64; } @@ -28,7 +32,7 @@ fun ir_ast_inspect_probe(slots: ptr, capacity: u64, id: u64, return capacity; } -export(c) fun whale_ir_ast_inspect_rehash(state: ptr, +pub export(c) fun whale_ir_ast_inspect_rehash(state: ptr, old: ptr, old_capacity: u64, slots: ptr, capacity: u64, max_work: u64, result: ptr) -> i32 { @@ -58,7 +62,7 @@ export(c) fun whale_ir_ast_inspect_rehash(state: ptr, result.status = 0; return 0; } -export(c) fun whale_ir_ast_inspect_step(state: ptr, +pub export(c) fun whale_ir_ast_inspect_step(state: ptr, event: ptr, max_depth: u64, max_nodes: u64, max_strings: u64, max_source_work: u64, slots: ptr, capacity: u64, result: ptr) -> i32 { diff --git a/ir/lower_model.wave b/ir/src/lowering/model.wave similarity index 87% rename from ir/lower_model.wave rename to ir/src/lowering/model.wave index 5522a98..e776430 100644 --- a/ir/lower_model.wave +++ b/ir/src/lowering/model.wave @@ -1,19 +1,29 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::layout")::{ir_layout_node}; +import("whale_wave_ir::model")::{ + IrStorage, + IrTypeLayout, + IrTypeNode, + ir_power_two, + ir_span_valid, + ir_storage_valid, +}; + // Private flat frontend/output storage for O0 lowering. Types are canonical // structural identities; field names remain source layout facts, not IR types. -struct IrLowerNode { tag: u64; a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; g: u64; h: u64; i: u64; j: u64; k: u64; } +pub struct IrLowerNode { tag: u64; a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; g: u64; h: u64; i: u64; j: u64; k: u64; } -struct IrLowerString { data: ptr; length: u64; } +pub struct IrLowerString { data: ptr; length: u64; } -struct IrLowerType { kind: u64; child: u64; first: u64; count: u64; auxiliary: u64; } +pub struct IrLowerType { kind: u64; child: u64; first: u64; count: u64; auxiliary: u64; } -struct IrLowerValue { value: u64; ty: u64; } +pub struct IrLowerValue { value: u64; ty: u64; } -struct IrLowerBinding { name: u64; ty: u64; value: u64; kind: u64; constant: u64; } +pub struct IrLowerBinding { name: u64; ty: u64; value: u64; kind: u64; constant: u64; } struct IrLowerResult { status: u64; node: u64; expected: u64; actual: u64; annotation: u64; detail: u64; work: u64; } -struct IrLowerContext { +pub struct IrLowerContext { nodes: ptr; node_count: u64; edges: ptr; edge_count: u64; names: ptr; name_count: u64; @@ -28,7 +38,7 @@ struct IrLowerContext { result: ptr; } -fun ir_lower_fail(p: ptr, status: u64, node: u64, +pub fun ir_lower_fail(p: ptr, status: u64, node: u64, expected: u64, actual: u64, detail: u64) -> bool { p.result.status = status; p.result.node = node; p.result.expected = expected; p.result.actual = actual; @@ -36,45 +46,45 @@ fun ir_lower_fail(p: ptr, status: u64, node: u64, return false; } -fun ir_lower_charge(p: ptr, amount: u64, node: u64) -> bool { +pub fun ir_lower_charge(p: ptr, amount: u64, node: u64) -> bool { if (amount > p.max_work - p.work) { return ir_lower_fail(p, 1, node, 0, 0, 0); } p.work += amount; return true; } -fun ir_lower_node(p: ptr, node: u64, depth: u64) -> bool { +pub fun ir_lower_node(p: ptr, node: u64, depth: u64) -> bool { if (depth > p.max_depth) { return ir_lower_fail(p, 2, node, 0, 0, 0); } if (!ir_lower_charge(p, 1, node)) { return false; } if (node >= p.node_count) { return ir_lower_fail(p, 3, node, 0, 0, 0); } return true; } -fun ir_lower_edges(p: ptr, first: u64, count: u64, node: u64) -> bool { +pub fun ir_lower_edges(p: ptr, first: u64, count: u64, node: u64) -> bool { if (first > p.edge_count || count > p.edge_count - first) { return ir_lower_fail(p, 3, node, 0, 0, 0); } return true; } -fun ir_lower_name(p: ptr, name: u64, node: u64) -> bool { +pub fun ir_lower_name(p: ptr, name: u64, node: u64) -> bool { if (name >= p.name_count) { return ir_lower_fail(p, 3, node, 0, 0, 0); } return true; } -fun ir_lower_integer(ty: u64) -> bool { return ty >= 2 && ty <= 13; } +pub fun ir_lower_integer(ty: u64) -> bool { return ty >= 2 && ty <= 13; } -fun ir_lower_signed(ty: u64) -> bool { return ty == 2 || (ty >= 4 && ty <= 8); } +pub fun ir_lower_signed(ty: u64) -> bool { return ty == 2 || (ty >= 4 && ty <= 8); } -fun ir_lower_float(ty: u64) -> bool { return ty >= 14 && ty <= 16; } +pub fun ir_lower_float(ty: u64) -> bool { return ty >= 14 && ty <= 16; } -fun ir_lower_scalar(p: ptr, ty: u64) -> bool { +pub fun ir_lower_scalar(p: ptr, ty: u64) -> bool { return ty != 0 && ty < p.type_count && p.types[ty].kind <= 18; } -fun ir_lower_aggregate(p: ptr, ty: u64) -> bool { +pub fun ir_lower_aggregate(p: ptr, ty: u64) -> bool { return p.types[ty].kind == 19 || p.types[ty].kind == 20; } -fun ir_lower_width(ty: u64) -> u64 { +pub fun ir_lower_width(ty: u64) -> u64 { if (ty == 2 || ty == 3) { return 1; } if (ty >= 9 && ty <= 13) { ty -= 5; } if (ty == 4) { return 8; } @@ -106,7 +116,7 @@ fun ir_lower_mix(value: u64) -> u64 { return value ^ (value >> 31); } -fun ir_lower_type_intern(p: ptr, kind: u64, child: u64, +pub fun ir_lower_type_intern(p: ptr, kind: u64, child: u64, children: ptr, count: u64, auxiliary: u64, node: u64, output: ptr) -> bool { var hash: u64 = kind ^ (child << 7) ^ (child >> 57) ^ auxiliary ^ (count << 21); var at: u64 = 0; @@ -159,11 +169,11 @@ fun ir_lower_type_intern(p: ptr, kind: u64, child: u64, return ir_lower_fail(p, 4, node, 0, 0, 0); } -fun ir_lower_pointer(p: ptr, child: u64, node: u64, output: ptr) -> bool { +pub fun ir_lower_pointer(p: ptr, child: u64, node: u64, output: ptr) -> bool { return ir_lower_type_intern(p, 17, child, null, 0, 0, node, output); } -fun ir_lower_type(p: ptr, node: u64, depth: u64, output: ptr) -> bool { +pub fun ir_lower_type(p: ptr, node: u64, depth: u64, output: ptr) -> bool { if (!ir_lower_node(p, node, depth)) { return false; } if (p.type_map[node] != 18446744073709551615) { output[0] = p.type_map[node]; return true; } var n: ptr = &p.nodes[node]; @@ -252,7 +262,7 @@ fun ir_lower_type(p: ptr, node: u64, depth: u64, output: ptr, ty: u64, node: u64) -> bool { +pub fun ir_lower_layout(p: ptr, ty: u64, node: u64) -> bool { var remaining: u64 = p.max_work - p.work; var status: i32 = ir_layout_node(ty, p.layout_nodes, p.type_count, p.type_edges, p.type_edge_count, p.storage, p.max_depth, @@ -263,7 +273,7 @@ fun ir_lower_layout(p: ptr, ty: u64, node: u64) -> bool { return true; } -fun ir_lower_initialize(p: ptr) -> bool { +pub fun ir_lower_initialize(p: ptr) -> bool { if (p == null || p.result == null) { return false; } p.result.status = 0; p.result.node = 0; p.result.expected = 0; p.result.actual = 0; p.result.annotation = 18446744073709551615; p.result.detail = 0; p.result.work = 0; @@ -315,7 +325,7 @@ fun ir_lower_initialize(p: ptr) -> bool { // Native conformance probe shares the same canonical model and Wave layout // routines as the complete O0 lowering driver. The output ID is transactional. -export(c) fun whale_ir_lower_type(p: ptr, node: u64, output: ptr) -> i32 { +pub export(c) fun whale_ir_lower_type(p: ptr, node: u64, output: ptr) -> i32 { if (p == null || p.result == null || output == null) { return 3; } if (!ir_lower_initialize(p)) { p.result.work = p.work; return p.result.status as i32; } var ty: u64 = 0; diff --git a/ir/lower_output.wave b/ir/src/lowering/output.wave similarity index 88% rename from ir/lower_output.wave rename to ir/src/lowering/output.wave index f56cc51..e46a665 100644 --- a/ir/lower_output.wave +++ b/ir/src/lowering/output.wave @@ -1,4 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::lowering::model")::{ + IrLowerBinding, + IrLowerContext, + IrLowerType, + ir_lower_charge, + ir_lower_fail, + ir_lower_name, +}; + // Typed O0 output is a caller-owned flat model. Wave chooses every identity, // body link, hoisted allocation position and source identity before Rust reads it. struct IrLowerInstruction { @@ -12,14 +21,14 @@ struct IrLowerBlock { term_ty: u64; term_annotation: u64; term_source: u64; } -struct IrLowerConstant { +pub struct IrLowerConstant { kind: u64; operation: u64; ty: u64; low: u64; high: u64; left: u64; right: u64; reference: u64; annotation: u64; } -struct IrLowerDeclaration { name: u64; signature: u64; linkage: u64; link_name: u64; defined: u64; source: u64; } +pub struct IrLowerDeclaration { name: u64; signature: u64; linkage: u64; link_name: u64; defined: u64; source: u64; } -struct IrLowerFunction { declaration: u64; first_param: u64; param_count: u64; first_block: u64; block_count: u64; entry: u64; source: u64; } +pub struct IrLowerFunction { declaration: u64; first_param: u64; param_count: u64; first_block: u64; block_count: u64; entry: u64; source: u64; } struct IrLowerGlobal { name: u64; ty: u64; expression: u64; align: u64; annotation: u64; source: u64; } @@ -33,7 +42,7 @@ struct IrLowerOriginalSlot { id: u64; occupied: u64; } struct IrLowerEvalRequest { expression: u64; kind: u64; identity: u64; annotation: u64; } -struct IrLowerDriver { +pub struct IrLowerDriver { core: ptr; mode: u64; expansion: u64; max_expansion: u64; instructions: ptr; instruction_count: u64; instruction_capacity: u64; output_edges: ptr; output_edge_count: u64; output_edge_capacity: u64; @@ -59,14 +68,14 @@ struct IrLowerDriver { requests: ptr; request_count: u64; request_capacity: u64; } -fun ir_lower_source_charge(p: ptr, amount: u64, node: u64) -> bool { +pub fun ir_lower_source_charge(p: ptr, amount: u64, node: u64) -> bool { if (amount > p.max_source_work - p.source_work) { return ir_lower_fail(p.core, 22, node, 0, 0, 0); } p.source_work += amount; return ir_lower_charge(p.core, amount, node); } -fun ir_lower_expand(p: ptr, amount: u64, node: u64) -> bool { +pub fun ir_lower_expand(p: ptr, amount: u64, node: u64) -> bool { if (!ir_lower_charge(p.core, amount, node)) { return false; } if (amount > p.max_expansion - p.expansion) { return ir_lower_fail(p.core, 23, node, 0, 0, 0); @@ -74,7 +83,7 @@ fun ir_lower_expand(p: ptr, amount: u64, node: u64) -> bool { p.expansion += amount; return true; } -fun ir_lower_type_size(p: ptr, ty: u64, node: u64, depth: u64, size: ptr) -> bool { +pub fun ir_lower_type_size(p: ptr, ty: u64, node: u64, depth: u64, size: ptr) -> bool { if (ty >= p.core.type_count || depth > 32) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } if (!ir_lower_charge(p.core, 1, node)) { return false; } if (p.type_sizes[ty] != 0) { size[0] = p.type_sizes[ty]; return true; } @@ -96,7 +105,7 @@ fun ir_lower_type_size(p: ptr, ty: u64, node: u64, depth: u64, si p.type_sizes[ty] = count; size[0] = count; return true; } -fun ir_lower_value(p: ptr, ty: u64, node: u64, output: ptr) -> bool { +pub fun ir_lower_value(p: ptr, ty: u64, node: u64, output: ptr) -> bool { var size: u64 = 0; if (!ir_lower_type_size(p, ty, node, 0, &size) || !ir_lower_expand(p, 1 + size, node)) { return false; } if (p.next_value >= 4294967295) { return ir_lower_fail(p.core, 23, node, 0, 0, 0); } @@ -107,7 +116,7 @@ fun ir_lower_value(p: ptr, ty: u64, node: u64, output: ptr) output[0] = p.next_value; p.next_value += 1; return true; } -fun ir_lower_block(p: ptr, name: u64, node: u64, output: ptr) -> bool { +pub fun ir_lower_block(p: ptr, name: u64, node: u64, output: ptr) -> bool { if (!ir_lower_expand(p, 1, node)) { return false; } if (p.block_count >= p.block_capacity || p.block_count >= 4294967295) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); @@ -122,7 +131,7 @@ fun ir_lower_block(p: ptr, name: u64, node: u64, output: ptr p.blocks[id].term_source = node; p.block_count += 1; output[0] = id; return true; } -fun ir_lower_emit(p: ptr, tag: u64, dst: u64, ty: u64, +pub fun ir_lower_emit(p: ptr, tag: u64, dst: u64, ty: u64, a: u64, b: u64, c: u64, d: u64, e: u64, edges: ptr, count: u64, hoisted: bool, node: u64) -> bool { var type_size: u64 = 0; @@ -173,7 +182,7 @@ fun ir_lower_emit(p: ptr, tag: u64, dst: u64, ty: u64, p.blocks[block].instruction_count += 1; return true; } -fun ir_lower_term(p: ptr, kind: u64, ty: u64, a: u64, +pub fun ir_lower_term(p: ptr, kind: u64, ty: u64, a: u64, b: u64, c: u64, node: u64) -> bool { if (!ir_lower_expand(p, 1, node)) { return false; } if (p.current_block >= p.block_count || p.blocks[p.current_block].term_kind != 0) { @@ -186,7 +195,7 @@ fun ir_lower_term(p: ptr, kind: u64, ty: u64, a: u64, block.term_c = c; block.term_annotation = p.core.annotation; block.term_source = node; return true; } -fun ir_lower_source(p: ptr, annotation: u64, node: u64) -> bool { +pub fun ir_lower_source(p: ptr, annotation: u64, node: u64) -> bool { if (annotation >= p.annotation_count) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } if (!ir_lower_source_charge(p, 1, node)) { return false; } if (p.source_marks[annotation] != 0) { return true; } @@ -204,7 +213,7 @@ fun ir_lower_source(p: ptr, annotation: u64, node: u64) -> bool { // Binding.constant stores the previous local slot. Typed constant payloads are // separate records, so a scope restores names by popping only its own bindings. -fun ir_lower_binding(p: ptr, name: u64, node: u64, +pub fun ir_lower_binding(p: ptr, name: u64, node: u64, global_only: bool, output: ptr) -> bool { if (!ir_lower_charge(p.core, 1, node) || !ir_lower_name(p.core, name, node)) { return false; } var slot: u64 = 18446744073709551615; @@ -215,7 +224,7 @@ fun ir_lower_binding(p: ptr, name: u64, node: u64, return ir_lower_fail(p.core, 11, node, 0, 0, name); } -fun ir_lower_bind(p: ptr, name: u64, ty: u64, value: u64, +pub fun ir_lower_bind(p: ptr, name: u64, ty: u64, value: u64, kind: u64, constant: u64, node: u64) -> bool { if (!ir_lower_charge(p.core, 1, node) || !ir_lower_name(p.core, name, node)) { return false; } if (p.binding_count >= p.binding_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } @@ -225,7 +234,7 @@ fun ir_lower_bind(p: ptr, name: u64, ty: u64, value: u64, p.local_slots[name] = at; p.binding_count += 1; return true; } -fun ir_lower_restore(p: ptr, saved: u64, node: u64) -> bool { +pub fun ir_lower_restore(p: ptr, saved: u64, node: u64) -> bool { while (p.binding_count > saved) { if (!ir_lower_charge(p.core, 1, node)) { return false; } p.binding_count -= 1; @@ -235,7 +244,7 @@ fun ir_lower_restore(p: ptr, saved: u64, node: u64) -> bool { return true; } -fun ir_lower_local_binding(p: ptr, name: u64, node: u64, +pub fun ir_lower_local_binding(p: ptr, name: u64, node: u64, output: ptr) -> bool { if (!ir_lower_charge(p.core, 1, node) || !ir_lower_name(p.core, name, node)) { return false; } var slot: u64 = p.local_slots[name]; @@ -243,7 +252,7 @@ fun ir_lower_local_binding(p: ptr, name: u64, node: u64, return ir_lower_fail(p.core, 11, node, 0, 0, name); } -fun ir_lower_complete_source(p: ptr, annotation: u64, node: u64) -> bool { +pub fun ir_lower_complete_source(p: ptr, annotation: u64, node: u64) -> bool { if (!ir_lower_source(p, annotation, node)) { return false; } if (p.mode == 1) { if (p.mapping_count >= p.mapping_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } @@ -254,7 +263,7 @@ fun ir_lower_complete_source(p: ptr, annotation: u64, node: u64) // A completed constexpr is evaluated by the central numeric engine before a // later AST error is reported. Partial preservation never publishes a request. -fun ir_lower_evaluate_request(p: ptr, expression: u64, kind: u64, +pub fun ir_lower_evaluate_request(p: ptr, expression: u64, kind: u64, identity: u64, node: u64) -> bool { if (p.request_count >= p.request_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } var record: ptr = &p.requests[p.request_count]; diff --git a/ir/src/lowering/signature.wave b/ir/src/lowering/signature.wave new file mode 100644 index 0000000..9e3aca0 --- /dev/null +++ b/ir/src/lowering/signature.wave @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::lowering::model")::{ + IrLowerType, + ir_lower_aggregate, + ir_lower_charge, + ir_lower_fail, +}; +import("whale_wave_ir::lowering::output")::{IrLowerDriver}; + +fun ir_lower_signature_type(p: ptr, ty: u64, depth: u64, node: u64) -> bool { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (depth > p.core.max_depth) { return ir_lower_fail(p.core, 2, node, 0, 0, 0); } + if (ty >= p.core.type_count) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + var t: ptr = &p.core.types[ty]; + if (t.kind == 0) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + if (t.kind == 18) { return ir_lower_signature_validate(p, ty, depth + 1, node); } + if (t.kind == 17) { + if (t.child == 0) { return true; } + return ir_lower_signature_type(p, t.child, depth + 1, node); + } + if (t.kind == 19) { return ir_lower_signature_type(p, t.child, depth + 1, node); } + var at: u64 = 0; + if (t.kind == 20 || t.kind == 21) { + while (at < t.count) { + if (!ir_lower_signature_type(p, p.core.type_edges[t.first + at], depth + 1, node)) { return false; } + at += 1; + } + } + return true; +} + +pub fun ir_lower_signature_validate(p: ptr, ty: u64, depth: u64, node: u64) -> bool { + if (depth > p.core.max_depth) { return ir_lower_fail(p.core, 2, node, 0, 0, 0); } + if (ty >= p.core.type_count || p.core.types[ty].kind != 18) { + return ir_lower_fail(p.core, 21, node, 0, 0, 1); + } + var t: ptr = &p.core.types[ty]; + if (t.child != 0) { + if (t.auxiliary == 1 && ir_lower_aggregate(p.core, t.child)) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + if (!ir_lower_signature_type(p, t.child, depth + 1, node)) { return false; } + } + var at: u64 = 0; + while (at < t.count) { + var param: u64 = p.core.type_edges[t.first + at]; + if (t.auxiliary == 1 && ir_lower_aggregate(p.core, param)) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + if (!ir_lower_signature_type(p, param, depth + 1, node)) { return false; } + at += 1; + } + return true; +} + +pub fun ir_lower_scalar_signature(p: ptr, ty: u64, node: u64) -> bool { + var signature: ptr = &p.core.types[ty]; + if (ir_lower_aggregate(p.core, signature.child)) { return ir_lower_fail(p.core, 18, node, 0, 0, 9); } + var at: u64 = 0; + while (at < signature.count) { + var kind: u64 = p.core.types[p.core.type_edges[signature.first + at]].kind; + if (kind == 20 || kind == 21) { return ir_lower_fail(p.core, 18, node, 0, 0, 9); } + at += 1; + } + return true; +} diff --git a/ir/lower_statement.wave b/ir/src/lowering/statement.wave similarity index 91% rename from ir/lower_statement.wave rename to ir/src/lowering/statement.wave index c923983..73810fa 100644 --- a/ir/lower_statement.wave +++ b/ir/src/lowering/statement.wave @@ -1,6 +1,38 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::lowering::expression")::{ + ir_lower_expression, + ir_lower_mismatch, + ir_lower_place, + ir_lower_preserve_constant, +}; +import("whale_wave_ir::lowering::model")::{ + IrLowerBinding, + IrLowerNode, + IrLowerValue, + ir_lower_edges, + ir_lower_fail, + ir_lower_layout, + ir_lower_name, + ir_lower_node, + ir_lower_scalar, + ir_lower_type, +}; +import("whale_wave_ir::lowering::output")::{ + IrLowerDriver, + ir_lower_bind, + ir_lower_block, + ir_lower_complete_source, + ir_lower_emit, + ir_lower_evaluate_request, + ir_lower_local_binding, + ir_lower_restore, + ir_lower_term, + ir_lower_value, +}; +import("whale_wave_ir::lowering::storage")::{ir_lower_alloca, ir_lower_write}; + // Wave owns lexical scope restoration and all O0 control-flow construction. -fun ir_lower_statements(p: ptr, first: u64, count: u64, +pub fun ir_lower_statements(p: ptr, first: u64, count: u64, depth: u64, node: u64) -> bool { if (!ir_lower_edges(p.core, first, count, node)) { return false; } var at: u64 = 0; diff --git a/ir/src/lowering/storage.wave b/ir/src/lowering/storage.wave new file mode 100644 index 0000000..f819708 --- /dev/null +++ b/ir/src/lowering/storage.wave @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::lowering::model")::{ + IrLowerNode, + IrLowerValue, + ir_lower_aggregate, + ir_lower_charge, + ir_lower_fail, + ir_lower_layout, + ir_lower_pointer, +}; +import("whale_wave_ir::lowering::output")::{IrLowerDriver, ir_lower_emit, ir_lower_value}; +import("whale_wave_ir::lowering::values")::{ir_lower_cast_value, ir_lower_immediate}; + +// Frontend aggregates denote addresses; scalar expressions denote SSA values. +// Copying an aggregate snapshots the RHS before touching a possibly aliasing LHS. +pub fun ir_lower_alloca(p: ptr, ty: u64, align: u64, node: u64, output: ptr) -> bool { + var pointer: u64 = 0; + var value: u64 = 0; + if (!ir_lower_pointer(p.core, ty, node, &pointer) + || !ir_lower_value(p, pointer, node, &value) + || !ir_lower_emit(p, 18, value, ty, align, 0, 0, 0, 0, null, 0, true, node)) { return false; } + output[0] = value; return true; +} + +pub fun ir_lower_read(p: ptr, pointer: u64, ty: u64, node: u64, + output: ptr) -> bool { + if (ir_lower_aggregate(p.core, ty)) { output.value = pointer; output.ty = ty; return true; } + if (!ir_lower_layout(p.core, ty, node)) { return false; } + var value: u64 = 0; + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, 21, value, ty, pointer, p.core.layouts[ty].allocation_align, + 0, 0, 0, null, 0, false, node)) { return false; } + output.value = value; output.ty = ty; return true; +} + +pub fun ir_lower_write(p: ptr, pointer: u64, value: u64, ty: u64, node: u64) -> bool { + if (!ir_lower_layout(p.core, ty, node)) { return false; } + var align: u64 = p.core.layouts[ty].align; + if (!ir_lower_aggregate(p.core, ty)) { + return ir_lower_emit(p, 23, 18446744073709551615, ty, + value, pointer, align, 0, 0, null, 0, false, node); + } + if (pointer == value) { return true; } + var temporary: u64 = 0; + var byte_pointer: u64 = 0; + var aggregate_pointer: u64 = 0; + var destination: u64 = 0; + var source: u64 = 0; + var snapshot: u64 = 0; + var size: u64 = 0; + if (!ir_lower_alloca(p, ty, align, node, &temporary) + || !ir_lower_pointer(p.core, 9, node, &byte_pointer) + || !ir_lower_pointer(p.core, ty, node, &aggregate_pointer) + || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, pointer, node, &destination) + || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, value, node, &source) + || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, temporary, node, &snapshot) + || !ir_lower_immediate(p, 12, p.core.layouts[ty].size, 0, node, &size) + || !ir_lower_emit(p, 25, 18446744073709551615, 18446744073709551615, + snapshot, source, size, align, 0, null, 0, false, node) + || !ir_lower_emit(p, 25, 18446744073709551615, 18446744073709551615, + destination, snapshot, size, align, 0, null, 0, false, node)) { return false; } + return true; +} + +pub fun ir_lower_field_pointer(p: ptr, base: u64, ordinal: u64, ty: u64, + node: u64, output: ptr) -> bool { + var zero: u64 = 0; + var index: u64 = 0; + var pointer: u64 = 0; + var destination: u64 = 0; + var indices: array; + if (!ir_lower_immediate(p, 12, 0, 0, node, &zero) + || !ir_lower_immediate(p, 12, ordinal, 0, node, &index) + || !ir_lower_pointer(p.core, ty, node, &pointer) + || !ir_lower_value(p, pointer, node, &destination)) { return false; } + indices[0] = zero; indices[1] = index; + if (!ir_lower_emit(p, 24, destination, pointer, base, 0, 0, 0, 0, + &indices[0], 2, false, node)) { return false; } + output[0] = destination; return true; +} + + + +pub fun ir_lower_field_map(p: ptr, layout: u64, node: u64) -> bool { + var t: ptr = &p.core.nodes[layout]; + var at: u64 = 0; + while (at < t.b) { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (p.field_binding_count >= p.field_binding_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + var name: u64 = p.core.nodes[p.core.edges[t.a + at]].a; + var id: u64 = p.field_binding_count; + p.field_bindings[id].name = name; p.field_bindings[id].ordinal = at; + p.field_bindings[id].previous = p.field_slots[name]; p.field_bindings[id].used = 0; + p.field_slots[name] = id; p.field_binding_count += 1; at += 1; + } + return true; +} diff --git a/ir/src/lowering/values.wave b/ir/src/lowering/values.wave new file mode 100644 index 0000000..4f343c6 --- /dev/null +++ b/ir/src/lowering/values.wave @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::lowering::model")::{ir_lower_float, ir_lower_signed}; +import("whale_wave_ir::lowering::output")::{IrLowerDriver, ir_lower_emit, ir_lower_value}; + +pub fun ir_lower_immediate(p: ptr, ty: u64, low: u64, high: u64, + node: u64, output: ptr) -> bool { + var id: u64 = 0; + if (!ir_lower_value(p, ty, node, &id)) { return false; } + var category: u64 = 3; + if (ty == 1) { category = 1; } + else if (ir_lower_signed(ty)) { category = 2; } + else if (ir_lower_float(ty)) { category = 4; } + if (!ir_lower_emit(p, 4, id, ty, 2, low, high, category, 0, null, 0, false, node)) { return false; } + output[0] = id; return true; +} + +pub fun ir_lower_cast_value(p: ptr, op: u64, src_ty: u64, dst_ty: u64, + value: u64, node: u64, output: ptr) -> bool { + var id: u64 = 0; + if (!ir_lower_value(p, dst_ty, node, &id) + || !ir_lower_emit(p, 14, id, dst_ty, op, src_ty, value, 0, 0, null, 0, false, node)) { return false; } + output[0] = id; return true; +} diff --git a/ir/model.wave b/ir/src/model.wave similarity index 84% rename from ir/model.wave rename to ir/src/model.wave index 6f4b343..e604be3 100644 --- a/ir/model.wave +++ b/ir/src/model.wave @@ -4,14 +4,14 @@ // Kinds: void, 1/2/4/8/16-byte scalar, pointer, function pointer, array, // struct, tuple. The Rust compatibility model maps its named scalar types to // these storage classes at this internal boundary. -struct IrTypeNode { +pub struct IrTypeNode { kind: u64; child: u64; first: u64; count: u64; } -struct IrStorage { +pub struct IrStorage { ptr_bits: u64; pointer_align: u64; scalar_align1: u64; @@ -24,7 +24,7 @@ struct IrStorage { has_large_array: u64; } -struct IrTypeLayout { +pub struct IrTypeLayout { size: u64; align: u64; stride: u64; @@ -32,16 +32,16 @@ struct IrTypeLayout { depth: u64; } -struct IrLayoutResult { +pub struct IrLayoutResult { status: u64; index: u64; } -fun ir_power_two(value: u64) -> bool { +pub fun ir_power_two(value: u64) -> bool { return value != 0 && (value & (value - 1)) == 0; } -fun ir_storage_valid(storage: ptr) -> bool { +pub fun ir_storage_valid(storage: ptr) -> bool { if (storage == null || (storage.ptr_bits != 32 && storage.ptr_bits != 64) || !ir_power_two(storage.pointer_align) || storage.pointer_align > storage.ptr_bits / 8 @@ -54,13 +54,13 @@ fun ir_storage_valid(storage: ptr) -> bool { return storage.has_large_array == 0 || ir_power_two(storage.large_array_align); } -fun ir_span_valid(data: ptr, count: u64, width: u64) -> bool { +pub fun ir_span_valid(data: ptr, count: u64, width: u64) -> bool { return count <= 9223372036854775807 / width && (count == 0 || data != null) && count * width <= 18446744073709551615 - (data as u64); } -fun ir_align_up(size: u64, align: u64, result: ptr) -> bool { +pub fun ir_align_up(size: u64, align: u64, result: ptr) -> bool { var mask: u64 = align - 1; if (size > 18446744073709551615 - mask) { return false; } result[0] = (size + mask) & ~mask; diff --git a/ir/float_arithmetic.wave b/ir/src/numeric/float_arithmetic.wave similarity index 90% rename from ir/float_arithmetic.wave rename to ir/src/numeric/float_arithmetic.wave index afe1b87..aff08b2 100644 --- a/ir/float_arithmetic.wave +++ b/ir/src/numeric/float_arithmetic.wave @@ -1,6 +1,29 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::numeric::float_model")::{ + IrFloatFormat, + IrFloatParts, + ir_float_format, + ir_float_nan, + ir_float_normalize, + ir_float_pack, + ir_float_special, + ir_float_unpack, + ir_float_wide_zero, +}; +import("whale_wave_ir::numeric::wide")::{ + IrWide, + ir_wide_add, + ir_wide_cmp, + ir_wide_divmod, + ir_wide_from, + ir_wide_jam, + ir_wide_mul, + ir_wide_shl, + ir_wide_sub, +}; + // Finite products remain exact through 106 bits; only packing rounds. -fun ir_float_arithmetic(operation: u64, kind: u64, lhs: u64, rhs: u64, output: ptr) -> bool { +pub fun ir_float_arithmetic(operation: u64, kind: u64, lhs: u64, rhs: u64, output: ptr) -> bool { var format: IrFloatFormat; if (operation > 4 || !ir_float_format(kind, &format)) { return false; diff --git a/ir/float_convert.wave b/ir/src/numeric/float_convert.wave similarity index 91% rename from ir/float_convert.wave rename to ir/src/numeric/float_convert.wave index 8a30e06..2006e3e 100644 --- a/ir/float_convert.wave +++ b/ir/src/numeric/float_convert.wave @@ -1,4 +1,39 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::numeric::float_arithmetic")::{ir_float_arithmetic}; +import("whale_wave_ir::numeric::float_model")::{ + IrFloatFormat, + IrFloatParts, + IrFloatRequest, + IrFloatResult, + ir_float_format, + ir_float_infinity, + ir_float_nan, + ir_float_pack, + ir_float_predicate, + ir_float_sign, + ir_float_special, + ir_float_unpack, + ir_float_wide_zero, +}; +import("whale_wave_ir::model")::{ir_span_valid}; +import("whale_wave_ir::verifier::module")::{ + ir_verify_literal, + ir_verify_signed, + ir_verify_unsigned, + ir_verify_width, +}; +import("whale_wave_ir::numeric::wide")::{ + IrWide, + ir_wide_clz, + ir_wide_cmp, + ir_wide_from, + ir_wide_neg, + ir_wide_shl, + ir_wide_shr, + ir_wide_sub, + ir_wide_zero, +}; + // Numeric conversions share the single packer's rounding; stored NaNs stay separate. fun ir_float_integer_mask(width: u64, output: ptr) { var one: u64 = 1; @@ -219,7 +254,7 @@ fun ir_float_input_valid(kind: u64, literal: u64, low: u64, high: u64) -> bool { return true; } -export(c) fun whale_ir_float(request: ptr, result: ptr) -> i32 { +pub export(c) fun whale_ir_float(request: ptr, result: ptr) -> i32 { if (!ir_span_valid(result as ptr, 1, 32)) { return 9; } diff --git a/ir/float_model.wave b/ir/src/numeric/float_model.wave similarity index 86% rename from ir/float_model.wave rename to ir/src/numeric/float_model.wave index 4ee8bf3..ec448bd 100644 --- a/ir/float_model.wave +++ b/ir/src/numeric/float_model.wave @@ -1,12 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::numeric::wide")::{ + IrWide, + ir_wide_clz, + ir_wide_from, + ir_wide_round, + ir_wide_shl, + ir_wide_shr, +}; + // IEEE storage and nearest-even packing use only the shared two-word integer. -struct IrFloatFormat { +pub struct IrFloatFormat { width: u64; fraction: u64; bias: i64; } -struct IrFloatParts { +pub struct IrFloatParts { negative: bool; significand: IrWide; exponent: i64; @@ -14,14 +23,14 @@ struct IrFloatParts { infinity: bool; } -struct IrFloatResult { +pub struct IrFloatResult { status: u64; low: u64; high: u64; flag: u64; } -struct IrFloatRequest { +pub struct IrFloatRequest { mode: u64; operation: u64; source: u64; @@ -34,7 +43,7 @@ struct IrFloatRequest { right_high: u64; } -fun ir_float_format(kind: u64, output: ptr) -> bool { +pub fun ir_float_format(kind: u64, output: ptr) -> bool { if (kind == 14) { output.width = 16; output.fraction = 10; @@ -53,21 +62,21 @@ fun ir_float_format(kind: u64, output: ptr) -> bool { return true; } -fun ir_float_sign(format: ptr) -> u64 { +pub fun ir_float_sign(format: ptr) -> u64 { var one: u64 = 1; return one << (format.width - 1); } -fun ir_float_infinity(format: ptr) -> u64 { +pub fun ir_float_infinity(format: ptr) -> u64 { return ((format.bias * 2 + 1) as u64) << format.fraction; } -fun ir_float_nan(format: ptr) -> u64 { +pub fun ir_float_nan(format: ptr) -> u64 { var one: u64 = 1; return ir_float_infinity(format) | (one << (format.fraction - 1)); } -fun ir_float_special(format: ptr, negative: bool, infinity: bool) -> u64 { +pub fun ir_float_special(format: ptr, negative: bool, infinity: bool) -> u64 { var bits: u64 = 0; if (negative) { bits = ir_float_sign(format); @@ -78,11 +87,11 @@ fun ir_float_special(format: ptr, negative: bool, infinity: bool) return bits; } -fun ir_float_wide_zero(value: ptr) -> bool { +pub fun ir_float_wide_zero(value: ptr) -> bool { return value.low == 0 && value.high == 0; } -fun ir_float_unpack(format: ptr, bits: u64, output: ptr) { +pub fun ir_float_unpack(format: ptr, bits: u64, output: ptr) { var one: u64 = 1; var exponent: i64 = ((bits & ~ir_float_sign(format)) >> format.fraction) as i64; var fraction: u64 = bits & ((one << format.fraction) - 1); @@ -100,7 +109,7 @@ fun ir_float_unpack(format: ptr, bits: u64, output: ptr, value: ptr) { +pub fun ir_float_normalize(format: ptr, value: ptr) { if (!ir_float_wide_zero(&value.significand)) { var shift: u64 = ir_wide_clz(&value.significand) - (127 - format.fraction); ir_wide_shl(&value.significand, shift, &value.significand); @@ -108,7 +117,7 @@ fun ir_float_normalize(format: ptr, value: ptr) { } } -fun ir_float_pack( +pub fun ir_float_pack( format: ptr, negative: bool, significand: ptr, @@ -153,7 +162,7 @@ fun ir_float_pack( 1)); } -fun ir_float_predicate( +pub fun ir_float_predicate( format: ptr, a: u64, b: u64, diff --git a/ir/integer.wave b/ir/src/numeric/integer.wave similarity index 94% rename from ir/integer.wave rename to ir/src/numeric/integer.wave index f13daf4..0a62792 100644 --- a/ir/integer.wave +++ b/ir/src/numeric/integer.wave @@ -1,13 +1,34 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::numeric::wide")::{ + IrWide, + ir_wide_add, + ir_wide_ashr, + ir_wide_bit, + ir_wide_clz, + ir_wide_cmp, + ir_wide_divmod, + ir_wide_from, + ir_wide_jam, + ir_wide_mask, + ir_wide_mul, + ir_wide_neg, + ir_wide_round, + ir_wide_shl, + ir_wide_shr, + ir_wide_sub, + ir_wide_trim, + ir_wide_zero, +}; + // Defined fixed-width scalar arithmetic and conversion over shared two-word math. -struct IrIntegerResult { +pub struct IrIntegerResult { status: u64; low: u64; high: u64; flag: u64; } -fun ir_integer_width(kind: u64) -> u64 { +pub fun ir_integer_width(kind: u64) -> u64 { if (kind == 1 || kind == 2 || kind == 3) { return 1; } @@ -29,7 +50,7 @@ fun ir_integer_width(kind: u64) -> u64 { return 0; } -fun ir_integer_signed(kind: u64) -> bool { +pub fun ir_integer_signed(kind: u64) -> bool { return kind == 2 || (kind >= 4 && kind <= 8); } @@ -77,7 +98,7 @@ fun ir_integer_magnitude(value: ptr, width: u64, negative: bool, output: } } -export(c) fun whale_ir_integer_bits(low: u64, high: u64, width: u64, +pub export(c) fun whale_ir_integer_bits(low: u64, high: u64, width: u64, is_signed: u64, result: ptr) -> i32 { if (result == null) { return 4; @@ -104,7 +125,7 @@ export(c) fun whale_ir_integer_bits(low: u64, high: u64, width: u64, // Modes: binary, checked, cast, comparison, checked cast, normalize, unary. // Binary codes match the complete IR BinOp inventory, including float holes. -export(c) fun whale_ir_integer(mode: u64, op: u64, source_kind: u64, +pub export(c) fun whale_ir_integer(mode: u64, op: u64, source_kind: u64, destination_kind: u64, a_low: u64, a_high: u64, b_low: u64, b_high: u64, result: ptr) -> i32 { if (result == null) { @@ -344,7 +365,7 @@ export(c) fun whale_ir_integer(mode: u64, op: u64, source_kind: u64, } // Direct primitive boundary for independent mathematical conformance. -export(c) fun whale_ir_wide(op: u64, low: u64, high: u64, other_low: u64, +pub export(c) fun whale_ir_wide(op: u64, low: u64, high: u64, other_low: u64, other_high: u64, count: u64, result: ptr) -> i32 { if (result == null) { return 4; diff --git a/ir/wide.wave b/ir/src/numeric/wide.wave similarity index 85% rename from ir/wide.wave rename to ir/src/numeric/wide.wave index 8f1f6a8..79a6304 100644 --- a/ir/wide.wave +++ b/ir/src/numeric/wide.wave @@ -1,21 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 // Two-word arithmetic. No host pointer width, native u128 or runtime helpers. -struct IrWide { +pub struct IrWide { low: u64; high: u64; } -fun ir_wide_from(low: u64, high: u64, output: ptr) { +pub fun ir_wide_from(low: u64, high: u64, output: ptr) { output.low = low; output.high = high; } -fun ir_wide_zero(output: ptr) { +pub fun ir_wide_zero(output: ptr) { output.low = 0; output.high = 0; } -fun ir_wide_cmp(a: ptr, b: ptr) -> i32 { +pub fun ir_wide_cmp(a: ptr, b: ptr) -> i32 { if (a.high < b.high || (a.high == b.high && a.low < b.low)) { return -1; } @@ -25,7 +25,7 @@ fun ir_wide_cmp(a: ptr, b: ptr) -> i32 { return 1; } -fun ir_wide_add(a: ptr, b: ptr, output: ptr) -> u64 { +pub fun ir_wide_add(a: ptr, b: ptr, output: ptr) -> u64 { var al: u64 = a.low; var ah: u64 = a.high; var bl: u64 = b.low; @@ -40,7 +40,7 @@ fun ir_wide_add(a: ptr, b: ptr, output: ptr) -> u64 { return (overflow || result < high) as u64; } -fun ir_wide_sub(a: ptr, b: ptr, output: ptr) -> u64 { +pub fun ir_wide_sub(a: ptr, b: ptr, output: ptr) -> u64 { var al: u64 = a.low; var ah: u64 = a.high; var bl: u64 = b.low; @@ -52,7 +52,7 @@ fun ir_wide_sub(a: ptr, b: ptr, output: ptr) -> u64 { return (ah < bh || high < borrow) as u64; } -fun ir_wide_neg(a: ptr, output: ptr) { +pub fun ir_wide_neg(a: ptr, output: ptr) { var low: u64 = 0 - a.low; var high: u64 = ~a.high; if (low == 0) { @@ -62,7 +62,7 @@ fun ir_wide_neg(a: ptr, output: ptr) { output.high = high; } -fun ir_wide_shl(a: ptr, count: u64, output: ptr) { +pub fun ir_wide_shl(a: ptr, count: u64, output: ptr) { var low: u64 = a.low; var high: u64 = a.high; if (count == 0) { @@ -79,7 +79,7 @@ fun ir_wide_shl(a: ptr, count: u64, output: ptr) { } } -fun ir_wide_shr(a: ptr, count: u64, output: ptr) { +pub fun ir_wide_shr(a: ptr, count: u64, output: ptr) { var low: u64 = a.low; var high: u64 = a.high; if (count == 0) { @@ -96,7 +96,7 @@ fun ir_wide_shr(a: ptr, count: u64, output: ptr) { } } -fun ir_wide_mask(width: u64, output: ptr) { +pub fun ir_wide_mask(width: u64, output: ptr) { if (width == 0) { ir_wide_zero(output); } else if (width < 64) { @@ -114,7 +114,7 @@ fun ir_wide_mask(width: u64, output: ptr) { } } -fun ir_wide_ashr(a: ptr, count: u64, output: ptr) { +pub fun ir_wide_ashr(a: ptr, count: u64, output: ptr) { var value: IrWide = a[0]; var negative: bool = (value.high & 9223372036854775808) != 0; ir_wide_shr(&value, count, output); @@ -130,14 +130,14 @@ fun ir_wide_ashr(a: ptr, count: u64, output: ptr) { } } -fun ir_wide_trim(a: ptr, width: u64, output: ptr) { +pub fun ir_wide_trim(a: ptr, width: u64, output: ptr) { var mask: IrWide; ir_wide_mask(width, &mask); output.low = a.low & mask.low; output.high = a.high & mask.high; } -fun ir_wide_bit(a: ptr, index: u64) -> u64 { +pub fun ir_wide_bit(a: ptr, index: u64) -> u64 { if (index < 64) { return (a.low >> index) & 1; } @@ -147,7 +147,7 @@ fun ir_wide_bit(a: ptr, index: u64) -> u64 { return 0; } -fun ir_wide_clz(a: ptr) -> u64 { +pub fun ir_wide_clz(a: ptr) -> u64 { if (a.high == 0 && a.low == 0) { return 128; } @@ -179,7 +179,7 @@ fun ir_wide_mul64(a: u64, b: u64, output: ptr) { output.high = p11 + (p01 >> 32) + (p10 >> 32) + (middle >> 32); } -fun ir_wide_mul(a: ptr, b: ptr, output: ptr) -> bool { +pub fun ir_wide_mul(a: ptr, b: ptr, output: ptr) -> bool { var al: u64 = a.low; var ah: u64 = a.high; var bl: u64 = b.low; @@ -200,7 +200,7 @@ fun ir_wide_mul(a: ptr, b: ptr, output: ptr) -> bool { return overflow; } -fun ir_wide_divmod(a: ptr, b: ptr, quotient: ptr, +pub fun ir_wide_divmod(a: ptr, b: ptr, quotient: ptr, remainder: ptr) -> bool { var numerator: IrWide = a[0]; var divisor: IrWide = b[0]; @@ -233,7 +233,7 @@ fun ir_wide_divmod(a: ptr, b: ptr, quotient: ptr, return true; } -fun ir_wide_jam(a: ptr, count: u64, output: ptr) { +pub fun ir_wide_jam(a: ptr, count: u64, output: ptr) { var value: IrWide = a[0]; if (count == 0) { output[0] = value; @@ -254,7 +254,7 @@ fun ir_wide_jam(a: ptr, count: u64, output: ptr) { output[0] = shifted; } -fun ir_wide_round(a: ptr, count: u64, output: ptr) { +pub fun ir_wide_round(a: ptr, count: u64, output: ptr) { var value: IrWide = a[0]; if (count == 0) { output[0] = value; diff --git a/ir/expression_parser.wave b/ir/src/parser/expressions.wave similarity index 97% rename from ir/expression_parser.wave rename to ir/src/parser/expressions.wave index d7706da..584fbb6 100644 --- a/ir/expression_parser.wave +++ b/ir/src/parser/expressions.wave @@ -1,4 +1,14 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::header")::{IrTextToken}; +import("whale_wave_ir::parser::literal")::{IrLiteralResult, whale_ir_parse_literal}; +import("whale_wave_ir::model")::{ir_span_valid}; +import("whale_wave_ir::parser::types")::{ + IrParsedType, + IrTypeParseResult, + ir_type_word, + whale_ir_parse_type, +}; + // Preserved constant-expression grammar, separate from numeric evaluation. struct IrParsedExpression { kind: u64; @@ -251,7 +261,7 @@ fun ir_expression_node(p: ptr, depth: u64, meta: ptr, token_count: u64, +pub export(c) fun whale_ir_parse_expression(tokens: ptr, token_count: u64, start: u64, depth: u64, format: u64, max_depth: u64, max_type_depth: u64, max_nodes: u64, max_work: u64, mode: u64, type_scratch: ptr, type_capacity: u64, diff --git a/ir/header.wave b/ir/src/parser/header.wave similarity index 97% rename from ir/header.wave rename to ir/src/parser/header.wave index c731941..011c4ef 100644 --- a/ir/header.wave +++ b/ir/src/parser/header.wave @@ -1,7 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; + // Versioned IR header parser. Token text is borrowed from the caller and the // payload is published only after every required field has been checked. -struct IrTextToken { +pub struct IrTextToken { data: ptr; length: u64; kind: u64; // 0 word, 1 decoded string, 2 mark, 3 EOF @@ -84,7 +86,7 @@ fun ir_header_expect(tokens: ptr, count: u64, at: ptr, return true; } -export(c) fun whale_ir_header(tokens: ptr, count: u64, +pub export(c) fun whale_ir_header(tokens: ptr, count: u64, max_format: u64, semantics: u64, result: ptr) -> i32 { if (result == null) { return 8; } result.status = 8; result.at = 0; result.expected = 0; diff --git a/ir/instruction_parser.wave b/ir/src/parser/instructions.wave similarity index 99% rename from ir/instruction_parser.wave rename to ir/src/parser/instructions.wave index de01d49..88f4e06 100644 --- a/ir/instruction_parser.wave +++ b/ir/src/parser/instructions.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::header")::{IrTextToken}; +import("whale_wave_ir::model")::{ir_span_valid}; + // Versioned instruction/terminator grammar. Primitive production selection, // list loops, result presence and diagnostics run in Wave. Nested type/literal/ // constant-expression requests call the other Wave-owned grammar kernels. @@ -640,7 +643,7 @@ fun ir_instruction_final(p: ptr) -> bool { return ir_instruction_request(p, 110, comparison, 901); } -export(c) fun whale_ir_instruction_step(tokens: ptr, token_count: u64, +pub export(c) fun whale_ir_instruction_step(tokens: ptr, token_count: u64, state: ptr, max_nodes: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 6; } diff --git a/ir/lexer.wave b/ir/src/parser/lexer.wave similarity index 98% rename from ir/lexer.wave rename to ir/src/parser/lexer.wave index e0046fa..1deda8d 100644 --- a/ir/lexer.wave +++ b/ir/src/parser/lexer.wave @@ -1,4 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; + // Bounded tokenization for the versioned Whale IR text format. The caller // owns both scratch and published buffers; errors leave published data alone. struct IrToken { @@ -45,7 +47,7 @@ fun ir_lex_mark(cp: u64) -> bool { } // Return zero for invalid UTF-8. The source has already been span checked. -fun ir_lex_utf8(source: ptr, length: u64, at: u64, width: ptr, cp: ptr) -> bool { +pub fun ir_lex_utf8(source: ptr, length: u64, at: u64, width: ptr, cp: ptr) -> bool { if (at >= length) { return false; } var first: u64 = source[at] as u64; if (first < 128) { width[0] = 1; cp[0] = first; return true; } @@ -121,7 +123,7 @@ fun ir_lex_syntax_error(result: ptr, reason: u64, at: u64, return ir_lex_error(result, 1, at, line, column); } -export(c) fun whale_ir_lex(source: ptr, length: u64, max_tokens: u64, max_work: u64, +pub export(c) fun whale_ir_lex(source: ptr, length: u64, max_tokens: u64, max_work: u64, mode: u64, // 0 preflight counts; 1 publish after exact allocation scratch_tokens: ptr, token_capacity: u64, scratch_decoded: ptr, decoded_capacity: u64, output_tokens: ptr, output_token_capacity: u64, diff --git a/ir/literal.wave b/ir/src/parser/literal.wave similarity index 96% rename from ir/literal.wave rename to ir/src/parser/literal.wave index 99bd8e9..d3b478f 100644 --- a/ir/literal.wave +++ b/ir/src/parser/literal.wave @@ -1,14 +1,16 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; + // Exact scalar text decoding. Integer arithmetic uses four 32-bit limbs so // parsing i128/u128 never depends on host overflow or compiler-runtime helpers. -struct IrLiteralResult { +pub struct IrLiteralResult { status: u64; low: u64; high: u64; work: u64; } -export(c) fun whale_ir_parse_literal(source: ptr, length: u64, +pub export(c) fun whale_ir_parse_literal(source: ptr, length: u64, category: u64, width: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 11; } result.status = 0; result.low = 0; result.high = 0; result.work = 0; diff --git a/ir/module_parser.wave b/ir/src/parser/module.wave similarity index 98% rename from ir/module_parser.wave rename to ir/src/parser/module.wave index 98e71a4..dc75ab9 100644 --- a/ir/module_parser.wave +++ b/ir/src/parser/module.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::header")::{IrTextToken}; +import("whale_wave_ir::model")::{ir_span_valid}; + // Incremental versioned module grammar. Wave owns production selection and // loop/ordering/version rules; callers construct values from typed events. struct IrModuleState { @@ -334,7 +337,7 @@ fun ir_module_step(p: ptr) -> bool { return ir_module_fail(p, 6, 0, p.state.at, 0); } -export(c) fun whale_ir_module_step(tokens: ptr, token_count: u64, +pub export(c) fun whale_ir_module_step(tokens: ptr, token_count: u64, state: ptr, max_nodes: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 6; } diff --git a/ir/type_parser.wave b/ir/src/parser/types.wave similarity index 97% rename from ir/type_parser.wave rename to ir/src/parser/types.wave index dfbd270..d55589d 100644 --- a/ir/type_parser.wave +++ b/ir/src/parser/types.wave @@ -1,13 +1,16 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::header")::{IrTextToken}; +import("whale_wave_ir::model")::{ir_span_valid}; + // Bounded recursive descent for the complete typed IR type grammar. Postorder // records preserve exact scalar identity, aggregate order and call convention. -struct IrParsedType { +pub struct IrParsedType { kind: u64; value: u64; count: u64; } -struct IrTypeParseResult { +pub struct IrTypeParseResult { status: u64; // 1 syntax, 2 depth, 3 nodes, 4 work, 5 capacity, 6 transport reason: u64; // 1 expected token, 2 decimal, 3 range, 4 word, 5 type, 6 convention at: u64; @@ -35,7 +38,7 @@ struct IrTypeParser { // Expected bytes are packed constants so independent Wave object modules do // not acquire the pinned compiler's globally named string literal symbols. -fun ir_type_word(token: ptr, code: u64) -> bool { +pub fun ir_type_word(token: ptr, code: u64) -> bool { var packed: u64 = 0; var length: u64 = 0; if (code == 0) { packed = 1684631414; length = 4; } // void @@ -215,7 +218,7 @@ fun ir_type_parse_node(parser: ptr, depth: u64) -> bool { return ir_type_emit(parser, kind, value, count); } -export(c) fun whale_ir_parse_type(tokens: ptr, token_count: u64, +pub export(c) fun whale_ir_parse_type(tokens: ptr, token_count: u64, start: u64, depth: u64, max_depth: u64, max_nodes: u64, max_work: u64, mode: u64, scratch: ptr, capacity: u64, output: ptr, output_capacity: u64, result: ptr) -> i32 { diff --git a/ir/passes.wave b/ir/src/passes/driver.wave similarity index 96% rename from ir/passes.wave rename to ir/src/passes/driver.wave index 9fc40f9..eb500b9 100644 --- a/ir/passes.wave +++ b/ir/src/passes/driver.wave @@ -1,4 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; + // Verified transactional pass control. Actions call other IR components or the // caller's existing Pass trait; no host callback is invoked from Wave. struct IrPassState { @@ -93,7 +95,7 @@ fun ir_pass_equal(state: ptr, before: ptr, before_count: u64, // 5 after packet, 7 epoch commit, 8 rollback, 9 success, 10 failure. // Failure stages match Before/Transform/After/Contract (0..3). // Detail 0 preserves the adapter's error; 1 report, 2 epoch, 3 work. -export(c) fun whale_ir_pass_step(state: ptr, reply: ptr, +pub export(c) fun whale_ir_pass_step(state: ptr, reply: ptr, before: ptr, before_count: u64, after: ptr, after_count: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { @@ -195,7 +197,7 @@ export(c) fun whale_ir_pass_step(state: ptr, reply: ptr i32 { if (kind > 2) { return 2; diff --git a/ir/fold_integer.wave b/ir/src/passes/integer.wave similarity index 97% rename from ir/fold_integer.wave rename to ir/src/passes/integer.wave index dac6288..9432341 100644 --- a/ir/fold_integer.wave +++ b/ir/src/passes/integer.wave @@ -1,4 +1,12 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::numeric::integer")::{ + IrIntegerResult, + ir_integer_signed, + ir_integer_width, + whale_ir_integer, +}; +import("whale_wave_ir::model")::{ir_span_valid}; + // Sparse, function-scoped constant propagation. Each value becomes known once; // only its indexed users are revisited. No memory, call or trapping fold exists. struct IrFoldNode { @@ -247,7 +255,7 @@ fun ir_fold_compute(p: ptr, index: u64, result: ptr) return true; } -export(c) fun whale_ir_fold_integer(p: ptr, result: ptr) -> i32 { +pub export(c) fun whale_ir_fold_integer(p: ptr, result: ptr) -> i32 { if (result == null) { return 2; } diff --git a/ir/printer.wave b/ir/src/printer.wave similarity index 99% rename from ir/printer.wave rename to ir/src/printer.wave index 79907ad..65a68a2 100644 --- a/ir/printer.wave +++ b/ir/src/printer.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::parser::lexer")::{ir_lex_utf8}; +import("whale_wave_ir::model")::{ir_span_valid}; + // Canonical IR grammar and byte escaping live here. Rust supplies a flat, // borrowed model and drains bounded chunks; it does not choose print syntax. // The caller owns the resumable task stack. No global strings or allocation. @@ -2013,7 +2016,7 @@ fun irp_string(s: ptr, data: ptr, length: u64, // Status: 0 complete, 1 malformed transport, 2 output limit, 3 stack, // 4 work, 5 depth, 6 chunk ready. Each call advances the same state and // publishes at most capacity bytes; all status/error paths respect the ceiling. -export(c) fun whale_ir_print_step(s: ptr, root: u64, +pub export(c) fun whale_ir_print_step(s: ptr, root: u64, output: ptr, capacity: u64, written: ptr) -> i32 { if (s == null || written == null) { return 1; } written[0] = 0; diff --git a/ir/source.wave b/ir/src/source.wave similarity index 89% rename from ir/source.wave rename to ir/src/source.wave index 338fbab..4576a44 100644 --- a/ir/source.wave +++ b/ir/src/source.wave @@ -1,33 +1,36 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::verifier::cfg")::{ir_cfg_charge}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; + // Source identities and mapping validation. Caller storage, Wave decisions. -struct IrSourceFile { id: u64; bytes: ptr; length: u64; } +pub struct IrSourceFile { id: u64; bytes: ptr; length: u64; } -struct IrSourceOriginal { +pub struct IrSourceOriginal { id: u64; has_span: u64; file: u64; line: u64; column: u64; end_line: u64; end_column: u64; } -struct IrSourceBlock { function: u64; block: u64; instructions: u64; terminated: u64; } +pub struct IrSourceBlock { function: u64; block: u64; instructions: u64; terminated: u64; } -struct IrSourceMapping { kind: u64; function: u64; block: u64; index: u64; original: u64; } +pub struct IrSourceMapping { kind: u64; function: u64; block: u64; index: u64; original: u64; } -struct IrSourceSlot { kind: u64; a: u64; b: u64; c: u64; value: u64; extra: u64; } +pub struct IrSourceSlot { kind: u64; a: u64; b: u64; c: u64; value: u64; extra: u64; } -struct IrSourceResult { status: u64; index: u64; work: u64; } +pub struct IrSourceResult { status: u64; index: u64; work: u64; } fun ir_source_fail(result: ptr, status: u64, index: u64, work: u64) -> i32 { result.status = status; result.index = index; result.work = work; return status as i32; } // Return the matching slot or an empty slot. Probes always consume budget. -fun ir_source_mix(value: u64) -> u64 { +pub fun ir_source_mix(value: u64) -> u64 { var x: u64 = value; x = (x ^ (x >> 30)) * 13787848793156543929; x = (x ^ (x >> 27)) * 10723151780598845931; return x ^ (x >> 31); } -fun ir_source_slot(table: ptr, capacity: u64, kind: u64, +pub fun ir_source_slot(table: ptr, capacity: u64, kind: u64, a: u64, b: u64, c: u64, work: ptr, limit: u64) -> u64 { var hash: u64 = ir_source_mix(a ^ (kind * 16777619)); hash = ir_source_mix(hash ^ b); @@ -41,12 +44,12 @@ fun ir_source_slot(table: ptr, capacity: u64, kind: u64, return capacity; } -fun ir_source_put(table: ptr, at: u64, kind: u64, a: u64, b: u64, c: u64, value: u64, extra: u64) { +pub fun ir_source_put(table: ptr, at: u64, kind: u64, a: u64, b: u64, c: u64, value: u64, extra: u64) { table[at].kind = kind; table[at].a = a; table[at].b = b; table[at].c = c; table[at].value = value; table[at].extra = extra; } -export(c) fun whale_ir_verify_sources(files: ptr, file_count: u64, +pub export(c) fun whale_ir_verify_sources(files: ptr, file_count: u64, originals: ptr, original_count: u64, blocks: ptr, block_count: u64, globals: ptr, global_count: u64, diff --git a/ir/cfg.wave b/ir/src/verifier/cfg.wave similarity index 96% rename from ir/cfg.wave rename to ir/src/verifier/cfg.wave index 5cd0755..c7cb70d 100644 --- a/ir/cfg.wave +++ b/ir/src/verifier/cfg.wave @@ -1,19 +1,21 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_span_valid}; + // Structural CFG traversal for the IR verifier. Input is a caller-owned flat // successor graph; the published reverse postorder is unchanged on failure. -struct IrCfgBlock { +pub struct IrCfgBlock { first: u64; count: u64; } -struct IrCfgResult { +pub struct IrCfgResult { status: u64; // 1 entry predecessor, 2 capacity, 3 work, 5 invalid graph index: u64; // predecessor block for status 1 count: u64; work: u64; } -fun ir_cfg_charge(work: ptr, limit: u64) -> bool { +pub fun ir_cfg_charge(work: ptr, limit: u64) -> bool { if (work[0] >= limit) { return false; } work[0] += 1; return true; @@ -24,7 +26,7 @@ fun ir_cfg_error(result: ptr, status: u64, index: u64, work: u64) - return status as i32; } -export(c) fun whale_ir_cfg_rpo(blocks: ptr, block_count: u64, +pub export(c) fun whale_ir_cfg_rpo(blocks: ptr, block_count: u64, edges: ptr, edge_count: u64, entry: u64, max_work: u64, scratch_seen: ptr, seen_capacity: u64, scratch_stack_block: ptr, scratch_stack_next: ptr, stack_capacity: u64, @@ -106,7 +108,7 @@ export(c) fun whale_ir_cfg_rpo(blocks: ptr, block_count: u64, // Cooper-style iterative immediate dominators over reverse postorder. The // unvisited sentinel is kept in the caller-owned result for unreachable // blocks, which remain present for later identity/type checks. -export(c) fun whale_ir_cfg_idom(blocks: ptr, block_count: u64, +pub export(c) fun whale_ir_cfg_idom(blocks: ptr, block_count: u64, predecessors: ptr, predecessor_count: u64, order: ptr, order_count: u64, entry: u64, max_work: u64, scratch_rank: ptr, rank_capacity: u64, diff --git a/ir/verifier_index.wave b/ir/src/verifier/index.wave similarity index 90% rename from ir/verifier_index.wave rename to ir/src/verifier/index.wave index a3e0f94..2695d6e 100644 --- a/ir/verifier_index.wave +++ b/ir/src/verifier/index.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; +import("whale_wave_ir::verifier::module")::{IrVerifyResult, ir_verify_charge, ir_verify_error}; + // Incremental, bounded, caller-owned declaration identity index. Names are // borrowed from immutable module storage for the lifetime of verification. struct IrVerifyKey { kind: u64; number: u64; bytes: ptr; count: u64; } @@ -56,12 +59,12 @@ fun ir_verify_index(table: ptr, capacity: u64, return ir_verify_error(result, 8, 0, 0, 0, 0); } -export(c) fun whale_ir_verify_index_insert(table: ptr, capacity: u64, +pub export(c) fun whale_ir_verify_index_insert(table: ptr, capacity: u64, key: ptr, max_work: u64, result: ptr) -> i32 { return ir_verify_index(table, capacity, key, true, max_work, result); } -export(c) fun whale_ir_verify_index_contains(table: ptr, capacity: u64, +pub export(c) fun whale_ir_verify_index_contains(table: ptr, capacity: u64, key: ptr, max_work: u64, result: ptr) -> i32 { return ir_verify_index(table, capacity, key, false, max_work, result); } diff --git a/ir/verify.wave b/ir/src/verifier/module.wave similarity index 94% rename from ir/verify.wave rename to ir/src/verifier/module.wave index 9753864..de3d2f7 100644 --- a/ir/verify.wave +++ b/ir/src/verifier/module.wave @@ -1,25 +1,27 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; + // Semantic verification consumes a borrowed type graph and operand records. // No host callbacks participate in type/category, cast, memory or GEP rules. -struct IrVerifyType { kind: u64; child: u64; first: u64; count: u64; extra: u64; } +pub struct IrVerifyType { kind: u64; child: u64; first: u64; count: u64; extra: u64; } -struct IrVerifyOperand { value: u64; ty: u64; literal: u64; low: u64; high: u64; } +pub struct IrVerifyOperand { value: u64; ty: u64; literal: u64; low: u64; high: u64; } -struct IrVerifyInstruction { op: u64; sub: u64; ty: u64; other: u64; dst: u64; align: u64; } +pub struct IrVerifyInstruction { op: u64; sub: u64; ty: u64; other: u64; dst: u64; align: u64; } -struct IrVerifyResult { status: u64; index: u64; expected: u64; actual: u64; detail: u64; work: u64; } +pub struct IrVerifyResult { status: u64; index: u64; expected: u64; actual: u64; detail: u64; work: u64; } struct IrVerifyBinding { id: u64; ty: u64; index: u64; present: u64; } -fun ir_verify_signed(kind: u64) -> bool { return kind == 2 || (kind >= 4 && kind <= 8); } +pub fun ir_verify_signed(kind: u64) -> bool { return kind == 2 || (kind >= 4 && kind <= 8); } -fun ir_verify_unsigned(kind: u64) -> bool { return kind == 3 || (kind >= 9 && kind <= 13); } +pub fun ir_verify_unsigned(kind: u64) -> bool { return kind == 3 || (kind >= 9 && kind <= 13); } -fun ir_verify_integer(kind: u64) -> bool { return ir_verify_signed(kind) || ir_verify_unsigned(kind); } +pub fun ir_verify_integer(kind: u64) -> bool { return ir_verify_signed(kind) || ir_verify_unsigned(kind); } -fun ir_verify_float(kind: u64) -> bool { return kind >= 14 && kind <= 16; } +pub fun ir_verify_float(kind: u64) -> bool { return kind >= 14 && kind <= 16; } -fun ir_verify_width(kind: u64) -> u64 { +pub fun ir_verify_width(kind: u64) -> u64 { if (kind == 2 || kind == 3) { return 1; } if (kind == 4 || kind == 9) { return 8; } if (kind == 5 || kind == 10 || kind == 14) { return 16; } @@ -29,7 +31,7 @@ fun ir_verify_width(kind: u64) -> u64 { return 0; } -fun ir_verify_literal(kind: u64, literal: u64, low: u64, high: u64) -> bool { +pub fun ir_verify_literal(kind: u64, literal: u64, low: u64, high: u64) -> bool { var valid: bool = (kind == 1 && literal == 3) || (kind == 14 && literal == 4) || (kind == 15 && literal == 5) || (kind == 16 && literal == 6); var width: u64 = ir_verify_width(kind); var one: u64 = 1; @@ -47,18 +49,18 @@ fun ir_verify_literal(kind: u64, literal: u64, low: u64, high: u64) -> bool { return valid; } -fun ir_verify_error(result: ptr, status: u64, index: u64, +pub fun ir_verify_error(result: ptr, status: u64, index: u64, expected: u64, actual: u64, detail: u64) -> i32 { result.status = status; result.index = index; result.expected = expected; result.actual = actual; result.detail = detail; return status as i32; } -fun ir_verify_charge(result: ptr, limit: u64) -> bool { +pub fun ir_verify_charge(result: ptr, limit: u64) -> bool { if (result.work >= limit) { result.status = 8; return false; } result.work += 1; return true; } -fun ir_verify_equal(a: u64, b: u64, types: ptr, edges: ptr, +pub fun ir_verify_equal(a: u64, b: u64, types: ptr, edges: ptr, depth: u64, result: ptr, limit: u64) -> bool { if (!ir_verify_charge(result, limit)) { return false; } if (a == b) { return true; } @@ -82,7 +84,7 @@ fun ir_verify_equal(a: u64, b: u64, types: ptr, edges: ptr, return true; } -fun ir_verify_storable(ty: u64, types: ptr, edges: ptr, +pub fun ir_verify_storable(ty: u64, types: ptr, edges: ptr, depth: u64, result: ptr, limit: u64) -> bool { if (!ir_verify_charge(result, limit)) { return false; } if (depth == 0) { result.status = 8; return false; } @@ -101,7 +103,7 @@ fun ir_verify_storable(ty: u64, types: ptr, edges: ptr, return true; } -fun ir_verify_cast(op: u64, source: u64, destination: u64) -> bool { +pub fun ir_verify_cast(op: u64, source: u64, destination: u64) -> bool { var si: bool = ir_verify_integer(source); var di: bool = ir_verify_integer(destination); var sf: bool = ir_verify_float(source); var df: bool = ir_verify_float(destination); var sw: u64 = ir_verify_width(source); var dw: u64 = ir_verify_width(destination); @@ -142,7 +144,7 @@ fun ir_verify_operand_at(index: u64, expected: u64, pointer: bool, return true; } -fun ir_verify_graph_valid(types: ptr, type_count: u64, +pub fun ir_verify_graph_valid(types: ptr, type_count: u64, edges: ptr, edge_count: u64, max_work: u64, result: ptr) -> bool { if (!ir_span_valid(types as ptr, type_count, 40) || !ir_span_valid(edges as ptr, edge_count, 8)) { @@ -193,7 +195,7 @@ fun ir_verify_signature_type(ty: u64, types: ptr, edges: ptr, return true; } -fun ir_verify_signature(ty: u64, types: ptr, edges: ptr, +pub fun ir_verify_signature(ty: u64, types: ptr, edges: ptr, depth: u64, result: ptr, limit: u64) -> bool { if (!ir_verify_charge(result, limit)) { return false; } if (depth == 0) { result.status = 8; return false; } @@ -267,7 +269,7 @@ fun ir_verify_contains_fnptr(ty: u64, types: ptr, edges: ptr, // 18 store, 19 GEP, 20 memcpy, 21 memset, 22 condition, 23 equality, // 24 literal. Error statuses: category, missing type, mismatch, alignment, // cast, GEP, malformed transport, resource budget, invalid literal. -export(c) fun whale_ir_verify_semantics(types: ptr, type_count: u64, +pub export(c) fun whale_ir_verify_semantics(types: ptr, type_count: u64, edges: ptr, edge_count: u64, instruction: ptr, operands: ptr, operand_count: u64, max_work: u64, result: ptr) -> i32 { @@ -523,7 +525,7 @@ export(c) fun whale_ir_verify_semantics(types: ptr, type_count: u6 return 0; } -export(c) fun whale_ir_verify_link(external: u64, present: u64, bytes: ptr, count: u64, +pub export(c) fun whale_ir_verify_link(external: u64, present: u64, bytes: ptr, count: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 7; } result.status = 0; result.index = 0; result.expected = 0; @@ -542,7 +544,7 @@ export(c) fun whale_ir_verify_link(external: u64, present: u64, bytes: ptr, return 0; } -export(c) fun whale_ir_verify_value_types(types: ptr, type_count: u64, +pub export(c) fun whale_ir_verify_value_types(types: ptr, type_count: u64, edges: ptr, edge_count: u64, annotations: ptr, annotation_count: u64, definitions: ptr, definition_count: u64, table: ptr, capacity: u64, max_work: u64, diff --git a/ir/shape.wave b/ir/src/verifier/shape.wave similarity index 95% rename from ir/shape.wave rename to ir/src/verifier/shape.wave index 0910778..7987619 100644 --- a/ir/shape.wave +++ b/ir/src/verifier/shape.wave @@ -1,4 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::verifier::cfg")::{ir_cfg_charge}; +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; + // Bounded identity and branch-shape validation before SSA/type analysis. struct IrShapeBlock { id: u64; @@ -49,7 +52,7 @@ fun ir_shape_contains(table: ptr, capacity: u64, id: u64, } } -export(c) fun whale_ir_shape_contains(table: ptr, capacity: u64, id: u64, +pub export(c) fun whale_ir_shape_contains(table: ptr, capacity: u64, id: u64, max_work: u64, result: ptr) -> i32 { if (result == null) { return 6; } result.status = 0; result.index = 0; result.detail = 0; result.work = 0; @@ -70,7 +73,7 @@ fun ir_shape_error(result: ptr, status: u64, index: u64, return status as i32; } -export(c) fun whale_ir_verify_shape(blocks: ptr, block_count: u64, +pub export(c) fun whale_ir_verify_shape(blocks: ptr, block_count: u64, entry: u64, values: ptr, value_count: u64, edges: ptr, edge_count: u64, max_work: u64, block_table: ptr, block_table_capacity: u64, diff --git a/ir/verifier_ssa.wave b/ir/src/verifier/ssa.wave similarity index 93% rename from ir/verifier_ssa.wave rename to ir/src/verifier/ssa.wave index f87ece0..2e368d5 100644 --- a/ir/verifier_ssa.wave +++ b/ir/src/verifier/ssa.wave @@ -1,17 +1,27 @@ // SPDX-License-Identifier: MPL-2.0 +import("whale_wave_ir::model")::{ir_power_two, ir_span_valid}; +import("whale_wave_ir::verifier::module")::{ + IrVerifyResult, + IrVerifyType, + ir_verify_charge, + ir_verify_equal, + ir_verify_graph_valid, + ir_verify_storable, +}; + // SSA and phi validation over caller-owned CFG/dominator intervals. -struct IrSsaBlock { +pub struct IrSsaBlock { id: u64; first: u64; count: u64; pred_first: u64; pred_count: u64; reachable: u64; start: u64; end: u64; terminator_use: u64; } -struct IrSsaInstruction { phi: u64; dst: u64; ty: u64; first: u64; count: u64; } +pub struct IrSsaInstruction { phi: u64; dst: u64; ty: u64; first: u64; count: u64; } -struct IrSsaUse { value: u64; ty: u64; pred: u64; def_block: u64; def_position: u64; defined: u64; } +pub struct IrSsaUse { value: u64; ty: u64; pred: u64; def_block: u64; def_position: u64; defined: u64; } -struct IrSsaPredecessor { block: u64; seen: u64; } +pub struct IrSsaPredecessor { block: u64; seen: u64; } -struct IrSsaResult { status: u64; instruction: u64; usage: u64; detail: u64; work: u64; queries: u64; } +pub struct IrSsaResult { status: u64; instruction: u64; usage: u64; detail: u64; work: u64; queries: u64; } fun ir_ssa_error(result: ptr, status: u64, instruction: u64, usage: u64, detail: u64, semantic: ptr) -> i32 { @@ -38,7 +48,7 @@ fun ir_ssa_available(usage: ptr, block: u64, position: u64, // Status: 1 invalid phi, 2 undefined value, 3 non-dominating use, // 4 invalid phi type category, 5 phi operand type, 7 transport, 8 work. -export(c) fun whale_ir_verify_ssa(types: ptr, type_count: u64, +pub export(c) fun whale_ir_verify_ssa(types: ptr, type_count: u64, edges: ptr, edge_count: u64, blocks: ptr, block_count: u64, entry: u64, instructions: ptr, instruction_count: u64, uses: ptr, use_count: u64, predecessors: ptr, predecessor_count: u64, diff --git a/ir/vex.ws b/ir/vex.ws new file mode 100644 index 0000000..35be3cb --- /dev/null +++ b/ir/vex.ws @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + name = "whale_wave_ir", + version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ] +} diff --git a/meson.build b/meson.build index cbded86..57eb8e6 100644 --- a/meson.build +++ b/meson.build @@ -1,9 +1,8 @@ # SPDX-License-Identifier: MPL-2.0 -project('Whale', version: '0.1.0', meson_version: '>=1.8.0', +project('Whale', version: '0.1.0', meson_version: '>=1.8.5', default_options: ['buildtype=debug']) -# Cargo compiles the current Rust components. Meson owns product selection, -# dependency scheduling, the resulting executable, tests and installation. +# Meson automates the product. Vex owns Wave packages; Cargo owns Rust bindings. python = import('python').find_installation('python3') cargo = find_program('cargo', native: true) rustc = find_program('rustc', native: true) @@ -17,67 +16,60 @@ foreach arch : ['amd64', 'aarch64', 'riscv64', 'loongarch64'] assembler_outputs += [arch] endif endforeach -if get_option('socket-cli') - selected_features += ['socket-cli'] -endif -if get_option('native-linker') - selected_features += ['native-linker'] -endif -if get_option('rust-reference') - selected_features += ['rust-reference'] -endif - +foreach feature : ['socket-cli', 'native-linker', 'rust-reference'] + if get_option(feature) + selected_features += [feature] + endif +endforeach cargo_host_target = get_option('cargo-host-target') if meson.is_cross_build() and cargo_host_target == '' - error('Cross builds require -Dcargo-host-target=RUST_TRIPLE for the Whale executable host. Assembler output selections do not choose its host.') -endif - -# asmobj is one complete Wave source module. Cargo only links it through the -# data transport in toolchain; there is no Rust implementation or fallback. -wave_source = get_option('wave-source') -if not get_option('rust-reference') and wave_source == '' - required_modules = ['asmobj-dir', 'wave-ir-dir', 'wave-assembler-dir'] - foreach arch : assembler_outputs - required_modules += ['wave-' + arch + '-dir'] - endforeach - foreach module : required_modules - if get_option(module) == '' - error('The default Wave product requires -Dwave-source=/absolute/Wave or every selected prebuilt module; missing -D' + module + '. Rust reference builds require explicit -Drust-reference=true.') - endif - endforeach + error('Cross builds require -Dcargo-host-target=RUST_TRIPLE for the Whale executable host.') endif -wave_cache = get_option('wave-bootstrap-dir') -if wave_cache == '' - wave_cache = meson.project_build_root() / 'wave-bootstrap' -elif not fs.is_absolute(wave_cache) - error('-Dwave-bootstrap-dir must be absolute.') +module_target = cargo_host_target +if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc', 'freebsd': 'unknown-freebsd'} + if not target_os.has_key(host_machine.system()) + error('Set cargo-host-target for this executable host.') + endif + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + if host_machine.cpu_family() == 'riscv64' + module_target = 'riscv64gc-' + target_os[host_machine.system()] + endif endif -asmobj_directory = get_option('asmobj-dir') -wave_bootstrap = [] -needs_wave_bootstrap = asmobj_directory == '' -if wave_source != '' - needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-ir-dir') == '' or get_option('wave-assembler-dir') == '' - foreach arch : ['amd64', 'aarch64', 'riscv64', 'loongarch64'] - if get_option('asm-' + arch) - needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-' + arch + '-dir') == '' - endif +wave_profile = get_option('buildtype') in ['release', 'minsize', 'debugoptimized'] ? 'release' : 'dev' +needs_vex = get_option('asmobj-dir') == '' +if not get_option('rust-reference') + foreach option : ['wave-ir-dir', 'wave-assembler-dir'] + needs_vex = needs_vex or get_option(option) == '' + endforeach + foreach arch : assembler_outputs + needs_vex = needs_vex or get_option('wave-' + arch + '-dir') == '' endforeach endif -if needs_wave_bootstrap - if wave_source == '' or not fs.is_absolute(wave_source) or not fs.is_dir(wave_source) - error('Supply -Dwave-source=/absolute/Wave or -Dasmobj-dir=/absolute/built/module.') - endif - if build_machine.system() != 'linux' or build_machine.cpu_family() != 'x86_64' - error('Building the pinned Wave compiler currently requires a Linux x86_64 build machine; use a prebuilt asmobj module on other build machines.') +wave_prepared = [] +if needs_vex + vex = find_program(get_option('vex'), native: true) + wave_cache = get_option('wave-cache-dir') + if wave_cache == '' + wave_cache = meson.project_build_root() / 'wave-nightly' + elif not fs.is_absolute(wave_cache) + error('-Dwave-cache-dir must be absolute.') endif - bootstrap_arguments = ['bootstrap', '--wave-source', wave_source, '--cache-dir', wave_cache, - '--rust-toolchain', get_option('wave-rust-toolchain'), '--output', '@OUTPUT@'] - if get_option('wave-allow-network') - bootstrap_arguments += ['--allow-network'] + toolchain_arguments = ['--cache-dir', wave_cache, '--output', '@OUTPUT@'] + if get_option('wave-offline') + toolchain_arguments += ['--offline'] endif - wave_bootstrap = custom_target('wave-bootstrap', output: 'wave-bootstrap-ready.json', - command: [python, bridge, bootstrap_arguments], - depend_files: files('tools/wave_bootstrap.py', 'tools/meson_cargo.py'), console: true) + wave_toolchain = custom_target('wave-toolchain', output: 'wave-toolchain.json', + command: [python, files('tools/wave_nightly.py'), toolchain_arguments], + depend_files: files('tools/wave_nightly.py'), + build_always_stale: true, console: true) + wave_state = meson.project_build_root() / 'vex-state' + wave_prepared = custom_target('wave-prepared', output: 'wave-ready.json', + command: [python, files('tools/vex_module.py'), '--prepare', '--vex', vex, + '--toolchain', wave_toolchain, '--build-dir', meson.project_build_root() / 'vex/prepare', + '--state-dir', wave_state, '--ready', '@OUTPUT@'], + depend_files: files('vex.ws', 'vex.lock', 'tools/wave_modules.py', 'tools/vex_module.py'), + build_always_stale: true, console: true) endif subdir('assembler') subdir('ir') diff --git a/meson.options b/meson.options index d5ae65d..3974a90 100644 --- a/meson.options +++ b/meson.options @@ -16,7 +16,7 @@ option('rust-reference', type: 'boolean', value: false, option('asmobj-dir', type: 'string', value: '', description: 'Absolute directory of the complete prebuilt Wave asmobj module for the executable host') option('wave-ir-dir', type: 'string', value: '', - description: 'Absolute directory of a prebuilt internal Wave IR module; source builds use the pinned compiler') + description: 'Absolute directory of a prebuilt internal Wave IR module; source builds use the selected nightly') option('wave-assembler-dir', type: 'string', value: '', description: 'Absolute directory of the shared Wave assembler archive for the executable host') option('wave-amd64-dir', type: 'string', value: '', @@ -27,14 +27,12 @@ option('wave-riscv64-dir', type: 'string', value: '', description: 'Absolute directory of the Wave riscv64 module for the executable host') option('wave-loongarch64-dir', type: 'string', value: '', description: 'Absolute directory of the Wave loongarch64 module for the executable host') -option('wave-source', type: 'string', value: '', - description: 'Read-only Wave Git checkout containing the pinned bootstrap revision') -option('wave-bootstrap-dir', type: 'string', value: '', - description: 'Optional absolute compiler/std cache directory; default is private to this build') -option('wave-rust-toolchain', type: 'string', value: '1.89.0', - description: 'Installed Rust toolchain alias reporting the pinned Rust 1.89.0 compiler') -option('wave-allow-network', type: 'boolean', value: false, - description: 'Explicitly allow locked dependency downloads for the Wave bootstrap build') +option('vex', type: 'string', value: 'vex', + description: 'Build-machine Vex executable (v0.0.3-beta or newer)') +option('wave-cache-dir', type: 'string', value: '', + description: 'Absolute verified nightly cache; default is private to this build directory') +option('wave-offline', type: 'boolean', value: false, + description: 'Reuse the verified cached nightly without network access') option('cargo-host-target', type: 'string', value: '', description: 'Rust target triple for the Whale executable host; required for cross builds') option('cargo-offline', type: 'boolean', value: true, diff --git a/object/tests/elf_budgets.rs b/object/tests/elf_budgets.rs index b71071b..8cbb571 100644 --- a/object/tests/elf_budgets.rs +++ b/object/tests/elf_budgets.rs @@ -76,6 +76,7 @@ fn huge_name_budget_child() { #[test] fn huge_names_reject_before_copying_in_a_capped_child_process() { let output = std::process::Command::new("sh") + .env_clear() .arg("-c") .arg("ulimit -c 0; ulimit -v 51200; exec \"$@\"") .arg("elf-test") diff --git a/tests/cli_arguments.rs b/tests/cli_arguments.rs index c7d9838..fb93702 100644 --- a/tests/cli_arguments.rs +++ b/tests/cli_arguments.rs @@ -69,10 +69,15 @@ fn repeated_or_conflicting_architecture_options_fail_before_reading_input() { fn ir_output_flags_reject_option_shaped_paths_before_publication() { let directory = tempfile::tempdir().unwrap(); let input = directory.path().join("input.wir"); - fs::write(&input, include_str!("../ir/tests/fixtures/wave-control-v3.wir")).unwrap(); + fs::write(&input, include_str!("../bindings/rust/ir/tests/fixtures/wave-control-v3.wir")) + .unwrap(); let lower_input = directory.path().join("input.json"); if cfg!(feature = "socket-cli") { - fs::write(&lower_input, include_str!("../ir/tests/fixtures/ast-v2-u128.json")).unwrap(); + fs::write( + &lower_input, + include_str!("../bindings/rust/ir/tests/fixtures/ast-v2-u128.json"), + ) + .unwrap(); } let output = directory.path().join("output with spaces.wir"); let mut modes = vec![("print", &input)]; diff --git a/tests/float_comparisons_cli.rs b/tests/float_comparisons_cli.rs index d0f9911..a39596f 100644 --- a/tests/float_comparisons_cli.rs +++ b/tests/float_comparisons_cli.rs @@ -3,7 +3,7 @@ use std::{path::PathBuf, process::Command}; #[test] fn documented_float_comparisons_report_boolean_results() { let input = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("ir/tests/fixtures/float-comparisons-v7.wir"); + .join("bindings/rust/ir/tests/fixtures/float-comparisons-v7.wir"); for (function, a, b, expected) in [ ("@f0", "0x7ff0000000000001", "0x3ff0000000000000", "bool true\n"), ("@f0", "0x3ff0000000000000", "0xfff8123456789abc", "bool true\n"), diff --git a/tests/float_storage_cli.rs b/tests/float_storage_cli.rs index a18f87f..89d5038 100644 --- a/tests/float_storage_cli.rs +++ b/tests/float_storage_cli.rs @@ -1,8 +1,8 @@ use std::{path::PathBuf, process::Command}; fn run(function: &str, literal: Option<&str>) -> std::process::Output { - let input = - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ir/tests/fixtures/float-storage-v7.wir"); + let input = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("bindings/rust/ir/tests/fixtures/float-storage-v7.wir"); let mut command = Command::new(env!("CARGO_BIN_EXE_whale")); command.args(["ir", "run"]).arg(input).args(["--function", function]); if let Some(value) = literal { diff --git a/tests/interchange_cli.rs b/tests/interchange_cli.rs index 9275313..9fff8ea 100644 --- a/tests/interchange_cli.rs +++ b/tests/interchange_cli.rs @@ -23,8 +23,8 @@ fn disabled_feature_reports_recovery_without_output() { #[test] #[cfg(feature = "socket-cli")] fn schema_and_lowering_errors_preserve_existing_output_even_without_verify() { - let valid = include_str!("../ir/tests/fixtures/ast-v2-u128.json"); - let calls = include_str!("../ir/tests/fixtures/ast-v2-calls.json"); + let valid = include_str!("../bindings/rust/ir/tests/fixtures/ast-v2-u128.json"); + let calls = include_str!("../bindings/rust/ir/tests/fixtures/ast-v2-calls.json"); let cases = [ (calls.replace("\"Direct\": \"emit\"", "\"Direct\": \"missing\""), "UnknownFunctionName"), ( diff --git a/tests/runtime_diagnostics_cli.rs b/tests/runtime_diagnostics_cli.rs index f9fa291..fde869f 100644 --- a/tests/runtime_diagnostics_cli.rs +++ b/tests/runtime_diagnostics_cli.rs @@ -3,7 +3,7 @@ use std::{path::PathBuf, process::Command}; #[test] fn cli_reports_original_source_and_both_direct_and_indirect_callers_without_reading_source_files() { let input = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("ir/tests/fixtures/runtime-diagnostics-v7.wir"); + .join("bindings/rust/ir/tests/fixtures/runtime-diagnostics-v7.wir"); let output = Command::new(env!("CARGO_BIN_EXE_whale")) .args(["ir", "run"]) .arg(input) diff --git a/tests/runtime_storage_cli.rs b/tests/runtime_storage_cli.rs index 5db8c64..391102f 100644 --- a/tests/runtime_storage_cli.rs +++ b/tests/runtime_storage_cli.rs @@ -2,8 +2,8 @@ use std::{path::PathBuf, process::Command}; #[test] fn documented_storage_fixture_executes_and_reports_runtime_faults_through_the_cli() { - let input = - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ir/tests/fixtures/runtime-storage-v6.wir"); + let input = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("bindings/rust/ir/tests/fixtures/runtime-storage-v6.wir"); for (function, expected) in [("@f1", "u32 12\n"), ("@f3", "u32 42\n"), ("@f7", "i128 16\n")] { let output = Command::new(env!("CARGO_BIN_EXE_whale")) .args(["ir", "run"]) diff --git a/tests/text_ir_cli.rs b/tests/text_ir_cli.rs index 134feef..a14c664 100644 --- a/tests/text_ir_cli.rs +++ b/tests/text_ir_cli.rs @@ -8,7 +8,8 @@ fn run(args: &[&str]) -> std::process::Output { fn run_tracked_memory_reports_initialization_and_validates_byte_budgets() { let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("tracked memory.wir"); - fs::write(&path, include_str!("../ir/tests/fixtures/tracked-memory-v4.wir")).unwrap(); + fs::write(&path, include_str!("../bindings/rust/ir/tests/fixtures/tracked-memory-v4.wir")) + .unwrap(); let input = path.to_str().unwrap(); let r = run(&["ir", "run", input, "--function", "@f0", "--max-memory", "20"]); assert!(r.status.success(), "{r:?}"); @@ -40,7 +41,7 @@ fn typed_ir_commands_work_without_socket_and_publish_only_verified_output() { let output = tmp.path().join("output.wir"); let input = input.to_str().unwrap(); let output = output.to_str().unwrap(); - let good = include_str!("../ir/tests/fixtures/wave-control-v3.wir"); + let good = include_str!("../bindings/rust/ir/tests/fixtures/wave-control-v3.wir"); fs::write(input, good).unwrap(); let result = run(&["ir", "verify", input]); assert!(result.status.success(), "{result:?}"); @@ -88,7 +89,7 @@ fn hardlink_output_cannot_overwrite_ir_input() { let tmp = tempfile::tempdir().unwrap(); let input = tmp.path().join("input.wir"); let alias = tmp.path().join("alias.wir"); - let good = include_str!("../ir/tests/fixtures/calls-v3.wir"); + let good = include_str!("../bindings/rust/ir/tests/fixtures/calls-v3.wir"); fs::write(&input, good).unwrap(); fs::hard_link(&input, &alias).unwrap(); assert!(!run(&["ir", "print", input.to_str().unwrap(), "-o", alias.to_str().unwrap()]) @@ -102,7 +103,7 @@ fn canonical_printing_obeys_exact_byte_limits_and_preserves_existing_files() { let tmp = tempfile::tempdir().unwrap(); let input = tmp.path().join("input.wir"); let output = tmp.path().join("output.wir"); - let source = include_str!("../ir/tests/fixtures/wave-control-v3.wir"); + let source = include_str!("../bindings/rust/ir/tests/fixtures/wave-control-v3.wir"); fs::write(&input, source).unwrap(); let input_name = input.to_str().unwrap(); let output_name = output.to_str().unwrap(); @@ -146,7 +147,7 @@ fn run_executes_exact_arguments_and_reports_traps_fuel_and_unsupported_operation let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("loop input.wir"); let input = path.to_str().unwrap(); - let source = include_str!("../ir/tests/fixtures/interpreter-loop-v3.wir"); + let source = include_str!("../bindings/rust/ir/tests/fixtures/interpreter-loop-v3.wir"); fs::write(input, source).unwrap(); let result = run(&["ir", "run", input, "--function", "@f7", "--arg", "3"]); assert!(result.status.success(), "{result:?}"); @@ -199,7 +200,7 @@ fn run_executes_exact_arguments_and_reports_traps_fuel_and_unsupported_operation "{error}" ); assert!(error.contains(input)); - fs::write(input, include_str!("../ir/tests/fixtures/wave-casts-v3.wir")).unwrap(); + fs::write(input, include_str!("../bindings/rust/ir/tests/fixtures/wave-casts-v3.wir")).unwrap(); let converted = run(&["ir", "run", input, "--function", "@f0"]); assert!(converted.status.success(), "{converted:?}"); fs::write(input, "module { format_version 3 semantics_version 1 target \"x86_64-whale-linux\" datalayout {ptr=64,endian=little} declare @f0 \"aggregate\": whale () -> void, linkage internal fn @f0 \"aggregate\"() -> void, entry %b0 { %b0 \"entry\": %v0: ptr> = alloca array, align 1 %v1: array = load array, ptr> %v0, align 1 ret void } }").unwrap(); @@ -216,7 +217,7 @@ fn ast_lowering_streams_with_the_same_exact_publication_ceiling() { let tmp = tempfile::tempdir().unwrap(); let input = tmp.path().join("input.json"); let output = tmp.path().join("output.wir"); - let source = include_str!("../ir/tests/fixtures/ast-v2-u128.json"); + let source = include_str!("../bindings/rust/ir/tests/fixtures/ast-v2-u128.json"); fs::write(&input, source).unwrap(); let input_name = input.to_str().unwrap(); let output_name = output.to_str().unwrap(); diff --git a/toolchain/Cargo.toml b/toolchain/Cargo.toml index 5e39762..6c9f44b 100644 --- a/toolchain/Cargo.toml +++ b/toolchain/Cargo.toml @@ -9,9 +9,10 @@ default = [] rust-reference = ["assembler/rust-reference", "ir/rust-reference"] [dependencies] -assembler = { path = "../assembler" } +assembler = { path = "../bindings/rust/assembler" } +asmobj = { path = "../bindings/rust/asmobj" } backend-api = { path = "../backend-api" } target-spec = { path = "../target-spec" } -ir = { path = "../ir" } +ir = { path = "../bindings/rust/ir" } diagnostic = { path = "../diagnostic" } object = { path = "../object" } diff --git a/toolchain/build.rs b/toolchain/build.rs deleted file mode 100644 index 7f407e6..0000000 --- a/toolchain/build.rs +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -use std::{env, fs, io::Read, path::PathBuf}; - -fn update(hash: u64, bytes: &[u8]) -> u64 { - bytes.iter().fold(hash, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)) -} - -fn hash(bytes: &[u8]) -> String { - format!("{:016x}", update(0xcbf29ce484222325, bytes)) -} - -fn archive_hash(path: &std::path::Path) -> String { - let mut file = fs::File::open(path).expect("missing asmobj archive"); - let mut hash = 0xcbf29ce484222325; - let mut buffer = [0; 16384]; - loop { - let count = file.read(&mut buffer).expect("cannot read asmobj archive"); - if count == 0 { - return format!("{hash:016x}"); - } - hash = update(hash, &buffer[..count]); - } -} - -fn bounded_hash(path: &std::path::Path, maximum: u64, label: &str) -> String { - let mut bytes = Vec::new(); - fs::File::open(path) - .unwrap_or_else(|_| panic!("missing {label}")) - .take(maximum + 1) - .read_to_end(&mut bytes) - .unwrap_or_else(|_| panic!("cannot read {label}")); - assert!(bytes.len() as u64 <= maximum, "oversized {label}"); - hash(&bytes) -} - -fn main() { - println!("cargo:rustc-check-cfg=cfg(whale_asmobj)"); - println!("cargo:rerun-if-env-changed=WHALE_ASMOBJ_DIR"); - let Some(directory) = env::var_os("WHALE_ASMOBJ_DIR") else { return }; - let directory = PathBuf::from(directory).canonicalize().expect("WHALE_ASMOBJ_DIR must exist"); - let target = env::var("TARGET").unwrap(); - let archive = directory.join(if target.contains("msvc") { - "whale_asmobj.lib" - } else { - "libwhale_asmobj.a" - }); - let metadata = directory.join("asmobj.meta"); - let provenance = directory.join("provenance.json"); - println!("cargo:rerun-if-changed={}", archive.display()); - println!("cargo:rerun-if-changed={}", metadata.display()); - println!("cargo:rerun-if-changed={}", provenance.display()); - let mut text = String::new(); - fs::File::open(&metadata) - .expect("missing asmobj.meta; build with tools/build_asmobj.py") - .take(4097) - .read_to_string(&mut text) - .expect("invalid asmobj metadata"); - assert!(text.len() <= 4096, "oversized asmobj metadata"); - let mut fields = std::collections::BTreeMap::new(); - for line in text.lines() { - let (key, value) = line.split_once('=').expect("malformed asmobj metadata"); - assert!( - [ - "schema", - "target", - "wave_revision", - "opt_level", - "source_fnv64", - "abi_fnv64", - "archive_fnv64", - "provenance_fnv64" - ] - .contains(&key) - && fields.insert(key, value).is_none(), - "invalid asmobj metadata fields" - ); - } - assert_eq!(fields.len(), 8, "incomplete asmobj metadata"); - assert_eq!(fields.get("schema"), Some(&"2"), "unsupported asmobj metadata"); - assert_eq!(fields.get("target"), Some(&target.as_str()), "asmobj archive target mismatch"); - assert_eq!( - fields.get("wave_revision"), - Some(&"e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"), - "asmobj Wave compiler revision mismatch" - ); - assert!( - [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), - "unsupported asmobj optimization level" - ); - let root = - PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("../assembler/asmobj"); - let mut source = Vec::new(); - for (index, name) in [ - "model.wave", - "sections.wave", - "symbols.wave", - "relocations/amd64.wave", - "relocations/aarch64.wave", - "relocations/riscv64.wave", - "relocations/loongarch64.wave", - "relocations.wave", - "entry.wave", - ] - .iter() - .enumerate() - { - let path = root.join(name); - println!("cargo:rerun-if-changed={}", path.display()); - if index != 0 { - source.push(b'\n'); - } - source.extend(fs::read(path).expect("missing asmobj Wave source")); - } - assert_eq!( - fields.get("source_fnv64"), - Some(&hash(&source).as_str()), - "stale asmobj archive; rebuild with tools/build_asmobj.py" - ); - let abi_path = - PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("src/assembly_object.rs"); - println!("cargo:rerun-if-changed={}", abi_path.display()); - assert_eq!( - fields.get("abi_fnv64"), - Some(&bounded_hash(&abi_path, 1024 * 1024, "asmobj ABI source").as_str()), - "stale asmobj ABI; rebuild with tools/build_asmobj.py" - ); - assert_eq!( - fields.get("archive_fnv64"), - Some(&archive_hash(&archive).as_str()), - "corrupt asmobj archive" - ); - assert_eq!( - fields.get("provenance_fnv64"), - Some(&bounded_hash(&provenance, 16 * 1024, "asmobj provenance").as_str()), - "corrupt asmobj provenance" - ); - println!("cargo:rustc-link-search=native={}", directory.display()); - println!("cargo:rustc-link-lib=static=whale_asmobj"); - println!("cargo:rustc-cfg=whale_asmobj"); -} diff --git a/toolchain/src/lib.rs b/toolchain/src/lib.rs index cb5a5c1..bda884f 100644 --- a/toolchain/src/lib.rs +++ b/toolchain/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 //! Explicit composition root. No built-in ISA, global state, or dynamic loader. -pub mod assembly_object; +pub use asmobj as assembly_object; use assembler::extension::Assembler; diff --git a/tools/RELEASING.md b/tools/RELEASING.md index 74e1eca..c2a62c1 100644 --- a/tools/RELEASING.md +++ b/tools/RELEASING.md @@ -7,8 +7,7 @@ that mode. Cross-produced Wave objects do not establish another executable host. Build a clean revision with Meson, then package it with Python 3.13+: ```sh -meson setup /tmp/whale-release --buildtype=release -Dsocket-cli=true \ - -Dwave-source=/absolute/Wave -Dwave-rust-toolchain=1.89 +meson setup /tmp/whale-release --buildtype=release -Dsocket-cli=true meson compile -C /tmp/whale-release python3 tools/release.py package --binary /tmp/whale-release/whale \ --directory /tmp/whale-dist --version 0.1.0 --source FULL_40_DIGIT_COMMIT \ diff --git a/tools/build_asmobj.py b/tools/build_asmobj.py deleted file mode 100644 index 3dac442..0000000 --- a/tools/build_asmobj.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -"""Compile the complete asmobj Wave module; read the pinned compiler checkout only.""" -import argparse -import hashlib -import json -import os -from pathlib import Path -import tempfile -from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, ensure_bootstrap, run, digest - -SOURCES = ( - 'model.wave', 'sections.wave', 'symbols.wave', - 'relocations/amd64.wave', 'relocations/aarch64.wave', - 'relocations/riscv64.wave', 'relocations/loongarch64.wave', - 'relocations.wave', 'entry.wave', -) -ABI_SOURCE = 'toolchain/src/assembly_object.rs' -TARGETS = ('x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', - 'riscv64gc-unknown-linux-gnu', 'x86_64-pc-windows-msvc', - 'aarch64-pc-windows-msvc', 'x86_64-apple-darwin', 'aarch64-apple-darwin') - -def fnv64(data): - value = 0xcbf29ce484222325 - for octet in data: - value = ((value ^ octet) * 0x100000001b3) & 0xffffffffffffffff - return f'{value:016x}' - -def source_bytes(root): - return b'\n'.join((root / 'assembler/asmobj' / name).read_bytes() for name in SOURCES) - -def metadata(source, abi, archive, provenance, target, opt_level): - return (f'schema=2\ntarget={target}\nwave_revision={WAVE_REVISION}\n' - f'opt_level={opt_level}\nsource_fnv64={fnv64(source)}\n' - f'abi_fnv64={fnv64(abi)}\narchive_fnv64={fnv64(archive)}\n' - f'provenance_fnv64={fnv64(provenance)}\n') - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--wave-source', type=Path, required=True) - parser.add_argument('--out-dir', type=Path, required=True) - parser.add_argument('--bootstrap-dir', type=Path) - parser.add_argument('--rust-toolchain', default=DEFAULT_RUST_TOOLCHAIN) - parser.add_argument('--target', choices=TARGETS, default=TARGETS[0]) - parser.add_argument('--opt-level', choices=('0', '2'), default='2') - parser.add_argument('--allow-network', action='store_true') - args = parser.parse_args() - output = args.out_dir.resolve() - if output == args.wave_source.resolve() or output.is_relative_to(args.wave_source.resolve()): - parser.error('asmobj output must be outside the read-only Wave checkout') - output.mkdir(parents=True, exist_ok=True) - root = Path(__file__).resolve().parents[1] - source = source_bytes(root) - abi = (root / ABI_SOURCE).read_bytes() - bootstrap = ensure_bootstrap(args.wave_source, args.bootstrap_dir or output / 'bootstrap-cache', - rust_toolchain=args.rust_toolchain, allow_network=args.allow_network) - # Only code generation is cross-target; this never executes a foreign object. - wave_target = args.target.replace('riscv64gc-', 'riscv64-') - environment = os.environ.copy() - environment['WAVE_STD_REVISION'] = WAVE_REVISION - with tempfile.TemporaryDirectory(prefix='.asmobj-', dir=output) as temporary: - temporary = Path(temporary) - kernel = temporary / 'asmobj.wave' - kernel.write_bytes(source) - obj = temporary / 'asmobj.o' - run([bootstrap.compiler, '-O' + args.opt_level, '-C', 'relocation-model=pic', - '--std-root', bootstrap.std_root, '--target=' + wave_target, 'build', kernel, - '--freestanding', '--emit=obj', '-o', obj, '--target-dir', temporary / 'build'], - cwd=temporary, env=environment) - name = 'whale_asmobj.lib' if 'msvc' in args.target else 'libwhale_asmobj.a' - archive = temporary / name - archive_format = ('darwin' if 'apple-darwin' in args.target else - 'coff' if 'msvc' in args.target else None) - archiver = [environment.get('AR', 'ar')] - if archive_format: - # Cross-format symbol indexes must match the consuming linker. - # LLVM ar supports these explicit formats; a host GNU ar must fail - # rather than publish an archive it cannot index correctly. - archiver.append('--format=' + archive_format) - run([*archiver, 'crsD', archive, obj]) - provenance = temporary / 'provenance.json' - provenance.write_text(json.dumps({'wave_revision': WAVE_REVISION, 'target': args.target, - 'opt_level': args.opt_level, 'source_sha256': hashlib.sha256(source).hexdigest(), - 'abi_sha256': hashlib.sha256(abi).hexdigest(), - 'archive_sha256': digest(archive), 'compiler_sha256': digest(bootstrap.compiler), - 'bootstrap_rust_version': RUST_VERSION, 'required_llvm_major': 21, - 'std_sha256': bootstrap.metadata['std_sha256'], - 'bootstrap_provenance': str(bootstrap.provenance)}, indent=2) + '\n') - fingerprint = temporary / 'asmobj.meta' - fingerprint.write_text(metadata(source, abi, archive.read_bytes(), - provenance.read_bytes(), args.target, args.opt_level)) - staged = (archive, provenance, fingerprint) - previous = {} - for path in staged: - destination = output / path.name - if destination.exists(): - backup = temporary / (path.name + '.previous') - os.link(destination, backup) - previous[destination] = backup - published = [] - try: - for path in staged: - destination = output / path.name - os.replace(path, destination) - published.append(destination) - except OSError: - for destination in reversed(published): - backup = previous.get(destination) - if backup is None: - destination.unlink() - else: - os.replace(backup, destination) - raise - print(f'WHALE_ASMOBJ_DIR={output}') - -if __name__ == '__main__': - main() diff --git a/tools/build_wave_assembler.py b/tools/build_wave_assembler.py deleted file mode 100644 index 2a56cbc..0000000 --- a/tools/build_wave_assembler.py +++ /dev/null @@ -1,271 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -"""Build the explicit shared or ISA Wave assembler module with the pinned compiler, without editing Wave.""" - -import argparse -import hashlib -import json -import os -from pathlib import Path -import tempfile - -from wave_bootstrap import (DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, - digest, ensure_bootstrap, run) - - -MODULES = { - 'common': { - 'sources': ( - 'assembler/model.wave', - 'assembler/unicode.wave', - 'assembler/numeric.wave', - 'assembler/output.wave', - 'assembler/lexer.wave', - 'assembler/fixed_model.wave', - 'assembler/fixed_text.wave', - 'assembler/fixed_numbers.wave', - 'assembler/fixed_operands.wave', - 'assembler/fixed_namespace.wave', - 'assembler/fixed_relative.wave', - 'assembler/fixed_scalar.wave', - 'assembler/fixed_source.wave', - 'assembler/fixed_driver.wave', - ), - 'abi': ( - 'assembler/src/tokens.rs', - 'assembler/src/tokens_wave.rs', - 'assembler/src/fixed.rs', - 'assembler/src/fixed_wave.rs', - 'assembler/src/lib.rs', - ), - 'name': 'assembler', - }, - 'amd64': { - 'sources': ( - 'assembler/model.wave', - 'assembler/declarations.wave', - 'assembler/ast_model.wave', - 'assembler/amd64/parser_model.wave', - 'assembler/amd64/registers.wave', - 'assembler/amd64/expressions.wave', - 'assembler/amd64/operands.wave', - 'assembler/amd64/directives.wave', - 'assembler/amd64/parser.wave', - 'assembler/amd64/encoder_model.wave', - 'assembler/amd64/namespace.wave', - 'assembler/amd64/layout.wave', - 'assembler/amd64/address.wave', - 'assembler/amd64/emit.wave', - 'assembler/amd64/integer.wave', - 'assembler/amd64/sse.wave', - 'assembler/amd64/branch.wave', - 'assembler/amd64/directives_encode.wave', - 'assembler/amd64/encoder.wave', - ), - 'abi': ( - 'assembler/amd64/src/ast_model.rs', - 'assembler/amd64/src/parser_wave.rs', - 'assembler/amd64/src/encoder_wave.rs', - 'assembler/amd64/src/encoder_namespace_errors.rs', - 'assembler/amd64/src/tables.rs', - 'assembler/amd64/src/encoder.rs', - 'assembler/amd64/src/encoding/address.rs', - 'assembler/amd64/src/encoding/modrm.rs', - 'assembler/amd64/src/encoding/rex.rs', - 'assembler/amd64/src/encoding/sib.rs', - 'assembler/amd64/src/lib.rs', - ), - 'name': 'amd64', - }, - 'aarch64': { - 'sources': ( - 'assembler/model.wave', - 'assembler/declarations.wave', - 'assembler/fixed_model.wave', - 'assembler/fixed_declarations.wave', - 'assembler/aarch64/registers.wave', - 'assembler/aarch64/parser.wave', - 'assembler/aarch64/operands.wave', - 'assembler/aarch64/encoding.wave', - 'assembler/aarch64/encoder.wave', - 'assembler/aarch64/entry.wave', - ), - 'abi': ( - 'assembler/aarch64/src/wave.rs', - 'assembler/aarch64/src/lib.rs', - 'assembler/aarch64/src/encoder.rs', - 'assembler/aarch64/src/parser.rs', - ), - 'name': 'aarch64', - }, - 'riscv64': { - 'sources': ( - 'assembler/model.wave', - 'assembler/declarations.wave', - 'assembler/fixed_model.wave', - 'assembler/fixed_declarations.wave', - 'assembler/riscv64/registers.wave', - 'assembler/riscv64/operands.wave', - 'assembler/riscv64/encoding.wave', - 'assembler/riscv64/encoder.wave', - 'assembler/riscv64/parser.wave', - 'assembler/riscv64/entry.wave', - ), - 'abi': ( - 'assembler/riscv64/src/wave.rs', - 'assembler/riscv64/src/lib.rs', - 'assembler/riscv64/src/encoder.rs', - 'assembler/riscv64/src/parser.rs', - ), - 'name': 'riscv64', - }, - 'loongarch64': { - 'sources': ( - 'assembler/model.wave', - 'assembler/declarations.wave', - 'assembler/fixed_model.wave', - 'assembler/fixed_declarations.wave', - 'assembler/loongarch64/model.wave', - 'assembler/loongarch64/registers.wave', - 'assembler/loongarch64/tables.wave', - 'assembler/loongarch64/operands.wave', - 'assembler/loongarch64/formats.wave', - 'assembler/loongarch64/branch.wave', - 'assembler/loongarch64/encoder.wave', - 'assembler/loongarch64/entry.wave', - ), - 'abi': ( - 'assembler/loongarch64/src/wave.rs', - 'assembler/loongarch64/src/lib.rs', - 'assembler/loongarch64/src/encoder.rs', - 'assembler/loongarch64/src/parser.rs', - ), - 'name': 'loongarch64', - }, -} -TARGETS = ( - 'x86_64-unknown-linux-gnu', - 'aarch64-unknown-linux-gnu', - 'riscv64gc-unknown-linux-gnu', - 'x86_64-pc-windows-msvc', - 'aarch64-pc-windows-msvc', - 'x86_64-apple-darwin', - 'aarch64-apple-darwin', -) - - -def fnv64(data): - value = 0xcbf29ce484222325 - for octet in data: - value = ((value ^ octet) * 0x100000001b3) & 0xffffffffffffffff - return f"{value:016x}" - - -def source_bytes(root, module): - return b"\n".join((root / name).read_bytes() for name in MODULES[module]["sources"]) - - -def abi_bytes(root, module): - return b"\n".join((root / name).read_bytes() for name in MODULES[module]["abi"]) - - -def metadata(source, abi, archive, provenance, target, opt_level): - return (f"schema=1\ntarget={target}\nwave_revision={WAVE_REVISION}\n" - f"opt_level={opt_level}\nsource_fnv64={fnv64(source)}\n" - f"abi_fnv64={fnv64(abi)}\narchive_fnv64={fnv64(archive)}\n" - f"provenance_fnv64={fnv64(provenance)}\n") - - -def build(args): - root = Path(__file__).resolve().parents[1] - output = args.out_dir.resolve() - config = MODULES[args.module] - name = config["name"] - source = source_bytes(root, args.module) - abi = abi_bytes(root, args.module) - wave_source = args.wave_source.resolve() - if output == wave_source or output.is_relative_to(wave_source): - raise ValueError("Wave assembler output must be outside the read-only Wave checkout") - output.mkdir(parents=True, exist_ok=True) - bootstrap = ensure_bootstrap(wave_source, args.bootstrap_dir or output / "bootstrap-cache", - rust_toolchain=args.rust_toolchain, - allow_network=args.allow_network) - wave_target = args.target.replace("riscv64gc-", "riscv64-") - environment = os.environ.copy() - environment["WAVE_STD_REVISION"] = WAVE_REVISION - with tempfile.TemporaryDirectory(prefix=".wave-assembler-", dir=output) as temporary: - temporary = Path(temporary) - kernel = temporary / "assembler.wave" - kernel.write_bytes(source) - obj = temporary / "assembler.o" - run([bootstrap.compiler, "-O" + args.opt_level, "-C", "relocation-model=pic", - "--std-root", bootstrap.std_root, "--target=" + wave_target, "build", kernel, - "--freestanding", "--emit=obj", "-o", obj, "--target-dir", temporary / "build"], - cwd=temporary, env=environment) - archive_name = (f"whale_wave_{name}.lib" if "msvc" in args.target - else f"libwhale_wave_{name}.a") - archive = temporary / archive_name - archive_format = ("darwin" if "apple-darwin" in args.target else - "coff" if "msvc" in args.target else None) - archiver = [environment.get("AR", "ar")] - if archive_format: - archiver.append("--format=" + archive_format) - run([*archiver, "crsD", archive, obj]) - provenance = temporary / "provenance.json" - provenance.write_text(json.dumps({ - "wave_revision": WAVE_REVISION, "target": args.target, "module": args.module, - "opt_level": args.opt_level, - "source_sha256": hashlib.sha256(source).hexdigest(), - "abi_sha256": hashlib.sha256(abi).hexdigest(), - "archive_sha256": digest(archive), - "compiler_sha256": digest(bootstrap.compiler), - "std_sha256": bootstrap.metadata["std_sha256"], - "bootstrap_rust_version": RUST_VERSION, - "required_llvm_major": 21, - "bootstrap_provenance": str(bootstrap.provenance), - }, indent=2) + "\n") - fingerprint = temporary / f"wave-{name}.meta" - fingerprint.write_text(metadata(source, abi, archive.read_bytes(), - provenance.read_bytes(), args.target, args.opt_level)) - staged = (archive, provenance, fingerprint) - previous = {} - for path in staged: - destination = output / path.name - if destination.exists(): - backup = temporary / (path.name + ".previous") - os.link(destination, backup) - previous[destination] = backup - published = [] - try: - for path in staged: - destination = output / path.name - os.replace(path, destination) - published.append(destination) - except OSError: - for destination in reversed(published): - backup = previous.get(destination) - if backup is None: - destination.unlink() - else: - os.replace(backup, destination) - raise - return output - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--module", choices=tuple(MODULES), default="common") - parser.add_argument("--wave-source", type=Path, required=True) - parser.add_argument("--out-dir", type=Path, required=True) - parser.add_argument("--bootstrap-dir", type=Path) - parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) - parser.add_argument("--target", choices=TARGETS, default=TARGETS[0]) - parser.add_argument("--opt-level", choices=("0", "2"), default="2") - parser.add_argument("--allow-network", action="store_true") - args = parser.parse_args() - name = MODULES[args.module]["name"].upper() - print(f"WHALE_WAVE_{name}_DIR={build(args)}") - - -if __name__ == "__main__": - main() diff --git a/tools/build_wave_ir.py b/tools/build_wave_ir.py deleted file mode 100644 index dad85e1..0000000 --- a/tools/build_wave_ir.py +++ /dev/null @@ -1,227 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -"""Build the internal Wave IR module with the pinned compiler, without editing Wave.""" - -import argparse -import hashlib -import json -import os -from pathlib import Path -import tempfile - -from wave_bootstrap import (DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, - digest, ensure_bootstrap, run) - - -SOURCES = ( - 'model.wave', - 'layout.wave', - 'lexer.wave', - 'header.wave', - 'type_parser.wave', - 'literal.wave', - 'expression_parser.wave', - 'instruction_parser.wave', - 'module_parser.wave', - 'lower_hir.wave', - 'lower_model.wave', - 'lower_output.wave', - 'lower_expression.wave', - 'lower_storage.wave', - 'lower_statement.wave', - 'lower_driver.wave', - 'builder.wave', - 'builder_namespace.wave', - 'builder_body.wave', - 'verify.wave', - 'verifier_index.wave', - 'verifier_ssa.wave', - 'printer.wave', - 'cfg.wave', - 'shape.wave', - 'source.wave', - 'memory.wave', - 'lower_limits.wave', - 'wide.wave', - 'integer.wave', - 'float_model.wave', - 'float_arithmetic.wave', - 'float_convert.wave', - 'effects.wave', - 'passes.wave', - 'fold_integer.wave', - 'constant.wave', - 'constant_dependencies.wave', - 'runtime_model.wave', - 'runtime_prepare.wave', - 'runtime_execute.wave', - 'runtime_driver.wave', - 'bytecode_model.wave', - 'bytecode_inventory.wave', - 'bytecode_loader.wave', - 'bytecode_verify_types.wave', - 'bytecode_verify_instructions.wave', - 'bytecode_verify_flow.wave', - 'bytecode_verify.wave', - 'bytecode_writer.wave', - 'bytecode_runtime.wave', - 'entry.wave', -) -ABI_SOURCES = ( - 'ir/src/wave_layout.rs', - 'ir/src/interpreter/integer.rs', - 'ir/src/float/wave.rs', - 'ir/src/effects_wave.rs', - 'ir/src/pass_wave.rs', - 'ir/src/fold_integer_wave.rs', - 'ir/src/constant_wave.rs', - 'ir/src/interpreter/runtime_wave.rs', - 'ir/src/bytecode.rs', - 'ir/src/verifier/wave_constants.rs', - 'ir/src/source_wave.rs', - 'ir/src/interpreter/memory_wave.rs', - 'ir/src/lower_ast/wave_limits.rs', - 'ir/src/parser/wave_lexer.rs', - 'ir/src/parser/wave_header.rs', - 'ir/src/parser/wave_text.rs', - 'ir/src/parser/wave_type.rs', - 'ir/src/parser/wave_literal.rs', - 'ir/src/parser/wave_expression.rs', - 'ir/src/parser/wave_instruction.rs', - 'ir/src/parser/wave_module.rs', - 'ir/src/lower_ast/wave_hir.rs', - 'ir/src/lower_ast/wave_lower.rs', - 'ir/src/builder/wave.rs', - 'ir/src/builder/namespace.rs', - 'ir/src/builder/body.rs', - 'ir/src/verifier/wave_semantics.rs', - 'ir/src/verifier/wave_index.rs', - 'ir/src/verifier/wave_ssa.rs', - 'ir/src/printer_wave.rs', - 'ir/src/verifier/wave_cfg.rs', - 'ir/src/verifier/wave_shape.rs', - 'ir/src/lib.rs', - 'ir/src/function.rs', - 'ir/src/global_storage.rs', -) -TARGETS = ( - 'x86_64-unknown-linux-gnu', - 'aarch64-unknown-linux-gnu', - 'riscv64gc-unknown-linux-gnu', - 'x86_64-pc-windows-msvc', - 'aarch64-pc-windows-msvc', - 'x86_64-apple-darwin', - 'aarch64-apple-darwin', -) - - -def fnv64(data): - value = 0xcbf29ce484222325 - for octet in data: - value = ((value ^ octet) * 0x100000001b3) & 0xffffffffffffffff - return f"{value:016x}" - - -def source_bytes(root): - return b"\n".join((root / "ir" / name).read_bytes() for name in SOURCES) - - -def abi_bytes(root): - return b"\n".join((root / name).read_bytes() for name in ABI_SOURCES) - - -def metadata(source, abi, archive, provenance, target, opt_level): - return (f"schema=1\ntarget={target}\nwave_revision={WAVE_REVISION}\n" - f"opt_level={opt_level}\nsource_fnv64={fnv64(source)}\n" - f"abi_fnv64={fnv64(abi)}\narchive_fnv64={fnv64(archive)}\n" - f"provenance_fnv64={fnv64(provenance)}\n") - - -def build(args): - root = Path(__file__).resolve().parents[1] - output = args.out_dir.resolve() - source = source_bytes(root) - abi = abi_bytes(root) - wave_source = args.wave_source.resolve() - if output == wave_source or output.is_relative_to(wave_source): - raise ValueError("Wave IR output must be outside the read-only Wave checkout") - output.mkdir(parents=True, exist_ok=True) - bootstrap = ensure_bootstrap(wave_source, args.bootstrap_dir or output / "bootstrap-cache", - rust_toolchain=args.rust_toolchain, - allow_network=args.allow_network) - wave_target = args.target.replace("riscv64gc-", "riscv64-") - environment = os.environ.copy() - environment["WAVE_STD_REVISION"] = WAVE_REVISION - with tempfile.TemporaryDirectory(prefix=".wave-ir-", dir=output) as temporary: - temporary = Path(temporary) - kernel = temporary / "ir.wave" - kernel.write_bytes(source) - obj = temporary / "ir.o" - run([bootstrap.compiler, "-O" + args.opt_level, "-C", "relocation-model=pic", - "--std-root", bootstrap.std_root, "--target=" + wave_target, "build", kernel, - "--freestanding", "--emit=obj", "-o", obj, "--target-dir", temporary / "build"], - cwd=temporary, env=environment) - name = "whale_wave_ir.lib" if "msvc" in args.target else "libwhale_wave_ir.a" - archive = temporary / name - archive_format = ("darwin" if "apple-darwin" in args.target else - "coff" if "msvc" in args.target else None) - archiver = [environment.get("AR", "ar")] - if archive_format: - archiver.append("--format=" + archive_format) - run([*archiver, "crsD", archive, obj]) - provenance = temporary / "provenance.json" - provenance.write_text(json.dumps({ - "wave_revision": WAVE_REVISION, "target": args.target, - "opt_level": args.opt_level, - "source_sha256": hashlib.sha256(source).hexdigest(), - "abi_sha256": hashlib.sha256(abi).hexdigest(), - "archive_sha256": digest(archive), - "compiler_sha256": digest(bootstrap.compiler), - "std_sha256": bootstrap.metadata["std_sha256"], - "bootstrap_rust_version": RUST_VERSION, - "required_llvm_major": 21, - "bootstrap_provenance": str(bootstrap.provenance), - }, indent=2) + "\n") - fingerprint = temporary / "wave-ir.meta" - fingerprint.write_text(metadata(source, abi, archive.read_bytes(), - provenance.read_bytes(), args.target, args.opt_level)) - staged = (archive, provenance, fingerprint) - previous = {} - for path in staged: - destination = output / path.name - if destination.exists(): - backup = temporary / (path.name + ".previous") - os.link(destination, backup) - previous[destination] = backup - published = [] - try: - for path in staged: - destination = output / path.name - os.replace(path, destination) - published.append(destination) - except OSError: - for destination in reversed(published): - backup = previous.get(destination) - if backup is None: - destination.unlink() - else: - os.replace(backup, destination) - raise - return output - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--wave-source", type=Path, required=True) - parser.add_argument("--out-dir", type=Path, required=True) - parser.add_argument("--bootstrap-dir", type=Path) - parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) - parser.add_argument("--target", choices=TARGETS, default=TARGETS[0]) - parser.add_argument("--opt-level", choices=("0", "2"), default="2") - parser.add_argument("--allow-network", action="store_true") - args = parser.parse_args() - print(f"WHALE_WAVE_IR_DIR={build(args)}") - - -if __name__ == "__main__": - main() diff --git a/tools/check_module_layers.py b/tools/check_module_layers.py index 166a7a0..37f0e9e 100644 --- a/tools/check_module_layers.py +++ b/tools/check_module_layers.py @@ -15,12 +15,13 @@ "diagnostic": set(), "target-spec": set(), "assembler": {"target-spec", "diagnostic"}, + "asmobj": {"assembler", "object"}, "ir": {"target-spec", "diagnostic"}, "backend-api": {"ir", "target-spec", "diagnostic"}, "object": {"target-spec", "diagnostic"}, "linker": {"object", "diagnostic"}, "reverse": {"object"}, - "toolchain": {"assembler", "backend-api", "ir", "target-spec", "diagnostic", "object"}, + "toolchain": {"assembler", "asmobj", "backend-api", "ir", "target-spec", "diagnostic", "object"}, } diff --git a/tools/check_wave_amd64_layout.py b/tools/check_wave_amd64_layout.py index d9ffd3f..d82e534 100644 --- a/tools/check_wave_amd64_layout.py +++ b/tools/check_wave_amd64_layout.py @@ -11,8 +11,8 @@ NONE = (1 << 64) - 1 ROOT = Path(__file__).resolve().parents[1] TYPES = {'u64': U, 'i64': C.c_int64, 'u8': C.c_uint8, 'bool': C.c_bool} -for filename in ['assembler/model.wave', 'assembler/ast_model.wave', - 'assembler/amd64/encoder_model.wave']: +for filename in ['assembler/src/model.wave', 'assembler/src/ast.wave', + 'assembler/amd64/src/encoder/model.wave']: for name, body in re.findall(r'struct (\w+)\s*\{([^}]+)\}', (ROOT / filename).read_text()): if name in TYPES: continue diff --git a/tools/check_wave_assembler.py b/tools/check_wave_assembler.py index 17c3859..ccb9254 100644 --- a/tools/check_wave_assembler.py +++ b/tools/check_wave_assembler.py @@ -36,7 +36,7 @@ def integer(value): return bits - (1 << 128) if bits >> 127 else bits -text = (Path(__file__).resolve().parents[1] / "assembler/src/unicode_reference.rs").read_text() +text = (Path(__file__).resolve().parents[1] / "bindings/rust/assembler/src/unicode_reference.rs").read_text() RANGES = [(int(lo), int(hi)) for lo, hi in re.findall(r"\((\d+), (\d+)\)", text)] STARTS = [lo for lo, _ in RANGES] diff --git a/tools/check_wave_bytecode_cli.py b/tools/check_wave_bytecode_cli.py index 8a9932e..18d84aa 100644 --- a/tools/check_wave_bytecode_cli.py +++ b/tools/check_wave_bytecode_cli.py @@ -47,7 +47,7 @@ def invoke(executable, arguments): try: for name, cases in CASES.items(): - source = (ROOT / "ir/tests/fixtures" / name).read_text() + source = (ROOT / "bindings/rust/ir/tests/fixtures" / name).read_text() source = source.replace('"x86_64-whale-linux"', '"whale-bytecode-v1"') text = directory / name image = text.with_suffix(".wbc") diff --git a/tools/check_wave_fixed.py b/tools/check_wave_fixed.py index bfe4133..9d08720 100644 --- a/tools/check_wave_fixed.py +++ b/tools/check_wave_fixed.py @@ -13,7 +13,7 @@ SPACE = '\t\n\v\f\r \u0085\u00a0\u1680' + ''.join(chr(n) for n in range(0x2000, 0x200B)) + '\u2028\u2029\u202f\u205f\u3000' TYPES = {'u64': U, 'i64': C.c_int64, 'u8': C.c_uint8, 'bool': C.c_bool} for name, body in re.findall(r'struct (\w+)\s*\{([^}]+)\}', - (ROOT / 'assembler/fixed_model.wave').read_text()): + (ROOT / 'assembler/src/fixed/model.wave').read_text()): fields = [] for field, kind in re.findall(r'(\w+):\s*([^;]+);', body): pointer = re.fullmatch(r'ptr<(.+)>', kind) diff --git a/tools/check_wave_hir_fixture.py b/tools/check_wave_hir_fixture.py index b93ba91..1e0228f 100644 --- a/tools/check_wave_hir_fixture.py +++ b/tools/check_wave_hir_fixture.py @@ -11,7 +11,11 @@ import tarfile import tempfile -from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION +# This frozen interchange fixture deliberately identifies its historical +# frontend; it does not select the compiler used to build Whale's Wave modules. +DEFAULT_RUST_TOOLCHAIN = "1.89.0" +RUST_VERSION = "1.89.0" +WAVE_REVISION = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b" def main(): @@ -78,7 +82,7 @@ def main(): if actual["wave_revision"] != WAVE_REVISION: raise ValueError("fixture exporter revision differs from the pinned source") data = (json.dumps(actual, indent=2) + "\n").encode() - fixture = root / "ir" / "tests" / "fixtures" / "wave_typed_hir_scalar.json" + fixture = root / "bindings/rust/ir/tests/fixtures/wave_typed_hir_scalar.json" if args.update: fixture.write_bytes(data) elif fixture.read_bytes() != data: diff --git a/tools/check_wave_ir_float.py b/tools/check_wave_ir_float.py index b2306be..8f863d1 100644 --- a/tools/check_wave_ir_float.py +++ b/tools/check_wave_ir_float.py @@ -88,13 +88,13 @@ def conversion_oracle(src, dst, value): def retained(kernel, root): rows = 0 - for line in (root / 'ir/tests/fixtures/float-arithmetic.txt').read_text().splitlines(): + for line in (root / 'bindings/rust/ir/tests/fixtures/float-arithmetic.txt').read_text().splitlines(): if not line or line.startswith('#'): continue w, op, a, b, result = line.split() assert kernel.arithmetic(int(w), op, int(a, 16), int(b, 16)) == int(result, 16), line rows += 1 - for line in (root / 'ir/tests/fixtures/float-conversions.txt').read_text().splitlines(): + for line in (root / 'bindings/rust/ir/tests/fixtures/float-conversions.txt').read_text().splitlines(): if not line or line.startswith('#'): continue src, dst, op, source, expected = line.split() diff --git a/tools/check_wave_ir_runtime.py b/tools/check_wave_ir_runtime.py index f906604..d059ce8 100644 --- a/tools/check_wave_ir_runtime.py +++ b/tools/check_wave_ir_runtime.py @@ -27,7 +27,7 @@ def record(name, fields): # This reads only the record ABI. All generated operations and expected values below # are independent of Wave instruction implementation and Rust reference execution. for name, body in re.findall(r"struct (IrRuntime\w+)\s*\{([^}]+)\}", - (Path(__file__).resolve().parents[1] / "ir/runtime_model.wave").read_text()): + (Path(__file__).resolve().parents[1] / "ir/src/interpreter/model.wave").read_text()): fields = [] for field, kind in re.findall(r"(\w+):\s*([^;]+);", body): pointer = re.fullmatch(r"ptr<(.+)>", kind) diff --git a/tools/check_wave_loongarch64.py b/tools/check_wave_loongarch64.py index e0b293e..0b43fa2 100644 --- a/tools/check_wave_loongarch64.py +++ b/tools/check_wave_loongarch64.py @@ -12,7 +12,7 @@ NONE = (1 << 64) - 1 TYPES = {'u64': U, 'i64': C.c_int64, 'u8': C.c_uint8, 'bool': C.c_bool} for name, body in re.findall(r'struct (\w+)\s*\{([^}]+)\}', - (ROOT / 'assembler/fixed_model.wave').read_text()): + (ROOT / 'assembler/src/fixed/model.wave').read_text()): fields = [] for field, kind in re.findall(r'(\w+):\s*([^;]+);', body): pointer = re.fullmatch(r'ptr<(.+)>', kind) @@ -110,7 +110,7 @@ def main(): kernel = library.whale_loongarch64_encode kernel.argtypes = [C.POINTER(Instruction), C.POINTER(Context), C.POINTER(Result)] fixtures = 0 - for line in (ROOT / 'assembler/loongarch64/tests/fixtures/encodings.tsv').read_text().splitlines(): + for line in (ROOT / 'bindings/rust/loongarch64/tests/fixtures/encodings.tsv').read_text().splitlines(): if not line or line.startswith('#'): continue encoded, source = line.split('\t') diff --git a/tools/check_wave_module_selection.py b/tools/check_wave_module_selection.py index 3913e1c..a4c041b 100644 --- a/tools/check_wave_module_selection.py +++ b/tools/check_wave_module_selection.py @@ -36,9 +36,9 @@ def main(): raise RuntimeError('Cargo is required for actual module selection checks') checks = 0 for package, directory, variable, library, metadata in [ - ('ir', arguments.ir_dir, 'WHALE_WAVE_IR_DIR', 'libwhale_wave_ir.a', 'wave-ir.meta'), + ('ir', arguments.ir_dir, 'WHALE_WAVE_IR_DIR', 'libwhale_wave_ir.a', 'module.meta'), ('assembler', arguments.assembler_dir, 'WHALE_WAVE_ASSEMBLER_DIR', - 'libwhale_wave_assembler.a', 'wave-assembler.meta'), + 'libwhale_wave_assembler.a', 'module.meta'), ]: command = [cargo, 'check', '--manifest-path', str(root / 'Cargo.toml'), '-p', package, '--no-default-features', '--locked', '--offline', '--jobs', '2'] diff --git a/tools/generate_conversion_vectors.py b/tools/generate_conversion_vectors.py index 36e380d..4ddaaef 100644 --- a/tools/generate_conversion_vectors.py +++ b/tools/generate_conversion_vectors.py @@ -50,7 +50,7 @@ def main(): if dest != width: want = encode(dest, value, raw == sign) lines.append(f"f{width} f{dest} {'fext' if width < dest else 'ftrunc'} {raw:x} {want:x}") - path = Path(__file__).resolve().parent.parent / "ir/tests/fixtures/float-conversions.txt" + path = Path(__file__).resolve().parent.parent / "bindings/rust/ir/tests/fixtures/float-conversions.txt" path.write_text("\n".join(lines) + "\n", encoding="utf-8") print(f"Generated {len(lines) - 1} exact conversion vectors") diff --git a/tools/generate_float_vectors.py b/tools/generate_float_vectors.py index e88059b..6e45e24 100644 --- a/tools/generate_float_vectors.py +++ b/tools/generate_float_vectors.py @@ -112,7 +112,7 @@ def main(): for op in ("fadd", "fsub", "fmul", "fdiv", "frem"): expected = arithmetic(width, op, a, b) lines.append(f"{width} {op} {a:x} {b:x} {expected:x}") - output = Path(__file__).resolve().parent.parent / "ir/tests/fixtures/float-arithmetic.txt" + output = Path(__file__).resolve().parent.parent / "bindings/rust/ir/tests/fixtures/float-arithmetic.txt" output.write_text("\n".join(lines) + "\n", encoding="utf-8") print(f"Generated {len(lines) - 1} exact arithmetic vectors") diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py index bb2722f..96953e7 100644 --- a/tools/meson_cargo.py +++ b/tools/meson_cargo.py @@ -8,7 +8,6 @@ import argparse import json -import json import os from pathlib import Path import re @@ -23,8 +22,8 @@ class BuildError(ValueError): ASSEMBLERS = ("amd64", "aarch64", "riscv64", "loongarch64") FEATURES = {"asm-" + arch for arch in ASSEMBLERS} | {"socket-cli", "native-linker", "rust-reference"} -COMPONENTS = ("diagnostic", "assembler", "backend-api", "toolchain", - "reverse", "target-spec", "object", "linker", "ir") +COMPONENTS = ("diagnostic", "bindings/rust/assembler", "backend-api", "toolchain", + "reverse", "target-spec", "object", "linker", "bindings/rust/ir", "bindings/rust/asmobj") TRIPLE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]+\Z") @@ -170,7 +169,7 @@ def source_dependencies(source, features): # The repository root also receives unrelated tool state (for example # .git and editor directories). Tracking it makes every warm build dirty. dependencies = {source / "Cargo.toml", source / "Cargo.lock", Path(__file__).resolve()} - components = [*COMPONENTS, *("assembler/" + arch for arch in ASSEMBLERS if "asm-" + arch in features)] + components = [*COMPONENTS, *("bindings/rust/" + arch for arch in ASSEMBLERS if "asm-" + arch in features)] for component in ["", *components]: root = source / component for name in ["Cargo.toml", "build.rs"]: @@ -188,16 +187,7 @@ def source_dependencies(source, features): elif path.is_dir(): dependencies.add(path) dependencies.update(path.iterdir()) - dependencies.add(source / "assembler/asmobj") - dependencies.update((source / "assembler/asmobj").rglob("*.wave")) - dependencies.update(path for path in (source / "assembler/asmobj").rglob("*") if path.is_dir()) - dependencies.update((source / "ir").glob("*.wave")) - dependencies.update((source / "assembler").glob("*.wave")) - if (source / "assembler/build_support.rs").is_file(): - dependencies.add(source / "assembler/build_support.rs") - for arch in ASSEMBLERS: - if "asm-" + arch in features: - dependencies.update((source / "assembler" / arch).glob("*.wave")) + dependencies.add(source / "bindings/rust/build_support.rs") return dependencies @@ -297,17 +287,17 @@ def build(arguments): for path in cargo_dependencies(directory / "whale.d")) if asmobj_directory: archive = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" - dependencies.update(asmobj_directory / name for name in [archive, "asmobj.meta", "provenance.json"]) + dependencies.update(asmobj_directory / name for name in [archive, "module.meta", "provenance.json"]) if wave_ir_directory: archive = "whale_wave_ir.lib" if "msvc" in target else "libwhale_wave_ir.a" - dependencies.update(wave_ir_directory / name for name in [archive, "wave-ir.meta", "provenance.json"]) + dependencies.update(wave_ir_directory / name for name in [archive, "module.meta", "provenance.json"]) for name, directory in [("assembler", wave_assembler_directory), ("amd64", wave_amd64_directory), ("aarch64", wave_aarch64_directory), ("riscv64", wave_riscv64_directory), ("loongarch64", wave_loongarch64_directory)]: if directory: archive = f"whale_wave_{name}.lib" if "msvc" in target else f"libwhale_wave_{name}.a" dependencies.update(directory / file for file in - [archive, f"wave-{name}.meta", "provenance.json"]) + [archive, "module.meta", "provenance.json"]) contents = make_escape(output) + ": " + " ".join(make_escape(path) for path in sorted(dependencies)) + "\n" candidate = None candidate_depfile = None @@ -394,26 +384,6 @@ def invoke(values): raise BuildError("Whale bytecode execution smoke failed") -def bootstrap(arguments): - from wave_bootstrap import BootstrapError, ensure_bootstrap - try: - result = ensure_bootstrap(arguments.wave_source, arguments.cache_dir, - rust_toolchain=arguments.rust_toolchain, - allow_network=arguments.allow_network) - except BootstrapError as error: - raise BuildError(str(error)) from error - output = arguments.output.resolve() - candidate = None - try: - with tempfile.NamedTemporaryFile(prefix=".wave-ready-", dir=output.parent, delete=False) as temporary: - candidate = Path(temporary.name) - temporary.write((json.dumps(result.paths(), sort_keys=True) + "\n").encode("utf-8")) - os.replace(candidate, output) - finally: - if candidate is not None: - candidate.unlink(missing_ok=True) - - def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) @@ -442,12 +412,6 @@ def main(argv=None): smoke_parser.add_argument("--binary", type=Path, required=True) smoke_parser.add_argument("--feature", action="append", default=[]) smoke_parser.add_argument("--runner-arg", action="append", default=[]) - bootstrap_parser = commands.add_parser("bootstrap") - bootstrap_parser.add_argument("--wave-source", type=Path, required=True) - bootstrap_parser.add_argument("--cache-dir", type=Path, required=True) - bootstrap_parser.add_argument("--rust-toolchain", required=True) - bootstrap_parser.add_argument("--output", type=Path, required=True) - bootstrap_parser.add_argument("--allow-network", action="store_true") arguments = parser.parse_args(argv) try: if arguments.command == "build": @@ -456,8 +420,6 @@ def main(argv=None): build(arguments) elif arguments.command == "smoke": smoke(arguments) - else: - bootstrap(arguments) except (BuildError, OSError, subprocess.SubprocessError) as error: parser.exit(1, f"Meson Cargo bridge: {error}\n") return 0 diff --git a/tools/release.py b/tools/release.py index 512b902..7dbc0dd 100644 --- a/tools/release.py +++ b/tools/release.py @@ -16,7 +16,6 @@ import zipfile from ci_smoke import text_section -from wave_bootstrap import WAVE_REVISION ROOT = Path(__file__).resolve().parents[1] TARGETS = { @@ -60,17 +59,23 @@ def validate_product(info, version, target, source, socket, require_wave=False): or set(modules) != {name for name, value in implementations.items() if value == "wave"}): raise ValueError("product module identities and archives disagree") provenance_fields = {"wave_revision", "target", "opt_level", "source_sha256", "abi_sha256", - "archive_sha256", "compiler_sha256", "std_sha256", "bootstrap_rust_version", - "required_llvm_major"} + "archive_sha256", "compiler_sha256", "std_sha256", "compiler_version", + "nightly_archive_sha256", "vex_version", "vex_sha256", "vex_provenance_sha256"} for module in modules.values(): if (type(module) is not dict or set(module) != provenance_fields - or module["wave_revision"] != WAVE_REVISION or module["target"] != target + or type(module["wave_revision"]) is not str + or not re.fullmatch("[0-9a-f]{40}", module["wave_revision"]) or module["target"] != target or module["opt_level"] not in ("0", "2") - or module["bootstrap_rust_version"] != "1.89.0" - or type(module["required_llvm_major"]) is not int or module["required_llvm_major"] != 21 + or type(module["compiler_version"]) is not str + or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?", module["compiler_version"]) + or type(module["vex_version"]) is not str or not module["vex_version"].startswith("vex ") or any(type(module[key]) is not str or not re.fullmatch("[0-9a-f]{64}", module[key]) - for key in ("source_sha256", "abi_sha256", "archive_sha256", "compiler_sha256", "std_sha256"))): + for key in ("source_sha256", "abi_sha256", "archive_sha256", "compiler_sha256", "std_sha256", + "nightly_archive_sha256", "vex_sha256", "vex_provenance_sha256"))): raise ValueError("invalid Wave compiler/source/archive provenance") + if len({(m["wave_revision"], m["compiler_sha256"], m["std_sha256"], m["nightly_archive_sha256"], m["vex_sha256"]) + for m in modules.values()}) > 1: + raise ValueError("Wave modules used different nightly/compiler/std/Vex snapshots") mode = ("wave" if all(value == "wave" for value in implementations.values()) else "rust-reference" if implementations["ir"] == "rust-reference" else "mixed") if info["product_mode"] != mode: diff --git a/tools/schema_agreement.py b/tools/schema_agreement.py index 6150a2c..7d3104a 100644 --- a/tools/schema_agreement.py +++ b/tools/schema_agreement.py @@ -147,7 +147,7 @@ def check(label, instance, schema_ok, lower_ok, raw=None, decode_ok=None): for record in cases(version): label, instance, valid, lower, *decode = record check(f"v{version}-{label}", instance, valid, lower, decode_ok=decode[0] if decode else None) - accepted_fixtures = sorted((root / "ir/tests/fixtures").glob("ast-v*.json")) + accepted_fixtures = sorted((root / "bindings/rust/ir/tests/fixtures").glob("ast-v*.json")) accepted_fixtures += sorted((root / "fuzz/corpus/ast").glob("located-v*.json")) for path in accepted_fixtures: check(path.name, json.loads(path.read_text(encoding="utf-8")), True, True) diff --git a/tools/test_build_asmobj.py b/tools/test_build_asmobj.py deleted file mode 100644 index 7558df8..0000000 --- a/tools/test_build_asmobj.py +++ /dev/null @@ -1,441 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -"""Regress complete asmobj publication and its real std-only Cargo build guard.""" -import contextlib -import hashlib -import io -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -import build_asmobj as helper -from wave_bootstrap import Bootstrap - -ROOT = Path(__file__).resolve().parents[1] -NATIVE = "x86_64-unknown-linux-gnu" - - -class PublicationTests(unittest.TestCase): - def publication(self, *, failure=None, existing=True, target=NATIVE, allow_network=False): - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary).resolve() - source = root / "Wave" - source.mkdir() - marker = source / "user.wave" - marker.write_bytes(b"unrelated user changes") - output = root / "output" - output.mkdir() - compiler = root / "wavec" - compiler.write_bytes(b"pinned compiler") - std = root / "std" - std.mkdir() - bootstrap = Bootstrap(compiler, std, root / "bootstrap-provenance.json", {"std_sha256": "1" * 64}, True) - archive_name = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" - names = (archive_name, "provenance.json", "asmobj.meta") - original = {name: b"previous " + name.encode() for name in names} - if existing: - for name, data in original.items(): - (output / name).write_bytes(data) - calls = [] - publication_names = { - "publish-archive": archive_name, - "publish-provenance": "provenance.json", - "publish-meta": "asmobj.meta", - } - real_replace = os.replace - injected = False - - def replace(source_path, destination): - nonlocal injected - if (not injected and failure in publication_names - and Path(destination) == output / publication_names[failure]): - injected = True - raise OSError("injected publication failure") - return real_replace(source_path, destination) - - def fake_bootstrap(*args, **kwargs): - self.assertEqual(args, (source, output / "bootstrap-cache")) - self.assertEqual(kwargs, {"rust_toolchain": "1.89", "allow_network": allow_network}) - if failure == "bootstrap": - raise subprocess.CalledProcessError(1, ["cargo"]) - return bootstrap - - def fake_run(command, **kwargs): - command = list(map(str, command)) - calls.append(command) - if "-o" in command: - self.assertEqual(command[0], str(compiler)) - self.assertEqual(command[command.index("--std-root") + 1], str(std)) - self.assertIn("-O0", command) - self.assertIn("relocation-model=pic", command) - self.assertIn("--freestanding", command) - self.assertIn("--emit=obj", command) - wave_target = target.replace("riscv64gc-", "riscv64-") - self.assertIn("--target=" + wave_target, command) - self.assertEqual(kwargs["env"]["WAVE_STD_REVISION"], helper.WAVE_REVISION) - kernel = Path(command[command.index("build") + 1]) - self.assertEqual(kernel.read_bytes(), helper.source_bytes(ROOT)) - self.assertEqual(Path(kwargs["cwd"]), kernel.parent) - Path(command[command.index("-o") + 1]).write_bytes(b"object") - if failure == "compile": - raise subprocess.CalledProcessError(1, command) - else: - expected_archiver = ["asmobj-test-ar"] - if "msvc" in target: - expected_archiver.append("--format=coff") - elif "apple-darwin" in target: - expected_archiver.append("--format=darwin") - expected_archiver.append("crsD") - self.assertEqual(command[:-2], expected_archiver) - self.assertEqual(Path(command[-2]).name, archive_name) - self.assertEqual(Path(command[-1]).read_bytes(), b"object") - Path(command[-2]).write_bytes(b"new archive") - if failure == "archive": - raise subprocess.CalledProcessError(1, command) - - arguments = ["build_asmobj.py", "--wave-source", str(source), "--out-dir", str(output), - "--rust-toolchain", "1.89", "--target", target, "--opt-level", "0"] - if allow_network: - arguments.append("--allow-network") - with patch.object(sys, "argv", arguments), \ - patch.object(helper, "ensure_bootstrap", side_effect=fake_bootstrap), \ - patch.object(helper, "run", side_effect=fake_run), \ - patch.object(helper.os, "replace", side_effect=replace), \ - patch.dict(os.environ, {"AR": "asmobj-test-ar"}), \ - contextlib.redirect_stdout(io.StringIO()): - if failure: - expected = OSError if failure in publication_names else subprocess.CalledProcessError - with self.assertRaises(expected): - helper.main() - else: - helper.main() - self.assertEqual(marker.read_bytes(), b"unrelated user changes") - self.assertEqual(sorted(p.name for p in source.iterdir()), ["user.wave"]) - self.assertFalse(any(p.name.startswith(".asmobj-") for p in output.iterdir())) - for name in names: - path = output / name - if failure and existing: - self.assertEqual(path.read_bytes(), original[name]) - elif failure: - self.assertFalse(path.exists(), name) - else: - self.assertTrue(path.is_file(), name) - if not failure: - self.assertEqual(len(calls), 2) - source_bytes = helper.source_bytes(ROOT) - abi_bytes = (ROOT / helper.ABI_SOURCE).read_bytes() - provenance_bytes = (output / "provenance.json").read_bytes() - self.assertEqual((output / "asmobj.meta").read_text(), - helper.metadata(source_bytes, abi_bytes, b"new archive", - provenance_bytes, target, "0")) - provenance = json.loads((output / "provenance.json").read_text()) - self.assertEqual(provenance, { - "wave_revision": helper.WAVE_REVISION, - "target": target, - "opt_level": "0", - "source_sha256": hashlib.sha256(source_bytes).hexdigest(), - "abi_sha256": hashlib.sha256(abi_bytes).hexdigest(), - "archive_sha256": hashlib.sha256(b"new archive").hexdigest(), - "compiler_sha256": hashlib.sha256(b"pinned compiler").hexdigest(), - "bootstrap_rust_version": helper.RUST_VERSION, - "required_llvm_major": 21, - "std_sha256": "1" * 64, - "bootstrap_provenance": str(bootstrap.provenance), - }) - - def test_success_publishes_exact_source_archive_and_compiler_provenance(self): - self.publication() - - def test_compile_archive_and_bootstrap_failures_preserve_last_good_set(self): - for failure in ("bootstrap", "compile", "archive"): - with self.subTest(failure=failure): - self.publication(failure=failure) - - def test_failed_first_build_never_publishes_partial_artifacts(self): - for failure in ("bootstrap", "compile", "archive"): - with self.subTest(failure=failure): - self.publication(failure=failure, existing=False) - - def test_each_publication_failure_rolls_back_last_good_set(self): - for failure in ("publish-archive", "publish-provenance", "publish-meta"): - with self.subTest(failure=failure): - self.publication(failure=failure) - - def test_each_failed_first_publication_leaves_no_artifact_set(self): - for failure in ("publish-archive", "publish-provenance", "publish-meta"): - with self.subTest(failure=failure): - self.publication(failure=failure, existing=False) - - def test_cross_object_targets_keep_distinct_metadata_and_archive_names(self): - for target in ("riscv64gc-unknown-linux-gnu", "aarch64-pc-windows-msvc", "aarch64-apple-darwin"): - with self.subTest(target=target): - self.publication(target=target) - - def test_network_permission_is_explicitly_forwarded(self): - self.publication(allow_network=True) - - def test_output_inside_compiler_checkout_is_rejected_before_bootstrap(self): - with tempfile.TemporaryDirectory() as temporary: - source = Path(temporary).resolve() / "Wave" - source.mkdir() - for output in (source, source / "output"): - with self.subTest(output=output), \ - patch.object(sys, "argv", ["build_asmobj.py", "--wave-source", str(source), - "--out-dir", str(output)]), \ - patch.object(helper, "ensure_bootstrap") as bootstrap, \ - contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as error: - helper.main() - self.assertEqual(error.exception.code, 2) - bootstrap.assert_not_called() - self.assertEqual(list(source.iterdir()), []) - - -class BuildGuardTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.temporary = tempfile.TemporaryDirectory() - cls.guard = Path(cls.temporary.name).resolve() / ("guard.exe" if os.name == "nt" else "guard") - subprocess.run([shutil.which("rustc") or "rustc", str(ROOT / "toolchain/build.rs"), - "--edition=2021", "-Dwarnings", "-o", str(cls.guard)], - check=True, capture_output=True) - - @classmethod - def tearDownClass(cls): - cls.temporary.cleanup() - - @staticmethod - def make_project(root, target=NATIVE): - manifest = root / "toolchain" - manifest.mkdir() - (manifest / "src").mkdir() - (manifest / "src/assembly_object.rs").write_bytes(b"asmobj ffi boundary") - sources = root / "assembler/asmobj" - sources.mkdir(parents=True) - for index, name in enumerate(helper.SOURCES): - (sources / name).parent.mkdir(parents=True, exist_ok=True) - (sources / name).write_bytes(f"source {index}: {name}\n".encode()) - archive_dir = root / "archive" - archive_dir.mkdir() - archive = archive_dir / ("whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a") - archive.write_bytes(b"archive") - source_bytes = b"\n".join((sources / name).read_bytes() for name in helper.SOURCES) - provenance = archive_dir / "provenance.json" - provenance.write_bytes(b'{"wave_revision":"pinned"}\n') - metadata = archive_dir / "asmobj.meta" - metadata.write_text(helper.metadata(source_bytes, b"asmobj ffi boundary", b"archive", - provenance.read_bytes(), target, "2")) - return manifest, sources, archive_dir, archive, metadata - - def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): - with tempfile.TemporaryDirectory() as temporary: - manifest, sources, archive_dir, archive, metadata = self.make_project(Path(temporary).resolve(), target) - if corruption == "source": - (sources / helper.SOURCES[2]).write_bytes(b"changed source") - elif corruption == "archive": - archive.write_bytes(b"changed archive") - elif corruption == "abi": - (manifest / "src/assembly_object.rs").write_bytes(b"changed ffi boundary") - elif corruption == "provenance": - (archive_dir / "provenance.json").write_bytes(b"changed provenance") - elif corruption == "oversized-provenance": - (archive_dir / "provenance.json").write_bytes(b"x" * 16385) - elif corruption == "missing-archive": - archive.unlink() - elif corruption == "missing-source": - (sources / helper.SOURCES[2]).unlink() - elif corruption == "missing-metadata": - metadata.unlink() - elif corruption == "oversized": - metadata.write_text("x" * 4097) - elif corruption == "duplicate": - metadata.write_text(metadata.read_text() + "schema=1\n") - elif corruption == "unknown": - metadata.write_text(metadata.read_text() + "future=1\n") - elif corruption == "incomplete": - metadata.write_text("\n".join(metadata.read_text().splitlines()[:-1]) + "\n") - elif corruption == "malformed": - metadata.write_text(metadata.read_text() + "not an assignment\n") - elif corruption == "invalid-utf8": - metadata.write_bytes(b"\xff") - elif corruption == "schema": - metadata.write_text(metadata.read_text().replace("schema=2", "schema=3")) - elif corruption == "revision": - metadata.write_text(metadata.read_text().replace(helper.WAVE_REVISION, "0" * 40)) - elif corruption == "target": - metadata.write_text(metadata.read_text().replace("target=" + target, "target=aarch64-unknown-linux-gnu")) - environment = os.environ.copy() - environment.pop("WHALE_ASMOBJ_DIR", None) - environment.update(CARGO_MANIFEST_DIR=str(manifest), HOST=NATIVE, TARGET=target) - if enabled: - environment["WHALE_ASMOBJ_DIR"] = str(archive_dir) - return subprocess.run([str(self.guard)], env=environment, capture_output=True, text=True) - - def test_matching_guard_watches_all_sources_and_published_artifacts(self): - result = self.run_guard() - self.assertEqual(result.returncode, 0, result.stderr) - for name in (*helper.SOURCES, "asmobj.meta", "provenance.json", "libwhale_asmobj.a", - "assembly_object.rs"): - self.assertIn(name, result.stdout) - self.assertIn("cargo:rustc-cfg=whale_asmobj", result.stdout) - self.assertIn("cargo:rustc-link-lib=static=whale_asmobj", result.stdout) - - def test_mismatched_or_invalid_artifacts_fail_before_link_selection(self): - expectations = { - "source": "stale asmobj", "archive": "corrupt asmobj", - "abi": "stale asmobj ABI", "provenance": "corrupt asmobj provenance", - "oversized-provenance": "oversized asmobj provenance", - "target": "target mismatch", "oversized": "oversized", - "revision": "compiler revision mismatch", - "duplicate": "metadata fields", "unknown": "metadata fields", - "incomplete": "incomplete", "malformed": "malformed", - "invalid-utf8": "invalid asmobj metadata", "schema": "unsupported", - "missing-source": "missing asmobj Wave source", - "missing-archive": "missing asmobj archive", - "missing-metadata": "missing asmobj.meta", - } - for corruption, reason in expectations.items(): - with self.subTest(corruption=corruption): - result = self.run_guard(corruption) - self.assertNotEqual(result.returncode, 0, result.stdout) - self.assertIn(reason, result.stderr) - self.assertNotIn("cargo:rustc-link-lib", result.stdout) - self.assertNotIn("cargo:rustc-cfg=whale_asmobj", result.stdout) - - def test_each_isa_relocation_source_invalidates_the_guard(self): - for name in helper.SOURCES: - if "/" not in name: - continue - with self.subTest(source=name), tempfile.TemporaryDirectory() as temporary: - manifest, sources, archive_dir, _, _ = self.make_project(Path(temporary).resolve()) - (sources / name).write_bytes(b"changed architecture mapping") - environment = os.environ.copy() - environment.update(CARGO_MANIFEST_DIR=str(manifest), HOST=NATIVE, TARGET=NATIVE, - WHALE_ASMOBJ_DIR=str(archive_dir)) - result = subprocess.run([str(self.guard)], env=environment, capture_output=True, text=True) - self.assertNotEqual(result.returncode, 0) - self.assertIn("stale asmobj archive", result.stderr) - self.assertNotIn("cargo:rustc-link-lib", result.stdout) - - def test_plain_cargo_build_needs_neither_compiler_nor_wave_artifact(self): - result = self.run_guard("missing-metadata", enabled=False) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("cargo:rustc-link-lib", result.stdout) - self.assertNotIn("cargo:rustc-cfg=whale_asmobj", result.stdout) - - def test_cross_linked_object_must_match_cargo_target_without_claiming_execution(self): - for target in helper.TARGETS[1:]: - with self.subTest(target=target): - result = self.run_guard(target=target) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("cargo:rustc-cfg=whale_asmobj", result.stdout) - archive = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" - self.assertIn(archive, result.stdout) - - def test_cargo_rechecks_warm_source_and_archive_changes(self): - identity = subprocess.check_output([shutil.which("rustc") or "rustc", "-vV"], text=True) - hosts = [line.removeprefix("host: ") for line in identity.splitlines() - if line.startswith("host: ")] - self.assertEqual(len(hosts), 1) - with tempfile.TemporaryDirectory() as temporary: - manifest, sources, archive_dir, archive, metadata = self.make_project(Path(temporary).resolve(), hosts[0]) - (manifest / "src/lib.rs").write_text("pub fn marker() {}\n") - (manifest / "Cargo.toml").write_text( - '[package]\nname="asmobj-guard-probe"\nversion="0.0.0"\nedition="2021"\n') - shutil.copyfile(ROOT / "toolchain/build.rs", manifest / "build.rs") - environment = os.environ.copy() - environment.pop("CARGO_BUILD_TARGET", None) - environment.update(WHALE_ASMOBJ_DIR=str(archive_dir), CARGO_TARGET_DIR=str(manifest / "target")) - command = [shutil.which("cargo") or "cargo", "check", "--offline", "--target", hosts[0], - "--manifest-path", str(manifest / "Cargo.toml")] - - def check(success, reason=None): - result = subprocess.run(command, env=environment, capture_output=True, text=True) - self.assertEqual(result.returncode == 0, success, result.stderr) - if reason: - self.assertIn(reason, result.stderr) - - check(True) - source = sources / helper.SOURCES[3] - original = source.read_bytes() - source.write_bytes(original + b"\n") - check(False, "stale asmobj archive") - source.write_bytes(original) - check(True) - archive.write_bytes(b"broken") - check(False, "corrupt asmobj archive") - archive.write_bytes(b"archive") - check(True) - abi = manifest / "src/assembly_object.rs" - abi.write_bytes(b"changed ffi boundary") - check(False, "stale asmobj ABI") - abi.write_bytes(b"asmobj ffi boundary") - check(True) - provenance = archive_dir / "provenance.json" - provenance.write_bytes(b"changed provenance") - check(False, "corrupt asmobj provenance") - provenance.write_bytes(b'{"wave_revision":"pinned"}\n') - check(True) - original_metadata = metadata.read_text() - metadata.write_text(original_metadata.replace("schema=2", "schema=3")) - check(False, "unsupported asmobj metadata") - metadata.write_text(original_metadata) - check(True) - - -class SourceStructureTests(unittest.TestCase): - def test_autocrlf_checkout_preserves_wave_source_fingerprint(self): - # Archives are built on Linux and reused by Windows CI. Git must not - # rewrite their source bytes before the Cargo fingerprint guard runs. - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary).resolve() - sources = root / "assembler/asmobj" - sources.mkdir(parents=True) - abi = root / helper.ABI_SOURCE - abi.parent.mkdir(parents=True) - shutil.copyfile(ROOT / ".gitattributes", root / ".gitattributes") - for name in helper.SOURCES: - (sources / name).parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(ROOT / "assembler/asmobj" / name, sources / name) - shutil.copyfile(ROOT / helper.ABI_SOURCE, abi) - original = helper.source_bytes(root) - original_abi = abi.read_bytes() - environment = {key: value for key, value in os.environ.items() - if not key.startswith("GIT_")} - environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) - git = shutil.which("git") or "git" - for arguments in (["init", "--quiet"], - ["config", "core.autocrlf", "true"], - ["add", ".gitattributes", "assembler/asmobj", helper.ABI_SOURCE]): - subprocess.run([git, *arguments], cwd=root, env=environment, - check=True, capture_output=True) - for name in helper.SOURCES: - (sources / name).unlink() - abi.unlink() - subprocess.run([git, "checkout-index", "--all", "--force"], cwd=root, - env=environment, check=True, capture_output=True) - checked_out = helper.source_bytes(root) - self.assertNotIn(b"\r\n", checked_out) - self.assertEqual(checked_out, original) - self.assertEqual(helper.fnv64(checked_out), helper.fnv64(original)) - self.assertNotIn(b"\r\n", abi.read_bytes()) - self.assertEqual(abi.read_bytes(), original_abi) - - def test_asmobj_is_a_complete_wave_module_with_isa_owned_role_files(self): - module = ROOT / "assembler/asmobj" - self.assertEqual(sorted(path.relative_to(module).as_posix() for path in module.rglob("*.wave")), sorted(helper.SOURCES)) - self.assertEqual(list(module.rglob("*.rs")), []) - self.assertFalse((module / "Cargo.toml").exists()) - for directory in ("assembler", "object", "reverse", "ir", "toolchain", "src"): - source_root = ROOT / directory - if source_root.is_dir(): - self.assertFalse(any(path.is_dir() and path.name == "wave" for path in source_root.rglob("*"))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_build_wave_assembler.py b/tools/test_build_wave_assembler.py deleted file mode 100644 index a57176e..0000000 --- a/tools/test_build_wave_assembler.py +++ /dev/null @@ -1,170 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -"""Assembler archive publication, selection and source/ABI guard regressions.""" - -import argparse -import hashlib -import os -from pathlib import Path -import subprocess -import tempfile -import unittest -from unittest.mock import patch - -import build_wave_assembler as helper -from wave_bootstrap import Bootstrap - - -ROOT = Path(__file__).resolve().parents[1] -NATIVE = "x86_64-unknown-linux-gnu" - - -class PublicationTests(unittest.TestCase): - def test_all_owned_wave_roles_are_in_the_explicit_build_lists(self): - owned = {path.relative_to(ROOT).as_posix() - for directory in (ROOT / "assembler", *(ROOT / "assembler" / name - for name in helper.MODULES if name != "common")) - for path in directory.glob("*.wave")} - configured = {file for config in helper.MODULES.values() for file in config["sources"]} - self.assertEqual(owned, configured) - - def test_compilation_archiving_and_partial_publication_preserve_last_good_set(self): - for module, config in helper.MODULES.items(): - name = config["name"] - names = (f"libwhale_wave_{name}.a", "provenance.json", f"wave-{name}.meta") - failures = ("compile", "archive", *names) - for failure in failures: - with self.subTest(module=module, failure=failure), tempfile.TemporaryDirectory() as tmp: - root = Path(tmp).resolve() - wave = root / "Wave" - wave.mkdir() - marker = wave / "unrelated.wave" - marker.write_bytes(b"owned elsewhere") - output = root / "output" - output.mkdir() - for file in names: - (output / file).write_bytes(b"previous " + file.encode()) - compiler = root / "compiler" - compiler.write_bytes(b"pinned compiler") - bootstrap = Bootstrap(compiler, root / "std", root / "bootstrap.json", - {"std_sha256": "1" * 64}, True) - args = argparse.Namespace(module=module, wave_source=wave, out_dir=output, - bootstrap_dir=root / "cache", rust_toolchain="1.89", target=NATIVE, - opt_level="2", allow_network=False) - original_replace = os.replace - injected = False - - def replace(source, destination): - nonlocal injected - if not injected and Path(destination) == output / failure: - injected = True - raise OSError("injected publication failure") - return original_replace(source, destination) - - def run(command, **kwargs): - command = list(map(str, command)) - if "-o" in command: - kernel = Path(command[command.index("build") + 1]) - self.assertEqual(kernel.read_bytes(), b"kernel") - Path(command[command.index("-o") + 1]).write_bytes(b"object") - if failure == "compile": - raise subprocess.CalledProcessError(1, command) - else: - Path(command[-2]).write_bytes(b"new archive") - if failure == "archive": - raise subprocess.CalledProcessError(1, command) - - with patch.object(helper, "ensure_bootstrap", return_value=bootstrap), \ - patch.object(helper, "source_bytes", return_value=b"kernel"), \ - patch.object(helper, "abi_bytes", return_value=b"ABI"), \ - patch.object(helper, "run", side_effect=run), \ - patch.object(helper.os, "replace", side_effect=replace): - with self.assertRaises((OSError, subprocess.CalledProcessError)): - helper.build(args) - for file in names: - self.assertEqual((output / file).read_bytes(), b"previous " + file.encode()) - self.assertEqual(marker.read_bytes(), b"owned elsewhere") - self.assertEqual({p.name for p in output.iterdir()}, set(names)) - - -class GuardTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.temporary = tempfile.TemporaryDirectory() - cls.directory = Path(cls.temporary.name).resolve() - cls.guards = {} - for module in helper.MODULES: - source = ROOT / "assembler" / ("build.rs" if module == "common" else module + "/build.rs") - binary = cls.directory / module - subprocess.run(["rustc", "--edition=2021", "-Dwarnings", str(source), "-o", str(binary)], - check=True, capture_output=True) - cls.guards[module] = binary - - @classmethod - def tearDownClass(cls): - cls.temporary.cleanup() - - def test_reference_is_explicit_and_all_stale_or_corrupt_inputs_are_rejected(self): - for module, config in helper.MODULES.items(): - with self.subTest(module=module), tempfile.TemporaryDirectory() as tmp: - root = Path(tmp).resolve() - for file in (*config["sources"], *config["abi"]): - path = root / file - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(file.encode()) - source = root / "assembler" - if module != "common": - source /= module - output = root / "archive" - output.mkdir() - name = config["name"] - archive = output / f"libwhale_wave_{name}.a" - provenance = output / "provenance.json" - metadata = output / f"wave-{name}.meta" - archive.write_bytes(b"archive") - provenance.write_bytes(b"pinned provenance") - original = helper.metadata(helper.source_bytes(root, module), - helper.abi_bytes(root, module), archive.read_bytes(), provenance.read_bytes(), NATIVE, "2") - metadata.write_text(original) - env = os.environ.copy() - for variable in (f"WHALE_WAVE_{config['name'].upper()}_DIR" - for config in helper.MODULES.values()): - env.pop(variable, None) - env.update(CARGO_MANIFEST_DIR=str(source), TARGET=NATIVE) - env.pop("CARGO_FEATURE_RUST_REFERENCE", None) - plain = subprocess.run([str(self.guards[module])], env=env, capture_output=True) - self.assertNotEqual(plain.returncode, 0, plain.stderr) - self.assertIn(b"requires its Wave module", plain.stderr) - env["CARGO_FEATURE_RUST_REFERENCE"] = "1" - reference = subprocess.run([str(self.guards[module])], env=env, capture_output=True) - self.assertEqual(reference.returncode, 0, reference.stderr) - self.assertNotIn(b"rustc-link-lib", reference.stdout) - env.pop("CARGO_FEATURE_RUST_REFERENCE") - env["WHALE_WAVE_ASSEMBLER_DIR"] = str(output) - env[f"WHALE_WAVE_{name.upper()}_DIR"] = str(output) - - def check(path, replacement, accepted=False): - previous = path.read_bytes() - path.write_bytes(replacement) - try: - result = subprocess.run([str(self.guards[module])], env=env, capture_output=True) - self.assertEqual(result.returncode == 0, accepted, result.stderr) - finally: - path.write_bytes(previous) - - check(metadata, original.encode(), True) - for file in (*config["sources"], *config["abi"]): - check(root / file, b"changed source or boundary") - check(archive, b"corrupt archive") - check(provenance, b"corrupt provenance") - check(metadata, original.replace("schema=1", "schema=2").encode()) - check(metadata, original.replace("opt_level=2", "opt_level=1").encode()) - check(metadata, (original + "schema=1\n").encode()) - check(metadata, original.replace(NATIVE, "aarch64-unknown-linux-gnu").encode()) - check(metadata, b"x" * 4097) - check(provenance, b"x" * (16 * 1024 + 1)) - self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), - hashlib.sha256(b"archive").hexdigest()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_build_wave_ir.py b/tools/test_build_wave_ir.py deleted file mode 100644 index bc1ea95..0000000 --- a/tools/test_build_wave_ir.py +++ /dev/null @@ -1,197 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -"""Pinned Wave IR publication and std-only Cargo guard regressions.""" - -import argparse -import hashlib -import json -import os -from pathlib import Path -import subprocess -import tempfile -import unittest -from unittest.mock import patch - -import build_wave_ir as helper -from wave_bootstrap import Bootstrap - - -ROOT = Path(__file__).resolve().parents[1] -NATIVE = "x86_64-unknown-linux-gnu" - - -class PublicationTests(unittest.TestCase): - def test_wave_ir_sources_are_explicit_role_files(self): - self.assertEqual({path.name for path in (ROOT / "ir").glob("*.wave")}, set(helper.SOURCES)) - - def test_compile_archive_and_publication_failures_preserve_last_good_set(self): - for failure in ("compile", "archive", "publish-archive", "publish-provenance", "publish-meta"): - with self.subTest(failure=failure), tempfile.TemporaryDirectory() as temporary: - root = Path(temporary).resolve() - wave = root / "Wave" - wave.mkdir() - marker = wave / "user.wave" - marker.write_bytes(b"unrelated user changes") - output = root / "output" - output.mkdir() - compiler = root / "wavec" - compiler.write_bytes(b"pinned compiler") - std = root / "std" - std.mkdir() - bootstrap = Bootstrap(compiler, std, root / "bootstrap.json", - {"std_sha256": "1" * 64}, True) - names = ("libwhale_wave_ir.a", "provenance.json", "wave-ir.meta") - for name in names: - (output / name).write_bytes(b"previous " + name.encode()) - args = argparse.Namespace(wave_source=wave, out_dir=output, - bootstrap_dir=root / "cache", rust_toolchain="1.89", target=NATIVE, - opt_level="0", allow_network=False) - real_replace = os.replace - failed = False - - def replace(source, destination): - nonlocal failed - selected = {"publish-archive": names[0], "publish-provenance": names[1], - "publish-meta": names[2]}.get(failure) - if not failed and selected and Path(destination) == output / selected: - failed = True - raise OSError("injected publication failure") - return real_replace(source, destination) - - def run(command, **kwargs): - command = list(map(str, command)) - if "-o" in command: - kernel = Path(command[command.index("build") + 1]) - self.assertEqual(kernel.read_bytes(), helper.source_bytes(ROOT)) - self.assertEqual(command[0], str(compiler)) - self.assertIn("--freestanding", command) - Path(command[command.index("-o") + 1]).write_bytes(b"object") - if failure == "compile": - raise subprocess.CalledProcessError(1, command) - else: - Path(command[-2]).write_bytes(b"new archive") - if failure == "archive": - raise subprocess.CalledProcessError(1, command) - - with patch.object(helper, "ensure_bootstrap", return_value=bootstrap), \ - patch.object(helper, "run", side_effect=run), \ - patch.object(helper.os, "replace", side_effect=replace): - with self.assertRaises(OSError if failure.startswith("publish") else subprocess.CalledProcessError): - helper.build(args) - for name in names: - self.assertEqual((output / name).read_bytes(), b"previous " + name.encode()) - self.assertEqual(marker.read_bytes(), b"unrelated user changes") - self.assertFalse(any(path.name.startswith(".wave-ir-") for path in output.iterdir())) - - def test_success_records_source_abi_and_compiler_identity(self): - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary).resolve() - wave = root / "Wave" - wave.mkdir() - output = root / "output" - compiler = root / "wavec" - compiler.write_bytes(b"compiler") - std = root / "std" - std.mkdir() - bootstrap = Bootstrap(compiler, std, root / "bootstrap.json", - {"std_sha256": "1" * 64}, True) - args = argparse.Namespace(wave_source=wave, out_dir=output, bootstrap_dir=root / "cache", - rust_toolchain="1.89", target=NATIVE, opt_level="2", - allow_network=False) - - def run(command, **kwargs): - command = list(map(str, command)) - if "-o" in command: - Path(command[command.index("-o") + 1]).write_bytes(b"object") - else: - Path(command[-2]).write_bytes(b"archive") - - with patch.object(helper, "ensure_bootstrap", return_value=bootstrap), \ - patch.object(helper, "run", side_effect=run): - self.assertEqual(helper.build(args), output) - provenance = (output / "provenance.json").read_bytes() - source = helper.source_bytes(ROOT) - abi = helper.abi_bytes(ROOT) - self.assertEqual((output / "wave-ir.meta").read_text(), - helper.metadata(source, abi, b"archive", provenance, NATIVE, "2")) - record = json.loads(provenance) - self.assertEqual(record["source_sha256"], hashlib.sha256(source).hexdigest()) - self.assertEqual(record["abi_sha256"], hashlib.sha256(abi).hexdigest()) - self.assertEqual(record["compiler_sha256"], hashlib.sha256(b"compiler").hexdigest()) - self.assertEqual(record["wave_revision"], helper.WAVE_REVISION) - - -class GuardTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.temporary = tempfile.TemporaryDirectory() - cls.guard = Path(cls.temporary.name).resolve() / "guard" - subprocess.run(["rustc", "--edition=2021", "-Dwarnings", str(ROOT / "ir/build.rs"), - "-o", str(cls.guard)], check=True, capture_output=True) - - @classmethod - def tearDownClass(cls): - cls.temporary.cleanup() - - def test_explicit_reference_and_corrupt_artifact_rejection(self): - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary).resolve() - source = root / "ir" - source.mkdir() - for name in helper.SOURCES: - (source / name).write_bytes((name + "\n").encode()) - abi_paths = {} - for index, name in enumerate(helper.ABI_SOURCES): - path = root / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes((name + " ffi").encode()) - abi_paths[f"abi{index}"] = path - output = root / "archive" - output.mkdir() - archive = output / "libwhale_wave_ir.a" - archive.write_bytes(b"archive") - provenance = output / "provenance.json" - provenance.write_bytes(b"pinned provenance") - metadata = output / "wave-ir.meta" - original = helper.metadata(helper.source_bytes(root), helper.abi_bytes(root), b"archive", - provenance.read_bytes(), NATIVE, "2") - metadata.write_text(original) - environment = os.environ.copy() - environment.pop("WHALE_WAVE_IR_DIR", None) - environment.update(CARGO_MANIFEST_DIR=str(source), TARGET=NATIVE) - - def check(changes, expected): - paths = {"source": source / helper.SOURCES[0], **abi_paths, - "archive": archive, - "provenance": provenance, "meta": metadata} - originals = {key: path.read_bytes() for key, path in paths.items()} - for key, data in changes.items(): - paths[key].write_bytes(data) - result = subprocess.run([str(self.guard)], env={**environment, - "WHALE_WAVE_IR_DIR": str(output)}, capture_output=True, text=True) - self.assertEqual(result.returncode == 0, expected is None, result.stderr) - if expected: - self.assertIn(expected, result.stderr) - self.assertNotIn("cargo:rustc-link-lib", result.stdout) - for key, data in originals.items(): - paths[key].write_bytes(data) - - environment.pop("CARGO_FEATURE_RUST_REFERENCE", None) - plain = subprocess.run([str(self.guard)], env=environment, capture_output=True) - self.assertNotEqual(plain.returncode, 0) - self.assertIn(b"requires its Wave module", plain.stderr) - reference = subprocess.run([str(self.guard)], env={**environment, - "CARGO_FEATURE_RUST_REFERENCE": "1"}, capture_output=True) - self.assertEqual(reference.returncode, 0, reference.stderr) - self.assertNotIn(b"cargo:rustc-link-lib", reference.stdout) - check({}, None) - check({"source": b"changed"}, "stale Wave IR archive") - for name in abi_paths: - check({name: b"changed"}, "stale Wave IR ABI") - check({"archive": b"changed"}, "corrupt Wave IR archive") - check({"provenance": b"changed"}, "corrupt Wave IR provenance") - check({"meta": original.replace("schema=1", "schema=2").encode()}, - "unsupported Wave IR metadata") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_check_module_layers.py b/tools/test_check_module_layers.py index 452b3f2..61815d6 100644 --- a/tools/test_check_module_layers.py +++ b/tools/test_check_module_layers.py @@ -43,10 +43,10 @@ def test_concrete_isa_dependency_into_ir_is_rejected(self): destination = root / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, destination) - manifest = root / "ir/Cargo.toml" + manifest = root / "bindings/rust/ir/Cargo.toml" with manifest.open("a") as stream: stream.write('\n[target.\'cfg(windows)\'.dependencies]\n' - 'amd64 = { path = "../assembler/amd64", optional = true }\n') + 'amd64 = { path = "../amd64", optional = true }\n') with self.assertRaisesRegex(ValueError, "ir.*forbidden.*amd64"): layers.audit(root) @@ -61,8 +61,8 @@ def test_inherited_aliases_resolve_from_workspace_for_all_production_kinds(self) shutil.copyfile(source, destination) with (root / "Cargo.toml").open("a") as stream: stream.write('\n[workspace.dependencies]\n' - 'forbidden = { package = "amd64", path = "assembler/amd64" }\n') - ir_manifest = root / "ir/Cargo.toml" + 'forbidden = { package = "amd64", path = "bindings/rust/amd64" }\n') + ir_manifest = root / "bindings/rust/ir/Cargo.toml" for declaration in [ '\n[dependencies]\nforbidden = { workspace = true, optional = true }\n', '\n[build-dependencies]\nforbidden.workspace = true\n', diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py index 1521393..25bc687 100644 --- a/tools/test_meson_build.py +++ b/tools/test_meson_build.py @@ -161,29 +161,21 @@ def test_malformed_depfile_fails_instead_of_publishing_untracked_binary(self): def test_source_dirs_and_manifests_track_additions_without_disabled_isas(self): with tempfile.TemporaryDirectory() as temporary: source = Path(temporary).resolve() - for name in ["src", "toolchain/src", "assembler/amd64/src", "assembler/aarch64/src"]: + for name in ["src", "toolchain/src", "bindings/rust/asmobj/src", "bindings/rust/ir/src", + "bindings/rust/amd64/src", "bindings/rust/aarch64/src"]: (source / name).mkdir(parents=True) (source / name / "lib.rs").write_text("// source") - (source / "ir").mkdir() - (source / "ir/model.wave").write_text("// type graph") - (source / "toolchain/src/assembly_object.rs").write_text("// ffi boundary") (source / "Cargo.toml").write_text("manifest") - (source / "assembler/model.wave").write_text("shared model") - (source / "assembler/build_support.rs").write_text("guard") - (source / "assembler/amd64/encoder.wave").write_text("disabled") - (source / "assembler/aarch64/encoder.wave").write_text("selected") + (source / "bindings/rust/build_support.rs").write_text("guard") dependencies = source_dependencies(source, ["asm-aarch64"]) self.assertNotIn(source, dependencies) - self.assertIn(source / "assembler/aarch64/src", dependencies) - self.assertIn(source / "assembler/aarch64/src/lib.rs", dependencies) - self.assertNotIn(source / "assembler/amd64/src/lib.rs", dependencies) - self.assertNotIn(source / "assembler/amd64/encoder.wave", dependencies) - self.assertIn(source / "assembler/aarch64/encoder.wave", dependencies) - self.assertIn(source / "assembler/model.wave", dependencies) - self.assertIn(source / "assembler/build_support.rs", dependencies) + self.assertIn(source / "bindings/rust/aarch64/src", dependencies) + self.assertIn(source / "bindings/rust/aarch64/src/lib.rs", dependencies) + self.assertNotIn(source / "bindings/rust/amd64/src/lib.rs", dependencies) + self.assertIn(source / "bindings/rust/build_support.rs", dependencies) self.assertIn(source / "Cargo.toml", dependencies) - self.assertIn(source / "toolchain/src/assembly_object.rs", dependencies) - self.assertIn(source / "ir/model.wave", dependencies) + self.assertIn(source / "bindings/rust/asmobj/src/lib.rs", dependencies) + self.assertIn(source / "bindings/rust/ir/src/lib.rs", dependencies) class PublicationTests(unittest.TestCase): diff --git a/tools/test_release.py b/tools/test_release.py index c6f63ed..f62cb59 100644 --- a/tools/test_release.py +++ b/tools/test_release.py @@ -23,10 +23,12 @@ def product(target, socket=False, reference=False): implementations = {name: "wave" for name in ("ir", "assembler", "asmobj", "amd64")} if reference: implementations.update(ir="rust-reference", assembler="rust-reference", amd64="rust-reference") - provenance = {"wave_revision": release.WAVE_REVISION, "target": target, "opt_level": "2", + provenance = {"wave_revision": "a" * 40, "target": target, "opt_level": "2", "source_sha256": "1" * 64, "abi_sha256": "2" * 64, "archive_sha256": "3" * 64, "compiler_sha256": "4" * 64, "std_sha256": "5" * 64, - "bootstrap_rust_version": "1.89.0", "required_llvm_major": 21} + "compiler_version": "0.0.1-alpha-dev", "nightly_archive_sha256": "6" * 64, + "vex_version": "vex 0.0.3-beta", "vex_sha256": "7" * 64, + "vex_provenance_sha256": "8" * 64} return {"schema_version": 1, "version": VERSION, "source_commit": SOURCE, "source_dirty": False, "host_target": target, "rustc": "rustc 1.86.0", "reference_feature": reference, "wave_modules": {name: provenance.copy() for name, value in implementations.items() if value == "wave"}, diff --git a/tools/test_vex_guards.py b/tools/test_vex_guards.py new file mode 100644 index 0000000..406fa6e --- /dev/null +++ b/tools/test_vex_guards.py @@ -0,0 +1,246 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Exercise the real std-only Cargo guards for every Wave/Rust binding.""" + +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from wave_modules import ASSEMBLERS, MODULES, ROOT, fnv64, input_hashes, inputs + + +class GuardTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temporary = tempfile.TemporaryDirectory() + cls.directory = Path(cls.temporary.name).resolve() + cls.binaries = {} + for module in MODULES: + output = cls.directory / module + subprocess.run( + [ + "rustc", + "--edition=2021", + "-Dwarnings", + str(ROOT / "bindings/rust" / module / "build.rs"), + "-o", + str(output), + ], + check=True, + capture_output=True, + ) + cls.binaries[module] = output + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + def fixture(self, root, module, target="x86_64-unknown-linux-gnu"): + directory, library, variable = MODULES[module] + for relative in ( + (directory, "assembler") if module in ASSEMBLERS else (directory,) + ): + source = root / relative + (source / "src/nested").mkdir(parents=True, exist_ok=True) + (source / "vex.ws").write_bytes(b"module manifest\n") + (source / "src/lib.wave").write_bytes(b"// source entry\n") + (source / "src/nested/role.wave").write_bytes(b"// role\n") + for name in ("vex.ws", "vex.lock"): + (root / name).write_bytes(name.encode()) + binding = root / "bindings/rust" / module + (binding / "src").mkdir(parents=True) + (binding / "src/lib.rs").write_bytes(b"// typed data bridge\n") + (binding / "Cargo.toml").write_bytes(b"binding manifest\n") + output = root / "artifacts" + output.mkdir() + archive = output / ( + library + ".lib" if "msvc" in target else "lib" + library + ".a" + ) + archive.write_bytes(b"!\n") + provenance = output / "provenance.json" + provenance.write_bytes(b"verified compiler/std identities\n") + sources, abi = inputs(module, root) + fields = dict( + schema="3", + target=target, + wave_revision="a" * 40, + opt_level="0", + source_fnv64=input_hashes(sources, root)[0], + abi_fnv64=input_hashes(abi, root)[0], + archive_fnv64=fnv64([archive.read_bytes()]), + provenance_fnv64=fnv64([provenance.read_bytes()]), + ) + metadata = output / "module.meta" + metadata.write_text( + "".join(f"{key}={value}\n" for key, value in fields.items()) + ) + environment = { + key: value + for key, value in os.environ.items() + if not key.startswith("WHALE_") and key != "CARGO_FEATURE_RUST_REFERENCE" + } + environment.update(CARGO_MANIFEST_DIR=str(binding), TARGET=target) + environment[variable] = str(output) + if module in ASSEMBLERS: + environment["WHALE_WAVE_ASSEMBLER_DIR"] = str(output) + return environment, sources, abi, archive, provenance, metadata + + def execute(self, module, environment): + return subprocess.run( + [str(self.binaries[module])], env=environment, capture_output=True + ) + + def test_matching_modules_watch_all_role_and_binding_inputs(self): + for module in MODULES: + with ( + self.subTest(module=module), + tempfile.TemporaryDirectory() as temporary, + ): + root = Path(temporary).resolve() + environment, sources, abi, archive, provenance, metadata = self.fixture( + root, module + ) + result = self.execute(module, environment) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(b"rustc-link-lib=static=", result.stdout) + for path in [*sources, *abi, archive, provenance, metadata]: + self.assertIn(str(path).encode(), result.stdout) + + def test_source_abi_archive_and_provenance_changes_fail_before_link_selection(self): + for module in MODULES: + with ( + self.subTest(module=module), + tempfile.TemporaryDirectory() as temporary, + ): + environment, sources, abi, archive, provenance, metadata = self.fixture( + Path(temporary).resolve(), module + ) + for path in [*sources, *abi, archive, provenance]: + previous = path.read_bytes() + try: + path.write_bytes(previous + b"changed") + result = self.execute(module, environment) + self.assertNotEqual(result.returncode, 0, str(path)) + self.assertNotIn(b"rustc-link-lib", result.stdout) + finally: + path.write_bytes(previous) + + def test_added_empty_role_invalidates_the_source_fingerprint(self): + for module in MODULES: + with ( + self.subTest(module=module), + tempfile.TemporaryDirectory() as temporary, + ): + root = Path(temporary).resolve() + environment, *_ = self.fixture(root, module) + path = root / MODULES[module][0] / "src/new.wave" + path.write_bytes(b"") + result = self.execute(module, environment) + self.assertNotEqual(result.returncode, 0) + self.assertIn(b"stale Wave source", result.stderr) + + def test_malformed_metadata_and_foreign_host_mismatch_are_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + environment, *_, metadata = self.fixture( + Path(temporary).resolve(), "asmobj" + ) + original = metadata.read_text() + for text in ( + original.replace("schema=3", "schema=4"), + original + "schema=3\n", + original.replace("opt_level=0", "opt_level=1"), + "x" * 4097, + original.replace( + "x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu" + ), + original.replace("a" * 40, "A" * 40), + ): + with self.subTest(text=text[:60]): + metadata.write_text(text) + result = self.execute("asmobj", environment) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn(b"rustc-link-lib", result.stdout) + + def test_missing_module_requires_explicit_reference_and_asmobj_reports_unavailable( + self, + ): + for module in MODULES: + with ( + self.subTest(module=module), + tempfile.TemporaryDirectory() as temporary, + ): + environment, *_ = self.fixture(Path(temporary).resolve(), module) + environment.pop(MODULES[module][2]) + plain = self.execute(module, environment) + self.assertEqual(plain.returncode == 0, module == "asmobj") + self.assertNotIn(b"rustc-link-lib", plain.stdout) + environment["CARGO_FEATURE_RUST_REFERENCE"] = "1" + self.assertEqual(self.execute(module, environment).returncode, 0) + + def test_cross_object_selection_uses_the_consuming_target_without_executing_it( + self, + ): + for target in ( + "aarch64-unknown-linux-gnu", + "x86_64-pc-windows-msvc", + "aarch64-apple-darwin", + ): + with ( + self.subTest(target=target), + tempfile.TemporaryDirectory() as temporary, + ): + environment, *_ = self.fixture( + Path(temporary).resolve(), "asmobj", target + ) + result = self.execute("asmobj", environment) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(b"rustc-link-lib=static=whale_asmobj", result.stdout) + + def test_actual_warm_cargo_build_rechecks_changed_source_and_archive(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + environment, sources, abi, archive, provenance, metadata = self.fixture( + root, "asmobj" + ) + binding = root / "bindings/rust/asmobj" + (binding / "Cargo.toml").write_text( + '[package]\nname="guard-probe"\nversion="0.1.0"\nedition="2021"\n' + ) + (binding / "src/lib.rs").write_text("pub fn value() -> u64 { 42 }\n") + shutil.copyfile( + ROOT / "bindings/rust/asmobj/build.rs", binding / "build.rs" + ) + shutil.copyfile( + ROOT / "bindings/rust/build_support.rs", + binding.parent / "build_support.rs", + ) + text = metadata.read_text() + old = next( + line for line in text.splitlines() if line.startswith("abi_fnv64=") + ) + metadata.write_text( + text.replace(old, "abi_fnv64=" + input_hashes(abi, root)[0]) + ) + command = [ + "cargo", + "build", + "--offline", + "--manifest-path", + str(binding / "Cargo.toml"), + "--target-dir", + str(root / "cargo"), + ] + first = subprocess.run(command, env=environment, capture_output=True) + self.assertEqual(first.returncode, 0, first.stderr) + for path in (sources[-1], archive): + previous = path.read_bytes() + path.write_bytes(previous + b"changed") + result = subprocess.run(command, env=environment, capture_output=True) + self.assertNotEqual(result.returncode, 0, result.stderr) + path.write_bytes(previous) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_vex_module.py b/tools/test_vex_module.py new file mode 100644 index 0000000..791da82 --- /dev/null +++ b/tools/test_vex_module.py @@ -0,0 +1,243 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Verify Vex result admission and complete-set publication failures.""" + +from argparse import Namespace +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +import vex_module as helper + + +class PublicationTests(unittest.TestCase): + def test_unchanged_outputs_keep_their_mtimes(self): + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) + files = { + "archive.a": b"archive", + "module.meta": b"metadata", + "provenance.json": b"provenance", + } + helper.publish(output, files) + before = {name: (output / name).stat().st_mtime_ns for name in files} + helper.publish(output, files) + self.assertEqual( + before, {name: (output / name).stat().st_mtime_ns for name in files} + ) + + def test_every_failed_replace_preserves_the_previous_complete_set(self): + replace = helper.os.replace + for previous in ( + {}, + { + "archive.a": b"old", + "module.meta": b"old-meta", + "provenance.json": b"old-proof", + }, + ): + for boundary in range(3): + with ( + self.subTest(previous=bool(previous), boundary=boundary), + tempfile.TemporaryDirectory() as temporary, + ): + output = Path(temporary) + for name, data in previous.items(): + (output / name).write_bytes(data) + calls = 0 + + def fail_once(source, destination): + nonlocal calls + calls += 1 + if calls == boundary + 1: + raise OSError("injected publication failure") + return replace(source, destination) + + with patch.object(helper.os, "replace", side_effect=fail_once): + with self.assertRaises(OSError): + helper.publish( + output, + { + "archive.a": b"new", + "module.meta": b"new-meta", + "provenance.json": b"new-proof", + }, + ) + self.assertEqual( + {p.name: p.read_bytes() for p in output.iterdir()}, previous + ) + + def test_symlinks_and_nonlocal_names_do_not_modify_other_files(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + other = root / "other" + other.write_bytes(b"keep") + output = root / "module" + output.mkdir() + for name in ("../other", "nested/file", ".", ".."): + with self.assertRaises(ValueError): + helper.publish(output, {name: b"bad"}) + try: + (output / "archive").symlink_to(other) + except OSError: + self.skipTest("symlinks unavailable") + with self.assertRaises(ValueError): + helper.publish(output, {"archive": b"bad"}) + self.assertEqual(other.read_bytes(), b"keep") + + +class ResultTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + root = Path(temporary.name).resolve() + self.source = root / "role.wave" + self.source.write_bytes(b"source") + self.abi = root / "bridge.rs" + self.abi.write_bytes(b"abi") + self.args = Namespace( + module="asmobj", + vex=root / "vex", + build_dir=root / "vex-build", + state_dir=root / "state", + output_dir=root / "output", + toolchain=root / "toolchain.json", + target="x86_64-unknown-linux-gnu", + profile="dev", + depfile=None, + ) + self.args.vex.write_bytes(b"vex") + self.toolchain = dict( + wavec="/compiler", + std="/std", + source_revision="a" * 40, + compiler_sha256="b" * 64, + std_sha256="c" * 64, + archive_sha256="d" * 64, + ) + self.args.toolchain.write_text(json.dumps(self.toolchain)) + self.generation = self.args.build_dir / "target/.vex-run/123-456" + self.generation.mkdir(parents=True) + lock = self.args.build_dir / ".vex/run-locks/123-456.lock" + lock.parent.mkdir(parents=True) + lock.touch() + self.archive = self.generation / "archive.a" + self.archive.write_bytes(b"!\n") + self.result = dict( + schema="vex.artifact-generation", + schema_version=1, + generation=str(self.generation), + provenance={"portable": "proof"}, + metadata=dict( + artifact_kind="static", + target=self.args.target, + profile={"name": "dev", "opt_level": 0}, + package_target={"name": "whale_asmobj"}, + compiler={ + **{k: self.toolchain[k] for k in ("compiler_sha256", "std_sha256")}, + "compiler_version": "test", + }, + inputs={"files": [], "directories": []}, + ), + artifacts=[ + dict( + path=str(self.archive), + role="primary", + sha256=helper.digest(self.archive), + ) + ], + ) + self.action = None + self.addCleanup(patch.stopall) + patch.object(helper, "inputs", return_value=([self.source], [self.abi])).start() + patch.object( + helper, + "input_hashes", + side_effect=lambda paths: ( + "a" * 16, + hashlib.sha256(b"".join(p.read_bytes() for p in paths)).hexdigest(), + ), + ).start() + patch.object( + helper.subprocess, "check_output", return_value="vex 0.0.3-beta\n" + ).start() + patch.object(helper.subprocess, "run", side_effect=self.invoke).start() + + def invoke(self, command, **kwargs): + if self.action: + self.action() + report = dict(schema="vex.artifacts", schema_version=1, results=[self.result]) + (self.args.build_dir / "result.json").write_text(json.dumps(report)) + + def test_admits_verified_generation_and_records_one_compiler_identity(self): + helper.build(self.args) + proof = json.loads((self.args.output_dir / "provenance.json").read_bytes()) + self.assertEqual(proof["wave_revision"], self.toolchain["source_revision"]) + self.assertEqual(proof["std_sha256"], self.toolchain["std_sha256"]) + self.assertEqual(proof["vex_sha256"], helper.digest(self.args.vex)) + self.assertEqual( + (self.args.output_dir / "libwhale_asmobj.a").read_bytes(), + self.archive.read_bytes(), + ) + + def test_bad_target_profile_package_compiler_and_digest_never_publish(self): + initial = copy.deepcopy(self.result) + for field, value in ( + ("target", "other-host"), + ("profile", {"name": "release", "opt_level": 2}), + ("package_target", {"name": "other"}), + ("artifact_kind", "executable"), + ("compiler", {"compiler_sha256": "e" * 64, "std_sha256": "c" * 64}), + ): + with self.subTest(field=field): + self.result = copy.deepcopy(initial) + self.result["metadata"][field] = value + with self.assertRaises(ValueError): + helper.build(self.args) + self.assertFalse(self.args.output_dir.exists()) + self.result = initial + self.archive.write_bytes(b"corrupt") + with self.assertRaisesRegex(ValueError, "SHA256"): + helper.build(self.args) + self.assertFalse(self.args.output_dir.exists()) + + def test_failed_vex_and_mutated_inputs_preserve_previous_files(self): + self.args.output_dir.mkdir() + previous = self.args.output_dir / "libwhale_asmobj.a" + previous.write_bytes(b"last-good") + actions = [ + lambda: self.source.write_bytes(b"changed"), + lambda: self.abi.write_bytes(b"changed"), + lambda: self.args.vex.write_bytes(b"changed"), + ] + + def fail(): + raise subprocess.CalledProcessError(1, "vex") + + actions.append(fail) + for action in actions: + with self.subTest(action=action): + self.action = action + with self.assertRaises((ValueError, subprocess.CalledProcessError)): + helper.build(self.args) + self.assertEqual(previous.read_bytes(), b"last-good") + self.assertEqual(list(self.args.output_dir.iterdir()), [previous]) + self.source.write_bytes(b"source") + self.abi.write_bytes(b"abi") + self.args.vex.write_bytes(b"vex") + + def test_old_vex_is_rejected_before_compilation(self): + with patch.object( + helper.subprocess, "check_output", return_value="vex 0.0.2-beta" + ): + with self.assertRaisesRegex(ValueError, "v0.0.3"): + helper.build(self.args) + helper.subprocess.run.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_wave_bootstrap.py b/tools/test_wave_bootstrap.py deleted file mode 100644 index 80ee372..0000000 --- a/tools/test_wave_bootstrap.py +++ /dev/null @@ -1,235 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -import io -import json -import os -from pathlib import Path -import subprocess -import tarfile -import tempfile -import unittest -from unittest.mock import patch - -import wave_bootstrap as bootstrap - - -class BootstrapTests(unittest.TestCase): - def setUp(self): - self.temporary = tempfile.TemporaryDirectory() - self.addCleanup(self.temporary.cleanup) - self.root = Path(self.temporary.name).resolve() - self.source = self.root / "Wave" - self.source.mkdir() - self.marker = self.source / "unrelated.wave" - self.marker.write_bytes(b"uncommitted changes stay here") - self.output = self.root / "cache" - self.calls = [] - self.rustc = "rustc 1.89.0 (test)" - self.version = "wavec 0.0.1-alpha-dev (test host)\n backend: LLVM 21.1.8" - self.failure = None - archive = io.BytesIO() - with tarfile.open(fileobj=archive, mode="w") as tree: - for name, data in {"Cargo.toml": b'[package]\nname="wavec"\nversion="0.0.1-alpha-dev"\n', - "Cargo.lock": b"pinned lockfile", "std/base.wave": b"pub const X: u32 = 1;"}.items(): - member = tarfile.TarInfo(name) - member.size = len(data) - tree.addfile(member, io.BytesIO(data)) - self.archive = archive.getvalue() - self.check = patch.object(bootstrap.subprocess, "check_output", side_effect=self.check_output).start() - self.run = patch.object(bootstrap, "run", side_effect=self.run_build).start() - self.addCleanup(patch.stopall) - - def check_output(self, command, **kwargs): - arguments = list(map(str, command)) - self.calls.append(arguments) - if arguments[0] == "git": - self.assertEqual(arguments[1:3], ["-C", str(self.source)]) - self.assertNotIn("checkout", arguments) - self.assertNotIn("reset", arguments) - if "archive" in arguments: - return self.archive - return "a" * 40 if arguments[-1].endswith(":std") else bootstrap.WAVE_REVISION - if arguments[0] == "rustup": - self.assertEqual(arguments[1:], ["which", "--toolchain", "1.89", "rustc"]) - if self.failure == "toolchain": - raise subprocess.CalledProcessError(1, arguments) - return "/installed/rustc" - if arguments[0] == "/installed/rustc": - return self.rustc - self.assertEqual(arguments[1:], ["--version"]) - if self.failure == "version" and "candidate" in arguments[0]: - return "wavec 99.0.0 (wrong)" - return self.version - - def run_build(self, command, **kwargs): - arguments = list(map(str, command)) - self.assertEqual(arguments[:5], ["cargo", "+1.89", "build", "--locked", "--jobs"]) - self.assertNotEqual(kwargs["cwd"], self.source) - self.assertEqual(kwargs["env"]["WAVE_STD_REVISION"], bootstrap.WAVE_REVISION) - self.assertEqual(kwargs["env"]["CARGO_INCREMENTAL"], "0") - self.assertEqual(kwargs["env"]["RUSTUP_AUTO_INSTALL"], "0") - self.assertIn("--bin", arguments) - if self.failure == "build": - raise subprocess.CalledProcessError(1, arguments) - compiler = self.output / "build/debug" / ("wavec.exe" if os.name == "nt" else "wavec") - compiler.parent.mkdir(parents=True, exist_ok=True) - compiler.write_bytes(b"pinned compiler") - compiler.chmod(0o755) - - def ensure(self, **kwargs): - result = bootstrap.ensure_bootstrap(self.source, self.output, rust_toolchain="1.89", **kwargs) - self.assertEqual(self.marker.read_bytes(), b"uncommitted changes stay here") - return result - - def test_build_publishes_compiler_std_and_provenance_as_one_generation(self): - result = self.ensure() - self.assertFalse(result.reused) - self.assertEqual(result.compiler.parent, result.std_root.parent) - self.assertEqual(result.compiler.parent, result.provenance.parent) - self.assertEqual(result.metadata["std_revision"], bootstrap.WAVE_REVISION) - self.assertEqual(result.metadata["std_tree"], "a" * 40) - self.assertEqual(result.metadata["compiler_sha256"], bootstrap.digest(result.compiler)) - self.assertEqual(result.metadata["std_sha256"], bootstrap._std_digest(result.std_root)) - self.assertEqual(result.metadata, json.loads(result.provenance.read_text())) - self.assertIn("--offline", self.run.call_args.args[0]) - self.assertEqual(self.run.call_args.kwargs["env"]["CARGO_NET_OFFLINE"], "true") - self.assertFalse(any(path.name.startswith(".wave-bootstrap-") for path in self.output.iterdir())) - - def test_second_build_validates_and_reuses_cache_without_cargo_or_archive(self): - first = self.ensure() - second = self.ensure() - self.assertTrue(second.reused) - self.assertEqual(first.compiler, second.compiler) - self.assertEqual(self.run.call_count, 1) - self.assertEqual(sum("archive" in call for call in self.calls), 1) - - def test_allow_network_is_explicit_and_never_installs_rust(self): - self.ensure(allow_network=True) - self.assertNotIn("--offline", self.run.call_args.args[0]) - self.assertFalse(any("install" in call for call in self.calls)) - - def test_stage_zero_does_not_inherit_final_host_or_whale_archives(self): - ambient = {"CARGO_BUILD_TARGET": "aarch64-unknown-linux-gnu", - "WHALE_WAVE_ELF_DIR": "/previous/elf", - "WHALE_WAVE_REVERSE_DIR": "/previous/reverse"} - with patch.dict(os.environ, ambient): - self.ensure() - environment = self.run.call_args.kwargs["env"] - for name in ambient: - self.assertNotIn(name, environment) - - def test_compiler_identity_probe_disables_ambient_terminal_colors(self): - def probe(command, **kwargs): - self.assertEqual(command, ["wavec", "--version"]) - self.assertEqual(kwargs["env"]["NO_COLOR"], "1") - self.assertEqual(kwargs["env"]["CLICOLOR"], "0") - self.assertEqual(kwargs["env"]["CLICOLOR_FORCE"], "0") - return self.version - - with patch.dict(os.environ, {"CLICOLOR": "1", "CLICOLOR_FORCE": "1"}): - os.environ.pop("NO_COLOR", None) - with patch.object(bootstrap.subprocess, "check_output", side_effect=probe): - self.assertEqual(bootstrap._compiler_version(Path("wavec")), self.version) - self.assertNotIn("NO_COLOR", os.environ) - self.assertEqual(os.environ["CLICOLOR_FORCE"], "1") - - def test_missing_or_wrong_rust_does_not_build_or_modify_source(self): - self.failure = "toolchain" - with self.assertRaises(subprocess.CalledProcessError): - self.ensure() - self.failure = None - self.rustc = "rustc 1.96.0 (wrong)" - with self.assertRaisesRegex(bootstrap.BootstrapError, "1.89.0"): - self.ensure() - self.run.assert_not_called() - self.assertFalse(self.output.exists()) - - def test_corrupt_compiler_and_std_are_rejected_before_cached_execution(self): - result = self.ensure() - original = result.compiler.read_bytes() - result.compiler.write_bytes(b"corrupt compiler") - self.check.reset_mock() - with self.assertRaisesRegex(bootstrap.BootstrapError, "compiler"): - bootstrap.load_bootstrap(self.output) - self.check.assert_not_called() - result.compiler.write_bytes(original) - (result.std_root / "base.wave").write_bytes(b"changed std") - with self.assertRaisesRegex(bootstrap.BootstrapError, "std"): - bootstrap.load_bootstrap(self.output) - self.check.assert_not_called() - - def test_revision_versions_hashes_and_pointer_paths_are_checked(self): - result = self.ensure() - original = result.provenance.read_text() - for field, value in (("std_revision", "b" * 40), ("wave_revision", "b" * 40), - ("std_tree", "not-a-tree"), ("wave_version", "99"), - ("schema", True), ("compiler_sha256", "bad")): - with self.subTest(field=field): - metadata = json.loads(original) - metadata[field] = value - result.provenance.write_text(json.dumps(metadata)) - with self.assertRaises(bootstrap.BootstrapError): - bootstrap.load_bootstrap(self.output) - result.provenance.write_text(original) - with self.assertRaisesRegex(bootstrap.BootstrapError, "std revision"): - bootstrap.load_bootstrap(self.output, std_tree="b" * 40) - (self.output / bootstrap.POINTER_NAME).write_text('{"schema":1,"generation":"../../Wave"}') - with self.assertRaisesRegex(bootstrap.BootstrapError, "pointer"): - bootstrap.load_bootstrap(self.output) - - def test_failed_rebuild_or_publication_preserves_last_good_generation(self): - first = self.ensure() - pointer = (self.output / bootstrap.POINTER_NAME).read_bytes() - files = {path: path.read_bytes() for path in (first.compiler, first.provenance, first.std_root / "base.wave")} - # A different Rust build identity requires a new generation while the - # pinned Rust release itself remains valid. - self.rustc = "rustc 1.89.0 (different build)" - for failure in ("build", "version", "publication"): - self.failure = failure - replace = os.replace - - def replacement(source, destination): - if failure == "publication" and Path(destination).name == bootstrap.POINTER_NAME: - raise OSError("interrupted publication") - return replace(source, destination) - - with self.subTest(failure=failure), patch.object(bootstrap.os, "replace", side_effect=replacement): - with self.assertRaises((bootstrap.BootstrapError, OSError, subprocess.CalledProcessError)): - self.ensure() - self.assertEqual((self.output / bootstrap.POINTER_NAME).read_bytes(), pointer) - self.assertEqual(list((self.output / "generations").iterdir()), [first.compiler.parent]) - for path, payload in files.items(): - self.assertEqual(path.read_bytes(), payload) - self.assertFalse(any(path.name.startswith(".wave-bootstrap-") for path in self.output.iterdir())) - - def test_failed_first_build_never_publishes_pointer_or_generation(self): - self.failure = "version" - with self.assertRaises(bootstrap.BootstrapError): - self.ensure() - self.assertFalse((self.output / bootstrap.POINTER_NAME).exists()) - self.assertFalse((self.output / "generations").exists()) - - def test_output_inside_read_only_checkout_is_rejected_before_any_commands(self): - with self.assertRaisesRegex(bootstrap.BootstrapError, "outside"): - bootstrap.ensure_bootstrap(self.source, self.source / "cache") - self.check.assert_not_called() - self.run.assert_not_called() - self.assertEqual(list(self.source.iterdir()), [self.marker]) - - def test_symlinked_std_or_build_directory_is_rejected(self): - result = self.ensure() - alias = result.std_root / "alias.wave" - try: - alias.symlink_to(self.marker) - except (OSError, NotImplementedError): - self.skipTest("symlinks unavailable") - with self.assertRaisesRegex(bootstrap.BootstrapError, "special file"): - bootstrap.load_bootstrap(self.output) - shutil = __import__("shutil") - shutil.rmtree(self.output / "build") - (self.output / "build").symlink_to(self.source, target_is_directory=True) - with self.assertRaisesRegex(bootstrap.BootstrapError, "symlinks"): - self.ensure() - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_wave_nightly.py b/tools/test_wave_nightly.py new file mode 100644 index 0000000..051f5d0 --- /dev/null +++ b/tools/test_wave_nightly.py @@ -0,0 +1,263 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Nightly selection, immutable cache integrity and failure preservation.""" + +import copy +import hashlib +import io +import json +from pathlib import Path +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +import wave_nightly as helper + + +def checksum(data): + return hashlib.sha256(data).hexdigest() + + +def distribution(source="a", payload=b"compiler"): + generation = source * 40 + "-123-1" + name = "wave-nightly-" + generation + "-x86_64-linux-gnu.tar.gz" + stream = io.BytesIO() + with tarfile.open(fileobj=stream, mode="w:gz") as archive: + for path, data in { + "wave/wavec": payload, + "wave/std/lib.wave": b"std", + "wave/llvm/bin/ar": b"runtime", + }.items(): + entry = tarfile.TarInfo(path) + entry.size, entry.mode = len(data), 0o755 + archive.addfile(entry, io.BytesIO(data)) + payload = stream.getvalue() + metadata = json.dumps( + dict( + schema_version=1, + channel="nightly", + source_sha=source * 40, + generation=generation, + archive=name, + sha256=checksum(payload), + target="x86_64-unknown-linux-gnu", + paths={"compiler": "wavec", "std": "std"}, + ) + ).encode() + entries = {name: payload, name + ".metadata.json": metadata} + assets = [ + dict( + name=n, + digest="sha256:" + checksum(data), + size=len(data), + browser_download_url=helper.DOWNLOAD_ROOT + n, + ) + for n, data in entries.items() + ] + release = dict( + draft=False, tag_name="nightly", target_commitish=source * 40, assets=assets + ) + return release, entries + + +class NightlyTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.cache, self.output = ( + self.root / "cache", + self.root / "build/toolchain.json", + ) + self.release, self.payloads = distribution() + self.downloads = [] + self.addCleanup(patch.stopall) + patch.object( + helper, + "host_target", + return_value=("x86_64-unknown-linux-gnu", "x86_64-linux-gnu.tar.gz"), + ).start() + self.probe = patch.object(helper, "probe").start() + patch.object(helper, "download", side_effect=self.download).start() + + def download(self, url, destination, maximum): + self.downloads.append(url) + data = ( + json.dumps(self.release).encode() + if url == helper.RELEASE_URL + else self.payloads[url.removeprefix(helper.DOWNLOAD_ROOT)] + ) + self.assertLessEqual(len(data), maximum) + destination.write_bytes(data) + + def prepare(self, offline=False): + return helper.prepare(self.cache, self.output, offline) + + def test_success_records_exact_generation_and_verifies_cache_before_offline_reuse( + self, + ): + first = self.prepare() + self.assertEqual(first["source_revision"], "a" * 40) + self.assertEqual(first["compiler_sha256"], checksum(b"compiler")) + before, mtime = self.output.read_bytes(), self.output.stat().st_mtime_ns + self.downloads.clear() + self.assertEqual(self.prepare(True), first) + self.assertEqual(self.downloads, []) + self.assertEqual(self.output.read_bytes(), before) + self.assertEqual(self.output.stat().st_mtime_ns, mtime) + + def test_new_nightly_keeps_the_old_generation_and_updates_only_this_build_snapshot( + self, + ): + first = self.prepare() + separate = self.root / "other-build.json" + separate.write_bytes(self.output.read_bytes()) + self.release, self.payloads = distribution("b", b"new compiler") + second = self.prepare() + self.assertNotEqual(first["archive_sha256"], second["archive_sha256"]) + self.assertTrue(Path(first["wavec"]).is_file()) + self.assertEqual(json.loads(separate.read_bytes()), first) + self.assertEqual(json.loads(self.output.read_bytes()), second) + + def test_resolution_queries_the_moving_release_once_per_build(self): + first_download = self.download + + def moving(url, destination, maximum): + first_download(url, destination, maximum) + if url == helper.RELEASE_URL: + self.release = distribution("b")[0] + + with patch.object(helper, "download", side_effect=moving): + result = self.prepare() + self.assertEqual(result["source_revision"], "a" * 40) + self.assertEqual(self.downloads.count(helper.RELEASE_URL), 1) + + def test_changed_compiler_std_or_runtime_is_rejected_before_cached_execution(self): + record = self.prepare() + distribution_root = Path(record["wavec"]).parent + for relative in ("wavec", "std/lib.wave", "llvm/bin/ar"): + with self.subTest(relative=relative): + path = distribution_root / relative + previous, report = path.read_bytes(), self.output.read_bytes() + path.write_bytes(b"tampered") + self.probe.reset_mock() + try: + with self.assertRaisesRegex(ValueError, "files changed"): + self.prepare(True) + self.probe.assert_not_called() + self.assertEqual(self.output.read_bytes(), report) + finally: + path.write_bytes(previous) + + def test_download_or_capability_failure_preserves_previous_pointer_and_output(self): + self.prepare() + before = self.output.read_bytes(), (self.cache / "nightly.json").read_bytes() + for failure in ("download", "capabilities"): + with self.subTest(failure=failure): + self.release, self.payloads = distribution("b", b"new") + if failure == "download": + archive = self.release["assets"][0]["name"] + self.payloads[archive] += b"corrupt" + self.probe.side_effect = ( + ValueError("unsupported capabilities") + if failure == "capabilities" + else None + ) + with self.assertRaises(ValueError): + self.prepare() + self.assertEqual( + ( + self.output.read_bytes(), + (self.cache / "nightly.json").read_bytes(), + ), + before, + ) + + def test_first_failure_never_publishes_a_ready_toolchain(self): + self.probe.side_effect = ValueError("unsupported compiler") + with self.assertRaises(ValueError): + self.prepare() + self.assertFalse(self.output.exists()) + self.assertFalse((self.cache / "nightly.json").exists()) + + def test_offline_requires_a_matching_prepared_host(self): + with self.assertRaises(ValueError): + self.prepare(True) + self.prepare() + with patch.object( + helper, "host_target", return_value=("aarch64-unknown-linux-gnu", "unused") + ): + with self.assertRaisesRegex(ValueError, "another executable host"): + self.prepare(True) + + def test_ambiguous_malformed_and_unverified_release_assets_fail(self): + bad = [ + dict(self.release, draft=True), + dict(self.release, assets=[]), + dict( + self.release, + assets=[*self.release["assets"], self.release["assets"][0]], + ), + dict(self.release, target_commitish="b" * 40), + ] + changed = copy.deepcopy(self.release) + changed["assets"][0]["digest"] = None + bad.append(changed) + changed = copy.deepcopy(self.release) + changed["assets"][0]["browser_download_url"] = "https://example.com/compiler" + bad.append(changed) + for release in bad: + with self.subTest(release=release), self.assertRaises(ValueError): + helper.select_assets(release, "x86_64-linux-gnu.tar.gz") + + def test_metadata_source_and_paths_are_validated_before_archive_execution(self): + name = self.release["assets"][1]["name"] + original = json.loads(self.payloads[name]) + for details in ( + [], + dict(original, source_sha="b" * 40), + dict(original, paths={"compiler": "../outside", "std": "std"}), + ): + with self.subTest(details=details): + data = json.dumps(details).encode() + self.payloads[name] = data + self.release["assets"][1].update( + digest="sha256:" + checksum(data), size=len(data) + ) + with self.assertRaises(ValueError): + self.prepare() + self.probe.assert_not_called() + + def test_cache_metadata_cannot_redirect_compiler_outside_its_generation(self): + self.prepare() + pointer = helper.read_json(self.cache / "nightly.json") + pointer["compiler"] = "../outside" + helper.publish_json(self.cache / "nightly.json", pointer) + with self.assertRaisesRegex(ValueError, "compiler/std path"): + self.prepare(True) + + def test_archive_traversal_links_duplicates_and_multiple_roots_are_rejected(self): + for names, linked in ( + (["../outside"], False), + (["wave/link"], True), + (["wave/file", "wave/file"], False), + (["one/file", "two/file"], False), + ): + with ( + self.subTest(names=names), + tempfile.TemporaryDirectory(dir=self.root) as temporary, + ): + archive = Path(temporary) / "test.tar" + with tarfile.open(archive, "w") as source: + for name in names: + entry = tarfile.TarInfo(name) + entry.type = tarfile.SYMTYPE if linked else tarfile.REGTYPE + entry.linkname = "/outside" if linked else "" + entry.size = 0 + source.addfile(entry, io.BytesIO()) + with self.assertRaises((ValueError, FileExistsError)): + helper.unpack(archive, Path(temporary) / "output") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/vex_module.py b/tools/vex_module.py new file mode 100644 index 0000000..2d64d89 --- /dev/null +++ b/tools/vex_module.py @@ -0,0 +1,339 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Link Vex's verified Wave results to Whale's existing Cargo data bindings.""" + +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import time + +from wave_modules import MODULES, ROOT, fnv64, input_hashes, inputs +from wave_nightly import digest, publish_json, read_json + + +def environment(toolchain): + return dict(os.environ, VEX_WAVEC=toolchain["wavec"], VEX_WAVE_STD=toolchain["std"]) + + +def command(vex, build, state): + return [ + str(vex), + "--manifest-path", + str(ROOT / "vex.ws"), + "--build-dir", + str(build), + "--state-dir", + str(state), + ] + + +def vex_identity(vex): + version = subprocess.check_output([str(vex), "--version"], text=True).strip() + match = re.fullmatch(r"vex (\d+)\.(\d+)\.(\d+)(?:-[A-Za-z0-9.-]+)?", version) + if not match or tuple(map(int, match.groups())) < (0, 0, 3): + raise ValueError("Vex v0.0.3-beta or newer is required") + return version, digest(vex.resolve()) + + +@contextmanager +def generation_lease(build, generation): + """Vex v0.0.3-beta's documented generation lease (MPL-2.0). + + Adapted from wavefnd/Vex tools/meson_consumer.py at v0.0.3-beta. + """ + if ( + generation.parent != build / "target/.vex-run" + or not generation.name + or any(c not in "0123456789-" for c in generation.name) + ): + raise ValueError("invalid Vex artifact generation") + lock = build / ".vex/run-locks" / (generation.name + ".lock") + if lock.is_symlink() or not lock.is_file(): + raise ValueError("missing Vex generation lease") + if os.name == "nt": + import ctypes + from ctypes import wintypes + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.CreateFileW.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ] + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + deadline = time.monotonic() + 30 + while True: + handle = kernel.CreateFileW( + str(lock), 0x80000000, 1, None, 3, 0x00200000, None + ) + if handle != wintypes.HANDLE(-1).value: + break + code = ctypes.get_last_error() + if code != 32 or time.monotonic() >= deadline: + raise OSError(code, "cannot lease Vex artifact generation") + time.sleep(0.04) + try: + yield + finally: + kernel.CloseHandle(handle) + else: + import fcntl + + descriptor = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW) + try: + fcntl.flock(descriptor, fcntl.LOCK_SH) + yield + finally: + os.close(descriptor) + + +def publish(output, files): + """Stage the entire binding set before replacing any prior good file.""" + output.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".vex-module-", dir=output) as temporary: + temporary = Path(temporary) + changed = [] + for name, data in files.items(): + if Path(name).name != name or name in (".", ".."): + raise ValueError("module output names must be plain filenames") + destination = output / name + if destination.is_symlink(): + raise ValueError("module outputs must not be symlinks") + if destination.exists() and destination.read_bytes() == data: + continue + (temporary / name).write_bytes(data) + if destination.exists(): + shutil.copyfile(destination, temporary / (name + ".previous")) + changed.append(name) + published = [] + try: + for name in changed: + os.replace(temporary / name, output / name) + published.append(name) + except OSError: + for name in reversed(published): + previous = temporary / (name + ".previous") + if previous.exists(): + os.replace(previous, output / name) + else: + (output / name).unlink() + raise + + +def escape(path): + text = str(path) + if any(c in text for c in "\r\n\0"): + raise ValueError("depfile cannot represent this path") + return ( + text.replace("\\", "\\\\") + .replace("$", "$$") + .replace(" ", "\\ ") + .replace("#", "\\#") + .replace(":", "\\:") + ) + + +def build(args): + toolchain = read_json(args.toolchain) + version, vex_hash = vex_identity(args.vex) + _, package, variable = MODULES[args.module] + sources, abi = inputs(args.module) + before = input_hashes(sources), input_hashes(abi) + report = args.build_dir / "result.json" + args.build_dir.mkdir(parents=True, exist_ok=True) + wave_target = args.target.replace("riscv64gc-", "riscv64-") + invoke = command(args.vex, args.build_dir, args.state_dir) + invoke += [ + "-p", + package, + "build", + "--lib", + "--locked", + "--offline", + "--target", + wave_target, + "--profile", + args.profile, + "--artifact-manifest", + str(report), + "--depfile", + str(args.build_dir / "inputs.d"), + ] + subprocess.run(invoke, env=environment(toolchain), check=True) + value = read_json(report) + if ( + value.get("schema") != "vex.artifacts" + or value.get("schema_version") != 1 + or len(value.get("results", [])) != 1 + ): + raise ValueError("expected one completed Vex library result") + result = value["results"][0] + details = result["metadata"] + if ( + result.get("schema") != "vex.artifact-generation" + or result.get("schema_version") != 1 + or details["artifact_kind"] != "static" + or details["target"] != wave_target + or details["profile"] + != {"name": args.profile, "opt_level": 0 if args.profile == "dev" else 2} + or details["package_target"]["name"] != package + ): + raise ValueError("Vex result differs from the selected module/target/profile") + compiler = details["compiler"] + if ( + compiler["compiler_sha256"] != toolchain["compiler_sha256"] + or compiler["std_sha256"] != toolchain["std_sha256"] + ): + raise ValueError("Vex did not use the build's selected compiler/std snapshot") + after_sources, after_abi = inputs(args.module) + if before != (input_hashes(after_sources), input_hashes(after_abi)): + raise ValueError("module source or Rust ABI changed during compilation") + if vex_hash != digest(args.vex.resolve()): + raise ValueError("Vex executable changed during compilation") + library = package + ".lib" if "msvc" in args.target else "lib" + package + ".a" + generation = Path(result["generation"]) + with generation_lease(args.build_dir, generation): + primary = [] + for artifact in result["artifacts"]: + path = Path(artifact["path"]) + if ( + not path.is_relative_to(generation) + or ".." in path.parts + or path.is_symlink() + or digest(path) != artifact["sha256"] + ): + raise ValueError("Vex artifact failed generation/SHA256 validation") + if artifact["role"] == "primary": + primary.append(path) + if len(primary) != 1: + raise ValueError("expected one verified static library") + archive = primary[0].read_bytes() + source_hash, abi_hash = before + portable = json.dumps( + result["provenance"], sort_keys=True, separators=(",", ":") + ).encode() + provenance = dict( + wave_revision=toolchain["source_revision"], + target=args.target, + opt_level="0" if args.profile == "dev" else "2", + source_sha256=source_hash[1], + abi_sha256=abi_hash[1], + archive_sha256=hashlib.sha256(archive).hexdigest(), + compiler_sha256=compiler["compiler_sha256"], + std_sha256=compiler["std_sha256"], + compiler_version=compiler["compiler_version"], + nightly_archive_sha256=toolchain["archive_sha256"], + vex_version=version, + vex_sha256=vex_hash, + vex_provenance_sha256=hashlib.sha256(portable).hexdigest(), + ) + provenance_bytes = ( + json.dumps(provenance, sort_keys=True, indent=2) + "\n" + ).encode() + metadata = dict( + schema="3", + target=args.target, + wave_revision=toolchain["source_revision"], + opt_level=provenance["opt_level"], + source_fnv64=source_hash[0], + abi_fnv64=abi_hash[0], + archive_fnv64=fnv64([archive]), + provenance_fnv64=fnv64([provenance_bytes]), + ) + files = { + library: archive, + "provenance.json": provenance_bytes, + "module.meta": "".join( + f"{key}={value}\n" for key, value in metadata.items() + ).encode(), + } + if args.depfile: + dependencies = [ + *sources, + *abi, + args.toolchain.resolve(), + Path(__file__).resolve(), + ROOT / "tools/wave_modules.py", + *map(Path, details["inputs"]["files"]), + *map(Path, details["inputs"]["directories"]), + ] + depfile = ( + escape(args.output_dir / library) + + ": " + + " ".join(escape(path) for path in sorted(set(dependencies))) + + "\n" + ) + # Meson supplies a sibling depfile in this module's output directory. + if args.depfile.parent != args.output_dir: + raise ValueError("module depfile must be in its output directory") + files[args.depfile.name] = depfile.encode() + publish(args.output_dir, files) + print(f"{variable}={args.output_dir}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--module", choices=MODULES) + parser.add_argument("--prepare", action="store_true") + parser.add_argument("--vex", type=Path, required=True) + parser.add_argument("--toolchain", type=Path, required=True) + parser.add_argument("--build-dir", type=Path, required=True) + parser.add_argument("--state-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--ready", type=Path) + parser.add_argument("--depfile", type=Path) + parser.add_argument("--target", default="x86_64-unknown-linux-gnu") + parser.add_argument("--profile", choices=("dev", "release"), default="dev") + args = parser.parse_args() + for name in ("toolchain", "build_dir", "state_dir", "output_dir", "depfile"): + value = getattr(args, name) + if value is not None: + setattr(args, name, value.absolute()) + try: + if args.prepare: + vex_identity(args.vex) + subprocess.run( + command(args.vex, args.build_dir, args.state_dir) + + ["fetch", "--locked", "--offline"], + env=environment(read_json(args.toolchain)), + check=True, + ) + if args.ready: + publish_json( + args.ready, + dict( + toolchain=read_json(args.toolchain), + vex_sha256=digest(args.vex.resolve()), + lock_sha256=digest(ROOT / "vex.lock"), + ), + ) + else: + if args.module is None or args.output_dir is None: + parser.error( + "--module and --output-dir are required for a library build" + ) + build(args) + except ( + OSError, + ValueError, + KeyError, + TypeError, + subprocess.SubprocessError, + ) as error: + parser.exit(1, f"Wave module build failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/wave_bootstrap.py b/tools/wave_bootstrap.py deleted file mode 100644 index 6ec7c1c..0000000 --- a/tools/wave_bootstrap.py +++ /dev/null @@ -1,276 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -"""Build and reuse the pinned Wave compiler and std without editing its checkout. - -The default is offline. The cache publishes one immutable compiler/std/provenance -directory, then atomically replaces a small pointer file. No module registry or -SDK is involved; ordinary internal Wave build rules consume the returned paths. -""" - -import argparse -from dataclasses import dataclass -import hashlib -import io -import json -import os -from pathlib import Path -import platform -import re -import shutil -import stat -import subprocess -import tarfile -import tempfile -import uuid - - -WAVE_REVISION = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b" -WAVE_VERSION = "0.0.1-alpha-dev" -RUST_VERSION = "1.89.0" -DEFAULT_RUST_TOOLCHAIN = "1.89.0" -CACHE_SCHEMA = 1 -POINTER_NAME = "bootstrap.json" -PROVENANCE_NAME = "provenance.json" - - -class BootstrapError(ValueError): - pass - - -@dataclass(frozen=True) -class Bootstrap: - compiler: Path - std_root: Path - provenance: Path - metadata: dict - reused: bool - - def paths(self): - return {"compiler": str(self.compiler), "std_root": str(self.std_root), - "provenance": str(self.provenance), "wave_revision": WAVE_REVISION, - "reused": self.reused} - - -def run(arguments, **kwargs): - subprocess.run(list(map(str, arguments)), check=True, **kwargs) - - -def digest(path): - result = hashlib.sha256() - with Path(path).open("rb") as source: - for chunk in iter(lambda: source.read(1024 * 1024), b""): - result.update(chunk) - return result.hexdigest() - - -def _std_digest(root): - """Hash sorted relative names and payloads; never follow cache symlinks.""" - root = Path(root) - if root.is_symlink() or not root.is_dir(): - raise BootstrapError("cached Wave std must be a regular directory") - result = hashlib.sha256() - count = total = 0 - for directory, directories, files in os.walk(root, followlinks=False): - directories.sort() - files.sort() - for name in directories: - if (Path(directory) / name).is_symlink(): - raise BootstrapError("cached Wave std contains a symlink") - for name in files: - path = Path(directory) / name - metadata = path.lstat() - if not stat.S_ISREG(metadata.st_mode): - raise BootstrapError("cached Wave std contains a special file") - count += 1 - total += metadata.st_size - if count > 8192 or total > 64 * 1024 * 1024: - raise BootstrapError("cached Wave std exceeds the bootstrap validation limit") - relative = path.relative_to(root).as_posix().encode("utf-8") - result.update(len(relative).to_bytes(4, "little")) - result.update(relative) - result.update(metadata.st_size.to_bytes(8, "little")) - result.update(bytes.fromhex(digest(path))) - if count == 0: - raise BootstrapError("cached Wave std is empty") - return result.hexdigest() - - -def _read_json(path, maximum): - if path.is_symlink() or not path.is_file() or path.stat().st_size > maximum: - raise BootstrapError("invalid or oversized bootstrap metadata") - try: - with path.open("rb") as source: - data = source.read(maximum + 1) - if len(data) > maximum: - raise BootstrapError("oversized bootstrap metadata") - return json.loads(data) - except (OSError, ValueError, UnicodeError, RecursionError) as error: - raise BootstrapError("invalid bootstrap metadata") from error - - -def _compiler_version(compiler): - environment = os.environ.copy() - environment.update(NO_COLOR="1", CLICOLOR="0", CLICOLOR_FORCE="0") - version = subprocess.check_output([str(compiler), "--version"], text=True, env=environment).strip() - if not version.startswith("wavec " + WAVE_VERSION + " ("): - raise BootstrapError(f"expected pinned Wave compiler version {WAVE_VERSION}") - return version - - -def _host(): - return platform.system().lower() + "-" + platform.machine().lower() - - -def load_bootstrap(out_dir, *, rustc=None, std_tree=None): - """Validate a published cache before returning executable/compiler paths.""" - output = Path(out_dir).resolve() - pointer = _read_json(output / POINTER_NAME, 4096) - if (not isinstance(pointer, dict) or set(pointer) != {"schema", "generation"} - or type(pointer["schema"]) is not int or pointer["schema"] != CACHE_SCHEMA - or not isinstance(pointer["generation"], str) - or not re.fullmatch(r"[a-f0-9]{32}", pointer["generation"])): - raise BootstrapError("invalid bootstrap cache pointer") - generation = output / "generations" / pointer["generation"] - if (output / "generations").is_symlink() or generation.is_symlink(): - raise BootstrapError("bootstrap generation must not be a symlink") - provenance = generation / PROVENANCE_NAME - metadata = _read_json(provenance, 16384) - required = {"schema", "wave_revision", "wave_version", "std_revision", "std_tree", - "std_sha256", "rustc", "rust_toolchain", "host", "compiler_version", - "compiler_sha256", "source_archive_sha256"} - if not isinstance(metadata, dict) or set(metadata) != required: - raise BootstrapError("invalid bootstrap provenance schema") - if (type(metadata["schema"]) is not int or metadata["schema"] != CACHE_SCHEMA - or metadata["wave_revision"] != WAVE_REVISION - or metadata["std_revision"] != WAVE_REVISION - or metadata["wave_version"] != WAVE_VERSION or metadata["host"] != _host() - or not isinstance(metadata["rustc"], str) - or not metadata["rustc"].startswith("rustc " + RUST_VERSION + " ") - or (rustc is not None and metadata["rustc"] != rustc) - or (std_tree is not None and metadata["std_tree"] != std_tree)): - raise BootstrapError("stale Wave compiler, Rust compiler or std revision in cache") - for field in ("std_sha256", "compiler_sha256", "source_archive_sha256"): - if not isinstance(metadata[field], str) or not re.fullmatch(r"[a-f0-9]{64}", metadata[field]): - raise BootstrapError("invalid bootstrap provenance digest") - if (not isinstance(metadata["std_tree"], str) - or not re.fullmatch(r"[a-f0-9]{40}", metadata["std_tree"]) - or not isinstance(metadata["rust_toolchain"], str) - or not metadata["rust_toolchain"]): - raise BootstrapError("invalid bootstrap compiler/std identity") - compiler = generation / ("wavec.exe" if os.name == "nt" else "wavec") - if compiler.is_symlink() or not compiler.is_file() or digest(compiler) != metadata["compiler_sha256"]: - raise BootstrapError("corrupt cached Wave compiler") - std_root = generation / "std" - if _std_digest(std_root) != metadata["std_sha256"]: - raise BootstrapError("corrupt cached Wave std") - # Hash and std checks precede execution of any cached compiler. - if _compiler_version(compiler) != metadata["compiler_version"]: - raise BootstrapError("cached Wave compiler version changed") - return Bootstrap(compiler, std_root, provenance, metadata, True) - - -def ensure_bootstrap(wave_source, out_dir, *, rust_toolchain=DEFAULT_RUST_TOOLCHAIN, - allow_network=False): - """Reuse a valid cache or build from git archive of the immutable pin.""" - repository = Path(wave_source).resolve() - output = Path(out_dir).resolve() - if output == repository or output.is_relative_to(repository): - raise BootstrapError("bootstrap output must be outside the read-only Wave checkout") - revision = subprocess.check_output( - ["git", "-C", str(repository), "rev-parse", WAVE_REVISION + "^{commit}"], text=True).strip() - if revision != WAVE_REVISION: - raise BootstrapError("Wave repository does not contain the pinned immutable commit") - std_tree = subprocess.check_output( - ["git", "-C", str(repository), "rev-parse", WAVE_REVISION + ":std"], text=True).strip() - if not re.fullmatch(r"[a-f0-9]{40}", std_tree): - raise BootstrapError("invalid pinned Wave std tree") - # `rustup which` never installs a missing toolchain. Do not let an implicit - # rustup download precede Cargo's explicit offline policy. - rustc_path = subprocess.check_output( - ["rustup", "which", "--toolchain", rust_toolchain, "rustc"], text=True).strip() - rustc = subprocess.check_output([rustc_path, "--version"], text=True).strip() - if not rustc.startswith("rustc " + RUST_VERSION + " "): - raise BootstrapError("the pinned Wave compiler requires installed Rust 1.89.0") - output.mkdir(parents=True, exist_ok=True) - if any((output / name).is_symlink() for name in ("build", "generations")): - raise BootstrapError("bootstrap build/cache directories must not be symlinks") - if (output / POINTER_NAME).exists(): - try: - return load_bootstrap(output, rustc=rustc, std_tree=std_tree) - except (BootstrapError, OSError, subprocess.SubprocessError): - # An invalid cache is rebuilt from the pin; its current generation - # remains untouched until the replacement is completely validated. - pass - environment = os.environ.copy() - # Stage 0 runs on this build machine; final Whale host selections and - # optional Whale archives must not leak into the compiler bootstrap. - environment.pop("CARGO_BUILD_TARGET", None) - environment.pop("WHALE_WAVE_ELF_DIR", None) - environment.pop("WHALE_ASMOBJ_DIR", None) - environment.pop("WHALE_WAVE_REVERSE_DIR", None) - environment.update(WAVE_STD_REVISION=WAVE_REVISION, CARGO_INCREMENTAL="0", RUSTUP_AUTO_INSTALL="0") - if not allow_network: - environment["CARGO_NET_OFFLINE"] = "true" - archive = subprocess.check_output( - ["git", "-C", str(repository), "archive", "--format=tar", WAVE_REVISION]) - with tempfile.TemporaryDirectory(prefix=".wave-bootstrap-", dir=output) as temporary: - temporary = Path(temporary) - source = temporary / "source" - source.mkdir() - with tarfile.open(fileobj=io.BytesIO(archive)) as tree: - tree.extractall(source, filter="data") - command = ["cargo", "+" + rust_toolchain, "build", "--locked", "--jobs", "2", - "--manifest-path", source / "Cargo.toml", "--target-dir", output / "build", "--bin", "wavec"] - if not allow_network: - command.append("--offline") - run(command, cwd=source, env=environment) - built = output / "build/debug" / ("wavec.exe" if os.name == "nt" else "wavec") - candidate = temporary / "candidate" - candidate.mkdir() - compiler = candidate / built.name - shutil.copy2(built, compiler) - shutil.copytree(source / "std", candidate / "std") - compiler_version = _compiler_version(compiler) - metadata = { - "schema": CACHE_SCHEMA, "wave_revision": WAVE_REVISION, - "wave_version": WAVE_VERSION, "std_revision": WAVE_REVISION, - "std_tree": std_tree, "std_sha256": _std_digest(candidate / "std"), - "rustc": rustc, "rust_toolchain": rust_toolchain, "host": _host(), - "compiler_version": compiler_version, "compiler_sha256": digest(compiler), - "source_archive_sha256": hashlib.sha256(archive).hexdigest(), - } - (candidate / PROVENANCE_NAME).write_text(json.dumps(metadata, indent=2) + "\n") - generation_id = uuid.uuid4().hex - generations = output / "generations" - generations.mkdir(exist_ok=True) - generation = generations / generation_id - pointer = temporary / POINTER_NAME - pointer.write_text(json.dumps({"schema": CACHE_SCHEMA, "generation": generation_id}) + "\n") - os.replace(candidate, generation) - try: - os.replace(pointer, output / POINTER_NAME) - except OSError: - shutil.rmtree(generation) - raise - return Bootstrap(generation / built.name, generation / "std", - generation / PROVENANCE_NAME, metadata, False) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--wave-source", required=True, type=Path) - parser.add_argument("--out-dir", required=True, type=Path) - parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) - parser.add_argument("--allow-network", action="store_true", - help="explicitly permit Cargo dependency downloads; Rust must already be installed") - args = parser.parse_args() - try: - result = ensure_bootstrap(args.wave_source, args.out_dir, - rust_toolchain=args.rust_toolchain, allow_network=args.allow_network) - except (BootstrapError, OSError, subprocess.SubprocessError, tarfile.TarError) as error: - parser.exit(1, f"Wave bootstrap failed: {error}\n") - print(json.dumps(result.paths(), sort_keys=True)) - - -if __name__ == "__main__": - main() diff --git a/tools/wave_modules.py b/tools/wave_modules.py new file mode 100644 index 0000000..f5f60d7 --- /dev/null +++ b/tools/wave_modules.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Explicit internal Wave packages and their Rust data bindings.""" + +import hashlib +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +MODULES = { + "asmobj": ("assembler/asmobj", "whale_asmobj", "WHALE_ASMOBJ_DIR"), + "assembler": ("assembler", "whale_wave_assembler", "WHALE_WAVE_ASSEMBLER_DIR"), + "amd64": ("assembler/amd64", "whale_wave_amd64", "WHALE_WAVE_AMD64_DIR"), + "aarch64": ("assembler/aarch64", "whale_wave_aarch64", "WHALE_WAVE_AARCH64_DIR"), + "riscv64": ("assembler/riscv64", "whale_wave_riscv64", "WHALE_WAVE_RISCV64_DIR"), + "loongarch64": ( + "assembler/loongarch64", + "whale_wave_loongarch64", + "WHALE_WAVE_LOONGARCH64_DIR", + ), + "ir": ("ir", "whale_wave_ir", "WHALE_WAVE_IR_DIR"), +} +ASSEMBLERS = ("amd64", "aarch64", "riscv64", "loongarch64") + + +def inputs(module, root=ROOT): + directory = MODULES[module][0] + directories = [directory, "assembler"] if module in ASSEMBLERS else [directory] + sources = [root / "vex.ws", root / "vex.lock"] + for directory in directories: + sources += [ + root / directory / "vex.ws", + *(root / directory / "src").rglob("*.wave"), + ] + binding = root / "bindings/rust" / module + abi = [binding / "Cargo.toml", *(binding / "src").rglob("*.rs")] + return sorted(set(sources)), sorted(set(abi)) + + +def input_bytes(paths, root=ROOT): + for path in sorted(set(paths)): + yield path.relative_to(root).as_posix().encode() + b"\0" + yield path.read_bytes() + yield b"\0" + + +def fnv64(chunks): + value = 0xCBF29CE484222325 + for chunk in chunks: + for byte in chunk: + value = ((value ^ byte) * 0x100000001B3) & ((1 << 64) - 1) + return f"{value:016x}" + + +def input_hashes(paths, root=ROOT): + sha = hashlib.sha256() + for chunk in input_bytes(paths, root): + sha.update(chunk) + return fnv64(input_bytes(paths, root)), sha.hexdigest() diff --git a/tools/wave_nightly.py b/tools/wave_nightly.py new file mode 100644 index 0000000..c9d92c6 --- /dev/null +++ b/tools/wave_nightly.py @@ -0,0 +1,382 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Resolve one verified Wave nightly generation for a complete Meson build.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import platform +import re +import shutil +import stat +import subprocess +import tarfile +import tempfile +import urllib.request +import zipfile + + +RELEASE_URL = "https://api.github.com/repos/wavefnd/Wave/releases/tags/nightly" +DOWNLOAD_ROOT = "https://github.com/wavefnd/Wave/releases/download/nightly/" +MAX_ARCHIVE = 512 * 1024 * 1024 +MAX_UNPACKED = 2 * 1024 * 1024 * 1024 + + +def digest(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +def publish_json(path, value): + data = (json.dumps(value, indent=2, sort_keys=True) + "\n").encode() + path.parent.mkdir(parents=True, exist_ok=True) + if path.is_file() and not path.is_symlink() and path.read_bytes() == data: + return + with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as temporary: + pending = Path(temporary.name) + temporary.write(data) + temporary.flush() + os.fsync(temporary.fileno()) + try: + os.replace(pending, path) + finally: + pending.unlink(missing_ok=True) + + +def read_json(path): + if path.is_symlink() or not path.is_file() or path.stat().st_size > 8 * 1024 * 1024: + raise ValueError(f"invalid toolchain metadata: {path}") + return json.loads(path.read_bytes()) + + +def host_target(): + machine = {"amd64": "x86_64", "arm64": "aarch64"}.get( + platform.machine().lower(), platform.machine().lower() + ) + system = platform.system().lower() + if system == "linux" and machine in ("x86_64", "aarch64", "riscv64", "loongarch64"): + return machine + "-unknown-linux-gnu", machine + "-linux-gnu.tar.gz" + if system == "darwin" and machine in ("x86_64", "aarch64"): + return machine + "-apple-darwin", machine + "-apple-darwin.tar.gz" + if system == "windows" and machine in ("x86_64", "aarch64"): + return machine + "-pc-windows-msvc", machine + "-pc-windows-msvc.zip" + if system == "freebsd" and machine == "x86_64": + return "x86_64-unknown-freebsd", "x86_64-unknown-freebsd.tar.gz" + raise ValueError(f"no Wave nightly host mapping for {system}/{machine}") + + +def download(url, destination, maximum): + request = urllib.request.Request( + url, + headers={ + "User-Agent": "Whale-build", + "Accept": "application/vnd.github+json" + if url == RELEASE_URL + else "application/octet-stream", + }, + ) + with ( + urllib.request.urlopen(request, timeout=60) as response, + destination.open("wb") as output, + ): + if not response.url.startswith("https://"): + raise ValueError("Wave download redirected away from HTTPS") + count = 0 + while chunk := response.read(65536): + count += len(chunk) + if count > maximum: + raise ValueError("Wave download exceeds its size limit") + output.write(chunk) + + +def asset_fields(asset): + name = asset.get("name") + checksum = asset.get("digest") + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", name): + raise ValueError("invalid Wave asset name") + if not isinstance(checksum, str) or not re.fullmatch( + r"sha256:[0-9a-f]{64}", checksum + ): + raise ValueError("Wave asset requires a published SHA256 digest") + url = DOWNLOAD_ROOT + name + if asset.get("browser_download_url") != url or type(asset.get("size")) is not int: + raise ValueError("invalid Wave asset origin or size") + return name, checksum[7:], url + + +def select_assets(release, suffix): + if ( + not isinstance(release, dict) + or release.get("draft") is not False + or release.get("tag_name") != "nightly" + ): + raise ValueError("expected a published Wave nightly release") + assets = release.get("assets") + if not isinstance(assets, list) or any(not isinstance(x, dict) for x in assets): + raise ValueError("invalid Wave nightly asset list") + pattern = r"wave-nightly-([0-9a-f]{40})-([0-9]+)-([0-9]+)-" + re.escape(suffix) + matches = [ + (x, re.fullmatch(pattern, x.get("name", ""))) + for x in assets + if isinstance(x.get("name"), str) + ] + matches = [(x, match) for x, match in matches if match] + if len(matches) != 1: + raise ValueError(f"expected one Wave nightly archive for {suffix}") + archive, match = matches[0] + name, checksum, url = asset_fields(archive) + metadata = [x for x in assets if x.get("name") == name + ".metadata.json"] + if len(metadata) != 1: + raise ValueError("Wave nightly requires matching artifact metadata") + asset_fields(metadata[0]) + if not 0 < archive["size"] <= MAX_ARCHIVE or not 0 < metadata[0]["size"] <= 65536: + raise ValueError("invalid Wave nightly asset size") + source = match[1] + if release.get("target_commitish") not in (source, "master"): + raise ValueError("Wave nightly source does not match its archive") + return archive, metadata[0], source, "-".join(match.groups()) + + +def fetch_asset(asset, destination, maximum): + _, checksum, url = asset_fields(asset) + download(url, destination, maximum) + if destination.stat().st_size != asset["size"] or digest(destination) != checksum: + raise ValueError("Wave nightly asset failed size/SHA256 verification") + + +def unpack(archive, output): + """Extract regular payloads only; no archive-provided links or permissions.""" + count = total = 0 + roots = set() + + def destination(name, size): + nonlocal count, total + path = PurePosixPath(name) + if ( + path.is_absolute() + or ".." in path.parts + or not path.parts + or "\\" in name + or ":" in name + ): + raise ValueError("invalid Wave archive path") + count += 1 + total += size + if count > 32768 or size < 0 or total > MAX_UNPACKED: + raise ValueError("Wave archive exceeds extraction limits") + roots.add(path.parts[0]) + result = output.joinpath(*path.parts) + result.parent.mkdir(parents=True, exist_ok=True) + return result + + if zipfile.is_zipfile(archive): + with zipfile.ZipFile(archive) as source: + for entry in source.infolist(): + mode = entry.external_attr >> 16 + if entry.is_dir(): + destination(entry.filename, 0).mkdir(exist_ok=True) + elif stat.S_IFMT(mode) not in (0, stat.S_IFREG): + raise ValueError("Wave archive contains a nonregular entry") + else: + path = destination(entry.filename, entry.file_size) + with source.open(entry) as data, path.open("xb") as target: + shutil.copyfileobj(data, target) + path.chmod(0o755 if path.suffix == ".exe" else 0o644) + else: + with tarfile.open(archive) as source: + for entry in source: + if entry.isdir(): + destination(entry.name, 0).mkdir(exist_ok=True) + elif entry.isfile(): + path = destination(entry.name, entry.size) + with source.extractfile(entry) as data, path.open("xb") as target: + shutil.copyfileobj(data, target) + path.chmod(0o755 if entry.mode & 0o111 else 0o644) + else: + raise ValueError("Wave archive contains a nonregular entry") + if len(roots) != 1: + raise ValueError("Wave archive must have one distribution root") + return output / roots.pop() + + +def inventory(root): + files = {} + for path in sorted(root.rglob("*")): + if path.is_symlink() or not (path.is_dir() or path.is_file()): + raise ValueError("Wave toolchain contains a nonregular entry") + if path.is_file(): + files[path.relative_to(root).as_posix()] = digest(path) + return files + + +def probe(compiler, standard): + result = subprocess.run( + [ + str(compiler), + "--std-root", + str(standard), + "print", + "vex-capabilities", + "--format=json", + ], + check=True, + capture_output=True, + timeout=30, + ) + capabilities = json.loads(result.stdout) + if capabilities.get("schema_version") != 1 or any( + capabilities.get(name) != 1 + for name in ("package_graph", "path_remap", "source_inputs") + ): + raise ValueError( + "Wave nightly does not support the required Vex package contract" + ) + + +def load_generation(cache, selection): + checksum = selection.get("archive_sha256") + if not isinstance(checksum, str) or not re.fullmatch(r"[0-9a-f]{64}", checksum): + raise ValueError("invalid cached Wave generation identity") + generation = cache / checksum + if generation.is_symlink(): + raise ValueError("cached Wave generation must not be a link") + for key in ("compiler", "std"): + path = selection.get(key) + if ( + not isinstance(path, str) + or not re.fullmatch(r"[A-Za-z0-9_./-]+", path) + or PurePosixPath(path).is_absolute() + or ".." in PurePosixPath(path).parts + ): + raise ValueError("invalid cached compiler/std path") + record = read_json(generation / "toolchain.json") + if record.get("selection") != selection: + raise ValueError("cached Wave generation metadata differs") + root = generation / "distribution" + observed_files = inventory(root) + if root.is_symlink() or observed_files != record.get("files"): + raise ValueError("cached Wave compiler/std/runtime files changed") + compiler = root / selection["compiler"] + standard = root / selection["std"] + if not compiler.is_file() or not standard.is_dir(): + raise ValueError("cached Wave compiler/std is incomplete") + probe(compiler, standard) + # Match Vex's versioned std-tree identity while reusing verified file hashes. + std_hash = hashlib.sha256(b"vex.std-tree.v1\0") + prefix = selection["std"].rstrip("/") + "/" + for name, checksum in observed_files.items(): + if name.startswith(prefix): + relative = name[len(prefix) :].encode() + std_hash.update(len(relative).to_bytes(8, "little")) + std_hash.update(relative) + std_hash.update(checksum.encode()) + return dict( + selection, + wavec=str(compiler), + std=str(standard), + compiler_sha256=digest(compiler), + std_sha256=std_hash.hexdigest(), + ) + + +def prepare(cache, output, offline=False): + cache = cache.resolve() + cache.mkdir(parents=True, exist_ok=True) + pointer = cache / "nightly.json" + target, suffix = host_target() + if offline: + selection = read_json(pointer) + if selection.get("host") != target: + raise ValueError("cached Wave nightly belongs to another executable host") + else: + with tempfile.TemporaryDirectory(prefix=".nightly-", dir=cache) as temporary: + temporary = Path(temporary) + release_path = temporary / "release.json" + download(RELEASE_URL, release_path, 8 * 1024 * 1024) + archive, metadata, source, generation = select_assets( + read_json(release_path), suffix + ) + name, checksum, _ = asset_fields(archive) + metadata_path = temporary / "artifact.json" + fetch_asset(metadata, metadata_path, 65536) + details = read_json(metadata_path) + if ( + not isinstance(details, dict) + or details.get("schema_version") != 1 + or details.get("channel") != "nightly" + or details.get("source_sha") != source + or details.get("generation") != generation + or details.get("archive") != name + or details.get("sha256") != checksum + or details.get("target") != target + ): + raise ValueError( + "Wave nightly metadata does not match the selected archive" + ) + paths = details.get("paths", {}) + if not isinstance(paths, dict): + raise ValueError("invalid Wave distribution paths") + for key in ("compiler", "std"): + path = paths.get(key) + if ( + not isinstance(path, str) + or not re.fullmatch(r"[A-Za-z0-9_./-]+", path) + or PurePosixPath(path).is_absolute() + or ".." in PurePosixPath(path).parts + ): + raise ValueError("invalid Wave distribution compiler/std path") + selection = dict( + schema_version=1, + host=target, + source_revision=source, + generation=generation, + archive=name, + archive_sha256=checksum, + compiler=paths["compiler"], + std=paths["std"], + ) + destination = cache / checksum + if not destination.exists(): + payload = temporary / "archive" + fetch_asset(archive, payload, MAX_ARCHIVE) + extracted = unpack(payload, temporary / "unpacked") + pending = temporary / "generation" + pending.mkdir() + shutil.move(extracted, pending / "distribution") + publish_json( + pending / "toolchain.json", + dict( + selection=selection, files=inventory(pending / "distribution") + ), + ) + probe( + pending / "distribution" / paths["compiler"], + pending / "distribution" / paths["std"], + ) + try: + pending.rename(destination) + except FileExistsError: + pass # Another build published this exact content generation. + record = load_generation(cache, selection) + publish_json(pointer, selection) + publish_json(output, record) + return record + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--offline", action="store_true") + args = parser.parse_args() + try: + record = prepare(args.cache_dir, args.output, args.offline) + print(f"Wave nightly {record['source_revision'][:12]} ({record['host']})") + except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error: + parser.exit(1, f"Wave toolchain preparation failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/vex.lock b/vex.lock new file mode 100644 index 0000000..ea13715 --- /dev/null +++ b/vex.lock @@ -0,0 +1,17 @@ +{ + version = 4, + roots = [{edges = [{alias = "whale_wave_assembler", default_features = true, features = [], key = "binding_66c52b8baba9c424444225e1437fecb6da8226d0e7d26fb25769078ff5409d87", optional = false, target = null}], features = {}, manifest = "assembler/aarch64/vex.ws", name = "whale_wave_aarch64", version = "0.1.0"}, {edges = [{alias = "whale_wave_assembler", default_features = true, features = [], key = "binding_66c52b8baba9c424444225e1437fecb6da8226d0e7d26fb25769078ff5409d87", optional = false, target = null}], features = {}, manifest = "assembler/amd64/vex.ws", name = "whale_wave_amd64", version = "0.1.0"}, {edges = [], features = {}, manifest = "assembler/asmobj/vex.ws", name = "whale_asmobj", version = "0.1.0"}, {edges = [{alias = "whale_wave_assembler", default_features = true, features = [], key = "binding_66c52b8baba9c424444225e1437fecb6da8226d0e7d26fb25769078ff5409d87", optional = false, target = null}], features = {}, manifest = "assembler/loongarch64/vex.ws", name = "whale_wave_loongarch64", version = "0.1.0"}, {edges = [{alias = "whale_wave_assembler", default_features = true, features = [], key = "binding_66c52b8baba9c424444225e1437fecb6da8226d0e7d26fb25769078ff5409d87", optional = false, target = null}], features = {}, manifest = "assembler/riscv64/vex.ws", name = "whale_wave_riscv64", version = "0.1.0"}, {edges = [], features = {}, manifest = "assembler/vex.ws", name = "whale_wave_assembler", version = "0.1.0"}, {edges = [], features = {}, manifest = "ir/vex.ws", name = "whale_wave_ir", version = "0.1.0"}], + package = [ + { + name = "binding_66c52b8baba9c424444225e1437fecb6da8226d0e7d26fb25769078ff5409d87", + version = "0.1.0", + package = "whale_wave_assembler", + id = "e8f0d5b5c99914af7f588dc4cef9e14dd25fb6e8244627f46758ea8de59c68a8", + import_name = "whale_wave_assembler", + source = "path", + path = "..", + resolved = "assembler", + dependencies = [] + } + ] +} diff --git a/vex.ws b/vex.ws new file mode 100644 index 0000000..7799a6c --- /dev/null +++ b/vex.ws @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +{ + format = 5, + workspace = { + members = [ + "assembler/asmobj", "assembler", "assembler/amd64", + "assembler/aarch64", "assembler/riscv64", "assembler/loongarch64", "ir" + ] + }, + profiles = { dev = { opt_level = 0 }, release = { opt_level = 2 } }, + build = { reproducible = true } +}