diff --git a/.github/actions/install-rust/action.yml b/.github/actions/install-rust/action.yml index 759cf6e1c891..1812d9ee152c 100644 --- a/.github/actions/install-rust/action.yml +++ b/.github/actions/install-rust/action.yml @@ -24,9 +24,11 @@ runs: range=${{ inputs.msrv_range }} if [ "${{ inputs.toolchain }}" = "default" ]; then - echo "version=1.$((msrv+range)).0" >> "$GITHUB_OUTPUT" + #echo "version=1.$((msrv+range)).0" >> "$GITHUB_OUTPUT" + echo "version=beta" >> "$GITHUB_OUTPUT" elif [ "${{ inputs.toolchain }}" = "msrv" ]; then - echo "version=1.$msrv.0" >> "$GITHUB_OUTPUT" + #echo "version=1.$msrv.0" >> "$GITHUB_OUTPUT" + echo "version=beta" >> "$GITHUB_OUTPUT" elif [ "${{ inputs.toolchain }}" = "wasmtime-ci-pinned-nightly" ]; then echo "version=nightly-2025-01-09" >> "$GITHUB_OUTPUT" else diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c4fda5ae0d02..45dc06e63314 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -196,6 +196,7 @@ jobs: platform-checks: ${{ steps.calculate.outputs.platform-checks }} steps: - uses: actions/checkout@v4 + - run: rustup update beta && rustup default beta - id: calculate env: GH_TOKEN: ${{ github.token }} diff --git a/Cargo.lock b/Cargo.lock index 6291e5c5b124..913a02ac0c6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -1406,12 +1406,13 @@ dependencies = [ [[package]] name = "futures" -version = "0.3.27" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "531ac96c6ff5fd7c62263c5e3c67a603af4fcaee2e1a0ae5565ba3a11e69e549" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" dependencies = [ "futures-channel", "futures-core", + "futures-executor", "futures-io", "futures-sink", "futures-task", @@ -1420,9 +1421,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.27" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "164713a5a0dcc3e7b4b1ed7d3b433cabc18025386f9339346e8daf15963cf7ac" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", "futures-sink", @@ -1434,11 +1435,33 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.90", +] [[package]] name = "futures-sink" @@ -1458,11 +1481,16 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "pin-utils", + "slab", ] [[package]] @@ -3209,7 +3237,7 @@ dependencies = [ "cargo_metadata", "heck 0.5.0", "wasmtime", - "wit-component 0.223.0", + "wit-component", ] [[package]] @@ -3618,7 +3646,7 @@ name = "verify-component-adapter" version = "30.0.0" dependencies = [ "anyhow", - "wasmparser 0.223.0", + "wasmparser", "wat", ] @@ -3710,7 +3738,7 @@ dependencies = [ "byte-array-literals", "object", "wasi", - "wasm-encoder 0.223.0", + "wasm-encoder", "wit-bindgen-rust-macro", ] @@ -3769,16 +3797,6 @@ version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49" -[[package]] -name = "wasm-encoder" -version = "0.220.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebf48234b389415b226a4daef6562933d38c7b28a8b8f64c5c4130dad1561ab7" -dependencies = [ - "leb128", - "wasmparser 0.220.0", -] - [[package]] name = "wasm-encoder" version = "0.223.0" @@ -3786,23 +3804,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e636076193fa68103e937ac951b5f2f587624097017d764b8984d9c0f149464" dependencies = [ "leb128", - "wasmparser 0.223.0", -] - -[[package]] -name = "wasm-metadata" -version = "0.220.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f3e5f5920c5abfc45573c89b07b38efdaae1515ef86f83dad12d60e50ecd62b" -dependencies = [ - "anyhow", - "indexmap 2.7.0", - "serde", - "serde_derive", - "serde_json", - "spdx", - "wasm-encoder 0.220.0", - "wasmparser 0.220.0", + "wasmparser", ] [[package]] @@ -3818,8 +3820,8 @@ dependencies = [ "serde_json", "spdx", "url", - "wasm-encoder 0.223.0", - "wasmparser 0.223.0", + "wasm-encoder", + "wasmparser", ] [[package]] @@ -3832,8 +3834,8 @@ dependencies = [ "log", "rand", "thiserror", - "wasm-encoder 0.223.0", - "wasmparser 0.223.0", + "wasm-encoder", + "wasmparser", ] [[package]] @@ -3847,7 +3849,7 @@ dependencies = [ "flagset", "indexmap 2.7.0", "leb128", - "wasm-encoder 0.223.0", + "wasm-encoder", ] [[package]] @@ -3867,7 +3869,7 @@ dependencies = [ "indexmap 2.7.0", "logos", "thiserror", - "wit-parser 0.223.0", + "wit-parser", ] [[package]] @@ -3914,19 +3916,6 @@ dependencies = [ "wasmi_core", ] -[[package]] -name = "wasmparser" -version = "0.220.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e246c2772ce3ebc83f89a2d4487ac5794cad6c309b2071818a88c7db7c36d87b" -dependencies = [ - "ahash", - "bitflags 2.6.0", - "hashbrown 0.14.3", - "indexmap 2.7.0", - "semver", -] - [[package]] name = "wasmparser" version = "0.223.0" @@ -3957,7 +3946,7 @@ checksum = "9235722b8cdb6c1c6daa537d4be4e230e76ce3ce0e4ba991956a1c6aed50305a" dependencies = [ "anyhow", "termcolor", - "wasmparser 0.223.0", + "wasmparser", ] [[package]] @@ -4002,9 +3991,9 @@ dependencies = [ "tempfile", "trait-variant", "wasi-common", - "wasm-encoder 0.223.0", + "wasm-encoder", "wasm-wave", - "wasmparser 0.223.0", + "wasmparser", "wasmtime-asm-macros", "wasmtime-cache", "wasmtime-component-macro", @@ -4147,8 +4136,8 @@ dependencies = [ "trait-variant", "walkdir", "wasi-common", - "wasm-encoder 0.223.0", - "wasmparser 0.223.0", + "wasm-encoder", + "wasmparser", "wasmtime", "wasmtime-cache", "wasmtime-cli-flags", @@ -4168,7 +4157,7 @@ dependencies = [ "wast 223.0.0", "wat", "windows-sys 0.59.0", - "wit-component 0.223.0", + "wit-component", ] [[package]] @@ -4201,7 +4190,7 @@ dependencies = [ "wasmtime", "wasmtime-component-util", "wasmtime-wit-bindgen", - "wit-parser 0.223.0", + "wit-parser", ] [[package]] @@ -4227,7 +4216,7 @@ dependencies = [ "smallvec", "target-lexicon", "thiserror", - "wasmparser 0.223.0", + "wasmparser", "wasmtime-environ", "wasmtime-versioned-export-macros", ] @@ -4253,8 +4242,8 @@ dependencies = [ "serde_derive", "smallvec", "target-lexicon", - "wasm-encoder 0.223.0", - "wasmparser 0.223.0", + "wasm-encoder", + "wasmparser", "wasmprinter", "wasmtime-component-util", "wat", @@ -4268,7 +4257,7 @@ dependencies = [ "component-fuzz-util", "env_logger 0.11.5", "libfuzzer-sys", - "wasmparser 0.223.0", + "wasmparser", "wasmprinter", "wasmtime-environ", "wat", @@ -4327,7 +4316,7 @@ dependencies = [ "rand", "smallvec", "target-lexicon", - "wasmparser 0.223.0", + "wasmparser", "wasmtime", "wasmtime-fuzzing", ] @@ -4348,12 +4337,12 @@ dependencies = [ "target-lexicon", "tempfile", "v8", - "wasm-encoder 0.223.0", + "wasm-encoder", "wasm-mutate", "wasm-smith", "wasm-spec-interpreter", "wasmi", - "wasmparser 0.223.0", + "wasmparser", "wasmprinter", "wasmtime", "wasmtime-wast", @@ -4555,7 +4544,7 @@ dependencies = [ "gimli", "object", "target-lexicon", - "wasmparser 0.223.0", + "wasmparser", "wasmtime-cranelift", "wasmtime-environ", "winch-codegen", @@ -4568,7 +4557,7 @@ dependencies = [ "anyhow", "heck 0.5.0", "indexmap 2.7.0", - "wit-parser 0.223.0", + "wit-parser", ] [[package]] @@ -4594,7 +4583,7 @@ dependencies = [ "leb128", "memchr", "unicode-width 0.2.0", - "wasm-encoder 0.223.0", + "wasm-encoder", ] [[package]] @@ -4745,7 +4734,7 @@ dependencies = [ "smallvec", "target-lexicon", "thiserror", - "wasmparser 0.223.0", + "wasmparser", "wasmtime-cranelift", "wasmtime-environ", ] @@ -4968,9 +4957,8 @@ dependencies = [ [[package]] name = "wit-bindgen" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c966692b6d8c4bb3c1aee3313e0930f44457a5763cfffb666f814506124e4691" +version = "0.36.0" +source = "git+https://github.com/bytecodealliance/wit-bindgen#51e1ef5573ca3e00be63ec404d5a19d064bec6d6" dependencies = [ "wit-bindgen-rt", "wit-bindgen-rust-macro", @@ -4978,45 +4966,43 @@ dependencies = [ [[package]] name = "wit-bindgen-core" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19857cff2a480fece56ea43f9199322ee5014688a3539ebf8d29ae62d75a3a1f" +version = "0.36.0" +source = "git+https://github.com/bytecodealliance/wit-bindgen#51e1ef5573ca3e00be63ec404d5a19d064bec6d6" dependencies = [ "anyhow", "heck 0.5.0", - "wit-parser 0.220.0", + "wit-parser", ] [[package]] name = "wit-bindgen-rt" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "605d5562e971a823cf5a550a9d69cb7144e9b4969a810043127175517a4e1865" +version = "0.36.0" +source = "git+https://github.com/bytecodealliance/wit-bindgen#51e1ef5573ca3e00be63ec404d5a19d064bec6d6" dependencies = [ "bitflags 2.6.0", + "futures", + "once_cell", ] [[package]] name = "wit-bindgen-rust" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d894e599c161d71acb6a78e8ec8a609a09c2bb227de50829f5afbd03b844a69" +version = "0.36.0" +source = "git+https://github.com/bytecodealliance/wit-bindgen#51e1ef5573ca3e00be63ec404d5a19d064bec6d6" dependencies = [ "anyhow", "heck 0.5.0", "indexmap 2.7.0", "prettyplease", "syn 2.0.90", - "wasm-metadata 0.220.0", + "wasm-metadata", "wit-bindgen-core", - "wit-component 0.220.0", + "wit-component", ] [[package]] name = "wit-bindgen-rust-macro" -version = "0.35.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a723cf943bba3bf34f437eb101e5a78180971e25dfb0085d80dbe4e73afb2854" +version = "0.36.0" +source = "git+https://github.com/bytecodealliance/wit-bindgen#51e1ef5573ca3e00be63ec404d5a19d064bec6d6" dependencies = [ "anyhow", "prettyplease", @@ -5027,25 +5013,6 @@ dependencies = [ "wit-bindgen-rust", ] -[[package]] -name = "wit-component" -version = "0.220.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ccedf54cc65f287da268d64d2bf4f7530d2cfb2296ffbe3ad5f65567e4cf53" -dependencies = [ - "anyhow", - "bitflags 2.6.0", - "indexmap 2.7.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder 0.220.0", - "wasm-metadata 0.220.0", - "wasmparser 0.220.0", - "wit-parser 0.220.0", -] - [[package]] name = "wit-component" version = "0.223.0" @@ -5059,28 +5026,10 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "wasm-encoder 0.223.0", - "wasm-metadata 0.223.0", - "wasmparser 0.223.0", - "wit-parser 0.223.0", -] - -[[package]] -name = "wit-parser" -version = "0.220.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b7117ce3adc0b4354b46dc1cf3190b00b333e65243d244c613ffcc58bdec84d" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.7.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser 0.220.0", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", ] [[package]] @@ -5098,7 +5047,7 @@ dependencies = [ "serde_derive", "serde_json", "unicode-xid", - "wasmparser 0.223.0", + "wasmparser", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 16cfce9cbffb..627b83f08b22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -165,10 +165,10 @@ exclude = [ [workspace.package] version = "30.0.0" authors = ["The Wasmtime Project Developers"] -edition = "2021" +edition = "2024" # Wasmtime's current policy is that this number can be no larger than the # current stable release of Rust minus 2. -rust-version = "1.82.0" +rust-version = "1.85.0" [workspace.lints.rust] # Turn on some lints which are otherwise allow-by-default in rustc. @@ -191,6 +191,8 @@ rust-2024-incompatible-pat = 'warn' missing-unsafe-on-extern = 'warn' impl-trait-overcaptures = 'warn' +unsafe-op-in-unsafe-fn = 'allow' + # Don't warn about unknown cfgs for pulley [workspace.lints.rust.unexpected_cfgs] level = "warn" @@ -293,8 +295,8 @@ io-lifetimes = { version = "2.0.3", default-features = false } io-extras = "0.18.1" rustix = "0.38.43" # wit-bindgen: -wit-bindgen = { version = "0.35.0", default-features = false } -wit-bindgen-rust-macro = { version = "0.35.0", default-features = false } +wit-bindgen = { version = "0.36.0", default-features = false } +wit-bindgen-rust-macro = { version = "0.36.0", default-features = false } # wasm-tools family: wasmparser = { version = "0.223.0", default-features = false, features = ['simd'] } @@ -563,3 +565,7 @@ opt-level = 's' inherits = "release" codegen-units = 1 lto = true + +[patch.crates-io] +wit-bindgen = { git = 'https://github.com/bytecodealliance/wit-bindgen' } +wit-bindgen-rust-macro = { git = 'https://github.com/bytecodealliance/wit-bindgen' } diff --git a/benches/call.rs b/benches/call.rs index 8e7d95aa8ffb..5e39e4c96247 100644 --- a/benches/call.rs +++ b/benches/call.rs @@ -1,5 +1,5 @@ use criterion::measurement::WallTime; -use criterion::{criterion_group, criterion_main, BenchmarkGroup, Criterion}; +use criterion::{BenchmarkGroup, Criterion, criterion_group, criterion_main}; use std::fmt::Debug; use std::future::Future; use std::pin::Pin; diff --git a/benches/instantiation.rs b/benches/instantiation.rs index 112a9a4f9cf5..824cf9492da3 100644 --- a/benches/instantiation.rs +++ b/benches/instantiation.rs @@ -1,12 +1,12 @@ use anyhow::Result; -use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use std::cell::LazyCell; use std::path::Path; use std::process::Command; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; use std::thread; -use wasi_common::{sync::WasiCtxBuilder, WasiCtx}; +use wasi_common::{WasiCtx, sync::WasiCtxBuilder}; use wasmtime::*; fn store(engine: &Engine) -> Store { diff --git a/benches/thread_eager_init.rs b/benches/thread_eager_init.rs index 421ac043b5cb..bd98ab55bd7c 100644 --- a/benches/thread_eager_init.rs +++ b/benches/thread_eager_init.rs @@ -1,4 +1,4 @@ -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use std::thread; use std::time::{Duration, Instant}; use wasmtime::*; diff --git a/benches/wasi.rs b/benches/wasi.rs index 77944071ba9e..d93b83858d2f 100644 --- a/benches/wasi.rs +++ b/benches/wasi.rs @@ -1,8 +1,8 @@ //! Measure some common WASI call scenarios. -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use std::{fs::File, path::Path, time::Instant}; -use wasi_common::{sync::WasiCtxBuilder, WasiCtx}; +use wasi_common::{WasiCtx, sync::WasiCtxBuilder}; use wasmtime::{Engine, Linker, Module, Store, TypedFunc}; criterion_group!(benches, bench_wasi); diff --git a/cranelift/bforest/src/map.rs b/cranelift/bforest/src/map.rs index d539e1d8cc4e..22e0748d1580 100644 --- a/cranelift/bforest/src/map.rs +++ b/cranelift/bforest/src/map.rs @@ -1,6 +1,6 @@ //! Forest of maps. -use super::{Comparator, Forest, Node, NodeData, NodePool, Path, INNER_SIZE}; +use super::{Comparator, Forest, INNER_SIZE, Node, NodeData, NodePool, Path}; use crate::packed_option::PackedOption; #[cfg(test)] use alloc::string::String; @@ -480,18 +480,15 @@ mod tests { m.verify(f, &()); - assert_eq!( - m.iter(f).collect::>(), - [ - (20, 2.0), - (40, 4.0), - (50, 5.5), - (60, 6.0), - (80, 8.0), - (90, 9.0), - (200, 20.0), - ] - ); + assert_eq!(m.iter(f).collect::>(), [ + (20, 2.0), + (40, 4.0), + (50, 5.5), + (60, 6.0), + (80, 8.0), + (90, 9.0), + (200, 20.0), + ]); assert_eq!(m.get(0, f, &()), None); assert_eq!(m.get(20, f, &()), Some(2.0)); @@ -593,10 +590,11 @@ mod tests { *v = (k / 10) as f32; (k % 20) == 0 }); - assert_eq!( - m.iter(f).collect::>(), - [(20, 2.0), (40, 4.0), (60, 6.0)] - ); + assert_eq!(m.iter(f).collect::>(), [ + (20, 2.0), + (40, 4.0), + (60, 6.0) + ]); // Insert at back of leaf. let mut m = full_leaf(f); diff --git a/cranelift/bforest/src/node.rs b/cranelift/bforest/src/node.rs index 848c657e82c8..b7b4595c5677 100644 --- a/cranelift/bforest/src/node.rs +++ b/cranelift/bforest/src/node.rs @@ -1,6 +1,6 @@ //! B+-tree nodes. -use super::{slice_insert, slice_shift, Forest, Node, SetValue, INNER_SIZE}; +use super::{Forest, INNER_SIZE, Node, SetValue, slice_insert, slice_shift}; use core::borrow::{Borrow, BorrowMut}; use core::fmt; diff --git a/cranelift/bforest/src/path.rs b/cranelift/bforest/src/path.rs index 896bd0e23db2..660999306482 100644 --- a/cranelift/bforest/src/path.rs +++ b/cranelift/bforest/src/path.rs @@ -1,7 +1,7 @@ //! A path from the root of a B+-tree to a leaf node. use super::node::Removed; -use super::{slice_insert, slice_shift, Comparator, Forest, Node, NodeData, NodePool, MAX_PATH}; +use super::{Comparator, Forest, MAX_PATH, Node, NodeData, NodePool, slice_insert, slice_shift}; use core::borrow::Borrow; use core::marker::PhantomData; diff --git a/cranelift/bforest/src/set.rs b/cranelift/bforest/src/set.rs index 34a3063c2f3d..bbbf0d4ca858 100644 --- a/cranelift/bforest/src/set.rs +++ b/cranelift/bforest/src/set.rs @@ -1,6 +1,6 @@ //! Forest of sets. -use super::{Comparator, Forest, Node, NodeData, NodePool, Path, SetValue, INNER_SIZE}; +use super::{Comparator, Forest, INNER_SIZE, Node, NodeData, NodePool, Path, SetValue}; use crate::packed_option::PackedOption; #[cfg(test)] use alloc::string::String; @@ -548,10 +548,9 @@ mod tests { let mut f = SetForest::::new(); let mut s = dense4l(&mut f); - assert_eq!( - s.iter(&f).collect::>()[0..10], - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - ); + assert_eq!(s.iter(&f).collect::>()[0..10], [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + ]); let mut c = s.cursor(&mut f, &()); diff --git a/cranelift/codegen/benches/x64-evex-encoding.rs b/cranelift/codegen/benches/x64-evex-encoding.rs index dd280212c598..86842054e143 100644 --- a/cranelift/codegen/benches/x64-evex-encoding.rs +++ b/cranelift/codegen/benches/x64-evex-encoding.rs @@ -8,7 +8,7 @@ mod x86 { evex::{EvexInstruction, EvexVectorLength, Register}, rex::{LegacyPrefixes, OpcodeMap}, }; - use criterion::{criterion_group, Criterion}; + use criterion::{Criterion, criterion_group}; // Define the benchmarks. fn x64_evex_encoding_benchmarks(c: &mut Criterion) { diff --git a/cranelift/codegen/meta/src/cdsl/types.rs b/cranelift/codegen/meta/src/cdsl/types.rs index ce3c2e582553..44d11eaf004a 100644 --- a/cranelift/codegen/meta/src/cdsl/types.rs +++ b/cranelift/codegen/meta/src/cdsl/types.rs @@ -222,14 +222,10 @@ impl fmt::Display for LaneType { impl fmt::Debug for LaneType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let inner_msg = format!("bits={}", self.lane_bits()); - write!( - f, - "{}", - match *self { - LaneType::Float(_) => format!("FloatType({inner_msg})"), - LaneType::Int(_) => format!("IntType({inner_msg})"), - } - ) + write!(f, "{}", match *self { + LaneType::Float(_) => format!("FloatType({inner_msg})"), + LaneType::Int(_) => format!("IntType({inner_msg})"), + }) } } @@ -368,8 +364,7 @@ impl DynamicVectorType { pub fn doc(&self) -> String { format!( "A dynamically-scaled SIMD vector with a minimum of {} lanes containing `{}` bits each.", - self.unscaled_lanes, - self.base + self.unscaled_lanes, self.base ) } diff --git a/cranelift/codegen/meta/src/cdsl/typevar.rs b/cranelift/codegen/meta/src/cdsl/typevar.rs index 61f31d9dbf50..496c10adb091 100644 --- a/cranelift/codegen/meta/src/cdsl/typevar.rs +++ b/cranelift/codegen/meta/src/cdsl/typevar.rs @@ -714,10 +714,9 @@ fn test_typevar_builder() { .dynamic_simd_lanes(Interval::All) .includes_scalars(false) .build(); - assert_eq!( - type_set.dynamic_lanes, - num_set![2, 4, 8, 16, 32, 64, 128, 256] - ); + assert_eq!(type_set.dynamic_lanes, num_set![ + 2, 4, 8, 16, 32, 64, 128, 256 + ]); assert_eq!(type_set.ints, num_set![8, 16, 32, 64, 128]); assert_eq!(type_set.floats, num_set![16, 32, 64, 128]); assert_eq!(type_set.lanes, num_set![1]); @@ -727,10 +726,9 @@ fn test_typevar_builder() { .dynamic_simd_lanes(Interval::All) .includes_scalars(false) .build(); - assert_eq!( - type_set.dynamic_lanes, - num_set![2, 4, 8, 16, 32, 64, 128, 256] - ); + assert_eq!(type_set.dynamic_lanes, num_set![ + 2, 4, 8, 16, 32, 64, 128, 256 + ]); assert_eq!(type_set.floats, num_set![16, 32, 64, 128]); assert_eq!(type_set.lanes, num_set![1]); assert!(type_set.ints.is_empty()); diff --git a/cranelift/codegen/meta/src/constant_hash.rs b/cranelift/codegen/meta/src/constant_hash.rs index 044e1b706e34..034575bf11e8 100644 --- a/cranelift/codegen/meta/src/constant_hash.rs +++ b/cranelift/codegen/meta/src/constant_hash.rs @@ -50,14 +50,11 @@ mod tests { fn test_generate_table() { let v = vec!["Hello".to_string(), "world".to_string()]; let table = generate_table(v.iter(), v.len(), |s| simple_hash(&s)); - assert_eq!( - table, - vec![ - None, - Some(&"Hello".to_string()), - Some(&"world".to_string()), - None - ] - ); + assert_eq!(table, vec![ + None, + Some(&"Hello".to_string()), + Some(&"world".to_string()), + None + ]); } } diff --git a/cranelift/codegen/meta/src/shared/instructions.rs b/cranelift/codegen/meta/src/shared/instructions.rs index 2611f5d714f1..65d58c1001d0 100644 --- a/cranelift/codegen/meta/src/shared/instructions.rs +++ b/cranelift/codegen/meta/src/shared/instructions.rs @@ -29,8 +29,10 @@ fn define_control_flow( "#, &formats.jump, ) - .operands_in(vec![Operand::new("block_call", &entities.block_call) - .with_doc("Destination basic block, with its arguments provided")]) + .operands_in(vec![ + Operand::new("block_call", &entities.block_call) + .with_doc("Destination basic block, with its arguments provided"), + ]) .branches(), ); @@ -174,7 +176,7 @@ fn define_control_flow( &formats.multiary, ) .operands_in(vec![ - Operand::new("rvals", &entities.varargs).with_doc("return values") + Operand::new("rvals", &entities.varargs).with_doc("return values"), ]) .returns(), ); @@ -196,7 +198,7 @@ fn define_control_flow( Operand::new("args", &entities.varargs).with_doc("call arguments"), ]) .operands_out(vec![ - Operand::new("rvals", &entities.varargs).with_doc("return values") + Operand::new("rvals", &entities.varargs).with_doc("return values"), ]) .call(), ); @@ -223,7 +225,7 @@ fn define_control_flow( Operand::new("args", &entities.varargs).with_doc("call arguments"), ]) .operands_out(vec![ - Operand::new("rvals", &entities.varargs).with_doc("return values") + Operand::new("rvals", &entities.varargs).with_doc("return values"), ]) .call(), ); @@ -295,8 +297,10 @@ fn define_control_flow( "#, &formats.func_addr, ) - .operands_in(vec![Operand::new("FN", &entities.func_ref) - .with_doc("function to call, declared by `function`")]) + .operands_in(vec![ + Operand::new("FN", &entities.func_ref) + .with_doc("function to call, declared by `function`"), + ]) .operands_out(vec![Operand::new("addr", iAddr)]), ); } @@ -331,7 +335,7 @@ fn define_simd_lane_access( &formats.unary, ) .operands_in(vec![ - Operand::new("x", &TxN.lane_of()).with_doc("Value to splat to all lanes") + Operand::new("x", &TxN.lane_of()).with_doc("Value to splat to all lanes"), ]) .operands_out(vec![Operand::new("a", TxN)]), ); @@ -1335,7 +1339,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("N", &imm.imm64)]) .operands_out(vec![ - Operand::new("a", NarrowInt).with_doc("A constant integer scalar or vector value") + Operand::new("a", NarrowInt).with_doc("A constant integer scalar or vector value"), ]), ); @@ -1351,7 +1355,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("N", &imm.ieee16)]) .operands_out(vec![ - Operand::new("a", f16_).with_doc("A constant f16 scalar value") + Operand::new("a", f16_).with_doc("A constant f16 scalar value"), ]), ); @@ -1367,7 +1371,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("N", &imm.ieee32)]) .operands_out(vec![ - Operand::new("a", f32_).with_doc("A constant f32 scalar value") + Operand::new("a", f32_).with_doc("A constant f32 scalar value"), ]), ); @@ -1383,7 +1387,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("N", &imm.ieee64)]) .operands_out(vec![ - Operand::new("a", f64_).with_doc("A constant f64 scalar value") + Operand::new("a", f64_).with_doc("A constant f64 scalar value"), ]), ); @@ -1399,7 +1403,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("N", &imm.pool_constant)]) .operands_out(vec![ - Operand::new("a", f128_).with_doc("A constant f128 scalar value") + Operand::new("a", f128_).with_doc("A constant f128 scalar value"), ]), ); @@ -1413,10 +1417,12 @@ pub(crate) fn define( "#, &formats.unary_const, ) - .operands_in(vec![Operand::new("N", &imm.pool_constant) - .with_doc("The 16 immediate bytes of a 128-bit vector")]) + .operands_in(vec![ + Operand::new("N", &imm.pool_constant) + .with_doc("The 16 immediate bytes of a 128-bit vector"), + ]) .operands_out(vec![ - Operand::new("a", TxN).with_doc("A constant vector value") + Operand::new("a", TxN).with_doc("A constant vector value"), ]), ); @@ -2780,7 +2786,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("Result of applying operator to each lane") + Operand::new("a", Float).with_doc("Result of applying operator to each lane"), ]), ); @@ -2794,7 +2800,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("Result of applying operator to each lane") + Operand::new("a", Float).with_doc("Result of applying operator to each lane"), ]), ); @@ -2808,7 +2814,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("Result of applying operator to each lane") + Operand::new("a", Float).with_doc("Result of applying operator to each lane"), ]), ); @@ -2826,7 +2832,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("Result of applying operator to each lane") + Operand::new("a", Float).with_doc("Result of applying operator to each lane"), ]), ); @@ -2840,7 +2846,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("Result of applying operator to each lane") + Operand::new("a", Float).with_doc("Result of applying operator to each lane"), ]), ); @@ -2861,7 +2867,7 @@ pub(crate) fn define( Operand::new("z", Float), ]) .operands_out(vec![ - Operand::new("a", Float).with_doc("Result of applying operator to each lane") + Operand::new("a", Float).with_doc("Result of applying operator to each lane"), ]), ); @@ -2877,7 +2883,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` with its sign bit inverted") + Operand::new("a", Float).with_doc("``x`` with its sign bit inverted"), ]), ); @@ -2893,7 +2899,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` with its sign bit cleared") + Operand::new("a", Float).with_doc("``x`` with its sign bit cleared"), ]), ); @@ -2910,7 +2916,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` with its sign bit changed to that of ``y``") + Operand::new("a", Float).with_doc("``x`` with its sign bit changed to that of ``y``"), ]), ); @@ -2929,7 +2935,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("The smaller of ``x`` and ``y``") + Operand::new("a", Float).with_doc("The smaller of ``x`` and ``y``"), ]), ); @@ -2948,7 +2954,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float), Operand::new("y", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("The larger of ``x`` and ``y``") + Operand::new("a", Float).with_doc("The larger of ``x`` and ``y``"), ]), ); @@ -2962,7 +2968,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` rounded to integral value") + Operand::new("a", Float).with_doc("``x`` rounded to integral value"), ]), ); @@ -2976,7 +2982,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` rounded to integral value") + Operand::new("a", Float).with_doc("``x`` rounded to integral value"), ]), ); @@ -2990,7 +2996,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` rounded to integral value") + Operand::new("a", Float).with_doc("``x`` rounded to integral value"), ]), ); @@ -3005,7 +3011,7 @@ pub(crate) fn define( ) .operands_in(vec![Operand::new("x", Float)]) .operands_out(vec![ - Operand::new("a", Float).with_doc("``x`` rounded to integral value") + Operand::new("a", Float).with_doc("``x`` rounded to integral value"), ]), ); @@ -3031,7 +3037,7 @@ pub(crate) fn define( Operand::new("x", Mem), ]) .operands_out(vec![ - Operand::new("a", MemTo).with_doc("Bits of `x` reinterpreted") + Operand::new("a", MemTo).with_doc("Bits of `x` reinterpreted"), ]), ); @@ -3045,7 +3051,7 @@ pub(crate) fn define( &formats.unary, ) .operands_in(vec![ - Operand::new("s", &TxN.lane_of()).with_doc("A scalar value") + Operand::new("s", &TxN.lane_of()).with_doc("A scalar value"), ]) .operands_out(vec![Operand::new("a", TxN).with_doc("A vector value")]), ); @@ -3092,8 +3098,10 @@ pub(crate) fn define( "#, &formats.unary, ) - .operands_in(vec![Operand::new("x", &Int.wider()) - .with_doc("A scalar integer type, wider than the controlling type")]) + .operands_in(vec![ + Operand::new("x", &Int.wider()) + .with_doc("A scalar integer type, wider than the controlling type"), + ]) .operands_out(vec![Operand::new("a", Int)]), ); @@ -3629,8 +3637,10 @@ pub(crate) fn define( Operand::new("lo", NarrowInt), Operand::new("hi", NarrowInt), ]) - .operands_out(vec![Operand::new("a", &NarrowInt.double_width()) - .with_doc("The concatenation of `lo` and `hi`")]), + .operands_out(vec![ + Operand::new("a", &NarrowInt.double_width()) + .with_doc("The concatenation of `lo` and `hi`"), + ]), ); // Instructions relating to atomic memory accesses and fences @@ -3660,7 +3670,7 @@ pub(crate) fn define( Operand::new("x", AtomicMem).with_doc("Value to be atomically stored"), ]) .operands_out(vec![ - Operand::new("a", AtomicMem).with_doc("Value atomically loaded") + Operand::new("a", AtomicMem).with_doc("Value atomically loaded"), ]) .can_load() .can_store() @@ -3689,7 +3699,7 @@ pub(crate) fn define( Operand::new("x", AtomicMem).with_doc("Value to be atomically stored"), ]) .operands_out(vec![ - Operand::new("a", AtomicMem).with_doc("Value atomically loaded") + Operand::new("a", AtomicMem).with_doc("Value atomically loaded"), ]) .can_load() .can_store() @@ -3715,7 +3725,7 @@ pub(crate) fn define( Operand::new("p", iAddr), ]) .operands_out(vec![ - Operand::new("a", AtomicMem).with_doc("Value atomically loaded") + Operand::new("a", AtomicMem).with_doc("Value atomically loaded"), ]) .can_load() .other_side_effects(), @@ -3780,7 +3790,7 @@ pub(crate) fn define( Operand::new("y", &imm.uimm8).with_doc("128-bit vector index"), ]) .operands_out(vec![ - Operand::new("a", &TxN.dynamic_to_vector()).with_doc("New fixed vector") + Operand::new("a", &TxN.dynamic_to_vector()).with_doc("New fixed vector"), ]), ); } diff --git a/cranelift/codegen/meta/src/srcgen.rs b/cranelift/codegen/meta/src/srcgen.rs index d3c321e5bc51..564889f35879 100644 --- a/cranelift/codegen/meta/src/srcgen.rs +++ b/cranelift/codegen/meta/src/srcgen.rs @@ -299,9 +299,9 @@ impl Match { #[cfg(test)] mod srcgen_tests { - use super::parse_multiline; use super::Formatter; use super::Match; + use super::parse_multiline; fn from_raw_string>(s: S) -> Vec { s.into() diff --git a/cranelift/codegen/src/alias_analysis.rs b/cranelift/codegen/src/alias_analysis.rs index 6a6e9f2748ba..da93c5b1dd2c 100644 --- a/cranelift/codegen/src/alias_analysis.rs +++ b/cranelift/codegen/src/alias_analysis.rs @@ -67,10 +67,10 @@ use crate::{ inst_predicates::{ has_memory_fence_semantics, inst_addr_offset_type, inst_store_data, visit_block_succs, }, - ir::{immediates::Offset32, AliasRegion, Block, Function, Inst, Opcode, Type, Value}, + ir::{AliasRegion, Block, Function, Inst, Opcode, Type, Value, immediates::Offset32}, trace, }; -use cranelift_entity::{packed_option::PackedOption, EntityRef}; +use cranelift_entity::{EntityRef, packed_option::PackedOption}; use rustc_hash::{FxHashMap, FxHashSet}; /// For a given program point, the vector of last-store instruction diff --git a/cranelift/codegen/src/context.rs b/cranelift/codegen/src/context.rs index 9cc7b7140d1e..9b65e3d3b078 100644 --- a/cranelift/codegen/src/context.rs +++ b/cranelift/codegen/src/context.rs @@ -24,8 +24,8 @@ use crate::result::{CodegenResult, CompileResult}; use crate::settings::{FlagsOrIsa, OptLevel}; use crate::trace; use crate::unreachable_code::eliminate_unreachable_code; -use crate::verifier::{verify_context, VerifierErrors, VerifierResult}; -use crate::{timing, CompileError}; +use crate::verifier::{VerifierErrors, VerifierResult, verify_context}; +use crate::{CompileError, timing}; #[cfg(feature = "souper-harvest")] use alloc::string::String; use alloc::vec::Vec; diff --git a/cranelift/codegen/src/data_value.rs b/cranelift/codegen/src/data_value.rs index 523182f07d9e..93758477d83f 100644 --- a/cranelift/codegen/src/data_value.rs +++ b/cranelift/codegen/src/data_value.rs @@ -1,7 +1,7 @@ //! This module gives users to instantiate values that Cranelift understands. These values are used, //! for example, during interpretation and for wrapping immediates. -use crate::ir::immediates::{Ieee128, Ieee16, Ieee32, Ieee64, Offset32}; -use crate::ir::{types, ConstantData, Type}; +use crate::ir::immediates::{Ieee16, Ieee32, Ieee64, Ieee128, Offset32}; +use crate::ir::{ConstantData, Type, types}; use core::cmp::Ordering; use core::fmt::{self, Display, Formatter}; diff --git a/cranelift/codegen/src/egraph.rs b/cranelift/codegen/src/egraph.rs index eef19a600717..e0161bbd22de 100644 --- a/cranelift/codegen/src/egraph.rs +++ b/cranelift/codegen/src/egraph.rs @@ -19,8 +19,8 @@ use crate::trace; use crate::unionfind::UnionFind; use core::cmp::Ordering; use cranelift_control::ControlPlane; -use cranelift_entity::packed_option::ReservedValue; use cranelift_entity::SecondaryMap; +use cranelift_entity::packed_option::ReservedValue; use rustc_hash::FxHashSet; use smallvec::SmallVec; use std::hash::Hasher; @@ -365,8 +365,7 @@ where for optimized_value in optimized_values.drain(..) { trace!( "Returned from ISLE for {}, got {:?}", - orig_value, - optimized_value + orig_value, optimized_value ); if optimized_value == orig_value { trace!(" -> same as orig value; skipping"); @@ -461,9 +460,7 @@ where let result = self.func.dfg.first_result(inst); trace!( " -> inst {} has result {} replaced with {}", - inst, - result, - new_result + inst, result, new_result ); self.value_to_opt_value[result] = new_result; self.func.dfg.merge_facts(result, new_result); diff --git a/cranelift/codegen/src/egraph/elaborate.rs b/cranelift/codegen/src/egraph/elaborate.rs index a35c2ac25734..561d336555cd 100644 --- a/cranelift/codegen/src/egraph/elaborate.rs +++ b/cranelift/codegen/src/egraph/elaborate.rs @@ -1,8 +1,8 @@ //! Elaboration phase: lowers EGraph back to sequences of operations //! in CFG nodes. -use super::cost::Cost; use super::Stats; +use super::cost::Cost; use crate::dominator_tree::DominatorTreePreorder; use crate::hash_map::Entry as HashEntry; use crate::inst_predicates::is_pure_for_egraph; @@ -12,9 +12,9 @@ use crate::scoped_hash_map::ScopedHashMap; use crate::trace; use alloc::vec::Vec; use cranelift_control::ControlPlane; -use cranelift_entity::{packed_option::ReservedValue, SecondaryMap}; +use cranelift_entity::{SecondaryMap, packed_option::ReservedValue}; use rustc_hash::{FxHashMap, FxHashSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; pub(crate) struct Elaborator<'a> { func: &'a mut Function, @@ -282,9 +282,7 @@ impl<'a> Elaborator<'a> { }; trace!( " -> best of union({:?}, {:?}) = {:?}", - best[x], - best[y], - best[value] + best[x], best[y], best[value] ); } ValueDef::Param(_, _) => { @@ -444,9 +442,7 @@ impl<'a> Elaborator<'a> { ValueDef::Result(inst, result_idx) => { trace!( " -> value {} is result {} of {}", - best_value, - result_idx, - inst + best_value, result_idx, inst ); (inst, result_idx) } @@ -469,8 +465,7 @@ impl<'a> Elaborator<'a> { trace!( " -> result {} of inst {:?}", - result_idx, - self.func.dfg.insts[inst] + result_idx, self.func.dfg.insts[inst] ); // We're going to need to use this instruction @@ -503,10 +498,7 @@ impl<'a> Elaborator<'a> { } => { trace!( "PendingInst: {} result {} args {} before {}", - inst, - result_idx, - num_args, - before + inst, result_idx, num_args, before ); // We should have all args resolved at this @@ -543,8 +535,7 @@ impl<'a> Elaborator<'a> { .unwrap_or(self.loop_stack.len()); trace!( " -> arg: elab_value {:?} hoist level {:?}", - value, - hoist_level + value, hoist_level ); hoist_level }) @@ -592,8 +583,7 @@ impl<'a> Elaborator<'a> { trace!( " -> decided to place: before {} insert_block {}", - before, - insert_block + before, insert_block ); // Now that we have the location for the @@ -633,8 +623,7 @@ impl<'a> Elaborator<'a> { let new_inst = self.func.dfg.clone_inst(inst); trace!( " -> inst {} already has a location; cloned to {}", - inst, - new_inst + inst, new_inst ); // Create mappings in the // value-to-elab'd-value map from original @@ -661,8 +650,7 @@ impl<'a> Elaborator<'a> { trace!( " -> cloned inst has new result {} for orig {}", - new_result, - result + new_result, result ); } new_inst @@ -771,13 +759,11 @@ impl<'a> Elaborator<'a> { for &result in self.func.dfg.inst_results(inst) { trace!(" -> result {}", result); let best_result = self.value_to_best_value[result]; - self.value_to_elaborated_value.insert_if_absent( - best_result.1, - ElaboratedValue { + self.value_to_elaborated_value + .insert_if_absent(best_result.1, ElaboratedValue { in_block: block, value: result, - }, - ); + }); } next_inst = self.func.layout.next_inst(inst); diff --git a/cranelift/codegen/src/flowgraph.rs b/cranelift/codegen/src/flowgraph.rs index b57af31055d0..59ab006346fd 100644 --- a/cranelift/codegen/src/flowgraph.rs +++ b/cranelift/codegen/src/flowgraph.rs @@ -197,7 +197,7 @@ pub type SuccIter<'a> = bforest::SetIter<'a, Block>; mod tests { use super::*; use crate::cursor::{Cursor, FuncCursor}; - use crate::ir::{types, InstBuilder}; + use crate::ir::{InstBuilder, types}; use alloc::vec::Vec; #[test] diff --git a/cranelift/codegen/src/incremental_cache.rs b/cranelift/codegen/src/incremental_cache.rs index 89e42cf242a0..852330b27033 100644 --- a/cranelift/codegen/src/incremental_cache.rs +++ b/cranelift/codegen/src/incremental_cache.rs @@ -24,12 +24,12 @@ use core::fmt; use crate::alloc::string::String; use crate::alloc::vec::Vec; -use crate::ir::function::{FunctionStencil, VersionMarker}; use crate::ir::Function; +use crate::ir::function::{FunctionStencil, VersionMarker}; use crate::machinst::{CompiledCode, CompiledCodeStencil}; use crate::result::CompileResult; +use crate::{CompileError, Context, trace}; use crate::{isa::TargetIsa, timing}; -use crate::{trace, CompileError, Context}; use alloc::borrow::{Cow, ToOwned as _}; use alloc::string::ToString as _; use cranelift_control::ControlPlane; diff --git a/cranelift/codegen/src/ir/constant.rs b/cranelift/codegen/src/ir/constant.rs index 0db31628cca2..1a7b92ba7bd8 100644 --- a/cranelift/codegen/src/ir/constant.rs +++ b/cranelift/codegen/src/ir/constant.rs @@ -8,13 +8,13 @@ //! - ensuring alignment of constants within the pool, //! - bucketing constants by size. -use crate::ir::immediates::{Ieee128, IntoBytes, V128Imm}; use crate::ir::Constant; +use crate::ir::immediates::{Ieee128, IntoBytes, V128Imm}; use alloc::collections::BTreeMap; use alloc::vec::Vec; use core::fmt; use core::slice::Iter; -use core::str::{from_utf8, FromStr}; +use core::str::{FromStr, from_utf8}; use cranelift_entity::EntityRef; #[cfg(feature = "enable-serde")] @@ -454,32 +454,27 @@ mod tests { .into_vec() } - assert_eq!( - parse_to_uimm128("0x42"), - [0x42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ); - assert_eq!( - parse_to_uimm128("0x00"), - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ); - assert_eq!( - parse_to_uimm128("0x12345678"), - [0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ); - assert_eq!( - parse_to_uimm128("0x1234_5678"), - [0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - ); + assert_eq!(parse_to_uimm128("0x42"), [ + 0x42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ]); + assert_eq!(parse_to_uimm128("0x00"), [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ]); + assert_eq!(parse_to_uimm128("0x12345678"), [ + 0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ]); + assert_eq!(parse_to_uimm128("0x1234_5678"), [ + 0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ]); } #[test] fn constant_ieee128() { let value = Ieee128::with_bits(0x000102030405060708090a0b0c0d0e0f); let constant = ConstantData::from(value); - assert_eq!( - constant.as_slice(), - &[0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0] - ); + assert_eq!(constant.as_slice(), &[ + 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0 + ]); assert_eq!(Ieee128::try_from(&constant).unwrap().bits(), value.bits()); } } diff --git a/cranelift/codegen/src/ir/dfg.rs b/cranelift/codegen/src/ir/dfg.rs index 593d4cdb4a33..4b29a722533c 100644 --- a/cranelift/codegen/src/ir/dfg.rs +++ b/cranelift/codegen/src/ir/dfg.rs @@ -8,9 +8,9 @@ use crate::ir::instructions::{CallInfo, InstructionData}; use crate::ir::pcc::Fact; use crate::ir::user_stack_maps::{UserStackMapEntry, UserStackMapEntryVec}; use crate::ir::{ - types, Block, BlockCall, ConstantData, ConstantPool, DynamicType, ExtFuncData, FuncRef, - Immediate, Inst, JumpTables, RelSourceLoc, SigRef, Signature, Type, Value, - ValueLabelAssignments, ValueList, ValueListPool, + Block, BlockCall, ConstantData, ConstantPool, DynamicType, ExtFuncData, FuncRef, Immediate, + Inst, JumpTables, RelSourceLoc, SigRef, Signature, Type, Value, ValueLabelAssignments, + ValueList, ValueListPool, types, }; use crate::packed_option::ReservedValue; use crate::write::write_operands; @@ -690,11 +690,7 @@ fn encode_narrow_field(x: u32, bits: u8) -> u32 { /// The inverse of the above `encode_narrow_field`: unpacks 2^n-1 into /// 2^32-1. fn decode_narrow_field(x: u32, bits: u8) -> u32 { - if x == (1 << bits) - 1 { - 0xffff_ffff - } else { - x - } + if x == (1 << bits) - 1 { 0xffff_ffff } else { x } } impl ValueDataPacked { @@ -1742,8 +1738,8 @@ mod tests { #[test] fn aliases() { - use crate::ir::condcodes::IntCC; use crate::ir::InstBuilder; + use crate::ir::condcodes::IntCC; let mut func = Function::new(); let block0 = func.dfg.make_block(); diff --git a/cranelift/codegen/src/ir/dynamic_type.rs b/cranelift/codegen/src/ir/dynamic_type.rs index d98ced809ef6..53027c196945 100644 --- a/cranelift/codegen/src/ir/dynamic_type.rs +++ b/cranelift/codegen/src/ir/dynamic_type.rs @@ -1,9 +1,9 @@ //! Dynamic IR types -use crate::ir::entities::DynamicType; -use crate::ir::types::*; use crate::ir::GlobalValue; use crate::ir::PrimaryMap; +use crate::ir::entities::DynamicType; +use crate::ir::types::*; #[cfg(feature = "enable-serde")] use serde_derive::{Deserialize, Serialize}; diff --git a/cranelift/codegen/src/ir/entities.rs b/cranelift/codegen/src/ir/entities.rs index 005007471b35..e768b1e4236c 100644 --- a/cranelift/codegen/src/ir/entities.rs +++ b/cranelift/codegen/src/ir/entities.rs @@ -42,11 +42,7 @@ impl Block { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -128,11 +124,7 @@ impl StackSlot { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -147,11 +139,7 @@ impl DynamicStackSlot { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -166,11 +154,7 @@ impl DynamicType { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -200,11 +184,7 @@ impl GlobalValue { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -223,11 +203,7 @@ impl MemoryType { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -249,11 +225,7 @@ impl Constant { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -275,11 +247,7 @@ impl Immediate { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -305,11 +273,7 @@ impl JumpTable { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -338,11 +302,7 @@ impl FuncRef { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } @@ -376,11 +336,7 @@ impl SigRef { /// /// This method is for use by the parser. pub fn with_number(n: u32) -> Option { - if n < u32::MAX { - Some(Self(n)) - } else { - None - } + if n < u32::MAX { Some(Self(n)) } else { None } } } diff --git a/cranelift/codegen/src/ir/extfunc.rs b/cranelift/codegen/src/ir/extfunc.rs index 319ec4038243..821eb009dd55 100644 --- a/cranelift/codegen/src/ir/extfunc.rs +++ b/cranelift/codegen/src/ir/extfunc.rs @@ -352,7 +352,7 @@ impl<'a> fmt::Display for DisplayableExtFuncData<'a> { #[cfg(test)] mod tests { use super::*; - use crate::ir::types::{F32, I32, I8}; + use crate::ir::types::{F32, I8, I32}; use alloc::string::ToString; #[test] diff --git a/cranelift/codegen/src/ir/extname.rs b/cranelift/codegen/src/ir/extname.rs index 8484376b5a87..452652baf28a 100644 --- a/cranelift/codegen/src/ir/extname.rs +++ b/cranelift/codegen/src/ir/extname.rs @@ -233,7 +233,7 @@ impl FromStr for ExternalName { mod tests { use super::ExternalName; use crate::ir::{ - entities::UserExternalNameRef, function::FunctionParameters, LibCall, UserExternalName, + LibCall, UserExternalName, entities::UserExternalNameRef, function::FunctionParameters, }; use alloc::string::ToString; use core::u32; diff --git a/cranelift/codegen/src/ir/function.rs b/cranelift/codegen/src/ir/function.rs index ebf7f08cb85c..620b88f16a8c 100644 --- a/cranelift/codegen/src/ir/function.rs +++ b/cranelift/codegen/src/ir/function.rs @@ -3,16 +3,16 @@ //! The `Function` struct defined in this module owns all of its basic blocks and //! instructions. +use crate::HashMap; use crate::entity::{PrimaryMap, SecondaryMap}; use crate::ir::{ - self, pcc::Fact, Block, DataFlowGraph, DynamicStackSlot, DynamicStackSlotData, - DynamicStackSlots, DynamicType, ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Inst, - JumpTable, JumpTableData, Layout, MemoryType, MemoryTypeData, SigRef, Signature, SourceLocs, - StackSlot, StackSlotData, StackSlots, Type, + self, Block, DataFlowGraph, DynamicStackSlot, DynamicStackSlotData, DynamicStackSlots, + DynamicType, ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Inst, JumpTable, + JumpTableData, Layout, MemoryType, MemoryTypeData, SigRef, Signature, SourceLocs, StackSlot, + StackSlotData, StackSlots, Type, pcc::Fact, }; use crate::isa::CallConv; use crate::write::write_function; -use crate::HashMap; #[cfg(feature = "enable-serde")] use alloc::string::String; use core::fmt; @@ -349,12 +349,13 @@ impl FunctionStencil { self.dfg.inst_results(dst).len(), self.dfg.inst_results(src).len() ); - debug_assert!(self - .dfg - .inst_results(dst) - .iter() - .zip(self.dfg.inst_results(src)) - .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b))); + debug_assert!( + self.dfg + .inst_results(dst) + .iter() + .zip(self.dfg.inst_results(src)) + .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b)) + ); self.dfg.insts[dst] = self.dfg.insts[src]; self.layout.remove_inst(src); diff --git a/cranelift/codegen/src/ir/instructions.rs b/cranelift/codegen/src/ir/instructions.rs index 556e3092b313..86ecc28d84e7 100644 --- a/cranelift/codegen/src/ir/instructions.rs +++ b/cranelift/codegen/src/ir/instructions.rs @@ -18,10 +18,10 @@ use serde_derive::{Deserialize, Serialize}; use crate::bitset::ScalarBitSet; use crate::entity; use crate::ir::{ - self, + self, Block, FuncRef, MemFlags, SigRef, StackSlot, Type, Value, condcodes::{FloatCC, IntCC}, trapcode::TrapCode, - types, Block, FuncRef, MemFlags, SigRef, StackSlot, Type, Value, + types, }; /// Some instructions use an external list of argument values because there is not enough space in diff --git a/cranelift/codegen/src/ir/jumptable.rs b/cranelift/codegen/src/ir/jumptable.rs index 8e1e15c7d621..1d0b40fefb9e 100644 --- a/cranelift/codegen/src/ir/jumptable.rs +++ b/cranelift/codegen/src/ir/jumptable.rs @@ -3,8 +3,8 @@ //! Jump tables are declared in the preamble and assigned an `ir::entities::JumpTable` reference. //! The actual table of destinations is stored in a `JumpTableData` struct defined in this module. -use crate::ir::instructions::ValueListPool; use crate::ir::BlockCall; +use crate::ir::instructions::ValueListPool; use alloc::vec::Vec; use core::fmt::{self, Display, Formatter}; use core::slice::{Iter, IterMut}; diff --git a/cranelift/codegen/src/ir/layout.rs b/cranelift/codegen/src/ir/layout.rs index 4e6ca774cc26..32ba39adecea 100644 --- a/cranelift/codegen/src/ir/layout.rs +++ b/cranelift/codegen/src/ir/layout.rs @@ -92,11 +92,7 @@ fn midpoint(a: SequenceNumber, b: SequenceNumber) -> Option { debug_assert!(a < b); // Avoid integer overflow. let m = a + (b - a) / 2; - if m > a { - Some(m) - } else { - None - } + if m > a { Some(m) } else { None } } impl Layout { diff --git a/cranelift/codegen/src/ir/libcall.rs b/cranelift/codegen/src/ir/libcall.rs index 1e05adcc5d5f..96f953c51edb 100644 --- a/cranelift/codegen/src/ir/libcall.rs +++ b/cranelift/codegen/src/ir/libcall.rs @@ -1,7 +1,7 @@ //! Naming well-known routines in the runtime library. use crate::{ - ir::{types, AbiParam, ExternalName, FuncRef, Function, Signature, Type}, + ir::{AbiParam, ExternalName, FuncRef, Function, Signature, Type, types}, isa::CallConv, }; use core::fmt; diff --git a/cranelift/codegen/src/ir/mod.rs b/cranelift/codegen/src/ir/mod.rs index e6f082d70a8d..19a7773bcb78 100644 --- a/cranelift/codegen/src/ir/mod.rs +++ b/cranelift/codegen/src/ir/mod.rs @@ -36,7 +36,7 @@ pub use crate::ir::builder::{ }; pub use crate::ir::constant::{ConstantData, ConstantPool}; pub use crate::ir::dfg::{BlockData, DataFlowGraph, ValueDef}; -pub use crate::ir::dynamic_type::{dynamic_to_fixed, DynamicTypeData, DynamicTypes}; +pub use crate::ir::dynamic_type::{DynamicTypeData, DynamicTypes, dynamic_to_fixed}; pub use crate::ir::entities::{ Block, Constant, DynamicStackSlot, DynamicType, FuncRef, GlobalValue, Immediate, Inst, JumpTable, MemoryType, SigRef, StackSlot, UserExternalNameRef, Value, @@ -53,7 +53,7 @@ pub use crate::ir::instructions::{ pub use crate::ir::jumptable::JumpTableData; pub use crate::ir::known_symbol::KnownSymbol; pub use crate::ir::layout::Layout; -pub use crate::ir::libcall::{get_probestack_funcref, LibCall}; +pub use crate::ir::libcall::{LibCall, get_probestack_funcref}; pub use crate::ir::memflags::{AliasRegion, Endianness, MemFlags}; pub use crate::ir::memtype::{MemoryTypeData, MemoryTypeField}; pub use crate::ir::pcc::{BaseExpr, Expr, Fact, FactContext, PccError, PccResult}; @@ -67,7 +67,7 @@ pub use crate::ir::trapcode::TrapCode; pub use crate::ir::types::Type; pub use crate::ir::user_stack_maps::{UserStackMap, UserStackMapEntry}; -use crate::entity::{entity_impl, PrimaryMap, SecondaryMap}; +use crate::entity::{PrimaryMap, SecondaryMap, entity_impl}; /// Map of jump tables. pub type JumpTables = PrimaryMap; diff --git a/cranelift/codegen/src/ir/pcc.rs b/cranelift/codegen/src/ir/pcc.rs index 624e18753d61..4fb88fd02ebf 100644 --- a/cranelift/codegen/src/ir/pcc.rs +++ b/cranelift/codegen/src/ir/pcc.rs @@ -1183,9 +1183,7 @@ impl<'a> FactContext<'a> { trace!( "truncate: fact {:?} from {} to {}", - fact, - from_width, - to_width + fact, from_width, to_width ); match fact { diff --git a/cranelift/codegen/src/ir/stackslot.rs b/cranelift/codegen/src/ir/stackslot.rs index d906fb291324..1cec0f270472 100644 --- a/cranelift/codegen/src/ir/stackslot.rs +++ b/cranelift/codegen/src/ir/stackslot.rs @@ -4,8 +4,8 @@ //! use crate::entity::PrimaryMap; -use crate::ir::entities::{DynamicStackSlot, DynamicType}; use crate::ir::StackSlot; +use crate::ir::entities::{DynamicStackSlot, DynamicType}; use core::fmt; use core::str::FromStr; diff --git a/cranelift/codegen/src/isa/aarch64/abi.rs b/cranelift/codegen/src/isa/aarch64/abi.rs index 3008a42f687d..fc2e58c92dd9 100644 --- a/cranelift/codegen/src/isa/aarch64/abi.rs +++ b/cranelift/codegen/src/isa/aarch64/abi.rs @@ -1,21 +1,21 @@ //! Implementation of a standard AArch64 ABI. +use crate::CodegenResult; use crate::ir; +use crate::ir::MemFlags; use crate::ir::types; use crate::ir::types::*; -use crate::ir::MemFlags; -use crate::ir::{dynamic_to_fixed, ExternalName, LibCall, Signature}; +use crate::ir::{ExternalName, LibCall, Signature, dynamic_to_fixed}; use crate::isa; -use crate::isa::aarch64::{inst::*, settings as aarch64_settings, AArch64Backend}; +use crate::isa::aarch64::{AArch64Backend, inst::*, settings as aarch64_settings}; use crate::isa::unwind::UnwindInst; use crate::isa::winch; use crate::machinst::*; use crate::settings; -use crate::CodegenResult; use alloc::boxed::Box; use alloc::vec::Vec; use regalloc2::{MachineEnv, PReg, PRegSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::borrow::ToOwned; use std::sync::OnceLock; diff --git a/cranelift/codegen/src/isa/aarch64/inst/emit.rs b/cranelift/codegen/src/isa/aarch64/inst/emit.rs index d31e08fcedb8..8a8e8be24ab1 100644 --- a/cranelift/codegen/src/isa/aarch64/inst/emit.rs +++ b/cranelift/codegen/src/isa/aarch64/inst/emit.rs @@ -1372,13 +1372,15 @@ impl MachInstEmit for Inst { } &Inst::MovFromPReg { rd, rm } => { let rm: Reg = rm.into(); - debug_assert!([ - regs::fp_reg(), - regs::stack_reg(), - regs::link_reg(), - regs::pinned_reg() - ] - .contains(&rm)); + debug_assert!( + [ + regs::fp_reg(), + regs::stack_reg(), + regs::link_reg(), + regs::pinned_reg() + ] + .contains(&rm) + ); assert!(rm.class() == RegClass::Int); assert!(rd.to_reg().class() == rm.class()); let size = OperandSize::Size64; @@ -1386,13 +1388,15 @@ impl MachInstEmit for Inst { } &Inst::MovToPReg { rd, rm } => { let rd: Writable = Writable::from_reg(rd.into()); - debug_assert!([ - regs::fp_reg(), - regs::stack_reg(), - regs::link_reg(), - regs::pinned_reg() - ] - .contains(&rd.to_reg())); + debug_assert!( + [ + regs::fp_reg(), + regs::stack_reg(), + regs::link_reg(), + regs::pinned_reg() + ] + .contains(&rd.to_reg()) + ); assert!(rd.to_reg().class() == RegClass::Int); assert!(rm.class() == rd.to_reg().class()); let size = OperandSize::Size64; diff --git a/cranelift/codegen/src/isa/aarch64/inst/imms.rs b/cranelift/codegen/src/isa/aarch64/inst/imms.rs index e8495d6557a3..e90b622ec707 100644 --- a/cranelift/codegen/src/isa/aarch64/inst/imms.rs +++ b/cranelift/codegen/src/isa/aarch64/inst/imms.rs @@ -289,11 +289,7 @@ impl Imm12 { /// Bits for 2-bit "shift" field in e.g. AddI. pub fn shift_bits(&self) -> u32 { - if self.shift12 { - 0b01 - } else { - 0b00 - } + if self.shift12 { 0b01 } else { 0b00 } } /// Bits for 12-bit "imm" field in e.g. AddI. @@ -304,11 +300,7 @@ impl Imm12 { /// Get the actual value that this immediate corresponds to. pub fn value(&self) -> u32 { let base = self.bits as u32; - if self.shift12 { - base << 12 - } else { - base - } + if self.shift12 { base << 12 } else { base } } } diff --git a/cranelift/codegen/src/isa/aarch64/inst/mod.rs b/cranelift/codegen/src/isa/aarch64/inst/mod.rs index 2c60b0b5069f..bae83205e72f 100644 --- a/cranelift/codegen/src/isa/aarch64/inst/mod.rs +++ b/cranelift/codegen/src/isa/aarch64/inst/mod.rs @@ -1,16 +1,16 @@ //! This module defines aarch64-specific machine instruction types. use crate::binemit::{Addend, CodeOffset, Reloc}; -use crate::ir::types::{F128, F16, F32, F64, I128, I16, I32, I64, I8, I8X16}; -use crate::ir::{types, MemFlags, Type}; +use crate::ir::types::{F16, F32, F64, F128, I8, I8X16, I16, I32, I64, I128}; +use crate::ir::{MemFlags, Type, types}; use crate::isa::{CallConv, FunctionAlignment}; use crate::machinst::*; -use crate::{settings, CodegenError, CodegenResult}; +use crate::{CodegenError, CodegenResult, settings}; use crate::machinst::{PrettyPrint, Reg, RegClass, Writable}; use alloc::vec::Vec; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::fmt::Write; use std::string::{String, ToString}; diff --git a/cranelift/codegen/src/isa/aarch64/inst/unwind/systemv.rs b/cranelift/codegen/src/isa/aarch64/inst/unwind/systemv.rs index 2d7bb02202e0..9378c46fa53b 100644 --- a/cranelift/codegen/src/isa/aarch64/inst/unwind/systemv.rs +++ b/cranelift/codegen/src/isa/aarch64/inst/unwind/systemv.rs @@ -3,7 +3,7 @@ use crate::isa::aarch64::inst::regs; use crate::isa::unwind::systemv::RegisterMappingError; use crate::machinst::{Reg, RegClass}; -use gimli::{write::CommonInformationEntry, Encoding, Format, Register}; +use gimli::{Encoding, Format, Register, write::CommonInformationEntry}; /// Creates a new aarch64 common information entry (CIE). pub fn create_cie() -> CommonInformationEntry { @@ -66,13 +66,13 @@ impl crate::isa::unwind::systemv::RegisterMapper for RegisterMapper { #[cfg(test)] mod tests { + use crate::Context; use crate::cursor::{Cursor, FuncCursor}; use crate::ir::{ - types, AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, + AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, types, }; - use crate::isa::{lookup, CallConv}; - use crate::settings::{builder, Flags}; - use crate::Context; + use crate::isa::{CallConv, lookup}; + use crate::settings::{Flags, builder}; use gimli::write::Address; use target_lexicon::triple; @@ -102,7 +102,10 @@ mod tests { _ => panic!("expected unwind information"), }; - assert_eq!(format!("{fde:?}"), "FrameDescriptionEntry { address: Constant(1234), length: 24, lsda: None, instructions: [(4, CfaOffset(16)), (4, Offset(Register(29), -16)), (4, Offset(Register(30), -8)), (8, CfaRegister(Register(29)))] }"); + assert_eq!( + format!("{fde:?}"), + "FrameDescriptionEntry { address: Constant(1234), length: 24, lsda: None, instructions: [(4, CfaOffset(16)), (4, Offset(Register(29), -16)), (4, Offset(Register(30), -8)), (8, CfaRegister(Register(29)))] }" + ); } fn create_function(call_conv: CallConv, stack_slot: Option) -> Function { diff --git a/cranelift/codegen/src/isa/aarch64/lower.rs b/cranelift/codegen/src/isa/aarch64/lower.rs index 5ed10a490ac4..758571947a64 100644 --- a/cranelift/codegen/src/isa/aarch64/lower.rs +++ b/cranelift/codegen/src/isa/aarch64/lower.rs @@ -7,13 +7,13 @@ //! //! - Floating-point immediates (FIMM instruction). +use crate::ir::Inst as IRInst; use crate::ir::condcodes::{FloatCC, IntCC}; use crate::ir::pcc::{FactContext, PccResult}; -use crate::ir::Inst as IRInst; use crate::ir::{Opcode, Value}; +use crate::isa::aarch64::AArch64Backend; use crate::isa::aarch64::inst::*; use crate::isa::aarch64::pcc; -use crate::isa::aarch64::AArch64Backend; use crate::machinst::lower::*; use crate::machinst::*; diff --git a/cranelift/codegen/src/isa/aarch64/lower/isle.rs b/cranelift/codegen/src/isa/aarch64/lower/isle.rs index a783e7fd4f07..1533e38bceaa 100644 --- a/cranelift/codegen/src/isa/aarch64/lower/isle.rs +++ b/cranelift/codegen/src/isa/aarch64/lower/isle.rs @@ -6,28 +6,28 @@ use generated_code::{Context, ImmExtend}; // Types that the generated ISLE code uses via `use super::*`. use super::{ - fp_reg, lower_condcode, lower_fp_condcode, stack_reg, writable_link_reg, writable_zero_reg, - zero_reg, ASIMDFPModImm, ASIMDMovModImm, BranchTarget, CallInfo, Cond, CondBrKind, ExtendOp, - FPUOpRI, FPUOpRIMod, FloatCC, Imm12, ImmLogic, ImmShift, Inst as MInst, IntCC, MachLabel, - MemLabel, MoveWideConst, MoveWideOp, Opcode, OperandSize, Reg, SImm9, ScalarSize, - ShiftOpAndAmt, UImm12Scaled, UImm5, VecMisc2, VectorSize, NZCV, + ASIMDFPModImm, ASIMDMovModImm, BranchTarget, CallInfo, Cond, CondBrKind, ExtendOp, FPUOpRI, + FPUOpRIMod, FloatCC, Imm12, ImmLogic, ImmShift, Inst as MInst, IntCC, MachLabel, MemLabel, + MoveWideConst, MoveWideOp, NZCV, Opcode, OperandSize, Reg, SImm9, ScalarSize, ShiftOpAndAmt, + UImm5, UImm12Scaled, VecMisc2, VectorSize, fp_reg, lower_condcode, lower_fp_condcode, + stack_reg, writable_link_reg, writable_zero_reg, zero_reg, }; -use crate::ir::{condcodes, ArgumentExtension}; +use crate::ir::{ArgumentExtension, condcodes}; use crate::isa; -use crate::isa::aarch64::inst::{FPULeftShiftImm, FPURightShiftImm, ReturnCallInfo}; use crate::isa::aarch64::AArch64Backend; +use crate::isa::aarch64::inst::{FPULeftShiftImm, FPURightShiftImm, ReturnCallInfo}; use crate::machinst::isle::*; use crate::{ binemit::CodeOffset, ir::{ - immediates::*, types::*, AtomicRmwOp, BlockCall, ExternalName, Inst, InstructionData, - MemFlags, TrapCode, Value, ValueList, + AtomicRmwOp, BlockCall, ExternalName, Inst, InstructionData, MemFlags, TrapCode, Value, + ValueList, immediates::*, types::*, }, isa::aarch64::abi::AArch64CallSite, - isa::aarch64::inst::args::{ShiftOp, ShiftOpShiftImm}, isa::aarch64::inst::SImm7Scaled, + isa::aarch64::inst::args::{ShiftOp, ShiftOpShiftImm}, machinst::{ - abi::ArgPair, ty_bits, InstOutput, IsTailCall, MachInst, VCodeConstant, VCodeConstantData, + InstOutput, IsTailCall, MachInst, VCodeConstant, VCodeConstantData, abi::ArgPair, ty_bits, }, }; use core::u32; @@ -179,19 +179,11 @@ impl Context for IsleContext<'_, '_, MInst, AArch64Backend> { } fn is_zero_simm9(&mut self, imm: &SImm9) -> Option<()> { - if imm.value() == 0 { - Some(()) - } else { - None - } + if imm.value() == 0 { Some(()) } else { None } } fn is_zero_uimm12(&mut self, imm: &UImm12Scaled) -> Option<()> { - if imm.value() == 0 { - Some(()) - } else { - None - } + if imm.value() == 0 { Some(()) } else { None } } /// This is target-word-size dependent. And it excludes booleans and reftypes. @@ -705,11 +697,7 @@ impl Context for IsleContext<'_, '_, MInst, AArch64Backend> { } fn shuffle_dup64_from_imm(&mut self, imm: Immediate) -> Option { let (a, b) = self.shuffle64_from_imm(imm)?; - if a == b && a < 2 { - Some(a) - } else { - None - } + if a == b && a < 2 { Some(a) } else { None } } fn asimd_mov_mod_imm_zero(&mut self, size: &ScalarSize) -> ASIMDMovModImm { diff --git a/cranelift/codegen/src/isa/aarch64/mod.rs b/cranelift/codegen/src/isa/aarch64/mod.rs index ce70f51e184f..bc42e280783a 100644 --- a/cranelift/codegen/src/isa/aarch64/mod.rs +++ b/cranelift/codegen/src/isa/aarch64/mod.rs @@ -7,8 +7,8 @@ use crate::isa::aarch64::settings as aarch64_settings; use crate::isa::unwind::systemv; use crate::isa::{Builder as IsaBuilder, FunctionAlignment, TargetIsa}; use crate::machinst::{ - compile, CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, - TextSectionBuilder, VCode, + CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, + TextSectionBuilder, VCode, compile, }; use crate::result::CodegenResult; use crate::settings as shared_settings; @@ -161,7 +161,9 @@ impl TargetIsa for AArch64Backend { && self.isa_flags.sign_return_address_with_bkey() && !is_apple_os { - unimplemented!("Specifying that the B key is used with pointer authentication instructions in the CIE is not implemented."); + unimplemented!( + "Specifying that the B key is used with pointer authentication instructions in the CIE is not implemented." + ); } Some(inst::unwind::systemv::create_cie()) diff --git a/cranelift/codegen/src/isa/aarch64/pcc.rs b/cranelift/codegen/src/isa/aarch64/pcc.rs index 46a0a48bac03..83c6d236f837 100644 --- a/cranelift/codegen/src/isa/aarch64/pcc.rs +++ b/cranelift/codegen/src/isa/aarch64/pcc.rs @@ -1,15 +1,15 @@ //! Proof-carrying code checking for AArch64 VCode. +use crate::ir::MemFlags; use crate::ir::pcc::*; use crate::ir::types::*; -use crate::ir::MemFlags; +use crate::isa::aarch64::inst::Inst; use crate::isa::aarch64::inst::args::{Cond, PairAMode, ShiftOp}; use crate::isa::aarch64::inst::regs::zero_reg; -use crate::isa::aarch64::inst::Inst; use crate::isa::aarch64::inst::{ALUOp, MoveWideOp}; use crate::isa::aarch64::inst::{AMode, ExtendOp}; -use crate::machinst::pcc::*; use crate::machinst::Reg; +use crate::machinst::pcc::*; use crate::machinst::{InsnIndex, VCode}; use crate::trace; @@ -376,18 +376,11 @@ fn check_load( ) -> PccResult<()> { let result_fact = rd.and_then(|rd| vcode.vreg_fact(rd.into())); let bits = u16::try_from(ty.bits()).unwrap(); - check_addr( - ctx, - flags, - addr, - vcode, - ty, - LoadOrStore::Load { - result_fact, - from_bits: bits, - to_bits: bits, - }, - ) + check_addr(ctx, flags, addr, vcode, ty, LoadOrStore::Load { + result_fact, + from_bits: bits, + to_bits: bits, + }) } fn check_store( @@ -399,14 +392,9 @@ fn check_store( ty: Type, ) -> PccResult<()> { let stored_fact = rd.and_then(|rd| vcode.vreg_fact(rd.into())); - check_addr( - ctx, - flags, - addr, - vcode, - ty, - LoadOrStore::Store { stored_fact }, - ) + check_addr(ctx, flags, addr, vcode, ty, LoadOrStore::Store { + stored_fact, + }) } fn check_addr<'a>( diff --git a/cranelift/codegen/src/isa/aarch64/settings.rs b/cranelift/codegen/src/isa/aarch64/settings.rs index 9a00124d4258..2cda69446ff3 100644 --- a/cranelift/codegen/src/isa/aarch64/settings.rs +++ b/cranelift/codegen/src/isa/aarch64/settings.rs @@ -1,6 +1,6 @@ //! AArch64 Settings. -use crate::settings::{self, detail, Builder, Value}; +use crate::settings::{self, Builder, Value, detail}; use core::fmt; // Include code generated by `cranelift/codegen/meta/src/gen_settings.rs:`. This file contains a diff --git a/cranelift/codegen/src/isa/mod.rs b/cranelift/codegen/src/isa/mod.rs index 05f70225112a..ad8dd29d5d64 100644 --- a/cranelift/codegen/src/isa/mod.rs +++ b/cranelift/codegen/src/isa/mod.rs @@ -46,20 +46,20 @@ use crate::dominator_tree::DominatorTree; pub use crate::isa::call_conv::CallConv; +use crate::CodegenResult; use crate::flowgraph; use crate::ir::{self, Function, Type}; #[cfg(feature = "unwind")] -use crate::isa::unwind::{systemv::RegisterMappingError, UnwindInfoKind}; +use crate::isa::unwind::{UnwindInfoKind, systemv::RegisterMappingError}; use crate::machinst::{CompiledCode, CompiledCodeStencil, TextSectionBuilder}; use crate::settings; use crate::settings::Configurable; use crate::settings::SetResult; -use crate::CodegenResult; use alloc::{boxed::Box, sync::Arc, vec::Vec}; use core::fmt; use core::fmt::{Debug, Formatter}; use cranelift_control::ControlPlane; -use target_lexicon::{triple, Architecture, PointerWidth, Triple}; +use target_lexicon::{Architecture, PointerWidth, Triple, triple}; // This module is made public here for benchmarking purposes. No guarantees are // made regarding API stability. diff --git a/cranelift/codegen/src/isa/pulley_shared/abi.rs b/cranelift/codegen/src/isa/pulley_shared/abi.rs index 6efbd3927b2b..e8d6bdb7af3d 100644 --- a/cranelift/codegen/src/isa/pulley_shared/abi.rs +++ b/cranelift/codegen/src/isa/pulley_shared/abi.rs @@ -1,18 +1,19 @@ //! Implementation of a standard Pulley ABI. -use super::{inst::*, PulleyFlags, PulleyTargetKind}; +use super::{PulleyFlags, PulleyTargetKind, inst::*}; use crate::isa::pulley_shared::{PointerWidth, PulleyBackend}; use crate::{ - ir::{self, types::*, MemFlags, Signature}, + CodegenResult, + ir::{self, MemFlags, Signature, types::*}, isa, machinst::*, - settings, CodegenResult, + settings, }; use alloc::{boxed::Box, vec::Vec}; use core::marker::PhantomData; use cranelift_bitset::ScalarBitSet; use regalloc2::{MachineEnv, PReg, PRegSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::borrow::ToOwned; use std::sync::OnceLock; @@ -472,25 +473,31 @@ where args.push(XReg::new(arg.vreg).unwrap()); false }); - smallvec![Inst::Call { - info: Box::new(info.map(|()| PulleyCall { - name: name.clone(), - args, - })) - } - .into()] + smallvec![ + Inst::Call { + info: Box::new(info.map(|()| PulleyCall { + name: name.clone(), + args, + })) + } + .into() + ] } // "far" calls are pulley->host calls so they use a different opcode // which is lowered with a special relocation in the backend. - CallDest::ExtName(name, RelocDistance::Far) => smallvec![Inst::IndirectCallHost { - info: Box::new(info.map(|()| name.clone())) - } - .into()], + CallDest::ExtName(name, RelocDistance::Far) => smallvec![ + Inst::IndirectCallHost { + info: Box::new(info.map(|()| name.clone())) + } + .into() + ], // Indirect calls are all assumed to be pulley->pulley calls - CallDest::Reg(reg) => smallvec![Inst::IndirectCall { - info: Box::new(info.map(|()| XReg::new(*reg).unwrap())) - } - .into()], + CallDest::Reg(reg) => smallvec![ + Inst::IndirectCall { + info: Box::new(info.map(|()| XReg::new(*reg).unwrap())) + } + .into() + ], } } diff --git a/cranelift/codegen/src/isa/pulley_shared/inst/emit.rs b/cranelift/codegen/src/isa/pulley_shared/inst/emit.rs index 9090e3585f2e..8656b593a796 100644 --- a/cranelift/codegen/src/isa/pulley_shared/inst/emit.rs +++ b/cranelift/codegen/src/isa/pulley_shared/inst/emit.rs @@ -2,8 +2,8 @@ use super::*; use crate::ir::{self, Endianness}; -use crate::isa::pulley_shared::abi::PulleyMachineDeps; use crate::isa::pulley_shared::PointerWidth; +use crate::isa::pulley_shared::abi::PulleyMachineDeps; use core::marker::PhantomData; use cranelift_control::ControlPlane; use pulley_interpreter::encode as enc; diff --git a/cranelift/codegen/src/isa/pulley_shared/inst/mod.rs b/cranelift/codegen/src/isa/pulley_shared/inst/mod.rs index 6b77be3d8e3f..f4d336e73030 100644 --- a/cranelift/codegen/src/isa/pulley_shared/inst/mod.rs +++ b/cranelift/codegen/src/isa/pulley_shared/inst/mod.rs @@ -3,12 +3,12 @@ use core::marker::PhantomData; use crate::binemit::{Addend, CodeOffset, Reloc}; -use crate::ir::types::{self, F32, F64, I128, I16, I32, I64, I8, I8X16}; +use crate::ir::types::{self, F32, F64, I8, I8X16, I16, I32, I64, I128}; use crate::ir::{self, MemFlags, Type}; -use crate::isa::pulley_shared::abi::PulleyMachineDeps; use crate::isa::FunctionAlignment; +use crate::isa::pulley_shared::abi::PulleyMachineDeps; +use crate::{CodegenError, CodegenResult, settings}; use crate::{machinst::*, trace}; -use crate::{settings, CodegenError, CodegenResult}; use alloc::string::{String, ToString}; use regalloc2::RegClass; use smallvec::SmallVec; diff --git a/cranelift/codegen/src/isa/pulley_shared/lower.rs b/cranelift/codegen/src/isa/pulley_shared/lower.rs index 9f8754d513d3..8dd5a0cea50c 100644 --- a/cranelift/codegen/src/isa/pulley_shared/lower.rs +++ b/cranelift/codegen/src/isa/pulley_shared/lower.rs @@ -2,7 +2,7 @@ pub mod isle; -use super::{inst::*, PulleyBackend, PulleyTargetKind}; +use super::{PulleyBackend, PulleyTargetKind, inst::*}; use crate::{ ir, machinst::{lower::*, *}, diff --git a/cranelift/codegen/src/isa/pulley_shared/lower/isle.rs b/cranelift/codegen/src/isa/pulley_shared/lower/isle.rs index f344d33436df..874504151c1a 100644 --- a/cranelift/codegen/src/isa/pulley_shared/lower/isle.rs +++ b/cranelift/codegen/src/isa/pulley_shared/lower/isle.rs @@ -13,13 +13,13 @@ use crate::isa::pulley_shared::{ FReg, OperandSize, PulleyCall, ReturnCallInfo, VReg, WritableFReg, WritableVReg, WritableXReg, XReg, }, - lower::{regs, Cond}, + lower::{Cond, regs}, *, }; use crate::machinst::{ + CallInfo, IsTailCall, MachInst, Reg, VCodeConstant, VCodeConstantData, abi::{ArgPair, RetPair, StackAMode}, isle::*, - CallInfo, IsTailCall, MachInst, Reg, VCodeConstant, VCodeConstantData, }; use alloc::boxed::Box; use pulley_interpreter::U6; diff --git a/cranelift/codegen/src/isa/pulley_shared/mod.rs b/cranelift/codegen/src/isa/pulley_shared/mod.rs index 16aba8304e72..d5df6fa33c58 100644 --- a/cranelift/codegen/src/isa/pulley_shared/mod.rs +++ b/cranelift/codegen/src/isa/pulley_shared/mod.rs @@ -8,13 +8,13 @@ mod settings; use self::inst::EmitInfo; use super::{Builder as IsaBuilder, FunctionAlignment}; use crate::{ + MachTextSectionBuilder, TextSectionBuilder, dominator_tree::DominatorTree, ir, isa::{self, OwnedTargetIsa, TargetIsa}, machinst::{self, CompiledCodeStencil, MachInst, SigSet, VCode}, result::CodegenResult, settings::{self as shared_settings, Flags}, - MachTextSectionBuilder, TextSectionBuilder, }; use alloc::boxed::Box; use alloc::vec::Vec; diff --git a/cranelift/codegen/src/isa/pulley_shared/settings.rs b/cranelift/codegen/src/isa/pulley_shared/settings.rs index 937384db1468..3e2f5f2780b1 100644 --- a/cranelift/codegen/src/isa/pulley_shared/settings.rs +++ b/cranelift/codegen/src/isa/pulley_shared/settings.rs @@ -5,7 +5,7 @@ use crate::{ machinst::IsaFlags, - settings::{self, detail, Builder, Value}, + settings::{self, Builder, Value, detail}, }; use core::fmt; diff --git a/cranelift/codegen/src/isa/riscv64/abi.rs b/cranelift/codegen/src/isa/riscv64/abi.rs index 3bde5ea9bb17..a1634e6b3da9 100644 --- a/cranelift/codegen/src/isa/riscv64/abi.rs +++ b/cranelift/codegen/src/isa/riscv64/abi.rs @@ -5,21 +5,21 @@ use crate::ir::types::*; use crate::isa; -use crate::isa::riscv64::{inst::*, Riscv64Backend}; use crate::isa::CallConv; +use crate::isa::riscv64::{Riscv64Backend, inst::*}; use crate::machinst::*; +use crate::CodegenResult; use crate::ir::LibCall; use crate::ir::Signature; use crate::isa::riscv64::settings::Flags as RiscvFlags; use crate::isa::unwind::UnwindInst; use crate::settings; -use crate::CodegenResult; use alloc::boxed::Box; use alloc::vec::Vec; use regalloc2::{MachineEnv, PReg, PRegSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::borrow::ToOwned; use std::sync::OnceLock; diff --git a/cranelift/codegen/src/isa/riscv64/inst/args.rs b/cranelift/codegen/src/isa/riscv64/inst/args.rs index 6c973b068590..63ccd8ca1cd7 100644 --- a/cranelift/codegen/src/isa/riscv64/inst/args.rs +++ b/cranelift/codegen/src/isa/riscv64/inst/args.rs @@ -38,11 +38,7 @@ macro_rules! newtype_of_reg { /// Create this newtype from the given register, or return `None` if the register /// is not a valid instance of this newtype. pub fn new($check_reg: Reg) -> Option { - if $check { - Some(Self($check_reg)) - } else { - None - } + if $check { Some(Self($check_reg)) } else { None } } /// Get this newtype's underlying `Reg`. @@ -610,16 +606,12 @@ impl FpuOPRRR { impl Display for FpuOPWidth { fn fmt(&self, f: &mut Formatter<'_>) -> Result { - write!( - f, - "{}", - match self { - FpuOPWidth::H => "h", - FpuOPWidth::S => "s", - FpuOPWidth::D => "d", - FpuOPWidth::Q => "q", - } - ) + write!(f, "{}", match self { + FpuOPWidth::H => "h", + FpuOPWidth::S => "s", + FpuOPWidth::D => "d", + FpuOPWidth::Q => "q", + }) } } @@ -1409,18 +1401,10 @@ impl AtomicOP { } pub(crate) fn load_op(t: Type) -> Self { - if t.bits() <= 32 { - Self::LrW - } else { - Self::LrD - } + if t.bits() <= 32 { Self::LrW } else { Self::LrD } } pub(crate) fn store_op(t: Type) -> Self { - if t.bits() <= 32 { - Self::ScW - } else { - Self::ScD - } + if t.bits() <= 32 { Self::ScW } else { Self::ScD } } /// extract diff --git a/cranelift/codegen/src/isa/riscv64/inst/mod.rs b/cranelift/codegen/src/isa/riscv64/inst/mod.rs index 6e593f6901c6..12ea50d61dec 100644 --- a/cranelift/codegen/src/isa/riscv64/inst/mod.rs +++ b/cranelift/codegen/src/isa/riscv64/inst/mod.rs @@ -3,18 +3,18 @@ use super::lower::isle::generated_code::{VecAMode, VecElementWidth, VecOpMasking}; use crate::binemit::{Addend, CodeOffset, Reloc}; pub use crate::ir::condcodes::IntCC; -use crate::ir::types::{self, F128, F16, F32, F64, I128, I16, I32, I64, I8, I8X16}; +use crate::ir::types::{self, F16, F32, F64, F128, I8, I8X16, I16, I32, I64, I128}; pub use crate::ir::{ExternalName, MemFlags, Type}; use crate::isa::{CallConv, FunctionAlignment}; use crate::machinst::*; -use crate::{settings, CodegenError, CodegenResult}; +use crate::{CodegenError, CodegenResult, settings}; pub use crate::ir::condcodes::FloatCC; use alloc::vec::Vec; use regalloc2::RegClass; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::boxed::Box; use std::fmt::Write; use std::string::{String, ToString}; @@ -46,8 +46,8 @@ pub(crate) type VecU8 = Vec; // Instructions (top level): definition pub use crate::isa::riscv64::lower::isle::generated_code::{ - AluOPRRI, AluOPRRR, AtomicOP, CsrImmOP, CsrRegOP, FClassResult, FFlagsException, FpuOPRR, - FpuOPRRR, FpuOPRRRR, LoadOP, MInst as Inst, StoreOP, CSR, FRM, + AluOPRRI, AluOPRRR, AtomicOP, CSR, CsrImmOP, CsrRegOP, FClassResult, FFlagsException, FRM, + FpuOPRR, FpuOPRRR, FpuOPRRRR, LoadOP, MInst as Inst, StoreOP, }; use crate::isa::riscv64::lower::isle::generated_code::{CjOp, MInst, VecAluOpRRImm5, VecAluOpRRR}; diff --git a/cranelift/codegen/src/isa/riscv64/inst/unwind/systemv.rs b/cranelift/codegen/src/isa/riscv64/inst/unwind/systemv.rs index 4bbb8401451e..0b2ef040b19c 100644 --- a/cranelift/codegen/src/isa/riscv64/inst/unwind/systemv.rs +++ b/cranelift/codegen/src/isa/riscv64/inst/unwind/systemv.rs @@ -3,7 +3,7 @@ use crate::isa::riscv64::inst::regs; use crate::isa::unwind::systemv::RegisterMappingError; use crate::machinst::Reg; -use gimli::{write::CommonInformationEntry, Encoding, Format, Register}; +use gimli::{Encoding, Format, Register, write::CommonInformationEntry}; use regalloc2::RegClass; /// Creates a new riscv64 common information entry (CIE). @@ -61,13 +61,13 @@ impl crate::isa::unwind::systemv::RegisterMapper for RegisterMapper { mod tests { use crate::cursor::{Cursor, FuncCursor}; + use crate::Context; use crate::ir::{ - types, AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, - UserFuncName, + AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, UserFuncName, + types, }; - use crate::isa::{lookup, CallConv}; - use crate::settings::{builder, Flags}; - use crate::Context; + use crate::isa::{CallConv, lookup}; + use crate::settings::{Flags, builder}; use gimli::write::Address; use target_lexicon::triple; @@ -97,7 +97,10 @@ mod tests { _ => panic!("expected unwind information"), }; - assert_eq!(format!("{fde:?}"), "FrameDescriptionEntry { address: Constant(1234), length: 40, lsda: None, instructions: [(12, CfaOffset(16)), (12, Offset(Register(8), -16)), (12, Offset(Register(1), -8)), (16, CfaRegister(Register(8)))] }"); + assert_eq!( + format!("{fde:?}"), + "FrameDescriptionEntry { address: Constant(1234), length: 40, lsda: None, instructions: [(12, CfaOffset(16)), (12, Offset(Register(8), -16)), (12, Offset(Register(1), -8)), (16, CfaRegister(Register(8)))] }" + ); } fn create_function(call_conv: CallConv, stack_slot: Option) -> Function { diff --git a/cranelift/codegen/src/isa/riscv64/inst/vector.rs b/cranelift/codegen/src/isa/riscv64/inst/vector.rs index d1ed3703cb6d..269e6481b506 100644 --- a/cranelift/codegen/src/isa/riscv64/inst/vector.rs +++ b/cranelift/codegen/src/isa/riscv64/inst/vector.rs @@ -1,10 +1,10 @@ +use crate::Reg; use crate::isa::riscv64::lower::isle::generated_code::VecAluOpRRRR; use crate::isa::riscv64::lower::isle::generated_code::{ VecAMode, VecAluOpRImm5, VecAluOpRR, VecAluOpRRImm5, VecAluOpRRR, VecAluOpRRRImm5, VecAvl, VecElementWidth, VecLmul, VecMaskMode, VecOpCategory, VecOpMasking, VecTailMode, }; use crate::machinst::{OperandVisitor, RegClass}; -use crate::Reg; use core::fmt; use super::{Type, UImm5}; diff --git a/cranelift/codegen/src/isa/riscv64/lower.rs b/cranelift/codegen/src/isa/riscv64/lower.rs index 41b114441052..117778f820b3 100644 --- a/cranelift/codegen/src/isa/riscv64/lower.rs +++ b/cranelift/codegen/src/isa/riscv64/lower.rs @@ -1,7 +1,7 @@ //! Lowering rules for Riscv64. use crate::ir::Inst as IRInst; -use crate::isa::riscv64::inst::*; use crate::isa::riscv64::Riscv64Backend; +use crate::isa::riscv64::inst::*; use crate::machinst::lower::*; use crate::machinst::*; pub mod isle; diff --git a/cranelift/codegen/src/isa/riscv64/lower/isle.rs b/cranelift/codegen/src/isa/riscv64/lower/isle.rs index c39bfd4e5dfb..bf8ab7125a89 100644 --- a/cranelift/codegen/src/isa/riscv64/lower/isle.rs +++ b/cranelift/codegen/src/isa/riscv64/lower/isle.rs @@ -8,18 +8,18 @@ use generated_code::MInst; // Types that the generated ISLE code uses via `use super::*`. use self::generated_code::{FpuOPWidth, VecAluOpRR, VecLmul}; use crate::isa; +use crate::isa::riscv64::Riscv64Backend; use crate::isa::riscv64::abi::Riscv64ABICallSite; use crate::isa::riscv64::lower::args::{ FReg, VReg, WritableFReg, WritableVReg, WritableXReg, XReg, }; -use crate::isa::riscv64::Riscv64Backend; use crate::machinst::Reg; -use crate::machinst::{isle::*, CallInfo, MachInst}; +use crate::machinst::{CallInfo, MachInst, isle::*}; use crate::machinst::{VCodeConstant, VCodeConstantData}; use crate::{ ir::{ - immediates::*, types::*, AtomicRmwOp, BlockCall, ExternalName, Inst, InstructionData, - MemFlags, Opcode, TrapCode, Value, ValueList, + AtomicRmwOp, BlockCall, ExternalName, Inst, InstructionData, MemFlags, Opcode, TrapCode, + Value, ValueList, immediates::*, types::*, }, isa::riscv64::inst::*, machinst::{ArgPair, InstOutput, IsTailCall}, @@ -171,11 +171,7 @@ impl generated_code::Context for RV64IsleContext<'_, '_, MInst, Riscv64Backend> _ => false, }; - if supported { - Some(ty) - } else { - None - } + if supported { Some(ty) } else { None } } fn ty_supported_float(&mut self, ty: Type) -> Option { @@ -264,11 +260,7 @@ impl generated_code::Context for RV64IsleContext<'_, '_, MInst, Riscv64Backend> } #[inline] fn imm12_is_zero(&mut self, imm: Imm12) -> Option<()> { - if imm.as_i16() == 0 { - Some(()) - } else { - None - } + if imm.as_i16() == 0 { Some(()) } else { None } } #[inline] @@ -281,11 +273,7 @@ impl generated_code::Context for RV64IsleContext<'_, '_, MInst, Riscv64Backend> } #[inline] fn imm20_is_zero(&mut self, imm: Imm20) -> Option<()> { - if imm.as_i32() == 0 { - Some(()) - } else { - None - } + if imm.as_i32() == 0 { Some(()) } else { None } } #[inline] diff --git a/cranelift/codegen/src/isa/riscv64/mod.rs b/cranelift/codegen/src/isa/riscv64/mod.rs index 0035a721048c..dbd4249f3104 100644 --- a/cranelift/codegen/src/isa/riscv64/mod.rs +++ b/cranelift/codegen/src/isa/riscv64/mod.rs @@ -5,12 +5,12 @@ use crate::ir::{Function, Type}; use crate::isa::riscv64::settings as riscv_settings; use crate::isa::{Builder as IsaBuilder, FunctionAlignment, OwnedTargetIsa, TargetIsa}; use crate::machinst::{ - compile, CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, - TextSectionBuilder, VCode, + CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, + TextSectionBuilder, VCode, compile, }; use crate::result::CodegenResult; use crate::settings::{self as shared_settings, Flags}; -use crate::{ir, CodegenError}; +use crate::{CodegenError, ir}; use alloc::{boxed::Box, vec::Vec}; use core::fmt; use cranelift_control::ControlPlane; diff --git a/cranelift/codegen/src/isa/riscv64/settings.rs b/cranelift/codegen/src/isa/riscv64/settings.rs index 993062a9b831..119190f9a945 100644 --- a/cranelift/codegen/src/isa/riscv64/settings.rs +++ b/cranelift/codegen/src/isa/riscv64/settings.rs @@ -1,6 +1,6 @@ //! riscv64 Settings. -use crate::settings::{self, detail, Builder, Value}; +use crate::settings::{self, Builder, Value, detail}; use core::fmt; // Include code generated by `cranelift-codegen/meta/src/gen_settings.rs:`. This file contains a diff --git a/cranelift/codegen/src/isa/s390x/abi.rs b/cranelift/codegen/src/isa/s390x/abi.rs index 845599cb04a6..201372eb4bc0 100644 --- a/cranelift/codegen/src/isa/s390x/abi.rs +++ b/cranelift/codegen/src/isa/s390x/abi.rs @@ -132,21 +132,21 @@ //! (low address) //! ``` +use crate::CodegenResult; use crate::ir; -use crate::ir::condcodes::IntCC; -use crate::ir::types; use crate::ir::MemFlags; use crate::ir::Signature; use crate::ir::Type; +use crate::ir::condcodes::IntCC; +use crate::ir::types; use crate::isa; use crate::isa::s390x::{inst::*, settings as s390x_settings}; use crate::isa::unwind::UnwindInst; use crate::machinst::*; use crate::settings; -use crate::CodegenResult; use alloc::vec::Vec; use regalloc2::{MachineEnv, PRegSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::borrow::ToOwned; use std::sync::OnceLock; diff --git a/cranelift/codegen/src/isa/s390x/inst/args.rs b/cranelift/codegen/src/isa/s390x/inst/args.rs index 5134f9bd397f..5b6c7aa8525c 100644 --- a/cranelift/codegen/src/isa/s390x/inst/args.rs +++ b/cranelift/codegen/src/isa/s390x/inst/args.rs @@ -1,7 +1,7 @@ //! S390x ISA definitions: instruction arguments. -use crate::ir::condcodes::{FloatCC, IntCC}; use crate::ir::MemFlags; +use crate::ir::condcodes::{FloatCC, IntCC}; use crate::isa::s390x::inst::*; //============================================================================= diff --git a/cranelift/codegen/src/isa/s390x/inst/emit.rs b/cranelift/codegen/src/isa/s390x/inst/emit.rs index 53d383ea535a..72d64ff6dae3 100644 --- a/cranelift/codegen/src/isa/s390x/inst/emit.rs +++ b/cranelift/codegen/src/isa/s390x/inst/emit.rs @@ -175,17 +175,13 @@ pub fn mem_emit( emit_info: &EmitInfo, state: &mut EmitState, ) { - let (mem_insts, mem) = mem_finalize( - mem, - state, - MemInstType { - have_d12: opcode_rx.is_some(), - have_d20: opcode_rxy.is_some(), - have_pcrel: opcode_ril.is_some(), - have_unaligned_pcrel: opcode_ril.is_some() && !add_trap, - have_index: true, - }, - ); + let (mem_insts, mem) = mem_finalize(mem, state, MemInstType { + have_d12: opcode_rx.is_some(), + have_d20: opcode_rxy.is_some(), + have_pcrel: opcode_ril.is_some(), + have_unaligned_pcrel: opcode_ril.is_some() && !add_trap, + have_index: true, + }); for inst in mem_insts.into_iter() { inst.emit(sink, emit_info, state); } @@ -244,17 +240,13 @@ pub fn mem_rs_emit( emit_info: &EmitInfo, state: &mut EmitState, ) { - let (mem_insts, mem) = mem_finalize( - mem, - state, - MemInstType { - have_d12: opcode_rs.is_some(), - have_d20: opcode_rsy.is_some(), - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_insts, mem) = mem_finalize(mem, state, MemInstType { + have_d12: opcode_rs.is_some(), + have_d20: opcode_rsy.is_some(), + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); for inst in mem_insts.into_iter() { inst.emit(sink, emit_info, state); } @@ -295,17 +287,13 @@ pub fn mem_imm8_emit( emit_info: &EmitInfo, state: &mut EmitState, ) { - let (mem_insts, mem) = mem_finalize( - mem, - state, - MemInstType { - have_d12: true, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_insts, mem) = mem_finalize(mem, state, MemInstType { + have_d12: true, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); for inst in mem_insts.into_iter() { inst.emit(sink, emit_info, state); } @@ -342,17 +330,13 @@ pub fn mem_imm16_emit( emit_info: &EmitInfo, state: &mut EmitState, ) { - let (mem_insts, mem) = mem_finalize( - mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_insts, mem) = mem_finalize(mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); for inst in mem_insts.into_iter() { inst.emit(sink, emit_info, state); } @@ -384,17 +368,13 @@ pub fn mem_vrx_emit( emit_info: &EmitInfo, state: &mut EmitState, ) { - let (mem_insts, mem) = mem_finalize( - mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_insts, mem) = mem_finalize(mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); for inst in mem_insts.into_iter() { inst.emit(sink, emit_info, state); } diff --git a/cranelift/codegen/src/isa/s390x/inst/mod.rs b/cranelift/codegen/src/isa/s390x/inst/mod.rs index 75e7daab707f..5a33fde86366 100644 --- a/cranelift/codegen/src/isa/s390x/inst/mod.rs +++ b/cranelift/codegen/src/isa/s390x/inst/mod.rs @@ -1,11 +1,11 @@ //! This module defines s390x-specific machine instruction types. use crate::binemit::{Addend, CodeOffset, Reloc}; -use crate::ir::{types, ExternalName, Type}; +use crate::ir::{ExternalName, Type, types}; use crate::isa::s390x::abi::S390xMachineDeps; use crate::isa::{CallConv, FunctionAlignment}; use crate::machinst::*; -use crate::{settings, CodegenError, CodegenResult}; +use crate::{CodegenError, CodegenResult, settings}; use alloc::boxed::Box; use alloc::vec::Vec; use regalloc2::{PReg, PRegSet}; @@ -1030,13 +1030,10 @@ impl MachInst for Inst { const TRAP_OPCODE: &'static [u8] = &[0, 0]; fn get_operands(&mut self, collector: &mut impl OperandVisitor) { - s390x_get_operands( - self, - &mut DenyReuseVisitor { - inner: collector, - deny_reuse: false, - }, - ); + s390x_get_operands(self, &mut DenyReuseVisitor { + inner: collector, + deny_reuse: false, + }); } fn is_move(&self) -> Option<(Writable, Reg)> { @@ -1342,17 +1339,13 @@ impl Inst { let rd = pretty_print_reg_mod(rd, ri); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: opcode_rx.is_some(), - have_d20: opcode_rxy.is_some(), - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: opcode_rx.is_some(), + have_d20: opcode_rxy.is_some(), + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rx, &MemArg::BXD20 { .. } => opcode_rxy, @@ -1624,17 +1617,13 @@ impl Inst { let rn = pretty_print_reg(rn); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: opcode_rx.is_some(), - have_d20: opcode_rxy.is_some(), - have_pcrel: opcode_ril.is_some(), - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: opcode_rx.is_some(), + have_d20: opcode_rxy.is_some(), + have_pcrel: opcode_ril.is_some(), + have_unaligned_pcrel: false, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rx, &MemArg::BXD20 { .. } => opcode_rxy, @@ -1734,17 +1723,13 @@ impl Inst { let rd = pretty_print_reg(rd.to_reg()); let rn = pretty_print_reg(rn); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: false, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: false, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{op} {rd}, {rn}, {mem}") } @@ -1769,17 +1754,13 @@ impl Inst { let rd = pretty_print_reg_mod(rd, ri); let rn = pretty_print_reg(rn); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: opcode_rs.is_some(), - have_d20: opcode_rsy.is_some(), - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: opcode_rs.is_some(), + have_d20: opcode_rsy.is_some(), + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rs, &MemArg::BXD20 { .. } => opcode_rsy, @@ -1826,17 +1807,13 @@ impl Inst { let rd = pretty_print_reg(rd.to_reg()); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: opcode_rx.is_some(), - have_d20: opcode_rxy.is_some(), - have_pcrel: opcode_ril.is_some(), - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: opcode_rx.is_some(), + have_d20: opcode_rxy.is_some(), + have_pcrel: opcode_ril.is_some(), + have_unaligned_pcrel: false, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rx, &MemArg::BXD20 { .. } => opcode_rxy, @@ -1866,17 +1843,13 @@ impl Inst { let rd = pretty_print_reg(rd); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: opcode_rx.is_some(), - have_d20: opcode_rxy.is_some(), - have_pcrel: opcode_ril.is_some(), - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: opcode_rx.is_some(), + have_d20: opcode_rxy.is_some(), + have_pcrel: opcode_ril.is_some(), + have_unaligned_pcrel: false, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rx, &MemArg::BXD20 { .. } => opcode_rxy, @@ -1889,17 +1862,13 @@ impl Inst { } &Inst::StoreImm8 { imm, ref mem } => { let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); let op = match &mem { &MemArg::BXD12 { .. } => "mvi", &MemArg::BXD20 { .. } => "mviy", @@ -1913,17 +1882,13 @@ impl Inst { | &Inst::StoreImm32SExt16 { imm, ref mem } | &Inst::StoreImm64SExt16 { imm, ref mem } => { let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: false, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: false, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); let op = match self { &Inst::StoreImm16 { .. } => "mvhhi", &Inst::StoreImm32SExt16 { .. } => "mvhi", @@ -1936,17 +1901,13 @@ impl Inst { } &Inst::LoadMultiple64 { rt, rt2, ref mem } => { let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: false, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: false, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); let rt = pretty_print_reg(rt.to_reg()); let rt2 = pretty_print_reg(rt2.to_reg()); let mem = mem.pretty_print_default(); @@ -1954,17 +1915,13 @@ impl Inst { } &Inst::StoreMultiple64 { rt, rt2, ref mem } => { let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: false, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: false, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: false, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: false, + }); let rt = pretty_print_reg(rt); let rt2 = pretty_print_reg(rt2); let mem = mem.pretty_print_default(); @@ -2659,17 +2616,13 @@ impl Inst { let rd = pretty_print_reg(rd.to_reg()); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{opcode} {rd}, {mem}") } @@ -2695,17 +2648,13 @@ impl Inst { let rd = pretty_print_reg(rd); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{opcode} {rd}, {mem}") } @@ -2724,17 +2673,13 @@ impl Inst { let rd = pretty_print_reg(rd.to_reg()); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{opcode} {rd}, {mem}") } @@ -2841,17 +2786,13 @@ impl Inst { let (rd, _) = pretty_print_fpr(rd.to_reg()); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{opcode_vrx} {rd}, {mem}, {lane_imm}") } @@ -2881,17 +2822,13 @@ impl Inst { let (rd, rd_fpr) = pretty_print_fpr(rd.to_reg()); let mem = mem.clone(); if lane_imm == 0 && rd_fpr.is_some() && opcode_rx.is_some() { - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rx, &MemArg::BXD20 { .. } => opcode_rxy, @@ -2900,17 +2837,13 @@ impl Inst { let mem = mem.pretty_print_default(); format!("{}{} {}, {}", mem_str, op.unwrap(), rd_fpr.unwrap(), mem) } else { - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{opcode_vrx} {rd}, {mem}, {lane_imm}") } @@ -2941,17 +2874,13 @@ impl Inst { let (rd, rd_fpr) = pretty_print_fpr(rd); let mem = mem.clone(); if lane_imm == 0 && rd_fpr.is_some() && opcode_rx.is_some() { - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: true, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: true, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => opcode_rx, &MemArg::BXD20 { .. } => opcode_rxy, @@ -2960,17 +2889,13 @@ impl Inst { let mem = mem.pretty_print_default(); format!("{}{} {}, {}", mem_str, op.unwrap(), rd_fpr.unwrap(), mem) } else { - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: false, - have_pcrel: false, - have_unaligned_pcrel: false, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: false, + have_pcrel: false, + have_unaligned_pcrel: false, + have_index: true, + }); let mem = mem.pretty_print_default(); format!("{mem_str}{opcode_vrx} {rd}, {mem}, {lane_imm}",) } @@ -3263,17 +3188,13 @@ impl Inst { &Inst::LoadAddr { rd, ref mem } => { let rd = pretty_print_reg(rd.to_reg()); let mem = mem.clone(); - let (mem_str, mem) = mem_finalize_for_show( - &mem, - state, - MemInstType { - have_d12: true, - have_d20: true, - have_pcrel: true, - have_unaligned_pcrel: true, - have_index: true, - }, - ); + let (mem_str, mem) = mem_finalize_for_show(&mem, state, MemInstType { + have_d12: true, + have_d20: true, + have_pcrel: true, + have_unaligned_pcrel: true, + have_index: true, + }); let op = match &mem { &MemArg::BXD12 { .. } => "la", &MemArg::BXD20 { .. } => "lay", @@ -3290,7 +3211,9 @@ impl Inst { } => { let probe_count = pretty_print_reg(probe_count.to_reg()); let stack_reg = pretty_print_reg(stack_reg()); - format!("0: aghi {stack_reg}, -{guard_size} ; mvi 0({stack_reg}), 0 ; brct {probe_count}, 0b") + format!( + "0: aghi {stack_reg}, -{guard_size} ; mvi 0({stack_reg}), 0 ; brct {probe_count}, 0b" + ) } &Inst::Loop { ref body, cond } => { let body = body diff --git a/cranelift/codegen/src/isa/s390x/inst/unwind/systemv.rs b/cranelift/codegen/src/isa/s390x/inst/unwind/systemv.rs index 203fbc759133..6ae2c7e262d9 100644 --- a/cranelift/codegen/src/isa/s390x/inst/unwind/systemv.rs +++ b/cranelift/codegen/src/isa/s390x/inst/unwind/systemv.rs @@ -2,7 +2,7 @@ use crate::isa::unwind::systemv::RegisterMappingError; use crate::machinst::{Reg, RegClass}; -use gimli::{write::CommonInformationEntry, Encoding, Format, Register}; +use gimli::{Encoding, Format, Register, write::CommonInformationEntry}; /// Creates a new s390x common information entry (CIE). pub fn create_cie() -> CommonInformationEntry { @@ -97,13 +97,13 @@ impl crate::isa::unwind::systemv::RegisterMapper for RegisterMapper { #[cfg(test)] mod tests { + use crate::Context; use crate::cursor::{Cursor, FuncCursor}; use crate::ir::{ - types, AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, + AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, types, }; - use crate::isa::{lookup, CallConv}; - use crate::settings::{builder, Flags}; - use crate::Context; + use crate::isa::{CallConv, lookup}; + use crate::settings::{Flags, builder}; use gimli::write::Address; use target_lexicon::triple; @@ -133,7 +133,10 @@ mod tests { _ => panic!("expected unwind information"), }; - assert_eq!(format!("{fde:?}"), "FrameDescriptionEntry { address: Constant(1234), length: 10, lsda: None, instructions: [(4, CfaOffset(224))] }"); + assert_eq!( + format!("{fde:?}"), + "FrameDescriptionEntry { address: Constant(1234), length: 10, lsda: None, instructions: [(4, CfaOffset(224))] }" + ); } fn create_function(call_conv: CallConv, stack_slot: Option) -> Function { @@ -177,7 +180,10 @@ mod tests { _ => panic!("expected unwind information"), }; - assert_eq!(format!("{fde:?}"), "FrameDescriptionEntry { address: Constant(4321), length: 26, lsda: None, instructions: [(4, CfaOffset(224))] }"); + assert_eq!( + format!("{fde:?}"), + "FrameDescriptionEntry { address: Constant(4321), length: 26, lsda: None, instructions: [(4, CfaOffset(224))] }" + ); } fn create_multi_return_function( diff --git a/cranelift/codegen/src/isa/s390x/lower.rs b/cranelift/codegen/src/isa/s390x/lower.rs index eea3c1fdc985..9af0b96147e5 100644 --- a/cranelift/codegen/src/isa/s390x/lower.rs +++ b/cranelift/codegen/src/isa/s390x/lower.rs @@ -1,8 +1,8 @@ //! Lowering rules for S390x. use crate::ir::Inst as IRInst; -use crate::isa::s390x::inst::Inst; use crate::isa::s390x::S390xBackend; +use crate::isa::s390x::inst::Inst; use crate::machinst::{InstOutput, Lower, LowerBackend, MachLabel}; pub mod isle; diff --git a/cranelift/codegen/src/isa/s390x/lower/isle.rs b/cranelift/codegen/src/isa/s390x/lower/isle.rs index c65aa9c2184a..ee431a14ea36 100644 --- a/cranelift/codegen/src/isa/s390x/lower/isle.rs +++ b/cranelift/codegen/src/isa/s390x/lower/isle.rs @@ -5,19 +5,19 @@ pub mod generated_code; use crate::ir::ExternalName; // Types that the generated ISLE code uses via `use super::*`. -use crate::isa::s390x::abi::{S390xMachineDeps, REG_SAVE_AREA_SIZE}; +use crate::isa::s390x::S390xBackend; +use crate::isa::s390x::abi::{REG_SAVE_AREA_SIZE, S390xMachineDeps}; use crate::isa::s390x::inst::{ - gpr, stack_reg, writable_gpr, zero_reg, Cond, Inst as MInst, LaneOrder, MemArg, RegPair, - ReturnCallInfo, SymbolReloc, UImm12, UImm16Shifted, UImm32Shifted, WritableRegPair, + Cond, Inst as MInst, LaneOrder, MemArg, RegPair, ReturnCallInfo, SymbolReloc, UImm12, + UImm16Shifted, UImm32Shifted, WritableRegPair, gpr, stack_reg, writable_gpr, zero_reg, }; -use crate::isa::s390x::S390xBackend; use crate::machinst::isle::*; use crate::machinst::{CallInfo, MachLabel, Reg}; use crate::{ ir::{ - condcodes::*, immediates::*, types::*, ArgumentExtension, ArgumentPurpose, AtomicRmwOp, - BlockCall, Endianness, Inst, InstructionData, KnownSymbol, MemFlags, Opcode, TrapCode, - Value, ValueList, + ArgumentExtension, ArgumentPurpose, AtomicRmwOp, BlockCall, Endianness, Inst, + InstructionData, KnownSymbol, MemFlags, Opcode, TrapCode, Value, ValueList, condcodes::*, + immediates::*, types::*, }, isa::CallConv, machinst::abi::ABIMachineSpec, @@ -403,11 +403,7 @@ impl generated_code::Context for IsleContext<'_, '_, MInst, S390xBackend> { #[inline] fn i64_nonequal(&mut self, val: i64, cmp: i64) -> Option { - if val != cmp { - Some(val) - } else { - None - } + if val != cmp { Some(val) } else { None } } #[inline] @@ -468,21 +464,13 @@ impl generated_code::Context for IsleContext<'_, '_, MInst, S390xBackend> { #[inline] fn u64_nonzero_hipart(&mut self, n: u64) -> Option { let part = n & 0xffff_ffff_0000_0000; - if part != 0 { - Some(part) - } else { - None - } + if part != 0 { Some(part) } else { None } } #[inline] fn u64_nonzero_lopart(&mut self, n: u64) -> Option { let part = n & 0x0000_0000_ffff_ffff; - if part != 0 { - Some(part) - } else { - None - } + if part != 0 { Some(part) } else { None } } #[inline] @@ -868,11 +856,7 @@ impl generated_code::Context for IsleContext<'_, '_, MInst, S390xBackend> { #[inline] fn memarg_symbol_offset_sum(&mut self, off1: i64, off2: i64) -> Option { let off = i32::try_from(off1 + off2).ok()?; - if off & 1 == 0 { - Some(off) - } else { - None - } + if off & 1 == 0 { Some(off) } else { None } } #[inline] @@ -915,11 +899,7 @@ impl generated_code::Context for IsleContext<'_, '_, MInst, S390xBackend> { #[inline] fn same_reg(&mut self, dst: WritableReg, src: Reg) -> Option { - if dst.to_reg() == src { - Some(src) - } else { - None - } + if dst.to_reg() == src { Some(src) } else { None } } #[inline] diff --git a/cranelift/codegen/src/isa/s390x/mod.rs b/cranelift/codegen/src/isa/s390x/mod.rs index 842cc4cdf11e..7890da3eeb16 100644 --- a/cranelift/codegen/src/isa/s390x/mod.rs +++ b/cranelift/codegen/src/isa/s390x/mod.rs @@ -7,8 +7,8 @@ use crate::isa::s390x::settings as s390x_settings; use crate::isa::unwind::systemv::RegisterMappingError; use crate::isa::{Builder as IsaBuilder, FunctionAlignment, TargetIsa}; use crate::machinst::{ - compile, CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, - TextSectionBuilder, VCode, + CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, + TextSectionBuilder, VCode, compile, }; use crate::result::CodegenResult; use crate::settings as shared_settings; diff --git a/cranelift/codegen/src/isa/s390x/settings.rs b/cranelift/codegen/src/isa/s390x/settings.rs index 69859cee4feb..457aca49d355 100644 --- a/cranelift/codegen/src/isa/s390x/settings.rs +++ b/cranelift/codegen/src/isa/s390x/settings.rs @@ -1,6 +1,6 @@ //! S390X Settings. -use crate::settings::{self, detail, Builder, Value}; +use crate::settings::{self, Builder, Value, detail}; use core::fmt; // Include code generated by `cranelift-codegen/meta/src/gen_settings.rs:`. This file contains a diff --git a/cranelift/codegen/src/isa/unwind/systemv.rs b/cranelift/codegen/src/isa/unwind/systemv.rs index 5a721fbd8232..955c5f1b2c21 100644 --- a/cranelift/codegen/src/isa/unwind/systemv.rs +++ b/cranelift/codegen/src/isa/unwind/systemv.rs @@ -3,7 +3,7 @@ use crate::isa::unwind::UnwindInst; use crate::machinst::Reg; use crate::result::CodegenResult; -use crate::{binemit::CodeOffset, CodegenError}; +use crate::{CodegenError, binemit::CodeOffset}; use alloc::vec::Vec; use gimli::write::{Address, FrameDescriptionEntry}; @@ -95,7 +95,7 @@ impl From for CallFrameInstruction { impl Into for CallFrameInstruction { fn into(self) -> gimli::write::CallFrameInstruction { - use gimli::{write::CallFrameInstruction, write::Expression, Register}; + use gimli::{Register, write::CallFrameInstruction, write::Expression}; match self { Self::Cfa(reg, offset) => CallFrameInstruction::Cfa(Register(reg), offset), diff --git a/cranelift/codegen/src/isa/x64/abi.rs b/cranelift/codegen/src/isa/x64/abi.rs index 52005855553d..8b2fe703f8cb 100644 --- a/cranelift/codegen/src/isa/x64/abi.rs +++ b/cranelift/codegen/src/isa/x64/abi.rs @@ -1,20 +1,20 @@ //! Implementation of the standard x64 ABI. -use crate::ir::{self, types, LibCall, MemFlags, Signature, TrapCode}; -use crate::ir::{types::*, ExternalName}; +use crate::CodegenResult; +use crate::ir::{self, LibCall, MemFlags, Signature, TrapCode, types}; +use crate::ir::{ExternalName, types::*}; use crate::isa; use crate::isa::winch; use crate::isa::x64::X64Backend; -use crate::isa::{unwind::UnwindInst, x64::inst::*, x64::settings as x64_settings, CallConv}; +use crate::isa::{CallConv, unwind::UnwindInst, x64::inst::*, x64::settings as x64_settings}; use crate::machinst::abi::*; use crate::machinst::*; use crate::settings; -use crate::CodegenResult; use alloc::boxed::Box; use alloc::vec::Vec; use args::*; use regalloc2::{MachineEnv, PReg, PRegSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::borrow::ToOwned; use std::sync::OnceLock; diff --git a/cranelift/codegen/src/isa/x64/encoding/evex.rs b/cranelift/codegen/src/isa/x64/encoding/evex.rs index bacbf841643b..5d7d6dae024f 100644 --- a/cranelift/codegen/src/isa/x64/encoding/evex.rs +++ b/cranelift/codegen/src/isa/x64/encoding/evex.rs @@ -15,9 +15,9 @@ //! Software Development Manual, volume 2A). use super::rex::{self, LegacyPrefixes, OpcodeMap}; +use crate::MachBuffer; use crate::isa::x64::args::{Amode, Avx512TupleType}; use crate::isa::x64::inst::Inst; -use crate::MachBuffer; use core::ops::RangeInclusive; /// Constructs an EVEX-encoded instruction using a builder pattern. This approach makes it visually @@ -293,11 +293,7 @@ impl EvexInstruction { match self.tuple_type { Some(Full) => { if self.read(Self::b) == 1 { - if self.read(Self::W) == 0 { - 4 - } else { - 8 - } + if self.read(Self::W) == 0 { 4 } else { 8 } } else { vector_size_scaling() } diff --git a/cranelift/codegen/src/isa/x64/encoding/rex.rs b/cranelift/codegen/src/isa/x64/encoding/rex.rs index ae456b7d6545..d1ee0632a069 100644 --- a/cranelift/codegen/src/isa/x64/encoding/rex.rs +++ b/cranelift/codegen/src/isa/x64/encoding/rex.rs @@ -12,7 +12,7 @@ use super::ByteSink; use crate::isa::x64::inst::args::{Amode, OperandSize}; -use crate::isa::x64::inst::{regs, Inst, LabelUse}; +use crate::isa::x64::inst::{Inst, LabelUse, regs}; use crate::machinst::{MachBuffer, Reg, RegClass}; pub(crate) fn low8_will_sign_extend_to_64(x: u32) -> bool { diff --git a/cranelift/codegen/src/isa/x64/encoding/vex.rs b/cranelift/codegen/src/isa/x64/encoding/vex.rs index 44942570b679..7e23e74d72cf 100644 --- a/cranelift/codegen/src/isa/x64/encoding/vex.rs +++ b/cranelift/codegen/src/isa/x64/encoding/vex.rs @@ -1,9 +1,9 @@ //! Encodes VEX instructions. These instructions are those added by the Advanced Vector Extensions //! (AVX). +use super::ByteSink; use super::evex::{Register, RegisterOrAmode}; use super::rex::{LegacyPrefixes, OpcodeMap}; -use super::ByteSink; use crate::isa::x64::args::Amode; use crate::isa::x64::encoding::rex; use crate::isa::x64::inst::Inst; diff --git a/cranelift/codegen/src/isa/x64/inst/args.rs b/cranelift/codegen/src/isa/x64/inst/args.rs index 97c47276d4d0..61df5c27e9a7 100644 --- a/cranelift/codegen/src/isa/x64/inst/args.rs +++ b/cranelift/codegen/src/isa/x64/inst/args.rs @@ -1,13 +1,13 @@ //! Instruction operand sub-components (aka "parts"): definitions and printing. use super::regs::{self}; +use crate::ir::MemFlags; use crate::ir::condcodes::{FloatCC, IntCC}; use crate::ir::types::*; -use crate::ir::MemFlags; -use crate::isa::x64::inst::regs::pretty_print_reg; use crate::isa::x64::inst::Inst; +use crate::isa::x64::inst::regs::pretty_print_reg; use crate::machinst::*; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::fmt; use std::string::String; diff --git a/cranelift/codegen/src/isa/x64/inst/emit.rs b/cranelift/codegen/src/isa/x64/inst/emit.rs index 2a8ce8d7ff15..972e8bb9e130 100644 --- a/cranelift/codegen/src/isa/x64/inst/emit.rs +++ b/cranelift/codegen/src/isa/x64/inst/emit.rs @@ -1,10 +1,10 @@ -use crate::ir::immediates::{Ieee32, Ieee64}; use crate::ir::KnownSymbol; +use crate::ir::immediates::{Ieee32, Ieee64}; use crate::isa::x64::encoding::evex::{EvexInstruction, EvexVectorLength, RegisterOrAmode}; use crate::isa::x64::encoding::rex::{ - emit_simm, emit_std_enc_enc, emit_std_enc_mem, emit_std_reg_mem, emit_std_reg_reg, int_reg_enc, - low8_will_sign_extend_to_32, low8_will_sign_extend_to_64, reg_enc, LegacyPrefixes, OpcodeMap, - RexFlags, + LegacyPrefixes, OpcodeMap, RexFlags, emit_simm, emit_std_enc_enc, emit_std_enc_mem, + emit_std_reg_mem, emit_std_reg_reg, int_reg_enc, low8_will_sign_extend_to_32, + low8_will_sign_extend_to_64, reg_enc, }; use crate::isa::x64::encoding::vex::{VexInstruction, VexVectorLength}; use crate::isa::x64::inst::args::*; @@ -211,11 +211,7 @@ pub(crate) fn emit( if low8_will_sign_extend_to_32(simm32) { 1 } else { - if *size == OperandSize::Size16 { - 2 - } else { - 4 - } + if *size == OperandSize::Size16 { 2 } else { 4 } } }; @@ -672,11 +668,7 @@ pub(crate) fn emit( let imm_size = if i8::try_from(*src2).is_ok() { 1 } else { - if *size == OperandSize::Size16 { - 2 - } else { - 4 - } + if *size == OperandSize::Size16 { 2 } else { 4 } }; let opcode = if imm_size == 1 { 0x6B } else { 0x69 }; match src1 { diff --git a/cranelift/codegen/src/isa/x64/inst/mod.rs b/cranelift/codegen/src/isa/x64/inst/mod.rs index 39086b9f7e42..05334d2977c6 100644 --- a/cranelift/codegen/src/isa/x64/inst/mod.rs +++ b/cranelift/codegen/src/isa/x64/inst/mod.rs @@ -3,15 +3,15 @@ pub use emit_state::EmitState; use crate::binemit::{Addend, CodeOffset, Reloc}; -use crate::ir::{types, ExternalName, LibCall, TrapCode, Type}; +use crate::ir::{ExternalName, LibCall, TrapCode, Type, types}; use crate::isa::x64::abi::X64ABIMachineSpec; use crate::isa::x64::inst::regs::{pretty_print_reg, show_ireg_sized}; use crate::isa::x64::settings as x64_settings; use crate::isa::{CallConv, FunctionAlignment}; +use crate::{CodegenError, CodegenResult, settings}; use crate::{machinst::*, trace}; -use crate::{settings, CodegenError, CodegenResult}; use alloc::boxed::Box; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::fmt::{self, Write}; use std::string::{String, ToString}; @@ -1728,7 +1728,9 @@ impl PrettyPrint for Inst { let load_context_ptr = pretty_print_reg(**load_context_ptr, 8); let in_payload0 = pretty_print_reg(**in_payload0, 8); let out_payload0 = pretty_print_reg(*out_payload0.to_reg(), 8); - format!("{out_payload0} = stack_switch_basic {store_context_ptr}, {load_context_ptr}, {in_payload0}") + format!( + "{out_payload0} = stack_switch_basic {store_context_ptr}, {load_context_ptr}, {in_payload0}" + ) } Inst::JmpKnown { dst } => { @@ -1895,7 +1897,9 @@ impl PrettyPrint for Inst { let dst_old_low = pretty_print_reg(dst_old_low.to_reg(), 8); let dst_old_high = pretty_print_reg(dst_old_high.to_reg(), 8); let mem = mem.pretty_print(16); - format!("atomically {{ {dst_old_high}:{dst_old_low} = {mem}; {temp_high}:{temp_low} = {dst_old_high}:{dst_old_low} {op:?} {operand_high}:{operand_low}; {mem} = {temp_high}:{temp_low} }}") + format!( + "atomically {{ {dst_old_high}:{dst_old_low} = {mem}; {temp_high}:{temp_low} = {dst_old_high}:{dst_old_low} {op:?} {operand_high}:{operand_low}; {mem} = {temp_high}:{temp_low} }}" + ) } Inst::Atomic128XchgSeq { @@ -1910,7 +1914,9 @@ impl PrettyPrint for Inst { let dst_old_low = pretty_print_reg(dst_old_low.to_reg(), 8); let dst_old_high = pretty_print_reg(dst_old_high.to_reg(), 8); let mem = mem.pretty_print(16); - format!("atomically {{ {dst_old_high}:{dst_old_low} = {mem}; {mem} = {operand_high}:{operand_low} }}") + format!( + "atomically {{ {dst_old_high}:{dst_old_low} = {mem}; {mem} = {operand_high}:{operand_low} }}" + ) } Inst::Fence { kind } => match kind { diff --git a/cranelift/codegen/src/isa/x64/inst/unwind/systemv.rs b/cranelift/codegen/src/isa/x64/inst/unwind/systemv.rs index 948b9e4deb31..3f46843ab4f4 100644 --- a/cranelift/codegen/src/isa/x64/inst/unwind/systemv.rs +++ b/cranelift/codegen/src/isa/x64/inst/unwind/systemv.rs @@ -2,7 +2,7 @@ use crate::isa::unwind::systemv::RegisterMappingError; use crate::machinst::{Reg, RegClass}; -use gimli::{write::CommonInformationEntry, Encoding, Format, Register, X86_64}; +use gimli::{Encoding, Format, Register, X86_64, write::CommonInformationEntry}; /// Creates a new x86-64 common information entry (CIE). pub fn create_cie() -> CommonInformationEntry { @@ -93,13 +93,13 @@ impl crate::isa::unwind::systemv::RegisterMapper for RegisterMapper { #[cfg(test)] mod tests { + use crate::Context; use crate::cursor::{Cursor, FuncCursor}; use crate::ir::{ - types, AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, + AbiParam, Function, InstBuilder, Signature, StackSlotData, StackSlotKind, types, }; - use crate::isa::{lookup, CallConv}; - use crate::settings::{builder, Flags}; - use crate::Context; + use crate::isa::{CallConv, lookup}; + use crate::settings::{Flags, builder}; use gimli::write::Address; use target_lexicon::triple; @@ -129,7 +129,10 @@ mod tests { _ => panic!("expected unwind information"), }; - assert_eq!(format!("{fde:?}"), "FrameDescriptionEntry { address: Constant(1234), length: 17, lsda: None, instructions: [(1, CfaOffset(16)), (1, Offset(Register(6), -16)), (4, CfaRegister(Register(6)))] }"); + assert_eq!( + format!("{fde:?}"), + "FrameDescriptionEntry { address: Constant(1234), length: 17, lsda: None, instructions: [(1, CfaOffset(16)), (1, Offset(Register(6), -16)), (4, CfaRegister(Register(6)))] }" + ); } fn create_function(call_conv: CallConv, stack_slot: Option) -> Function { @@ -170,7 +173,10 @@ mod tests { _ => panic!("expected unwind information"), }; - assert_eq!(format!("{fde:?}"), "FrameDescriptionEntry { address: Constant(4321), length: 22, lsda: None, instructions: [(1, CfaOffset(16)), (1, Offset(Register(6), -16)), (4, CfaRegister(Register(6)))] }"); + assert_eq!( + format!("{fde:?}"), + "FrameDescriptionEntry { address: Constant(4321), length: 22, lsda: None, instructions: [(1, CfaOffset(16)), (1, Offset(Register(6), -16)), (4, CfaRegister(Register(6)))] }" + ); } fn create_multi_return_function(call_conv: CallConv) -> Function { diff --git a/cranelift/codegen/src/isa/x64/lower.rs b/cranelift/codegen/src/isa/x64/lower.rs index ae780089d4c5..56bf24f558c4 100644 --- a/cranelift/codegen/src/isa/x64/lower.rs +++ b/cranelift/codegen/src/isa/x64/lower.rs @@ -4,17 +4,17 @@ pub(super) mod isle; use crate::ir::pcc::{FactContext, PccResult}; -use crate::ir::{types, ExternalName, Inst as IRInst, InstructionData, LibCall, Opcode, Type}; +use crate::ir::{ExternalName, Inst as IRInst, InstructionData, LibCall, Opcode, Type, types}; use crate::isa::x64::abi::*; use crate::isa::x64::inst::args::*; use crate::isa::x64::inst::*; use crate::isa::x64::pcc; -use crate::isa::{x64::X64Backend, CallConv}; +use crate::isa::{CallConv, x64::X64Backend}; use crate::machinst::lower::*; use crate::machinst::*; use crate::result::CodegenResult; use crate::settings::Flags; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use target_lexicon::Triple; //============================================================================= @@ -200,13 +200,10 @@ fn emit_vm_call( /// The goal is to embed it within an address mode. fn matches_small_constant_shift(ctx: &mut Lower, spec: InsnInput) -> Option<(InsnInput, u8)> { matches_input(ctx, spec, Opcode::Ishl).and_then(|shift| { - match input_to_imm( - ctx, - InsnInput { - insn: shift, - input: 1, - }, - ) { + match input_to_imm(ctx, InsnInput { + insn: shift, + input: 1, + }) { Some(shift_amt) if shift_amt <= 3 => Some(( InsnInput { insn: shift, diff --git a/cranelift/codegen/src/isa/x64/lower/isle.rs b/cranelift/codegen/src/isa/x64/lower/isle.rs index 85268a90b6b8..2182355a2f7c 100644 --- a/cranelift/codegen/src/isa/x64/lower/isle.rs +++ b/cranelift/codegen/src/isa/x64/lower/isle.rs @@ -2,21 +2,21 @@ // Pull in the ISLE generated code. pub(crate) mod generated_code; -use crate::{ir::types, ir::AtomicRmwOp, isa}; +use crate::{ir::AtomicRmwOp, ir::types, isa}; use generated_code::{Context, MInst, RegisterClass}; // Types that the generated ISLE code uses via `use super::*`. -use super::{is_int_or_ref_ty, is_mergeable_load, lower_to_amode, MergeableLoadSize}; +use super::{MergeableLoadSize, is_int_or_ref_ty, is_mergeable_load, lower_to_amode}; use crate::ir::condcodes::{FloatCC, IntCC}; use crate::ir::immediates::*; use crate::ir::types::*; use crate::ir::{ BlockCall, Inst, InstructionData, LibCall, MemFlags, Opcode, TrapCode, Value, ValueList, }; +use crate::isa::x64::X64Backend; use crate::isa::x64::abi::X64CallSite; -use crate::isa::x64::inst::{args::*, regs, ReturnCallInfo}; +use crate::isa::x64::inst::{ReturnCallInfo, args::*, regs}; use crate::isa::x64::lower::emit_vm_call; -use crate::isa::x64::X64Backend; use crate::machinst::isle::*; use crate::machinst::{ ArgPair, CallInfo, InsnInput, InstOutput, IsTailCall, MachInst, VCodeConstant, @@ -902,11 +902,7 @@ impl Context for IsleContext<'_, '_, MInst, X64Backend> { // corresponding bit. let bit = |x: u8, c: u8| { if x % 8 == c { - if x < 8 { - Some(0) - } else { - Some(1 << c) - } + if x < 8 { Some(0) } else { Some(1 << c) } } else { None } diff --git a/cranelift/codegen/src/isa/x64/mod.rs b/cranelift/codegen/src/isa/x64/mod.rs index 7545a6f14835..e888d1bfb70a 100644 --- a/cranelift/codegen/src/isa/x64/mod.rs +++ b/cranelift/codegen/src/isa/x64/mod.rs @@ -1,17 +1,17 @@ //! X86_64-bit Instruction Set Architecture. -pub use self::inst::{args, EmitInfo, EmitState, Inst}; +pub use self::inst::{EmitInfo, EmitState, Inst, args}; use super::{OwnedTargetIsa, TargetIsa}; use crate::dominator_tree::DominatorTree; -use crate::ir::{types, Function, Type}; +use crate::ir::{Function, Type, types}; #[cfg(feature = "unwind")] use crate::isa::unwind::systemv; use crate::isa::x64::settings as x64_settings; use crate::isa::{Builder as IsaBuilder, FunctionAlignment}; use crate::machinst::{ - compile, CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, - TextSectionBuilder, VCode, + CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, + TextSectionBuilder, VCode, compile, }; use crate::result::CodegenResult; use crate::settings::{self as shared_settings, Flags}; diff --git a/cranelift/codegen/src/isa/x64/pcc.rs b/cranelift/codegen/src/isa/x64/pcc.rs index b3595ca7a06d..358780ce38ed 100644 --- a/cranelift/codegen/src/isa/x64/pcc.rs +++ b/cranelift/codegen/src/isa/x64/pcc.rs @@ -3,11 +3,11 @@ use crate::ir::pcc::*; use crate::ir::types::*; use crate::isa::x64::args::AvxOpcode; +use crate::isa::x64::inst::Inst; use crate::isa::x64::inst::args::{ - AluRmiROpcode, Amode, Gpr, Imm8Reg, RegMem, RegMemImm, ShiftKind, SseOpcode, SyntheticAmode, - ToWritableReg, CC, + AluRmiROpcode, Amode, CC, Gpr, Imm8Reg, RegMem, RegMemImm, ShiftKind, SseOpcode, + SyntheticAmode, ToWritableReg, }; -use crate::isa::x64::inst::Inst; use crate::machinst::pcc::*; use crate::machinst::{InsnIndex, VCode, VCodeConstantData}; use crate::machinst::{Reg, Writable}; @@ -992,17 +992,11 @@ fn check_load( ) -> PccResult> { let result_fact = dst.and_then(|dst| vcode.vreg_fact(dst.to_reg().into())); let from_bits = u16::try_from(ty.bits()).unwrap(); - check_mem( - ctx, - src, - vcode, - ty, - LoadOrStore::Load { - result_fact, - from_bits, - to_bits, - }, - ) + check_mem(ctx, src, vcode, ty, LoadOrStore::Load { + result_fact, + from_bits, + to_bits, + }) } fn check_store( @@ -1039,8 +1033,7 @@ fn check_mem<'a>( let loaded_fact = clamp_range(ctx, to_bits, from_bits, ctx.load(&addr, ty)?.cloned())?; trace!( "loaded_fact = {:?} result_fact = {:?}", - loaded_fact, - result_fact + loaded_fact, result_fact ); if ctx.subsumes_fact_optionals(loaded_fact.as_ref(), result_fact) { Ok(loaded_fact.clone()) diff --git a/cranelift/codegen/src/isa/x64/settings.rs b/cranelift/codegen/src/isa/x64/settings.rs index 501e153b46b3..98a64ddb6e57 100644 --- a/cranelift/codegen/src/isa/x64/settings.rs +++ b/cranelift/codegen/src/isa/x64/settings.rs @@ -1,6 +1,6 @@ //! x86 Settings. -use crate::settings::{self, detail, Builder, Value}; +use crate::settings::{self, Builder, Value, detail}; use core::fmt; // Include code generated by `cranelift-codegen/meta/src/gen_settings.rs:`. This file contains a diff --git a/cranelift/codegen/src/isle_prelude.rs b/cranelift/codegen/src/isle_prelude.rs index 2f346309b26e..621934853bf7 100644 --- a/cranelift/codegen/src/isle_prelude.rs +++ b/cranelift/codegen/src/isle_prelude.rs @@ -367,20 +367,12 @@ macro_rules! isle_common_prelude_methods { #[inline] fn ty_32(&mut self, ty: Type) -> Option { - if ty.bits() == 32 { - Some(ty) - } else { - None - } + if ty.bits() == 32 { Some(ty) } else { None } } #[inline] fn ty_64(&mut self, ty: Type) -> Option { - if ty.bits() == 64 { - Some(ty) - } else { - None - } + if ty.bits() == 64 { Some(ty) } else { None } } #[inline] @@ -441,20 +433,12 @@ macro_rules! isle_common_prelude_methods { #[inline] fn ty_scalar(&mut self, ty: Type) -> Option { - if ty.lane_count() == 1 { - Some(ty) - } else { - None - } + if ty.lane_count() == 1 { Some(ty) } else { None } } #[inline] fn ty_scalar_float(&mut self, ty: Type) -> Option { - if ty.is_float() { - Some(ty) - } else { - None - } + if ty.is_float() { Some(ty) } else { None } } #[inline] @@ -572,11 +556,7 @@ macro_rules! isle_common_prelude_methods { #[inline] fn u64_from_bool(&mut self, b: bool) -> u64 { - if b { - u64::MAX - } else { - 0 - } + if b { u64::MAX } else { 0 } } #[inline] @@ -640,11 +620,7 @@ macro_rules! isle_common_prelude_methods { } fn not_i64x2(&mut self, ty: Type) -> Option<()> { - if ty == I64X2 { - None - } else { - Some(()) - } + if ty == I64X2 { None } else { Some(()) } } fn trap_code_division_by_zero(&mut self) -> TrapCode { @@ -693,38 +669,22 @@ macro_rules! isle_common_prelude_methods { #[inline] fn u32_nonnegative(&mut self, x: u32) -> Option { - if (x as i32) >= 0 { - Some(x) - } else { - None - } + if (x as i32) >= 0 { Some(x) } else { None } } #[inline] fn u32_lteq(&mut self, a: u32, b: u32) -> Option<()> { - if a <= b { - Some(()) - } else { - None - } + if a <= b { Some(()) } else { None } } #[inline] fn u8_lteq(&mut self, a: u8, b: u8) -> Option<()> { - if a <= b { - Some(()) - } else { - None - } + if a <= b { Some(()) } else { None } } #[inline] fn u8_lt(&mut self, a: u8, b: u8) -> Option<()> { - if a < b { - Some(()) - } else { - None - } + if a < b { Some(()) } else { None } } #[inline] diff --git a/cranelift/codegen/src/legalizer/globalvalue.rs b/cranelift/codegen/src/legalizer/globalvalue.rs index 9837dd59278e..daef57d41d41 100644 --- a/cranelift/codegen/src/legalizer/globalvalue.rs +++ b/cranelift/codegen/src/legalizer/globalvalue.rs @@ -4,7 +4,7 @@ //! instruction into code that depends on the kind of global value referenced. use crate::cursor::{Cursor, FuncCursor}; -use crate::ir::{self, pcc::Fact, InstBuilder}; +use crate::ir::{self, InstBuilder, pcc::Fact}; use crate::isa::TargetIsa; /// Expand a `global_value` instruction according to the definition of the global value. diff --git a/cranelift/codegen/src/legalizer/mod.rs b/cranelift/codegen/src/legalizer/mod.rs index 5a45b45ba270..dbb041b19f43 100644 --- a/cranelift/codegen/src/legalizer/mod.rs +++ b/cranelift/codegen/src/legalizer/mod.rs @@ -15,7 +15,7 @@ use crate::cursor::{Cursor, FuncCursor}; use crate::ir::immediates::Imm64; -use crate::ir::types::{self, I128, I64}; +use crate::ir::types::{self, I64, I128}; use crate::ir::{self, InstBuilder, InstructionData, MemFlags, Value}; use crate::isa::TargetIsa; use crate::trace; diff --git a/cranelift/codegen/src/lib.rs b/cranelift/codegen/src/lib.rs index 55f7a12b3437..f52204decc31 100644 --- a/cranelift/codegen/src/lib.rs +++ b/cranelift/codegen/src/lib.rs @@ -21,9 +21,9 @@ extern crate alloc; extern crate std; #[cfg(not(feature = "std"))] -use hashbrown::{hash_map, HashMap}; +use hashbrown::{HashMap, hash_map}; #[cfg(feature = "std")] -use std::collections::{hash_map, HashMap}; +use std::collections::{HashMap, hash_map}; pub use crate::context::Context; pub use crate::value_label::{LabelValueLoc, ValueLabelsRanges, ValueLocRange}; diff --git a/cranelift/codegen/src/loop_analysis.rs b/cranelift/codegen/src/loop_analysis.rs index 71f845652233..0f457bca2f3c 100644 --- a/cranelift/codegen/src/loop_analysis.rs +++ b/cranelift/codegen/src/loop_analysis.rs @@ -2,8 +2,8 @@ //! and parent in the loop tree. use crate::dominator_tree::DominatorTree; -use crate::entity::entity_impl; use crate::entity::SecondaryMap; +use crate::entity::entity_impl; use crate::entity::{Keys, PrimaryMap}; use crate::flowgraph::ControlFlowGraph; use crate::ir::{Block, Function, Layout}; @@ -321,7 +321,7 @@ mod tests { use crate::cursor::{Cursor, FuncCursor}; use crate::dominator_tree::DominatorTree; use crate::flowgraph::ControlFlowGraph; - use crate::ir::{types, Function, InstBuilder}; + use crate::ir::{Function, InstBuilder, types}; use crate::loop_analysis::{Loop, LoopAnalysis}; use alloc::vec::Vec; diff --git a/cranelift/codegen/src/machinst/abi.rs b/cranelift/codegen/src/machinst/abi.rs index 1849a7e2ffcc..226606adb76f 100644 --- a/cranelift/codegen/src/machinst/abi.rs +++ b/cranelift/codegen/src/machinst/abi.rs @@ -98,12 +98,12 @@ //! registers. In some cases this is an extension of the base system //! ABI. See each platform's `abi.rs` implementation for details. +use crate::CodegenError; use crate::entity::SecondaryMap; use crate::ir::types::*; use crate::ir::{ArgumentExtension, ArgumentPurpose, Signature}; use crate::isa::TargetIsa; use crate::settings::ProbestackStrategy; -use crate::CodegenError; use crate::{ir, isa}; use crate::{machinst::*, trace}; use regalloc2::{MachineEnv, PReg, PRegSet}; @@ -2418,19 +2418,15 @@ impl CallSite { // function that establish the SP invariants that are relied on elsewhere and are generated // after the register allocator has run and thus cannot have register allocator-inserted // references to SP offsets.) - for inst in M::gen_call( - &self.dest, - tmp, - CallInfo { - dest: (), - uses, - defs, - clobbers, - callee_conv: call_conv, - caller_conv: self.caller_conv, - callee_pop_size, - }, - ) + for inst in M::gen_call(&self.dest, tmp, CallInfo { + dest: (), + uses, + defs, + clobbers, + callee_conv: call_conv, + caller_conv: self.caller_conv, + callee_pop_size, + }) .into_iter() { ctx.emit(inst); diff --git a/cranelift/codegen/src/machinst/blockorder.rs b/cranelift/codegen/src/machinst/blockorder.rs index b23fcf4859b1..119f99756249 100644 --- a/cranelift/codegen/src/machinst/blockorder.rs +++ b/cranelift/codegen/src/machinst/blockorder.rs @@ -326,8 +326,8 @@ mod test { use super::*; use crate::cursor::{Cursor, FuncCursor}; use crate::flowgraph::ControlFlowGraph; - use crate::ir::types::*; use crate::ir::UserFuncName; + use crate::ir::types::*; use crate::ir::{AbiParam, InstBuilder, Signature}; use crate::isa::CallConv; @@ -400,19 +400,16 @@ mod test { // // (3 -> 5, and 3 -> 6 are critical edges and must be split) // - let order = build_test_func( - 7, - &[ - (0, 1), - (0, 2), - (1, 3), - (1, 4), - (2, 5), - (3, 5), - (3, 6), - (4, 6), - ], - ); + let order = build_test_func(7, &[ + (0, 1), + (0, 2), + (1, 3), + (1, 4), + (2, 5), + (3, 5), + (3, 6), + (4, 6), + ]); assert_eq!(order.lowered_order.len(), 9); println!("ordered = {:?}", order.lowered_order); diff --git a/cranelift/codegen/src/machinst/buffer.rs b/cranelift/codegen/src/machinst/buffer.rs index 518b4cdbe389..a24cee079a02 100644 --- a/cranelift/codegen/src/machinst/buffer.rs +++ b/cranelift/codegen/src/machinst/buffer.rs @@ -178,10 +178,10 @@ use crate::machinst::{ BlockIndex, MachInstLabelUse, TextSectionBuilder, VCodeConstant, VCodeConstants, VCodeInst, }; use crate::trace; -use crate::{ir, MachInstEmitState}; -use crate::{timing, VCodeConstantData}; +use crate::{MachInstEmitState, ir}; +use crate::{VCodeConstantData, timing}; use cranelift_control::ControlPlane; -use cranelift_entity::{entity_impl, PrimaryMap}; +use cranelift_entity::{PrimaryMap, entity_impl}; use smallvec::SmallVec; use std::cmp::Ordering; use std::collections::BinaryHeap; @@ -718,9 +718,7 @@ impl MachBuffer { pub fn use_label_at_offset(&mut self, offset: CodeOffset, label: MachLabel, kind: I::LabelUse) { trace!( "MachBuffer: use_label_at_offset: offset {} label {:?} kind {:?}", - offset, - label, - kind + offset, label, kind ); // Add the fixup, and update the worst-case island size based on a @@ -864,8 +862,7 @@ impl MachBuffer { trace!( "truncate_last_branch: truncated {:?}; off now {}", - b, - cur_off + b, cur_off ); // Fix up resolved label offsets for labels at tail. @@ -925,9 +922,7 @@ impl MachBuffer { trace!( "enter optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}", - self.latest_branches, - self.labels_at_tail, - self.pending_fixup_records + self.latest_branches, self.labels_at_tail, self.pending_fixup_records ); // We continue to munch on branches at the tail of the buffer until no @@ -1093,8 +1088,7 @@ impl MachBuffer { for &l in &b.labels_at_this_branch { trace!( " -> label at start of branch {:?} redirected to target {:?}", - l, - b.target + l, b.target ); self.label_aliases[l.0 as usize] = b.target; // NOTE: we continue to ensure the invariant that labels @@ -1145,7 +1139,9 @@ impl MachBuffer { && prev_b.end == b.start && self.resolve_label_offset(prev_b.target) == cur_off { - trace!(" -> uncond follows a conditional, and conditional's target resolves to current offset"); + trace!( + " -> uncond follows a conditional, and conditional's target resolves to current offset" + ); // Save the target of the uncond (this becomes the // target of the cond), and truncate the uncond. let target = b.target; @@ -1186,9 +1182,7 @@ impl MachBuffer { trace!( "leave optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}", - self.latest_branches, - self.labels_at_tail, - self.pending_fixup_records + self.latest_branches, self.labels_at_tail, self.pending_fixup_records ); } @@ -1411,7 +1405,9 @@ impl MachBuffer { self.emit_veneer(label, offset, kind); } else { let slice = &mut self.data[start..end]; - trace!("patching in-range! slice = {slice:?}; offset = {offset:#x}; label_offset = {label_offset:#x}"); + trace!( + "patching in-range! slice = {slice:?}; offset = {offset:#x}; label_offset = {label_offset:#x}" + ); kind.patch(slice, offset, label_offset); } } else { @@ -1447,8 +1443,7 @@ impl MachBuffer { // Patch the original label use to refer to the veneer. trace!( "patching original at offset {} to veneer offset {}", - offset, - veneer_offset + offset, veneer_offset ); kind.patch(slice, offset, veneer_offset); // Generate the veneer. @@ -1457,8 +1452,7 @@ impl MachBuffer { kind.generate_veneer(veneer_slice, veneer_offset); trace!( "generated veneer; fixup offset {}, label_use {:?}", - veneer_fixup_off, - veneer_label_use + veneer_fixup_off, veneer_label_use ); // Register a new use of `label` with our new veneer fixup and // offset. This'll recalculate deadlines accordingly and @@ -2061,8 +2055,8 @@ mod test { use super::*; use crate::ir::UserExternalNameRef; - use crate::isa::aarch64::inst::{xreg, OperandSize}; use crate::isa::aarch64::inst::{BranchTarget, CondBrKind, EmitInfo, Inst}; + use crate::isa::aarch64::inst::{OperandSize, xreg}; use crate::machinst::{MachInstEmit, MachInstEmitState}; use crate::settings; diff --git a/cranelift/codegen/src/machinst/compile.rs b/cranelift/codegen/src/machinst/compile.rs index 2324e65ce2ff..c4c0071c3fca 100644 --- a/cranelift/codegen/src/machinst/compile.rs +++ b/cranelift/codegen/src/machinst/compile.rs @@ -1,14 +1,14 @@ //! Compilation backend pipeline: optimized IR to VCode / binemit. +use crate::CodegenError; use crate::dominator_tree::DominatorTree; -use crate::ir::pcc; use crate::ir::Function; +use crate::ir::pcc; use crate::isa::TargetIsa; use crate::machinst::*; use crate::settings::RegallocAlgorithm; use crate::timing; use crate::trace; -use crate::CodegenError; use regalloc2::{Algorithm, RegallocOptions}; diff --git a/cranelift/codegen/src/machinst/isle.rs b/cranelift/codegen/src/machinst/isle.rs index 8875097f1c51..72e608639913 100644 --- a/cranelift/codegen/src/machinst/isle.rs +++ b/cranelift/codegen/src/machinst/isle.rs @@ -7,7 +7,7 @@ use std::cell::Cell; pub use super::MachLabel; use super::RetPair; pub use crate::ir::{condcodes::CondCode, *}; -pub use crate::isa::{unwind::UnwindInst, TargetIsa}; +pub use crate::isa::{TargetIsa, unwind::UnwindInst}; pub use crate::machinst::{ ABIArg, ABIArgSlot, ABIMachineSpec, CallSite, InputSourceInst, Lower, LowerBackend, RealReg, Reg, RelocDistance, Sig, VCodeInst, Writable, @@ -517,11 +517,12 @@ macro_rules! isle_lower_prelude_methods { dst: WritableReg, stack_slot: DynamicStackSlot, ) -> MInst { - assert!(self - .lower_ctx - .abi() - .dynamic_stackslot_offsets() - .is_valid(stack_slot)); + assert!( + self.lower_ctx + .abi() + .dynamic_stackslot_offsets() + .is_valid(stack_slot) + ); self.lower_ctx .abi() .dynamic_stackslot_addr(stack_slot, dst) diff --git a/cranelift/codegen/src/machinst/lower.rs b/cranelift/codegen/src/machinst/lower.rs index ea4fda7fc8e8..510a4e043a06 100644 --- a/cranelift/codegen/src/machinst/lower.rs +++ b/cranelift/codegen/src/machinst/lower.rs @@ -15,16 +15,16 @@ use crate::ir::{ }; use crate::machinst::valueregs::InvalidSentinel; use crate::machinst::{ - writable_value_regs, BackwardsInsnIndex, BlockIndex, BlockLoweringOrder, Callee, InsnIndex, - LoweredBlock, MachLabel, Reg, SigSet, VCode, VCodeBuilder, VCodeConstant, VCodeConstantData, - VCodeConstants, VCodeInst, ValueRegs, Writable, + BackwardsInsnIndex, BlockIndex, BlockLoweringOrder, Callee, InsnIndex, LoweredBlock, MachLabel, + Reg, SigSet, VCode, VCodeBuilder, VCodeConstant, VCodeConstantData, VCodeConstants, VCodeInst, + ValueRegs, Writable, writable_value_regs, }; use crate::settings::Flags; -use crate::{trace, CodegenError, CodegenResult}; +use crate::{CodegenError, CodegenResult, trace}; use alloc::vec::Vec; use cranelift_control::ControlPlane; use rustc_hash::{FxHashMap, FxHashSet}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::fmt::Debug; use super::{VCodeBuildDirection, VRegAllocator}; @@ -408,11 +408,7 @@ impl<'func, I: VCodeInst> Lower<'func, I> { value_regs[result] = regs; trace!( "bb {} inst {} ({:?}): result {} regs {:?}", - bb, - inst, - f.dfg.insts[inst], - result, - regs, + bb, inst, f.dfg.insts[inst], result, regs, ); } } @@ -822,9 +818,7 @@ impl<'func, I: VCodeInst> Lower<'func, I> { for label in labels { trace!( "value labeling: defines val {:?} -> reg {:?} -> label {:?}", - val, - reg, - label, + val, reg, label, ); self.vcode.add_value_label(reg, label); } @@ -883,9 +877,7 @@ impl<'func, I: VCodeInst> Lower<'func, I> { ) -> CodegenResult<()> { trace!( "lower_clif_branches: block {} branch {:?} targets {:?}", - block, - branch, - targets, + block, branch, targets, ); // When considering code-motion opportunities, consider the current // program point to be this branch. @@ -1040,8 +1032,7 @@ impl<'func, I: VCodeInst> Lower<'func, I> { // VCodeBuilder, let's build the VCode. trace!( "built vcode:\n{:?}Backwards {:?}", - &self.vregs, - &self.vcode.vcode + &self.vregs, &self.vcode.vcode ); let vcode = self.vcode.build(self.vregs); @@ -1345,9 +1336,7 @@ impl<'func, I: VCodeInst> Lower<'func, I> { pub fn get_value_as_source_or_const(&self, val: Value) -> NonRegInput { trace!( "get_input_for_val: val {} at cur_inst {:?} cur_scan_entry_color {:?}", - val, - self.cur_inst, - self.cur_scan_entry_color, + val, self.cur_inst, self.cur_scan_entry_color, ); let inst = match self.f.dfg.value_def(val) { // OK to merge source instruction if we have a source @@ -1413,9 +1402,7 @@ impl<'func, I: VCodeInst> Lower<'func, I> { // the code-motion. trace!( " -> side-effecting op {} for val {}: use state {:?}", - src_inst, - val, - self.value_ir_uses[val] + src_inst, val, self.value_ir_uses[val] ); if self.cur_scan_entry_color.is_some() && self.value_ir_uses[val] == ValueUseState::Once @@ -1540,14 +1527,12 @@ impl<'func, I: VCodeInst> Lower<'func, I> { /// Add a range fact to a register, if no other fact is present. pub fn add_range_fact(&mut self, reg: Reg, bit_width: u16, min: u64, max: u64) { if self.flags.enable_pcc() { - self.vregs.set_fact_if_missing( - reg.to_virtual_reg().unwrap(), - Fact::Range { + self.vregs + .set_fact_if_missing(reg.to_virtual_reg().unwrap(), Fact::Range { bit_width, min, max, - }, - ); + }); } } } diff --git a/cranelift/codegen/src/machinst/mod.rs b/cranelift/codegen/src/machinst/mod.rs index ed07b1bf0365..062544355145 100644 --- a/cranelift/codegen/src/machinst/mod.rs +++ b/cranelift/codegen/src/machinst/mod.rs @@ -46,7 +46,7 @@ use crate::binemit::{Addend, CodeInfo, CodeOffset, Reloc}; use crate::ir::{ - self, function::FunctionParameters, DynamicStackSlot, RelSourceLoc, StackSlot, Type, + self, DynamicStackSlot, RelSourceLoc, StackSlot, Type, function::FunctionParameters, }; use crate::isa::FunctionAlignment; use crate::result::CodegenResult; @@ -58,7 +58,7 @@ use core::fmt::Debug; use cranelift_control::ControlPlane; use cranelift_entity::PrimaryMap; use regalloc2::VReg; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::string::String; #[cfg(feature = "enable-serde")] diff --git a/cranelift/codegen/src/machinst/pcc.rs b/cranelift/codegen/src/machinst/pcc.rs index 0c70a023838f..046b2ca3b3e2 100644 --- a/cranelift/codegen/src/machinst/pcc.rs +++ b/cranelift/codegen/src/machinst/pcc.rs @@ -38,9 +38,7 @@ pub(crate) fn clamp_range( }; trace!( "clamp_range: fact {:?} from {} to {}", - fact, - from_bits, - to_bits + fact, from_bits, to_bits ); Ok(fact .and_then(|f| ctx.uextend(&f, from_bits, to_bits)) @@ -66,8 +64,7 @@ pub(crate) fn check_subsumes_optionals( ) -> PccResult<()> { trace!( "checking if derived fact {:?} subsumes stated fact {:?}", - subsumer, - subsumee + subsumer, subsumee ); if ctx.subsumes_fact_optionals(subsumer, subsumee) { diff --git a/cranelift/codegen/src/machinst/vcode.rs b/cranelift/codegen/src/machinst/vcode.rs index 12c816530f04..f745ee09bd9f 100644 --- a/cranelift/codegen/src/machinst/vcode.rs +++ b/cranelift/codegen/src/machinst/vcode.rs @@ -17,13 +17,13 @@ //! See the main module comment in `mod.rs` for more details on the VCode-based //! backend pipeline. +use crate::CodegenError; use crate::ir::pcc::*; -use crate::ir::{self, types, Constant, ConstantData, ValueLabel}; +use crate::ir::{self, Constant, ConstantData, ValueLabel, types}; use crate::machinst::*; use crate::ranges::Ranges; use crate::timing; use crate::trace; -use crate::CodegenError; use crate::{LabelValueLoc, ValueLocRange}; use regalloc2::{ Edit, Function as RegallocFunction, InstOrEdit, InstRange, MachineEnv, Operand, @@ -32,9 +32,9 @@ use regalloc2::{ use rustc_hash::FxHashMap; use core::mem::take; -use cranelift_entity::{entity_impl, Keys}; -use std::collections::hash_map::Entry; +use cranelift_entity::{Keys, entity_impl}; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::fmt; /// Index referring to an instruction in VCode. @@ -1109,9 +1109,7 @@ impl VCode { if inst_offset > next_offset { trace!( "Fixing code offset of the removed Inst {}: {} -> {}", - inst_index, - inst_offset, - next_offset + inst_index, inst_offset, next_offset ); inst_offsets[inst_index] = next_offset; continue; @@ -1189,9 +1187,7 @@ impl VCode { if last_loc_range.loc == loc && last_loc_range.end == start { trace!( "Extending debug range for VL{} in {:?} to {}", - label, - loc, - end + label, loc, end ); last_loc_range.end = end; continue; @@ -1732,11 +1728,7 @@ impl VCodeConstantData { /// Calculate the alignment of the constant data. pub fn alignment(&self) -> u32 { - if self.as_slice().len() <= 8 { - 8 - } else { - 16 - } + if self.as_slice().len() <= 8 { 8 } else { 16 } } } diff --git a/cranelift/codegen/src/opts.rs b/cranelift/codegen/src/opts.rs index c22a0ab2e0bc..3f7c4ffd5948 100644 --- a/cranelift/codegen/src/opts.rs +++ b/cranelift/codegen/src/opts.rs @@ -3,7 +3,7 @@ use crate::egraph::{NewOrExistingInst, OptimizeCtx}; pub use crate::ir::condcodes::{FloatCC, IntCC}; use crate::ir::dfg::ValueDef; -pub use crate::ir::immediates::{Ieee128, Ieee16, Ieee32, Ieee64, Imm64, Offset32, Uimm8, V128Imm}; +pub use crate::ir::immediates::{Ieee16, Ieee32, Ieee64, Ieee128, Imm64, Offset32, Uimm8, V128Imm}; use crate::ir::instructions::InstructionFormat; pub use crate::ir::types::*; pub use crate::ir::{ @@ -14,7 +14,7 @@ use crate::isle_common_prelude_methods; use crate::machinst::isle::*; use crate::trace; use cranelift_entity::packed_option::ReservedValue; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::marker::PhantomData; #[allow(dead_code)] diff --git a/cranelift/codegen/src/print_errors.rs b/cranelift/codegen/src/print_errors.rs index 23195bf88f7a..21a2767267e8 100644 --- a/cranelift/codegen/src/print_errors.rs +++ b/cranelift/codegen/src/print_errors.rs @@ -7,7 +7,7 @@ use crate::ir::function::Function; use crate::ir::pcc::Fact; use crate::result::CodegenError; use crate::verifier::{VerifierError, VerifierErrors}; -use crate::write::{decorate_function, FuncWriter, PlainWriter}; +use crate::write::{FuncWriter, PlainWriter, decorate_function}; use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec::Vec; diff --git a/cranelift/codegen/src/scoped_hash_map.rs b/cranelift/codegen/src/scoped_hash_map.rs index 170a6140d259..fb2093cb6049 100644 --- a/cranelift/codegen/src/scoped_hash_map.rs +++ b/cranelift/codegen/src/scoped_hash_map.rs @@ -6,7 +6,7 @@ use core::hash::Hash; use rustc_hash::FxHashMap; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; #[cfg(not(feature = "std"))] use crate::fx::FxHasher; diff --git a/cranelift/codegen/src/settings.rs b/cranelift/codegen/src/settings.rs index d8c2ad198e92..033e27d6050d 100644 --- a/cranelift/codegen/src/settings.rs +++ b/cranelift/codegen/src/settings.rs @@ -500,7 +500,7 @@ impl<'a> From<&'a dyn TargetIsa> for FlagsOrIsa<'a> { mod tests { use super::Configurable; use super::SetError::*; - use super::{builder, Flags}; + use super::{Flags, builder}; use alloc::string::ToString; #[test] diff --git a/cranelift/codegen/src/timing.rs b/cranelift/codegen/src/timing.rs index c634b5d90748..f0e362949605 100644 --- a/cranelift/codegen/src/timing.rs +++ b/cranelift/codegen/src/timing.rs @@ -213,7 +213,7 @@ pub fn take_current() -> PassTimes { #[cfg(feature = "timing")] mod enabled { - use super::{DefaultProfiler, Pass, Profiler, PASS_TIME}; + use super::{DefaultProfiler, PASS_TIME, Pass, Profiler}; use std::any::Any; use std::boxed::Box; use std::cell::Cell; diff --git a/cranelift/codegen/src/traversals.rs b/cranelift/codegen/src/traversals.rs index b3234601bf46..8deb4ee2709f 100644 --- a/cranelift/codegen/src/traversals.rs +++ b/cranelift/codegen/src/traversals.rs @@ -161,7 +161,7 @@ impl Iterator for DfsPostOrderIter<'_> { mod tests { use super::*; use crate::cursor::{Cursor, FuncCursor}; - use crate::ir::{types::I32, Function, InstBuilder, TrapCode}; + use crate::ir::{Function, InstBuilder, TrapCode, types::I32}; #[test] fn test_dfs_traversal() { @@ -203,16 +203,13 @@ mod tests { let mut dfs = Dfs::new(); - assert_eq!( - dfs.iter(&func).collect::>(), - vec![ - (Event::Enter, block0), - (Event::Enter, block2), - (Event::Exit, block2), - (Event::Enter, block3), - (Event::Exit, block3), - (Event::Exit, block0) - ], - ); + assert_eq!(dfs.iter(&func).collect::>(), vec![ + (Event::Enter, block0), + (Event::Enter, block2), + (Event::Exit, block2), + (Event::Enter, block3), + (Event::Exit, block3), + (Event::Exit, block0) + ],); } } diff --git a/cranelift/codegen/src/unionfind.rs b/cranelift/codegen/src/unionfind.rs index da96611ec366..42dc8a35549f 100644 --- a/cranelift/codegen/src/unionfind.rs +++ b/cranelift/codegen/src/unionfind.rs @@ -1,7 +1,7 @@ //! Simple union-find data structure. use crate::trace; -use cranelift_entity::{packed_option::ReservedValue, EntityRef, SecondaryMap}; +use cranelift_entity::{EntityRef, SecondaryMap, packed_option::ReservedValue}; use std::hash::Hash; use std::mem::swap; diff --git a/cranelift/codegen/src/value_label.rs b/cranelift/codegen/src/value_label.rs index e388b8aa1948..65b3e7d1eac9 100644 --- a/cranelift/codegen/src/value_label.rs +++ b/cranelift/codegen/src/value_label.rs @@ -1,6 +1,6 @@ +use crate::HashMap; use crate::ir::ValueLabel; use crate::machinst::Reg; -use crate::HashMap; use alloc::vec::Vec; #[cfg(feature = "enable-serde")] diff --git a/cranelift/codegen/src/verifier/mod.rs b/cranelift/codegen/src/verifier/mod.rs index 33d9132f8e68..cc92c4d7f0dc 100644 --- a/cranelift/codegen/src/verifier/mod.rs +++ b/cranelift/codegen/src/verifier/mod.rs @@ -71,9 +71,9 @@ use crate::ir::entities::AnyEntity; use crate::ir::instructions::{CallInfo, InstructionFormat, ResolvedConstraint}; use crate::ir::{self, ArgumentExtension}; use crate::ir::{ - types, ArgumentPurpose, Block, Constant, DynamicStackSlot, FuncRef, Function, GlobalValue, - Inst, JumpTable, MemFlags, MemoryTypeData, Opcode, SigRef, StackSlot, Type, Value, ValueDef, - ValueList, + ArgumentPurpose, Block, Constant, DynamicStackSlot, FuncRef, Function, GlobalValue, Inst, + JumpTable, MemFlags, MemoryTypeData, Opcode, SigRef, StackSlot, Type, Value, ValueDef, + ValueList, types, }; use crate::isa::TargetIsa; use crate::print_errors::pretty_verifier_error; @@ -202,11 +202,7 @@ impl VerifierErrors { /// and non-fatal otherwise. #[inline] pub fn as_result(&self) -> VerifierStepResult { - if self.is_empty() { - Ok(()) - } else { - Err(()) - } + if self.is_empty() { Ok(()) } else { Err(()) } } /// Report an error, adding it to the list of errors. @@ -241,11 +237,7 @@ impl Into> for VerifierErrors { impl Into> for VerifierErrors { fn into(self) -> VerifierResult<()> { - if self.is_empty() { - Ok(()) - } else { - Err(self) - } + if self.is_empty() { Ok(()) } else { Err(self) } } } @@ -1688,11 +1680,7 @@ impl<'a> Verifier<'a> { } } - if errors.has_error() { - Err(()) - } else { - Ok(()) - } + if errors.has_error() { Err(()) } else { Ok(()) } } pub fn run(&self, errors: &mut VerifierErrors) -> VerifierStepResult { @@ -1732,7 +1720,7 @@ impl<'a> Verifier<'a> { mod tests { use super::{Verifier, VerifierError, VerifierErrors}; use crate::ir::instructions::{InstructionData, Opcode}; - use crate::ir::{types, AbiParam, Function, Type}; + use crate::ir::{AbiParam, Function, Type, types}; use crate::settings; macro_rules! assert_err_with_msg { diff --git a/cranelift/entity/src/boxed_slice.rs b/cranelift/entity/src/boxed_slice.rs index 3b3b39155be5..5b4ac099874a 100644 --- a/cranelift/entity/src/boxed_slice.rs +++ b/cranelift/entity/src/boxed_slice.rs @@ -1,8 +1,8 @@ //! Boxed slices for `PrimaryMap`. +use crate::EntityRef; use crate::iter::{Iter, IterMut}; use crate::keys::Keys; -use crate::EntityRef; use alloc::boxed::Box; use core::marker::PhantomData; use core::ops::{Index, IndexMut}; diff --git a/cranelift/entity/src/list.rs b/cranelift/entity/src/list.rs index 29a6293c19bc..54d7141a5953 100644 --- a/cranelift/entity/src/list.rs +++ b/cranelift/entity/src/list.rs @@ -1,6 +1,6 @@ //! Small lists of entity references. -use crate::packed_option::ReservedValue; use crate::EntityRef; +use crate::packed_option::ReservedValue; use alloc::vec::Vec; use core::marker::PhantomData; use core::mem; @@ -784,10 +784,9 @@ mod tests { list.extend([i1, i1, i2, i2, i3, i3, i4, i4].iter().cloned(), pool); assert_eq!(list.len(pool), 12); - assert_eq!( - list.as_slice(pool), - &[i1, i2, i3, i4, i1, i1, i2, i2, i3, i3, i4, i4] - ); + assert_eq!(list.as_slice(pool), &[ + i1, i2, i3, i4, i1, i1, i2, i2, i3, i3, i4, i4 + ]); let list2 = EntityList::from_iter([i1, i1, i2, i2, i3, i3, i4, i4].iter().cloned(), pool); assert_eq!(list2.len(pool), 8); @@ -941,14 +940,12 @@ mod tests { assert_eq!(list.as_slice(pool), &[i4, i3, i2, i1, i1, i2, i3, i4]); // Panic should occur on the line below because `list.index == other.index` list.copy_from(&list_again, 0..=1, 8, pool); - assert_eq!( - list.as_slice(pool), - &[i4, i3, i2, i1, i1, i2, i3, i4, i4, i3] - ); + assert_eq!(list.as_slice(pool), &[ + i4, i3, i2, i1, i1, i2, i3, i4, i4, i3 + ]); list.copy_from(&list_again, .., 7, pool); - assert_eq!( - list.as_slice(pool), - &[i4, i3, i2, i1, i1, i2, i4, i3, i2, i1, i1, i2, i3, i4, i4, i3, i3, i4, i4, i3] - ) + assert_eq!(list.as_slice(pool), &[ + i4, i3, i2, i1, i1, i2, i4, i3, i2, i1, i1, i2, i3, i4, i4, i3, i3, i4, i4, i3 + ]) } } diff --git a/cranelift/entity/src/map.rs b/cranelift/entity/src/map.rs index 332cd061b73d..6181ddb692f4 100644 --- a/cranelift/entity/src/map.rs +++ b/cranelift/entity/src/map.rs @@ -1,8 +1,8 @@ //! Densely numbered entity references as mapping keys. +use crate::EntityRef; use crate::iter::{Iter, IterMut}; use crate::keys::Keys; -use crate::EntityRef; use alloc::vec::Vec; use core::cmp::min; use core::marker::PhantomData; @@ -10,9 +10,9 @@ use core::ops::{Index, IndexMut}; use core::slice; #[cfg(feature = "enable-serde")] use serde::{ + Deserialize, Serialize, de::{Deserializer, SeqAccess, Visitor}, ser::{SerializeSeq, Serializer}, - Deserialize, Serialize, }; /// A mapping `K -> V` for densely indexed entity references. diff --git a/cranelift/entity/src/packed_option.rs b/cranelift/entity/src/packed_option.rs index e4b949f34818..24d357992df9 100644 --- a/cranelift/entity/src/packed_option.rs +++ b/cranelift/entity/src/packed_option.rs @@ -43,11 +43,7 @@ impl PackedOption { /// Expand the packed option into a normal `Option`. pub fn expand(self) -> Option { - if self.is_none() { - None - } else { - Some(self.0) - } + if self.is_none() { None } else { Some(self.0) } } /// Maps a `PackedOption` to `Option` by applying a function to a contained value. diff --git a/cranelift/entity/src/primary.rs b/cranelift/entity/src/primary.rs index b47e8073db9c..1c7463a762bf 100644 --- a/cranelift/entity/src/primary.rs +++ b/cranelift/entity/src/primary.rs @@ -1,8 +1,8 @@ //! Densely numbered entity references as mapping keys. +use crate::EntityRef; use crate::boxed_slice::BoxedSlice; use crate::iter::{IntoIter, Iter, IterMut}; use crate::keys::Keys; -use crate::EntityRef; use alloc::boxed::Box; use alloc::vec::Vec; use core::marker::PhantomData; diff --git a/cranelift/entity/src/set.rs b/cranelift/entity/src/set.rs index 3c5925a219b8..5d3c5e2dc881 100644 --- a/cranelift/entity/src/set.rs +++ b/cranelift/entity/src/set.rs @@ -1,7 +1,7 @@ //! Densely numbered entity references as set keys. -use crate::keys::Keys; use crate::EntityRef; +use crate::keys::Keys; use core::marker::PhantomData; use cranelift_bitset::CompoundBitSet; diff --git a/cranelift/entity/src/sparse.rs b/cranelift/entity/src/sparse.rs index 0993e070ccde..079ebf660bd4 100644 --- a/cranelift/entity/src/sparse.rs +++ b/cranelift/entity/src/sparse.rs @@ -7,8 +7,8 @@ //! > Briggs, Torczon, *An efficient representation for sparse sets*, //! > ACM Letters on Programming Languages and Systems, Volume 2, Issue 1-4, March-Dec. 1993. -use crate::map::SecondaryMap; use crate::EntityRef; +use crate::map::SecondaryMap; use alloc::vec::Vec; use core::fmt; use core::mem; @@ -334,10 +334,9 @@ mod tests { assert_eq!(map.insert(Obj(i0, "baz")), None); // Iteration order = insertion order when nothing has been removed yet. - assert_eq!( - map.values().map(|obj| obj.1).collect::>(), - ["foo", "bar", "baz"] - ); + assert_eq!(map.values().map(|obj| obj.1).collect::>(), [ + "foo", "bar", "baz" + ]); assert_eq!(map.len(), 3); assert_eq!(map.get(i0), Some(&Obj(i0, "baz"))); diff --git a/cranelift/filetests/src/concurrent.rs b/cranelift/filetests/src/concurrent.rs index fec83b3b957b..8c272579ba76 100644 --- a/cranelift/filetests/src/concurrent.rs +++ b/cranelift/filetests/src/concurrent.rs @@ -9,7 +9,7 @@ use cranelift_codegen::timing; use log::error; use std::panic::catch_unwind; use std::path::{Path, PathBuf}; -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; diff --git a/cranelift/filetests/src/function_runner.rs b/cranelift/filetests/src/function_runner.rs index e4f9e3b3b472..635b3db717c8 100644 --- a/cranelift/filetests/src/function_runner.rs +++ b/cranelift/filetests/src/function_runner.rs @@ -1,12 +1,12 @@ //! Provides functionality for compiling and running CLIF IR for `run` tests. -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use core::mem; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::{ ExternalName, Function, InstBuilder, Signature, UserExternalName, UserFuncName, }; use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; -use cranelift_codegen::{ir, settings, CodegenError, Context}; +use cranelift_codegen::{CodegenError, Context, ir, settings}; use cranelift_control::ControlPlane; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_jit::{JITBuilder, JITModule}; @@ -15,8 +15,8 @@ use cranelift_native::builder_with_options; use cranelift_reader::TestFile; use pulley_interpreter::interp as pulley; use std::cmp::max; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::ptr::NonNull; use target_lexicon::Architecture; use thiserror::Error; @@ -613,7 +613,7 @@ extern "C" fn __cranelift_x86_pshufb(a: __m128i, b: __m128i) -> __m128i { #[cfg(test)] mod test { use super::*; - use cranelift_reader::{parse_functions, parse_test, ParseOptions}; + use cranelift_reader::{ParseOptions, parse_functions, parse_test}; fn parse(code: &str) -> Function { parse_functions(code).unwrap().into_iter().nth(0).unwrap() diff --git a/cranelift/filetests/src/runone.rs b/cranelift/filetests/src/runone.rs index 0ac1c55e75b7..bb6788ed8e27 100644 --- a/cranelift/filetests/src/runone.rs +++ b/cranelift/filetests/src/runone.rs @@ -2,13 +2,13 @@ use crate::new_subtest; use crate::subtest::SubTest; -use anyhow::{bail, Context as _, Result}; +use anyhow::{Context as _, Result, bail}; use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{Flags, FlagsOrIsa}; use cranelift_codegen::timing; use cranelift_codegen::verify_function; -use cranelift_reader::{parse_test, IsaSpec, Location, ParseOptions, TestFile}; +use cranelift_reader::{IsaSpec, Location, ParseOptions, TestFile, parse_test}; use log::info; use std::cell::Cell; use std::fs; diff --git a/cranelift/filetests/src/subtest.rs b/cranelift/filetests/src/subtest.rs index 5321a4e1c9f0..cf5589ffc6ed 100644 --- a/cranelift/filetests/src/subtest.rs +++ b/cranelift/filetests/src/subtest.rs @@ -2,7 +2,7 @@ use crate::runone::FileUpdate; use anyhow::Context as _; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use cranelift_codegen::ir::Function; use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::settings::{Flags, FlagsOrIsa}; diff --git a/cranelift/filetests/src/test_alias_analysis.rs b/cranelift/filetests/src/test_alias_analysis.rs index 029392d40d98..2ff4f4f19c17 100644 --- a/cranelift/filetests/src/test_alias_analysis.rs +++ b/cranelift/filetests/src/test_alias_analysis.rs @@ -6,7 +6,7 @@ //! //! The resulting function is sent to `filecheck`. -use crate::subtest::{run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, run_filecheck}; use cranelift_codegen::ir::Function; use cranelift_reader::TestCommand; use std::borrow::Cow; diff --git a/cranelift/filetests/src/test_compile.rs b/cranelift/filetests/src/test_compile.rs index 8843bb6656c8..234e8e0d37df 100644 --- a/cranelift/filetests/src/test_compile.rs +++ b/cranelift/filetests/src/test_compile.rs @@ -2,7 +2,7 @@ //! //! The `compile` test command runs each function through the full code generator pipeline -use crate::subtest::{check_precise_output, run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, check_precise_output, run_filecheck}; use anyhow::Result; use cranelift_codegen::ir; use cranelift_reader::{TestCommand, TestOption}; diff --git a/cranelift/filetests/src/test_domtree.rs b/cranelift/filetests/src/test_domtree.rs index 63ed99388f2c..7255c728cb02 100644 --- a/cranelift/filetests/src/test_domtree.rs +++ b/cranelift/filetests/src/test_domtree.rs @@ -13,11 +13,11 @@ //! use crate::match_directive::match_directive; -use crate::subtest::{run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, run_filecheck}; use cranelift_codegen::dominator_tree::{DominatorTree, DominatorTreePreorder}; use cranelift_codegen::flowgraph::ControlFlowGraph; -use cranelift_codegen::ir::entities::AnyEntity; use cranelift_codegen::ir::Function; +use cranelift_codegen::ir::entities::AnyEntity; use cranelift_reader::TestCommand; use std::borrow::{Borrow, Cow}; use std::collections::HashMap; diff --git a/cranelift/filetests/src/test_interpret.rs b/cranelift/filetests/src/test_interpret.rs index 8f653349a0f7..a3388bdc7c36 100644 --- a/cranelift/filetests/src/test_interpret.rs +++ b/cranelift/filetests/src/test_interpret.rs @@ -14,7 +14,7 @@ use cranelift_codegen::settings::Flags; use cranelift_interpreter::environment::FunctionStore; use cranelift_interpreter::interpreter::{Interpreter, InterpreterState, LibCallValues}; use cranelift_interpreter::step::ControlFlow; -use cranelift_reader::{parse_run_command, Details, TestCommand, TestFile}; +use cranelift_reader::{Details, TestCommand, TestFile, parse_run_command}; use log::{info, trace}; use smallvec::smallvec; use std::borrow::Cow; diff --git a/cranelift/filetests/src/test_legalizer.rs b/cranelift/filetests/src/test_legalizer.rs index c0c12e220f46..2e9a55831600 100644 --- a/cranelift/filetests/src/test_legalizer.rs +++ b/cranelift/filetests/src/test_legalizer.rs @@ -3,7 +3,7 @@ //! The `test legalizer` test command runs each function through `legalize_function()` and sends //! the result to filecheck. -use crate::subtest::{run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, run_filecheck}; use cranelift_codegen::ir::Function; use cranelift_reader::TestCommand; use std::borrow::Cow; diff --git a/cranelift/filetests/src/test_optimize.rs b/cranelift/filetests/src/test_optimize.rs index 4550d5ab037d..593bd23701e4 100644 --- a/cranelift/filetests/src/test_optimize.rs +++ b/cranelift/filetests/src/test_optimize.rs @@ -7,7 +7,7 @@ //! Some legalization may be ISA-specific, so this requires an ISA //! (for now). -use crate::subtest::{check_precise_output, run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, check_precise_output, run_filecheck}; use anyhow::Result; use cranelift_codegen::ir; use cranelift_control::ControlPlane; diff --git a/cranelift/filetests/src/test_run.rs b/cranelift/filetests/src/test_run.rs index aee78c164446..57e0cb3b1866 100644 --- a/cranelift/filetests/src/test_run.rs +++ b/cranelift/filetests/src/test_run.rs @@ -12,7 +12,7 @@ use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; use cranelift_codegen::settings::{Configurable, Flags}; use cranelift_codegen::{ir, settings}; use cranelift_reader::TestCommand; -use cranelift_reader::{parse_run_command, TestFile}; +use cranelift_reader::{TestFile, parse_run_command}; use log::{info, trace}; use std::borrow::Cow; use target_lexicon::Architecture; @@ -79,7 +79,7 @@ fn is_isa_compatible( _ => { return Err(format!( "skipped {file_path}: host can't run {requested_arch:?} programs" - )) + )); } } @@ -213,11 +213,13 @@ impl SubTest for TestRun { // Disable runtests with pinned reg enabled. // We've had some abi issues that the trampoline isn't quite ready for. if flags.enable_pinned_reg() { - return Err(anyhow::anyhow!([ - "Cannot run runtests with pinned_reg enabled.", - "See https://github.com/bytecodealliance/wasmtime/issues/4376 for more info" - ] - .join("\n"))); + return Err(anyhow::anyhow!( + [ + "Cannot run runtests with pinned_reg enabled.", + "See https://github.com/bytecodealliance/wasmtime/issues/4376 for more info" + ] + .join("\n") + )); } // Check that the host machine can run this test case (i.e. has all extensions) diff --git a/cranelift/filetests/src/test_safepoint.rs b/cranelift/filetests/src/test_safepoint.rs index 49676e01be20..a3e38efe0a11 100644 --- a/cranelift/filetests/src/test_safepoint.rs +++ b/cranelift/filetests/src/test_safepoint.rs @@ -1,4 +1,4 @@ -use crate::subtest::{run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, run_filecheck}; use cranelift_codegen::ir::Function; use cranelift_reader::TestCommand; use std::borrow::Cow; diff --git a/cranelift/filetests/src/test_unwind.rs b/cranelift/filetests/src/test_unwind.rs index 7b01873af06d..e945565ff1a1 100644 --- a/cranelift/filetests/src/test_unwind.rs +++ b/cranelift/filetests/src/test_unwind.rs @@ -2,12 +2,12 @@ //! //! The `unwind` test command runs each function through the full code generator pipeline. -use crate::subtest::{run_filecheck, Context, SubTest}; +use crate::subtest::{Context, SubTest, run_filecheck}; use cranelift_codegen::{ir, isa::unwind::UnwindInfo}; use cranelift_reader::TestCommand; use gimli::{ - write::{Address, EhFrame, EndianVec, FrameTable}, LittleEndian, + write::{Address, EhFrame, EndianVec, FrameTable}, }; use std::borrow::Cow; diff --git a/cranelift/frontend/src/frontend.rs b/cranelift/frontend/src/frontend.rs index 125be6a773b7..ce63abf17957 100644 --- a/cranelift/frontend/src/frontend.rs +++ b/cranelift/frontend/src/frontend.rs @@ -8,11 +8,11 @@ use cranelift_codegen::entity::{EntityRef, EntitySet, SecondaryMap}; use cranelift_codegen::ir; use cranelift_codegen::ir::condcodes::IntCC; use cranelift_codegen::ir::{ - types, AbiParam, Block, DataFlowGraph, DynamicStackSlot, DynamicStackSlotData, ExtFuncData, + AbiParam, Block, DataFlowGraph, DynamicStackSlot, DynamicStackSlotData, ExtFuncData, ExternalName, FuncRef, Function, GlobalValue, GlobalValueData, Inst, InstBuilder, InstBuilderBase, InstructionData, JumpTable, JumpTableData, LibCall, MemFlags, RelSourceLoc, SigRef, Signature, StackSlot, StackSlotData, Type, Value, ValueLabel, ValueLabelAssignments, - ValueLabelStart, + ValueLabelStart, types, }; use cranelift_codegen::isa::TargetFrontendConfig; use cranelift_codegen::packed_option::PackedOption; @@ -1187,16 +1187,16 @@ impl<'a> FunctionBuilder<'a> { #[cfg(test)] mod tests { use super::greatest_divisible_power_of_two; + use crate::Variable; use crate::frontend::{ DeclareVariableError, DefVariableError, FunctionBuilder, FunctionBuilderContext, UseVariableError, }; - use crate::Variable; use alloc::string::ToString; use cranelift_codegen::entity::EntityRef; use cranelift_codegen::ir::condcodes::IntCC; - use cranelift_codegen::ir::{types::*, UserFuncName}; use cranelift_codegen::ir::{AbiParam, Function, InstBuilder, MemFlags, Signature, Value}; + use cranelift_codegen::ir::{UserFuncName, types::*}; use cranelift_codegen::isa::{CallConv, TargetFrontendConfig, TargetIsa}; use cranelift_codegen::settings; use cranelift_codegen::verifier::verify_function; diff --git a/cranelift/frontend/src/frontend/safepoints.rs b/cranelift/frontend/src/frontend/safepoints.rs index f4a9f8455a1d..aa18e481437f 100644 --- a/cranelift/frontend/src/frontend/safepoints.rs +++ b/cranelift/frontend/src/frontend/safepoints.rs @@ -675,14 +675,12 @@ impl SafepointSpiller { func.dfg.display_inst(inst) ); let ty = func.dfg.value_type(*val); - func.dfg.append_user_stack_map_entry( - inst, - ir::UserStackMapEntry { + func.dfg + .append_user_stack_map_entry(inst, ir::UserStackMapEntry { ty, slot, offset: 0, - }, - ); + }); } } diff --git a/cranelift/frontend/src/ssa.rs b/cranelift/frontend/src/ssa.rs index 694e467b0b20..ace15f62c6d6 100644 --- a/cranelift/frontend/src/ssa.rs +++ b/cranelift/frontend/src/ssa.rs @@ -13,7 +13,7 @@ use core::mem; use cranelift_codegen::cursor::{Cursor, FuncCursor}; use cranelift_codegen::entity::{EntityList, EntitySet, ListPool, SecondaryMap}; use cranelift_codegen::ir::immediates::{Ieee32, Ieee64}; -use cranelift_codegen::ir::types::{F32, F64, I128, I64}; +use cranelift_codegen::ir::types::{F32, F64, I64, I128}; use cranelift_codegen::ir::{Block, Function, Inst, InstBuilder, Type, Value}; use cranelift_codegen::packed_option::PackedOption; @@ -600,8 +600,8 @@ impl SSABuilder { #[cfg(test)] mod tests { - use crate::ssa::SSABuilder; use crate::Variable; + use crate::ssa::SSABuilder; use cranelift_codegen::cursor::{Cursor, FuncCursor}; use cranelift_codegen::entity::EntityRef; use cranelift_codegen::ir; @@ -954,13 +954,10 @@ mod tests { ssa.def_var(x_var, x1, block0); ssa.use_var(&mut func, x_var, I32, block0).0; let br_table = { - let jump_table = JumpTableData::new( + let jump_table = JumpTableData::new(func.dfg.block_call(block2, &[]), &[ func.dfg.block_call(block2, &[]), - &[ - func.dfg.block_call(block2, &[]), - func.dfg.block_call(block1, &[]), - ], - ); + func.dfg.block_call(block1, &[]), + ]); let jt = func.create_jump_table(jump_table); let mut cur = FuncCursor::new(&mut func).at_bottom(block0); cur.ins().br_table(x1, jt) diff --git a/cranelift/fuzzgen/src/function_generator.rs b/cranelift/fuzzgen/src/function_generator.rs index 5e018d881a35..e3bc5ddfdf9d 100644 --- a/cranelift/fuzzgen/src/function_generator.rs +++ b/cranelift/fuzzgen/src/function_generator.rs @@ -9,8 +9,8 @@ use cranelift::codegen::ir::instructions::{InstructionFormat, ResolvedConstraint use cranelift::codegen::ir::stackslot::StackSize; use cranelift::codegen::ir::{ - types::*, AliasRegion, AtomicRmwOp, Block, ConstantData, Endianness, ExternalName, FuncRef, - Function, LibCall, Opcode, SigRef, Signature, StackSlot, UserExternalName, UserFuncName, Value, + AliasRegion, AtomicRmwOp, Block, ConstantData, Endianness, ExternalName, FuncRef, Function, + LibCall, Opcode, SigRef, Signature, StackSlot, UserExternalName, UserFuncName, Value, types::*, }; use cranelift::codegen::isa::CallConv; use cranelift::frontend::{FunctionBuilder, FunctionBuilderContext, Switch, Variable}; @@ -599,24 +599,27 @@ fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) - (Opcode::Select, &[_, I128, I128]), // These stack accesses can cause segfaults if they are merged into an SSE instruction. // See: #5922 - ( - Opcode::StackStore, - &[I8X16 | I16X8 | I32X4 | I64X2 | F32X4 | F64X2] - ), - ( - Opcode::StackLoad, - &[], - &[I8X16 | I16X8 | I32X4 | I64X2 | F32X4 | F64X2] - ), + (Opcode::StackStore, &[I8X16 + | I16X8 + | I32X4 + | I64X2 + | F32X4 + | F64X2]), + (Opcode::StackLoad, &[], &[I8X16 + | I16X8 + | I32X4 + | I64X2 + | F32X4 + | F64X2]), // TODO - ( - Opcode::Sshr | Opcode::Ushr | Opcode::Ishl, - &[I8X16 | I16X8 | I32X4 | I64X2, I128] - ), - ( - Opcode::Rotr | Opcode::Rotl, - &[I8X16 | I16X8 | I32X4 | I64X2, _] - ), + (Opcode::Sshr | Opcode::Ushr | Opcode::Ishl, &[ + I8X16 | I16X8 | I32X4 | I64X2, + I128 + ]), + (Opcode::Rotr | Opcode::Rotl, &[ + I8X16 | I16X8 | I32X4 | I64X2, + _ + ]), ) } @@ -658,11 +661,9 @@ fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) - &[I128] ), // https://github.com/bytecodealliance/wasmtime/issues/4933 - ( - Opcode::FcvtFromUint | Opcode::FcvtFromSint, - &[I128], - &[F32 | F64] - ), + (Opcode::FcvtFromUint | Opcode::FcvtFromSint, &[I128], &[ + F32 | F64 + ]), ( Opcode::Umulhi | Opcode::Smulhi, &([I8X16, I8X16] | [I16X8, I16X8] | [I32X4, I32X4] | [I64X2, I64X2]) @@ -675,14 +676,14 @@ fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) - (Opcode::Bitcast, &[I128], &[_]), (Opcode::Bitcast, &[_], &[I128]), // TODO - ( - Opcode::Sshr | Opcode::Ushr | Opcode::Ishl, - &[I8X16 | I16X8 | I32X4 | I64X2, I128] - ), - ( - Opcode::Rotr | Opcode::Rotl, - &[I8X16 | I16X8 | I32X4 | I64X2, _] - ), + (Opcode::Sshr | Opcode::Ushr | Opcode::Ishl, &[ + I8X16 | I16X8 | I32X4 | I64X2, + I128 + ]), + (Opcode::Rotr | Opcode::Rotl, &[ + I8X16 | I16X8 | I32X4 | I64X2, + _ + ]), // TODO (Opcode::Bitselect, &[_, _, _], &[F32 | F64]), (Opcode::VhighBits, &[F32X4 | F64X2]), @@ -719,11 +720,9 @@ fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) - &[F32 | F64], &[I128] ), - ( - Opcode::FcvtFromUint | Opcode::FcvtFromSint, - &[I128], - &[F32 | F64] - ), + (Opcode::FcvtFromUint | Opcode::FcvtFromSint, &[I128], &[ + F32 | F64 + ]), (Opcode::SsubSat | Opcode::SaddSat, &[I64X2, I64X2]), // https://github.com/bytecodealliance/wasmtime/issues/6104 (Opcode::Bitcast, &[I128], &[_]), @@ -752,34 +751,33 @@ fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) - // TODO (Opcode::Bitselect, &[I128, I128, I128]), // https://github.com/bytecodealliance/wasmtime/issues/5528 - ( - Opcode::FcvtToUint | Opcode::FcvtToSint, - [F32 | F64], - &[I128] - ), + (Opcode::FcvtToUint | Opcode::FcvtToSint, [F32 | F64], &[ + I128 + ]), ( Opcode::FcvtToUintSat | Opcode::FcvtToSintSat, &[F32 | F64], &[I128] ), // https://github.com/bytecodealliance/wasmtime/issues/5528 - ( - Opcode::FcvtFromUint | Opcode::FcvtFromSint, - &[I128], - &[F32 | F64] - ), + (Opcode::FcvtFromUint | Opcode::FcvtFromSint, &[I128], &[ + F32 | F64 + ]), // TODO - ( - Opcode::SelectSpectreGuard, - &[_, _, _], - &[F32 | F64 | I8X16 | I16X8 | I32X4 | I64X2 | F64X2 | F32X4] - ), + (Opcode::SelectSpectreGuard, &[_, _, _], &[F32 + | F64 + | I8X16 + | I16X8 + | I32X4 + | I64X2 + | F64X2 + | F32X4]), // TODO (Opcode::Bitselect, &[_, _, _], &[F32 | F64]), - ( - Opcode::Rotr | Opcode::Rotl, - &[I8X16 | I16X8 | I32X4 | I64X2, _] - ), + (Opcode::Rotr | Opcode::Rotl, &[ + I8X16 | I16X8 | I32X4 | I64X2, + _ + ]), ) } diff --git a/cranelift/fuzzgen/src/lib.rs b/cranelift/fuzzgen/src/lib.rs index 8693e023f7de..3fbc89777b4b 100644 --- a/cranelift/fuzzgen/src/lib.rs +++ b/cranelift/fuzzgen/src/lib.rs @@ -3,11 +3,11 @@ use crate::function_generator::FunctionGenerator; use crate::settings::{Flags, OptLevel}; use anyhow::Result; use arbitrary::{Arbitrary, Unstructured}; +use cranelift::codegen::Context; use cranelift::codegen::data_value::DataValue; use cranelift::codegen::ir::{Function, LibCall}; use cranelift::codegen::ir::{UserExternalName, UserFuncName}; use cranelift::codegen::isa::Builder; -use cranelift::codegen::Context; use cranelift::prelude::isa::{OwnedTargetIsa, TargetIsa}; use cranelift::prelude::settings::SettingKind; use cranelift::prelude::*; diff --git a/cranelift/fuzzgen/src/print.rs b/cranelift/fuzzgen/src/print.rs index e4b18f946380..0a20c722bd92 100644 --- a/cranelift/fuzzgen/src/print.rs +++ b/cranelift/fuzzgen/src/print.rs @@ -81,7 +81,10 @@ impl<'a> fmt::Debug for PrintableTestCase<'a> { } if !self.inputs.is_empty() { - writeln!(f, "; Note: the results in the below test cases are simply a placeholder and probably will be wrong\n")?; + writeln!( + f, + "; Note: the results in the below test cases are simply a placeholder and probably will be wrong\n" + )?; } for input in self.inputs.iter() { diff --git a/cranelift/interpreter/src/address.rs b/cranelift/interpreter/src/address.rs index f782a7a236b4..88e54af6d1ad 100644 --- a/cranelift/interpreter/src/address.rs +++ b/cranelift/interpreter/src/address.rs @@ -34,7 +34,7 @@ use crate::state::MemoryError; use cranelift_codegen::data_value::DataValue; -use cranelift_codegen::ir::{types, Type}; +use cranelift_codegen::ir::{Type, types}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum AddressSize { diff --git a/cranelift/interpreter/src/environment.rs b/cranelift/interpreter/src/environment.rs index 63cd61d8e317..79da5a39613e 100644 --- a/cranelift/interpreter/src/environment.rs +++ b/cranelift/interpreter/src/environment.rs @@ -1,6 +1,6 @@ //! Implements the function environment (e.g. a name-to-function mapping) for interpretation. use cranelift_codegen::ir::{FuncRef, Function}; -use cranelift_entity::{entity_impl, PrimaryMap}; +use cranelift_entity::{PrimaryMap, entity_impl}; use std::collections::HashMap; /// A function store contains all of the functions that are accessible to an interpreter. diff --git a/cranelift/interpreter/src/frame.rs b/cranelift/interpreter/src/frame.rs index d503b6a32196..5352cce0f02f 100644 --- a/cranelift/interpreter/src/frame.rs +++ b/cranelift/interpreter/src/frame.rs @@ -1,7 +1,7 @@ //! Implements a call frame (activation record) for the Cranelift interpreter. use cranelift_codegen::data_value::DataValue; -use cranelift_codegen::ir::{types, Function, Value as ValueRef}; +use cranelift_codegen::ir::{Function, Value as ValueRef, types}; use cranelift_entity::EntityRef; use log::trace; @@ -110,8 +110,8 @@ impl<'a> Frame<'a> { #[cfg(test)] mod tests { use super::*; - use cranelift_codegen::ir::immediates::{Ieee32, Ieee64}; use cranelift_codegen::ir::InstBuilder; + use cranelift_codegen::ir::immediates::{Ieee32, Ieee64}; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_reader::parse_functions; diff --git a/cranelift/interpreter/src/interpreter.rs b/cranelift/interpreter/src/interpreter.rs index 8797d61b784f..4850eb5e4d9e 100644 --- a/cranelift/interpreter/src/interpreter.rs +++ b/cranelift/interpreter/src/interpreter.rs @@ -7,7 +7,7 @@ use crate::environment::{FuncIndex, FunctionStore}; use crate::frame::Frame; use crate::instruction::DfgInstructionContext; use crate::state::{InterpreterFunctionRef, MemoryError, State}; -use crate::step::{step, ControlFlow, CraneliftTrap, StepError}; +use crate::step::{ControlFlow, CraneliftTrap, StepError, step}; use crate::value::{DataValueExt, ValueError}; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::{ @@ -562,8 +562,8 @@ impl<'a> State<'a> for InterpreterState<'a> { mod tests { use super::*; use crate::step::CraneliftTrap; - use cranelift_codegen::ir::immediates::Ieee32; use cranelift_codegen::ir::TrapCode; + use cranelift_codegen::ir::immediates::Ieee32; use cranelift_reader::parse_functions; use smallvec::smallvec; @@ -750,15 +750,12 @@ mod tests { let state = InterpreterState::default().with_function_store(env); let result = Interpreter::new(state) - .call_by_name( - "%caller", - &[ - DataValue::I64(3), - DataValue::I64(5), - DataValue::I64(7), - DataValue::I64(11), - ], - ) + .call_by_name("%caller", &[ + DataValue::I64(3), + DataValue::I64(5), + DataValue::I64(7), + DataValue::I64(11), + ]) .unwrap(); assert_eq!(result, ControlFlow::Return(smallvec![DataValue::I64(26)])) diff --git a/cranelift/interpreter/src/state.rs b/cranelift/interpreter/src/state.rs index 7b9c6b5baa43..2447a5fbcb7c 100644 --- a/cranelift/interpreter/src/state.rs +++ b/cranelift/interpreter/src/state.rs @@ -5,8 +5,8 @@ use crate::frame::Frame; use crate::interpreter::LibCallHandler; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::{ - types, ExternalName, FuncRef, Function, GlobalValue, LibCall, MemFlags, Signature, StackSlot, - Type, Value, + ExternalName, FuncRef, Function, GlobalValue, LibCall, MemFlags, Signature, StackSlot, Type, + Value, types, }; use cranelift_codegen::isa::CallConv; use smallvec::SmallVec; diff --git a/cranelift/interpreter/src/step.rs b/cranelift/interpreter/src/step.rs index 8e602fdb262a..f2f5f8f25367 100644 --- a/cranelift/interpreter/src/step.rs +++ b/cranelift/interpreter/src/step.rs @@ -7,11 +7,11 @@ use crate::value::{DataValueExt, ValueConversionKind, ValueError, ValueResult}; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::condcodes::{FloatCC, IntCC}; use cranelift_codegen::ir::{ - types, AbiParam, AtomicRmwOp, Block, BlockCall, Endianness, ExternalName, FuncRef, Function, - InstructionData, MemFlags, Opcode, TrapCode, Type, Value as ValueRef, + AbiParam, AtomicRmwOp, Block, BlockCall, Endianness, ExternalName, FuncRef, Function, + InstructionData, MemFlags, Opcode, TrapCode, Type, Value as ValueRef, types, }; use log::trace; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use std::fmt::Debug; use std::ops::RangeFrom; use thiserror::Error; @@ -92,10 +92,18 @@ where .constants .get(constant_handle); match (ctrl_ty.bytes(), opcode) { - (_, Opcode::F128const) => DataValue::F128(buffer.try_into().expect("a 16-byte data buffer")), - (16, Opcode::Vconst) => DataValue::V128(buffer.as_slice().try_into().expect("a 16-byte data buffer")), - (8, Opcode::Vconst) => DataValue::V64(buffer.as_slice().try_into().expect("an 8-byte data buffer")), - (length, opcode) => panic!("unexpected UnaryConst controlling type size {length} for opcode {opcode:?}"), + (_, Opcode::F128const) => { + DataValue::F128(buffer.try_into().expect("a 16-byte data buffer")) + } + (16, Opcode::Vconst) => DataValue::V128( + buffer.as_slice().try_into().expect("a 16-byte data buffer"), + ), + (8, Opcode::Vconst) => { + DataValue::V64(buffer.as_slice().try_into().expect("an 8-byte data buffer")) + } + (length, opcode) => panic!( + "unexpected UnaryConst controlling type size {length} for opcode {opcode:?}" + ), } } InstructionData::Shuffle { imm, .. } => { diff --git a/cranelift/interpreter/src/value.rs b/cranelift/interpreter/src/value.rs index a41d54c25543..739d7aaf9375 100644 --- a/cranelift/interpreter/src/value.rs +++ b/cranelift/interpreter/src/value.rs @@ -6,11 +6,11 @@ use core::fmt::{self, Display, Formatter}; use core::ops::Neg; use cranelift_codegen::data_value::{DataValue, DataValueCastFailure}; -use cranelift_codegen::ir::immediates::{Ieee128, Ieee16, Ieee32, Ieee64}; -use cranelift_codegen::ir::{types, Type}; +use cranelift_codegen::ir::immediates::{Ieee16, Ieee32, Ieee64, Ieee128}; +use cranelift_codegen::ir::{Type, types}; use thiserror::Error; -use crate::step::{extractlanes, SimdVec}; +use crate::step::{SimdVec, extractlanes}; pub type ValueResult = Result; @@ -321,11 +321,7 @@ impl DataValueExt for DataValue { macro_rules! make_bool { ($ty:ident) => { Ok(DataValue::$ty(if b { - if vec_elem { - -1 - } else { - 1 - } + if vec_elem { -1 } else { 1 } } else { 0 })) @@ -504,37 +500,21 @@ impl DataValueExt for DataValue { fn umax(self, other: Self) -> ValueResult { let lhs = self.clone().into_int_unsigned()?; let rhs = other.clone().into_int_unsigned()?; - if lhs > rhs { - Ok(self) - } else { - Ok(other) - } + if lhs > rhs { Ok(self) } else { Ok(other) } } fn smax(self, other: Self) -> ValueResult { - if self > other { - Ok(self) - } else { - Ok(other) - } + if self > other { Ok(self) } else { Ok(other) } } fn umin(self, other: Self) -> ValueResult { let lhs = self.clone().into_int_unsigned()?; let rhs = other.clone().into_int_unsigned()?; - if lhs < rhs { - Ok(self) - } else { - Ok(other) - } + if lhs < rhs { Ok(self) } else { Ok(other) } } fn smin(self, other: Self) -> ValueResult { - if self < other { - Ok(self) - } else { - Ok(other) - } + if self < other { Ok(self) } else { Ok(other) } } fn uno(&self, other: &Self) -> ValueResult { diff --git a/cranelift/isle/isle/src/codegen.rs b/cranelift/isle/isle/src/codegen.rs index 769223d38368..7d0c48eb7320 100644 --- a/cranelift/isle/isle/src/codegen.rs +++ b/cranelift/isle/isle/src/codegen.rs @@ -455,9 +455,7 @@ impl Length for ContextIterWrapper {{ ReturnKind::Plain => format!( "unreachable!(\"no rule matched for term {{}} at {{}}; should it be partial?\", {:?}, {:?})", term_name, - termdata - .decl_pos - .pretty_print_line(&self.files) + termdata.decl_pos.pretty_print_line(&self.files) ), } }; @@ -481,10 +479,12 @@ impl Length for ContextIterWrapper {{ fn validate_block(ret_kind: ReturnKind, block: &Block) -> Nested { if !matches!(ret_kind, ReturnKind::Iterator) { // Loops are only allowed if we're returning an iterator. - assert!(!block - .steps - .iter() - .any(|c| matches!(c.check, ControlFlow::Loop { .. }))); + assert!( + !block + .steps + .iter() + .any(|c| matches!(c.check, ControlFlow::Loop { .. })) + ); // Unless we're returning an iterator, a case which returns a result must be the last // case in a block. diff --git a/cranelift/isle/isle/src/compile.rs b/cranelift/isle/isle/src/compile.rs index db3497fa9424..fbf4bf3f0e5a 100644 --- a/cranelift/isle/isle/src/compile.rs +++ b/cranelift/isle/isle/src/compile.rs @@ -43,7 +43,7 @@ pub fn from_files>( return Err(Errors::from_io( err, format!("cannot read file {}", path.display()), - )) + )); } }; @@ -76,7 +76,7 @@ pub fn create_envs( return Err(Errors::from_io( err, format!("cannot read file {}", path.display()), - )) + )); } }; let files = Arc::new(files); diff --git a/cranelift/isle/isle/src/lexer.rs b/cranelift/isle/isle/src/lexer.rs index 2b792ab962c8..8c551116b6b4 100644 --- a/cranelift/isle/isle/src/lexer.rs +++ b/cranelift/isle/isle/src/lexer.rs @@ -234,7 +234,7 @@ impl<'src> Lexer<'src> { let num = match (neg, num) { (true, 0x80000000000000000000000000000000) => { - return Err(self.error(start_pos, "integer literal cannot fit in i128")) + return Err(self.error(start_pos, "integer literal cannot fit in i128")); } (true, _) => -(num as i128), (false, _) => num as i128, @@ -309,7 +309,9 @@ mod test { #[test] fn lexer_basic() { assert_eq!( - lex(";; comment\n; another\r\n \t(one two three (; block comment ;) 23 (; nested (; block ;) comment ;) -568 )\n"), + lex( + ";; comment\n; another\r\n \t(one two three (; block comment ;) 23 (; nested (; block ;) comment ;) -568 )\n" + ), [ Token::LParen, Token::Symbol("one".to_string()), @@ -334,26 +336,24 @@ mod test { #[test] fn weird_syms() { - assert_eq!( - lex("(+ [] => !! _test!;comment\n)"), - [ - Token::LParen, - Token::Symbol("+".to_string()), - Token::Symbol("[]".to_string()), - Token::Symbol("=>".to_string()), - Token::Symbol("!!".to_string()), - Token::Symbol("_test!".to_string()), - Token::RParen, - ] - ); + assert_eq!(lex("(+ [] => !! _test!;comment\n)"), [ + Token::LParen, + Token::Symbol("+".to_string()), + Token::Symbol("[]".to_string()), + Token::Symbol("=>".to_string()), + Token::Symbol("!!".to_string()), + Token::Symbol("_test!".to_string()), + Token::RParen, + ]); } #[test] fn integers() { - assert_eq!( - lex("0 1 -1"), - [Token::Int(0), Token::Int(1), Token::Int(-1)] - ); + assert_eq!(lex("0 1 -1"), [ + Token::Int(0), + Token::Int(1), + Token::Int(-1) + ]); assert_eq!( lex("340_282_366_920_938_463_463_374_607_431_768_211_455"), diff --git a/cranelift/isle/isle/src/sema.rs b/cranelift/isle/isle/src/sema.rs index 3acee1e28bd6..46fadf742749 100644 --- a/cranelift/isle/isle/src/sema.rs +++ b/cranelift/isle/isle/src/sema.rs @@ -18,10 +18,10 @@ use crate::error::*; use crate::lexer::Pos; use crate::log; use crate::stablemapset::{StableMap, StableSet}; -use std::collections::hash_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::fmt; declare_id!( @@ -507,13 +507,10 @@ impl Term { /// Is this term partial? pub fn is_partial(&self) -> bool { - matches!( - self.kind, - TermKind::Decl { - flags: TermFlags { partial: true, .. }, - .. - } - ) + matches!(self.kind, TermKind::Decl { + flags: TermFlags { partial: true, .. }, + .. + }) } /// Does this term have a constructor? @@ -542,24 +539,18 @@ impl Term { /// Is this term's extractor external? pub fn has_external_extractor(&self) -> bool { - matches!( - self.kind, - TermKind::Decl { - extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }), - .. - } - ) + matches!(self.kind, TermKind::Decl { + extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }), + .. + }) } /// Is this term's constructor external? pub fn has_external_constructor(&self) -> bool { - matches!( - self.kind, - TermKind::Decl { - constructor_kind: Some(ConstructorKind::ExternalConstructor { .. }), - .. - } - ) + matches!(self.kind, TermKind::Decl { + constructor_kind: Some(ConstructorKind::ExternalConstructor { .. }), + .. + }) } /// Get this term's extractor's external function signature, if any. @@ -2668,14 +2659,10 @@ mod test { assert_eq!(tyenv.type_map.get(&sym_a).unwrap(), &TypeId(14)); let expected_types = vec![ - Type::Primitive( - TypeId(13), - sym_uimm8, - Pos { - file: 0, - offset: 19, - }, - ), + Type::Primitive(TypeId(13), sym_uimm8, Pos { + file: 0, + offset: 19, + }), Type::Enum { name: sym_a, id: TypeId(14), diff --git a/cranelift/isle/isle/src/trie_again.rs b/cranelift/isle/isle/src/trie_again.rs index 8db8d0ea6749..3a16f06c9195 100644 --- a/cranelift/isle/isle/src/trie_again.rs +++ b/cranelift/isle/isle/src/trie_again.rs @@ -5,7 +5,7 @@ use crate::error::{Error, Span}; use crate::lexer::Pos; use crate::sema; use crate::stablemapset::StableSet; -use std::collections::{hash_map::Entry, HashMap}; +use std::collections::{HashMap, hash_map::Entry}; /// A field index in a tuple or an enum variant. #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] @@ -565,14 +565,11 @@ impl sema::PatternVisitor for RuleSetBuilder { variant: sema::VariantId, ) -> Vec { let fields = TupleIndex(arg_tys.len().try_into().unwrap()); - self.set_constraint( - input, - Constraint::Variant { - fields, - ty: input_ty, - variant, - }, - ) + self.set_constraint(input, Constraint::Variant { + fields, + ty: input_ty, + variant, + }) } fn add_extract( diff --git a/cranelift/isle/isle/tests/run_tests.rs b/cranelift/isle/isle/tests/run_tests.rs index 5fbabdca75ed..c9b8ca70fba7 100644 --- a/cranelift/isle/isle/tests/run_tests.rs +++ b/cranelift/isle/isle/tests/run_tests.rs @@ -65,12 +65,14 @@ pub fn run_link(isle_filename: &str) { pub fn run_run(isle_filename: &str) { let (_tempdir, exe) = build_and_link_isle(isle_filename); - assert!(std::process::Command::new(exe) - .spawn() - .unwrap() - .wait() - .unwrap() - .success()); + assert!( + std::process::Command::new(exe) + .spawn() + .unwrap() + .wait() + .unwrap() + .success() + ); } // Generated by build.rs. diff --git a/cranelift/jit/examples/jit-minimal.rs b/cranelift/jit/examples/jit-minimal.rs index f806929bc153..1ef211fac79c 100644 --- a/cranelift/jit/examples/jit-minimal.rs +++ b/cranelift/jit/examples/jit-minimal.rs @@ -1,7 +1,7 @@ use codegen::ir::UserFuncName; use cranelift::prelude::*; use cranelift_jit::{JITBuilder, JITModule}; -use cranelift_module::{default_libcall_names, Linkage, Module}; +use cranelift_module::{Linkage, Module, default_libcall_names}; use std::mem; fn main() { diff --git a/cranelift/jit/src/backend.rs b/cranelift/jit/src/backend.rs index 8f95a30b5a7a..cdc587760cc9 100644 --- a/cranelift/jit/src/backend.rs +++ b/cranelift/jit/src/backend.rs @@ -4,7 +4,7 @@ use crate::{compiled_blob::CompiledBlob, memory::BranchProtection, memory::Memor use cranelift_codegen::binemit::Reloc; use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; use cranelift_codegen::settings::Configurable; -use cranelift_codegen::{ir, settings, FinalizedMachReloc}; +use cranelift_codegen::{FinalizedMachReloc, ir, settings}; use cranelift_control::ControlPlane; use cranelift_entity::SecondaryMap; use cranelift_module::{ diff --git a/cranelift/jit/src/compiled_blob.rs b/cranelift/jit/src/compiled_blob.rs index 95c3d2495b79..f655aa934244 100644 --- a/cranelift/jit/src/compiled_blob.rs +++ b/cranelift/jit/src/compiled_blob.rs @@ -96,7 +96,10 @@ impl CompiledBlob { } Reloc::Aarch64AdrGotPage21 => { // Set the immediate value of an ADRP to bits [32:12] of X; check that –2^32 <= X < 2^32 - assert_eq!(addend, 0, "addend affects the address looked up in get_got_entry, which is currently only called with a symbol"); + assert_eq!( + addend, 0, + "addend affects the address looked up in get_got_entry, which is currently only called with a symbol" + ); let what = get_got_entry(name); let what_page = (what as usize) & !0xfff; let at_page = (at as usize) & !0xfff; diff --git a/cranelift/jit/src/memory.rs b/cranelift/jit/src/memory.rs index 3e005716d26d..d7b9086fac19 100644 --- a/cranelift/jit/src/memory.rs +++ b/cranelift/jit/src/memory.rs @@ -70,7 +70,7 @@ impl PtrLen { #[cfg(target_os = "windows")] fn with_size(size: usize) -> io::Result { use windows_sys::Win32::System::Memory::{ - VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, }; // VirtualAlloc always rounds up to the next multiple of the page size diff --git a/cranelift/jit/tests/basic.rs b/cranelift/jit/tests/basic.rs index 6220782c7d9d..6551c4aeedd7 100644 --- a/cranelift/jit/tests/basic.rs +++ b/cranelift/jit/tests/basic.rs @@ -1,7 +1,7 @@ use cranelift_codegen::ir::*; use cranelift_codegen::isa::CallConv; use cranelift_codegen::settings::{self, Configurable}; -use cranelift_codegen::{ir::types::I16, Context}; +use cranelift_codegen::{Context, ir::types::I16}; use cranelift_entity::EntityRef; use cranelift_frontend::*; use cranelift_jit::*; diff --git a/cranelift/module/src/data_context.rs b/cranelift/module/src/data_context.rs index b55f96fcd3c5..7a55e936b024 100644 --- a/cranelift/module/src/data_context.rs +++ b/cranelift/module/src/data_context.rs @@ -8,8 +8,8 @@ use std::boxed::Box; use std::string::String; use std::vec::Vec; -use crate::module::ModuleReloc; use crate::ModuleRelocTarget; +use crate::module::ModuleReloc; /// This specifies how data is to be initialized. #[derive(Clone, PartialEq, Eq, Debug)] @@ -219,12 +219,9 @@ mod tests { let contents_clone = contents.clone(); data.define(contents.into_boxed_slice()); - assert_eq!( - data.init, - Init::Bytes { - contents: contents_clone.into_boxed_slice() - } - ); + assert_eq!(data.init, Init::Bytes { + contents: contents_clone.into_boxed_slice() + }); assert_eq!(data.function_decls.len(), 0); assert_eq!(data.data_decls.len(), 0); assert_eq!(data.function_relocs.len(), 0); diff --git a/cranelift/module/src/lib.rs b/cranelift/module/src/lib.rs index 7528ad67caad..bb1e3994bb78 100644 --- a/cranelift/module/src/lib.rs +++ b/cranelift/module/src/lib.rs @@ -11,11 +11,11 @@ extern crate alloc as std; extern crate std; #[cfg(not(feature = "std"))] -use hashbrown::{hash_map, HashMap}; +use hashbrown::{HashMap, hash_map}; use std::borrow::ToOwned; use std::boxed::Box; #[cfg(feature = "std")] -use std::collections::{hash_map, HashMap}; +use std::collections::{HashMap, hash_map}; use std::string::String; use cranelift_codegen::ir; diff --git a/cranelift/module/src/module.rs b/cranelift/module/src/module.rs index 4a32837787ca..c82134964dd3 100644 --- a/cranelift/module/src/module.rs +++ b/cranelift/module/src/module.rs @@ -9,12 +9,12 @@ use super::HashMap; use crate::data_context::DataDescription; use core::fmt::Display; use cranelift_codegen::binemit::{CodeOffset, Reloc}; -use cranelift_codegen::entity::{entity_impl, PrimaryMap}; -use cranelift_codegen::ir::function::{Function, VersionMarker}; +use cranelift_codegen::entity::{PrimaryMap, entity_impl}; use cranelift_codegen::ir::ExternalName; +use cranelift_codegen::ir::function::{Function, VersionMarker}; use cranelift_codegen::settings::SetError; use cranelift_codegen::{ - ir, isa, CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget, + CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget, ir, isa, }; use cranelift_control::ControlPlane; use std::borrow::{Cow, ToOwned}; diff --git a/cranelift/object/src/backend.rs b/cranelift/object/src/backend.rs index 2de22223868b..55d17587643f 100644 --- a/cranelift/object/src/backend.rs +++ b/cranelift/object/src/backend.rs @@ -4,7 +4,7 @@ use anyhow::anyhow; use cranelift_codegen::binemit::{Addend, CodeOffset, Reloc}; use cranelift_codegen::entity::SecondaryMap; use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; -use cranelift_codegen::{ir, FinalizedMachReloc}; +use cranelift_codegen::{FinalizedMachReloc, ir}; use cranelift_control::ControlPlane; use cranelift_module::{ DataDescription, DataId, FuncId, Init, Linkage, Module, ModuleDeclarations, ModuleError, @@ -18,8 +18,8 @@ use object::{ RelocationEncoding, RelocationFlags, RelocationKind, SectionKind, SymbolFlags, SymbolKind, SymbolScope, }; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::mem; use target_lexicon::PointerWidth; @@ -57,16 +57,16 @@ impl ObjectBuilder { target_lexicon::BinaryFormat::Wasm => { return Err(ModuleError::Backend(anyhow!( "binary format wasm is unsupported", - ))) + ))); } target_lexicon::BinaryFormat::Unknown => { - return Err(ModuleError::Backend(anyhow!("binary format is unknown"))) + return Err(ModuleError::Backend(anyhow!("binary format is unknown"))); } other => { return Err(ModuleError::Backend(anyhow!( "binary format {} not recognized", other - ))) + ))); } }; let architecture = match isa.triple().architecture { @@ -107,7 +107,7 @@ impl ObjectBuilder { return Err(ModuleError::Backend(anyhow!( "target architecture {:?} is unsupported", architecture, - ))) + ))); } }; let endian = match isa.triple().endianness().unwrap() { @@ -524,15 +524,12 @@ impl ObjectModule { { let target_symbol = self.get_symbol(name); self.object - .add_relocation( - symbol.section, - Relocation { - offset: symbol.offset + u64::from(offset), - flags, - symbol: target_symbol, - addend, - }, - ) + .add_relocation(symbol.section, Relocation { + offset: symbol.offset + u64::from(offset), + flags, + symbol: target_symbol, + addend, + }) .unwrap(); } } diff --git a/cranelift/object/tests/basic.rs b/cranelift/object/tests/basic.rs index 51b500dc8d3e..8a46ee173530 100644 --- a/cranelift/object/tests/basic.rs +++ b/cranelift/object/tests/basic.rs @@ -1,7 +1,7 @@ use cranelift_codegen::ir::*; use cranelift_codegen::isa::CallConv; use cranelift_codegen::settings; -use cranelift_codegen::{ir::types::I16, Context}; +use cranelift_codegen::{Context, ir::types::I16}; use cranelift_entity::EntityRef; use cranelift_frontend::*; use cranelift_module::*; diff --git a/cranelift/reader/src/lib.rs b/cranelift/reader/src/lib.rs index e4d5ea95e030..b836997f94af 100644 --- a/cranelift/reader/src/lib.rs +++ b/cranelift/reader/src/lib.rs @@ -6,8 +6,8 @@ #![deny(missing_docs)] pub use crate::error::{Location, ParseError, ParseResult}; -pub use crate::isaspec::{parse_option, parse_options, IsaSpec, ParseOptionError}; -pub use crate::parser::{parse_functions, parse_run_command, parse_test, ParseOptions}; +pub use crate::isaspec::{IsaSpec, ParseOptionError, parse_option, parse_options}; +pub use crate::parser::{ParseOptions, parse_functions, parse_run_command, parse_test}; pub use crate::run_command::{Comparison, Invocation, RunCommand}; pub use crate::sourcemap::SourceMap; pub use crate::testcommand::{TestCommand, TestOption}; diff --git a/cranelift/reader/src/parser.rs b/cranelift/reader/src/parser.rs index a4160305a726..58e3cb1adaef 100644 --- a/cranelift/reader/src/parser.rs +++ b/cranelift/reader/src/parser.rs @@ -11,7 +11,7 @@ use cranelift_codegen::data_value::DataValue; use cranelift_codegen::entity::{EntityRef, PrimaryMap}; use cranelift_codegen::ir::entities::{AnyEntity, DynamicType, MemoryType}; use cranelift_codegen::ir::immediates::{ - Ieee128, Ieee16, Ieee32, Ieee64, Imm64, Offset32, Uimm32, Uimm64, + Ieee16, Ieee32, Ieee64, Ieee128, Imm64, Offset32, Uimm32, Uimm64, }; use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs}; use cranelift_codegen::ir::pcc::{BaseExpr, Expr, Fact}; @@ -1065,11 +1065,7 @@ impl<'a> Parser<'a> { let mut flag_builder = settings::builder(); let bool_to_str = |val: bool| { - if val { - "true" - } else { - "false" - } + if val { "true" } else { "false" } }; // default to enabling cfg info @@ -1164,7 +1160,7 @@ impl<'a> Parser<'a> { return err!( self.loc, format!("Expected feature flag string, got {:?}", tok) - ) + ); } } self.consume(); @@ -1785,7 +1781,7 @@ impl<'a> Parser<'a> { self.loc, "Unknown memory type declaration kind '{:?}'", other - ) + ); } }; @@ -2861,7 +2857,7 @@ impl<'a> Parser<'a> { return err!( self.loc, "expected one of the following type: i8, i16, i32 or i64" - ) + ); } }; InstructionData::UnaryImm { @@ -3530,13 +3526,10 @@ mod tests { .unwrap(); assert_eq!(func.name.to_string(), "%comment"); assert_eq!(comments.len(), 7); // no 'before' comment. - assert_eq!( - comments[0], - Comment { - entity: AnyEntity::Function, - text: "; decl", - } - ); + assert_eq!(comments[0], Comment { + entity: AnyEntity::Function, + text: "; decl", + }); assert_eq!(comments[1].entity.to_string(), "ss10"); assert_eq!(comments[2].entity.to_string(), "ss10"); assert_eq!(comments[2].text, "; Still stackslot."); @@ -3585,20 +3578,24 @@ mod tests { #[test] fn isa_spec() { - assert!(parse_test( - "target + assert!( + parse_test( + "target function %foo() system_v {}", - ParseOptions::default() - ) - .is_err()); + ParseOptions::default() + ) + .is_err() + ); - assert!(parse_test( - "target x86_64 + assert!( + parse_test( + "target x86_64 set enable_float=false function %foo() system_v {}", - ParseOptions::default() - ) - .is_err()); + ParseOptions::default() + ) + .is_err() + ); match parse_test( "set enable_float=false @@ -3775,19 +3772,13 @@ mod tests { #[test] fn uimm128() { macro_rules! parse_as_constant_data { - ($text:expr, $type:expr) => {{ - Parser::new($text).parse_literals_to_constant_data($type) - }}; + ($text:expr, $type:expr) => {{ Parser::new($text).parse_literals_to_constant_data($type) }}; } macro_rules! can_parse_as_constant_data { - ($text:expr, $type:expr) => {{ - assert!(parse_as_constant_data!($text, $type).is_ok()) - }}; + ($text:expr, $type:expr) => {{ assert!(parse_as_constant_data!($text, $type).is_ok()) }}; } macro_rules! cannot_parse_as_constant_data { - ($text:expr, $type:expr) => {{ - assert!(parse_as_constant_data!($text, $type).is_err()) - }}; + ($text:expr, $type:expr) => {{ assert!(parse_as_constant_data!($text, $type).is_err()) }}; } can_parse_as_constant_data!("1 2 3 4", I32X4); @@ -3808,10 +3799,9 @@ mod tests { let c = Parser::new("-1 0 -1 0") .parse_literals_to_constant_data(I32X4) .unwrap(); - assert_eq!( - c.into_vec(), - [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0] - ) + assert_eq!(c.into_vec(), [ + 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0 + ]) } #[test] @@ -3825,9 +3815,11 @@ mod tests { ); // Only parse hexadecimal constants: - assert!(Parser::new("228") - .match_hexadecimal_constant("err message") - .is_err()); + assert!( + Parser::new("228") + .match_hexadecimal_constant("err message") + .is_err() + ); } #[test] diff --git a/cranelift/reader/src/run_command.rs b/cranelift/reader/src/run_command.rs index 2fa616539694..5d810afee6d1 100644 --- a/cranelift/reader/src/run_command.rs +++ b/cranelift/reader/src/run_command.rs @@ -125,7 +125,7 @@ impl Display for Comparison { mod test { use super::*; use crate::parse_run_command; - use cranelift_codegen::ir::{types, AbiParam, Signature}; + use cranelift_codegen::ir::{AbiParam, Signature, types}; use cranelift_codegen::isa::CallConv; #[test] diff --git a/cranelift/reader/src/sourcemap.rs b/cranelift/reader/src/sourcemap.rs index 36b10f1c8d91..2c79de5ea471 100644 --- a/cranelift/reader/src/sourcemap.rs +++ b/cranelift/reader/src/sourcemap.rs @@ -208,7 +208,7 @@ impl SourceMap { #[cfg(test)] mod tests { - use crate::{parse_test, ParseOptions}; + use crate::{ParseOptions, parse_test}; #[test] fn details() { diff --git a/cranelift/reader/src/testfile.rs b/cranelift/reader/src/testfile.rs index 08c102467034..339030716461 100644 --- a/cranelift/reader/src/testfile.rs +++ b/cranelift/reader/src/testfile.rs @@ -8,8 +8,8 @@ use crate::error::Location; use crate::isaspec::IsaSpec; use crate::sourcemap::SourceMap; use crate::testcommand::TestCommand; -use cranelift_codegen::ir::entities::AnyEntity; use cranelift_codegen::ir::Function; +use cranelift_codegen::ir::entities::AnyEntity; /// A parsed test case. /// diff --git a/cranelift/src/bugpoint.rs b/cranelift/src/bugpoint.rs index 3c0b506afdbe..875bc1742858 100644 --- a/cranelift/src/bugpoint.rs +++ b/cranelift/src/bugpoint.rs @@ -4,17 +4,17 @@ use crate::utils::read_to_string; use anyhow::{Context as _, Result}; use clap::Parser; use cranelift::prelude::Value; +use cranelift_codegen::Context; use cranelift_codegen::cursor::{Cursor, FuncCursor}; use cranelift_codegen::flowgraph::ControlFlowGraph; -use cranelift_codegen::ir::types::{F32, F64, I128, I64}; +use cranelift_codegen::ir::types::{F32, F64, I64, I128}; use cranelift_codegen::ir::{ self, Block, FuncRef, Function, GlobalValueData, Inst, InstBuilder, InstructionData, StackSlots, TrapCode, }; use cranelift_codegen::isa::TargetIsa; -use cranelift_codegen::Context; use cranelift_entity::PrimaryMap; -use cranelift_reader::{parse_sets_and_triple, parse_test, ParseOptions}; +use cranelift_reader::{ParseOptions, parse_sets_and_triple, parse_test}; use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle}; use std::collections::HashMap; use std::path::PathBuf; diff --git a/cranelift/src/compile.rs b/cranelift/src/compile.rs index 381ac47aa20e..3668a786bc46 100644 --- a/cranelift/src/compile.rs +++ b/cranelift/src/compile.rs @@ -4,12 +4,12 @@ use crate::disasm::print_all; use crate::utils::read_to_string; use anyhow::{Context as _, Result}; use clap::Parser; +use cranelift_codegen::Context; use cranelift_codegen::print_errors::pretty_error; use cranelift_codegen::settings::FlagsOrIsa; use cranelift_codegen::timing; -use cranelift_codegen::Context; use cranelift_reader::OwnedFlagsOrIsa; -use cranelift_reader::{parse_sets_and_triple, parse_test, ParseOptions}; +use cranelift_reader::{ParseOptions, parse_sets_and_triple, parse_test}; use std::path::Path; use std::path::PathBuf; diff --git a/cranelift/src/disasm.rs b/cranelift/src/disasm.rs index 574f72ec3bf6..931f1d861d23 100644 --- a/cranelift/src/disasm.rs +++ b/cranelift/src/disasm.rs @@ -1,7 +1,7 @@ use anyhow::Result; use cfg_if::cfg_if; -use cranelift_codegen::ir::function::FunctionParameters; use cranelift_codegen::ir::Function; +use cranelift_codegen::ir::function::FunctionParameters; use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::{FinalizedMachReloc, MachTrap}; use std::fmt::Write; diff --git a/cranelift/src/interpret.rs b/cranelift/src/interpret.rs index d0fce058a759..4d68ce3d2d53 100644 --- a/cranelift/src/interpret.rs +++ b/cranelift/src/interpret.rs @@ -5,7 +5,7 @@ use clap::Parser; use cranelift_interpreter::environment::FunctionStore; use cranelift_interpreter::interpreter::{Interpreter, InterpreterState}; use cranelift_interpreter::step::ControlFlow; -use cranelift_reader::{parse_run_command, parse_test, ParseError, ParseOptions}; +use cranelift_reader::{ParseError, ParseOptions, parse_run_command, parse_test}; use std::path::PathBuf; use std::{fs, io}; use thiserror::Error; diff --git a/cranelift/src/run.rs b/cranelift/src/run.rs index bc9048688fd0..64d01530b376 100644 --- a/cranelift/src/run.rs +++ b/cranelift/src/run.rs @@ -6,9 +6,9 @@ use clap::Parser; use cranelift_codegen::isa::{CallConv, OwnedTargetIsa}; use cranelift_filetests::TestFileCompiler; use cranelift_native::builder as host_isa_builder; -use cranelift_reader::{parse_run_command, parse_test, Details, IsaSpec, ParseOptions}; +use cranelift_reader::{Details, IsaSpec, ParseOptions, parse_run_command, parse_test}; use std::path::{Path, PathBuf}; -use target_lexicon::{Triple, HOST}; +use target_lexicon::{HOST, Triple}; /// Execute clif code and verify with test expressions #[derive(Parser)] diff --git a/cranelift/src/souper_harvest.rs b/cranelift/src/souper_harvest.rs index d8a559c437c7..74f58edb1d99 100644 --- a/cranelift/src/souper_harvest.rs +++ b/cranelift/src/souper_harvest.rs @@ -1,9 +1,9 @@ use crate::utils::{iterate_files, read_to_string}; use anyhow::{Context as _, Result}; use clap::Parser; +use cranelift_codegen::Context; use cranelift_codegen::control::ControlPlane; use cranelift_codegen::ir::Function; -use cranelift_codegen::Context; use cranelift_reader::parse_sets_and_triple; use rayon::iter::{IntoParallelIterator, ParallelBridge, ParallelIterator}; use std::collections::HashSet; @@ -64,7 +64,7 @@ pub fn run(options: &Options) -> Result<()> { return Err(e).context(format!( "failed to create output directory: {}", options.output_dir.display() - )) + )); } } diff --git a/crates/bench-api/src/lib.rs b/crates/bench-api/src/lib.rs index ff6b88be310a..f52ac9e23c25 100644 --- a/crates/bench-api/src/lib.rs +++ b/crates/bench-api/src/lib.rs @@ -141,7 +141,7 @@ use clap::Parser; use std::os::raw::{c_int, c_void}; use std::slice; use std::{env, path::PathBuf}; -use wasi_common::{sync::WasiCtxBuilder, I32Exit, WasiCtx}; +use wasi_common::{I32Exit, WasiCtx, sync::WasiCtxBuilder}; use wasmtime::{Engine, Instance, Linker, Module, Store}; use wasmtime_cli_flags::CommonOptions; diff --git a/crates/c-api/src/async.rs b/crates/c-api/src/async.rs index d501fce3b90f..48118321a981 100644 --- a/crates/c-api/src/async.rs +++ b/crates/c-api/src/async.rs @@ -12,10 +12,10 @@ use wasmtime::{ }; use crate::{ - bad_utf8, handle_result, to_str, translate_args, wasm_config_t, wasm_functype_t, wasm_trap_t, - wasmtime_caller_t, wasmtime_error_t, wasmtime_instance_pre_t, wasmtime_linker_t, - wasmtime_module_t, wasmtime_val_t, wasmtime_val_union, WasmtimeCaller, WasmtimeStoreContextMut, - WASMTIME_I32, + WASMTIME_I32, WasmtimeCaller, WasmtimeStoreContextMut, bad_utf8, handle_result, to_str, + translate_args, wasm_config_t, wasm_functype_t, wasm_trap_t, wasmtime_caller_t, + wasmtime_error_t, wasmtime_instance_pre_t, wasmtime_linker_t, wasmtime_module_t, + wasmtime_val_t, wasmtime_val_union, }; #[unsafe(no_mangle)] @@ -176,9 +176,9 @@ unsafe fn c_async_callback_to_rust_fn( &'a [Val], &'a mut [Val], ) -> Box> + Send + 'a> - + Send - + Sync - + 'static { ++ Send ++ Sync ++ 'static { let foreign = crate::ForeignData { data, finalizer }; move |caller, params, results| { let _ = &foreign; // move entire foreign into this closure diff --git a/crates/c-api/src/error.rs b/crates/c-api/src/error.rs index 01bcbfedfbd8..ffac9df4d436 100644 --- a/crates/c-api/src/error.rs +++ b/crates/c-api/src/error.rs @@ -1,5 +1,5 @@ use crate::{wasm_frame_vec_t, wasm_name_t}; -use anyhow::{anyhow, Error, Result}; +use anyhow::{Error, Result, anyhow}; #[repr(C)] pub struct wasmtime_error_t { diff --git a/crates/c-api/src/extern.rs b/crates/c-api/src/extern.rs index f7227c8ab80c..c21b2047c0da 100644 --- a/crates/c-api/src/extern.rs +++ b/crates/c-api/src/extern.rs @@ -1,6 +1,6 @@ use crate::{ - wasm_externkind_t, wasm_externtype_t, wasm_func_t, wasm_global_t, wasm_memory_t, wasm_table_t, - WasmStoreRef, WasmtimeStoreContext, + WasmStoreRef, WasmtimeStoreContext, wasm_externkind_t, wasm_externtype_t, wasm_func_t, + wasm_global_t, wasm_memory_t, wasm_table_t, }; use std::mem::ManuallyDrop; use wasmtime::{Extern, Func, Global, Memory, SharedMemory, Table}; diff --git a/crates/c-api/src/func.rs b/crates/c-api/src/func.rs index 84bd06eacc6a..c45f3a4c846a 100644 --- a/crates/c-api/src/func.rs +++ b/crates/c-api/src/func.rs @@ -1,9 +1,9 @@ +use crate::{WasmtimeCaller, WasmtimeStoreData, wasm_trap_t}; use crate::{ - wasm_extern_t, wasm_functype_t, wasm_store_t, wasm_val_t, wasm_val_vec_t, wasmtime_error_t, - wasmtime_extern_t, wasmtime_val_t, wasmtime_val_union, WasmtimeStoreContext, - WasmtimeStoreContextMut, + WasmtimeStoreContext, WasmtimeStoreContextMut, wasm_extern_t, wasm_functype_t, wasm_store_t, + wasm_val_t, wasm_val_vec_t, wasmtime_error_t, wasmtime_extern_t, wasmtime_val_t, + wasmtime_val_union, }; -use crate::{wasm_trap_t, WasmtimeCaller, WasmtimeStoreData}; use anyhow::{Error, Result}; use std::any::Any; use std::ffi::c_void; @@ -55,9 +55,9 @@ unsafe fn create_function( store: &mut wasm_store_t, ty: &wasm_functype_t, func: impl Fn(*const wasm_val_vec_t, *mut wasm_val_vec_t) -> Option> - + Send - + Sync - + 'static, + + Send + + Sync + + 'static, ) -> Box { let ty = ty.ty().ty(store.store.context().engine()); let func = Func::new( diff --git a/crates/c-api/src/global.rs b/crates/c-api/src/global.rs index 82db17ec013e..dd3605301bfc 100644 --- a/crates/c-api/src/global.rs +++ b/crates/c-api/src/global.rs @@ -1,6 +1,6 @@ use crate::{ - handle_result, wasm_extern_t, wasm_globaltype_t, wasm_store_t, wasm_val_t, wasmtime_error_t, - wasmtime_val_t, WasmtimeStoreContext, WasmtimeStoreContextMut, + WasmtimeStoreContext, WasmtimeStoreContextMut, handle_result, wasm_extern_t, wasm_globaltype_t, + wasm_store_t, wasm_val_t, wasmtime_error_t, wasmtime_val_t, }; use std::mem::MaybeUninit; use wasmtime::{Extern, Global, RootScope}; diff --git a/crates/c-api/src/instance.rs b/crates/c-api/src/instance.rs index 531e71223de9..6fece5782ac0 100644 --- a/crates/c-api/src/instance.rs +++ b/crates/c-api/src/instance.rs @@ -1,6 +1,7 @@ use crate::{ - wasm_extern_t, wasm_extern_vec_t, wasm_module_t, wasm_store_t, wasm_trap_t, wasmtime_error_t, - wasmtime_extern_t, wasmtime_module_t, WasmStoreRef, WasmtimeStoreContextMut, WasmtimeStoreData, + WasmStoreRef, WasmtimeStoreContextMut, WasmtimeStoreData, wasm_extern_t, wasm_extern_vec_t, + wasm_module_t, wasm_store_t, wasm_trap_t, wasmtime_error_t, wasmtime_extern_t, + wasmtime_module_t, }; use std::mem::MaybeUninit; use wasmtime::{Instance, InstancePre, Trap}; diff --git a/crates/c-api/src/lib.rs b/crates/c-api/src/lib.rs index 9537407f2e6f..580fac3e1f55 100644 --- a/crates/c-api/src/lib.rs +++ b/crates/c-api/src/lib.rs @@ -40,13 +40,13 @@ mod vec; pub use crate::config::*; pub use crate::engine::*; pub use crate::error::*; +pub use crate::r#extern::*; pub use crate::func::*; pub use crate::global::*; pub use crate::instance::*; pub use crate::linker::*; pub use crate::memory::*; pub use crate::module::*; -pub use crate::r#extern::*; pub use crate::r#ref::*; pub use crate::store::*; pub use crate::table::*; diff --git a/crates/c-api/src/linker.rs b/crates/c-api/src/linker.rs index 28fa087153ae..fb77542e8d37 100644 --- a/crates/c-api/src/linker.rs +++ b/crates/c-api/src/linker.rs @@ -1,7 +1,7 @@ use crate::{ - bad_utf8, handle_result, wasm_engine_t, wasm_functype_t, wasm_trap_t, wasmtime_error_t, - wasmtime_extern_t, wasmtime_instance_pre_t, wasmtime_module_t, WasmtimeStoreContext, - WasmtimeStoreContextMut, + WasmtimeStoreContext, WasmtimeStoreContextMut, bad_utf8, handle_result, wasm_engine_t, + wasm_functype_t, wasm_trap_t, wasmtime_error_t, wasmtime_extern_t, wasmtime_instance_pre_t, + wasmtime_module_t, }; use std::ffi::c_void; use std::mem::MaybeUninit; diff --git a/crates/c-api/src/memory.rs b/crates/c-api/src/memory.rs index 460cc83bc413..72f9e2968d84 100644 --- a/crates/c-api/src/memory.rs +++ b/crates/c-api/src/memory.rs @@ -1,6 +1,6 @@ use crate::{ - handle_result, wasm_extern_t, wasm_memorytype_t, wasm_store_t, wasmtime_error_t, - WasmtimeStoreContext, WasmtimeStoreContextMut, + WasmtimeStoreContext, WasmtimeStoreContextMut, handle_result, wasm_extern_t, wasm_memorytype_t, + wasm_store_t, wasmtime_error_t, }; use std::convert::TryFrom; use wasmtime::{Extern, Memory}; diff --git a/crates/c-api/src/module.rs b/crates/c-api/src/module.rs index 7cc2a394667f..d16726b5116a 100644 --- a/crates/c-api/src/module.rs +++ b/crates/c-api/src/module.rs @@ -1,6 +1,7 @@ use crate::{ - handle_result, wasm_byte_vec_t, wasm_engine_t, wasm_exporttype_t, wasm_exporttype_vec_t, - wasm_importtype_t, wasm_importtype_vec_t, wasm_store_t, wasmtime_error_t, CExternType, + CExternType, handle_result, wasm_byte_vec_t, wasm_engine_t, wasm_exporttype_t, + wasm_exporttype_vec_t, wasm_importtype_t, wasm_importtype_vec_t, wasm_store_t, + wasmtime_error_t, }; use anyhow::Context; use std::ffi::CStr; diff --git a/crates/c-api/src/ref.rs b/crates/c-api/src/ref.rs index 2a80c20a0c42..ff2ee34bf3ab 100644 --- a/crates/c-api/src/ref.rs +++ b/crates/c-api/src/ref.rs @@ -1,6 +1,6 @@ -use crate::{abort, WasmtimeStoreContextMut}; +use crate::{WasmtimeStoreContextMut, abort}; use std::{mem::MaybeUninit, num::NonZeroU64, os::raw::c_void, ptr}; -use wasmtime::{AnyRef, ExternRef, ManuallyRooted, Ref, RootScope, Val, I31}; +use wasmtime::{AnyRef, ExternRef, I31, ManuallyRooted, Ref, RootScope, Val}; /// `*mut wasm_ref_t` is a reference type (`externref` or `funcref`), as seen by /// the C API. Because we do not have a uniform representation for `funcref`s diff --git a/crates/c-api/src/store.rs b/crates/c-api/src/store.rs index 90e133e7a061..e7eb2f1d8d4e 100644 --- a/crates/c-api/src/store.rs +++ b/crates/c-api/src/store.rs @@ -1,4 +1,4 @@ -use crate::{wasm_engine_t, wasmtime_error_t, wasmtime_val_t, ForeignData}; +use crate::{ForeignData, wasm_engine_t, wasmtime_error_t, wasmtime_val_t}; use std::cell::UnsafeCell; use std::ffi::c_void; use std::sync::Arc; @@ -104,17 +104,14 @@ pub extern "C" fn wasmtime_store_new( finalizer: Option, ) -> Box { Box::new(wasmtime_store_t { - store: Store::new( - &engine.engine, - WasmtimeStoreData { - foreign: ForeignData { data, finalizer }, - #[cfg(feature = "wasi")] - wasi: None, - hostcall_val_storage: Vec::new(), - wasm_val_storage: Vec::new(), - store_limits: StoreLimits::default(), - }, - ), + store: Store::new(&engine.engine, WasmtimeStoreData { + foreign: ForeignData { data, finalizer }, + #[cfg(feature = "wasi")] + wasi: None, + hostcall_val_storage: Vec::new(), + wasm_val_storage: Vec::new(), + store_limits: StoreLimits::default(), + }), }) } diff --git a/crates/c-api/src/table.rs b/crates/c-api/src/table.rs index 663ccc89439c..806bcbe10bdd 100644 --- a/crates/c-api/src/table.rs +++ b/crates/c-api/src/table.rs @@ -1,6 +1,6 @@ use crate::{ - handle_result, wasm_extern_t, wasm_ref_t, wasm_store_t, wasm_tabletype_t, wasmtime_error_t, - wasmtime_val_t, WasmtimeStoreContext, WasmtimeStoreContextMut, + WasmtimeStoreContext, WasmtimeStoreContextMut, handle_result, wasm_extern_t, wasm_ref_t, + wasm_store_t, wasm_tabletype_t, wasmtime_error_t, wasmtime_val_t, }; use anyhow::anyhow; use std::mem::MaybeUninit; diff --git a/crates/c-api/src/trap.rs b/crates/c-api/src/trap.rs index 4f176a74bd2e..9631c2dd3442 100644 --- a/crates/c-api/src/trap.rs +++ b/crates/c-api/src/trap.rs @@ -1,5 +1,5 @@ use crate::{wasm_frame_vec_t, wasm_instance_t, wasm_name_t, wasm_store_t}; -use anyhow::{anyhow, Error}; +use anyhow::{Error, anyhow}; use std::cell::OnceCell; use wasmtime::{Trap, WasmBacktrace}; diff --git a/crates/c-api/src/types.rs b/crates/c-api/src/types.rs index 9df1715cf319..e1aa3a704a34 100644 --- a/crates/c-api/src/types.rs +++ b/crates/c-api/src/types.rs @@ -24,10 +24,10 @@ mod memory; mod table; mod val; pub use self::export::*; +pub use self::r#extern::*; pub use self::func::*; pub use self::global::*; pub use self::import::*; pub use self::memory::*; -pub use self::r#extern::*; pub use self::table::*; pub use self::val::*; diff --git a/crates/c-api/src/types/export.rs b/crates/c-api/src/types/export.rs index 255c63f726b3..5a7a72c58204 100644 --- a/crates/c-api/src/types/export.rs +++ b/crates/c-api/src/types/export.rs @@ -1,4 +1,4 @@ -use crate::{wasm_externtype_t, wasm_name_t, CExternType}; +use crate::{CExternType, wasm_externtype_t, wasm_name_t}; use std::cell::OnceCell; #[repr(C)] diff --git a/crates/c-api/src/types/extern.rs b/crates/c-api/src/types/extern.rs index 66707b8f0979..27da9ed9196d 100644 --- a/crates/c-api/src/types/extern.rs +++ b/crates/c-api/src/types/extern.rs @@ -1,5 +1,5 @@ -use crate::{wasm_functype_t, wasm_globaltype_t, wasm_memorytype_t, wasm_tabletype_t}; use crate::{CFuncType, CGlobalType, CMemoryType, CTableType}; +use crate::{wasm_functype_t, wasm_globaltype_t, wasm_memorytype_t, wasm_tabletype_t}; use wasmtime::ExternType; #[repr(C)] diff --git a/crates/c-api/src/types/func.rs b/crates/c-api/src/types/func.rs index 2d2cb7dd21fa..220801a3f1c1 100644 --- a/crates/c-api/src/types/func.rs +++ b/crates/c-api/src/types/func.rs @@ -1,4 +1,4 @@ -use crate::{wasm_externtype_t, wasm_valtype_t, wasm_valtype_vec_t, CExternType}; +use crate::{CExternType, wasm_externtype_t, wasm_valtype_t, wasm_valtype_vec_t}; use std::cell::OnceCell; use std::{ mem, diff --git a/crates/c-api/src/types/global.rs b/crates/c-api/src/types/global.rs index f19d78197ca2..aa34df67fd1a 100644 --- a/crates/c-api/src/types/global.rs +++ b/crates/c-api/src/types/global.rs @@ -1,4 +1,4 @@ -use crate::{wasm_externtype_t, wasm_valtype_t, CExternType}; +use crate::{CExternType, wasm_externtype_t, wasm_valtype_t}; use std::cell::OnceCell; use wasmtime::GlobalType; diff --git a/crates/c-api/src/types/import.rs b/crates/c-api/src/types/import.rs index 848d07469715..3500d4ffc69c 100644 --- a/crates/c-api/src/types/import.rs +++ b/crates/c-api/src/types/import.rs @@ -1,4 +1,4 @@ -use crate::{wasm_externtype_t, wasm_name_t, CExternType}; +use crate::{CExternType, wasm_externtype_t, wasm_name_t}; use std::cell::OnceCell; #[repr(C)] diff --git a/crates/c-api/src/types/memory.rs b/crates/c-api/src/types/memory.rs index a49dc8daeba6..5521413ff8e7 100644 --- a/crates/c-api/src/types/memory.rs +++ b/crates/c-api/src/types/memory.rs @@ -1,4 +1,4 @@ -use crate::{wasm_externtype_t, wasm_limits_t, CExternType}; +use crate::{CExternType, wasm_externtype_t, wasm_limits_t}; use std::cell::OnceCell; use std::convert::TryFrom; use wasmtime::{MemoryType, MemoryTypeBuilder}; diff --git a/crates/c-api/src/types/table.rs b/crates/c-api/src/types/table.rs index 6ede2e622c12..63440f9b29e6 100644 --- a/crates/c-api/src/types/table.rs +++ b/crates/c-api/src/types/table.rs @@ -1,4 +1,4 @@ -use crate::{wasm_externtype_t, wasm_limits_t, wasm_valtype_t, CExternType}; +use crate::{CExternType, wasm_externtype_t, wasm_limits_t, wasm_valtype_t}; use std::cell::OnceCell; use wasmtime::{TableType, ValType}; diff --git a/crates/c-api/src/val.rs b/crates/c-api/src/val.rs index bdd9a6be9610..05f532defb5a 100644 --- a/crates/c-api/src/val.rs +++ b/crates/c-api/src/val.rs @@ -1,7 +1,7 @@ use crate::r#ref::ref_to_val; use crate::{ - from_valtype, into_valtype, wasm_ref_t, wasm_valkind_t, wasmtime_anyref_t, - wasmtime_externref_t, wasmtime_valkind_t, WasmtimeStoreContextMut, WASM_I32, + WASM_I32, WasmtimeStoreContextMut, from_valtype, into_valtype, wasm_ref_t, wasm_valkind_t, + wasmtime_anyref_t, wasmtime_externref_t, wasmtime_valkind_t, }; use std::mem::{ManuallyDrop, MaybeUninit}; use std::ptr; diff --git a/crates/c-api/src/wasi.rs b/crates/c-api/src/wasi.rs index baa612c6a0fc..1dca998d5207 100644 --- a/crates/c-api/src/wasi.rs +++ b/crates/c-api/src/wasi.rs @@ -2,11 +2,11 @@ use crate::wasm_byte_vec_t; use anyhow::Result; -use std::ffi::{c_char, CStr}; +use std::ffi::{CStr, c_char}; use std::fs::File; use std::path::Path; use std::slice; -use wasmtime_wasi::{preview1::WasiP1Ctx, WasiCtxBuilder}; +use wasmtime_wasi::{WasiCtxBuilder, preview1::WasiP1Ctx}; unsafe fn cstr_to_path<'a>(path: *const c_char) -> Option<&'a Path> { CStr::from_ptr(path).to_str().map(Path::new).ok() diff --git a/crates/cache/src/config.rs b/crates/cache/src/config.rs index 62fc6e936f8e..4923930fea66 100644 --- a/crates/cache/src/config.rs +++ b/crates/cache/src/config.rs @@ -1,18 +1,18 @@ //! Module for configuring the cache system. use super::Worker; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use directories_next::ProjectDirs; use log::{trace, warn}; use serde::{ - de::{self, Deserializer}, Deserialize, + de::{self, Deserializer}, }; use std::fmt::Debug; use std::fs; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::time::Duration; // wrapped, so we have named section in config, diff --git a/crates/cache/src/lib.rs b/crates/cache/src/lib.rs index 88dbcfd953e1..a3929ae73dfb 100644 --- a/crates/cache/src/lib.rs +++ b/crates/cache/src/lib.rs @@ -12,7 +12,7 @@ use std::{fs, io}; mod config; mod worker; -pub use config::{create_new_config, CacheConfig}; +pub use config::{CacheConfig, create_new_config}; use worker::Worker; /// Module level cache entry. diff --git a/crates/cache/src/worker.rs b/crates/cache/src/worker.rs index 78561c104eca..341176b022dc 100644 --- a/crates/cache/src/worker.rs +++ b/crates/cache/src/worker.rs @@ -5,7 +5,7 @@ //! but we guarantee eventual consistency and fault tolerancy. //! Background tasks can be CPU intensive, but the worker thread has low priority. -use super::{fs_write_atomic, CacheConfig}; +use super::{CacheConfig, fs_write_atomic}; use log::{debug, info, trace, warn}; use serde_derive::{Deserialize, Serialize}; use std::cmp; @@ -14,7 +14,7 @@ use std::ffi::OsStr; use std::fmt; use std::fs; use std::path::{Path, PathBuf}; -use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; +use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; #[cfg(test)] use std::sync::{Arc, Condvar, Mutex}; use std::thread; @@ -253,7 +253,9 @@ impl WorkerThread { } Err(err) => { warn!( - "Failed to lower worker thread priority ({:?}). It might affect application performance.", err); + "Failed to lower worker thread priority ({:?}). It might affect application performance.", + err + ); } }; } diff --git a/crates/cli-flags/src/opt.rs b/crates/cli-flags/src/opt.rs index 9814ef3169fb..ab4e0e56c5f2 100644 --- a/crates/cli-flags/src/opt.rs +++ b/crates/cli-flags/src/opt.rs @@ -6,7 +6,7 @@ //! option parsing is contained exclusively within this module. use crate::{KeyValuePair, WasiNnGraph}; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use clap::builder::{StringValueParser, TypedValueParser, ValueParserFactory}; use clap::error::{Error, ErrorKind}; use std::marker; @@ -212,11 +212,7 @@ where .filter_map(|d| match d.name { OptName::Name(s) => { let s = s.replace('_', "-"); - if s == key { - Some((d, s)) - } else { - None - } + if s == key { Some((d, s)) } else { None } } OptName::Prefix(s) => { let name = key.strip_prefix(s)?.strip_prefix("-")?; diff --git a/crates/component-macro/src/bindgen.rs b/crates/component-macro/src/bindgen.rs index b33bbc5bcb7c..5f3d501f78bd 100644 --- a/crates/component-macro/src/bindgen.rs +++ b/crates/component-macro/src/bindgen.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; use syn::parse::{Error, Parse, ParseStream, Result}; use syn::punctuated::Punctuated; -use syn::{braced, token, Token}; +use syn::{Token, braced, token}; use wasmtime_wit_bindgen::{AsyncConfig, Opts, Ownership, TrappableError, TrappableImports}; use wit_parser::{PackageId, Resolve, UnresolvedPackageGroup, WorldId}; diff --git a/crates/component-macro/src/component.rs b/crates/component-macro/src/component.rs index a4c44e784607..0f8432e5504f 100644 --- a/crates/component-macro/src/component.rs +++ b/crates/component-macro/src/component.rs @@ -4,7 +4,7 @@ use std::collections::HashSet; use std::fmt; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; -use syn::{braced, parse_quote, Data, DeriveInput, Error, Ident, Result, Token}; +use syn::{Data, DeriveInput, Error, Ident, Result, Token, braced, parse_quote}; use wasmtime_component_util::{DiscriminantSize, FlagsSize}; mod kw { @@ -219,7 +219,9 @@ fn expand_variant( if body.variants.is_empty() { return Err(Error::new( name.span(), - format!("`{style}` component types can only be derived for Rust `enum`s with at least one variant"), + format!( + "`{style}` component types can only be derived for Rust `enum`s with at least one variant" + ), )); } @@ -261,7 +263,7 @@ fn expand_variant( Style::Record => unreachable!(), } ), - )) + )); } }, }) diff --git a/crates/component-macro/src/lib.rs b/crates/component-macro/src/lib.rs index d8026c31da49..43ffd093607f 100644 --- a/crates/component-macro/src/lib.rs +++ b/crates/component-macro/src/lib.rs @@ -1,4 +1,4 @@ -use syn::{parse_macro_input, DeriveInput, Error}; +use syn::{DeriveInput, Error, parse_macro_input}; mod bindgen; mod component; diff --git a/crates/component-macro/tests/codegen.rs b/crates/component-macro/tests/codegen.rs index 73d61fd99539..ce220ed4e8d5 100644 --- a/crates/component-macro/tests/codegen.rs +++ b/crates/component-macro/tests/codegen.rs @@ -524,7 +524,7 @@ mod trappable_imports { } mod custom_derives { - use std::collections::{hash_map::RandomState, HashSet}; + use std::collections::{HashSet, hash_map::RandomState}; wasmtime::component::bindgen!({ inline: " diff --git a/crates/component-macro/tests/expanded.rs b/crates/component-macro/tests/expanded.rs index 29e338bc02f0..4ce3efdd32fa 100644 --- a/crates/component-macro/tests/expanded.rs +++ b/crates/component-macro/tests/expanded.rs @@ -1,6 +1,6 @@ use std::path::Path; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; macro_rules! genexpand { ($id:ident $name:tt $path:tt) => { @@ -53,13 +53,11 @@ fn process_expanded(path: &str, suffix: &str, src: &str) -> Result<()> { .header("expected", "actual") ) } - Err(err) => { - return Err(err).with_context(|| { - format!( + Err(err) => return Err(err).with_context(|| { + format!( "failed to read {expanded_path:?}; re-run with BINDGEN_TEST_BLESS=1 to create" ) - }) - } + }), } } Ok(()) diff --git a/crates/cranelift/src/builder.rs b/crates/cranelift/src/builder.rs index 58df015e97a1..a06c284806d5 100644 --- a/crates/cranelift/src/builder.rs +++ b/crates/cranelift/src/builder.rs @@ -6,8 +6,8 @@ use crate::isa_builder::IsaBuilder; use anyhow::Result; use cranelift_codegen::{ - isa::{self, OwnedTargetIsa}, CodegenResult, + isa::{self, OwnedTargetIsa}, }; use std::fmt; use std::path; diff --git a/crates/cranelift/src/compiled_function.rs b/crates/cranelift/src/compiled_function.rs index d5428cb2a1e3..ca1faab58eb0 100644 --- a/crates/cranelift/src/compiled_function.rs +++ b/crates/cranelift/src/compiled_function.rs @@ -1,7 +1,7 @@ -use crate::{mach_reloc_to_reloc, mach_trap_to_trap, Relocation}; +use crate::{Relocation, mach_reloc_to_reloc, mach_trap_to_trap}; use cranelift_codegen::{ - ir, isa::unwind::CfaUnwindInfo, isa::unwind::UnwindInfo, Final, MachBufferFinalized, - MachSrcLoc, ValueLabelsRanges, + Final, MachBufferFinalized, MachSrcLoc, ValueLabelsRanges, ir, isa::unwind::CfaUnwindInfo, + isa::unwind::UnwindInfo, }; use wasmtime_environ::{FilePos, InstructionAddressMap, PrimaryMap, TrapInformation}; diff --git a/crates/cranelift/src/compiler.rs b/crates/cranelift/src/compiler.rs index ea87148ca01a..ddd663083a1f 100644 --- a/crates/cranelift/src/compiler.rs +++ b/crates/cranelift/src/compiler.rs @@ -1,17 +1,17 @@ +use crate::TRAP_INTERNAL_ASSERT; use crate::debug::DwarfSectionRelocTarget; use crate::func_environ::FuncEnvironment; use crate::translate::FuncTranslator; -use crate::TRAP_INTERNAL_ASSERT; -use crate::{array_call_signature, CompiledFunction, ModuleTextBuilder}; -use crate::{builder::LinkOptions, wasm_call_signature, BuiltinFunctionSignatures}; +use crate::{BuiltinFunctionSignatures, builder::LinkOptions, wasm_call_signature}; +use crate::{CompiledFunction, ModuleTextBuilder, array_call_signature}; use anyhow::{Context as _, Result}; use cranelift_codegen::binemit::CodeOffset; use cranelift_codegen::bitset::CompoundBitSet; use cranelift_codegen::ir::condcodes::IntCC; use cranelift_codegen::ir::{self, InstBuilder, MemFlags, UserExternalName, UserFuncName, Value}; use cranelift_codegen::isa::{ - unwind::{UnwindInfo, UnwindInfoKind}, OwnedTargetIsa, TargetIsa, + unwind::{UnwindInfo, UnwindInfoKind}, }; use cranelift_codegen::print_errors::pretty_error; use cranelift_codegen::{CompiledCode, Context}; @@ -548,19 +548,16 @@ impl wasmtime_environ::Compiler for Compiler { obj.section_symbol(dwarf_sections_ids[name]) } }; - obj.add_relocation( - section_id, - object::write::Relocation { - offset: u64::from(reloc.offset), - symbol: target_symbol, - addend: i64::from(reloc.addend), - flags: RelocationFlags::Generic { - size: reloc.size << 3, - kind: RelocationKind::Absolute, - encoding: RelocationEncoding::Generic, - }, + obj.add_relocation(section_id, object::write::Relocation { + offset: u64::from(reloc.offset), + symbol: target_symbol, + addend: i64::from(reloc.addend), + flags: RelocationFlags::Generic { + size: reloc.size << 3, + kind: RelocationKind::Absolute, + encoding: RelocationEncoding::Generic, }, - )?; + })?; } } diff --git a/crates/cranelift/src/compiler/component.rs b/crates/cranelift/src/compiler/component.rs index c3c84ad6bfc8..dbdfddf612e1 100644 --- a/crates/cranelift/src/compiler/component.rs +++ b/crates/cranelift/src/compiler/component.rs @@ -1,6 +1,6 @@ //! Compilation support for the component model. -use crate::{compiler::Compiler, TRAP_ALWAYS, TRAP_CANNOT_ENTER, TRAP_INTERNAL_ASSERT}; +use crate::{TRAP_ALWAYS, TRAP_CANNOT_ENTER, TRAP_INTERNAL_ASSERT, compiler::Compiler}; use anyhow::Result; use cranelift_codegen::ir::condcodes::IntCC; use cranelift_codegen::ir::{self, InstBuilder, MemFlags}; @@ -42,13 +42,10 @@ impl<'a> TrampolineCompiler<'a> { let isa = &*compiler.isa; let signature = component.trampolines[index]; let ty = types[signature].unwrap_func(); - let func = ir::Function::with_name_signature( - ir::UserFuncName::user(0, 0), - match abi { - Abi::Wasm => crate::wasm_call_signature(isa, ty, &compiler.tunables), - Abi::Array => crate::array_call_signature(isa), - }, - ); + let func = ir::Function::with_name_signature(ir::UserFuncName::user(0, 0), match abi { + Abi::Wasm => crate::wasm_call_signature(isa, ty, &compiler.tunables), + Abi::Array => crate::array_call_signature(isa), + }); let (builder, block0) = func_compiler.builder(func); TrampolineCompiler { compiler, @@ -291,13 +288,8 @@ impl<'a> TrampolineCompiler<'a> { ir::types::I8, i64::from(wasmtime_environ::Trap::AlwaysTrapAdapter as u8), ); - self.compiler.call_indirect_host( - &mut self.builder, - index, - host_sig, - host_fn, - &[vmctx, code], - ); + self.compiler + .call_indirect_host(&mut self.builder, index, host_sig, host_fn, &[vmctx, code]); let succeeded = self.builder.ins().iconst(ir::types::I8, 0); self.raise_if_host_trapped(succeeded); // debug trap in case execution actually falls through, but this @@ -532,11 +524,11 @@ impl<'a> TrampolineCompiler<'a> { // takes ourselves out of the chain here but that's ok since the // caller is only used for store/limits and that same info is // stored, but elsewhere, in the component context. - self.builder.ins().call_indirect( - sig_ref, - func_addr, - &[callee_vmctx, caller_vmctx, rep], - ); + self.builder.ins().call_indirect(sig_ref, func_addr, &[ + callee_vmctx, + caller_vmctx, + rep, + ]); } self.builder.ins().jump(return_block, &[]); self.builder.seal_block(run_destructor_block); diff --git a/crates/cranelift/src/debug.rs b/crates/cranelift/src/debug.rs index 96863c11e636..aadc36682893 100644 --- a/crates/cranelift/src/debug.rs +++ b/crates/cranelift/src/debug.rs @@ -201,7 +201,7 @@ impl<'a> fmt::Debug for Compilation<'a> { } } -pub use write_debuginfo::{emit_dwarf, DwarfSectionRelocTarget}; +pub use write_debuginfo::{DwarfSectionRelocTarget, emit_dwarf}; mod gc; mod transform; diff --git a/crates/cranelift/src/debug/gc.rs b/crates/cranelift/src/debug/gc.rs index 3bbc56aca285..ec1b0558949f 100644 --- a/crates/cranelift/src/debug/gc.rs +++ b/crates/cranelift/src/debug/gc.rs @@ -1,8 +1,8 @@ use crate::debug::transform::AddressTransform; use crate::debug::{Compilation, Reader}; +use gimli::UnitSectionOffset; use gimli::constants; use gimli::read; -use gimli::UnitSectionOffset; use std::collections::{HashMap, HashSet}; use wasmtime_environ::{PrimaryMap, StaticModuleIndex}; diff --git a/crates/cranelift/src/debug/transform/address_transform.rs b/crates/cranelift/src/debug/transform/address_transform.rs index 2bb126dde764..da70155038c8 100644 --- a/crates/cranelift/src/debug/transform/address_transform.rs +++ b/crates/cranelift/src/debug/transform/address_transform.rs @@ -1,5 +1,5 @@ -use crate::debug::Compilation; use crate::FunctionAddressMap; +use crate::debug::Compilation; use gimli::write; use std::collections::BTreeMap; use wasmtime_environ::{DefinedFuncIndex, FilePos, PrimaryMap, StaticModuleIndex}; @@ -474,15 +474,12 @@ impl AddressTransform { let (fn_start, fn_end, lookup) = build_function_lookup(&metadata.address_map, code_section_offset); - func.insert( - fn_start, - FuncTransform { - start: fn_start, - end: fn_end, - index: idx, - lookup, - }, - ); + func.insert(fn_start, FuncTransform { + start: fn_start, + end: fn_end, + index: idx, + lookup, + }); } let map = build_function_addr_map(compilation, module); @@ -661,7 +658,7 @@ impl AddressTransform { #[cfg(test)] mod tests { - use super::{build_function_lookup, get_wasm_code_offset, AddressTransform}; + use super::{AddressTransform, build_function_lookup, get_wasm_code_offset}; use crate::{CompiledFunctionMetadata, FunctionAddressMap}; use cranelift_entity::PrimaryMap; use gimli::write::Address; @@ -789,15 +786,12 @@ mod tests { ..Default::default() }; let input = PrimaryMap::from_iter([&func]); - let at = AddressTransform::mock( - &input, - WasmFileInfo { - path: None, - code_section_offset: 1, - imported_func_count: 0, - funcs: Vec::new(), - }, - ); + let at = AddressTransform::mock(&input, WasmFileInfo { + path: None, + code_section_offset: 1, + imported_func_count: 0, + funcs: Vec::new(), + }); let addr = at.translate(10); assert_eq!( diff --git a/crates/cranelift/src/debug/transform/attr.rs b/crates/cranelift/src/debug/transform/attr.rs index 4b753e175a3a..d1ad275a822e 100644 --- a/crates/cranelift/src/debug/transform/attr.rs +++ b/crates/cranelift/src/debug/transform/attr.rs @@ -1,16 +1,16 @@ -use crate::debug::transform::utils::resolve_die_ref; use crate::debug::Reader; +use crate::debug::transform::utils::resolve_die_ref; use super::address_transform::AddressTransform; -use super::expression::{compile_expression, CompiledExpression, FunctionFrameInfo}; +use super::expression::{CompiledExpression, FunctionFrameInfo, compile_expression}; use super::range_info_builder::RangeInfoBuilder; use super::refs::{PendingDebugInfoRefs, PendingUnitRefs}; use super::unit::InheritedAttr; -use super::{dbi_log, TransformError}; -use anyhow::{bail, Error}; +use super::{TransformError, dbi_log}; +use anyhow::{Error, bail}; use cranelift_codegen::isa::TargetIsa; use gimli::{ - write, AttributeValue, DebugLineOffset, DebuggingInformationEntry, Dwarf, Unit, UnitOffset, + AttributeValue, DebugLineOffset, DebuggingInformationEntry, Dwarf, Unit, UnitOffset, write, }; #[derive(Debug)] @@ -243,11 +243,7 @@ pub(crate) fn clone_die_attributes<'a>( ) .filter(|i| { // Ignore empty range - if let Ok((_, 0, _)) = i { - false - } else { - true - } + if let Ok((_, 0, _)) = i { false } else { true } }) .map(|i| { i.map(|(start, len, expr)| write::Location::StartLength { @@ -393,13 +389,10 @@ fn prepare_die_context( match entry.tag() { gimli::DW_TAG_subprogram | gimli::DW_TAG_inlined_subroutine | gimli::DW_TAG_entry_point => { // Push the 'context' of there being no parameters (yet). - subprograms.push( - *depth, - SubprogramContext { - obj_ptr: UnitOffset { 0: 0 }, - param_num: -1, - }, - ); + subprograms.push(*depth, SubprogramContext { + obj_ptr: UnitOffset { 0: 0 }, + param_num: -1, + }); } gimli::DW_TAG_formal_parameter => { // Formal parameter tags can be parented by catch blocks diff --git a/crates/cranelift/src/debug/transform/debug_transform_logging.rs b/crates/cranelift/src/debug/transform/debug_transform_logging.rs index 1a56eb70a1bc..afc959a936e1 100644 --- a/crates/cranelift/src/debug/transform/debug_transform_logging.rs +++ b/crates/cranelift/src/debug/transform/debug_transform_logging.rs @@ -1,8 +1,8 @@ use crate::debug::Reader; use core::fmt; use gimli::{ - write, AttributeValue, DebuggingInformationEntry, Dwarf, LittleEndian, Unit, UnitOffset, - UnitSectionOffset, + AttributeValue, DebuggingInformationEntry, Dwarf, LittleEndian, Unit, UnitOffset, + UnitSectionOffset, write, }; macro_rules! dbi_log { diff --git a/crates/cranelift/src/debug/transform/expression.rs b/crates/cranelift/src/debug/transform/expression.rs index 873a76240f6b..3ecaa820b4ef 100644 --- a/crates/cranelift/src/debug/transform/expression.rs +++ b/crates/cranelift/src/debug/transform/expression.rs @@ -2,11 +2,11 @@ use super::address_transform::AddressTransform; use crate::debug::ModuleMemoryOffset; use crate::translate::get_vmctx_value_label; use anyhow::{Context, Error, Result}; -use cranelift_codegen::ir::ValueLabel; -use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::LabelValueLoc; use cranelift_codegen::ValueLabelsRanges; -use gimli::{write, Expression, Operation, Reader, ReaderOffset}; +use cranelift_codegen::ir::ValueLabel; +use cranelift_codegen::isa::TargetIsa; +use gimli::{Expression, Operation, Reader, ReaderOffset, write}; use std::cmp::PartialEq; use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; @@ -797,11 +797,11 @@ impl std::fmt::Debug for JumpTargetMarker { #[expect(trivial_numeric_casts, reason = "macro-generated code")] mod tests { use super::{ - compile_expression, AddressTransform, CompiledExpression, CompiledExpressionPart, - FunctionFrameInfo, JumpTargetMarker, ValueLabel, ValueLabelsRanges, + AddressTransform, CompiledExpression, CompiledExpressionPart, FunctionFrameInfo, + JumpTargetMarker, ValueLabel, ValueLabelsRanges, compile_expression, }; use crate::CompiledFunctionMetadata; - use gimli::{constants, Encoding, EndianSlice, Expression, RunTimeEndian}; + use gimli::{Encoding, EndianSlice, Expression, RunTimeEndian, constants}; use wasmtime_environ::FilePos; macro_rules! dw_op { @@ -868,16 +868,13 @@ mod tests { let ce = compile_expression(&e, DWARF_ENCODING, None) .expect("non-error") .expect("expression"); - assert_eq!( - ce, - CompiledExpression { - parts: vec![CompiledExpressionPart::Local { - label: val20, - trailing: true - }], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![CompiledExpressionPart::Local { + label: val20, + trailing: true + }], + need_deref: false, + }); let e = expression!( DW_OP_WASM_location, @@ -890,19 +887,16 @@ mod tests { let ce = compile_expression(&e, DWARF_ENCODING, None) .expect("non-error") .expect("expression"); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Local { - label: val1, - trailing: false - }, - CompiledExpressionPart::Code(vec![35, 16, 159]) - ], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Local { + label: val1, + trailing: false + }, + CompiledExpressionPart::Code(vec![35, 16, 159]) + ], + need_deref: false, + }); let e = expression!(DW_OP_WASM_location, 0x0, 3, DW_OP_stack_value); let fe = compile_expression(&e, DWARF_ENCODING, None).expect("non-error"); @@ -910,19 +904,16 @@ mod tests { let ce = compile_expression(&e, DWARF_ENCODING, fe.as_ref()) .expect("non-error") .expect("expression"); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Local { - label: val3, - trailing: false - }, - CompiledExpressionPart::Code(vec![35, 18]) - ], - need_deref: true, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Local { + label: val3, + trailing: false + }, + CompiledExpressionPart::Code(vec![35, 18]) + ], + need_deref: true, + }); let e = expression!( DW_OP_WASM_location, @@ -936,21 +927,18 @@ mod tests { let ce = compile_expression(&e, DWARF_ENCODING, None) .expect("non-error") .expect("expression"); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Local { - label: val1, - trailing: false - }, - CompiledExpressionPart::Code(vec![35, 5]), - CompiledExpressionPart::Deref, - CompiledExpressionPart::Code(vec![6, 159]) - ], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Local { + label: val1, + trailing: false + }, + CompiledExpressionPart::Code(vec![35, 5]), + CompiledExpressionPart::Deref, + CompiledExpressionPart::Code(vec![6, 159]) + ], + need_deref: false, + }); let e = expression!( DW_OP_WASM_location, @@ -963,19 +951,16 @@ mod tests { let ce = compile_expression(&e, DWARF_ENCODING, None) .expect("non-error") .expect("expression"); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Local { - label: val1, - trailing: false - }, - CompiledExpressionPart::Code(vec![64, 35, 32, 22, 8, 32, 36, 22, 38, 159]) - ], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Local { + label: val1, + trailing: false + }, + CompiledExpressionPart::Code(vec![64, 35, 32, 22, 8, 32, 36, 22, 38, 159]) + ], + need_deref: false, + }); let e = expression!( DW_OP_lit1, @@ -1003,35 +988,32 @@ mod tests { .expect("expression"); let targets = find_jump_targets(&ce); assert_eq!(targets.len(), 2); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Code(vec![49, 18]), - CompiledExpressionPart::Local { - label: val1, - trailing: false - }, - CompiledExpressionPart::Code(vec![26]), - CompiledExpressionPart::Jump { - conditionally: true, - target: targets[0].clone(), - }, - CompiledExpressionPart::Code(vec![22, 35, 32, 22, 8, 32, 36, 22, 37]), - CompiledExpressionPart::Jump { - conditionally: false, - target: targets[1].clone(), - }, - CompiledExpressionPart::LandingPad(targets[0].clone()), // capture from - CompiledExpressionPart::Code(vec![34]), - CompiledExpressionPart::Deref, - CompiledExpressionPart::Code(vec![6]), - CompiledExpressionPart::LandingPad(targets[1].clone()), // capture to - CompiledExpressionPart::Code(vec![159]) - ], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Code(vec![49, 18]), + CompiledExpressionPart::Local { + label: val1, + trailing: false + }, + CompiledExpressionPart::Code(vec![26]), + CompiledExpressionPart::Jump { + conditionally: true, + target: targets[0].clone(), + }, + CompiledExpressionPart::Code(vec![22, 35, 32, 22, 8, 32, 36, 22, 37]), + CompiledExpressionPart::Jump { + conditionally: false, + target: targets[1].clone(), + }, + CompiledExpressionPart::LandingPad(targets[0].clone()), // capture from + CompiledExpressionPart::Code(vec![34]), + CompiledExpressionPart::Deref, + CompiledExpressionPart::Code(vec![6]), + CompiledExpressionPart::LandingPad(targets[1].clone()), // capture to + CompiledExpressionPart::Code(vec![159]) + ], + need_deref: false, + }); let e = expression!( DW_OP_lit1, @@ -1049,23 +1031,20 @@ mod tests { .expect("expression"); let targets = find_jump_targets(&ce); assert_eq!(targets.len(), 1); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Code(vec![49, 18]), - CompiledExpressionPart::Jump { - conditionally: true, - target: targets[0].clone(), - }, - CompiledExpressionPart::Deref, - CompiledExpressionPart::Code(vec![6, 48]), - CompiledExpressionPart::LandingPad(targets[0].clone()), // capture to - CompiledExpressionPart::Code(vec![159]) - ], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Code(vec![49, 18]), + CompiledExpressionPart::Jump { + conditionally: true, + target: targets[0].clone(), + }, + CompiledExpressionPart::Deref, + CompiledExpressionPart::Code(vec![6, 48]), + CompiledExpressionPart::LandingPad(targets[0].clone()), // capture to + CompiledExpressionPart::Code(vec![159]) + ], + need_deref: false, + }); let e = expression!( DW_OP_lit1, @@ -1087,46 +1066,40 @@ mod tests { .expect("expression"); let targets = find_jump_targets(&ce); assert_eq!(targets.len(), 2); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Code(vec![49]), - CompiledExpressionPart::LandingPad(targets[0].clone()), - CompiledExpressionPart::Code(vec![18, 73, 42]), - CompiledExpressionPart::Jump { - conditionally: true, - target: targets[1].clone(), - }, - CompiledExpressionPart::Code(vec![35, 1]), - CompiledExpressionPart::Jump { - conditionally: false, - target: targets[0].clone(), - }, - CompiledExpressionPart::LandingPad(targets[1].clone()), - CompiledExpressionPart::Code(vec![159]) - ], - need_deref: false, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Code(vec![49]), + CompiledExpressionPart::LandingPad(targets[0].clone()), + CompiledExpressionPart::Code(vec![18, 73, 42]), + CompiledExpressionPart::Jump { + conditionally: true, + target: targets[1].clone(), + }, + CompiledExpressionPart::Code(vec![35, 1]), + CompiledExpressionPart::Jump { + conditionally: false, + target: targets[0].clone(), + }, + CompiledExpressionPart::LandingPad(targets[1].clone()), + CompiledExpressionPart::Code(vec![159]) + ], + need_deref: false, + }); let e = expression!(DW_OP_WASM_location, 0x0, 1, DW_OP_plus_uconst, 5); let ce = compile_expression(&e, DWARF_ENCODING, None) .expect("non-error") .expect("expression"); - assert_eq!( - ce, - CompiledExpression { - parts: vec![ - CompiledExpressionPart::Local { - label: val1, - trailing: false - }, - CompiledExpressionPart::Code(vec![35, 5]) - ], - need_deref: true, - } - ); + assert_eq!(ce, CompiledExpression { + parts: vec![ + CompiledExpressionPart::Local { + label: val1, + trailing: false + }, + CompiledExpressionPart::Code(vec![35, 5]) + ], + need_deref: true, + }); } fn create_mock_address_transform() -> AddressTransform { @@ -1183,37 +1156,28 @@ mod tests { let value_0 = ValueLabel::new(0); let value_1 = ValueLabel::new(1); let value_2 = ValueLabel::new(2); - value_ranges.insert( - value_0, - vec![ValueLocRange { + value_ranges.insert(value_0, vec![ValueLocRange { + loc: LabelValueLoc::CFAOffset(0), + start: 0, + end: 25, + }]); + value_ranges.insert(value_1, vec![ValueLocRange { + loc: LabelValueLoc::CFAOffset(0), + start: 5, + end: 30, + }]); + value_ranges.insert(value_2, vec![ + ValueLocRange { loc: LabelValueLoc::CFAOffset(0), start: 0, - end: 25, - }], - ); - value_ranges.insert( - value_1, - vec![ValueLocRange { + end: 10, + }, + ValueLocRange { loc: LabelValueLoc::CFAOffset(0), - start: 5, + start: 20, end: 30, - }], - ); - value_ranges.insert( - value_2, - vec![ - ValueLocRange { - loc: LabelValueLoc::CFAOffset(0), - start: 0, - end: 10, - }, - ValueLocRange { - loc: LabelValueLoc::CFAOffset(0), - start: 20, - end: 30, - }, - ], - ); + }, + ]); (value_ranges, (value_0, value_1, value_2)) } diff --git a/crates/cranelift/src/debug/transform/line_program.rs b/crates/cranelift/src/debug/transform/line_program.rs index 56835d6feb97..81c734fb2260 100644 --- a/crates/cranelift/src/debug/transform/line_program.rs +++ b/crates/cranelift/src/debug/transform/line_program.rs @@ -1,7 +1,7 @@ use super::address_transform::AddressTransform; use super::{Reader, TransformError}; -use anyhow::{bail, Error}; -use gimli::{write, DebugLineOffset, LineEncoding, Unit}; +use anyhow::{Error, bail}; +use gimli::{DebugLineOffset, LineEncoding, Unit, write}; use wasmtime_environ::DefinedFuncIndex; #[derive(Debug)] diff --git a/crates/cranelift/src/debug/transform/mod.rs b/crates/cranelift/src/debug/transform/mod.rs index 5f3deb7c7b9c..7c6bc3aa7df7 100644 --- a/crates/cranelift/src/debug/transform/mod.rs +++ b/crates/cranelift/src/debug/transform/mod.rs @@ -2,11 +2,11 @@ use self::debug_transform_logging::dbi_log; use self::refs::DebugInfoRefsMap; use self::simulate::generate_simulated_dwarf; use self::unit::clone_unit; -use crate::debug::gc::build_dependencies; use crate::debug::Compilation; +use crate::debug::gc::build_dependencies; use anyhow::Error; use cranelift_codegen::isa::TargetIsa; -use gimli::{write, Dwarf, DwarfPackage, LittleEndian, Section, Unit, UnitSectionOffset}; +use gimli::{Dwarf, DwarfPackage, LittleEndian, Section, Unit, UnitSectionOffset, write}; use std::{collections::HashSet, fmt::Debug}; use synthetic::ModuleSyntheticUnit; use thiserror::Error; diff --git a/crates/cranelift/src/debug/transform/range_info_builder.rs b/crates/cranelift/src/debug/transform/range_info_builder.rs index 526c83e6173f..776217beae0d 100644 --- a/crates/cranelift/src/debug/transform/range_info_builder.rs +++ b/crates/cranelift/src/debug/transform/range_info_builder.rs @@ -1,7 +1,7 @@ -use super::address_transform::AddressTransform; use super::Reader; +use super::address_transform::AddressTransform; use anyhow::Error; -use gimli::{write, AttributeValue, DebuggingInformationEntry, RangeListsOffset, Unit}; +use gimli::{AttributeValue, DebuggingInformationEntry, RangeListsOffset, Unit, write}; use wasmtime_environ::DefinedFuncIndex; pub(crate) enum RangeInfoBuilder { diff --git a/crates/cranelift/src/debug/transform/simulate.rs b/crates/cranelift/src/debug/transform/simulate.rs index 1e8ab10400e1..e4eac158c314 100644 --- a/crates/cranelift/src/debug/transform/simulate.rs +++ b/crates/cranelift/src/debug/transform/simulate.rs @@ -1,12 +1,12 @@ +use super::AddressTransform; use super::expression::{CompiledExpression, FunctionFrameInfo}; use super::utils::append_vmctx_info; -use super::AddressTransform; use crate::debug::Compilation; use crate::translate::get_vmctx_value_label; use anyhow::{Context, Error}; use cranelift_codegen::isa::TargetIsa; -use gimli::write; use gimli::LineEncoding; +use gimli::write; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; @@ -94,11 +94,7 @@ fn generate_line_info( } fn check_invalid_chars_in_name(s: &str) -> Option<&str> { - if s.contains('\x00') { - None - } else { - Some(s) - } + if s.contains('\x00') { None } else { Some(s) } } fn autogenerate_dwarf_wasm_path(di: &DebugInfoData) -> PathBuf { @@ -301,11 +297,12 @@ pub fn generate_simulated_dwarf( }; let (unit, root_id, file_id) = { - let comp_dir_id = out_strings.add(assert_dwarf_str!(path - .parent() - .context("path dir")? - .to_str() - .context("path dir encoding")?)); + let comp_dir_id = out_strings.add(assert_dwarf_str!( + path.parent() + .context("path dir")? + .to_str() + .context("path dir encoding")? + )); let name = path .file_name() .context("path name")? diff --git a/crates/cranelift/src/debug/transform/unit.rs b/crates/cranelift/src/debug/transform/unit.rs index 491a669dfa15..94411f09b1f9 100644 --- a/crates/cranelift/src/debug/transform/unit.rs +++ b/crates/cranelift/src/debug/transform/unit.rs @@ -1,5 +1,6 @@ +use super::DebugInputContext; use super::address_transform::AddressTransform; -use super::attr::{clone_die_attributes, EntryAttributesContext}; +use super::attr::{EntryAttributesContext, clone_die_attributes}; use super::debug_transform_logging::{ dbi_log, log_begin_input_die, log_end_output_die, log_end_output_die_skipped, log_get_cu_summary, @@ -10,7 +11,6 @@ use super::range_info_builder::RangeInfoBuilder; use super::refs::{PendingDebugInfoRefs, PendingUnitRefs, UnitRefsMap}; use super::synthetic::ModuleSyntheticUnit; use super::utils::{append_vmctx_info, resolve_die_ref}; -use super::DebugInputContext; use crate::debug::{Compilation, Reader}; use anyhow::{Context, Error}; use cranelift_codegen::ir::Endianness; diff --git a/crates/cranelift/src/debug/transform/utils.rs b/crates/cranelift/src/debug/transform/utils.rs index c23e98b4d47c..999828d2dcf3 100644 --- a/crates/cranelift/src/debug/transform/utils.rs +++ b/crates/cranelift/src/debug/transform/utils.rs @@ -4,7 +4,7 @@ use super::address_transform::AddressTransform; use super::expression::{CompiledExpression, FunctionFrameInfo}; use anyhow::Error; use cranelift_codegen::isa::TargetIsa; -use gimli::{write, AttributeValue, DebuggingInformationEntry, Unit}; +use gimli::{AttributeValue, DebuggingInformationEntry, Unit, write}; pub(crate) fn append_vmctx_info( comp_unit: &mut write::Unit, diff --git a/crates/cranelift/src/debug/write_debuginfo.rs b/crates/cranelift/src/debug/write_debuginfo.rs index 34054598406d..4b686b5d5a06 100644 --- a/crates/cranelift/src/debug/write_debuginfo.rs +++ b/crates/cranelift/src/debug/write_debuginfo.rs @@ -1,9 +1,9 @@ -pub use crate::debug::transform::transform_dwarf; use crate::debug::Compilation; +pub use crate::debug::transform::transform_dwarf; use cranelift_codegen::ir::Endianness; use cranelift_codegen::isa::{ - unwind::{CfaUnwindInfo, UnwindInfo}, TargetIsa, + unwind::{CfaUnwindInfo, UnwindInfo}, }; use gimli::write::{Address, Dwarf, EndianVec, FrameTable, Result, Sections, Writer}; use gimli::{RunTimeEndian, SectionId}; diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs index 15e2ba6ed3de..66f8fbb5a0eb 100644 --- a/crates/cranelift/src/func_environ.rs +++ b/crates/cranelift/src/func_environ.rs @@ -3,7 +3,7 @@ use crate::translate::{ FuncTranslationState, GlobalVariable, Heap, HeapData, StructFieldsVec, TableData, TableSize, TargetEnvironment, }; -use crate::{gc, BuiltinFunctionSignatures, TRAP_INTERNAL_ASSERT}; +use crate::{BuiltinFunctionSignatures, TRAP_INTERNAL_ASSERT, gc}; use cranelift_codegen::cursor::FuncCursor; use cranelift_codegen::ir::condcodes::{FloatCC, IntCC}; use cranelift_codegen::ir::immediates::{Imm64, Offset32}; @@ -1086,14 +1086,11 @@ impl<'module_environment> FuncEnvironment<'module_environment> { let ty = builder.func.dfg.value_type(rhs); let minus_one = builder.ins().iconst(ty, -1); let rhs_is_minus_one = builder.ins().icmp(IntCC::Equal, rhs, minus_one); - let int_min = builder.ins().iconst( - ty, - match ty { - I32 => i64::from(i32::MIN), - I64 => i64::MIN, - _ => unreachable!(), - }, - ); + let int_min = builder.ins().iconst(ty, match ty { + I32 => i64::from(i32::MIN), + I64 => i64::MIN, + _ => unreachable!(), + }); let lhs_is_int_min = builder.ins().icmp(IntCC::Equal, lhs, int_min); let is_integer_overflow = builder.ins().band(rhs_is_minus_one, lhs_is_int_min); self.conditionally_trap(builder, is_integer_overflow, ir::TrapCode::INTEGER_OVERFLOW); @@ -2040,10 +2037,13 @@ impl FuncEnvironment<'_> { .ins() .iconst(I32, i64::from(interned_type_index.as_u32())); let data_index = builder.ins().iconst(I32, i64::from(data_index.as_u32())); - let call_inst = builder.ins().call( - libcall, - &[vmctx, interned_type_index, data_index, data_offset, len], - ); + let call_inst = builder.ins().call(libcall, &[ + vmctx, + interned_type_index, + data_index, + data_offset, + len, + ]); let result = builder.func.dfg.first_result(call_inst); Ok(builder.ins().ireduce(ir::types::I32, result)) } @@ -2063,10 +2063,13 @@ impl FuncEnvironment<'_> { .ins() .iconst(I32, i64::from(interned_type_index.as_u32())); let elem_index = builder.ins().iconst(I32, i64::from(elem_index.as_u32())); - let call_inst = builder.ins().call( - libcall, - &[vmctx, interned_type_index, elem_index, elem_offset, len], - ); + let call_inst = builder.ins().call(libcall, &[ + vmctx, + interned_type_index, + elem_index, + elem_offset, + len, + ]); let result = builder.func.dfg.first_result(call_inst); Ok(builder.ins().ireduce(ir::types::I32, result)) } @@ -2084,10 +2087,9 @@ impl FuncEnvironment<'_> { ) -> WasmResult<()> { let libcall = gc::builtins::array_copy(self, builder.func)?; let vmctx = self.vmctx_val(&mut builder.cursor()); - builder.ins().call( - libcall, - &[vmctx, dst_array, dst_index, src_array, src_index, len], - ); + builder.ins().call(libcall, &[ + vmctx, dst_array, dst_index, src_array, src_index, len, + ]); Ok(()) } @@ -2120,18 +2122,15 @@ impl FuncEnvironment<'_> { .ins() .iconst(I32, i64::from(interned_type_index.as_u32())); let data_index = builder.ins().iconst(I32, i64::from(data_index.as_u32())); - builder.ins().call( - libcall, - &[ - vmctx, - interned_type_index, - array, - dst_index, - data_index, - data_offset, - len, - ], - ); + builder.ins().call(libcall, &[ + vmctx, + interned_type_index, + array, + dst_index, + data_index, + data_offset, + len, + ]); Ok(()) } @@ -2152,18 +2151,15 @@ impl FuncEnvironment<'_> { .ins() .iconst(I32, i64::from(interned_type_index.as_u32())); let elem_index = builder.ins().iconst(I32, i64::from(elem_index.as_u32())); - builder.ins().call( - libcall, - &[ - vmctx, - interned_type_index, - array, - dst_index, - elem_index, - elem_offset, - len, - ], - ); + builder.ins().call(libcall, &[ + vmctx, + interned_type_index, + array, + dst_index, + elem_index, + elem_offset, + len, + ]); Ok(()) } @@ -2862,10 +2858,14 @@ impl FuncEnvironment<'_> { let dst = self.cast_index_to_i64(&mut pos, dst, self.memory(memory_index).idx_type); - pos.ins().call( - memory_init, - &[vmctx, memory_index_arg, seg_index_arg, dst, src, len], - ); + pos.ins().call(memory_init, &[ + vmctx, + memory_index_arg, + seg_index_arg, + dst, + src, + len, + ]); Ok(()) } @@ -2914,17 +2914,14 @@ impl FuncEnvironment<'_> { let dst_table_index_arg = pos.ins().iconst(I32, dst_table_index_arg as i64); let src_table_index_arg = pos.ins().iconst(I32, src_table_index_arg as i64); let vmctx = self.vmctx_val(&mut pos); - pos.ins().call( - table_copy, - &[ - vmctx, - dst_table_index_arg, - src_table_index_arg, - dst, - src, - len, - ], - ); + pos.ins().call(table_copy, &[ + vmctx, + dst_table_index_arg, + src_table_index_arg, + dst, + src, + len, + ]); Ok(()) } @@ -2948,10 +2945,14 @@ impl FuncEnvironment<'_> { let src = pos.ins().uextend(I64, src); let len = pos.ins().uextend(I64, len); - pos.ins().call( - table_init, - &[vmctx, table_index_arg, seg_index_arg, dst, src, len], - ); + pos.ins().call(table_init, &[ + vmctx, + table_index_arg, + seg_index_arg, + dst, + src, + len, + ]); Ok(()) } @@ -2985,10 +2986,13 @@ impl FuncEnvironment<'_> { let vmctx = self.vmctx_val(&mut pos); - let call_inst = pos.ins().call( - wait_func, - &[vmctx, memory_index_arg, addr, expected, timeout], - ); + let call_inst = pos.ins().call(wait_func, &[ + vmctx, + memory_index_arg, + addr, + expected, + timeout, + ]); let ret = pos.func.dfg.inst_results(call_inst)[0]; Ok(builder.ins().ireduce(ir::types::I32, ret)) } diff --git a/crates/cranelift/src/gc/disabled.rs b/crates/cranelift/src/gc/disabled.rs index ebdc46b4821c..d02dcc14baf3 100644 --- a/crates/cranelift/src/gc/disabled.rs +++ b/crates/cranelift/src/gc/disabled.rs @@ -4,7 +4,7 @@ use super::GcCompiler; use crate::func_environ::FuncEnvironment; use cranelift_codegen::ir; use cranelift_frontend::FunctionBuilder; -use wasmtime_environ::{wasm_unsupported, TypeIndex, WasmRefType, WasmResult}; +use wasmtime_environ::{TypeIndex, WasmRefType, WasmResult, wasm_unsupported}; fn disabled() -> WasmResult { Err(wasm_unsupported!( diff --git a/crates/cranelift/src/gc/enabled.rs b/crates/cranelift/src/gc/enabled.rs index 01ef65274076..2edc57abd699 100644 --- a/crates/cranelift/src/gc/enabled.rs +++ b/crates/cranelift/src/gc/enabled.rs @@ -1,19 +1,19 @@ use super::GcCompiler; +use crate::TRAP_INTERNAL_ASSERT; use crate::func_environ::FuncEnvironment; use crate::gc::ArrayInit; use crate::translate::{StructFieldsVec, TargetEnvironment}; -use crate::TRAP_INTERNAL_ASSERT; use cranelift_codegen::{ cursor::FuncCursor, - ir::{self, condcodes::IntCC, InstBuilder}, + ir::{self, InstBuilder, condcodes::IntCC}, }; use cranelift_entity::packed_option::ReservedValue; use cranelift_frontend::FunctionBuilder; use smallvec::SmallVec; use wasmtime_environ::{ - wasm_unsupported, Collector, GcArrayLayout, GcLayout, GcStructLayout, ModuleInternedTypeIndex, - PtrSize, TypeIndex, VMGcKind, WasmHeapTopType, WasmHeapType, WasmRefType, WasmResult, - WasmStorageType, WasmValType, I31_DISCRIMINANT, NON_NULL_NON_I31_MASK, + Collector, GcArrayLayout, GcLayout, GcStructLayout, I31_DISCRIMINANT, ModuleInternedTypeIndex, + NON_NULL_NON_I31_MASK, PtrSize, TypeIndex, VMGcKind, WasmHeapTopType, WasmHeapType, + WasmRefType, WasmResult, WasmStorageType, WasmValType, wasm_unsupported, }; #[cfg(feature = "gc-drc")] @@ -148,9 +148,11 @@ fn read_field_at_addr( .builtin_functions .get_interned_func_ref(builder.func); - let call_inst = builder - .ins() - .call(get_interned_func_ref, &[vmctx, func_ref_id, expected_ty]); + let call_inst = builder.ins().call(get_interned_func_ref, &[ + vmctx, + func_ref_id, + expected_ty, + ]); builder.func.dfg.first_result(call_inst) } }, @@ -448,12 +450,10 @@ pub fn translate_array_new( elem: ir::Value, len: ir::Value, ) -> WasmResult { - gc_compiler(func_env)?.alloc_array( - func_env, - builder, - array_type_index, - ArrayInit::Fill { elem, len }, - ) + gc_compiler(func_env)?.alloc_array(func_env, builder, array_type_index, ArrayInit::Fill { + elem, + len, + }) } pub fn translate_array_new_default( @@ -465,12 +465,10 @@ pub fn translate_array_new_default( let interned_ty = func_env.module.types[array_type_index]; let array_ty = func_env.types.unwrap_array(interned_ty)?; let elem = default_value(&mut builder.cursor(), func_env, &array_ty.0.element_type); - gc_compiler(func_env)?.alloc_array( - func_env, - builder, - array_type_index, - ArrayInit::Fill { elem, len }, - ) + gc_compiler(func_env)?.alloc_array(func_env, builder, array_type_index, ArrayInit::Fill { + elem, + len, + }) } pub fn translate_array_new_fixed( diff --git a/crates/cranelift/src/gc/enabled/drc.rs b/crates/cranelift/src/gc/enabled/drc.rs index 412e644cd292..99ae255fc337 100644 --- a/crates/cranelift/src/gc/enabled/drc.rs +++ b/crates/cranelift/src/gc/enabled/drc.rs @@ -4,14 +4,14 @@ use super::*; use crate::gc::gc_compiler; use crate::translate::TargetEnvironment; -use crate::{func_environ::FuncEnvironment, gc::GcCompiler, TRAP_INTERNAL_ASSERT}; +use crate::{TRAP_INTERNAL_ASSERT, func_environ::FuncEnvironment, gc::GcCompiler}; use cranelift_codegen::ir::condcodes::IntCC; use cranelift_codegen::ir::{self, InstBuilder}; use cranelift_frontend::FunctionBuilder; use smallvec::SmallVec; use wasmtime_environ::{ - drc::DrcTypeLayouts, GcTypeLayouts, ModuleInternedTypeIndex, PtrSize, TypeIndex, VMGcKind, - WasmHeapTopType, WasmHeapType, WasmRefType, WasmResult, WasmStorageType, WasmValType, + GcTypeLayouts, ModuleInternedTypeIndex, PtrSize, TypeIndex, VMGcKind, WasmHeapTopType, + WasmHeapType, WasmRefType, WasmResult, WasmStorageType, WasmValType, drc::DrcTypeLayouts, }; #[derive(Default)] diff --git a/crates/cranelift/src/gc/enabled/null.rs b/crates/cranelift/src/gc/enabled/null.rs index bf478f82f511..3159ef0dec83 100644 --- a/crates/cranelift/src/gc/enabled/null.rs +++ b/crates/cranelift/src/gc/enabled/null.rs @@ -11,8 +11,8 @@ use cranelift_codegen::ir::{self, InstBuilder}; use cranelift_frontend::FunctionBuilder; use wasmtime_environ::VMSharedTypeIndex; use wasmtime_environ::{ - null::NullTypeLayouts, GcTypeLayouts, ModuleInternedTypeIndex, PtrSize, TypeIndex, VMGcKind, - WasmRefType, WasmResult, + GcTypeLayouts, ModuleInternedTypeIndex, PtrSize, TypeIndex, VMGcKind, WasmRefType, WasmResult, + null::NullTypeLayouts, }; #[derive(Default)] diff --git a/crates/cranelift/src/lib.rs b/crates/cranelift/src/lib.rs index 717c8008765d..fc90178519d5 100644 --- a/crates/cranelift/src/lib.rs +++ b/crates/cranelift/src/lib.rs @@ -8,11 +8,11 @@ #![warn(clippy::cast_possible_truncation, clippy::cast_sign_loss)] use cranelift_codegen::{ - binemit, + FinalizedMachReloc, FinalizedRelocTarget, MachTrap, binemit, cursor::FuncCursor, ir::{self, AbiParam, ArgumentPurpose, ExternalName, InstBuilder, Signature, TrapCode}, isa::{CallConv, TargetIsa}, - settings, FinalizedMachReloc, FinalizedRelocTarget, MachTrap, + settings, }; use cranelift_entity::PrimaryMap; diff --git a/crates/cranelift/src/obj.rs b/crates/cranelift/src/obj.rs index 2fe5b314f887..df6c26375292 100644 --- a/crates/cranelift/src/obj.rs +++ b/crates/cranelift/src/obj.rs @@ -15,12 +15,12 @@ use crate::{CompiledFunction, RelocationTarget}; use anyhow::Result; -use cranelift_codegen::binemit::Reloc; -use cranelift_codegen::isa::unwind::{systemv, UnwindInfo}; use cranelift_codegen::TextSectionBuilder; +use cranelift_codegen::binemit::Reloc; +use cranelift_codegen::isa::unwind::{UnwindInfo, systemv}; use cranelift_control::ControlPlane; -use gimli::write::{Address, EhFrame, EndianVec, FrameTable, Writer}; use gimli::RunTimeEndian; +use gimli::write::{Address, EhFrame, EndianVec, FrameTable, Writer}; use object::write::{Object, SectionId, StandardSegment, Symbol, SymbolId, SymbolSection}; use object::{Architecture, SectionFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope}; use std::collections::HashMap; @@ -206,15 +206,12 @@ impl<'a> ModuleTextBuilder<'a> { other => unimplemented!("unimplemented relocation kind {other:?}"), }; self.obj - .add_relocation( - self.text_section, - object::write::Relocation { - symbol, - flags, - offset: reloc_offset, - addend: r.addend, - }, - ) + .add_relocation(self.text_section, object::write::Relocation { + symbol, + flags, + offset: reloc_offset, + addend: r.addend, + }) .unwrap(); } diff --git a/crates/cranelift/src/translate/code_translator.rs b/crates/cranelift/src/translate/code_translator.rs index 6a687f41634a..adb7e8f02cc4 100644 --- a/crates/cranelift/src/translate/code_translator.rs +++ b/crates/cranelift/src/translate/code_translator.rs @@ -89,12 +89,12 @@ use cranelift_codegen::packed_option::ReservedValue; use cranelift_frontend::{FunctionBuilder, Variable}; use itertools::Itertools; use smallvec::SmallVec; -use std::collections::{hash_map, HashMap}; +use std::collections::{HashMap, hash_map}; use std::vec::Vec; use wasmparser::{FuncValidator, MemArg, Operator, WasmModuleResources}; use wasmtime_environ::{ - wasm_unsupported, DataIndex, ElemIndex, FuncIndex, GlobalIndex, MemoryIndex, Signed, - TableIndex, TypeConvert, TypeIndex, Unsigned, WasmRefType, WasmResult, + DataIndex, ElemIndex, FuncIndex, GlobalIndex, MemoryIndex, Signed, TableIndex, TypeConvert, + TypeIndex, Unsigned, WasmRefType, WasmResult, wasm_unsupported, }; /// Given a `Reachability`, unwrap the inner `T` or, when unreachable, set @@ -312,13 +312,10 @@ pub fn translate_operator( destination, state.peekn(params.len()), ); - ( - destination, - ElseData::NoElse { - branch_inst, - placeholder: destination, - }, - ) + (destination, ElseData::NoElse { + branch_inst, + placeholder: destination, + }) } else { // The `if` type signature is not valid without an `else` block, // so we eagerly allocate the `else` block here. @@ -3418,7 +3415,7 @@ fn translate_atomic_rmw( return Err(wasm_unsupported!( "atomic_rmw: unsupported access type {:?}", access_ty - )) + )); } }; let w_ty_ok = match widened_ty { @@ -3471,7 +3468,7 @@ fn translate_atomic_cas( return Err(wasm_unsupported!( "atomic_cas: unsupported access type {:?}", access_ty - )) + )); } }; let w_ty_ok = match widened_ty { @@ -3523,7 +3520,7 @@ fn translate_atomic_load( return Err(wasm_unsupported!( "atomic_load: unsupported access type {:?}", access_ty - )) + )); } }; let w_ty_ok = match widened_ty { @@ -3568,7 +3565,7 @@ fn translate_atomic_store( return Err(wasm_unsupported!( "atomic_store: unsupported access type {:?}", access_ty - )) + )); } }; let d_ty_ok = match data_ty { diff --git a/crates/cranelift/src/translate/code_translator/bounds_checks.rs b/crates/cranelift/src/translate/code_translator/bounds_checks.rs index b45699ca3415..5214d44bc784 100644 --- a/crates/cranelift/src/translate/code_translator/bounds_checks.rs +++ b/crates/cranelift/src/translate/code_translator/bounds_checks.rs @@ -22,14 +22,14 @@ use super::Reachability; use crate::func_environ::FuncEnvironment; use crate::translate::{HeapData, TargetEnvironment}; +use Reachability::*; use cranelift_codegen::{ cursor::{Cursor, FuncCursor}, - ir::{self, condcodes::IntCC, InstBuilder, RelSourceLoc}, + ir::{self, InstBuilder, RelSourceLoc, condcodes::IntCC}, ir::{Expr, Fact}, }; use cranelift_frontend::FunctionBuilder; use wasmtime_environ::{Unsigned, WasmResult}; -use Reachability::*; /// Helper used to emit bounds checks (as necessary) and compute the native /// address of a heap access. diff --git a/crates/cranelift/src/translate/func_translator.rs b/crates/cranelift/src/translate/func_translator.rs index d7c0739b367a..8009055b7520 100644 --- a/crates/cranelift/src/translate/func_translator.rs +++ b/crates/cranelift/src/translate/func_translator.rs @@ -5,10 +5,10 @@ //! WebAssembly module and the runtime environment. use crate::func_environ::FuncEnvironment; +use crate::translate::TargetEnvironment; use crate::translate::code_translator::{bitcast_wasm_returns, translate_operator}; use crate::translate::state::FuncTranslationState; use crate::translate::translation_utils::get_vmctx_value_label; -use crate::translate::TargetEnvironment; use cranelift_codegen::entity::EntityRef; use cranelift_codegen::ir::{self, Block, InstBuilder, ValueLabel}; use cranelift_codegen::timing; diff --git a/crates/cranelift/src/translate/state.rs b/crates/cranelift/src/translate/state.rs index 7420b03882db..8e320dc64bba 100644 --- a/crates/cranelift/src/translate/state.rs +++ b/crates/cranelift/src/translate/state.rs @@ -4,8 +4,8 @@ //! value and control stacks during the translation of a single function. use crate::func_environ::FuncEnvironment; -use crate::translate::environ::GlobalVariable; use crate::translate::Heap; +use crate::translate::environ::GlobalVariable; use cranelift_codegen::ir::{self, Block, Inst, Value}; use std::collections::hash_map::{Entry::Occupied, Entry::Vacant, HashMap}; use std::vec::Vec; diff --git a/crates/cranelift/src/translate/table.rs b/crates/cranelift/src/translate/table.rs index cd6ae8bfb97a..648694e56efc 100644 --- a/crates/cranelift/src/translate/table.rs +++ b/crates/cranelift/src/translate/table.rs @@ -1,6 +1,6 @@ use crate::func_environ::FuncEnvironment; use cranelift_codegen::cursor::FuncCursor; -use cranelift_codegen::ir::{self, condcodes::IntCC, immediates::Imm64, InstBuilder}; +use cranelift_codegen::ir::{self, InstBuilder, condcodes::IntCC, immediates::Imm64}; use cranelift_codegen::isa::TargetIsa; use cranelift_frontend::FunctionBuilder; diff --git a/crates/environ/examples/factc.rs b/crates/environ/examples/factc.rs index 2c692a926465..b03e19c297ce 100644 --- a/crates/environ/examples/factc.rs +++ b/crates/environ/examples/factc.rs @@ -1,4 +1,4 @@ -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use clap::Parser; use std::io::{IsTerminal, Write}; use std::path::PathBuf; diff --git a/crates/environ/fuzz/fuzz_targets/fact-valid-module.rs b/crates/environ/fuzz/fuzz_targets/fact-valid-module.rs index 2995aab756e1..a1c80cda71a2 100644 --- a/crates/environ/fuzz/fuzz_targets/fact-valid-module.rs +++ b/crates/environ/fuzz/fuzz_targets/fact-valid-module.rs @@ -10,7 +10,7 @@ #![no_main] use arbitrary::Unstructured; -use component_fuzz_util::{TestCase, Type, MAX_TYPE_DEPTH}; +use component_fuzz_util::{MAX_TYPE_DEPTH, TestCase, Type}; use libfuzzer_sys::fuzz_target; use wasmparser::component_types::ComponentAnyTypeId; use wasmparser::{Parser, Payload, Validator, WasmFeatures}; diff --git a/crates/environ/src/compile/address_map.rs b/crates/environ/src/compile/address_map.rs index 6bdaa0bd5af5..de04f4f1dcb7 100644 --- a/crates/environ/src/compile/address_map.rs +++ b/crates/environ/src/compile/address_map.rs @@ -1,8 +1,8 @@ //! Data structures to provide transformation of the source +use crate::InstructionAddressMap; use crate::obj::ELF_WASMTIME_ADDRMAP; use crate::prelude::*; -use crate::InstructionAddressMap; use object::write::{Object, StandardSegment}; use object::{LittleEndian, SectionKind, U32Bytes}; use std::ops::Range; diff --git a/crates/environ/src/compile/mod.rs b/crates/environ/src/compile/mod.rs index 5832ff9dfca1..cbf9d899ecb1 100644 --- a/crates/environ/src/compile/mod.rs +++ b/crates/environ/src/compile/mod.rs @@ -2,11 +2,11 @@ //! module. use crate::prelude::*; -use crate::{obj, Tunables}; use crate::{ BuiltinFunctionIndex, DefinedFuncIndex, FlagValue, FuncIndex, FunctionLoc, ObjectKind, PrimaryMap, StaticModuleIndex, TripleExt, WasmError, WasmFuncType, WasmFunctionInfo, }; +use crate::{Tunables, obj}; use anyhow::Result; use object::write::{Object, SymbolId}; use object::{Architecture, BinaryFormat, FileFlags}; diff --git a/crates/environ/src/compile/module_artifacts.rs b/crates/environ/src/compile/module_artifacts.rs index 9d992e25405c..4fc3a3792ae3 100644 --- a/crates/environ/src/compile/module_artifacts.rs +++ b/crates/environ/src/compile/module_artifacts.rs @@ -3,13 +3,13 @@ use crate::prelude::*; use crate::{ - obj, CompiledFunctionInfo, CompiledModuleInfo, DebugInfoData, DefinedFuncIndex, FunctionLoc, + CompiledFunctionInfo, CompiledModuleInfo, DebugInfoData, DefinedFuncIndex, FunctionLoc, FunctionName, MemoryInitialization, Metadata, ModuleInternedTypeIndex, ModuleTranslation, - PrimaryMap, Tunables, + PrimaryMap, Tunables, obj, }; -use anyhow::{bail, Result}; -use object::write::{Object, SectionId, StandardSegment, WritableBuffer}; +use anyhow::{Result, bail}; use object::SectionKind; +use object::write::{Object, SectionId, StandardSegment, WritableBuffer}; use std::ops::Range; /// Helper structure to create an ELF file as a compilation artifact. diff --git a/crates/environ/src/compile/module_environ.rs b/crates/environ/src/compile/module_environ.rs index 720ae1706248..b2ff5963f0d0 100644 --- a/crates/environ/src/compile/module_environ.rs +++ b/crates/environ/src/compile/module_environ.rs @@ -10,7 +10,7 @@ use crate::{ TableIndex, TableInitialValue, Tunables, TypeConvert, TypeIndex, Unsigned, WasmError, WasmHeapTopType, WasmHeapType, WasmResult, WasmValType, WasmparserTypeConverter, }; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use cranelift_entity::packed_option::ReservedValue; use std::borrow::Cow; use std::collections::HashMap; @@ -18,9 +18,9 @@ use std::mem; use std::path::PathBuf; use std::sync::Arc; use wasmparser::{ - types::Types, CustomSectionReader, DataKind, ElementItems, ElementKind, Encoding, ExternalKind, + CustomSectionReader, DataKind, ElementItems, ElementKind, Encoding, ExternalKind, FuncToValidate, FunctionBody, KnownCustom, NameSectionReader, Naming, Parser, Payload, TypeRef, - Validator, ValidatorResources, + Validator, ValidatorResources, types::Types, }; /// Object containing the standalone environment information. diff --git a/crates/environ/src/compile/module_types.rs b/crates/environ/src/compile/module_types.rs index 045786d436e1..b64db7deb50a 100644 --- a/crates/environ/src/compile/module_types.rs +++ b/crates/environ/src/compile/module_types.rs @@ -1,8 +1,7 @@ use crate::{ - wasm_unsupported, EngineOrModuleTypeIndex, EntityRef, ModuleInternedRecGroupIndex, - ModuleInternedTypeIndex, ModuleTypes, TypeConvert, TypeIndex, WasmArrayType, - WasmCompositeInnerType, WasmCompositeType, WasmFuncType, WasmHeapType, WasmResult, - WasmStructType, WasmSubType, + EngineOrModuleTypeIndex, EntityRef, ModuleInternedRecGroupIndex, ModuleInternedTypeIndex, + ModuleTypes, TypeConvert, TypeIndex, WasmArrayType, WasmCompositeInnerType, WasmCompositeType, + WasmFuncType, WasmHeapType, WasmResult, WasmStructType, WasmSubType, wasm_unsupported, }; use std::{borrow::Cow, collections::HashMap, ops::Index}; use wasmparser::{UnpackedIndex, Validator, ValidatorId}; @@ -264,16 +263,19 @@ impl ModuleTypesBuilder { assert_eq!(validator_types.id(), self.validator_id); let rec_group_id = validator_types.rec_group_id_of(id); - debug_assert!(validator_types - .rec_group_elements(rec_group_id) - .any(|e| e == id)); + debug_assert!( + validator_types + .rec_group_elements(rec_group_id) + .any(|e| e == id) + ); let interned_rec_group = self.intern_rec_group(validator_types, rec_group_id)?; let interned_type = self.wasmparser_to_wasmtime[&id]; - debug_assert!(self - .rec_group_elements(interned_rec_group) - .any(|e| e == interned_type)); + debug_assert!( + self.rec_group_elements(interned_rec_group) + .any(|e| e == interned_type) + ); Ok(interned_type) } diff --git a/crates/environ/src/compile/trap_encoding.rs b/crates/environ/src/compile/trap_encoding.rs index 73fa6994ccd4..3cd548aa380b 100644 --- a/crates/environ/src/compile/trap_encoding.rs +++ b/crates/environ/src/compile/trap_encoding.rs @@ -1,6 +1,6 @@ +use crate::TrapInformation; use crate::obj::ELF_WASMTIME_TRAPS; use crate::prelude::*; -use crate::TrapInformation; use object::write::{Object, StandardSegment}; use object::{LittleEndian, SectionKind, U32Bytes}; use std::ops::Range; diff --git a/crates/environ/src/component/artifacts.rs b/crates/environ/src/component/artifacts.rs index 7426a75e6de3..096ea839bea0 100644 --- a/crates/environ/src/component/artifacts.rs +++ b/crates/environ/src/component/artifacts.rs @@ -2,8 +2,8 @@ //! which are serialized with `bincode` into output ELF files. use crate::{ - component::{Component, ComponentTypes, TrampolineIndex, TypeComponentIndex}, CompiledModuleInfo, FunctionLoc, PrimaryMap, StaticModuleIndex, + component::{Component, ComponentTypes, TrampolineIndex, TypeComponentIndex}, }; use serde_derive::{Deserialize, Serialize}; diff --git a/crates/environ/src/component/compiler.rs b/crates/environ/src/component/compiler.rs index b4320ec407fc..aa5db2b066e5 100644 --- a/crates/environ/src/component/compiler.rs +++ b/crates/environ/src/component/compiler.rs @@ -1,6 +1,6 @@ +use crate::Tunables; use crate::component::{AllCallFunc, ComponentTranslation, ComponentTypesBuilder, TrampolineIndex}; use crate::prelude::*; -use crate::Tunables; use anyhow::Result; use std::any::Any; diff --git a/crates/environ/src/component/names.rs b/crates/environ/src/component/names.rs index e19cdd382f58..69174d9aa0c9 100644 --- a/crates/environ/src/component/names.rs +++ b/crates/environ/src/component/names.rs @@ -1,5 +1,5 @@ use crate::prelude::*; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use core::hash::Hash; use semver::Version; use serde_derive::{Deserialize, Serialize}; diff --git a/crates/environ/src/component/translate.rs b/crates/environ/src/component/translate.rs index 8568836278d2..64101cc7408a 100644 --- a/crates/environ/src/component/translate.rs +++ b/crates/environ/src/component/translate.rs @@ -1,13 +1,13 @@ +use crate::ScopeVec; use crate::component::*; use crate::prelude::*; -use crate::ScopeVec; use crate::{ EngineOrModuleTypeIndex, EntityIndex, ModuleEnvironment, ModuleInternedTypeIndex, ModuleTranslation, ModuleTypesBuilder, PrimaryMap, Tunables, TypeConvert, WasmHeapType, WasmResult, WasmValType, }; use anyhow::anyhow; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use indexmap::IndexMap; use std::collections::HashMap; use std::mem; diff --git a/crates/environ/src/component/translate/adapt.rs b/crates/environ/src/component/translate/adapt.rs index 8989e6fce1a1..3c0250ac67d3 100644 --- a/crates/environ/src/component/translate/adapt.rs +++ b/crates/environ/src/component/translate/adapt.rs @@ -115,9 +115,9 @@ //! time this may want to be revisited if too many adapter modules are being //! created. +use crate::EntityType; use crate::component::translate::*; use crate::fact; -use crate::EntityType; use std::collections::HashSet; /// Metadata information about a fused adapter. diff --git a/crates/environ/src/component/translate/inline.rs b/crates/environ/src/component/translate/inline.rs index 881cb7440f08..6f59df58565a 100644 --- a/crates/environ/src/component/translate/inline.rs +++ b/crates/environ/src/component/translate/inline.rs @@ -1054,7 +1054,9 @@ impl<'a> Inliner<'a> { // somewhat tricky and needs something like temporary scratch // space that isn't implemented. ComponentFuncDef::Import(_) => { - bail!("component export `{name}` is a reexport of an imported function which is not implemented") + bail!( + "component export `{name}` is a reexport of an imported function which is not implemented" + ) } }, diff --git a/crates/environ/src/component/types.rs b/crates/environ/src/component/types.rs index de3896c18f04..8697cd601e02 100644 --- a/crates/environ/src/component/types.rs +++ b/crates/environ/src/component/types.rs @@ -525,11 +525,7 @@ const fn align_to(a: u32, b: u32) -> u32 { } const fn max(a: u32, b: u32) -> u32 { - if a > b { - a - } else { - b - } + if a > b { a } else { b } } impl CanonicalAbiInfo { @@ -758,11 +754,7 @@ impl CanonicalAbiInfo { /// doesn't exceed the `max` specified. pub fn flat_count(&self, max: usize) -> Option { let flat = usize::from(self.flat_count?); - if flat > max { - None - } else { - Some(flat) - } + if flat > max { None } else { Some(flat) } } } @@ -817,7 +809,7 @@ impl VariantInfo { mod serde_discrim_size { use super::DiscriminantSize; - use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; + use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error}; pub fn serialize(disc: &DiscriminantSize, ser: S) -> Result where @@ -1008,11 +1000,7 @@ const fn add_flat(a: Option, b: Option) -> Option { }, _ => return None, }; - if sum > MAX { - None - } else { - Some(sum) - } + if sum > MAX { None } else { Some(sum) } } const fn max_flat(a: Option, b: Option) -> Option { diff --git a/crates/environ/src/component/types_builder.rs b/crates/environ/src/component/types_builder.rs index 4b71255a3cbd..6a8b63020b33 100644 --- a/crates/environ/src/component/types_builder.rs +++ b/crates/environ/src/component/types_builder.rs @@ -4,11 +4,12 @@ use crate::{ EngineOrModuleTypeIndex, EntityType, ModuleInternedTypeIndex, ModuleTypes, ModuleTypesBuilder, PrimaryMap, TypeConvert, WasmHeapType, WasmValType, }; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use cranelift_entity::EntityRef; use std::collections::HashMap; use std::hash::Hash; use std::ops::Index; +use wasmparser::Validator; use wasmparser::component_types::{ ComponentAnyTypeId, ComponentCoreModuleTypeId, ComponentDefinedType, ComponentDefinedTypeId, ComponentEntityType, ComponentFuncTypeId, ComponentInstanceTypeId, ComponentTypeId, @@ -16,7 +17,6 @@ use wasmparser::component_types::{ }; use wasmparser::names::KebabString; use wasmparser::types::TypesRef; -use wasmparser::Validator; use wasmtime_component_util::FlagsSize; mod resources; @@ -430,13 +430,10 @@ impl ComponentTypesBuilder { if case.refines.is_some() { bail!("refines is not supported at this time"); } - Ok(( - name.to_string(), - match &case.ty.as_ref() { - Some(ty) => Some(self.valtype(types, ty)?), - None => None, - }, - )) + Ok((name.to_string(), match &case.ty.as_ref() { + Some(ty) => Some(self.valtype(types, ty)?), + None => None, + })) }) .collect::>>()?; let (info, abi) = VariantInfo::new( diff --git a/crates/environ/src/component/vmcomponent_offsets.rs b/crates/environ/src/component/vmcomponent_offsets.rs index a46b855461da..9031581a546b 100644 --- a/crates/environ/src/component/vmcomponent_offsets.rs +++ b/crates/environ/src/component/vmcomponent_offsets.rs @@ -14,8 +14,8 @@ // resource_destructors: [*mut VMFuncRef; component.num_resources], // } -use crate::component::*; use crate::PtrSize; +use crate::component::*; /// Equivalent of `VMCONTEXT_MAGIC` except for components. /// diff --git a/crates/environ/src/fact.rs b/crates/environ/src/fact.rs index 4afdac971ff7..2984a4c92ff4 100644 --- a/crates/environ/src/fact.rs +++ b/crates/environ/src/fact.rs @@ -222,18 +222,15 @@ impl<'a> Module<'a> { // This will internally create the adapter as specified and append // anything necessary to `self.funcs`. - trampoline::compile( - self, - &AdapterData { - name: name.to_string(), - lift, - lower, - callee, - // FIXME(#4185) should be plumbed and handled as part of the new - // reentrance rules not yet implemented here. - called_as_export: true, - }, - ); + trampoline::compile(self, &AdapterData { + name: name.to_string(), + lift, + lower, + callee, + // FIXME(#4185) should be plumbed and handled as part of the new + // reentrance rules not yet implemented here. + called_as_export: true, + }); while let Some((result, helper)) = self.helper_worklist.pop() { trampoline::compile_helper(self, result, helper); @@ -573,11 +570,7 @@ impl Options { } fn ptr_size(&self) -> u8 { - if self.memory64 { - 8 - } else { - 4 - } + if self.memory64 { 8 } else { 4 } } fn flat_types<'a>( diff --git a/crates/environ/src/fact/signature.rs b/crates/environ/src/fact/signature.rs index 328ec085e359..c9d1f2fb1a61 100644 --- a/crates/environ/src/fact/signature.rs +++ b/crates/environ/src/fact/signature.rs @@ -107,10 +107,12 @@ impl ComponentTypesBuilder { // Only parameters need to be checked since results should never have // borrowed resources. - debug_assert!(!self[ty.results] - .types - .iter() - .any(|t| self.ty_contains_borrow_resource(t))); + debug_assert!( + !self[ty.results] + .types + .iter() + .any(|t| self.ty_contains_borrow_resource(t)) + ); self[ty.params] .types .iter() diff --git a/crates/environ/src/fact/trampoline.rs b/crates/environ/src/fact/trampoline.rs index 3a5c0f4ce78b..831af12f09bf 100644 --- a/crates/environ/src/fact/trampoline.rs +++ b/crates/environ/src/fact/trampoline.rs @@ -16,10 +16,10 @@ //! can be somewhat arbitrary, an intentional decision. use crate::component::{ - CanonicalAbiInfo, ComponentTypesBuilder, FixedEncoding as FE, FlatType, InterfaceType, - StringEncoding, Transcode, TypeEnumIndex, TypeFlagsIndex, TypeListIndex, TypeOptionIndex, - TypeRecordIndex, TypeResourceTableIndex, TypeResultIndex, TypeTupleIndex, TypeVariantIndex, - VariantInfo, FLAG_MAY_ENTER, FLAG_MAY_LEAVE, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, + CanonicalAbiInfo, ComponentTypesBuilder, FLAG_MAY_ENTER, FLAG_MAY_LEAVE, FixedEncoding as FE, + FlatType, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, StringEncoding, Transcode, + TypeEnumIndex, TypeFlagsIndex, TypeListIndex, TypeOptionIndex, TypeRecordIndex, + TypeResourceTableIndex, TypeResultIndex, TypeTupleIndex, TypeVariantIndex, VariantInfo, }; use crate::fact::signature::Signature; use crate::fact::transcode::Transcoder; diff --git a/crates/environ/src/fact/transcode.rs b/crates/environ/src/fact/transcode.rs index 14eddfe484b9..15e7b620ee1d 100644 --- a/crates/environ/src/fact/transcode.rs +++ b/crates/environ/src/fact/transcode.rs @@ -1,7 +1,7 @@ +use crate::MemoryIndex; use crate::component::Transcode; use crate::fact::core_types::CoreTypes; use crate::prelude::*; -use crate::MemoryIndex; use wasm_encoder::{EntityType, ValType}; #[derive(Copy, Clone, Hash, Eq, PartialEq)] diff --git a/crates/environ/src/hostcall.rs b/crates/environ/src/hostcall.rs index 38e2edc992a1..b31331ada2d4 100644 --- a/crates/environ/src/hostcall.rs +++ b/crates/environ/src/hostcall.rs @@ -1,6 +1,6 @@ +use crate::BuiltinFunctionIndex; #[cfg(feature = "component-model")] use crate::component::ComponentBuiltinFunctionIndex; -use crate::BuiltinFunctionIndex; /// Enumeration of all possible ways that wasm may execute code in the /// host. diff --git a/crates/environ/src/module.rs b/crates/environ/src/module.rs index 128678a75593..094b5cdc17d7 100644 --- a/crates/environ/src/module.rs +++ b/crates/environ/src/module.rs @@ -4,7 +4,7 @@ use crate::prelude::*; use crate::*; use alloc::collections::BTreeMap; use core::ops::Range; -use cranelift_entity::{packed_option::ReservedValue, EntityRef}; +use cranelift_entity::{EntityRef, packed_option::ReservedValue}; use serde_derive::{Deserialize, Serialize}; /// A WebAssembly linear memory initializer. diff --git a/crates/environ/src/module_types.rs b/crates/environ/src/module_types.rs index 6f498de03c50..6aa52f64a123 100644 --- a/crates/environ/src/module_types.rs +++ b/crates/environ/src/module_types.rs @@ -1,6 +1,6 @@ use crate::{ModuleInternedRecGroupIndex, ModuleInternedTypeIndex, PrimaryMap, WasmSubType}; use core::ops::{Index, Range}; -use cranelift_entity::{packed_option::PackedOption, SecondaryMap}; +use cranelift_entity::{SecondaryMap, packed_option::PackedOption}; use serde_derive::{Deserialize, Serialize}; /// All types used in a core wasm module. @@ -96,9 +96,11 @@ impl ModuleTypes { debug_assert!(!trampoline_ty.is_reserved_value()); debug_assert!(self.wasm_types[for_ty].is_func()); debug_assert!(self.trampoline_types[for_ty].is_none()); - debug_assert!(self.wasm_types[trampoline_ty] - .unwrap_func() - .is_trampoline_type()); + debug_assert!( + self.wasm_types[trampoline_ty] + .unwrap_func() + .is_trampoline_type() + ); self.trampoline_types[for_ty] = Some(trampoline_ty).into(); } diff --git a/crates/environ/src/tunables.rs b/crates/environ/src/tunables.rs index 090c948125ea..d82e8c6978df 100644 --- a/crates/environ/src/tunables.rs +++ b/crates/environ/src/tunables.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, bail, Result}; +use anyhow::{Result, anyhow, bail}; use core::fmt; use serde_derive::{Deserialize, Serialize}; use target_lexicon::{PointerWidth, Triple}; diff --git a/crates/environ/src/types.rs b/crates/environ/src/types.rs index ed6065291e52..bdf8fa91099e 100644 --- a/crates/environ/src/types.rs +++ b/crates/environ/src/types.rs @@ -1,4 +1,4 @@ -use crate::{wasm_unsupported, Tunables, WasmResult}; +use crate::{Tunables, WasmResult, wasm_unsupported}; use alloc::borrow::Cow; use alloc::boxed::Box; use core::{fmt, ops::Range}; @@ -1843,11 +1843,7 @@ impl Memory { pub fn static_heap_size(&self) -> Option { let min = self.minimum_byte_size().ok()?; let max = self.maximum_byte_size().ok()?; - if min == max { - Some(min) - } else { - None - } + if min == max { Some(min) } else { None } } /// Returs whether or not the base pointer of this memory is allowed to be diff --git a/crates/explorer/src/lib.rs b/crates/explorer/src/lib.rs index 11af007791a9..cf89c7c14f99 100644 --- a/crates/explorer/src/lib.rs +++ b/crates/explorer/src/lib.rs @@ -3,7 +3,7 @@ use capstone::arch::BuildsCapstone; use serde_derive::Serialize; use std::{ fs::File, - io::{read_to_string, Write}, + io::{Write, read_to_string}, path::Path, str::FromStr, }; diff --git a/crates/fuzzing/src/generators/config.rs b/crates/fuzzing/src/generators/config.rs index 437c7c235ba0..121f4033584c 100644 --- a/crates/fuzzing/src/generators/config.rs +++ b/crates/fuzzing/src/generators/config.rs @@ -10,7 +10,7 @@ use arbitrary::{Arbitrary, Unstructured}; use std::sync::Arc; use std::time::Duration; use wasmtime::{Engine, Module, MpkEnabled, Store}; -use wasmtime_wast_util::{limits, WastConfig, WastTest}; +use wasmtime_wast_util::{WastConfig, WastTest, limits}; /// Configuration for `wasmtime::Config` and generated modules for a session of /// fuzzing. diff --git a/crates/fuzzing/src/generators/stacks.rs b/crates/fuzzing/src/generators/stacks.rs index e7a3fcb31f34..752560d67643 100644 --- a/crates/fuzzing/src/generators/stacks.rs +++ b/crates/fuzzing/src/generators/stacks.rs @@ -128,10 +128,10 @@ impl Stacks { .function(vec![wasm_encoder::ValType::I32], vec![]); let get_stack_type = types.len(); - types.ty().function( - vec![], - vec![wasm_encoder::ValType::I32, wasm_encoder::ValType::I32], - ); + types.ty().function(vec![], vec![ + wasm_encoder::ValType::I32, + wasm_encoder::ValType::I32, + ]); let call_func_type = types.len(); types @@ -143,10 +143,10 @@ impl Stacks { let func_types_start = types.len(); for func in self.funcs.iter() { - types.ty().function( - vec![ValType::I32; func.params], - vec![ValType::I32; func.results], - ); + types.ty().function(vec![ValType::I32; func.params], vec![ + ValType::I32; + func.results + ]); } section(&mut module, types); diff --git a/crates/fuzzing/src/generators/table_ops.rs b/crates/fuzzing/src/generators/table_ops.rs index 15012dd948b2..76ed9aeb3c45 100644 --- a/crates/fuzzing/src/generators/table_ops.rs +++ b/crates/fuzzing/src/generators/table_ops.rs @@ -68,10 +68,11 @@ impl TableOps { ); // 3: `make_refs` - types.ty().function( - vec![], - vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF], - ); + types.ty().function(vec![], vec![ + ValType::EXTERNREF, + ValType::EXTERNREF, + ValType::EXTERNREF, + ]); // Import the GC function. let mut imports = ImportSection::new(); diff --git a/crates/fuzzing/src/oracles.rs b/crates/fuzzing/src/oracles.rs index 3592aebd3b79..c9196d5b5408 100644 --- a/crates/fuzzing/src/oracles.rs +++ b/crates/fuzzing/src/oracles.rs @@ -709,11 +709,11 @@ pub fn table_ops( // test case. const MAX_GCS: usize = 5; - let func_ty = FuncType::new( - store.engine(), - vec![], - vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF], - ); + let func_ty = FuncType::new(store.engine(), vec![], vec![ + ValType::EXTERNREF, + ValType::EXTERNREF, + ValType::EXTERNREF, + ]); let func = Func::new(&mut store, func_ty, { let num_dropped = num_dropped.clone(); let expected_drops = expected_drops.clone(); @@ -782,11 +782,11 @@ pub fn table_ops( }) .unwrap(); - let func_ty = FuncType::new( - store.engine(), - vec![], - vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF], - ); + let func_ty = FuncType::new(store.engine(), vec![], vec![ + ValType::EXTERNREF, + ValType::EXTERNREF, + ValType::EXTERNREF, + ]); let func = Func::new(&mut store, func_ty, { let num_dropped = num_dropped.clone(); let expected_drops = expected_drops.clone(); @@ -921,7 +921,7 @@ impl Drop for HelperThread { /// arbitrary types and values. pub fn dynamic_component_api_target(input: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { use crate::generators::component_types; - use component_fuzz_util::{TestCase, Type, EXPORT_FUNCTION, IMPORT_FUNCTION, MAX_TYPE_DEPTH}; + use component_fuzz_util::{EXPORT_FUNCTION, IMPORT_FUNCTION, MAX_TYPE_DEPTH, TestCase, Type}; use component_test_util::FuncExt; use wasmtime::component::{Component, Linker, Val}; diff --git a/crates/fuzzing/src/oracles/diff_spec.rs b/crates/fuzzing/src/oracles/diff_spec.rs index 23a5025555b9..7a54265b9741 100644 --- a/crates/fuzzing/src/oracles/diff_spec.rs +++ b/crates/fuzzing/src/oracles/diff_spec.rs @@ -3,7 +3,7 @@ use crate::generators::{Config, DiffValue, DiffValueType}; use crate::oracles::engine::{DiffEngine, DiffInstance}; -use anyhow::{anyhow, Error, Result}; +use anyhow::{Error, Result, anyhow}; use wasm_spec_interpreter::SpecValue; use wasmtime::Trap; @@ -77,7 +77,7 @@ impl DiffInstance for SpecInstance { } fn get_global(&mut self, name: &str, _ty: DiffValueType) -> Option { - use wasm_spec_interpreter::{export, SpecExport::Global}; + use wasm_spec_interpreter::{SpecExport::Global, export}; if let Ok(Global(g)) = export(&self.instance, name) { Some(g.into()) } else { @@ -86,7 +86,7 @@ impl DiffInstance for SpecInstance { } fn get_memory(&mut self, name: &str, _shared: bool) -> Option> { - use wasm_spec_interpreter::{export, SpecExport::Memory}; + use wasm_spec_interpreter::{SpecExport::Memory, export}; if let Ok(Memory(m)) = export(&self.instance, name) { Some(m) } else { diff --git a/crates/fuzzing/src/oracles/diff_v8.rs b/crates/fuzzing/src/oracles/diff_v8.rs index fee5fb555b6e..fa90d45a8466 100644 --- a/crates/fuzzing/src/oracles/diff_v8.rs +++ b/crates/fuzzing/src/oracles/diff_v8.rs @@ -1,6 +1,6 @@ use crate::generators::{Config, DiffValue, DiffValueType}; use crate::oracles::engine::{DiffEngine, DiffInstance}; -use anyhow::{bail, Error, Result}; +use anyhow::{Error, Result, bail}; use std::cell::RefCell; use std::rc::Rc; use std::sync::Once; @@ -92,7 +92,7 @@ impl DiffEngine for V8Engine { }; match wasmtime { Trap::MemoryOutOfBounds => { - return verify_v8(&["memory access out of bounds", "is out of bounds"]) + return verify_v8(&["memory access out of bounds", "is out of bounds"]); } Trap::UnreachableCodeReached => { return verify_v8(&[ @@ -110,7 +110,7 @@ impl DiffEngine for V8Engine { ]); } Trap::IntegerDivisionByZero => { - return verify_v8(&["divide by zero", "remainder by zero"]) + return verify_v8(&["divide by zero", "remainder by zero"]); } Trap::StackOverflow => { return verify_v8(&[ @@ -130,14 +130,14 @@ impl DiffEngine for V8Engine { "table initializer is out of bounds", "table index is out of bounds", "element segment out of bounds", - ]) + ]); } Trap::BadSignature => return verify_v8(&["function signature mismatch"]), Trap::IntegerOverflow | Trap::BadConversionToInteger => { return verify_v8(&[ "float unrepresentable in integer range", "divide result unrepresentable", - ]) + ]); } other => log::debug!("unknown code {:?}", other), } diff --git a/crates/fuzzing/src/oracles/diff_wasmtime.rs b/crates/fuzzing/src/oracles/diff_wasmtime.rs index 51293e6da09a..3be6e726a043 100644 --- a/crates/fuzzing/src/oracles/diff_wasmtime.rs +++ b/crates/fuzzing/src/oracles/diff_wasmtime.rs @@ -3,7 +3,7 @@ use crate::generators::{self, CompilerStrategy, DiffValue, DiffValueType, WasmtimeConfig}; use crate::oracles::dummy; use crate::oracles::engine::DiffInstance; -use crate::oracles::{compile_module, engine::DiffEngine, StoreLimits}; +use crate::oracles::{StoreLimits, compile_module, engine::DiffEngine}; use crate::single_module_fuzzer::KnownValid; use anyhow::{Context, Error, Result}; use arbitrary::Unstructured; diff --git a/crates/fuzzing/src/oracles/engine.rs b/crates/fuzzing/src/oracles/engine.rs index 887f8382b36c..09fc1c132ce3 100644 --- a/crates/fuzzing/src/oracles/engine.rs +++ b/crates/fuzzing/src/oracles/engine.rs @@ -209,11 +209,9 @@ pub fn smoke_test_engine( .unwrap(); let mut instance = engine.instantiate(&wasm).unwrap(); let results = instance - .evaluate( - "add", - &[DiffValue::I32(1), DiffValue::I32(2)], - &[DiffValueType::I32], - ) + .evaluate("add", &[DiffValue::I32(1), DiffValue::I32(2)], &[ + DiffValueType::I32, + ]) .unwrap(); assert_eq!(results, Some(vec![DiffValue::I32(3)])); diff --git a/crates/fuzzing/wasm-spec-interpreter/src/with_library.rs b/crates/fuzzing/wasm-spec-interpreter/src/with_library.rs index 05bd22d9fd4b..a0161f3b7535 100644 --- a/crates/fuzzing/wasm-spec-interpreter/src/with_library.rs +++ b/crates/fuzzing/wasm-spec-interpreter/src/with_library.rs @@ -107,8 +107,8 @@ pub fn export(instance: &SpecInstance, name: &str) -> Result mod ocaml_bindings { use super::*; use ocaml_interop::{ - impl_conv_ocaml_variant, ocaml, FromOCaml, OCaml, OCamlBytes, OCamlInt32, OCamlInt64, - OCamlList, + FromOCaml, OCaml, OCamlBytes, OCamlInt32, OCamlInt64, OCamlList, impl_conv_ocaml_variant, + ocaml, }; // Using this macro converts the enum both ways: Rust to OCaml and OCaml to @@ -268,12 +268,9 @@ mod tests { ])]); let results = interpret(&instance, "simd_not", parameters).unwrap(); - assert_eq!( - results, - vec![SpecValue::V128(vec![ - 255, 0, 255, 255, 0, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255 - ])] - ); + assert_eq!(results, vec![SpecValue::V128(vec![ + 255, 0, 255, 255, 0, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255 + ])]); } #[test] @@ -285,12 +282,9 @@ mod tests { ])]); let results = interpret_legacy(&module, parameters).unwrap(); - assert_eq!( - results, - vec![SpecValue::V128(vec![ - 255, 0, 255, 255, 0, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255 - ])] - ); + assert_eq!(results, vec![SpecValue::V128(vec![ + 255, 0, 255, 255, 0, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255 + ])]); } // See issue https://github.com/bytecodealliance/wasmtime/issues/4671. diff --git a/crates/jit-icache-coherence/src/libc.rs b/crates/jit-icache-coherence/src/libc.rs index 0e73ee54b8fe..1487a813fcaf 100644 --- a/crates/jit-icache-coherence/src/libc.rs +++ b/crates/jit-icache-coherence/src/libc.rs @@ -16,7 +16,7 @@ mod details { extern crate std; use super::*; - use libc::{syscall, EINVAL, EPERM}; + use libc::{EINVAL, EPERM, syscall}; use std::io::Error; const MEMBARRIER_CMD_GLOBAL: libc::c_int = 1; diff --git a/crates/misc/component-fuzz-util/src/lib.rs b/crates/misc/component-fuzz-util/src/lib.rs index 7e406bd3548b..06a1df4940e5 100644 --- a/crates/misc/component-fuzz-util/src/lib.rs +++ b/crates/misc/component-fuzz-util/src/lib.rs @@ -8,7 +8,7 @@ use arbitrary::{Arbitrary, Unstructured}; use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote, ToTokens}; +use quote::{ToTokens, format_ident, quote}; use std::borrow::Cow; use std::fmt::{self, Debug, Write}; use std::iter; diff --git a/crates/misc/component-macro-test/src/lib.rs b/crates/misc/component-macro-test/src/lib.rs index 26fc26546507..b66b8a6f7a4b 100644 --- a/crates/misc/component-macro-test/src/lib.rs +++ b/crates/misc/component-macro-test/src/lib.rs @@ -1,7 +1,7 @@ use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; -use syn::{parse_macro_input, Error, Result, Token}; +use syn::{Error, Result, Token, parse_macro_input}; #[proc_macro_attribute] pub fn add_variants( diff --git a/crates/test-macros/src/lib.rs b/crates/test-macros/src/lib.rs index 5a9c8c89a12c..793a93af41be 100644 --- a/crates/test-macros/src/lib.rs +++ b/crates/test-macros/src/lib.rs @@ -29,12 +29,12 @@ //! If the wasm feature is not supported by any of the compiler strategies, no //! tests will be generated for such strategy. use proc_macro::TokenStream; -use quote::{quote, ToTokens, TokenStreamExt}; +use quote::{ToTokens, TokenStreamExt, quote}; use syn::{ - braced, + Attribute, Ident, Result, ReturnType, Signature, Visibility, braced, meta::ParseNestedMeta, parse::{Parse, ParseStream}, - parse_macro_input, token, Attribute, Ident, Result, ReturnType, Signature, Visibility, + parse_macro_input, token, }; use wasmtime_wast_util::Compiler; diff --git a/crates/test-programs/artifacts/build.rs b/crates/test-programs/artifacts/build.rs index f5966a67ea5e..92d1afe7e4d1 100644 --- a/crates/test-programs/artifacts/build.rs +++ b/crates/test-programs/artifacts/build.rs @@ -14,16 +14,14 @@ fn build_and_generate_tests() { let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); let reactor_adapter = build_adapter(&out_dir, "reactor", &[]); - let command_adapter = build_adapter( - &out_dir, - "command", - &["--no-default-features", "--features=command"], - ); - let proxy_adapter = build_adapter( - &out_dir, - "proxy", - &["--no-default-features", "--features=proxy"], - ); + let command_adapter = build_adapter(&out_dir, "command", &[ + "--no-default-features", + "--features=command", + ]); + let proxy_adapter = build_adapter(&out_dir, "proxy", &[ + "--no-default-features", + "--features=proxy", + ]); println!("cargo:rerun-if-changed=../src"); diff --git a/crates/test-programs/src/bin/api_proxy_streaming.rs b/crates/test-programs/src/bin/api_proxy_streaming.rs index 5c8ca7ca1b2e..42a4ef89f461 100644 --- a/crates/test-programs/src/bin/api_proxy_streaming.rs +++ b/crates/test-programs/src/bin/api_proxy_streaming.rs @@ -1,5 +1,5 @@ -use anyhow::{anyhow, bail, Result}; -use futures::{future, stream, Future, SinkExt, StreamExt, TryStreamExt}; +use anyhow::{Result, anyhow, bail}; +use futures::{Future, SinkExt, StreamExt, TryStreamExt, future, stream}; use test_programs::wasi::http::types::{ Fields, IncomingRequest, IncomingResponse, Method, OutgoingBody, OutgoingRequest, OutgoingResponse, ResponseOutparam, Scheme, @@ -304,8 +304,8 @@ async fn hash(url: &Url) -> Result { fn main() {} mod executor { - use anyhow::{anyhow, Error, Result}; - use futures::{future, sink, stream, Sink, Stream}; + use anyhow::{Error, Result, anyhow}; + use futures::{Sink, Stream, future, sink, stream}; use std::{ cell::RefCell, future::Future, diff --git a/crates/test-programs/src/bin/api_reactor.rs b/crates/test-programs/src/bin/api_reactor.rs index f232743a80db..360c96fab61b 100644 --- a/crates/test-programs/src/bin/api_reactor.rs +++ b/crates/test-programs/src/bin/api_reactor.rs @@ -1,8 +1,3 @@ -#![expect( - unsafe_attr_outside_unsafe, - reason = "needs fixes in upstream wit-bindgen to satisfy this lint" -)] - use std::sync::{Mutex, MutexGuard}; wit_bindgen::generate!({ diff --git a/crates/test-programs/src/bin/api_read_only.rs b/crates/test-programs/src/bin/api_read_only.rs index d186341d3b84..89c7692f15d4 100644 --- a/crates/test-programs/src/bin/api_read_only.rs +++ b/crates/test-programs/src/bin/api_read_only.rs @@ -19,9 +19,10 @@ fn main() -> Result<(), Box> { assert_eq!("while in thought", &io::read_to_string(&mut file)?); - assert!(file - .write_all(b"Did gyre and gimble in the wabe;\n") - .is_err()); + assert!( + file.write_all(b"Did gyre and gimble in the wabe;\n") + .is_err() + ); } assert!(OpenOptions::new().append(true).open("bar.txt").is_err()); diff --git a/crates/test-programs/src/bin/cli_args.rs b/crates/test-programs/src/bin/cli_args.rs index e152e452ee3f..07596e2bf88a 100644 --- a/crates/test-programs/src/bin/cli_args.rs +++ b/crates/test-programs/src/bin/cli_args.rs @@ -1,7 +1,10 @@ fn main() { let args = std::env::args().skip(1).collect::>(); - assert_eq!( - args, - ["hello", "this", "", "is an argument", "with 🚩 emoji"] - ); + assert_eq!(args, [ + "hello", + "this", + "", + "is an argument", + "with 🚩 emoji" + ]); } diff --git a/crates/test-programs/src/bin/cli_stdin_empty.rs b/crates/test-programs/src/bin/cli_stdin_empty.rs index c5df2f09036e..6da30660bb7f 100644 --- a/crates/test-programs/src/bin/cli_stdin_empty.rs +++ b/crates/test-programs/src/bin/cli_stdin_empty.rs @@ -4,13 +4,10 @@ fn main() { let mut buffer = [0_u8; 0]; unsafe { - wasi::fd_read( - STDIN_FD, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: 0, - }], - ) + wasi::fd_read(STDIN_FD, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: 0, + }]) .expect("empty read should succeed"); } } diff --git a/crates/test-programs/src/bin/http_outbound_request_missing_path_and_query.rs b/crates/test-programs/src/bin/http_outbound_request_missing_path_and_query.rs index 4c278ade1452..03de40fbc4fa 100644 --- a/crates/test-programs/src/bin/http_outbound_request_missing_path_and_query.rs +++ b/crates/test-programs/src/bin/http_outbound_request_missing_path_and_query.rs @@ -1,4 +1,4 @@ -use test_programs::wasi::http::outgoing_handler::{handle, OutgoingRequest}; +use test_programs::wasi::http::outgoing_handler::{OutgoingRequest, handle}; use test_programs::wasi::http::types::{Fields, Method, Scheme}; fn main() { diff --git a/crates/test-programs/src/bin/http_outbound_request_response_build.rs b/crates/test-programs/src/bin/http_outbound_request_response_build.rs index 59664ccde309..0c4b82badad2 100644 --- a/crates/test-programs/src/bin/http_outbound_request_response_build.rs +++ b/crates/test-programs/src/bin/http_outbound_request_response_build.rs @@ -43,17 +43,19 @@ fn main() { { let req = http_types::OutgoingRequest::new(http_types::Fields::new()); - assert!(req - .set_method(&http_types::Method::Other("invalid method".to_string())) - .is_err()); + assert!( + req.set_method(&http_types::Method::Other("invalid method".to_string())) + .is_err() + ); assert!(req.set_authority(Some("bad-port:99999")).is_err()); assert!(req.set_authority(Some("bad-\nhost")).is_err()); assert!(req.set_authority(Some("too-many-ports:80:80:80")).is_err()); - assert!(req - .set_scheme(Some(&http_types::Scheme::Other("bad\nscheme".to_string()))) - .is_err()); + assert!( + req.set_scheme(Some(&http_types::Scheme::Other("bad\nscheme".to_string()))) + .is_err() + ); assert!(req.set_path_with_query(Some("/bad\npath")).is_err()); } diff --git a/crates/test-programs/src/bin/keyvalue_main.rs b/crates/test-programs/src/bin/keyvalue_main.rs index 0a5dfe5bfc05..83395bcd9fbe 100644 --- a/crates/test-programs/src/bin/keyvalue_main.rs +++ b/crates/test-programs/src/bin/keyvalue_main.rs @@ -18,27 +18,22 @@ fn main() { bucket.delete("hello").unwrap(); assert_eq!(bucket.exists("hello").unwrap(), false); - batch::set_many( - &bucket, - &[ - ("a1".to_string(), "v1".as_bytes().to_vec()), - ("b1".to_string(), "v1".as_bytes().to_vec()), - ("c1".to_string(), "v1".as_bytes().to_vec()), - ], - ) + batch::set_many(&bucket, &[ + ("a1".to_string(), "v1".as_bytes().to_vec()), + ("b1".to_string(), "v1".as_bytes().to_vec()), + ("c1".to_string(), "v1".as_bytes().to_vec()), + ]) .unwrap(); batch::delete_many(&bucket, &["a1".to_string(), "c1".to_string()]).unwrap(); - let values = batch::get_many( - &bucket, - &["a1".to_string(), "b1".to_string(), "c1".to_string()], - ) + let values = batch::get_many(&bucket, &[ + "a1".to_string(), + "b1".to_string(), + "c1".to_string(), + ]) .unwrap(); - assert_eq!( - values, - vec![ - None, - Some(("b1".to_string(), "v1".as_bytes().to_vec())), - None - ] - ); + assert_eq!(values, vec![ + None, + Some(("b1".to_string(), "v1".as_bytes().to_vec())), + None + ]); } diff --git a/crates/test-programs/src/bin/preview1_fd_filestat_set.rs b/crates/test-programs/src/bin/preview1_fd_filestat_set.rs index a4fe2e2a30f4..5980b5b2ea7c 100644 --- a/crates/test-programs/src/bin/preview1_fd_filestat_set.rs +++ b/crates/test-programs/src/bin/preview1_fd_filestat_set.rs @@ -1,6 +1,6 @@ use std::{env, process, time::Duration}; use test_programs::preview1::{ - assert_errno, assert_fs_time_eq, open_scratch_directory, TestConfig, + TestConfig, assert_errno, assert_fs_time_eq, open_scratch_directory, }; unsafe fn test_fd_filestat_set_size_rw(dir_fd: wasi::Fd) { diff --git a/crates/test-programs/src/bin/preview1_fd_flags_set.rs b/crates/test-programs/src/bin/preview1_fd_flags_set.rs index 5c0be39b31f5..0e24c049f097 100644 --- a/crates/test-programs/src/bin/preview1_fd_flags_set.rs +++ b/crates/test-programs/src/bin/preview1_fd_flags_set.rs @@ -18,13 +18,10 @@ unsafe fn test_fd_fdstat_set_flags(dir_fd: wasi::Fd) { // Write some data and then verify the written data assert_eq!( - wasi::fd_write( - file_fd, - &[wasi::Ciovec { - buf: data.as_ptr(), - buf_len: data.len(), - }], - ) + wasi::fd_write(file_fd, &[wasi::Ciovec { + buf: data.as_ptr(), + buf_len: data.len(), + }],) .expect("writing to a file"), data.len(), "should write {} bytes", @@ -36,13 +33,10 @@ unsafe fn test_fd_fdstat_set_flags(dir_fd: wasi::Fd) { let buffer = &mut [0u8; 100]; assert_eq!( - wasi::fd_read( - file_fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: buffer.len(), - }] - ) + wasi::fd_read(file_fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: buffer.len(), + }]) .expect("reading file"), buffer.len(), "should read {} bytes", @@ -57,13 +51,10 @@ unsafe fn test_fd_fdstat_set_flags(dir_fd: wasi::Fd) { wasi::fd_seek(file_fd, 0, wasi::WHENCE_SET).expect("seeking file"); assert_eq!( - wasi::fd_write( - file_fd, - &[wasi::Ciovec { - buf: data.as_ptr(), - buf_len: data.len(), - }], - ) + wasi::fd_write(file_fd, &[wasi::Ciovec { + buf: data.as_ptr(), + buf_len: data.len(), + }],) .expect("writing to a file"), data.len(), "should write {} bytes", @@ -73,13 +64,10 @@ unsafe fn test_fd_fdstat_set_flags(dir_fd: wasi::Fd) { wasi::fd_seek(file_fd, 100, wasi::WHENCE_SET).expect("seeking file"); assert_eq!( - wasi::fd_read( - file_fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: buffer.len(), - }] - ) + wasi::fd_read(file_fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: buffer.len(), + }]) .expect("reading file"), buffer.len(), "should read {} bytes", @@ -96,13 +84,10 @@ unsafe fn test_fd_fdstat_set_flags(dir_fd: wasi::Fd) { let data = &[2u8; 100]; assert_eq!( - wasi::fd_write( - file_fd, - &[wasi::Ciovec { - buf: data.as_ptr(), - buf_len: data.len(), - }], - ) + wasi::fd_write(file_fd, &[wasi::Ciovec { + buf: data.as_ptr(), + buf_len: data.len(), + }],) .expect("writing to a file"), data.len(), "should write {} bytes", @@ -112,13 +97,10 @@ unsafe fn test_fd_fdstat_set_flags(dir_fd: wasi::Fd) { wasi::fd_seek(file_fd, 0, wasi::WHENCE_SET).expect("seeking file"); assert_eq!( - wasi::fd_read( - file_fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: buffer.len(), - }] - ) + wasi::fd_read(file_fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: buffer.len(), + }]) .expect("reading file"), buffer.len(), "should read {} bytes", diff --git a/crates/test-programs/src/bin/preview1_file_truncation.rs b/crates/test-programs/src/bin/preview1_file_truncation.rs index 42b1698bddfa..48c92d744564 100644 --- a/crates/test-programs/src/bin/preview1_file_truncation.rs +++ b/crates/test-programs/src/bin/preview1_file_truncation.rs @@ -18,13 +18,10 @@ unsafe fn test_file_truncation(dir_fd: wasi::Fd) { // Write to the file let content = b"this content will be truncated!"; - let nwritten = wasi::fd_write( - file_fd, - &[wasi::Ciovec { - buf: content.as_ptr() as *const _, - buf_len: content.len(), - }], - ) + let nwritten = wasi::fd_write(file_fd, &[wasi::Ciovec { + buf: content.as_ptr() as *const _, + buf_len: content.len(), + }]) .expect("writing file content"); assert_eq!(nwritten, content.len(), "nwritten bytes check"); @@ -44,13 +41,10 @@ unsafe fn test_file_truncation(dir_fd: wasi::Fd) { // Read the file's contents let buffer = &mut [0u8; 100]; - let nread = wasi::fd_read( - file_fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: buffer.len(), - }], - ) + let nread = wasi::fd_read(file_fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: buffer.len(), + }]) .expect("reading file content"); // The file should be empty due to truncation diff --git a/crates/test-programs/src/bin/preview1_file_write.rs b/crates/test-programs/src/bin/preview1_file_write.rs index 7047fcf25dc2..ed7c531e84be 100644 --- a/crates/test-programs/src/bin/preview1_file_write.rs +++ b/crates/test-programs/src/bin/preview1_file_write.rs @@ -23,13 +23,10 @@ unsafe fn test_file_long_write(dir_fd: wasi::Fd, filename: &str) { } // Write to the file - let nwritten = wasi::fd_write( - file_fd, - &[wasi::Ciovec { - buf: content.as_slice().as_ptr() as *const _, - buf_len: content.len(), - }], - ) + let nwritten = wasi::fd_write(file_fd, &[wasi::Ciovec { + buf: content.as_slice().as_ptr() as *const _, + buf_len: content.len(), + }]) .expect("writing file content"); assert_eq!(nwritten, content.len(), "nwritten bytes check"); @@ -47,13 +44,10 @@ unsafe fn test_file_long_write(dir_fd: wasi::Fd, filename: &str) { // Read the file's contents let buffer = &mut [0u8; 100]; - let nread = wasi::fd_read( - file_fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: buffer.len(), - }], - ) + let nread = wasi::fd_read(file_fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: buffer.len(), + }]) .expect("reading first chunk file content"); assert_eq!(nread, buffer.len(), "read first chunk"); @@ -67,13 +61,10 @@ unsafe fn test_file_long_write(dir_fd: wasi::Fd, filename: &str) { wasi::fd_seek(file_fd, end_cursor as i64, wasi::WHENCE_SET) .expect("seeking to end of file minus buffer size"); - let nread = wasi::fd_read( - file_fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: buffer.len(), - }], - ) + let nread = wasi::fd_read(file_fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: buffer.len(), + }]) .expect("reading end chunk of file content"); assert_eq!(nread, buffer.len(), "read end chunk len"); @@ -96,13 +87,10 @@ unsafe fn test_file_long_write(dir_fd: wasi::Fd, filename: &str) { wasi::fd_close(file_fd).expect("closing the file"); let file_fd = wasi::path_open(dir_fd, 0, filename, 0, wasi::RIGHTS_FD_READ, 0, 0) .expect("opening a file for writing"); - let res = wasi::fd_write( - file_fd, - &[wasi::Ciovec { - buf: 3 as *const u8, - buf_len: 0, - }], - ); + let res = wasi::fd_write(file_fd, &[wasi::Ciovec { + buf: 3 as *const u8, + buf_len: 0, + }]); assert!( res == Err(wasi::ERRNO_BADF) || res == Err(wasi::ERRNO_PERM), "bad result {res:?}" diff --git a/crates/test-programs/src/bin/preview1_path_filestat.rs b/crates/test-programs/src/bin/preview1_path_filestat.rs index 6b25fc2e7e28..f7164893aa05 100644 --- a/crates/test-programs/src/bin/preview1_path_filestat.rs +++ b/crates/test-programs/src/bin/preview1_path_filestat.rs @@ -1,6 +1,6 @@ use std::{env, process, time::Duration}; use test_programs::preview1::{ - assert_errno, assert_fs_time_eq, open_scratch_directory, TestConfig, + TestConfig, assert_errno, assert_fs_time_eq, open_scratch_directory, }; unsafe fn test_path_filestat(dir_fd: wasi::Fd) { diff --git a/crates/test-programs/src/bin/preview1_poll_oneoff_stdio.rs b/crates/test-programs/src/bin/preview1_poll_oneoff_stdio.rs index 6d0616dcb101..99b2a12b7c1b 100644 --- a/crates/test-programs/src/bin/preview1_poll_oneoff_stdio.rs +++ b/crates/test-programs/src/bin/preview1_poll_oneoff_stdio.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; use std::mem::MaybeUninit; -use test_programs::preview1::{assert_errno, STDERR_FD, STDIN_FD, STDOUT_FD}; +use test_programs::preview1::{STDERR_FD, STDIN_FD, STDOUT_FD, assert_errno}; const TIMEOUT: u64 = 200_000_000u64; // 200 milliseconds, required to satisfy slow execution in CI const CLOCK_ID: wasi::Userdata = 0x0123_45678; diff --git a/crates/test-programs/src/bin/preview1_symlink_filestat.rs b/crates/test-programs/src/bin/preview1_symlink_filestat.rs index 57ec517d969c..0e320e00ebd0 100644 --- a/crates/test-programs/src/bin/preview1_symlink_filestat.rs +++ b/crates/test-programs/src/bin/preview1_symlink_filestat.rs @@ -1,5 +1,5 @@ use std::{env, process, time::Duration}; -use test_programs::preview1::{assert_fs_time_eq, open_scratch_directory, TestConfig}; +use test_programs::preview1::{TestConfig, assert_fs_time_eq, open_scratch_directory}; unsafe fn test_path_filestat(dir_fd: wasi::Fd) { let cfg = TestConfig::from_env(); diff --git a/crates/test-programs/src/bin/preview2_adapter_badfd.rs b/crates/test-programs/src/bin/preview2_adapter_badfd.rs index 9887c368ce04..92086ee4231d 100644 --- a/crates/test-programs/src/bin/preview2_adapter_badfd.rs +++ b/crates/test-programs/src/bin/preview2_adapter_badfd.rs @@ -20,24 +20,18 @@ fn main() { let mut buffer = [0_u8; 1]; assert_eq!( - wasi::fd_read( - fd, - &[wasi::Iovec { - buf: buffer.as_mut_ptr(), - buf_len: 1 - }] - ), + wasi::fd_read(fd, &[wasi::Iovec { + buf: buffer.as_mut_ptr(), + buf_len: 1 + }]), Err(wasi::ERRNO_BADF) ); assert_eq!( - wasi::fd_write( - fd, - &[wasi::Ciovec { - buf: buffer.as_ptr(), - buf_len: 1 - }] - ), + wasi::fd_write(fd, &[wasi::Ciovec { + buf: buffer.as_ptr(), + buf_len: 1 + }]), Err(wasi::ERRNO_BADF) ); diff --git a/crates/test-programs/src/http.rs b/crates/test-programs/src/http.rs index b2272699f6f2..5ecbea9a1034 100644 --- a/crates/test-programs/src/http.rs +++ b/crates/test-programs/src/http.rs @@ -1,6 +1,6 @@ use crate::wasi::http::{outgoing_handler, types as http_types}; use crate::wasi::io::streams; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use std::fmt; pub struct Response { diff --git a/crates/test-programs/src/nn.rs b/crates/test-programs/src/nn.rs index ebba36e1fde6..a03cf5051917 100644 --- a/crates/test-programs/src/nn.rs +++ b/crates/test-programs/src/nn.rs @@ -10,7 +10,7 @@ /// Call `wasi-nn` functions from WebAssembly using the canonical ABI of the /// component model via WIT-based tooling. Used by `bin/nn_wit_*.rs` tests. pub mod wit { - use anyhow::{anyhow, Result}; + use anyhow::{Result, anyhow}; use std::time::Instant; // Generate the wasi-nn bindings based on the `*.wit` files. diff --git a/crates/wasi-common/src/pipe.rs b/crates/wasi-common/src/pipe.rs index 9b282917c679..1b0f2f07cd19 100644 --- a/crates/wasi-common/src/pipe.rs +++ b/crates/wasi-common/src/pipe.rs @@ -9,8 +9,8 @@ //! Some convenience constructors are included for common backing types like `Vec` and `String`, //! but the virtual pipes can be instantiated with any `Read` or `Write` type. //! -use crate::file::{FdFlags, FileType, WasiFile}; use crate::Error; +use crate::file::{FdFlags, FileType, WasiFile}; use std::any::Any; use std::io::{self, Read, Write}; use std::sync::{Arc, RwLock}; diff --git a/crates/wasi-common/src/sched.rs b/crates/wasi-common/src/sched.rs index 237c66d49af4..02609e728498 100644 --- a/crates/wasi-common/src/sched.rs +++ b/crates/wasi-common/src/sched.rs @@ -1,6 +1,6 @@ +use crate::Error; use crate::clocks::WasiMonotonicClock; use crate::file::WasiFile; -use crate::Error; use cap_std::time::Instant; pub mod subscription; pub use cap_std::time::Duration; diff --git a/crates/wasi-common/src/sched/subscription.rs b/crates/wasi-common/src/sched/subscription.rs index 68754a0da690..bb28f6d5dfdc 100644 --- a/crates/wasi-common/src/sched/subscription.rs +++ b/crates/wasi-common/src/sched/subscription.rs @@ -1,6 +1,6 @@ +use crate::Error; use crate::clocks::WasiMonotonicClock; use crate::file::WasiFile; -use crate::Error; use bitflags::bitflags; use cap_std::time::{Duration, Instant}; diff --git a/crates/wasi-common/src/snapshots/preview_0.rs b/crates/wasi-common/src/snapshots/preview_0.rs index d53b49cdb99c..074470739e8c 100644 --- a/crates/wasi-common/src/snapshots/preview_0.rs +++ b/crates/wasi-common/src/snapshots/preview_0.rs @@ -1,7 +1,7 @@ use crate::file::TableFileExt; use crate::sched::{ - subscription::{RwEventFlags, SubscriptionResult}, Poll, Userdata, + subscription::{RwEventFlags, SubscriptionResult}, }; use crate::snapshots::preview_1::types as snapshot1_types; use crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1 as Snapshot1; @@ -846,15 +846,12 @@ impl wasi_unstable::WasiUnstable for WasiCtx { self.sched .sleep(Duration::from_nanos(clocksub.timeout)) .await?; - memory.write( - events, - types::Event { - userdata: sub.userdata, - error: types::Errno::Success, - type_: types::Eventtype::Clock, - fd_readwrite: fd_readwrite_empty(), - }, - )?; + memory.write(events, types::Event { + userdata: sub.userdata, + error: types::Errno::Success, + type_: types::Eventtype::Clock, + fd_readwrite: fd_readwrite_empty(), + })?; return Ok(1); } } @@ -939,63 +936,60 @@ impl wasi_unstable::WasiUnstable for WasiCtx { for ((result, userdata), event_elem) in results.into_iter().zip(events.iter()) { let event_ptr = event_elem?; let userdata: types::Userdata = userdata.into(); - memory.write( - event_ptr, - match result { - SubscriptionResult::Read(r) => { - let type_ = types::Eventtype::FdRead; - match r { - Ok((nbytes, flags)) => types::Event { - userdata, - error: types::Errno::Success, - type_, - fd_readwrite: types::EventFdReadwrite { - nbytes, - flags: types::Eventrwflags::from(&flags), - }, - }, - Err(e) => types::Event { - userdata, - error: types::Errno::from(e.downcast().map_err(Error::trap)?), - type_, - fd_readwrite: fd_readwrite_empty(), - }, - } - } - SubscriptionResult::Write(r) => { - let type_ = types::Eventtype::FdWrite; - match r { - Ok((nbytes, flags)) => types::Event { - userdata, - error: types::Errno::Success, - type_, - fd_readwrite: types::EventFdReadwrite { - nbytes, - flags: types::Eventrwflags::from(&flags), - }, - }, - Err(e) => types::Event { - userdata, - error: types::Errno::from(e.downcast().map_err(Error::trap)?), - type_, - fd_readwrite: fd_readwrite_empty(), + memory.write(event_ptr, match result { + SubscriptionResult::Read(r) => { + let type_ = types::Eventtype::FdRead; + match r { + Ok((nbytes, flags)) => types::Event { + userdata, + error: types::Errno::Success, + type_, + fd_readwrite: types::EventFdReadwrite { + nbytes, + flags: types::Eventrwflags::from(&flags), }, - } + }, + Err(e) => types::Event { + userdata, + error: types::Errno::from(e.downcast().map_err(Error::trap)?), + type_, + fd_readwrite: fd_readwrite_empty(), + }, } - SubscriptionResult::MonotonicClock(r) => { - let type_ = types::Eventtype::Clock; - types::Event { + } + SubscriptionResult::Write(r) => { + let type_ = types::Eventtype::FdWrite; + match r { + Ok((nbytes, flags)) => types::Event { userdata, - error: match r { - Ok(()) => types::Errno::Success, - Err(e) => types::Errno::from(e.downcast().map_err(Error::trap)?), + error: types::Errno::Success, + type_, + fd_readwrite: types::EventFdReadwrite { + nbytes, + flags: types::Eventrwflags::from(&flags), }, + }, + Err(e) => types::Event { + userdata, + error: types::Errno::from(e.downcast().map_err(Error::trap)?), type_, fd_readwrite: fd_readwrite_empty(), - } + }, } - }, - )?; + } + SubscriptionResult::MonotonicClock(r) => { + let type_ = types::Eventtype::Clock; + types::Event { + userdata, + error: match r { + Ok(()) => types::Errno::Success, + Err(e) => types::Errno::from(e.downcast().map_err(Error::trap)?), + }, + type_, + fd_readwrite: fd_readwrite_empty(), + } + } + })?; } Ok(num_results.try_into().expect("results fit into memory")) diff --git a/crates/wasi-common/src/snapshots/preview_1.rs b/crates/wasi-common/src/snapshots/preview_1.rs index 7e2d55a3b3ea..491d4c86190e 100644 --- a/crates/wasi-common/src/snapshots/preview_1.rs +++ b/crates/wasi-common/src/snapshots/preview_1.rs @@ -1,14 +1,14 @@ use crate::{ + I32Exit, SystemTimeSpec, WasiCtx, dir::{DirEntry, OpenResult, ReaddirCursor, ReaddirEntity, TableDirExt}, file::{ Advice, FdFlags, FdStat, FileAccessMode, FileEntry, FileType, Filestat, OFlags, RiFlags, RoFlags, SdFlags, SiFlags, TableFileExt, WasiFile, }, sched::{ - subscription::{RwEventFlags, SubscriptionResult}, Poll, Userdata, + subscription::{RwEventFlags, SubscriptionResult}, }, - I32Exit, SystemTimeSpec, WasiCtx, }; use cap_std::time::{Duration, SystemClock}; use std::borrow::Cow; @@ -228,7 +228,9 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx { .set_fdflags(FdFlags::from(flags)) .await } else { - log::warn!("`fd_fdstat_set_flags` does not work with wasi-threads enabled; see https://github.com/bytecodealliance/wasmtime/issues/5643"); + log::warn!( + "`fd_fdstat_set_flags` does not work with wasi-threads enabled; see https://github.com/bytecodealliance/wasmtime/issues/5643" + ); Err(Error::not_supported()) } } @@ -931,15 +933,12 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx { self.sched .sleep(Duration::from_nanos(clocksub.timeout)) .await?; - memory.write( - events, - types::Event { - userdata: sub.userdata, - error: types::Errno::Success, - type_: types::Eventtype::Clock, - fd_readwrite: fd_readwrite_empty(), - }, - )?; + memory.write(events, types::Event { + userdata: sub.userdata, + error: types::Errno::Success, + type_: types::Eventtype::Clock, + fd_readwrite: fd_readwrite_empty(), + })?; return Ok(1); } } @@ -1058,63 +1057,60 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx { for ((result, userdata), event_elem) in results.into_iter().zip(events.iter()) { let event_ptr = event_elem?; let userdata: types::Userdata = userdata.into(); - memory.write( - event_ptr, - match result { - SubscriptionResult::Read(r) => { - let type_ = types::Eventtype::FdRead; - match r { - Ok((nbytes, flags)) => types::Event { - userdata, - error: types::Errno::Success, - type_, - fd_readwrite: types::EventFdReadwrite { - nbytes, - flags: types::Eventrwflags::from(&flags), - }, - }, - Err(e) => types::Event { - userdata, - error: e.downcast().map_err(Error::trap)?, - type_, - fd_readwrite: fd_readwrite_empty(), - }, - } - } - SubscriptionResult::Write(r) => { - let type_ = types::Eventtype::FdWrite; - match r { - Ok((nbytes, flags)) => types::Event { - userdata, - error: types::Errno::Success, - type_, - fd_readwrite: types::EventFdReadwrite { - nbytes, - flags: types::Eventrwflags::from(&flags), - }, - }, - Err(e) => types::Event { - userdata, - error: e.downcast().map_err(Error::trap)?, - type_, - fd_readwrite: fd_readwrite_empty(), + memory.write(event_ptr, match result { + SubscriptionResult::Read(r) => { + let type_ = types::Eventtype::FdRead; + match r { + Ok((nbytes, flags)) => types::Event { + userdata, + error: types::Errno::Success, + type_, + fd_readwrite: types::EventFdReadwrite { + nbytes, + flags: types::Eventrwflags::from(&flags), }, - } + }, + Err(e) => types::Event { + userdata, + error: e.downcast().map_err(Error::trap)?, + type_, + fd_readwrite: fd_readwrite_empty(), + }, } - SubscriptionResult::MonotonicClock(r) => { - let type_ = types::Eventtype::Clock; - types::Event { + } + SubscriptionResult::Write(r) => { + let type_ = types::Eventtype::FdWrite; + match r { + Ok((nbytes, flags)) => types::Event { userdata, - error: match r { - Ok(()) => types::Errno::Success, - Err(e) => e.downcast().map_err(Error::trap)?, + error: types::Errno::Success, + type_, + fd_readwrite: types::EventFdReadwrite { + nbytes, + flags: types::Eventrwflags::from(&flags), }, + }, + Err(e) => types::Event { + userdata, + error: e.downcast().map_err(Error::trap)?, type_, fd_readwrite: fd_readwrite_empty(), - } + }, } - }, - )?; + } + SubscriptionResult::MonotonicClock(r) => { + let type_ = types::Eventtype::Clock; + types::Event { + userdata, + error: match r { + Ok(()) => types::Errno::Success, + Err(e) => e.downcast().map_err(Error::trap)?, + }, + type_, + fd_readwrite: fd_readwrite_empty(), + } + } + })?; } Ok(num_results.try_into().expect("results fit into memory")) diff --git a/crates/wasi-common/src/sync/clocks.rs b/crates/wasi-common/src/sync/clocks.rs index 1b85fe1140a4..bd333e10aedf 100644 --- a/crates/wasi-common/src/sync/clocks.rs +++ b/crates/wasi-common/src/sync/clocks.rs @@ -1,6 +1,6 @@ use crate::clocks::{WasiClocks, WasiMonotonicClock, WasiSystemClock}; use cap_std::time::{Duration, Instant, SystemTime}; -use cap_std::{ambient_authority, AmbientAuthority}; +use cap_std::{AmbientAuthority, ambient_authority}; use cap_time_ext::{MonotonicClockExt, SystemClockExt}; pub struct SystemClock(cap_std::time::SystemClock); diff --git a/crates/wasi-common/src/sync/dir.rs b/crates/wasi-common/src/sync/dir.rs index b532705d6e9c..35d19c0dbd2d 100644 --- a/crates/wasi-common/src/sync/dir.rs +++ b/crates/wasi-common/src/sync/dir.rs @@ -1,8 +1,8 @@ -use crate::sync::file::{filetype_from, File}; +use crate::sync::file::{File, filetype_from}; use crate::{ + Error, ErrorExt, dir::{ReaddirCursor, ReaddirEntity, WasiDir}, file::{FdFlags, FileType, Filestat, OFlags}, - Error, ErrorExt, }; use cap_fs_ext::{DirEntryExt, DirExt, MetadataExt, OpenOptionsMaybeDirExt, SystemTimeSpec}; use cap_std::fs; @@ -432,7 +432,9 @@ mod test { match f.as_mut().poll(&mut cx) { Poll::Ready(val) => return val, Poll::Pending => { - panic!("Cannot wait on pending future: must enable wiggle \"async\" future and execute on an async Store") + panic!( + "Cannot wait on pending future: must enable wiggle \"async\" future and execute on an async Store" + ) } } diff --git a/crates/wasi-common/src/sync/file.rs b/crates/wasi-common/src/sync/file.rs index 2ee6f99d1a82..78fa2bfccceb 100644 --- a/crates/wasi-common/src/sync/file.rs +++ b/crates/wasi-common/src/sync/file.rs @@ -1,6 +1,6 @@ use crate::{ - file::{Advice, FdFlags, FileType, Filestat, WasiFile}, Error, ErrorExt, + file::{Advice, FdFlags, FileType, Filestat, WasiFile}, }; use cap_fs_ext::MetadataExt; use fs_set_times::{SetTimes, SystemTimeSpec}; diff --git a/crates/wasi-common/src/sync/mod.rs b/crates/wasi-common/src/sync/mod.rs index 6986ce861ccd..2449f6cf204c 100644 --- a/crates/wasi-common/src/sync/mod.rs +++ b/crates/wasi-common/src/sync/mod.rs @@ -28,7 +28,7 @@ pub use clocks::clocks_ctx; pub use sched::sched_ctx; use self::net::Socket; -use crate::{file::FileAccessMode, table::Table, Error, WasiCtx, WasiFile}; +use crate::{Error, WasiCtx, WasiFile, file::FileAccessMode, table::Table}; use cap_rand::{Rng, RngCore, SeedableRng}; use std::mem; use std::path::Path; diff --git a/crates/wasi-common/src/sync/net.rs b/crates/wasi-common/src/sync/net.rs index f35e53c37132..e75f8b07aeff 100644 --- a/crates/wasi-common/src/sync/net.rs +++ b/crates/wasi-common/src/sync/net.rs @@ -1,6 +1,6 @@ use crate::{ - file::{FdFlags, FileType, RiFlags, RoFlags, SdFlags, SiFlags, WasiFile}, Error, ErrorExt, + file::{FdFlags, FileType, RiFlags, RoFlags, SdFlags, SiFlags, WasiFile}, }; #[cfg(windows)] use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket}; @@ -225,19 +225,11 @@ macro_rules! wasi_stream_write_impl { } async fn readable(&self) -> Result<(), Error> { let (readable, _writeable) = is_read_write(&self.0)?; - if readable { - Ok(()) - } else { - Err(Error::io()) - } + if readable { Ok(()) } else { Err(Error::io()) } } async fn writable(&self) -> Result<(), Error> { let (_readable, writeable) = is_read_write(&self.0)?; - if writeable { - Ok(()) - } else { - Err(Error::io()) - } + if writeable { Ok(()) } else { Err(Error::io()) } } async fn sock_recv<'a>( diff --git a/crates/wasi-common/src/sync/sched.rs b/crates/wasi-common/src/sync/sched.rs index e49ef46428fc..16633c68ec1e 100644 --- a/crates/wasi-common/src/sync/sched.rs +++ b/crates/wasi-common/src/sync/sched.rs @@ -9,8 +9,8 @@ pub mod windows; pub use windows::poll_oneoff; use crate::{ - sched::{Poll, WasiSched}, Error, + sched::{Poll, WasiSched}, }; use std::thread; use std::time::Duration; diff --git a/crates/wasi-common/src/sync/sched/unix.rs b/crates/wasi-common/src/sync/sched/unix.rs index 6d5bd05899ef..5ca57fb2bb81 100644 --- a/crates/wasi-common/src/sync/sched/unix.rs +++ b/crates/wasi-common/src/sync/sched/unix.rs @@ -1,5 +1,5 @@ use crate::sched::subscription::{RwEventFlags, Subscription}; -use crate::{sched::Poll, Error, ErrorExt}; +use crate::{Error, ErrorExt, sched::Poll}; use cap_std::time::Duration; use rustix::event::{PollFd, PollFlags}; diff --git a/crates/wasi-common/src/sync/sched/windows.rs b/crates/wasi-common/src/sync/sched/windows.rs index e140ccad00f8..a8e8580c5be1 100644 --- a/crates/wasi-common/src/sync/sched/windows.rs +++ b/crates/wasi-common/src/sync/sched/windows.rs @@ -9,7 +9,7 @@ // taken the time to improve it. See bug #2880. use crate::sched::subscription::{RwEventFlags, Subscription}; -use crate::{file::WasiFile, sched::Poll, Error, ErrorExt}; +use crate::{Error, ErrorExt, file::WasiFile, sched::Poll}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; use std::sync::{LazyLock, Mutex}; use std::thread; @@ -166,7 +166,7 @@ impl StdinPoll { Err(TryRecvError::Disconnected) => { return Err(Error::trap(anyhow::Error::msg( "StdinPoll notify_rx channel closed", - ))) + ))); } } diff --git a/crates/wasi-common/src/sync/stdio.rs b/crates/wasi-common/src/sync/stdio.rs index 5ff55632c072..a0682c32fa4d 100644 --- a/crates/wasi-common/src/sync/stdio.rs +++ b/crates/wasi-common/src/sync/stdio.rs @@ -5,8 +5,8 @@ use std::io::{self, IsTerminal, Read, Write}; use system_interface::io::ReadReady; use crate::{ - file::{FdFlags, FileType, WasiFile}, Error, ErrorExt, + file::{FdFlags, FileType, WasiFile}, }; #[cfg(windows)] use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket}; diff --git a/crates/wasi-common/src/tokio/dir.rs b/crates/wasi-common/src/tokio/dir.rs index 95347e8dc8c2..d71fc0e49390 100644 --- a/crates/wasi-common/src/tokio/dir.rs +++ b/crates/wasi-common/src/tokio/dir.rs @@ -1,8 +1,8 @@ use crate::tokio::{block_on_dummy_executor, file::File}; use crate::{ + Error, ErrorExt, dir::{ReaddirCursor, ReaddirEntity, WasiDir}, file::{FdFlags, Filestat, OFlags}, - Error, ErrorExt, }; use std::any::Any; use std::path::PathBuf; diff --git a/crates/wasi-common/src/tokio/file.rs b/crates/wasi-common/src/tokio/file.rs index 7aedddf33f32..942607c76391 100644 --- a/crates/wasi-common/src/tokio/file.rs +++ b/crates/wasi-common/src/tokio/file.rs @@ -1,7 +1,7 @@ use crate::tokio::block_on_dummy_executor; use crate::{ - file::{Advice, FdFlags, FileType, Filestat, WasiFile}, Error, + file::{Advice, FdFlags, FileType, Filestat, WasiFile}, }; #[cfg(windows)] use io_extras::os::windows::{AsRawHandleOrSocket, RawHandleOrSocket}; @@ -181,7 +181,7 @@ macro_rules! wasi_file_impl { // async method to ensure this is the only Future which can access the RawFd during the // lifetime of the AsyncFd. use std::os::unix::io::AsRawFd; - use tokio::io::{unix::AsyncFd, Interest}; + use tokio::io::{Interest, unix::AsyncFd}; let rawfd = self.0.borrow().as_fd().as_raw_fd(); match AsyncFd::with_interest(rawfd, Interest::READABLE) { Ok(asyncfd) => { @@ -205,7 +205,7 @@ macro_rules! wasi_file_impl { // async method to ensure this is the only Future which can access the RawFd during the // lifetime of the AsyncFd. use std::os::unix::io::AsRawFd; - use tokio::io::{unix::AsyncFd, Interest}; + use tokio::io::{Interest, unix::AsyncFd}; let rawfd = self.0.borrow().as_fd().as_raw_fd(); match AsyncFd::with_interest(rawfd, Interest::WRITABLE) { Ok(asyncfd) => { diff --git a/crates/wasi-common/src/tokio/mod.rs b/crates/wasi-common/src/tokio/mod.rs index ff80197f28f2..46b945a1fb88 100644 --- a/crates/wasi-common/src/tokio/mod.rs +++ b/crates/wasi-common/src/tokio/mod.rs @@ -7,7 +7,7 @@ pub mod stdio; use self::sched::sched_ctx; use crate::sync::net::Socket; pub use crate::sync::{clocks_ctx, random_ctx}; -use crate::{file::FileAccessMode, Error, Table, WasiCtx, WasiFile}; +use crate::{Error, Table, WasiCtx, WasiFile, file::FileAccessMode}; pub use dir::Dir; pub use file::File; pub use net::*; diff --git a/crates/wasi-common/src/tokio/sched.rs b/crates/wasi-common/src/tokio/sched.rs index e5c5a42a789d..ed107c223db7 100644 --- a/crates/wasi-common/src/tokio/sched.rs +++ b/crates/wasi-common/src/tokio/sched.rs @@ -9,8 +9,8 @@ mod windows; pub use windows::poll_oneoff; use crate::{ - sched::{Duration, Poll, WasiSched}, Error, + sched::{Duration, Poll, WasiSched}, }; pub fn sched_ctx() -> Box { diff --git a/crates/wasi-common/src/tokio/sched/unix.rs b/crates/wasi-common/src/tokio/sched/unix.rs index ca28242342fb..3f4e16d8a987 100644 --- a/crates/wasi-common/src/tokio/sched/unix.rs +++ b/crates/wasi-common/src/tokio/sched/unix.rs @@ -1,9 +1,9 @@ use crate::{ + Error, sched::{ - subscription::{RwEventFlags, Subscription}, Poll, + subscription::{RwEventFlags, Subscription}, }, - Error, }; use std::future::Future; use std::pin::Pin; diff --git a/crates/wasi-common/src/tokio/sched/windows.rs b/crates/wasi-common/src/tokio/sched/windows.rs index 55b4f5f5374e..f0d90fd0da52 100644 --- a/crates/wasi-common/src/tokio/sched/windows.rs +++ b/crates/wasi-common/src/tokio/sched/windows.rs @@ -1,6 +1,6 @@ use crate::sync::sched::windows::poll_oneoff_; use crate::tokio::block_on_dummy_executor; -use crate::{file::WasiFile, sched::Poll, Error}; +use crate::{Error, file::WasiFile, sched::Poll}; pub async fn poll_oneoff<'a>(poll: &mut Poll<'a>) -> Result<(), Error> { // Tokio doesn't provide us the AsyncFd primitive on Windows, so instead diff --git a/crates/wasi-common/src/tokio/stdio.rs b/crates/wasi-common/src/tokio/stdio.rs index 91590363ede3..c796fc722526 100644 --- a/crates/wasi-common/src/tokio/stdio.rs +++ b/crates/wasi-common/src/tokio/stdio.rs @@ -1 +1 @@ -pub use super::file::{stderr, stdin, stdout, Stderr, Stdin, Stdout}; +pub use super::file::{Stderr, Stdin, Stdout, stderr, stdin, stdout}; diff --git a/crates/wasi-common/tests/all/async_.rs b/crates/wasi-common/tests/all/async_.rs index 10b70b79c471..58b25adecf97 100644 --- a/crates/wasi-common/tests/all/async_.rs +++ b/crates/wasi-common/tests/all/async_.rs @@ -1,6 +1,6 @@ use super::*; use test_programs_artifacts::*; -use wasi_common::tokio::{add_to_linker, WasiCtxBuilder}; +use wasi_common::tokio::{WasiCtxBuilder, add_to_linker}; foreach_preview1!(assert_test_exists); diff --git a/crates/wasi-common/tests/all/sync.rs b/crates/wasi-common/tests/all/sync.rs index 4e0d38ca2fca..b9980faa1c3a 100644 --- a/crates/wasi-common/tests/all/sync.rs +++ b/crates/wasi-common/tests/all/sync.rs @@ -1,6 +1,6 @@ use super::*; use test_programs_artifacts::*; -use wasi_common::sync::{add_to_linker, WasiCtxBuilder}; +use wasi_common::sync::{WasiCtxBuilder, add_to_linker}; foreach_preview1!(assert_test_exists); diff --git a/crates/wasi-config/tests/main.rs b/crates/wasi-config/tests/main.rs index 6bcb8ec77887..101fe76f9b86 100644 --- a/crates/wasi-config/tests/main.rs +++ b/crates/wasi-config/tests/main.rs @@ -1,10 +1,10 @@ -use anyhow::{anyhow, Result}; -use test_programs_artifacts::{foreach_config, CONFIG_GET_COMPONENT}; +use anyhow::{Result, anyhow}; +use test_programs_artifacts::{CONFIG_GET_COMPONENT, foreach_config}; use wasmtime::{ - component::{Component, Linker, ResourceTable}, Store, + component::{Component, Linker, ResourceTable}, }; -use wasmtime_wasi::{add_to_linker_async, bindings::Command, WasiCtx, WasiCtxBuilder, WasiView}; +use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiView, add_to_linker_async, bindings::Command}; use wasmtime_wasi_config::{WasiConfig, WasiConfigVariables}; struct Ctx { @@ -55,13 +55,10 @@ foreach_config!(assert_test_exists); #[tokio::test(flavor = "multi_thread")] async fn config_get() -> Result<()> { - run_wasi( - CONFIG_GET_COMPONENT, - Ctx { - table: ResourceTable::new(), - wasi_ctx: WasiCtxBuilder::new().build(), - wasi_config_vars: WasiConfigVariables::from_iter(vec![("hello", "world")]), - }, - ) + run_wasi(CONFIG_GET_COMPONENT, Ctx { + table: ResourceTable::new(), + wasi_ctx: WasiCtxBuilder::new().build(), + wasi_config_vars: WasiConfigVariables::from_iter(vec![("hello", "world")]), + }) .await } diff --git a/crates/wasi-http/src/body.rs b/crates/wasi-http/src/body.rs index 96c783964746..9192ad0397f6 100644 --- a/crates/wasi-http/src/body.rs +++ b/crates/wasi-http/src/body.rs @@ -4,16 +4,16 @@ use crate::{bindings::http::types, types::FieldMap}; use anyhow::anyhow; use bytes::Bytes; use http_body::{Body, Frame}; -use http_body_util::combinators::BoxBody; use http_body_util::BodyExt; +use http_body_util::combinators::BoxBody; use std::future::Future; use std::mem; use std::task::{Context, Poll}; use std::{pin::Pin, sync::Arc, time::Duration}; use tokio::sync::{mpsc, oneshot}; use wasmtime_wasi::{ - runtime::{poll_noop, AbortOnDropJoinHandle}, HostInputStream, HostOutputStream, StreamError, Subscribe, + runtime::{AbortOnDropJoinHandle, poll_noop}, }; /// Common type for incoming bodies. @@ -615,9 +615,9 @@ impl HostOutputStream for BodyWriteStream { if let Some(written) = self.written.as_ref() { if !written.update(len) { let total = written.written(); - return Err(StreamError::LastOperationFailed(anyhow!(self - .context - .as_body_size_error(total)))); + return Err(StreamError::LastOperationFailed(anyhow!( + self.context.as_body_size_error(total) + ))); } } diff --git a/crates/wasi-http/src/http_impl.rs b/crates/wasi-http/src/http_impl.rs index 53f3bc33b2be..f52baec7be30 100644 --- a/crates/wasi-http/src/http_impl.rs +++ b/crates/wasi-http/src/http_impl.rs @@ -1,6 +1,7 @@ //! Implementation of the `wasi:http/outgoing-handler` interface. use crate::{ + WasiHttpImpl, WasiHttpView, bindings::http::{ outgoing_handler, types::{self, Scheme}, @@ -8,7 +9,6 @@ use crate::{ error::internal_error, http_request_error, types::{HostFutureIncomingResponse, HostOutgoingRequest, OutgoingRequestConfig}, - WasiHttpImpl, WasiHttpView, }; use bytes::Bytes; use http_body_util::{BodyExt, Empty}; @@ -93,15 +93,12 @@ where .body(body) .map_err(|err| internal_error(err.to_string()))?; - let future = self.send_request( - request, - OutgoingRequestConfig { - use_tls, - connect_timeout, - first_byte_timeout, - between_bytes_timeout, - }, - )?; + let future = self.send_request(request, OutgoingRequestConfig { + use_tls, + connect_timeout, + first_byte_timeout, + between_bytes_timeout, + })?; Ok(self.table().push(future)?) } diff --git a/crates/wasi-http/src/lib.rs b/crates/wasi-http/src/lib.rs index baf4bd6ba98d..45af3c433559 100644 --- a/crates/wasi-http/src/lib.rs +++ b/crates/wasi-http/src/lib.rs @@ -229,12 +229,12 @@ pub mod types; pub mod bindings; pub use crate::error::{ - http_request_error, hyper_request_error, hyper_response_error, HttpError, HttpResult, + HttpError, HttpResult, http_request_error, hyper_request_error, hyper_response_error, }; #[doc(inline)] pub use crate::types::{ - WasiHttpCtx, WasiHttpImpl, WasiHttpView, DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, - DEFAULT_OUTGOING_BODY_CHUNK_SIZE, + DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, DEFAULT_OUTGOING_BODY_CHUNK_SIZE, WasiHttpCtx, + WasiHttpImpl, WasiHttpView, }; /// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`]. diff --git a/crates/wasi-http/src/types.rs b/crates/wasi-http/src/types.rs index bb2935f0b820..c51263784a12 100644 --- a/crates/wasi-http/src/types.rs +++ b/crates/wasi-http/src/types.rs @@ -18,7 +18,7 @@ use std::time::Duration; use tokio::net::TcpStream; use tokio::time::timeout; use wasmtime::component::{Resource, ResourceTable}; -use wasmtime_wasi::{runtime::AbortOnDropJoinHandle, Subscribe}; +use wasmtime_wasi::{Subscribe, runtime::AbortOnDropJoinHandle}; /// Capture the state necessary for use in the wasi-http API implementation. #[derive(Debug)] diff --git a/crates/wasi-http/src/types_impl.rs b/crates/wasi-http/src/types_impl.rs index 337c1a3c76f7..fb88d31eec1e 100644 --- a/crates/wasi-http/src/types_impl.rs +++ b/crates/wasi-http/src/types_impl.rs @@ -1,22 +1,22 @@ //! Implementation for the `wasi:http/types` interface. use crate::{ + WasiHttpImpl, WasiHttpView, bindings::http::types::{self, Headers, Method, Scheme, StatusCode, Trailers}, body::{HostFutureTrailers, HostIncomingBody, HostOutgoingBody, StreamContext}, types::{ - is_forbidden_header, remove_forbidden_headers, FieldMap, HostFields, - HostFutureIncomingResponse, HostIncomingRequest, HostIncomingResponse, HostOutgoingRequest, - HostOutgoingResponse, HostResponseOutparam, + FieldMap, HostFields, HostFutureIncomingResponse, HostIncomingRequest, + HostIncomingResponse, HostOutgoingRequest, HostOutgoingResponse, HostResponseOutparam, + is_forbidden_header, remove_forbidden_headers, }, - WasiHttpImpl, WasiHttpView, }; use anyhow::Context; use std::any::Any; use std::str::FromStr; use wasmtime::component::{Resource, ResourceTable}; use wasmtime_wasi::{ - bindings::io::streams::{InputStream, OutputStream}, Pollable, ResourceTableError, + bindings::io::streams::{InputStream, OutputStream}, }; impl crate::bindings::http::types::Host for WasiHttpImpl diff --git a/crates/wasi-http/tests/all/http_server.rs b/crates/wasi-http/tests/all/http_server.rs index f1a22abf7edd..7d998072bf8e 100644 --- a/crates/wasi-http/tests/all/http_server.rs +++ b/crates/wasi-http/tests/all/http_server.rs @@ -1,6 +1,6 @@ use anyhow::{Context, Result}; -use http_body_util::{combinators::BoxBody, BodyExt, Full}; -use hyper::{body::Bytes, service::service_fn, Request, Response}; +use http_body_util::{BodyExt, Full, combinators::BoxBody}; +use hyper::{Request, Response, body::Bytes, service::service_fn}; use std::{ future::Future, net::{SocketAddr, TcpStream}, diff --git a/crates/wasi-http/tests/all/main.rs b/crates/wasi-http/tests/all/main.rs index 418ba66d4c35..1a6ef8803ffa 100644 --- a/crates/wasi-http/tests/all/main.rs +++ b/crates/wasi-http/tests/all/main.rs @@ -1,23 +1,23 @@ use crate::http_server::Server; -use anyhow::{anyhow, Context, Result}; -use futures::{channel::oneshot, future, stream, FutureExt}; +use anyhow::{Context, Result, anyhow}; +use futures::{FutureExt, channel::oneshot, future, stream}; use http_body::Frame; -use http_body_util::{combinators::BoxBody, BodyExt, Collected, Empty, StreamBody}; -use hyper::{body::Bytes, server::conn::http1, service::service_fn, Method, StatusCode}; +use http_body_util::{BodyExt, Collected, Empty, StreamBody, combinators::BoxBody}; +use hyper::{Method, StatusCode, body::Bytes, server::conn::http1, service::service_fn}; use sha2::{Digest, Sha256}; use std::{collections::HashMap, iter, net::Ipv4Addr, str, sync::Arc}; use tokio::task; use wasmtime::{ - component::{Component, Linker, ResourceTable}, Config, Engine, Store, + component::{Component, Linker, ResourceTable}, }; -use wasmtime_wasi::{self, pipe::MemoryOutputPipe, WasiCtx, WasiCtxBuilder, WasiView}; +use wasmtime_wasi::{self, WasiCtx, WasiCtxBuilder, WasiView, pipe::MemoryOutputPipe}; use wasmtime_wasi_http::{ + HttpResult, WasiHttpCtx, WasiHttpView, bindings::http::types::{ErrorCode, Scheme}, body::HyperOutgoingBody, io::TokioIo, types::{self, HostFutureIncomingResponse, IncomingResponse, OutgoingRequestConfig}, - HttpResult, WasiHttpCtx, WasiHttpView, }; mod http_server; @@ -554,9 +554,9 @@ async fn wasi_http_without_port() -> Result<()> { } mod body { - use http_body_util::{combinators::BoxBody, BodyExt, Empty, Full}; - use hyper::body::Bytes; + use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody}; use hyper::Error; + use hyper::body::Bytes; pub fn full(bytes: Bytes) -> BoxBody { BoxBody::new(Full::new(bytes).map_err(|_| unreachable!())) diff --git a/crates/wasi-keyvalue/tests/main.rs b/crates/wasi-keyvalue/tests/main.rs index 6ae8eee18a56..a23124393f3d 100644 --- a/crates/wasi-keyvalue/tests/main.rs +++ b/crates/wasi-keyvalue/tests/main.rs @@ -1,10 +1,10 @@ -use anyhow::{anyhow, Result}; -use test_programs_artifacts::{foreach_keyvalue, KEYVALUE_MAIN_COMPONENT}; +use anyhow::{Result, anyhow}; +use test_programs_artifacts::{KEYVALUE_MAIN_COMPONENT, foreach_keyvalue}; use wasmtime::{ - component::{Component, Linker, ResourceTable}, Store, + component::{Component, Linker, ResourceTable}, }; -use wasmtime_wasi::{bindings::Command, WasiCtx, WasiCtxBuilder, WasiView}; +use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiView, bindings::Command}; use wasmtime_wasi_keyvalue::{WasiKeyValue, WasiKeyValueCtx, WasiKeyValueCtxBuilder}; struct Ctx { @@ -55,15 +55,12 @@ foreach_keyvalue!(assert_test_exists); #[tokio::test(flavor = "multi_thread")] async fn keyvalue_main() -> Result<()> { - run_wasi( - KEYVALUE_MAIN_COMPONENT, - Ctx { - table: ResourceTable::new(), - wasi_ctx: WasiCtxBuilder::new().inherit_stderr().build(), - wasi_keyvalue_ctx: WasiKeyValueCtxBuilder::new() - .in_memory_data([("atomics_key", "5")]) - .build(), - }, - ) + run_wasi(KEYVALUE_MAIN_COMPONENT, Ctx { + table: ResourceTable::new(), + wasi_ctx: WasiCtxBuilder::new().inherit_stderr().build(), + wasi_keyvalue_ctx: WasiKeyValueCtxBuilder::new() + .in_memory_data([("atomics_key", "5")]) + .build(), + }) .await } diff --git a/crates/wasi-nn/src/backend/onnx.rs b/crates/wasi-nn/src/backend/onnx.rs index b6ae2ddf278e..bc95167f008f 100644 --- a/crates/wasi-nn/src/backend/onnx.rs +++ b/crates/wasi-nn/src/backend/onnx.rs @@ -1,11 +1,11 @@ //! Implements a `wasi-nn` [`BackendInner`] using ONNX via the `ort` crate. use super::{BackendError, BackendExecutionContext, BackendFromDir, BackendGraph, BackendInner}; -use crate::backend::{read, Id}; +use crate::backend::{Id, read}; use crate::wit::types::{ExecutionTarget, GraphEncoding, Tensor, TensorType}; use crate::{ExecutionContext, Graph}; use anyhow::Context; -use ort::{inputs, GraphOptimizationLevel, Session}; +use ort::{GraphOptimizationLevel, Session, inputs}; use std::path::Path; use std::sync::{Arc, Mutex}; diff --git a/crates/wasi-nn/src/backend/openvino.rs b/crates/wasi-nn/src/backend/openvino.rs index 8be15bd25051..bb45d9268b03 100644 --- a/crates/wasi-nn/src/backend/openvino.rs +++ b/crates/wasi-nn/src/backend/openvino.rs @@ -1,7 +1,7 @@ //! Implements a `wasi-nn` [`BackendInner`] using OpenVINO. use super::{ - read, BackendError, BackendExecutionContext, BackendFromDir, BackendGraph, BackendInner, Id, + BackendError, BackendExecutionContext, BackendFromDir, BackendGraph, BackendInner, Id, read, }; use crate::wit::{ExecutionTarget, GraphEncoding, Tensor, TensorType}; use crate::{ExecutionContext, Graph}; diff --git a/crates/wasi-nn/src/backend/winml.rs b/crates/wasi-nn/src/backend/winml.rs index 4f509351cc1b..6c5b94a1ed77 100644 --- a/crates/wasi-nn/src/backend/winml.rs +++ b/crates/wasi-nn/src/backend/winml.rs @@ -13,16 +13,16 @@ use crate::backend::{ use crate::wit::{ExecutionTarget, GraphEncoding, Tensor, TensorType}; use crate::{ExecutionContext, Graph}; use std::{fs::File, io::Read, mem::size_of, path::Path}; -use windows::core::{ComInterface, Error, IInspectable, HSTRING}; -use windows::Foundation::Collections::IVectorView; -use windows::Storage::Streams::{ - DataWriter, InMemoryRandomAccessStream, RandomAccessStreamReference, -}; use windows::AI::MachineLearning::{ ILearningModelFeatureDescriptor, LearningModel, LearningModelBinding, LearningModelDevice, LearningModelDeviceKind, LearningModelEvaluationResult, LearningModelSession, TensorFeatureDescriptor, TensorFloat, TensorFloat16Bit, TensorInt64Bit, TensorKind, }; +use windows::Foundation::Collections::IVectorView; +use windows::Storage::Streams::{ + DataWriter, InMemoryRandomAccessStream, RandomAccessStreamReference, +}; +use windows::core::{ComInterface, Error, HSTRING, IInspectable}; #[derive(Default)] pub struct WinMLBackend(); diff --git a/crates/wasi-nn/tests/check/onnx.rs b/crates/wasi-nn/tests/check/onnx.rs index cdbec420de22..61ce907f2724 100644 --- a/crates/wasi-nn/tests/check/onnx.rs +++ b/crates/wasi-nn/tests/check/onnx.rs @@ -1,4 +1,4 @@ -use super::{artifacts_dir, download, DOWNLOAD_LOCK}; +use super::{DOWNLOAD_LOCK, artifacts_dir, download}; use anyhow::{Context, Result}; use std::{env, fs}; @@ -7,8 +7,7 @@ use std::{env, fs}; pub fn are_artifacts_available() -> Result<()> { let _exclusively_retrieve_artifacts = DOWNLOAD_LOCK.lock().unwrap(); - const ONNX_BASE_URL: &str = - "https://github.com/onnx/models/raw/bec48b6a70e5e9042c0badbaafefe4454e072d08/validated/vision/classification/mobilenet/model/mobilenetv2-10.onnx?download="; + const ONNX_BASE_URL: &str = "https://github.com/onnx/models/raw/bec48b6a70e5e9042c0badbaafefe4454e072d08/validated/vision/classification/mobilenet/model/mobilenetv2-10.onnx?download="; let artifacts_dir = artifacts_dir(); if !artifacts_dir.is_dir() { diff --git a/crates/wasi-nn/tests/check/openvino.rs b/crates/wasi-nn/tests/check/openvino.rs index d773c1e3c55d..a584c9290377 100644 --- a/crates/wasi-nn/tests/check/openvino.rs +++ b/crates/wasi-nn/tests/check/openvino.rs @@ -1,5 +1,5 @@ -use super::{artifacts_dir, download, DOWNLOAD_LOCK}; -use anyhow::{bail, Context, Result}; +use super::{DOWNLOAD_LOCK, artifacts_dir, download}; +use anyhow::{Context, Result, bail}; use std::fs; /// Return `Ok` if we find a working OpenVINO installation. @@ -22,8 +22,7 @@ pub fn is_installed() -> Result<()> { /// download the artifacts if necessary. pub fn are_artifacts_available() -> Result<()> { let _exclusively_retrieve_artifacts = DOWNLOAD_LOCK.lock().unwrap(); - const BASE_URL: &str = - "https://github.com/intel/openvino-rs/raw/72d75601e9be394b3e8c7ff28313d66ef53ff358/crates/openvino/tests/fixtures/mobilenet"; + const BASE_URL: &str = "https://github.com/intel/openvino-rs/raw/72d75601e9be394b3e8c7ff28313d66ef53ff358/crates/openvino/tests/fixtures/mobilenet"; let artifacts_dir = artifacts_dir(); if !artifacts_dir.is_dir() { fs::create_dir(&artifacts_dir)?; diff --git a/crates/wasi-nn/tests/check/pytorch.rs b/crates/wasi-nn/tests/check/pytorch.rs index fcb553c55339..a6ac208d06bc 100644 --- a/crates/wasi-nn/tests/check/pytorch.rs +++ b/crates/wasi-nn/tests/check/pytorch.rs @@ -1,13 +1,12 @@ -use super::{artifacts_dir, download, DOWNLOAD_LOCK}; -use anyhow::{bail, Context, Result}; +use super::{DOWNLOAD_LOCK, artifacts_dir, download}; +use anyhow::{Context, Result, bail}; use std::{env, fs}; /// Return `Ok` if we find the cached MobileNet test artifacts; this will /// download the artifacts if necessary. pub fn are_artifacts_available() -> Result<()> { let _exclusively_retrieve_artifacts = DOWNLOAD_LOCK.lock().unwrap(); - const PYTORCH_BASE_URL: &str = - "https://github.com/rahulchaphalkar/libtorch-models/releases/download/v0.1/squeezenet1_1.pt"; + const PYTORCH_BASE_URL: &str = "https://github.com/rahulchaphalkar/libtorch-models/releases/download/v0.1/squeezenet1_1.pt"; let artifacts_dir = artifacts_dir(); if !artifacts_dir.is_dir() { fs::create_dir(&artifacts_dir)?; diff --git a/crates/wasi-nn/tests/check/winml.rs b/crates/wasi-nn/tests/check/winml.rs index fc45337a6025..a02a331169ac 100644 --- a/crates/wasi-nn/tests/check/winml.rs +++ b/crates/wasi-nn/tests/check/winml.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use windows::AI::MachineLearning::{LearningModelDevice, LearningModelDeviceKind}; /// Return `Ok` if we can use WinML. diff --git a/crates/wasi-nn/tests/exec/wit.rs b/crates/wasi-nn/tests/exec/wit.rs index 5f2d546d667d..3d4148c36427 100644 --- a/crates/wasi-nn/tests/exec/wit.rs +++ b/crates/wasi-nn/tests/exec/wit.rs @@ -1,13 +1,13 @@ use super::PREOPENED_DIR_NAME; use crate::check::artifacts_dir; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use std::path::Path; use wasmtime::component::{Component, Linker, ResourceTable}; use wasmtime::{Config, Engine, Store}; use wasmtime_wasi::bindings::sync::Command; use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, WasiCtxBuilder}; use wasmtime_wasi_nn::wit::WasiNnView; -use wasmtime_wasi_nn::{wit::WasiNnCtx, Backend, InMemoryRegistry}; +use wasmtime_wasi_nn::{Backend, InMemoryRegistry, wit::WasiNnCtx}; /// Run a wasi-nn test program. This is modeled after /// `crates/wasi/tests/all/main.rs` but still uses the older preview1 API for diff --git a/crates/wasi-nn/tests/exec/witx.rs b/crates/wasi-nn/tests/exec/witx.rs index 21feea1dd641..c5cb0f8379fe 100644 --- a/crates/wasi-nn/tests/exec/witx.rs +++ b/crates/wasi-nn/tests/exec/witx.rs @@ -3,8 +3,8 @@ use crate::check::artifacts_dir; use anyhow::Result; use std::path::Path; use wasmtime::{Config, Engine, Linker, Module, Store}; -use wasmtime_wasi::{preview1::WasiP1Ctx, DirPerms, FilePerms, WasiCtxBuilder}; -use wasmtime_wasi_nn::{witx::WasiNnCtx, Backend, InMemoryRegistry}; +use wasmtime_wasi::{DirPerms, FilePerms, WasiCtxBuilder, preview1::WasiP1Ctx}; +use wasmtime_wasi_nn::{Backend, InMemoryRegistry, witx::WasiNnCtx}; /// Run a wasi-nn test program. This is modeled after /// `crates/wasi/tests/all/main.rs` but still uses the older preview1 API diff --git a/crates/wasi-nn/tests/test-programs.rs b/crates/wasi-nn/tests/test-programs.rs index 3133bb264761..3d8d49478e5f 100644 --- a/crates/wasi-nn/tests/test-programs.rs +++ b/crates/wasi-nn/tests/test-programs.rs @@ -20,7 +20,7 @@ use anyhow::Result; use libtest_mimic::{Arguments, Trial}; use std::{borrow::Cow, env}; use test_programs_artifacts::*; -use wasmtime_wasi_nn::{backend, Backend}; +use wasmtime_wasi_nn::{Backend, backend}; fn main() -> Result<()> { tracing_subscriber::fmt::init(); diff --git a/crates/wasi-preview1-component-adapter/build.rs b/crates/wasi-preview1-component-adapter/build.rs index 36cf93c7b20e..e4b87e021333 100644 --- a/crates/wasi-preview1-component-adapter/build.rs +++ b/crates/wasi-preview1-component-adapter/build.rs @@ -239,7 +239,7 @@ fn build_raw_intrinsics() -> Vec { /// Like above this is still tricky, mainly around the production of the symbol /// table. fn build_archive(wasm: &[u8]) -> Vec { - use object::{bytes_of, endian::BigEndian, U32Bytes}; + use object::{U32Bytes, bytes_of, endian::BigEndian}; let mut archive = Vec::new(); archive.extend_from_slice(&object::archive::MAGIC); diff --git a/crates/wasi-preview1-component-adapter/src/descriptors.rs b/crates/wasi-preview1-component-adapter/src/descriptors.rs index 806192f33172..b27cdc17b341 100644 --- a/crates/wasi-preview1-component-adapter/src/descriptors.rs +++ b/crates/wasi-preview1-component-adapter/src/descriptors.rs @@ -6,10 +6,10 @@ use core::mem::MaybeUninit; use core::num::NonZeroUsize; use wasi::{Errno, Fd}; -#[cfg(not(feature = "proxy"))] -use crate::bindings::wasi::filesystem::types as filesystem; #[cfg(not(feature = "proxy"))] use crate::File; +#[cfg(not(feature = "proxy"))] +use crate::bindings::wasi::filesystem::types as filesystem; pub const MAX_DESCRIPTORS: usize = 128; diff --git a/crates/wasi-preview1-component-adapter/src/lib.rs b/crates/wasi-preview1-component-adapter/src/lib.rs index e0a23603045a..8c199e3fcbbf 100644 --- a/crates/wasi-preview1-component-adapter/src/lib.rs +++ b/crates/wasi-preview1-component-adapter/src/lib.rs @@ -23,7 +23,7 @@ use core::cell::{Cell, RefCell, RefMut, UnsafeCell}; use core::cmp::min; use core::ffi::c_void; use core::hint::black_box; -use core::mem::{self, align_of, forget, size_of, ManuallyDrop, MaybeUninit}; +use core::mem::{self, ManuallyDrop, MaybeUninit, align_of, forget, size_of}; use core::num::NonZeroUsize; use core::ops::{Deref, DerefMut}; use core::ptr::{self, null_mut}; @@ -2529,7 +2529,7 @@ impl BlockingMode { Ok(()) => {} Err(streams::StreamError::Closed) => return Err(ERRNO_IO), Err(streams::StreamError::LastOperationFailed(e)) => { - return Err(stream_error_to_errno(e)) + return Err(stream_error_to_errno(e)); } } } @@ -2541,7 +2541,7 @@ impl BlockingMode { Ok(n) => n, Err(streams::StreamError::Closed) => 0, Err(streams::StreamError::LastOperationFailed(e)) => { - return Err(stream_error_to_errno(e)) + return Err(stream_error_to_errno(e)); } }; @@ -2551,7 +2551,7 @@ impl BlockingMode { Ok(_) => {} Err(streams::StreamError::Closed) => return Ok(0), Err(streams::StreamError::LastOperationFailed(e)) => { - return Err(stream_error_to_errno(e)) + return Err(stream_error_to_errno(e)); } } @@ -2559,7 +2559,7 @@ impl BlockingMode { Ok(_) => {} Err(streams::StreamError::Closed) => return Ok(0), Err(streams::StreamError::LastOperationFailed(e)) => { - return Err(stream_error_to_errno(e)) + return Err(stream_error_to_errno(e)); } } diff --git a/crates/wasi-preview1-component-adapter/verify/src/main.rs b/crates/wasi-preview1-component-adapter/verify/src/main.rs index f074b61f0bcb..d35f36e1e297 100644 --- a/crates/wasi-preview1-component-adapter/verify/src/main.rs +++ b/crates/wasi-preview1-component-adapter/verify/src/main.rs @@ -1,4 +1,4 @@ -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use std::env; use wasmparser::*; diff --git a/crates/wasi-threads/src/lib.rs b/crates/wasi-threads/src/lib.rs index be775f5a4c13..69e015c95d1a 100644 --- a/crates/wasi-threads/src/lib.rs +++ b/crates/wasi-threads/src/lib.rs @@ -2,10 +2,10 @@ //! //! [`wasi-threads`]: https://github.com/WebAssembly/wasi-threads -use anyhow::{anyhow, Result}; -use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::sync::atomic::{AtomicI32, Ordering}; +use anyhow::{Result, anyhow}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::Arc; +use std::sync::atomic::{AtomicI32, Ordering}; use std::thread; use wasmtime::{Caller, ExternType, InstancePre, Linker, Module, SharedMemory, Store}; @@ -38,11 +38,15 @@ impl WasiThreadsCtx { // As defined in the wasi-threads specification, returning a negative // result here indicates to the guest module that the spawn failed. if !has_entry_point(instance_pre.module()) { - log::error!("failed to find a wasi-threads entry point function; expected an export with name: {WASI_ENTRY_POINT}"); + log::error!( + "failed to find a wasi-threads entry point function; expected an export with name: {WASI_ENTRY_POINT}" + ); return Ok(-1); } if !has_correct_signature(instance_pre.module()) { - log::error!("the exported entry point function has an incorrect signature: expected `(i32, i32) -> ()`"); + log::error!( + "the exported entry point function has an incorrect signature: expected `(i32, i32) -> ()`" + ); return Ok(-1); } diff --git a/crates/wasi/src/bindings.rs b/crates/wasi/src/bindings.rs index cefeec980ce3..f731596e3dca 100644 --- a/crates/wasi/src/bindings.rs +++ b/crates/wasi/src/bindings.rs @@ -417,9 +417,9 @@ mod async_io { }); } +pub use self::async_io::LinkOptions; pub use self::async_io::exports; pub use self::async_io::wasi::*; -pub use self::async_io::LinkOptions; /// Asynchronous bindings to execute and run a `wasi:cli/command`. /// diff --git a/crates/wasi/src/clocks/host.rs b/crates/wasi/src/clocks/host.rs index 20b35ce6438f..51ed26d3cfe0 100644 --- a/crates/wasi/src/clocks/host.rs +++ b/crates/wasi/src/clocks/host.rs @@ -1,6 +1,6 @@ use super::{HostMonotonicClock, HostWallClock}; use cap_std::time::{Duration, Instant, SystemClock}; -use cap_std::{ambient_authority, AmbientAuthority}; +use cap_std::{AmbientAuthority, ambient_authority}; use cap_time_ext::{MonotonicClockExt, SystemClockExt}; pub struct WallClock { diff --git a/crates/wasi/src/ctx.rs b/crates/wasi/src/ctx.rs index d7a5c4156ae0..d5c13e03901f 100644 --- a/crates/wasi/src/ctx.rs +++ b/crates/wasi/src/ctx.rs @@ -1,13 +1,13 @@ use crate::{ + DirPerms, FilePerms, clocks::{ - host::{monotonic_clock, wall_clock}, HostMonotonicClock, HostWallClock, + host::{monotonic_clock, wall_clock}, }, filesystem::{Dir, OpenMode}, network::{SocketAddrCheck, SocketAddrUse}, pipe, random, stdio, stdio::{StdinStream, StdoutStream}, - DirPerms, FilePerms, }; use anyhow::Result; use cap_rand::{Rng, RngCore, SeedableRng}; diff --git a/crates/wasi/src/filesystem.rs b/crates/wasi/src/filesystem.rs index 2c6f039de4f0..576726c7317d 100644 --- a/crates/wasi/src/filesystem.rs +++ b/crates/wasi/src/filesystem.rs @@ -1,5 +1,5 @@ use crate::bindings::filesystem::types; -use crate::runtime::{spawn_blocking, AbortOnDropJoinHandle}; +use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking}; use crate::{ HostInputStream, HostOutputStream, StreamError, StreamResult, Subscribe, TrappableError, }; diff --git a/crates/wasi/src/host/clocks.rs b/crates/wasi/src/host/clocks.rs index e94ca98555ff..8e8edd569d3d 100644 --- a/crates/wasi/src/host/clocks.rs +++ b/crates/wasi/src/host/clocks.rs @@ -4,7 +4,7 @@ use crate::bindings::{ clocks::monotonic_clock::{self, Duration as WasiDuration, Instant}, clocks::wall_clock::{self, Datetime}, }; -use crate::poll::{subscribe, Subscribe}; +use crate::poll::{Subscribe, subscribe}; use crate::{Pollable, WasiImpl, WasiView}; use cap_std::time::SystemTime; use std::time::Duration; diff --git a/crates/wasi/src/host/exit.rs b/crates/wasi/src/host/exit.rs index b955aa2244ab..0d7a09c7e077 100644 --- a/crates/wasi/src/host/exit.rs +++ b/crates/wasi/src/host/exit.rs @@ -1,4 +1,4 @@ -use crate::{bindings::cli::exit, I32Exit, WasiImpl, WasiView}; +use crate::{I32Exit, WasiImpl, WasiView, bindings::cli::exit}; impl exit::Host for WasiImpl where diff --git a/crates/wasi/src/host/io.rs b/crates/wasi/src/host/io.rs index 35a2e8e63aa9..62dc446f3c6b 100644 --- a/crates/wasi/src/host/io.rs +++ b/crates/wasi/src/host/io.rs @@ -1,8 +1,8 @@ use crate::{ + Pollable, StreamError, StreamResult, WasiImpl, WasiView, bindings::io::error, bindings::io::streams::{self, InputStream, OutputStream}, poll::subscribe, - Pollable, StreamError, StreamResult, WasiImpl, WasiView, }; use wasmtime::component::Resource; @@ -220,6 +220,7 @@ where pub mod sync { use crate::{ + StreamError, StreamResult, WasiImpl, WasiView, bindings::io::streams::{ self as async_streams, Host as AsyncHost, HostInputStream as AsyncHostInputStream, HostOutputStream as AsyncHostOutputStream, @@ -227,7 +228,6 @@ pub mod sync { bindings::sync::io::poll::Pollable, bindings::sync::io::streams::{self, InputStream, OutputStream}, runtime::in_tokio, - StreamError, StreamResult, WasiImpl, WasiView, }; use wasmtime::component::Resource; diff --git a/crates/wasi/src/host/random.rs b/crates/wasi/src/host/random.rs index a3fe59487d3f..361d38e2dde7 100644 --- a/crates/wasi/src/host/random.rs +++ b/crates/wasi/src/host/random.rs @@ -1,6 +1,6 @@ use crate::bindings::random::{insecure, insecure_seed, random}; use crate::{WasiImpl, WasiView}; -use cap_rand::{distributions::Standard, Rng}; +use cap_rand::{Rng, distributions::Standard}; impl random::Host for WasiImpl where diff --git a/crates/wasi/src/host/tcp.rs b/crates/wasi/src/host/tcp.rs index 160cb8a757c0..3a39fbe05323 100644 --- a/crates/wasi/src/host/tcp.rs +++ b/crates/wasi/src/host/tcp.rs @@ -1,4 +1,5 @@ use crate::network::SocketAddrUse; +use crate::{Pollable, SocketResult, WasiImpl, WasiView}; use crate::{ bindings::{ io::streams::{InputStream, OutputStream}, @@ -7,7 +8,6 @@ use crate::{ }, network::SocketAddressFamily, }; -use crate::{Pollable, SocketResult, WasiImpl, WasiView}; use std::net::SocketAddr; use std::time::Duration; use wasmtime::component::Resource; @@ -316,6 +316,7 @@ pub mod sync { use wasmtime::component::Resource; use crate::{ + SocketError, WasiImpl, WasiView, bindings::{ sockets::{ network::Network, @@ -327,7 +328,6 @@ pub mod sync { }, }, runtime::in_tokio, - SocketError, WasiImpl, WasiView, }; impl tcp::Host for WasiImpl where T: WasiView {} diff --git a/crates/wasi/src/host/udp.rs b/crates/wasi/src/host/udp.rs index 3dd73ff6ffe3..5973e42e38c4 100644 --- a/crates/wasi/src/host/udp.rs +++ b/crates/wasi/src/host/udp.rs @@ -1,14 +1,14 @@ use crate::host::network::util; use crate::network::{SocketAddrUse, SocketAddressFamily}; +use crate::{Pollable, SocketError, SocketResult, WasiImpl, WasiView}; use crate::{ + Subscribe, bindings::{ sockets::network::{ErrorCode, IpAddressFamily, IpSocketAddress, Network}, sockets::udp, }, udp::{IncomingDatagramStream, OutgoingDatagramStream, SendState, UdpState}, - Subscribe, }; -use crate::{Pollable, SocketError, SocketResult, WasiImpl, WasiView}; use anyhow::anyhow; use async_trait::async_trait; use io_lifetimes::AsSocketlike; @@ -471,12 +471,12 @@ where SendState::Permitted(_) => { return Err(SocketError::trap(anyhow::anyhow!( "unpermitted: argument exceeds permitted size" - ))) + ))); } SendState::Idle | SendState::Waiting => { return Err(SocketError::trap(anyhow::anyhow!( "unpermitted: must call check-send first" - ))) + ))); } } @@ -546,6 +546,7 @@ pub mod sync { use wasmtime::component::Resource; use crate::{ + SocketError, WasiImpl, WasiView, bindings::{ sockets::{ network::Network, @@ -564,7 +565,6 @@ pub mod sync { }, }, runtime::in_tokio, - SocketError, WasiImpl, WasiView, }; impl udp::Host for WasiImpl where T: WasiView {} diff --git a/crates/wasi/src/ip_name_lookup.rs b/crates/wasi/src/ip_name_lookup.rs index e013cefb01fc..55542fd858d3 100644 --- a/crates/wasi/src/ip_name_lookup.rs +++ b/crates/wasi/src/ip_name_lookup.rs @@ -1,8 +1,8 @@ use crate::bindings::sockets::ip_name_lookup::{Host, HostResolveAddressStream}; use crate::bindings::sockets::network::{ErrorCode, IpAddress, Network}; use crate::host::network::util; -use crate::poll::{subscribe, Pollable, Subscribe}; -use crate::runtime::{spawn_blocking, AbortOnDropJoinHandle}; +use crate::poll::{Pollable, Subscribe, subscribe}; +use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking}; use crate::{SocketError, WasiImpl, WasiView}; use anyhow::Result; use std::mem; diff --git a/crates/wasi/src/lib.rs b/crates/wasi/src/lib.rs index a19c6c42ba6d..aae4701c817c 100644 --- a/crates/wasi/src/lib.rs +++ b/crates/wasi/src/lib.rs @@ -212,11 +212,11 @@ pub use self::ctx::{WasiCtx, WasiCtxBuilder, WasiImpl, WasiView}; pub use self::error::{I32Exit, TrappableError}; pub use self::filesystem::{DirPerms, FileInputStream, FilePerms, FsError, FsResult}; pub use self::network::{Network, SocketAddrUse, SocketError, SocketResult}; -pub use self::poll::{subscribe, ClosureFuture, MakeFuture, Pollable, PollableFuture, Subscribe}; -pub use self::random::{thread_rng, Deterministic}; +pub use self::poll::{ClosureFuture, MakeFuture, Pollable, PollableFuture, Subscribe, subscribe}; +pub use self::random::{Deterministic, thread_rng}; pub use self::stdio::{ - stderr, stdin, stdout, AsyncStdinStream, AsyncStdoutStream, IsATTY, OutputFile, Stderr, Stdin, - StdinStream, Stdout, StdoutStream, + AsyncStdinStream, AsyncStdoutStream, IsATTY, OutputFile, Stderr, Stdin, StdinStream, Stdout, + StdoutStream, stderr, stdin, stdout, }; pub use self::stream::{ HostInputStream, HostOutputStream, InputStream, OutputStream, StreamError, StreamResult, diff --git a/crates/wasi/src/network.rs b/crates/wasi/src/network.rs index c435accf213f..42384b807be1 100644 --- a/crates/wasi/src/network.rs +++ b/crates/wasi/src/network.rs @@ -1,5 +1,5 @@ -use crate::bindings::sockets::network::{ErrorCode, Ipv4Address, Ipv6Address}; use crate::TrappableError; +use crate::bindings::sockets::network::{ErrorCode, Ipv4Address, Ipv6Address}; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; diff --git a/crates/wasi/src/pipe.rs b/crates/wasi/src/pipe.rs index c09fc1c33b94..0144de70f112 100644 --- a/crates/wasi/src/pipe.rs +++ b/crates/wasi/src/pipe.rs @@ -618,7 +618,9 @@ mod test { assert!(should_be_closed); } r => { - panic!("stream should be reported closed by the end of write_ready after flush, got {r:?}. {write_ready_res:?} {flush_res:?}") + panic!( + "stream should be reported closed by the end of write_ready after flush, got {r:?}. {write_ready_res:?} {flush_res:?}" + ) } } } diff --git a/crates/wasi/src/poll.rs b/crates/wasi/src/poll.rs index ea494a1dcc85..696b6b9dbf76 100644 --- a/crates/wasi/src/poll.rs +++ b/crates/wasi/src/poll.rs @@ -1,5 +1,5 @@ -use crate::{bindings::io::poll, WasiImpl, WasiView}; -use anyhow::{anyhow, Result}; +use crate::{WasiImpl, WasiView, bindings::io::poll}; +use anyhow::{Result, anyhow}; use std::any::Any; use std::collections::HashMap; use std::future::Future; @@ -209,10 +209,10 @@ where pub mod sync { use crate::{ + WasiImpl, WasiView, bindings::io::poll as async_poll, bindings::sync::io::poll::{self, Pollable}, runtime::in_tokio, - WasiImpl, WasiView, }; use anyhow::Result; use wasmtime::component::Resource; diff --git a/crates/wasi/src/preview0.rs b/crates/wasi/src/preview0.rs index 038b98b40df2..584c7368bdbb 100644 --- a/crates/wasi/src/preview0.rs +++ b/crates/wasi/src/preview0.rs @@ -4,9 +4,9 @@ //! You probably want to use [`preview1`](crate::preview1) instead. use crate::preview0::types::Error; +use crate::preview1::WasiP1Ctx; use crate::preview1::types as snapshot1_types; use crate::preview1::wasi_snapshot_preview1::WasiSnapshotPreview1 as Snapshot1; -use crate::preview1::WasiP1Ctx; use wiggle::{GuestError, GuestMemory, GuestPtr}; pub fn add_to_linker_async( @@ -521,23 +521,20 @@ impl wasi_unstable::WasiUnstable for T { let slot = slot?; let sub = memory.read(slot)?; old_subs.push(sub.clone()); - memory.write( - slot.cast(), - snapshot1_types::Subscription { - userdata: sub.userdata, - u: match sub.u { - types::SubscriptionU::Clock(c) => { - snapshot1_types::SubscriptionU::Clock(c.into()) - } - types::SubscriptionU::FdRead(c) => { - snapshot1_types::SubscriptionU::FdRead(c.into()) - } - types::SubscriptionU::FdWrite(c) => { - snapshot1_types::SubscriptionU::FdWrite(c.into()) - } - }, + memory.write(slot.cast(), snapshot1_types::Subscription { + userdata: sub.userdata, + u: match sub.u { + types::SubscriptionU::Clock(c) => { + snapshot1_types::SubscriptionU::Clock(c.into()) + } + types::SubscriptionU::FdRead(c) => { + snapshot1_types::SubscriptionU::FdRead(c.into()) + } + types::SubscriptionU::FdWrite(c) => { + snapshot1_types::SubscriptionU::FdWrite(c.into()) + } }, - )?; + })?; } let ret = Snapshot1::poll_oneoff(self, memory, subs.cast(), events.cast(), nsubscriptions) .await?; diff --git a/crates/wasi/src/preview1.rs b/crates/wasi/src/preview1.rs index a4aec9b58110..bcabe45a486c 100644 --- a/crates/wasi/src/preview1.rs +++ b/crates/wasi/src/preview1.rs @@ -75,13 +75,13 @@ use crate::bindings::{ use crate::{ FsError, IsATTY, ResourceTable, StreamError, StreamResult, WasiCtx, WasiImpl, WasiView, }; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use std::collections::{BTreeMap, HashSet}; use std::mem::{self, size_of, size_of_val}; use std::ops::{Deref, DerefMut}; use std::slice; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use system_interface::fs::FileIoExt; use wasmtime::component::Resource; use wiggle::tracing::instrument; @@ -1250,7 +1250,7 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiP1Ctx { .map_err(types::Error::trap)? } types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => { - return Err(types::Errno::Badf.into()) + return Err(types::Errno::Badf.into()); } }; Ok(res) @@ -1272,7 +1272,7 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiP1Ctx { .context("failed to call `monotonic_clock::now`") .map_err(types::Error::trap)?, types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => { - return Err(types::Errno::Badf.into()) + return Err(types::Errno::Badf.into()); } }; Ok(now) @@ -2281,18 +2281,15 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiP1Ctx { && self.ctx().allow_blocking_current_thread { std::thread::sleep(std::time::Duration::from_nanos(clocksub.timeout)); - memory.write( - events, - types::Event { - userdata: sub.userdata, - error: types::Errno::Success, - type_: types::Eventtype::Clock, - fd_readwrite: types::EventFdReadwrite { - flags: types::Eventrwflags::empty(), - nbytes: 1, - }, + memory.write(events, types::Event { + userdata: sub.userdata, + error: types::Errno::Success, + type_: types::Eventtype::Clock, + fd_readwrite: types::EventFdReadwrite { + flags: types::Eventrwflags::empty(), + nbytes: 1, }, - )?; + })?; return Ok(1); } } diff --git a/crates/wasi/src/stdio.rs b/crates/wasi/src/stdio.rs index 4fb359f394fb..ff4ab51968de 100644 --- a/crates/wasi/src/stdio.rs +++ b/crates/wasi/src/stdio.rs @@ -136,7 +136,7 @@ impl Subscribe for AsyncStdinStream { } mod worker_thread_stdin; -pub use self::worker_thread_stdin::{stdin, Stdin}; +pub use self::worker_thread_stdin::{Stdin, stdin}; /// Similar to [`StdinStream`], except for output. pub trait StdoutStream: Send { diff --git a/crates/wasi/src/tcp.rs b/crates/wasi/src/tcp.rs index 5b05ebb25339..057a39895d96 100644 --- a/crates/wasi/src/tcp.rs +++ b/crates/wasi/src/tcp.rs @@ -1,7 +1,7 @@ use crate::bindings::sockets::tcp::ErrorCode; use crate::host::network; use crate::network::SocketAddressFamily; -use crate::runtime::{with_ambient_tokio_runtime, AbortOnDropJoinHandle}; +use crate::runtime::{AbortOnDropJoinHandle, with_ambient_tokio_runtime}; use crate::{ HostInputStream, HostOutputStream, InputStream, OutputStream, SocketError, SocketResult, StreamError, Subscribe, @@ -9,8 +9,8 @@ use crate::{ use anyhow::Result; use cap_net_ext::AddressFamily; use futures::Future; -use io_lifetimes::views::SocketlikeView; use io_lifetimes::AsSocketlike; +use io_lifetimes::views::SocketlikeView; use rustix::io::Errno; use rustix::net::sockopt; use std::io; @@ -241,7 +241,7 @@ impl TcpSocket { TcpState::Default(..) | TcpState::Bound(..) => {} TcpState::Connecting(..) | TcpState::ConnectReady(..) => { - return Err(ErrorCode::ConcurrencyConflict.into()) + return Err(ErrorCode::ConcurrencyConflict.into()); } _ => return Err(ErrorCode::InvalidState.into()), @@ -473,7 +473,7 @@ impl TcpSocket { let view = match self.tcp_state { TcpState::Connected { .. } => self.as_std_view()?, TcpState::Connecting(..) | TcpState::ConnectReady(..) => { - return Err(ErrorCode::ConcurrencyConflict.into()) + return Err(ErrorCode::ConcurrencyConflict.into()); } _ => return Err(ErrorCode::InvalidState.into()), }; diff --git a/crates/wasi/tests/all/api.rs b/crates/wasi/tests/all/api.rs index 39d68a5f71a7..091b6c887477 100644 --- a/crates/wasi/tests/all/api.rs +++ b/crates/wasi/tests/all/api.rs @@ -4,13 +4,13 @@ use anyhow::Result; use std::io::Write; use std::sync::Mutex; use std::time::Duration; -use wasmtime::component::{Component, Linker, ResourceTable}; use wasmtime::Store; +use wasmtime::component::{Component, Linker, ResourceTable}; use wasmtime_wasi::bindings::Command; use wasmtime_wasi::{ + DirPerms, FilePerms, HostMonotonicClock, HostWallClock, WasiCtx, WasiCtxBuilder, WasiView, add_to_linker_async, bindings::{clocks::wall_clock, filesystem::types as filesystem}, - DirPerms, FilePerms, HostMonotonicClock, HostWallClock, WasiCtx, WasiCtxBuilder, WasiView, }; struct CommandCtx { diff --git a/crates/wasi/tests/all/main.rs b/crates/wasi/tests/all/main.rs index 19924d42c19a..0712e2dc336f 100644 --- a/crates/wasi/tests/all/main.rs +++ b/crates/wasi/tests/all/main.rs @@ -1,12 +1,12 @@ use anyhow::Result; use tempfile::TempDir; use wasmtime::{ - component::{Component, Linker, ResourceTable}, Engine, Store, + component::{Component, Linker, ResourceTable}, }; use wasmtime_wasi::preview1::WasiP1Ctx; use wasmtime_wasi::{ - pipe::MemoryOutputPipe, DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiView, + DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiView, pipe::MemoryOutputPipe, }; struct Ctx { diff --git a/crates/wasmtime/src/compile.rs b/crates/wasmtime/src/compile.rs index 1598bbf05e51..24f6255f8de0 100644 --- a/crates/wasmtime/src/compile.rs +++ b/crates/wasmtime/src/compile.rs @@ -22,14 +22,14 @@ //! functions. It is up to the caller to serialize the relevant parts of the //! `Artifacts` into the ELF file. +use crate::Engine; use crate::hash_map::HashMap; use crate::hash_set::HashSet; use crate::prelude::*; -use crate::Engine; use std::{ any::Any, borrow::Cow, - collections::{btree_map, BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, btree_map}, mem, }; @@ -131,10 +131,10 @@ pub(crate) fn build_component_artifacts( _dwarf_package: Option<&[u8]>, obj_state: &T::State, ) -> Result<(T, Option)> { + use wasmtime_environ::ScopeVec; use wasmtime_environ::component::{ CompiledComponentInfo, ComponentArtifacts, ComponentTypesBuilder, }; - use wasmtime_environ::ScopeVec; let tunables = engine.tunables(); let compiler = engine.compiler(); diff --git a/crates/wasmtime/src/compile/code_builder.rs b/crates/wasmtime/src/compile/code_builder.rs index d6b33fb25f1f..fb7737d82b9b 100644 --- a/crates/wasmtime/src/compile/code_builder.rs +++ b/crates/wasmtime/src/compile/code_builder.rs @@ -1,5 +1,5 @@ -use crate::prelude::*; use crate::Engine; +use crate::prelude::*; use std::borrow::Cow; use std::path::Path; diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs index 03a807484d96..26a59da38dc8 100644 --- a/crates/wasmtime/src/config.rs +++ b/crates/wasmtime/src/config.rs @@ -2305,7 +2305,9 @@ impl Config { .compiler_config .ensure_setting_unset_or_given("unwind_info", &unwind_requested.to_string()) { - bail!("incompatible settings requested for Cranelift and Wasmtime `unwind-info` settings"); + bail!( + "incompatible settings requested for Cranelift and Wasmtime `unwind-info` settings" + ); } } @@ -2354,7 +2356,9 @@ impl Config { .compiler_config .ensure_setting_unset_or_given("enable_safepoints", "true") { - bail!("compiler option 'enable_safepoints' must be enabled when 'reference types' is enabled"); + bail!( + "compiler option 'enable_safepoints' must be enabled when 'reference types' is enabled" + ); } } diff --git a/crates/wasmtime/src/engine.rs b/crates/wasmtime/src/engine.rs index 833b7cfb9f23..2da538e7f5f1 100644 --- a/crates/wasmtime/src/engine.rs +++ b/crates/wasmtime/src/engine.rs @@ -1,3 +1,4 @@ +use crate::Config; use crate::prelude::*; #[cfg(feature = "runtime")] pub use crate::runtime::code_memory::CustomCodeMemory; @@ -6,12 +7,11 @@ use crate::runtime::type_registry::TypeRegistry; #[cfg(feature = "runtime")] use crate::runtime::vm::GcRuntime; use crate::sync::OnceLock; -use crate::Config; use alloc::sync::Arc; use core::sync::atomic::{AtomicU64, Ordering}; +use object::SectionKind; #[cfg(any(feature = "cranelift", feature = "winch"))] use object::write::{Object, StandardSegment}; -use object::SectionKind; #[cfg(feature = "std")] use std::{fs::File, path::Path}; use wasmparser::WasmFeatures; @@ -429,14 +429,14 @@ impl Engine { Ok(()) } else { Err("wrong host pointer width".to_string()) - } + }; } FlagValue::Enum("pointer64") => { return if cfg!(target_pointer_width = "64") { Ok(()) } else { Err("wrong host pointer width".to_string()) - } + }; } // Only `bool` values are supported right now, other settings would @@ -444,7 +444,7 @@ impl Engine { _ => { return Err(format!( "isa-specific feature {flag:?} configured to unknown value {value:?}" - )) + )); } } @@ -493,7 +493,7 @@ impl Engine { // pulley features "big_endian" if cfg!(target_endian = "big") => return Ok(()), "big_endian" if cfg!(target_endian = "little") => { - return Err("wrong host endianness".to_string()) + return Err("wrong host endianness".to_string()); } _ => { @@ -515,7 +515,7 @@ impl Engine { "cannot determine if host feature {host_feature:?} is \ available at runtime, configure a probing function with \ `Config::detect_host_feature`" - )) + )); } }; diff --git a/crates/wasmtime/src/engine/serialization.rs b/crates/wasmtime/src/engine/serialization.rs index 6281c123aa4f..9f6baae213a7 100644 --- a/crates/wasmtime/src/engine/serialization.rs +++ b/crates/wasmtime/src/engine/serialization.rs @@ -27,7 +27,7 @@ use core::str::FromStr; use object::endian::Endianness; #[cfg(any(feature = "cranelift", feature = "winch"))] use object::write::{Object, StandardSegment}; -use object::{read::elf::ElfFile64, FileFlags, Object as _, ObjectSection, SectionKind}; +use object::{FileFlags, Object as _, ObjectSection, SectionKind, read::elf::ElfFile64}; use serde_derive::{Deserialize, Serialize}; use wasmtime_environ::obj; use wasmtime_environ::{FlagValue, ObjectKind, Tunables}; @@ -644,7 +644,7 @@ mod test { #[test] #[cfg(target_arch = "x86_64")] // test on a platform that is known to use - // Cranelift + // Cranelift fn test_os_mismatch() -> Result<()> { let engine = Engine::default(); let mut metadata = Metadata::new(&engine); @@ -725,7 +725,10 @@ Caused by: match metadata.check_compatible(&engine) { Ok(_) => unreachable!(), - Err(e) => assert_eq!(e.to_string(), "Module was compiled with a memory guard size of '0' but '33554432' is expected for the host"), + Err(e) => assert_eq!( + e.to_string(), + "Module was compiled with a memory guard size of '0' but '33554432' is expected for the host" + ), } Ok(()) @@ -768,7 +771,7 @@ Caused by: #[test] #[cfg(target_arch = "x86_64")] // test on a platform that is known to - // implement threads + // implement threads fn test_feature_mismatch() -> Result<()> { let mut config = Config::new(); config.wasm_threads(true); @@ -779,7 +782,10 @@ Caused by: match metadata.check_compatible(&engine) { Ok(_) => unreachable!(), - Err(e) => assert_eq!(e.to_string(), "Module was compiled without WebAssembly threads support but it is enabled for the host"), + Err(e) => assert_eq!( + e.to_string(), + "Module was compiled without WebAssembly threads support but it is enabled for the host" + ), } let mut config = Config::new(); @@ -791,7 +797,10 @@ Caused by: match metadata.check_compatible(&engine) { Ok(_) => unreachable!(), - Err(e) => assert_eq!(e.to_string(), "Module was compiled with WebAssembly threads support but it is not enabled for the host"), + Err(e) => assert_eq!( + e.to_string(), + "Module was compiled with WebAssembly threads support but it is not enabled for the host" + ), } Ok(()) diff --git a/crates/wasmtime/src/lib.rs b/crates/wasmtime/src/lib.rs index 757fe5f0f57c..ac0c0d6f21e5 100644 --- a/crates/wasmtime/src/lib.rs +++ b/crates/wasmtime/src/lib.rs @@ -297,7 +297,7 @@ extern crate alloc; pub(crate) mod prelude { pub use crate::{Error, Result}; - pub use anyhow::{anyhow, bail, ensure, format_err, Context}; + pub use anyhow::{Context, anyhow, bail, ensure, format_err}; pub use wasmtime_environ::prelude::*; } @@ -351,7 +351,7 @@ pub trait MaybeUninitExt { /// Note that this is `unsafe` as there is no guarantee that `U` comes from /// `T`. unsafe fn map(&mut self, f: impl FnOnce(*mut T) -> *mut U) - -> &mut core::mem::MaybeUninit; + -> &mut core::mem::MaybeUninit; } impl MaybeUninitExt for core::mem::MaybeUninit { diff --git a/crates/wasmtime/src/runtime/code.rs b/crates/wasmtime/src/runtime/code.rs index 5030d29623fc..952f44f7791f 100644 --- a/crates/wasmtime/src/runtime/code.rs +++ b/crates/wasmtime/src/runtime/code.rs @@ -1,8 +1,8 @@ use crate::{code_memory::CodeMemory, type_registry::TypeCollection}; use alloc::sync::Arc; +use wasmtime_environ::ModuleTypes; #[cfg(feature = "component-model")] use wasmtime_environ::component::ComponentTypes; -use wasmtime_environ::ModuleTypes; /// Metadata in Wasmtime about a loaded compiled artifact in memory which is /// ready to execute. diff --git a/crates/wasmtime/src/runtime/code_memory.rs b/crates/wasmtime/src/runtime/code_memory.rs index 390e851cac26..2e858cf9ccb5 100644 --- a/crates/wasmtime/src/runtime/code_memory.rs +++ b/crates/wasmtime/src/runtime/code_memory.rs @@ -1,14 +1,14 @@ //! Memory management for executable code. -use crate::prelude::*; -use crate::runtime::vm::{libcalls, MmapVec, UnwindRegistration}; use crate::Engine; +use crate::prelude::*; +use crate::runtime::vm::{MmapVec, UnwindRegistration, libcalls}; use alloc::sync::Arc; use core::ops::Range; use object::endian::Endianness; -use object::read::{elf::ElfFile64, Object, ObjectSection}; +use object::read::{Object, ObjectSection, elf::ElfFile64}; use object::{ObjectSymbol, SectionFlags}; -use wasmtime_environ::{lookup_trap_code, obj, Trap}; +use wasmtime_environ::{Trap, lookup_trap_code, obj}; /// Management of executable memory within a `MmapVec` /// diff --git a/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs b/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs index c8a756cd3de8..d61c9e7c964c 100644 --- a/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs +++ b/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs @@ -205,11 +205,11 @@ pub mod _1_world_imports; /// // ... /// } /// -/// # mod rand { pub fn thread_rng() -> G { G } pub struct G; impl G { pub fn gen(&self) -> u32 { 0 } } } +/// # mod rand { pub fn thread_rng() -> G { G } pub struct G; impl G { pub fn r#gen(&self) -> u32 { 0 } } } /// // Note that the trait here is per-interface and within a submodule now. /// impl my::project::host::Host for MyState { /// fn gen_random_integer(&mut self) -> u32 { -/// rand::thread_rng().gen() +/// rand::thread_rng().r#gen() /// } /// /// fn sha256(&mut self, bytes: Vec) -> String { diff --git a/crates/wasmtime/src/runtime/component/component.rs b/crates/wasmtime/src/runtime/component/component.rs index 10af60dc94ec..7ff1747c4306 100644 --- a/crates/wasmtime/src/runtime/component/component.rs +++ b/crates/wasmtime/src/runtime/component/component.rs @@ -1,6 +1,6 @@ +use crate::component::InstanceExportLookup; use crate::component::matching::InstanceType; use crate::component::types; -use crate::component::InstanceExportLookup; use crate::prelude::*; use crate::runtime::vm::component::ComponentRuntimeInfo; #[cfg(feature = "std")] @@ -9,8 +9,8 @@ use crate::runtime::vm::{ CompiledModuleId, VMArrayCallFunction, VMFuncRef, VMFunctionBody, VMWasmCallFunction, }; use crate::{ - code::CodeObject, code_memory::CodeMemory, type_registry::TypeCollection, Engine, Module, - ResourcesRequired, + Engine, Module, ResourcesRequired, code::CodeObject, code_memory::CodeMemory, + type_registry::TypeCollection, }; use crate::{FuncType, ValType}; use alloc::sync::Arc; @@ -722,13 +722,10 @@ impl Component { let item = self.with_uninstantiated_instance_type(|instance| { types::ComponentItem::from(&self.inner.engine, &ty, instance) }); - Some(( - item, - ComponentExportIndex { - id: self.inner.id, - index, - }, - )) + Some((item, ComponentExportIndex { + id: self.inner.id, + index, + })) } pub(crate) fn lookup_export_index( diff --git a/crates/wasmtime/src/runtime/component/func.rs b/crates/wasmtime/src/runtime/component/func.rs index 1bfcefff8e2b..46850ff7fa74 100644 --- a/crates/wasmtime/src/runtime/component/func.rs +++ b/crates/wasmtime/src/runtime/component/func.rs @@ -11,8 +11,8 @@ use alloc::sync::Arc; use core::mem::{self, MaybeUninit}; use core::ptr::NonNull; use wasmtime_environ::component::{ - CanonicalOptions, ComponentTypes, CoreDef, InterfaceType, RuntimeComponentInstanceIndex, - TypeFuncIndex, TypeTuple, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, + CanonicalOptions, ComponentTypes, CoreDef, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, + RuntimeComponentInstanceIndex, TypeFuncIndex, TypeTuple, }; mod host; diff --git a/crates/wasmtime/src/runtime/component/func/host.rs b/crates/wasmtime/src/runtime/component/func/host.rs index 3ab6581959b8..de934ca6cc8b 100644 --- a/crates/wasmtime/src/runtime/component/func/host.rs +++ b/crates/wasmtime/src/runtime/component/func/host.rs @@ -13,8 +13,8 @@ use core::any::Any; use core::mem::{self, MaybeUninit}; use core::ptr::NonNull; use wasmtime_environ::component::{ - CanonicalAbiInfo, ComponentTypes, InterfaceType, StringEncoding, TypeFuncIndex, - MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, + CanonicalAbiInfo, ComponentTypes, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, + StringEncoding, TypeFuncIndex, }; pub struct HostFunc { diff --git a/crates/wasmtime/src/runtime/component/func/options.rs b/crates/wasmtime/src/runtime/component/func/options.rs index ff58df0d5277..80cf2ead2e17 100644 --- a/crates/wasmtime/src/runtime/component/func/options.rs +++ b/crates/wasmtime/src/runtime/component/func/options.rs @@ -1,6 +1,6 @@ +use crate::component::ResourceType; use crate::component::matching::InstanceType; use crate::component::resources::{HostResourceData, HostResourceIndex, HostResourceTables}; -use crate::component::ResourceType; use crate::prelude::*; use crate::runtime::vm::component::{ CallContexts, ComponentInstance, InstanceFlags, ResourceTable, ResourceTables, diff --git a/crates/wasmtime/src/runtime/component/func/typed.rs b/crates/wasmtime/src/runtime/component/func/typed.rs index ecd38faad558..03a6f4d1db47 100644 --- a/crates/wasmtime/src/runtime/component/func/typed.rs +++ b/crates/wasmtime/src/runtime/component/func/typed.rs @@ -2,8 +2,8 @@ use crate::component::func::{Func, LiftContext, LowerContext, Options}; use crate::component::matching::InstanceType; use crate::component::storage::{storage_as_slice, storage_as_slice_mut}; use crate::prelude::*; -use crate::runtime::vm::component::ComponentInstance; use crate::runtime::vm::SendSyncPtr; +use crate::runtime::vm::component::ComponentInstance; use crate::{AsContextMut, StoreContext, StoreContextMut, ValRaw}; use alloc::borrow::Cow; use alloc::sync::Arc; @@ -13,8 +13,8 @@ use core::mem::{self, MaybeUninit}; use core::ptr::NonNull; use core::str; use wasmtime_environ::component::{ - CanonicalAbiInfo, ComponentTypes, InterfaceType, StringEncoding, VariantInfo, MAX_FLAT_PARAMS, - MAX_FLAT_RESULTS, + CanonicalAbiInfo, ComponentTypes, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS, + StringEncoding, VariantInfo, }; /// A statically-typed version of [`Func`] which takes `Params` as input and diff --git a/crates/wasmtime/src/runtime/component/instance.rs b/crates/wasmtime/src/runtime/component/instance.rs index bb7c337eb842..524206adfabe 100644 --- a/crates/wasmtime/src/runtime/component/instance.rs +++ b/crates/wasmtime/src/runtime/component/instance.rs @@ -13,7 +13,7 @@ use crate::{AsContextMut, Engine, Module, StoreContextMut}; use alloc::sync::Arc; use core::marker; use core::ptr::{self, NonNull}; -use wasmtime_environ::{component::*, EngineOrModuleTypeIndex}; +use wasmtime_environ::{EngineOrModuleTypeIndex, component::*}; use wasmtime_environ::{EntityIndex, EntityType, Global, PrimaryMap, WasmValType}; /// An instantiated component. diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rs index 31a3d5254884..eade60ffea1c 100644 --- a/crates/wasmtime/src/runtime/component/linker.rs +++ b/crates/wasmtime/src/runtime/component/linker.rs @@ -12,8 +12,8 @@ use alloc::sync::Arc; use core::future::Future; use core::marker; use core::pin::Pin; -use wasmtime_environ::component::{NameMap, NameMapIntern}; use wasmtime_environ::PrimaryMap; +use wasmtime_environ::component::{NameMap, NameMapIntern}; /// A type used to instantiate [`Component`]s. /// @@ -181,13 +181,10 @@ impl Linker { /// types imported by it replaced using imports present in [`Self`]. pub fn substituted_component_type(&self, component: &Component) -> Result { let cx = self.typecheck(&component)?; - Ok(types::Component::from( - component.ty(), - &InstanceType { - types: cx.types, - resources: &cx.imported_resources, - }, - )) + Ok(types::Component::from(component.ty(), &InstanceType { + types: cx.types, + resources: &cx.imported_resources, + })) } /// Performs a "pre-instantiation" to resolve the imports of the diff --git a/crates/wasmtime/src/runtime/component/matching.rs b/crates/wasmtime/src/runtime/component/matching.rs index 4222daa6dc62..4fd1b260424d 100644 --- a/crates/wasmtime/src/runtime/component/matching.rs +++ b/crates/wasmtime/src/runtime/component/matching.rs @@ -1,17 +1,17 @@ +use crate::Module; +use crate::component::ResourceType; use crate::component::func::HostFunc; use crate::component::linker::{Definition, Strings}; -use crate::component::ResourceType; use crate::prelude::*; use crate::runtime::vm::component::ComponentInstance; use crate::types::matching; -use crate::Module; use alloc::sync::Arc; use core::any::Any; +use wasmtime_environ::PrimaryMap; use wasmtime_environ::component::{ ComponentTypes, NameMap, ResourceIndex, TypeComponentInstance, TypeDef, TypeFuncIndex, TypeModule, TypeResourceTableIndex, }; -use wasmtime_environ::PrimaryMap; pub struct TypeChecker<'a> { pub types: &'a Arc, diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rs index 5c347102903a..59c6c1b479a7 100644 --- a/crates/wasmtime/src/runtime/component/mod.rs +++ b/crates/wasmtime/src/runtime/component/mod.rs @@ -134,13 +134,13 @@ pub use wasm_wave; #[doc(hidden)] pub mod __internal { pub use super::func::{ - bad_type_info, format_flags, lower_payload, typecheck_enum, typecheck_flags, - typecheck_record, typecheck_variant, ComponentVariant, LiftContext, LowerContext, Options, + ComponentVariant, LiftContext, LowerContext, Options, bad_type_info, format_flags, + lower_payload, typecheck_enum, typecheck_flags, typecheck_record, typecheck_variant, }; pub use super::matching::InstanceType; + pub use crate::MaybeUninitExt; pub use crate::map_maybe_uninit; pub use crate::store::StoreOpaque; - pub use crate::MaybeUninitExt; pub use alloc::boxed::Box; pub use alloc::string::String; pub use alloc::vec::Vec; diff --git a/crates/wasmtime/src/runtime/component/resource_table.rs b/crates/wasmtime/src/runtime/component/resource_table.rs index cceb65c20cd4..9cdc71d70cb9 100644 --- a/crates/wasmtime/src/runtime/component/resource_table.rs +++ b/crates/wasmtime/src/runtime/component/resource_table.rs @@ -141,12 +141,9 @@ impl ResourceTable { /// Free an entry in the table, returning its [`TableEntry`]. Add the index to the free list. fn free_entry(&mut self, ix: usize) -> TableEntry { - let entry = match core::mem::replace( - &mut self.entries[ix], - Entry::Free { - next: self.free_head, - }, - ) { + let entry = match core::mem::replace(&mut self.entries[ix], Entry::Free { + next: self.free_head, + }) { Entry::Occupied { entry } => entry, Entry::Free { .. } => unreachable!(), }; diff --git a/crates/wasmtime/src/runtime/component/resources.rs b/crates/wasmtime/src/runtime/component/resources.rs index ffbafdd2d382..8289e706abfd 100644 --- a/crates/wasmtime/src/runtime/component/resources.rs +++ b/crates/wasmtime/src/runtime/component/resources.rs @@ -1,4 +1,4 @@ -use crate::component::func::{bad_type_info, desc, LiftContext, LowerContext}; +use crate::component::func::{LiftContext, LowerContext, bad_type_info, desc}; use crate::component::matching::InstanceType; use crate::component::{ComponentType, Lift, Lower}; use crate::prelude::*; diff --git a/crates/wasmtime/src/runtime/component/types.rs b/crates/wasmtime/src/runtime/component/types.rs index 0d63bd664625..d4fbed4f1295 100644 --- a/crates/wasmtime/src/runtime/component/types.rs +++ b/crates/wasmtime/src/runtime/component/types.rs @@ -5,13 +5,13 @@ use crate::{Engine, ExternType, FuncType}; use alloc::sync::Arc; use core::fmt; use core::ops::Deref; +use wasmtime_environ::PrimaryMap; use wasmtime_environ::component::{ ComponentTypes, InterfaceType, ResourceIndex, TypeComponentIndex, TypeComponentInstanceIndex, TypeDef, TypeEnumIndex, TypeFlagsIndex, TypeFuncIndex, TypeListIndex, TypeModuleIndex, TypeOptionIndex, TypeRecordIndex, TypeResourceTableIndex, TypeResultIndex, TypeTupleIndex, TypeVariantIndex, }; -use wasmtime_environ::PrimaryMap; pub use crate::component::resources::ResourceType; diff --git a/crates/wasmtime/src/runtime/component/values.rs b/crates/wasmtime/src/runtime/component/values.rs index 5c0ed9250164..f86e0f90b8cf 100644 --- a/crates/wasmtime/src/runtime/component/values.rs +++ b/crates/wasmtime/src/runtime/component/values.rs @@ -1,7 +1,7 @@ -use crate::component::func::{desc, Lift, LiftContext, Lower, LowerContext}; +use crate::ValRaw; use crate::component::ResourceAny; +use crate::component::func::{Lift, LiftContext, Lower, LowerContext, desc}; use crate::prelude::*; -use crate::ValRaw; use core::mem::MaybeUninit; use core::slice::{Iter, IterMut}; use wasmtime_component_util::{DiscriminantSize, FlagsSize}; diff --git a/crates/wasmtime/src/runtime/coredump.rs b/crates/wasmtime/src/runtime/coredump.rs index 4101c4c26b55..b88d0dae7c5c 100644 --- a/crates/wasmtime/src/runtime/coredump.rs +++ b/crates/wasmtime/src/runtime/coredump.rs @@ -1,8 +1,8 @@ use crate::hash_map::HashMap; use crate::prelude::*; use crate::{ - store::StoreOpaque, AsContextMut, FrameInfo, Global, HeapType, Instance, Memory, Module, - StoreContextMut, Val, ValType, WasmBacktrace, + AsContextMut, FrameInfo, Global, HeapType, Instance, Memory, Module, StoreContextMut, Val, + ValType, WasmBacktrace, store::StoreOpaque, }; use std::fmt; diff --git a/crates/wasmtime/src/runtime/externals/global.rs b/crates/wasmtime/src/runtime/externals/global.rs index 785376632bb6..6854763d18de 100644 --- a/crates/wasmtime/src/runtime/externals/global.rs +++ b/crates/wasmtime/src/runtime/externals/global.rs @@ -1,10 +1,10 @@ use crate::prelude::*; use crate::runtime::vm::{GcRootsList, SendSyncPtr}; use crate::{ - store::{AutoAssertNoGc, StoreData, StoreOpaque, Stored}, - trampoline::generate_global_export, AnyRef, AsContext, AsContextMut, ExternRef, Func, GlobalType, HeapType, Mutability, Ref, RootedGcRefImpl, Val, ValType, + store::{AutoAssertNoGc, StoreData, StoreOpaque, Stored}, + trampoline::generate_global_export, }; use core::ptr; use core::ptr::NonNull; diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs index edf7264641a3..a54f3a996ab4 100644 --- a/crates/wasmtime/src/runtime/func.rs +++ b/crates/wasmtime/src/runtime/func.rs @@ -1,9 +1,9 @@ use crate::prelude::*; +use crate::runtime::Uninhabited; use crate::runtime::vm::{ ExportFunction, InterpreterRef, SendSyncPtr, StoreBox, VMArrayCallHostFuncContext, VMContext, VMFuncRef, VMFunctionImport, VMOpaqueContext, }; -use crate::runtime::Uninhabited; use crate::store::{AutoAssertNoGc, StoreData, StoreOpaque, Stored}; use crate::type_registry::RegisteredType; use crate::{ diff --git a/crates/wasmtime/src/runtime/func/typed.rs b/crates/wasmtime/src/runtime/func/typed.rs index 5c31182e6b2e..47e24888f590 100644 --- a/crates/wasmtime/src/runtime/func/typed.rs +++ b/crates/wasmtime/src/runtime/func/typed.rs @@ -599,7 +599,9 @@ unsafe impl WasmTy for Option { } else if nullable { Ok(()) } else { - bail!("argument type mismatch: expected non-nullable (ref {expected}), found null reference") + bail!( + "argument type mismatch: expected non-nullable (ref {expected}), found null reference" + ) } } diff --git a/crates/wasmtime/src/runtime/gc/disabled/anyref.rs b/crates/wasmtime/src/runtime/gc/disabled/anyref.rs index 097fc96399dd..c49143496075 100644 --- a/crates/wasmtime/src/runtime/gc/disabled/anyref.rs +++ b/crates/wasmtime/src/runtime/gc/disabled/anyref.rs @@ -1,8 +1,8 @@ use crate::runtime::vm::VMGcRef; use crate::{ + ArrayRef, AsContext, AsContextMut, EqRef, GcRefImpl, HeapType, I31, ManuallyRooted, Result, + Rooted, StructRef, store::{AutoAssertNoGc, StoreOpaque}, - ArrayRef, AsContext, AsContextMut, EqRef, GcRefImpl, HeapType, ManuallyRooted, Result, Rooted, - StructRef, I31, }; /// Support for `anyref` disabled at compile time because the `gc` cargo feature diff --git a/crates/wasmtime/src/runtime/gc/disabled/arrayref.rs b/crates/wasmtime/src/runtime/gc/disabled/arrayref.rs index 53679b8994cd..3b772bb9c671 100644 --- a/crates/wasmtime/src/runtime/gc/disabled/arrayref.rs +++ b/crates/wasmtime/src/runtime/gc/disabled/arrayref.rs @@ -1,7 +1,7 @@ use crate::runtime::vm::VMGcRef; use crate::{ + ArrayType, AsContext, AsContextMut, GcRefImpl, I31, Result, Rooted, Val, store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, - ArrayType, AsContext, AsContextMut, GcRefImpl, Result, Rooted, Val, I31, }; /// Support for `ArrayRefPre` disabled at compile time because the `gc` cargo diff --git a/crates/wasmtime/src/runtime/gc/disabled/eqref.rs b/crates/wasmtime/src/runtime/gc/disabled/eqref.rs index 460653402bbd..caa2467714c3 100644 --- a/crates/wasmtime/src/runtime/gc/disabled/eqref.rs +++ b/crates/wasmtime/src/runtime/gc/disabled/eqref.rs @@ -1,8 +1,8 @@ use crate::runtime::vm::VMGcRef; use crate::{ + ArrayRef, AsContext, AsContextMut, GcRefImpl, HeapType, I31, ManuallyRooted, Result, Rooted, + StructRef, store::{AutoAssertNoGc, StoreOpaque}, - ArrayRef, AsContext, AsContextMut, GcRefImpl, HeapType, ManuallyRooted, Result, Rooted, - StructRef, I31, }; /// Support for `eqref` disabled at compile time because the `gc` cargo feature diff --git a/crates/wasmtime/src/runtime/gc/disabled/externref.rs b/crates/wasmtime/src/runtime/gc/disabled/externref.rs index 55ef89e09a2d..0800106618e4 100644 --- a/crates/wasmtime/src/runtime/gc/disabled/externref.rs +++ b/crates/wasmtime/src/runtime/gc/disabled/externref.rs @@ -1,6 +1,6 @@ use crate::runtime::vm::VMGcRef; use crate::{ - store::AutoAssertNoGc, AsContextMut, GcRefImpl, Result, Rooted, StoreContext, StoreContextMut, + AsContextMut, GcRefImpl, Result, Rooted, StoreContext, StoreContextMut, store::AutoAssertNoGc, }; use core::any::Any; diff --git a/crates/wasmtime/src/runtime/gc/disabled/rooting.rs b/crates/wasmtime/src/runtime/gc/disabled/rooting.rs index 84ac4c6eba00..ed88fdd0baea 100644 --- a/crates/wasmtime/src/runtime/gc/disabled/rooting.rs +++ b/crates/wasmtime/src/runtime/gc/disabled/rooting.rs @@ -1,9 +1,9 @@ use crate::prelude::*; use crate::runtime::vm::{GcStore, VMGcRef}; use crate::{ + AsContext, AsContextMut, GcRef, Result, RootedGcRef, runtime::Uninhabited, store::{AutoAssertNoGc, StoreOpaque}, - AsContext, AsContextMut, GcRef, Result, RootedGcRef, }; use core::any::Any; use core::ffi::c_void; diff --git a/crates/wasmtime/src/runtime/gc/disabled/structref.rs b/crates/wasmtime/src/runtime/gc/disabled/structref.rs index af47636f7ce9..437405e95367 100644 --- a/crates/wasmtime/src/runtime/gc/disabled/structref.rs +++ b/crates/wasmtime/src/runtime/gc/disabled/structref.rs @@ -1,7 +1,7 @@ use crate::runtime::vm::VMGcRef; use crate::{ + AsContext, AsContextMut, GcRefImpl, I31, Result, Rooted, StructType, Val, store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, - AsContext, AsContextMut, GcRefImpl, Result, Rooted, StructType, Val, I31, }; /// Support for `StructRefPre` disabled at compile time because the `gc` cargo diff --git a/crates/wasmtime/src/runtime/gc/enabled/anyref.rs b/crates/wasmtime/src/runtime/gc/enabled/anyref.rs index 82efee808936..a1f0b42b6dc2 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/anyref.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/anyref.rs @@ -4,9 +4,9 @@ use super::{ExternRef, RootedGcRefImpl}; use crate::prelude::*; use crate::runtime::vm::VMGcRef; use crate::{ + ArrayRef, ArrayType, AsContext, AsContextMut, EqRef, GcRefImpl, GcRootIndex, HeapType, I31, + ManuallyRooted, RefType, Result, Rooted, StructRef, StructType, ValRaw, ValType, WasmTy, store::{AutoAssertNoGc, StoreOpaque}, - ArrayRef, ArrayType, AsContext, AsContextMut, EqRef, GcRefImpl, GcRootIndex, HeapType, - ManuallyRooted, RefType, Result, Rooted, StructRef, StructType, ValRaw, ValType, WasmTy, I31, }; use core::mem; use core::mem::MaybeUninit; @@ -145,12 +145,9 @@ unsafe impl GcRefImpl for AnyRef { let me: &Self = unsafe { mem::transmute(index) }; // Assert we really are just a newtype of a `GcRootIndex`. - assert!(matches!( - me, - Self { - inner: GcRootIndex { .. }, - } - )); + assert!(matches!(me, Self { + inner: GcRootIndex { .. }, + })); me } diff --git a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs index 14ee5b783856..4147f501d99d 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs @@ -3,13 +3,13 @@ use crate::runtime::vm::VMGcRef; use crate::store::StoreId; use crate::vm::{VMArrayRef, VMGcHeader}; +use crate::{AnyRef, FieldType}; use crate::{ - prelude::*, - store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, ArrayType, AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType, ManuallyRooted, RefType, Rooted, Val, ValRaw, ValType, WasmTy, + prelude::*, + store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, }; -use crate::{AnyRef, FieldType}; use core::mem::{self, MaybeUninit}; use wasmtime_environ::{GcArrayLayout, GcLayout, VMGcKind, VMSharedTypeIndex}; @@ -189,12 +189,9 @@ unsafe impl GcRefImpl for ArrayRef { let me: &Self = unsafe { mem::transmute(index) }; // Assert we really are just a newtype of a `GcRootIndex`. - assert!(matches!( - me, - Self { - inner: GcRootIndex { .. }, - } - )); + assert!(matches!(me, Self { + inner: GcRootIndex { .. }, + })); me } diff --git a/crates/wasmtime/src/runtime/gc/enabled/eqref.rs b/crates/wasmtime/src/runtime/gc/enabled/eqref.rs index f24e74aa4a0d..f551790a4a57 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/eqref.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/eqref.rs @@ -1,11 +1,11 @@ //! Working with GC `eqref`s. use crate::{ + AnyRef, ArrayRef, ArrayType, AsContext, GcRefImpl, GcRootIndex, HeapType, I31, ManuallyRooted, + RefType, Rooted, StructRef, StructType, ValRaw, ValType, WasmTy, prelude::*, runtime::vm::VMGcRef, store::{AutoAssertNoGc, StoreOpaque}, - AnyRef, ArrayRef, ArrayType, AsContext, GcRefImpl, GcRootIndex, HeapType, ManuallyRooted, - RefType, Rooted, StructRef, StructType, ValRaw, ValType, WasmTy, I31, }; use core::mem::{self, MaybeUninit}; use wasmtime_environ::VMGcKind; @@ -127,12 +127,9 @@ unsafe impl GcRefImpl for EqRef { let me: &Self = unsafe { mem::transmute(index) }; // Assert we really are just a newtype of a `GcRootIndex`. - assert!(matches!( - me, - Self { - inner: GcRootIndex { .. }, - } - )); + assert!(matches!(me, Self { + inner: GcRootIndex { .. }, + })); me } diff --git a/crates/wasmtime/src/runtime/gc/enabled/externref.rs b/crates/wasmtime/src/runtime/gc/enabled/externref.rs index 995477f2fa73..dc2a96a7e9da 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/externref.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/externref.rs @@ -4,9 +4,9 @@ use super::{AnyRef, RootedGcRefImpl}; use crate::prelude::*; use crate::runtime::vm::VMGcRef; use crate::{ - store::{AutoAssertNoGc, StoreOpaque}, AsContextMut, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType, ManuallyRooted, RefType, Result, Rooted, StoreContext, StoreContextMut, ValRaw, ValType, WasmTy, + store::{AutoAssertNoGc, StoreOpaque}, }; use core::any::Any; use core::mem; @@ -125,12 +125,9 @@ unsafe impl GcRefImpl for ExternRef { let me: &Self = unsafe { mem::transmute(index) }; // Assert we really are just a newtype of a `GcRootIndex`. - assert!(matches!( - me, - Self { - inner: GcRootIndex { .. }, - } - )); + assert!(matches!(me, Self { + inner: GcRootIndex { .. }, + })); me } diff --git a/crates/wasmtime/src/runtime/gc/enabled/i31.rs b/crates/wasmtime/src/runtime/gc/enabled/i31.rs index 6b739513dc07..85c4bce6e952 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/i31.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/i31.rs @@ -6,8 +6,8 @@ use crate::runtime::vm::{VMGcRef, ValRaw}; use crate::{ - store::{AutoAssertNoGc, StoreOpaque}, HeapType, RefType, Result, ValType, WasmTy, + store::{AutoAssertNoGc, StoreOpaque}, }; use core::fmt; use core::mem::MaybeUninit; diff --git a/crates/wasmtime/src/runtime/gc/enabled/rooting.rs b/crates/wasmtime/src/runtime/gc/enabled/rooting.rs index ae525854adca..88d97120827a 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/rooting.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/rooting.rs @@ -104,11 +104,11 @@ use crate::runtime::vm::{GcRootsList, GcStore, VMGcRef}; use crate::vm::VMStore; -use crate::{prelude::*, ValRaw}; use crate::{ - store::{AutoAssertNoGc, StoreId, StoreOpaque}, AsContext, AsContextMut, GcRef, Result, RootedGcRef, + store::{AutoAssertNoGc, StoreId, StoreOpaque}, }; +use crate::{ValRaw, prelude::*}; use core::any; use core::marker; use core::mem::{self, MaybeUninit}; diff --git a/crates/wasmtime/src/runtime/gc/enabled/structref.rs b/crates/wasmtime/src/runtime/gc/enabled/structref.rs index e111c2f2e633..fdc7a250594a 100644 --- a/crates/wasmtime/src/runtime/gc/enabled/structref.rs +++ b/crates/wasmtime/src/runtime/gc/enabled/structref.rs @@ -3,13 +3,13 @@ use crate::runtime::vm::VMGcRef; use crate::store::StoreId; use crate::vm::{VMGcHeader, VMStructRef}; +use crate::{AnyRef, FieldType}; use crate::{ - prelude::*, - store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType, ManuallyRooted, RefType, Rooted, StructType, Val, ValRaw, ValType, WasmTy, + prelude::*, + store::{AutoAssertNoGc, StoreContextMut, StoreOpaque}, }; -use crate::{AnyRef, FieldType}; use core::mem::{self, MaybeUninit}; use wasmtime_environ::{GcLayout, GcStructLayout, VMGcKind, VMSharedTypeIndex}; @@ -172,12 +172,9 @@ unsafe impl GcRefImpl for StructRef { let me: &Self = unsafe { mem::transmute(index) }; // Assert we really are just a newtype of a `GcRootIndex`. - assert!(matches!( - me, - Self { - inner: GcRootIndex { .. }, - } - )); + assert!(matches!(me, Self { + inner: GcRootIndex { .. }, + })); me } diff --git a/crates/wasmtime/src/runtime/gc/noextern.rs b/crates/wasmtime/src/runtime/gc/noextern.rs index 9cbe765262af..e022fb2ca32b 100644 --- a/crates/wasmtime/src/runtime/gc/noextern.rs +++ b/crates/wasmtime/src/runtime/gc/noextern.rs @@ -1,6 +1,6 @@ use crate::{ - store::{AutoAssertNoGc, StoreOpaque}, HeapType, Ref, RefType, Result, Uninhabited, Val, ValRaw, ValType, WasmTy, + store::{AutoAssertNoGc, StoreOpaque}, }; use core::mem::MaybeUninit; diff --git a/crates/wasmtime/src/runtime/gc/none_ref.rs b/crates/wasmtime/src/runtime/gc/none_ref.rs index 17cd47587480..f4c98856edc9 100644 --- a/crates/wasmtime/src/runtime/gc/none_ref.rs +++ b/crates/wasmtime/src/runtime/gc/none_ref.rs @@ -1,6 +1,6 @@ use crate::{ - store::{AutoAssertNoGc, StoreOpaque}, HeapType, Ref, RefType, Result, Uninhabited, Val, ValRaw, ValType, WasmTy, + store::{AutoAssertNoGc, StoreOpaque}, }; use core::mem::MaybeUninit; diff --git a/crates/wasmtime/src/runtime/linker.rs b/crates/wasmtime/src/runtime/linker.rs index 95cbb548447b..44ee7a344d37 100644 --- a/crates/wasmtime/src/runtime/linker.rs +++ b/crates/wasmtime/src/runtime/linker.rs @@ -2,11 +2,11 @@ use crate::func::HostFunc; use crate::hash_map::{Entry, HashMap}; use crate::instance::InstancePre; use crate::store::StoreOpaque; -use crate::{prelude::*, IntoFunc}; use crate::{ AsContext, AsContextMut, Caller, Engine, Extern, ExternType, Func, FuncType, ImportType, Instance, Module, StoreContextMut, Val, ValRaw, ValType, WasmTyList, }; +use crate::{IntoFunc, prelude::*}; use alloc::sync::Arc; use core::fmt; #[cfg(feature = "async")] @@ -950,7 +950,9 @@ impl Linker { } else if export.name() == "__rtti_base" && export.ty().global().is_some() { // Allow an exported "__rtti_base" memory for compatibility with // AssemblyScript. - warn!("command module exporting '__rtti_base' is deprecated; pass `--runtime half` to the AssemblyScript compiler"); + warn!( + "command module exporting '__rtti_base' is deprecated; pass `--runtime half` to the AssemblyScript compiler" + ); } else if !self.allow_unknown_exports { bail!("command export '{}' is not a function", export.name()); } diff --git a/crates/wasmtime/src/runtime/memory.rs b/crates/wasmtime/src/runtime/memory.rs index 57f6c2a01f35..e14bfccc8192 100644 --- a/crates/wasmtime/src/runtime/memory.rs +++ b/crates/wasmtime/src/runtime/memory.rs @@ -1,8 +1,8 @@ +use crate::Trap; use crate::prelude::*; use crate::runtime::vm::VMMemoryImport; use crate::store::{StoreData, StoreOpaque, Stored}; use crate::trampoline::generate_memory_export; -use crate::Trap; use crate::{AsContext, AsContextMut, Engine, MemoryType, StoreContext, StoreContextMut}; use core::cell::UnsafeCell; use core::fmt; @@ -116,35 +116,43 @@ impl std::error::Error for MemoryAccessError {} /// // First and foremost, any borrow can be invalidated at any time via the /// // `Memory::grow` function. This can relocate memory which causes any /// // previous pointer to be possibly invalid now. -/// let pointer: &u8 = &*mem.data_ptr(&store); -/// mem.grow(&mut *store, 1)?; // invalidates `pointer`! -/// // println!("{}", *pointer); // FATAL: use-after-free +/// unsafe { +/// let pointer: &u8 = &*mem.data_ptr(&store); +/// mem.grow(&mut *store, 1)?; // invalidates `pointer`! +/// // println!("{}", *pointer); // FATAL: use-after-free +/// } /// /// // Note that the use-after-free also applies to slices, whether they're /// // slices of bytes or strings. -/// let mem_slice = std::slice::from_raw_parts( -/// mem.data_ptr(&store), -/// mem.data_size(&store), -/// ); -/// let slice: &[u8] = &mem_slice[0x100..0x102]; -/// mem.grow(&mut *store, 1)?; // invalidates `slice`! -/// // println!("{:?}", slice); // FATAL: use-after-free +/// unsafe { +/// let mem_slice = std::slice::from_raw_parts( +/// mem.data_ptr(&store), +/// mem.data_size(&store), +/// ); +/// let slice: &[u8] = &mem_slice[0x100..0x102]; +/// mem.grow(&mut *store, 1)?; // invalidates `slice`! +/// // println!("{:?}", slice); // FATAL: use-after-free +/// } /// /// // The `Memory` type may be stored in other locations, so if you hand /// // off access to the `Store` then those locations may also call /// // `Memory::grow` or similar, so it's not enough to just audit code for /// // calls to `Memory::grow`. -/// let pointer: &u8 = &*mem.data_ptr(&store); -/// some_other_function(store); // may invalidate `pointer` through use of `store` -/// // println!("{:?}", pointer); // FATAL: maybe a use-after-free +/// unsafe { +/// let pointer: &u8 = &*mem.data_ptr(&store); +/// some_other_function(store); // may invalidate `pointer` through use of `store` +/// // println!("{:?}", pointer); // FATAL: maybe a use-after-free +/// } /// /// // An especially subtle aspect of accessing a wasm instance's memory is /// // that you need to be extremely careful about aliasing. Anyone at any /// // time can call `data_unchecked()` or `data_unchecked_mut()`, which /// // means you can easily have aliasing mutable references: -/// let ref1: &u8 = &*mem.data_ptr(&store).add(0x100); -/// let ref2: &mut u8 = &mut *mem.data_ptr(&store).add(0x100); -/// // *ref2 = *ref1; // FATAL: violates Rust's aliasing rules +/// unsafe { +/// let ref1: &u8 = &*mem.data_ptr(&store).add(0x100); +/// let ref2: &mut u8 = &mut *mem.data_ptr(&store).add(0x100); +/// // *ref2 = *ref1; // FATAL: violates Rust's aliasing rules +/// } /// /// Ok(()) /// } diff --git a/crates/wasmtime/src/runtime/module.rs b/crates/wasmtime/src/runtime/module.rs index 9f2c99a540b9..0d285437e1b3 100644 --- a/crates/wasmtime/src/runtime/module.rs +++ b/crates/wasmtime/src/runtime/module.rs @@ -4,13 +4,13 @@ use crate::runtime::vm::open_file_for_mmap; use crate::runtime::vm::{CompiledModuleId, MmapVec, ModuleMemoryImages, VMWasmCallFunction}; use crate::sync::OnceLock; use crate::{ + Engine, code::CodeObject, code_memory::CodeMemory, instantiate::CompiledModule, resources::ResourcesRequired, type_registry::TypeCollection, types::{ExportType, ExternType, ImportType}, - Engine, }; use alloc::sync::Arc; use core::fmt; @@ -1061,20 +1061,21 @@ impl Module { .code .signatures() .trampoline_type(trampoline_shared_ty)?; - debug_assert!(self - .inner - .engine - .signatures() - .borrow( - self.inner - .code - .signatures() - .shared_type(trampoline_module_ty) - .unwrap() - ) - .unwrap() - .unwrap_func() - .is_trampoline_type()); + debug_assert!( + self.inner + .engine + .signatures() + .borrow( + self.inner + .code + .signatures() + .shared_type(trampoline_module_ty) + .unwrap() + ) + .unwrap() + .unwrap_func() + .is_trampoline_type() + ); let ptr = self .compiled_module() diff --git a/crates/wasmtime/src/runtime/module/registry.rs b/crates/wasmtime/src/runtime/module/registry.rs index d6ec479c5839..5c92ebe62d21 100644 --- a/crates/wasmtime/src/runtime/module/registry.rs +++ b/crates/wasmtime/src/runtime/module/registry.rs @@ -6,7 +6,7 @@ use crate::component::Component; use crate::prelude::*; use crate::runtime::vm::VMWasmCallFunction; use crate::sync::{OnceLock, RwLock}; -use crate::{code_memory::CodeMemory, FrameInfo, Module}; +use crate::{FrameInfo, Module, code_memory::CodeMemory}; use alloc::collections::btree_map::{BTreeMap, Entry}; use alloc::sync::Arc; use core::ptr::NonNull; diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs index 512e520836ef..ceaae58589f9 100644 --- a/crates/wasmtime/src/runtime/store.rs +++ b/crates/wasmtime/src/runtime/store.rs @@ -76,6 +76,7 @@ //! contents of `StoreOpaque`. This is an invariant that we, as the authors of //! `wasmtime`, must uphold for the public interface to be safe. +use crate::RootSet; use crate::hash_set::HashSet; use crate::instance::InstanceData; use crate::linker::Definition; @@ -90,8 +91,7 @@ use crate::runtime::vm::{ }; use crate::trampoline::VMHostGlobalContext; use crate::type_registry::RegisteredType; -use crate::RootSet; -use crate::{module::ModuleRegistry, Engine, Module, Trap, Val, ValRaw}; +use crate::{Engine, Module, Trap, Val, ValRaw, module::ModuleRegistry}; use crate::{Global, Instance, Memory, RootScope, Table, Uninhabited}; use alloc::sync::Arc; use core::cell::UnsafeCell; @@ -783,9 +783,9 @@ impl Store { pub fn limiter_async( &mut self, mut limiter: impl FnMut(&mut T) -> &mut (dyn crate::ResourceLimiterAsync) - + Send - + Sync - + 'static, + + Send + + Sync + + 'static, ) { debug_assert!(self.inner.async_support()); // Apply the limits on instances, tables, and memory given by the limiter: diff --git a/crates/wasmtime/src/runtime/trampoline/memory.rs b/crates/wasmtime/src/runtime/trampoline/memory.rs index dd2f93f178bb..b9754a2becc7 100644 --- a/crates/wasmtime/src/runtime/trampoline/memory.rs +++ b/crates/wasmtime/src/runtime/trampoline/memory.rs @@ -1,3 +1,4 @@ +use crate::MemoryType; use crate::memory::{LinearMemory, MemoryCreator}; use crate::prelude::*; use crate::runtime::vm::mpk::ProtectionKey; @@ -8,7 +9,6 @@ use crate::runtime::vm::{ Table, TableAllocationIndex, }; use crate::store::{InstanceId, StoreOpaque}; -use crate::MemoryType; use alloc::sync::Arc; use wasmtime_environ::{ DefinedMemoryIndex, DefinedTableIndex, EntityIndex, HostPtr, Module, Tunables, VMOffsets, @@ -16,8 +16,8 @@ use wasmtime_environ::{ #[cfg(feature = "component-model")] use wasmtime_environ::{ - component::{Component, VMComponentOffsets}, StaticModuleIndex, + component::{Component, VMComponentOffsets}, }; /// Create a "frankenstein" instance with a single memory. diff --git a/crates/wasmtime/src/runtime/trampoline/table.rs b/crates/wasmtime/src/runtime/trampoline/table.rs index 0edd10810481..a5fb37a3881c 100644 --- a/crates/wasmtime/src/runtime/trampoline/table.rs +++ b/crates/wasmtime/src/runtime/trampoline/table.rs @@ -1,7 +1,7 @@ +use crate::TableType; use crate::prelude::*; use crate::store::{InstanceId, StoreOpaque}; use crate::trampoline::create_handle; -use crate::TableType; use wasmtime_environ::{EntityIndex, Module, TypeTrace}; pub fn create_table(store: &mut StoreOpaque, table: &TableType) -> Result { diff --git a/crates/wasmtime/src/runtime/trap.rs b/crates/wasmtime/src/runtime/trap.rs index 413cb33f8dfc..951cddcfe912 100644 --- a/crates/wasmtime/src/runtime/trap.rs +++ b/crates/wasmtime/src/runtime/trap.rs @@ -4,7 +4,7 @@ use crate::prelude::*; use crate::store::StoreOpaque; use crate::{AsContext, Module}; use core::fmt; -use wasmtime_environ::{demangle_function_name, demangle_function_name_or_index, FilePos}; +use wasmtime_environ::{FilePos, demangle_function_name, demangle_function_name_or_index}; /// Representation of a WebAssembly trap and what caused it to occur. /// @@ -394,7 +394,10 @@ impl fmt::Display for WasmBacktrace { } } if self.hint_wasm_backtrace_details_env { - write!(f, "\nnote: using the `WASMTIME_BACKTRACE_DETAILS=1` environment variable may show more debugging information")?; + write!( + f, + "\nnote: using the `WASMTIME_BACKTRACE_DETAILS=1` environment variable may show more debugging information" + )?; } Ok(()) } diff --git a/crates/wasmtime/src/runtime/type_registry.rs b/crates/wasmtime/src/runtime/type_registry.rs index 0a10b88e8f29..61e774ea4002 100644 --- a/crates/wasmtime/src/runtime/type_registry.rs +++ b/crates/wasmtime/src/runtime/type_registry.rs @@ -3,11 +3,11 @@ //! Helps implement fast indirect call signature checking, reference type //! downcasting, and etc... +use crate::Engine; use crate::hash_set::HashSet; use crate::prelude::*; use crate::sync::RwLock; use crate::vm::GcRuntime; -use crate::Engine; use alloc::borrow::Cow; use alloc::sync::Arc; use core::iter; @@ -22,10 +22,9 @@ use core::{ }, }; use wasmtime_environ::{ - iter_entity_range, - packed_option::{PackedOption, ReservedValue}, EngineOrModuleTypeIndex, GcLayout, ModuleInternedTypeIndex, ModuleTypes, PrimaryMap, - SecondaryMap, TypeTrace, VMSharedTypeIndex, WasmRecGroup, WasmSubType, + SecondaryMap, TypeTrace, VMSharedTypeIndex, WasmRecGroup, WasmSubType, iter_entity_range, + packed_option::{PackedOption, ReservedValue}, }; use wasmtime_slab::{Id as SlabId, Slab}; @@ -125,7 +124,9 @@ impl TypeCollection { let shared_ty = types[module_ty]; let trampoline_shared_ty = registry.trampoline_type(shared_ty); trampolines[trampoline_shared_ty] = Some(module_trampoline_ty).into(); - log::trace!("--> shared_to_module_trampolines[{trampoline_shared_ty:?}] = {module_trampoline_ty:?}"); + log::trace!( + "--> shared_to_module_trampolines[{trampoline_shared_ty:?}] = {module_trampoline_ty:?}" + ); } log::trace!("Done building module's shared-to-module-trampoline-types map"); @@ -732,9 +733,8 @@ impl TypeRegistryInner { // This will recursively call into rec group // registration, but at most once since trampoline // function types are their own trampoline type. - let trampoline_entry = self.register_singleton_rec_group( - gc_runtime, - WasmSubType { + let trampoline_entry = + self.register_singleton_rec_group(gc_runtime, WasmSubType { is_final: true, supertype: None, composite_type: wasmtime_environ::WasmCompositeType { @@ -743,8 +743,7 @@ impl TypeRegistryInner { trampoline.into_owned(), ), }, - }, - ); + }); let trampoline_index = trampoline_entry.0.shared_type_indices[0]; log::trace!( "Registering trampoline type:\n\ diff --git a/crates/wasmtime/src/runtime/types.rs b/crates/wasmtime/src/runtime/types.rs index 954df787969d..e20ffff81f8b 100644 --- a/crates/wasmtime/src/runtime/types.rs +++ b/crates/wasmtime/src/runtime/types.rs @@ -7,7 +7,7 @@ use wasmtime_environ::{ WasmSubType, WasmValType, }; -use crate::{type_registry::RegisteredType, Engine}; +use crate::{Engine, type_registry::RegisteredType}; pub(crate) mod matching; @@ -1764,17 +1764,14 @@ impl StructType { ({MAX_FIELDS})", ); - let ty = RegisteredType::new( - engine, - WasmSubType { - is_final, - supertype, - composite_type: WasmCompositeType { - shared: is_shared, - inner: WasmCompositeInnerType::Struct(ty), - }, + let ty = RegisteredType::new(engine, WasmSubType { + is_final, + supertype, + composite_type: WasmCompositeType { + shared: is_shared, + inner: WasmCompositeInnerType::Struct(ty), }, - ); + }); Ok(Self { registered_type: ty, }) @@ -2007,17 +2004,14 @@ impl ArrayType { supertype: Option, ty: WasmArrayType, ) -> ArrayType { - let ty = RegisteredType::new( - engine, - WasmSubType { - is_final, - supertype, - composite_type: WasmCompositeType { - shared: false, - inner: WasmCompositeInnerType::Array(ty), - }, + let ty = RegisteredType::new(engine, WasmSubType { + is_final, + supertype, + composite_type: WasmCompositeType { + shared: false, + inner: WasmCompositeInnerType::Array(ty), }, - ); + }); Self { registered_type: ty, } @@ -2366,17 +2360,14 @@ impl FuncType { supertype: Option, ty: WasmFuncType, ) -> FuncType { - let ty = RegisteredType::new( - engine, - WasmSubType { - is_final, - supertype, - composite_type: WasmCompositeType { - shared: false, - inner: WasmCompositeInnerType::Func(ty), - }, + let ty = RegisteredType::new(engine, WasmSubType { + is_final, + supertype, + composite_type: WasmCompositeType { + shared: false, + inner: WasmCompositeInnerType::Func(ty), }, - ); + }); Self { registered_type: ty, } diff --git a/crates/wasmtime/src/runtime/types/matching.rs b/crates/wasmtime/src/runtime/types/matching.rs index 7b133226f21a..2a663c2d7fb4 100644 --- a/crates/wasmtime/src/runtime/types/matching.rs +++ b/crates/wasmtime/src/runtime/types/matching.rs @@ -1,5 +1,5 @@ use crate::prelude::*; -use crate::{linker::DefinitionType, Engine}; +use crate::{Engine, linker::DefinitionType}; use wasmtime_environ::{ EntityType, Global, IndexType, Memory, ModuleTypes, Table, TypeTrace, VMSharedTypeIndex, WasmHeapType, WasmRefType, WasmSubType, WasmValType, diff --git a/crates/wasmtime/src/runtime/unix.rs b/crates/wasmtime/src/runtime/unix.rs index 5bbcf19cba0b..a8ffcb7b52a5 100644 --- a/crates/wasmtime/src/runtime/unix.rs +++ b/crates/wasmtime/src/runtime/unix.rs @@ -9,11 +9,11 @@ //! throughout the `wasmtime` crate with extra functionality that's only //! available on Unix. -#[cfg(feature = "signals-based-traps")] -use crate::prelude::*; #[cfg(feature = "signals-based-traps")] use crate::AsContextMut; use crate::Store; +#[cfg(feature = "signals-based-traps")] +use crate::prelude::*; /// Extensions for the [`Store`] type only available on Unix. pub trait StoreExt { diff --git a/crates/wasmtime/src/runtime/values.rs b/crates/wasmtime/src/runtime/values.rs index 4c4284abe946..045c6a2e2266 100644 --- a/crates/wasmtime/src/runtime/values.rs +++ b/crates/wasmtime/src/runtime/values.rs @@ -1,8 +1,8 @@ use crate::runtime::vm::TableElement; use crate::store::{AutoAssertNoGc, StoreOpaque}; use crate::{ - prelude::*, AnyRef, ArrayRef, AsContext, AsContextMut, ExternRef, Func, HeapType, RefType, - Rooted, RootedGcRefImpl, StructRef, ValType, V128, + AnyRef, ArrayRef, AsContext, AsContextMut, ExternRef, Func, HeapType, RefType, Rooted, + RootedGcRefImpl, StructRef, V128, ValType, prelude::*, }; use core::ptr; diff --git a/crates/wasmtime/src/runtime/vm/component.rs b/crates/wasmtime/src/runtime/vm/component.rs index c3ba4655312b..92ea122f9f44 100644 --- a/crates/wasmtime/src/runtime/vm/component.rs +++ b/crates/wasmtime/src/runtime/vm/component.rs @@ -24,7 +24,7 @@ use wasmtime_environ::component::*; use wasmtime_environ::{HostPtr, PrimaryMap, VMSharedTypeIndex}; #[allow(clippy::cast_possible_truncation)] // it's intended this is truncated on - // 32-bit platforms +// 32-bit platforms const INVALID_PTR: usize = 0xdead_dead_beef_beef_u64 as usize; mod libcalls; @@ -203,26 +203,23 @@ impl ComponentInstance { component_resource_tables.push(ResourceTable::default()); } - ptr::write( - ptr.as_ptr(), - ComponentInstance { - offsets, - vmctx_self_reference: SendSyncPtr::new( - NonNull::new( - ptr.as_ptr() - .byte_add(mem::size_of::()) - .cast(), - ) - .unwrap(), - ), - component_resource_tables, - runtime_info, - resource_types, - vmctx: VMComponentContext { - _marker: marker::PhantomPinned, - }, + ptr::write(ptr.as_ptr(), ComponentInstance { + offsets, + vmctx_self_reference: SendSyncPtr::new( + NonNull::new( + ptr.as_ptr() + .byte_add(mem::size_of::()) + .cast(), + ) + .unwrap(), + ), + component_resource_tables, + runtime_info, + resource_types, + vmctx: VMComponentContext { + _marker: marker::PhantomPinned, }, - ); + }); (*ptr.as_ptr()).initialize_vmctx(store); } diff --git a/crates/wasmtime/src/runtime/vm/component/libcalls.rs b/crates/wasmtime/src/runtime/vm/component/libcalls.rs index 94d83babe75f..79dd68971c47 100644 --- a/crates/wasmtime/src/runtime/vm/component/libcalls.rs +++ b/crates/wasmtime/src/runtime/vm/component/libcalls.rs @@ -1,8 +1,8 @@ //! Implementation of string transcoding required by the component model. use crate::prelude::*; -use crate::runtime::vm::component::{ComponentInstance, VMComponentContext}; use crate::runtime::vm::HostResultHasUnwindSentinel; +use crate::runtime::vm::component::{ComponentInstance, VMComponentContext}; use core::cell::Cell; use core::convert::Infallible; use core::slice; diff --git a/crates/wasmtime/src/runtime/vm/component/resources.rs b/crates/wasmtime/src/runtime/vm/component/resources.rs index 8ea8b7f15f87..a334d3dd3664 100644 --- a/crates/wasmtime/src/runtime/vm/component/resources.rs +++ b/crates/wasmtime/src/runtime/vm/component/resources.rs @@ -25,8 +25,8 @@ use crate::prelude::*; use core::mem; -use wasmtime_environ::component::TypeResourceTableIndex; use wasmtime_environ::PrimaryMap; +use wasmtime_environ::component::TypeResourceTableIndex; /// The maximum handle value is specified in /// diff --git a/crates/wasmtime/src/runtime/vm/const_expr.rs b/crates/wasmtime/src/runtime/vm/const_expr.rs index af1f6b9e1763..ef9cd1b6fc61 100644 --- a/crates/wasmtime/src/runtime/vm/const_expr.rs +++ b/crates/wasmtime/src/runtime/vm/const_expr.rs @@ -1,9 +1,9 @@ //! Evaluating const expressions. -use crate::runtime::vm::{Instance, VMGcRef, ValRaw, I31}; +use crate::runtime::vm::{I31, Instance, VMGcRef, ValRaw}; use crate::store::{AutoAssertNoGc, StoreOpaque}; use crate::{ - prelude::*, ArrayRef, ArrayRefPre, ArrayType, StructRef, StructRefPre, StructType, Val, + ArrayRef, ArrayRefPre, ArrayType, StructRef, StructRefPre, StructType, Val, prelude::*, }; use smallvec::SmallVec; use wasmtime_environ::{ diff --git a/crates/wasmtime/src/runtime/vm/cow.rs b/crates/wasmtime/src/runtime/vm/cow.rs index db9ddc3952c0..38f70fc55544 100644 --- a/crates/wasmtime/src/runtime/vm/cow.rs +++ b/crates/wasmtime/src/runtime/vm/cow.rs @@ -8,7 +8,7 @@ use super::sys::DecommitBehavior; use crate::prelude::*; use crate::runtime::vm::sys::vm::{self, MemoryImageSource}; -use crate::runtime::vm::{host_page_size, HostAlignedByteCount, MmapOffset, MmapVec}; +use crate::runtime::vm::{HostAlignedByteCount, MmapOffset, MmapVec, host_page_size}; use alloc::sync::Arc; use core::ops::Range; use core::ptr; @@ -786,7 +786,7 @@ mod test { use super::*; use crate::runtime::vm::mmap::{AlignedLength, Mmap}; use crate::runtime::vm::sys::vm::decommit_pages; - use crate::runtime::vm::{host_page_size, HostAlignedByteCount}; + use crate::runtime::vm::{HostAlignedByteCount, host_page_size}; use std::sync::Arc; use wasmtime_environ::{IndexType, Limits, Memory}; diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs index b5c47042dae9..98b8517d0ff4 100644 --- a/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs +++ b/crates/wasmtime/src/runtime/vm/gc/enabled/arrayref.rs @@ -1,10 +1,10 @@ -use super::{truncate_i32_to_i16, truncate_i32_to_i8}; +use super::{truncate_i32_to_i8, truncate_i32_to_i16}; use crate::{ + AnyRef, ExternRef, Func, HeapType, RootedGcRefImpl, StorageType, Val, ValType, prelude::*, runtime::vm::{GcHeap, GcStore, VMGcRef}, store::{AutoAssertNoGc, StoreOpaque}, vm::{FuncRefTableId, SendSyncPtr}, - AnyRef, ExternRef, Func, HeapType, RootedGcRefImpl, StorageType, Val, ValType, }; use core::fmt; use wasmtime_environ::{GcArrayLayout, VMGcKind}; diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs index 29c02e79e59f..ce7952bf1617 100644 --- a/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs +++ b/crates/wasmtime/src/runtime/vm/gc/enabled/drc.rs @@ -46,9 +46,9 @@ use super::{VMArrayRef, VMGcObjectDataMut, VMStructRef}; use crate::hash_set::HashSet; use crate::prelude::*; use crate::runtime::vm::{ - mmap::AlignedLength, ExternRefHostDataId, ExternRefHostDataTable, GarbageCollection, GcHeap, - GcHeapObject, GcProgress, GcRootsIter, GcRuntime, Mmap, TypedGcRef, VMExternRef, VMGcHeader, - VMGcRef, + ExternRefHostDataId, ExternRefHostDataTable, GarbageCollection, GcHeap, GcHeapObject, + GcProgress, GcRootsIter, GcRuntime, Mmap, TypedGcRef, VMExternRef, VMGcHeader, VMGcRef, + mmap::AlignedLength, }; use core::ops::{Deref, DerefMut, Range}; use core::{ diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/free_list.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/free_list.rs index e1d2a3f923e6..5d18d3e37b60 100644 --- a/crates/wasmtime/src/runtime/vm/gc/enabled/free_list.rs +++ b/crates/wasmtime/src/runtime/vm/gc/enabled/free_list.rs @@ -746,12 +746,17 @@ mod tests { // Attempt to allocate something that is 20 times the size of our // min-sized block. - assert!(free_list - .alloc( - Layout::from_size_align(usize::try_from(MIN_BLOCK_SIZE).unwrap() * 20, ALIGN_USIZE) + assert!( + free_list + .alloc( + Layout::from_size_align( + usize::try_from(MIN_BLOCK_SIZE).unwrap() * 20, + ALIGN_USIZE + ) .unwrap(), - ) - .is_err()); + ) + .is_err() + ); } #[test] @@ -766,11 +771,16 @@ mod tests { // Attempt to allocate something that requires larger alignment than // `FreeList` supports. - assert!(free_list - .alloc( - Layout::from_size_align(usize::try_from(MIN_BLOCK_SIZE).unwrap(), ALIGN_USIZE * 2) + assert!( + free_list + .alloc( + Layout::from_size_align( + usize::try_from(MIN_BLOCK_SIZE).unwrap(), + ALIGN_USIZE * 2 + ) .unwrap(), - ) - .is_err()); + ) + .is_err() + ); } } diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs index 776b3aabd1fb..c395a5979588 100644 --- a/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs +++ b/crates/wasmtime/src/runtime/vm/gc/enabled/null.rs @@ -6,13 +6,13 @@ use super::*; use crate::{ + GcHeapOutOfMemory, prelude::*, vm::{ - mmap::AlignedLength, ExternRefHostDataId, ExternRefHostDataTable, GarbageCollection, - GcHeap, GcHeapObject, GcProgress, GcRootsIter, Mmap, SendSyncUnsafeCell, TypedGcRef, - VMGcHeader, VMGcRef, + ExternRefHostDataId, ExternRefHostDataTable, GarbageCollection, GcHeap, GcHeapObject, + GcProgress, GcRootsIter, Mmap, SendSyncUnsafeCell, TypedGcRef, VMGcHeader, VMGcRef, + mmap::AlignedLength, }, - GcHeapOutOfMemory, }; use core::{ alloc::Layout, @@ -21,8 +21,8 @@ use core::{ num::{NonZeroU32, NonZeroUsize}, }; use wasmtime_environ::{ - null::NullTypeLayouts, GcArrayLayout, GcStructLayout, GcTypeLayouts, VMGcKind, - VMSharedTypeIndex, + GcArrayLayout, GcStructLayout, GcTypeLayouts, VMGcKind, VMSharedTypeIndex, + null::NullTypeLayouts, }; /// The null collector. diff --git a/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs b/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs index 51a0249953ca..516cfb625f60 100644 --- a/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs +++ b/crates/wasmtime/src/runtime/vm/gc/enabled/structref.rs @@ -1,10 +1,10 @@ -use super::{truncate_i32_to_i16, truncate_i32_to_i8}; +use super::{truncate_i32_to_i8, truncate_i32_to_i16}; use crate::{ + AnyRef, ExternRef, Func, HeapType, RootedGcRefImpl, StorageType, Val, ValType, prelude::*, runtime::vm::{GcHeap, GcStore, VMGcRef}, store::AutoAssertNoGc, vm::{FuncRefTableId, SendSyncPtr}, - AnyRef, ExternRef, Func, HeapType, RootedGcRefImpl, StorageType, Val, ValType, }; use core::fmt; use wasmtime_environ::{GcStructLayout, VMGcKind}; diff --git a/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs b/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs index c1f3bf899854..87ecf9e353f4 100644 --- a/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs +++ b/crates/wasmtime/src/runtime/vm/gc/gc_ref.rs @@ -236,11 +236,7 @@ impl VMGcRef { /// /// Returns `None` for `i31ref`s. pub fn as_heap_index(&self) -> Option { - if self.is_i31() { - None - } else { - Some(self.0) - } + if self.is_i31() { None } else { Some(self.0) } } /// Get this GC reference as a raw u32 value, regardless whether it is @@ -310,13 +306,10 @@ impl VMGcRef { if T::is(gc_heap.header(&self)) { let ptr = self as *const VMGcRef; let ret = unsafe { &*ptr.cast() }; - assert!(matches!( - ret, - TypedGcRef { - gc_ref: VMGcRef(_), - _phantom - } - )); + assert!(matches!(ret, TypedGcRef { + gc_ref: VMGcRef(_), + _phantom + })); Some(ret) } else { None @@ -336,13 +329,10 @@ impl VMGcRef { debug_assert!(!self.is_i31()); let ptr = self as *const VMGcRef; let ret = unsafe { &*ptr.cast() }; - assert!(matches!( - ret, - TypedGcRef { - gc_ref: VMGcRef(_), - _phantom - } - )); + assert!(matches!(ret, TypedGcRef { + gc_ref: VMGcRef(_), + _phantom + })); ret } diff --git a/crates/wasmtime/src/runtime/vm/instance.rs b/crates/wasmtime/src/runtime/vm/instance.rs index 347312fbde41..4875d28a398d 100644 --- a/crates/wasmtime/src/runtime/vm/instance.rs +++ b/crates/wasmtime/src/runtime/vm/instance.rs @@ -16,7 +16,7 @@ use crate::runtime::vm::{ SendSyncPtr, VMFunctionBody, VMGcRef, VMStore, WasmFault, }; use crate::store::{StoreInner, StoreOpaque}; -use crate::{prelude::*, StoreContextMut}; +use crate::{StoreContextMut, prelude::*}; use alloc::sync::Arc; use core::alloc::Layout; use core::any::Any; @@ -26,11 +26,11 @@ use core::sync::atomic::AtomicU64; use core::{mem, ptr}; use sptr::Strict; use wasmtime_environ::{ - packed_option::ReservedValue, DataIndex, DefinedGlobalIndex, DefinedMemoryIndex, - DefinedTableIndex, ElemIndex, EntityIndex, EntityRef, EntitySet, FuncIndex, GlobalIndex, - HostPtr, MemoryIndex, Module, ModuleInternedTypeIndex, PrimaryMap, PtrSize, TableIndex, - TableInitialValue, TableSegmentElements, Trap, VMOffsets, VMSharedTypeIndex, WasmHeapTopType, - VMCONTEXT_MAGIC, + DataIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, ElemIndex, EntityIndex, + EntityRef, EntitySet, FuncIndex, GlobalIndex, HostPtr, MemoryIndex, Module, + ModuleInternedTypeIndex, PrimaryMap, PtrSize, TableIndex, TableInitialValue, + TableSegmentElements, Trap, VMCONTEXT_MAGIC, VMOffsets, VMSharedTypeIndex, WasmHeapTopType, + packed_option::ReservedValue, }; #[cfg(feature = "wmemcheck")] use wasmtime_wmemcheck::Wmemcheck; @@ -313,36 +313,33 @@ impl Instance { #[cfg(not(feature = "wmemcheck"))] let _ = memory_tys; - ptr::write( - ptr, - Instance { - runtime_info: req.runtime_info.clone(), - memories, - tables, - dropped_elements, - dropped_data, - host_state: req.host_state, - vmctx_self_reference: SendSyncPtr::new(NonNull::new(ptr.add(1).cast()).unwrap()), - vmctx: VMContext { - _marker: core::marker::PhantomPinned, - }, - #[cfg(feature = "wmemcheck")] - wmemcheck_state: { - if req.wmemcheck { - let size = memory_tys - .iter() - .next() - .map(|memory| memory.1.limits.min) - .unwrap_or(0) - * 64 - * 1024; - Some(Wmemcheck::new(size as usize)) - } else { - None - } - }, + ptr::write(ptr, Instance { + runtime_info: req.runtime_info.clone(), + memories, + tables, + dropped_elements, + dropped_data, + host_state: req.host_state, + vmctx_self_reference: SendSyncPtr::new(NonNull::new(ptr.add(1).cast()).unwrap()), + vmctx: VMContext { + _marker: core::marker::PhantomPinned, }, - ); + #[cfg(feature = "wmemcheck")] + wmemcheck_state: { + if req.wmemcheck { + let size = memory_tys + .iter() + .next() + .map(|memory| memory.1.limits.min) + .unwrap_or(0) + * 64 + * 1024; + Some(Wmemcheck::new(size as usize)) + } else { + None + } + }, + }); (*ptr).initialize_vmctx(module, req.runtime_info.offsets(), req.store, req.imports); InstanceHandle { @@ -527,14 +524,11 @@ impl Instance { ) -> impl ExactSizeIterator + 'a { let module = self.env_module().clone(); module.globals.keys().map(move |idx| { - ( - idx, - ExportGlobal { - definition: self.defined_or_imported_global_ptr(idx), - vmctx: self.vmctx(), - global: self.env_module().globals[idx], - }, - ) + (idx, ExportGlobal { + definition: self.defined_or_imported_global_ptr(idx), + vmctx: self.vmctx(), + global: self.env_module().globals[idx], + }) }) } diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator.rs b/crates/wasmtime/src/runtime/vm/instance/allocator.rs index 1f3ee06ccfab..162b852a5dad 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator.rs @@ -21,8 +21,8 @@ use crate::runtime::vm::{GcHeap, GcRuntime}; #[cfg(feature = "component-model")] use wasmtime_environ::{ - component::{Component, VMComponentOffsets}, StaticModuleIndex, + component::{Component, VMComponentOffsets}, }; mod on_demand; diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/on_demand.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/on_demand.rs index c5adb7b9e724..1ed033d3c7b2 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/on_demand.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/on_demand.rs @@ -2,11 +2,11 @@ use super::{ InstanceAllocationRequest, InstanceAllocatorImpl, MemoryAllocationIndex, TableAllocationIndex, }; use crate::prelude::*; +use crate::runtime::vm::CompiledModuleId; use crate::runtime::vm::instance::RuntimeMemoryCreator; use crate::runtime::vm::memory::{DefaultMemoryCreator, Memory}; use crate::runtime::vm::mpk::ProtectionKey; use crate::runtime::vm::table::Table; -use crate::runtime::vm::CompiledModuleId; use alloc::sync::Arc; use wasmtime_environ::{ DefinedMemoryIndex, DefinedTableIndex, HostPtr, Module, Tunables, VMOffsets, @@ -20,8 +20,8 @@ use wasmtime_fiber::RuntimeFiberStackCreator; #[cfg(feature = "component-model")] use wasmtime_environ::{ - component::{Component, VMComponentOffsets}, StaticModuleIndex, + component::{Component, VMComponentOffsets}, }; /// Represents the on-demand instance allocator. diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs index f16ed6f7f516..9f31a899b18f 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling.rs @@ -48,9 +48,9 @@ use super::{ }; use crate::prelude::*; use crate::runtime::vm::{ + CompiledModuleId, Memory, Table, instance::Instance, mpk::{self, MpkEnabled, ProtectionKey, ProtectionMask}, - CompiledModuleId, Memory, Table, }; use std::borrow::Cow; use std::fmt::Display; @@ -75,8 +75,8 @@ use stack_pool::StackPool; #[cfg(feature = "component-model")] use wasmtime_environ::{ - component::{Component, VMComponentOffsets}, StaticModuleIndex, + component::{Component, VMComponentOffsets}, }; fn round_up_to_pow2(n: usize, to: usize) -> usize { @@ -714,13 +714,10 @@ mod test { ..PoolingInstanceAllocatorConfig::default() }; assert_eq!( - PoolingInstanceAllocator::new( - &config, - &Tunables { - memory_reservation: 0x10000, - ..Tunables::default_host() - }, - ) + PoolingInstanceAllocator::new(&config, &Tunables { + memory_reservation: 0x10000, + ..Tunables::default_host() + },) .map_err(|e| e.to_string()) .expect_err("expected a failure constructing instance allocator"), "maximum memory size of 0x100010000 bytes exceeds the configured \ diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs index 8d471384bbc8..91050f324e75 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/gc_heap_pool.rs @@ -1,5 +1,5 @@ -use super::index_allocator::{SimpleIndexAllocator, SlotId}; use super::GcHeapAllocationIndex; +use super::index_allocator::{SimpleIndexAllocator, SlotId}; use crate::prelude::*; use crate::runtime::vm::{GcHeap, GcRuntime, PoolingInstanceAllocatorConfig, Result}; use std::sync::Mutex; diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs index 0c2a4f1ecf5e..90e31336a1ce 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/generic_stack_pool.rs @@ -1,7 +1,7 @@ #![cfg_attr(not(asan), allow(dead_code))] use crate::prelude::*; -use crate::{runtime::vm::PoolingInstanceAllocatorConfig, PoolConcurrencyLimitError}; +use crate::{PoolConcurrencyLimitError, runtime::vm::PoolingInstanceAllocatorConfig}; use std::sync::atomic::{AtomicU64, Ordering}; /// A generic implementation of a stack pool. diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs index 3536479856dd..436cf7da1cdd 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/index_allocator.rs @@ -568,12 +568,16 @@ mod test { let index2 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap(); state.free(index2); state.free(index1); - assert!(state - .alloc_affine_and_clear_affinity(id, memory_index) - .is_some()); - assert!(state - .alloc_affine_and_clear_affinity(id, memory_index) - .is_some()); + assert!( + state + .alloc_affine_and_clear_affinity(id, memory_index) + .is_some() + ); + assert!( + state + .alloc_affine_and_clear_affinity(id, memory_index) + .is_some() + ); assert_eq!( state.alloc_affine_and_clear_affinity(id, memory_index), None diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs index 720deb7c5e54..b0ab48331b3c 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/memory_pool.rs @@ -51,13 +51,14 @@ //! [ColorGuard]: https://plas2022.github.io/files/pdf/SegueColorGuard.pdf use super::{ - index_allocator::{MemoryInModule, ModuleAffinityIndexAllocator, SlotId}, MemoryAllocationIndex, + index_allocator::{MemoryInModule, ModuleAffinityIndexAllocator, SlotId}, }; use crate::prelude::*; use crate::runtime::vm::{ - mmap::AlignedLength, CompiledModuleId, InstanceAllocationRequest, InstanceLimits, Memory, - MemoryBase, MemoryImageSlot, Mmap, MmapOffset, MpkEnabled, PoolingInstanceAllocatorConfig, + CompiledModuleId, InstanceAllocationRequest, InstanceLimits, Memory, MemoryBase, + MemoryImageSlot, Mmap, MmapOffset, MpkEnabled, PoolingInstanceAllocatorConfig, + mmap::AlignedLength, }; use crate::{ runtime::vm::mpk::{self, ProtectionKey, ProtectionMask}, diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs index 1c26e59b15ac..8d7df3946c30 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/table_pool.rs @@ -1,11 +1,11 @@ use super::{ - index_allocator::{SimpleIndexAllocator, SlotId}, TableAllocationIndex, + index_allocator::{SimpleIndexAllocator, SlotId}, }; use crate::runtime::vm::sys::vm::commit_pages; use crate::runtime::vm::{ - mmap::AlignedLength, InstanceAllocationRequest, Mmap, PoolingInstanceAllocatorConfig, - SendSyncPtr, Table, + InstanceAllocationRequest, Mmap, PoolingInstanceAllocatorConfig, SendSyncPtr, Table, + mmap::AlignedLength, }; use crate::{prelude::*, vm::HostAlignedByteCount}; use std::mem; diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs index ef15b03b28ae..d93acc68d288 100644 --- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs +++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/unix_stack_pool.rs @@ -4,7 +4,7 @@ use super::index_allocator::{SimpleIndexAllocator, SlotId}; use crate::prelude::*; use crate::runtime::vm::sys::vm::commit_pages; use crate::runtime::vm::{ - mmap::AlignedLength, HostAlignedByteCount, Mmap, PoolingInstanceAllocatorConfig, + HostAlignedByteCount, Mmap, PoolingInstanceAllocatorConfig, mmap::AlignedLength, }; /// Represents a pool of execution stacks (used for the async fiber implementation). @@ -30,7 +30,7 @@ pub struct StackPool { impl StackPool { pub fn new(config: &PoolingInstanceAllocatorConfig) -> Result { - use rustix::mm::{mprotect, MprotectFlags}; + use rustix::mm::{MprotectFlags, mprotect}; let page_size = HostAlignedByteCount::host_page_size(); @@ -286,21 +286,18 @@ mod tests { } } - assert_eq!( - pool.index_allocator.testing_freelist(), - [ - SlotId(0), - SlotId(1), - SlotId(2), - SlotId(3), - SlotId(4), - SlotId(5), - SlotId(6), - SlotId(7), - SlotId(8), - SlotId(9) - ], - ); + assert_eq!(pool.index_allocator.testing_freelist(), [ + SlotId(0), + SlotId(1), + SlotId(2), + SlotId(3), + SlotId(4), + SlotId(5), + SlotId(6), + SlotId(7), + SlotId(8), + SlotId(9) + ],); Ok(()) } diff --git a/crates/wasmtime/src/runtime/vm/interpreter.rs b/crates/wasmtime/src/runtime/vm/interpreter.rs index fbe7a8cd3ea5..7c7f1f751513 100644 --- a/crates/wasmtime/src/runtime/vm/interpreter.rs +++ b/crates/wasmtime/src/runtime/vm/interpreter.rs @@ -1,7 +1,7 @@ +use crate::ValRaw; use crate::prelude::*; use crate::runtime::vm::vmcontext::VMArrayCallNative; -use crate::runtime::vm::{tls, TrapRegisters, TrapTest, VMContext, VMOpaqueContext}; -use crate::ValRaw; +use crate::runtime::vm::{TrapRegisters, TrapTest, VMContext, VMOpaqueContext, tls}; use core::ptr::NonNull; use pulley_interpreter::interp::{DoneReason, RegType, TrapKind, Val, Vm, XRegVal}; use pulley_interpreter::{Reg, XReg}; diff --git a/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs b/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs index d410c2cb1bbc..ad943a37449c 100644 --- a/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs +++ b/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs @@ -4,9 +4,9 @@ //! `Option` is also zero-sized so there should be no runtime cost for //! having these structures plumbed around. -use crate::runtime::vm::VMOpaqueContext; -use crate::runtime::Uninhabited; use crate::ValRaw; +use crate::runtime::Uninhabited; +use crate::runtime::vm::VMOpaqueContext; use core::marker; use core::mem; use core::ptr::NonNull; diff --git a/crates/wasmtime/src/runtime/vm/libcalls.rs b/crates/wasmtime/src/runtime/vm/libcalls.rs index c61168c437ac..2beb68e80c98 100644 --- a/crates/wasmtime/src/runtime/vm/libcalls.rs +++ b/crates/wasmtime/src/runtime/vm/libcalls.rs @@ -485,7 +485,7 @@ unsafe fn gc_alloc_raw( size: u32, align: u32, ) -> Result { - use crate::{vm::VMGcHeader, GcHeapOutOfMemory}; + use crate::{GcHeapOutOfMemory, vm::VMGcHeader}; use core::alloc::Layout; use wasmtime_environ::{ModuleInternedTypeIndex, VMGcKind}; @@ -563,7 +563,7 @@ unsafe fn get_interned_func_ref( ) -> *mut u8 { use super::FuncRefTableId; use crate::store::AutoAssertNoGc; - use wasmtime_environ::{packed_option::ReservedValue, ModuleInternedTypeIndex}; + use wasmtime_environ::{ModuleInternedTypeIndex, packed_option::ReservedValue}; let store = AutoAssertNoGc::new(store.store_opaque_mut()); @@ -759,9 +759,9 @@ unsafe fn array_new_elem( len: u32, ) -> Result { use crate::{ + ArrayRef, ArrayRefPre, ArrayType, Func, GcHeapOutOfMemory, RootSet, RootedGcRefImpl, Val, store::AutoAssertNoGc, vm::const_expr::{ConstEvalContext, ConstExprEvaluator}, - ArrayRef, ArrayRefPre, ArrayType, Func, GcHeapOutOfMemory, RootSet, RootedGcRefImpl, Val, }; use wasmtime_environ::{ModuleInternedTypeIndex, TableSegmentElements}; @@ -847,9 +847,9 @@ unsafe fn array_init_elem( len: u32, ) -> Result<()> { use crate::{ + ArrayRef, Func, OpaqueRootScope, Val, store::AutoAssertNoGc, vm::const_expr::{ConstEvalContext, ConstExprEvaluator}, - ArrayRef, Func, OpaqueRootScope, Val, }; use wasmtime_environ::{ModuleInternedTypeIndex, TableSegmentElements}; @@ -860,8 +860,8 @@ unsafe fn array_init_elem( let elem_index = ElemIndex::from_u32(elem_index); log::trace!( - "array.init_elem(array={array:#x}, dst={dst}, elem_index={elem_index:?}, src={src}, len={len})", - ); + "array.init_elem(array={array:#x}, dst={dst}, elem_index={elem_index:?}, src={src}, len={len})", + ); // Convert the raw GC ref into a `Rooted`. let array = VMGcRef::from_raw_u32(array).ok_or_else(|| Trap::NullReference)?; @@ -945,11 +945,11 @@ unsafe fn array_copy( src: u32, len: u32, ) -> Result<()> { - use crate::{store::AutoAssertNoGc, ArrayRef, OpaqueRootScope}; + use crate::{ArrayRef, OpaqueRootScope, store::AutoAssertNoGc}; log::trace!( - "array.copy(dst_array={dst_array:#x}, dst_index={dst}, src_array={src_array:#x}, src_index={src}, len={len})", - ); + "array.copy(dst_array={dst_array:#x}, dst_index={dst}, src_array={src_array:#x}, src_index={src}, len={len})", + ); let mut store = OpaqueRootScope::new(store.store_opaque_mut()); let mut store = AutoAssertNoGc::new(&mut store); diff --git a/crates/wasmtime/src/runtime/vm/memory/malloc.rs b/crates/wasmtime/src/runtime/vm/memory/malloc.rs index 13c83bd859c3..6db4b2b80883 100644 --- a/crates/wasmtime/src/runtime/vm/memory/malloc.rs +++ b/crates/wasmtime/src/runtime/vm/memory/malloc.rs @@ -5,8 +5,8 @@ //! handle memory allocation failures. use crate::prelude::*; -use crate::runtime::vm::memory::{MemoryBase, RuntimeLinearMemory}; use crate::runtime::vm::SendSyncPtr; +use crate::runtime::vm::memory::{MemoryBase, RuntimeLinearMemory}; use core::mem; use core::ptr::NonNull; use wasmtime_environ::Tunables; diff --git a/crates/wasmtime/src/runtime/vm/memory/mmap.rs b/crates/wasmtime/src/runtime/vm/memory/mmap.rs index e82f159c2f51..28f61fd46715 100644 --- a/crates/wasmtime/src/runtime/vm/memory/mmap.rs +++ b/crates/wasmtime/src/runtime/vm/memory/mmap.rs @@ -3,7 +3,7 @@ use crate::prelude::*; use crate::runtime::vm::memory::RuntimeLinearMemory; -use crate::runtime::vm::{mmap::AlignedLength, HostAlignedByteCount, Mmap}; +use crate::runtime::vm::{HostAlignedByteCount, Mmap, mmap::AlignedLength}; use alloc::sync::Arc; use wasmtime_environ::Tunables; diff --git a/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs b/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs index 6412c325694d..af1295f721ab 100644 --- a/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs +++ b/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs @@ -1,5 +1,5 @@ use crate::prelude::*; -use crate::runtime::vm::memory::{validate_atomic_addr, LocalMemory, MmapMemory}; +use crate::runtime::vm::memory::{LocalMemory, MmapMemory, validate_atomic_addr}; use crate::runtime::vm::parking_spot::{ParkingSpot, Waiter}; use crate::runtime::vm::vmcontext::VMMemoryDefinition; use crate::runtime::vm::{Memory, VMStore, WaitResult}; diff --git a/crates/wasmtime/src/runtime/vm/memory/static_.rs b/crates/wasmtime/src/runtime/vm/memory/static_.rs index ed62d114652e..b489241cf099 100644 --- a/crates/wasmtime/src/runtime/vm/memory/static_.rs +++ b/crates/wasmtime/src/runtime/vm/memory/static_.rs @@ -2,8 +2,8 @@ //! fixed allocation that cannot move. use crate::prelude::*; -use crate::runtime::vm::memory::RuntimeLinearMemory; use crate::runtime::vm::MemoryBase; +use crate::runtime::vm::memory::RuntimeLinearMemory; /// A "static" memory where the lifetime of the backing memory is managed /// elsewhere. Currently used with the pooling allocator. diff --git a/crates/wasmtime/src/runtime/vm/mmap_vec.rs b/crates/wasmtime/src/runtime/vm/mmap_vec.rs index 33040642384e..9e595966e82c 100644 --- a/crates/wasmtime/src/runtime/vm/mmap_vec.rs +++ b/crates/wasmtime/src/runtime/vm/mmap_vec.rs @@ -2,7 +2,7 @@ use crate::prelude::*; #[cfg(not(feature = "signals-based-traps"))] use crate::runtime::vm::send_sync_ptr::SendSyncPtr; #[cfg(feature = "signals-based-traps")] -use crate::runtime::vm::{mmap::UnalignedLength, Mmap}; +use crate::runtime::vm::{Mmap, mmap::UnalignedLength}; #[cfg(not(feature = "signals-based-traps"))] use alloc::alloc::Layout; use alloc::sync::Arc; diff --git a/crates/wasmtime/src/runtime/vm/parking_spot.rs b/crates/wasmtime/src/runtime/vm/parking_spot.rs index 0de3260fc8f7..7cfb76930137 100644 --- a/crates/wasmtime/src/runtime/vm/parking_spot.rs +++ b/crates/wasmtime/src/runtime/vm/parking_spot.rs @@ -15,8 +15,8 @@ use crate::prelude::*; use crate::runtime::vm::{SendSyncPtr, WaitResult}; use std::collections::BTreeMap; use std::ptr::NonNull; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::SeqCst}; use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::SeqCst}; use std::thread::{self, Thread}; use std::time::{Duration, Instant}; @@ -363,8 +363,8 @@ mod tests { // This is a modified version of the parking_lot_core tests, // which are licensed under the MIT and Apache 2.0 licenses. use super::*; - use std::sync::atomic::AtomicU32; use std::sync::Arc; + use std::sync::atomic::AtomicU32; macro_rules! test { ( $( $name:ident( diff --git a/crates/wasmtime/src/runtime/vm/sys/custom/traphandlers.rs b/crates/wasmtime/src/runtime/vm/sys/custom/traphandlers.rs index ec3781c238ab..9b6379625d46 100644 --- a/crates/wasmtime/src/runtime/vm/sys/custom/traphandlers.rs +++ b/crates/wasmtime/src/runtime/vm/sys/custom/traphandlers.rs @@ -35,7 +35,7 @@ impl TrapHandler { #[cfg(feature = "signals-based-traps")] extern "C" fn handle_trap(pc: usize, fp: usize, has_faulting_addr: bool, faulting_addr: usize) { - use crate::runtime::vm::traphandlers::{tls, TrapRegisters, TrapTest}; + use crate::runtime::vm::traphandlers::{TrapRegisters, TrapTest, tls}; tls::with(|info| { let info = match info { diff --git a/crates/wasmtime/src/runtime/vm/sys/custom/vm.rs b/crates/wasmtime/src/runtime/vm/sys/custom/vm.rs index 414341c73e93..0762d4f8a2d5 100644 --- a/crates/wasmtime/src/runtime/vm/sys/custom/vm.rs +++ b/crates/wasmtime/src/runtime/vm/sys/custom/vm.rs @@ -1,7 +1,7 @@ use super::cvt; use crate::prelude::*; -use crate::runtime::vm::sys::capi; use crate::runtime::vm::SendSyncPtr; +use crate::runtime::vm::sys::capi; use crate::vm::sys::DecommitBehavior; use core::ptr::{self, NonNull}; #[cfg(feature = "std")] diff --git a/crates/wasmtime/src/runtime/vm/sys/unix/machports.rs b/crates/wasmtime/src/runtime/vm/sys/unix/machports.rs index 4120f4ce3ec2..25bd49ede33c 100644 --- a/crates/wasmtime/src/runtime/vm/sys/unix/machports.rs +++ b/crates/wasmtime/src/runtime/vm/sys/unix/machports.rs @@ -42,7 +42,7 @@ use crate::runtime::module::lookup_code; use crate::runtime::vm::sys::traphandlers::wasmtime_longjmp; -use crate::runtime::vm::traphandlers::{tls, TrapRegisters}; +use crate::runtime::vm::traphandlers::{TrapRegisters, tls}; use mach2::exc::*; use mach2::exception_types::*; use mach2::kern_return::*; diff --git a/crates/wasmtime/src/runtime/vm/sys/unix/mmap.rs b/crates/wasmtime/src/runtime/vm/sys/unix/mmap.rs index 68ec224f8ee1..f548f498efc9 100644 --- a/crates/wasmtime/src/runtime/vm/sys/unix/mmap.rs +++ b/crates/wasmtime/src/runtime/vm/sys/unix/mmap.rs @@ -1,7 +1,7 @@ use crate::prelude::*; use crate::runtime::vm::sys::vm::MemoryImageSource; use crate::runtime::vm::{HostAlignedByteCount, SendSyncPtr}; -use rustix::mm::{mprotect, MprotectFlags}; +use rustix::mm::{MprotectFlags, mprotect}; use std::ops::Range; use std::ptr::{self, NonNull}; #[cfg(feature = "std")] diff --git a/crates/wasmtime/src/runtime/vm/sys/unix/signals.rs b/crates/wasmtime/src/runtime/vm/sys/unix/signals.rs index 21d33c4d2ad4..9e96646a6d49 100644 --- a/crates/wasmtime/src/runtime/vm/sys/unix/signals.rs +++ b/crates/wasmtime/src/runtime/vm/sys/unix/signals.rs @@ -2,7 +2,7 @@ use crate::prelude::*; use crate::runtime::vm::sys::traphandlers::wasmtime_longjmp; -use crate::runtime::vm::traphandlers::{tls, TrapRegisters, TrapTest}; +use crate::runtime::vm::traphandlers::{TrapRegisters, TrapTest, tls}; use std::cell::RefCell; use std::io; use std::mem; @@ -262,7 +262,7 @@ pub fn abort_stack_overflow() -> ! { } #[allow(clippy::cast_possible_truncation)] // too fiddly to handle and wouldn't - // help much anyway +// help much anyway unsafe fn get_trap_registers(cx: *mut libc::c_void, _signum: libc::c_int) -> TrapRegisters { cfg_if::cfg_if! { if #[cfg(all(any(target_os = "linux", target_os = "android", target_os = "illumos"), target_arch = "x86_64"))] { diff --git a/crates/wasmtime/src/runtime/vm/sys/unix/vm.rs b/crates/wasmtime/src/runtime/vm/sys/unix/vm.rs index 2ad2a577bb41..105f6282b299 100644 --- a/crates/wasmtime/src/runtime/vm/sys/unix/vm.rs +++ b/crates/wasmtime/src/runtime/vm/sys/unix/vm.rs @@ -1,6 +1,6 @@ use crate::runtime::vm::sys::DecommitBehavior; use rustix::fd::AsRawFd; -use rustix::mm::{mmap_anonymous, mprotect, MapFlags, MprotectFlags, ProtFlags}; +use rustix::mm::{MapFlags, MprotectFlags, ProtFlags, mmap_anonymous, mprotect}; use std::fs::File; use std::io; #[cfg(feature = "std")] @@ -115,7 +115,7 @@ impl MemoryImageSource { // gracefully handle that and fall back to skipping the memfd // optimization. Err(memfd::Error::Create(err)) if err.kind() == ErrorKind::Unsupported => { - return Ok(None) + return Ok(None); } Err(e) => return Err(e.into()), }; diff --git a/crates/wasmtime/src/runtime/vm/sys/windows/traphandlers.rs b/crates/wasmtime/src/runtime/vm/sys/windows/traphandlers.rs index 68b4f6e4a594..d0237c850bb3 100644 --- a/crates/wasmtime/src/runtime/vm/sys/windows/traphandlers.rs +++ b/crates/wasmtime/src/runtime/vm/sys/windows/traphandlers.rs @@ -1,6 +1,6 @@ use crate::prelude::*; -use crate::runtime::vm::traphandlers::{tls, TrapRegisters, TrapTest}; use crate::runtime::vm::VMContext; +use crate::runtime::vm::traphandlers::{TrapRegisters, TrapTest, tls}; use std::ffi::c_void; use std::io; use windows_sys::Win32::Foundation::*; diff --git a/crates/wasmtime/src/runtime/vm/table.rs b/crates/wasmtime/src/runtime/vm/table.rs index f6c447b58b6b..83feeddd113d 100644 --- a/crates/wasmtime/src/runtime/vm/table.rs +++ b/crates/wasmtime/src/runtime/vm/table.rs @@ -13,7 +13,7 @@ use core::slice; use core::{cmp, usize}; use sptr::Strict; use wasmtime_environ::{ - IndexType, Trap, Tunables, WasmHeapTopType, WasmRefType, FUNCREF_INIT_BIT, FUNCREF_MASK, + FUNCREF_INIT_BIT, FUNCREF_MASK, IndexType, Trap, Tunables, WasmHeapTopType, WasmRefType, }; /// An element going into or coming out of a table. diff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rs index 9e12cdc9716f..df3fa3b46046 100644 --- a/crates/wasmtime/src/runtime/vm/traphandlers.rs +++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs @@ -27,7 +27,7 @@ use core::ptr::{self, NonNull}; pub use self::backtrace::Backtrace; pub use self::coredump::CoreDumpStack; -pub use self::tls::{tls_eager_initialize, AsyncWasmCallState, PreviousAsyncWasmCallState}; +pub use self::tls::{AsyncWasmCallState, PreviousAsyncWasmCallState, tls_eager_initialize}; pub use traphandlers::SignalHandler; diff --git a/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs b/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs index 717d0c558067..c24384a3e68f 100644 --- a/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs +++ b/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs @@ -24,8 +24,8 @@ use crate::prelude::*; use crate::runtime::store::StoreOpaque; use crate::runtime::vm::{ - traphandlers::{tls, CallThreadState}, Unwind, VMRuntimeLimits, + traphandlers::{CallThreadState, tls}, }; use core::ops::ControlFlow; diff --git a/crates/wasmtime/src/runtime/vm/traphandlers/coredump_disabled.rs b/crates/wasmtime/src/runtime/vm/traphandlers/coredump_disabled.rs index d4dc86a1d9bc..c8ab8929cc63 100644 --- a/crates/wasmtime/src/runtime/vm/traphandlers/coredump_disabled.rs +++ b/crates/wasmtime/src/runtime/vm/traphandlers/coredump_disabled.rs @@ -1,5 +1,5 @@ -use crate::runtime::vm::traphandlers::CallThreadState; use crate::runtime::vm::VMRuntimeLimits; +use crate::runtime::vm::traphandlers::CallThreadState; /// A WebAssembly Coredump #[derive(Debug)] diff --git a/crates/wasmtime/src/runtime/vm/vmcontext.rs b/crates/wasmtime/src/runtime/vm/vmcontext.rs index 450cfde37a0b..8e03aaa79696 100644 --- a/crates/wasmtime/src/runtime/vm/vmcontext.rs +++ b/crates/wasmtime/src/runtime/vm/vmcontext.rs @@ -16,8 +16,8 @@ use core::ptr::{self, NonNull}; use core::sync::atomic::{AtomicUsize, Ordering}; use sptr::Strict; use wasmtime_environ::{ - BuiltinFunctionIndex, DefinedMemoryIndex, Unsigned, VMSharedTypeIndex, WasmHeapTopType, - WasmValType, VMCONTEXT_MAGIC, + BuiltinFunctionIndex, DefinedMemoryIndex, Unsigned, VMCONTEXT_MAGIC, VMSharedTypeIndex, + WasmHeapTopType, WasmValType, }; /// A function pointer that exposes the array calling convention. diff --git a/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs b/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs index 3976be30bb92..de460d904dd0 100644 --- a/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs +++ b/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs @@ -7,7 +7,7 @@ use crate::prelude::*; use crate::runtime::vm::{StoreBox, VMFuncRef}; use core::any::Any; use core::ptr::{self, NonNull}; -use wasmtime_environ::{VMSharedTypeIndex, VM_ARRAY_CALL_HOST_FUNC_MAGIC}; +use wasmtime_environ::{VM_ARRAY_CALL_HOST_FUNC_MAGIC, VMSharedTypeIndex}; /// The `VM*Context` for array-call host functions. /// diff --git a/crates/wasmtime/src/runtime/wave.rs b/crates/wasmtime/src/runtime/wave.rs index b250c292559a..c8eee596c30b 100644 --- a/crates/wasmtime/src/runtime/wave.rs +++ b/crates/wasmtime/src/runtime/wave.rs @@ -25,18 +25,10 @@ pub(crate) use unwrap_val; #[inline] pub(crate) fn canonicalize_nan32(val: f32) -> f32 { - if val.is_nan() { - f32::NAN - } else { - val - } + if val.is_nan() { f32::NAN } else { val } } #[inline] pub(crate) fn canonicalize_nan64(val: f64) -> f64 { - if val.is_nan() { - f64::NAN - } else { - val - } + if val.is_nan() { f64::NAN } else { val } } diff --git a/crates/wasmtime/src/runtime/wave/component.rs b/crates/wasmtime/src/runtime/wave/component.rs index 238512012f1c..4417dcbc8946 100644 --- a/crates/wasmtime/src/runtime/wave/component.rs +++ b/crates/wasmtime/src/runtime/wave/component.rs @@ -4,7 +4,7 @@ use std::borrow::Cow; use super::{canonicalize_nan32, canonicalize_nan64, unwrap_2val, unwrap_val}; use component::wasm_wave::wasm::{ - ensure_type_kind, DisplayValue, WasmFunc, WasmType, WasmTypeKind, WasmValue, WasmValueError, + DisplayValue, WasmFunc, WasmType, WasmTypeKind, WasmValue, WasmValueError, ensure_type_kind, }; macro_rules! maybe_unwrap_type { @@ -382,7 +382,7 @@ fn ensure_type_val(ty: &component::Type, val: &component::Val) -> Result<(), Was component::Val::Resource(_) => { return Err(WasmValueError::UnsupportedType( DisplayValue(val).to_string(), - )) + )); } // Any leaf variant type has already had its kind compared above; nothing further to check. diff --git a/crates/wasmtime/src/runtime/wave/core.rs b/crates/wasmtime/src/runtime/wave/core.rs index 15bd3c23dab5..c5da6028f9f5 100644 --- a/crates/wasmtime/src/runtime/wave/core.rs +++ b/crates/wasmtime/src/runtime/wave/core.rs @@ -65,7 +65,7 @@ impl WasmValue for crate::Val { _ => { return Err(WasmValueError::Other( "tuples only used for v128 (v64x2)".to_string(), - )) + )); } } let [l_val, h_val]: [Self; 2] = vals diff --git a/crates/wasmtime/src/sync_nostd.rs b/crates/wasmtime/src/sync_nostd.rs index cfc7fe27dfb8..3b92192201fc 100644 --- a/crates/wasmtime/src/sync_nostd.rs +++ b/crates/wasmtime/src/sync_nostd.rs @@ -17,7 +17,7 @@ use core::cell::UnsafeCell; use core::mem::MaybeUninit; use core::ops::{Deref, DerefMut}; -use core::sync::atomic::{AtomicU32, AtomicU8, Ordering}; +use core::sync::atomic::{AtomicU8, AtomicU32, Ordering}; pub struct OnceLock { val: UnsafeCell>, diff --git a/crates/wast/src/component.rs b/crates/wast/src/component.rs index 8a7f19dc08d0..e55cd87549c6 100644 --- a/crates/wast/src/component.rs +++ b/crates/wast/src/component.rs @@ -1,5 +1,5 @@ use crate::core; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use std::collections::BTreeSet; use std::fmt::Debug; use wast::component::WastVal; diff --git a/crates/wast/src/core.rs b/crates/wast/src/core.rs index 99101f780e29..b25553e7a885 100644 --- a/crates/wast/src/core.rs +++ b/crates/wast/src/core.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use std::fmt::{Display, LowerHex}; use wasmtime::{AnyRef, ExternRef, Store, Val}; use wast::core::{AbstractHeapType, HeapType, NanPattern, V128Pattern, WastArgCore, WastRetCore}; diff --git a/crates/wast/src/lib.rs b/crates/wast/src/lib.rs index d8749e6e1ec8..e6aef9d0950b 100644 --- a/crates/wast/src/lib.rs +++ b/crates/wast/src/lib.rs @@ -8,7 +8,7 @@ mod core; mod spectest; mod wast; -pub use crate::spectest::{link_spectest, SpectestConfig}; +pub use crate::spectest::{SpectestConfig, link_spectest}; pub use crate::wast::WastContext; /// Version number of this crate. diff --git a/crates/wast/src/spectest.rs b/crates/wast/src/spectest.rs index 924bf66d1c40..c3e2b88832fa 100644 --- a/crates/wast/src/spectest.rs +++ b/crates/wast/src/spectest.rs @@ -89,8 +89,8 @@ pub fn link_spectest( #[cfg(feature = "component-model")] pub fn link_component_spectest(linker: &mut component::Linker) -> Result<()> { - use std::sync::atomic::{AtomicU32, Ordering::SeqCst}; use std::sync::Arc; + use std::sync::atomic::{AtomicU32, Ordering::SeqCst}; use wasmtime::component::{Resource, ResourceType}; let engine = linker.engine().clone(); diff --git a/crates/wast/src/wast.rs b/crates/wast/src/wast.rs index d44a48171004..1e405fe2a559 100644 --- a/crates/wast/src/wast.rs +++ b/crates/wast/src/wast.rs @@ -2,7 +2,7 @@ use crate::component; use crate::core; use crate::spectest::*; -use anyhow::{anyhow, bail, Context as _}; +use anyhow::{Context as _, anyhow, bail}; use std::collections::HashMap; use std::path::Path; use std::str; @@ -333,9 +333,9 @@ where #[cfg(feature = "component-model")] Export::Component(_) => bail!("no global named `{field}`"), }; - Ok(Outcome::Ok(Results::Core( - vec![global.get(&mut self.store)], - ))) + Ok(Outcome::Ok(Results::Core(vec![ + global.get(&mut self.store), + ]))) } fn assert_return(&mut self, result: Outcome, results: &[WastRet<'_>]) -> Result<()> { diff --git a/crates/wiggle/generate/src/codegen_settings.rs b/crates/wiggle/generate/src/codegen_settings.rs index 4b0e4d6bce5a..ecc2e91729ed 100644 --- a/crates/wiggle/generate/src/codegen_settings.rs +++ b/crates/wiggle/generate/src/codegen_settings.rs @@ -1,5 +1,5 @@ use crate::config::{AsyncConf, ErrorConf, ErrorConfField, TracingConf}; -use anyhow::{anyhow, Error}; +use anyhow::{Error, anyhow}; use proc_macro2::{Ident, TokenStream}; use quote::quote; use std::collections::HashMap; diff --git a/crates/wiggle/generate/src/config.rs b/crates/wiggle/generate/src/config.rs index cfb1bccea146..f97591c7fb11 100644 --- a/crates/wiggle/generate/src/config.rs +++ b/crates/wiggle/generate/src/config.rs @@ -2,10 +2,9 @@ use { proc_macro2::{Span, TokenStream}, std::{collections::HashMap, path::PathBuf}, syn::{ - braced, bracketed, + Error, Ident, LitStr, Result, Token, braced, bracketed, parse::{Parse, ParseStream}, punctuated::Punctuated, - Error, Ident, LitStr, Result, Token, }, }; @@ -304,10 +303,11 @@ impl Parse for ErrorConf { return Err(Error::new( *i.err_loc(), format!( - "duplicate definition of rich error type for {:?}: previously defined at {:?}", - i.abi_error(), prev_def.err_loc(), - ), - )) + "duplicate definition of rich error type for {:?}: previously defined at {:?}", + i.abi_error(), + prev_def.err_loc(), + ), + )); } } } diff --git a/crates/wiggle/generate/src/funcs.rs b/crates/wiggle/generate/src/funcs.rs index 7b6528208ce7..f8f781096972 100644 --- a/crates/wiggle/generate/src/funcs.rs +++ b/crates/wiggle/generate/src/funcs.rs @@ -53,19 +53,16 @@ fn _define_func( let mut body = TokenStream::new(); let mut bounds = vec![names::trait_name(&module.name)]; - func.call_interface( - &module.name, - &mut Rust { - src: &mut body, - params: ¶m_names, - block_storage: Vec::new(), - blocks: Vec::new(), - module, - funcname: func.name.as_str(), - settings, - bounds: &mut bounds, - }, - ); + func.call_interface(&module.name, &mut Rust { + src: &mut body, + params: ¶m_names, + block_storage: Vec::new(), + blocks: Vec::new(), + module, + funcname: func.name.as_str(), + settings, + bounds: &mut bounds, + }); let mod_name = &module.name.as_str(); let func_name = &func.name.as_str(); diff --git a/crates/wiggle/generate/src/names.rs b/crates/wiggle/generate/src/names.rs index f1748e729f26..edda8b7af444 100644 --- a/crates/wiggle/generate/src/names.rs +++ b/crates/wiggle/generate/src/names.rs @@ -1,4 +1,4 @@ -use escaping::{escape_id, handle_2big_enum_variant, NamingConvention}; +use escaping::{NamingConvention, escape_id, handle_2big_enum_variant}; use heck::{ToShoutySnakeCase, ToSnakeCase}; use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; diff --git a/crates/wiggle/generate/src/types/record.rs b/crates/wiggle/generate/src/types/record.rs index 2b71d568fc91..2e7e9758efb8 100644 --- a/crates/wiggle/generate/src/types/record.rs +++ b/crates/wiggle/generate/src/types/record.rs @@ -1,4 +1,4 @@ -use crate::lifetimes::{anon_lifetime, LifetimeExt}; +use crate::lifetimes::{LifetimeExt, anon_lifetime}; use crate::names; use proc_macro2::TokenStream; diff --git a/crates/wiggle/generate/src/wasmtime.rs b/crates/wiggle/generate/src/wasmtime.rs index cb488f992792..3d4a5ef282ac 100644 --- a/crates/wiggle/generate/src/wasmtime.rs +++ b/crates/wiggle/generate/src/wasmtime.rs @@ -1,7 +1,7 @@ +use crate::CodegenSettings; use crate::config::Asyncness; use crate::funcs::func_bounds; use crate::names; -use crate::CodegenSettings; use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote}; use std::collections::HashSet; diff --git a/crates/wiggle/src/guest_type.rs b/crates/wiggle/src/guest_type.rs index 45bf01ec800c..19d76a042b1d 100644 --- a/crates/wiggle/src/guest_type.rs +++ b/crates/wiggle/src/guest_type.rs @@ -2,7 +2,7 @@ use crate::{GuestError, GuestMemory, GuestPtr}; use std::cell::UnsafeCell; use std::mem; use std::sync::atomic::{ - AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU64, AtomicU8, Ordering, + AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering, }; /// A trait for types which are used to report errors. Each type used in the diff --git a/crates/wiggle/src/lib.rs b/crates/wiggle/src/lib.rs index a7f4bed304cc..42160cc630a0 100644 --- a/crates/wiggle/src/lib.rs +++ b/crates/wiggle/src/lib.rs @@ -1,4 +1,4 @@ -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use std::borrow::Cow; use std::cell::UnsafeCell; use std::fmt; @@ -577,8 +577,9 @@ pub fn run_in_dummy_executor(future: F) -> Result return Ok(val), - Poll::Pending => - bail!("Cannot wait on pending future: must enable wiggle \"async\" future and execute on an async Store"), + Poll::Pending => bail!( + "Cannot wait on pending future: must enable wiggle \"async\" future and execute on an async Store" + ), } fn dummy_waker() -> Waker { diff --git a/crates/wiggle/test-helpers/examples/tracing.rs b/crates/wiggle/test-helpers/examples/tracing.rs index 6680b1f81e0c..2d48d4156fa9 100644 --- a/crates/wiggle/test-helpers/examples/tracing.rs +++ b/crates/wiggle/test-helpers/examples/tracing.rs @@ -1,6 +1,6 @@ use anyhow::Result; use wiggle::GuestMemory; -use wiggle_test::{impl_errno, HostMemory, WasiCtx}; +use wiggle_test::{HostMemory, WasiCtx, impl_errno}; /// The `errors` argument to the wiggle gives us a hook to map a rich error /// type like this one (typical of wiggle use cases in wasi-common and beyond) diff --git a/crates/wiggle/test-helpers/src/lib.rs b/crates/wiggle/test-helpers/src/lib.rs index 57c32ac607ba..9dc024e9dbbf 100644 --- a/crates/wiggle/test-helpers/src/lib.rs +++ b/crates/wiggle/test-helpers/src/lib.rs @@ -174,7 +174,7 @@ impl MemArea { } /// Enumerate all memareas of size `len` inside a given area - fn inside(&self, len: u32) -> impl Iterator + use<'_> { + fn inside(&self, len: u32) -> impl Iterator + use<> { let end: i64 = self.len as i64 - len as i64; let start = self.ptr; (0..end).into_iter().map(move |v| MemArea { @@ -205,20 +205,20 @@ mod test { } invert_equality(&[], &[MemArea { ptr: 0, len: 4096 }]); - invert_equality( - &[MemArea { ptr: 0, len: 1 }], - &[MemArea { ptr: 1, len: 4095 }], - ); - - invert_equality( - &[MemArea { ptr: 1, len: 1 }], - &[MemArea { ptr: 0, len: 1 }, MemArea { ptr: 2, len: 4094 }], - ); - - invert_equality( - &[MemArea { ptr: 1, len: 4095 }], - &[MemArea { ptr: 0, len: 1 }], - ); + invert_equality(&[MemArea { ptr: 0, len: 1 }], &[MemArea { + ptr: 1, + len: 4095, + }]); + + invert_equality(&[MemArea { ptr: 1, len: 1 }], &[ + MemArea { ptr: 0, len: 1 }, + MemArea { ptr: 2, len: 4094 }, + ]); + + invert_equality(&[MemArea { ptr: 1, len: 4095 }], &[MemArea { + ptr: 0, + len: 1, + }]); invert_equality( &[MemArea { ptr: 0, len: 1 }, MemArea { ptr: 1, len: 4095 }], diff --git a/crates/wiggle/tests/atoms.rs b/crates/wiggle/tests/atoms.rs index 7954e5fbc1e0..4c28490cd468 100644 --- a/crates/wiggle/tests/atoms.rs +++ b/crates/wiggle/tests/atoms.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/atoms.witx"], diff --git a/crates/wiggle/tests/atoms_async.rs b/crates/wiggle/tests/atoms_async.rs index 34ecfb04ec6a..33033f6da145 100644 --- a/crates/wiggle/tests/atoms_async.rs +++ b/crates/wiggle/tests/atoms_async.rs @@ -3,7 +3,7 @@ use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/atoms.witx"], diff --git a/crates/wiggle/tests/errors.rs b/crates/wiggle/tests/errors.rs index c67f16a3fd51..7e228be1a81d 100644 --- a/crates/wiggle/tests/errors.rs +++ b/crates/wiggle/tests/errors.rs @@ -2,7 +2,7 @@ mod convert_just_errno { use anyhow::Result; use wiggle::GuestMemory; - use wiggle_test::{impl_errno, HostMemory, WasiCtx}; + use wiggle_test::{HostMemory, WasiCtx, impl_errno}; /// The `errors` argument to the wiggle gives us a hook to map a rich error /// type like this one (typical of wiggle use cases in wasi-common and beyond) @@ -95,7 +95,7 @@ mod convert_multiple_error_types { pub use super::convert_just_errno::RichError; use anyhow::Result; use wiggle::GuestMemory; - use wiggle_test::{impl_errno, WasiCtx}; + use wiggle_test::{WasiCtx, impl_errno}; /// Test that we can map multiple types of errors. #[derive(Debug, thiserror::Error)] diff --git a/crates/wiggle/tests/flags.rs b/crates/wiggle/tests/flags.rs index 1bdb11e1c4f4..3c66a5f8aaeb 100644 --- a/crates/wiggle/tests/flags.rs +++ b/crates/wiggle/tests/flags.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/flags.witx"], diff --git a/crates/wiggle/tests/handles.rs b/crates/wiggle/tests/handles.rs index 09f6d988993c..10208dcfc637 100644 --- a/crates/wiggle/tests/handles.rs +++ b/crates/wiggle/tests/handles.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr, GuestType}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; const FD_VAL: u32 = 123; diff --git a/crates/wiggle/tests/ints.rs b/crates/wiggle/tests/ints.rs index 21fb40db1897..a866728e7742 100644 --- a/crates/wiggle/tests/ints.rs +++ b/crates/wiggle/tests/ints.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/ints.witx"], diff --git a/crates/wiggle/tests/lists.rs b/crates/wiggle/tests/lists.rs index 44e4958a6944..b9742ce96ba6 100644 --- a/crates/wiggle/tests/lists.rs +++ b/crates/wiggle/tests/lists.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr, GuestType}; -use wiggle_test::{impl_errno, HostMemory, MemArea, MemAreas, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, MemAreas, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/lists.witx"], diff --git a/crates/wiggle/tests/pointers.rs b/crates/wiggle/tests/pointers.rs index 128935ca6435..34e067777977 100644 --- a/crates/wiggle/tests/pointers.rs +++ b/crates/wiggle/tests/pointers.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/pointers.witx"], diff --git a/crates/wiggle/tests/records.rs b/crates/wiggle/tests/records.rs index 1642a7ed09f3..09a010ad2e99 100644 --- a/crates/wiggle/tests/records.rs +++ b/crates/wiggle/tests/records.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, MemAreas, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, MemAreas, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/records.witx"], diff --git a/crates/wiggle/tests/strings.rs b/crates/wiggle/tests/strings.rs index 6e820d209e31..4dc03ccc5e5f 100644 --- a/crates/wiggle/tests/strings.rs +++ b/crates/wiggle/tests/strings.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr}; -use wiggle_test::{impl_errno, HostMemory, MemArea, MemAreas, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, MemAreas, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/strings.witx"], diff --git a/crates/wiggle/tests/variant.rs b/crates/wiggle/tests/variant.rs index 43c2943cc167..ea7a684ba4c4 100644 --- a/crates/wiggle/tests/variant.rs +++ b/crates/wiggle/tests/variant.rs @@ -1,6 +1,6 @@ use proptest::prelude::*; use wiggle::{GuestMemory, GuestPtr, GuestType}; -use wiggle_test::{impl_errno, HostMemory, MemArea, WasiCtx}; +use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno}; wiggle::from_witx!({ witx: ["$CARGO_MANIFEST_DIR/tests/variant.witx"], @@ -22,11 +22,7 @@ fn mult_zero_nan(a: f32, b: u32) -> f32 { 0.0 } else { let product = a * b as f32; - if product.is_nan() { - 0.0 - } else { - product - } + if product.is_nan() { 0.0 } else { product } } } diff --git a/crates/wiggle/tests/wasmtime_sync.rs b/crates/wiggle/tests/wasmtime_sync.rs index 8152da0a7446..a4fab61df415 100644 --- a/crates/wiggle/tests/wasmtime_sync.rs +++ b/crates/wiggle/tests/wasmtime_sync.rs @@ -132,11 +132,9 @@ fn test_async_host_func_pending() { let trap = shim_inst .get_func(&mut store, "double_int_return_float_shim") .unwrap() - .call( - &mut store, - &[input.into(), result_location.into()], - &mut [Val::I32(0)], - ) + .call(&mut store, &[input.into(), result_location.into()], &mut [ + Val::I32(0), + ]) .unwrap_err(); assert!( format!("{trap:?}").contains("Cannot wait on pending future"), diff --git a/crates/winch/src/builder.rs b/crates/winch/src/builder.rs index 16cdb4142fcd..82ab3a405291 100644 --- a/crates/winch/src/builder.rs +++ b/crates/winch/src/builder.rs @@ -1,10 +1,10 @@ use crate::compiler::Compiler; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use std::sync::Arc; use target_lexicon::Triple; use wasmtime_cranelift::isa_builder::IsaBuilder; use wasmtime_environ::{CompilerBuilder, Setting, Tunables}; -use winch_codegen::{isa, TargetIsa}; +use winch_codegen::{TargetIsa, isa}; /// Compiler builder. struct Builder { diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rs index 810565acf699..4cd2369bcb29 100644 --- a/crates/wit-bindgen/src/lib.rs +++ b/crates/wit-bindgen/src/lib.rs @@ -1,4 +1,4 @@ -use crate::rust::{to_rust_ident, to_rust_upper_camel_case, RustGenerator, TypeMode}; +use crate::rust::{RustGenerator, TypeMode, to_rust_ident, to_rust_upper_camel_case}; use crate::types::{TypeInfo, Types}; use anyhow::bail; use heck::*; @@ -798,16 +798,13 @@ fn _new( format!("{ty_index}::new_instance(&mut store, _instance)?"); } } - let prev = self.exports.fields.insert( - field, - ExportField { - ty, - ty_index, - load, - get_index_from_component, - get_index_from_instance, - }, - ); + let prev = self.exports.fields.insert(field, ExportField { + ty, + ty_index, + load, + get_index_from_component, + get_index_from_instance, + }); assert!(prev.is_none()); } @@ -1079,7 +1076,9 @@ impl<_T> {camel}Pre<_T> {{ unused_keys.sort(); if !unused_keys.is_empty() { - anyhow::bail!("interfaces were specified in the `with` config option but are not referenced in the target world: {unused_keys:?}"); + anyhow::bail!( + "interfaces were specified in the `with` config option but are not referenced in the target world: {unused_keys:?}" + ); } if let TrappableImports::Only(only) = &self.opts.trappable_imports { @@ -1090,7 +1089,9 @@ impl<_T> {camel}Pre<_T> {{ if !unused_imports.is_empty() { unused_imports.sort(); - anyhow::bail!("names specified in the `trappable_imports` config option but are not referenced in the target world: {unused_imports:?}"); + anyhow::bail!( + "names specified in the `trappable_imports` config option but are not referenced in the target world: {unused_imports:?}" + ); } } diff --git a/crates/wit-bindgen/src/rust.rs b/crates/wit-bindgen/src/rust.rs index 7b40523be26d..f15b28af1eed 100644 --- a/crates/wit-bindgen/src/rust.rs +++ b/crates/wit-bindgen/src/rust.rs @@ -1,4 +1,4 @@ -use crate::{types::TypeInfo, Ownership}; +use crate::{Ownership, types::TypeInfo}; use heck::*; use wit_parser::*; @@ -316,12 +316,9 @@ pub trait RustGenerator<'a> { info.has_list && info.borrowed && info.owned - && matches!( - self.ownership(), - Ownership::Borrowing { - duplicate_if_necessary: true - } - ) + && matches!(self.ownership(), Ownership::Borrowing { + duplicate_if_necessary: true + }) } fn lifetime_for(&self, info: &TypeInfo, mode: TypeMode) -> Option<&'static str> { diff --git a/examples/component/main.rs b/examples/component/main.rs index c26e70b57607..40b588916f39 100644 --- a/examples/component/main.rs +++ b/examples/component/main.rs @@ -2,8 +2,8 @@ use anyhow::Context; use std::{fs, path::Path}; use wasmtime::{ - component::{bindgen, Component, Linker}, Config, Engine, Result, Store, + component::{Component, Linker, bindgen}, }; // Generate bindings of the guest and host components. @@ -47,12 +47,9 @@ fn main() -> Result<()> { // Create our component and call our generated host function. let component = Component::from_binary(&engine, &component)?; - let mut store = Store::new( - &engine, - MyState { - host: HostComponent {}, - }, - ); + let mut store = Store::new(&engine, MyState { + host: HostComponent {}, + }); let mut linker = Linker::new(&engine); host::add_to_linker(&mut linker, |state: &mut MyState| &mut state.host)?; let convert = Convert::instantiate(&mut store, &component, &linker)?; diff --git a/examples/externref.rs b/examples/externref.rs index 2b98b2fb9ecc..46bb5975c116 100644 --- a/examples/externref.rs +++ b/examples/externref.rs @@ -19,10 +19,12 @@ fn main() -> Result<()> { println!("Creating new `externref`..."); let externref = ExternRef::new(&mut store, "Hello, World!")?; - assert!(externref - .data(&store)? - .expect("should have host data") - .is::<&'static str>()); + assert!( + externref + .data(&store)? + .expect("should have host data") + .is::<&'static str>() + ); assert_eq!( *externref .data(&store)? diff --git a/examples/hello.rs b/examples/hello.rs index fb0311f9c76f..0e49c40cb0e3 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -24,13 +24,10 @@ fn main() -> Result<()> { // contains an arbitrary piece of host information, and we use `MyState` // here. println!("Initializing..."); - let mut store = Store::new( - &engine, - MyState { - name: "hello, world!".to_string(), - count: 0, - }, - ); + let mut store = Store::new(&engine, MyState { + name: "hello, world!".to_string(), + count: 0, + }); // Our wasm module we'll be instantiating requires one imported function. // the function takes no parameters and returns no results. We create a host diff --git a/examples/min-platform/src/main.rs b/examples/min-platform/src/main.rs index 3aab4c4169f0..9d268e092c9b 100644 --- a/examples/min-platform/src/main.rs +++ b/examples/min-platform/src/main.rs @@ -8,8 +8,8 @@ fn main() -> Result<()> { #[cfg(target_os = "linux")] fn main() -> Result<()> { - use anyhow::{anyhow, Context}; - use libloading::os::unix::{Library, Symbol, RTLD_GLOBAL, RTLD_NOW}; + use anyhow::{Context, anyhow}; + use libloading::os::unix::{Library, RTLD_GLOBAL, RTLD_NOW, Symbol}; use object::{Object, ObjectSymbol}; use std::io::Write; use wasmtime::{Config, Engine}; diff --git a/examples/tokio/main.rs b/examples/tokio/main.rs index f35138fe7525..7e9d548c82e8 100644 --- a/examples/tokio/main.rs +++ b/examples/tokio/main.rs @@ -5,7 +5,7 @@ use wasmtime::{Config, Engine, Linker, Module, Store}; // For this example we want to use the async version of wasi_common. // Notably, this version of wasi uses a scheduler that will async yield // when sleeping in `poll_oneoff`. -use wasi_common::{tokio::WasiCtxBuilder, WasiCtx}; +use wasi_common::{WasiCtx, tokio::WasiCtxBuilder}; #[tokio::main] async fn main() -> Result<(), Error> { diff --git a/examples/wasip1-async/main.rs b/examples/wasip1-async/main.rs index 1c266752af88..73f18c5c24ce 100644 --- a/examples/wasip1-async/main.rs +++ b/examples/wasip1-async/main.rs @@ -9,8 +9,8 @@ You can execute this example with: use anyhow::Result; use wasmtime::{Config, Engine, Linker, Module, Store}; -use wasmtime_wasi::preview1::{self, WasiP1Ctx}; use wasmtime_wasi::WasiCtxBuilder; +use wasmtime_wasi::preview1::{self, WasiP1Ctx}; #[tokio::main] async fn main() -> Result<()> { diff --git a/fuzz/build.rs b/fuzz/build.rs index 98b364f0df4f..73f7642fb601 100644 --- a/fuzz/build.rs +++ b/fuzz/build.rs @@ -5,9 +5,9 @@ fn main() -> anyhow::Result<()> { } mod component { - use anyhow::{anyhow, Context, Error, Result}; + use anyhow::{Context, Error, Result, anyhow}; use arbitrary::Unstructured; - use component_fuzz_util::{Declarations, TestCase, Type, MAX_TYPE_DEPTH}; + use component_fuzz_util::{Declarations, MAX_TYPE_DEPTH, TestCase, Type}; use proc_macro2::TokenStream; use quote::quote; use rand::rngs::StdRng; diff --git a/fuzz/fuzz_targets/cranelift-fuzzgen.rs b/fuzz/fuzz_targets/cranelift-fuzzgen.rs index dd156567e921..a5541ee23680 100644 --- a/fuzz/fuzz_targets/cranelift-fuzzgen.rs +++ b/fuzz/fuzz_targets/cranelift-fuzzgen.rs @@ -1,10 +1,10 @@ #![no_main] +use cranelift_codegen::Context; use cranelift_codegen::ir::Function; use cranelift_codegen::ir::Signature; use cranelift_codegen::ir::UserExternalName; use cranelift_codegen::ir::UserFuncName; -use cranelift_codegen::Context; use cranelift_control::ControlPlane; use libfuzzer_sys::arbitrary; use libfuzzer_sys::arbitrary::Arbitrary; @@ -12,9 +12,9 @@ use libfuzzer_sys::arbitrary::Unstructured; use libfuzzer_sys::fuzz_target; use std::collections::HashMap; use std::fmt; +use std::sync::LazyLock; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; -use std::sync::LazyLock; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::{LibCall, TrapCode}; diff --git a/fuzz/fuzz_targets/cranelift-icache.rs b/fuzz/fuzz_targets/cranelift-icache.rs index 044a89d311f3..790ab5a7f9c5 100644 --- a/fuzz/fuzz_targets/cranelift-icache.rs +++ b/fuzz/fuzz_targets/cranelift-icache.rs @@ -1,13 +1,14 @@ #![no_main] use cranelift_codegen::{ + Context, cursor::{Cursor, FuncCursor}, incremental_cache as icache, ir::{ - self, immediates::Imm64, ExternalName, Function, LibCall, Signature, UserExternalName, - UserFuncName, + self, ExternalName, Function, LibCall, Signature, UserExternalName, UserFuncName, + immediates::Imm64, }, - isa, Context, + isa, }; use libfuzzer_sys::{ arbitrary::{self, Arbitrary, Unstructured}, diff --git a/fuzz/fuzz_targets/differential.rs b/fuzz/fuzz_targets/differential.rs index 5cc3fb4b4011..87961b2ffdad 100644 --- a/fuzz/fuzz_targets/differential.rs +++ b/fuzz/fuzz_targets/differential.rs @@ -8,7 +8,7 @@ use std::sync::{Mutex, Once}; use wasmtime_fuzzing::generators::{Config, DiffValue, DiffValueType, SingleInstModule}; use wasmtime_fuzzing::oracles::diff_wasmtime::WasmtimeInstance; use wasmtime_fuzzing::oracles::engine::{build_allowed_env_list, parse_env_list}; -use wasmtime_fuzzing::oracles::{differential, engine, log_wasm, DiffEqResult}; +use wasmtime_fuzzing::oracles::{DiffEqResult, differential, engine, log_wasm}; // Upper limit on the number of invocations for each WebAssembly function // executed by this fuzz target. @@ -36,14 +36,13 @@ fuzz_target!(|data: &[u8]| { // Retrieve the configuration for this fuzz target from `ALLOWED_*` // environment variables. - let allowed_engines = build_allowed_env_list( - parse_env_list("ALLOWED_ENGINES"), - &["wasmtime", "wasmi", "spec", "v8", "winch"], - ); - let allowed_modules = build_allowed_env_list( - parse_env_list("ALLOWED_MODULES"), - &["wasm-smith", "single-inst"], - ); + let allowed_engines = build_allowed_env_list(parse_env_list("ALLOWED_ENGINES"), &[ + "wasmtime", "wasmi", "spec", "v8", "winch", + ]); + let allowed_modules = build_allowed_env_list(parse_env_list("ALLOWED_MODULES"), &[ + "wasm-smith", + "single-inst", + ]); *ALLOWED_ENGINES.lock().unwrap() = allowed_engines; *ALLOWED_MODULES.lock().unwrap() = allowed_modules; diff --git a/fuzz/fuzz_targets/dominator_tree.rs b/fuzz/fuzz_targets/dominator_tree.rs index e9e78a52f2cf..dd6a49c7dde6 100644 --- a/fuzz/fuzz_targets/dominator_tree.rs +++ b/fuzz/fuzz_targets/dominator_tree.rs @@ -11,7 +11,7 @@ use cranelift_codegen::cursor::{Cursor, FuncCursor}; use cranelift_codegen::dominator_tree::{DominatorTree, SimpleDominatorTree}; use cranelift_codegen::flowgraph::ControlFlowGraph; use cranelift_codegen::ir::{ - types::I32, Block, BlockCall, Function, InstBuilder, JumpTableData, Value, + Block, BlockCall, Function, InstBuilder, JumpTableData, Value, types::I32, }; const MAX_BLOCKS: u16 = 1 << 12; diff --git a/fuzz/fuzz_targets/instantiate.rs b/fuzz/fuzz_targets/instantiate.rs index cc5ae10f516b..fdee9b66f141 100644 --- a/fuzz/fuzz_targets/instantiate.rs +++ b/fuzz/fuzz_targets/instantiate.rs @@ -2,7 +2,7 @@ use libfuzzer_sys::arbitrary::{Arbitrary, Result, Unstructured}; use wasmtime_fuzzing::generators::Config; -use wasmtime_fuzzing::oracles::{instantiate, Timeout}; +use wasmtime_fuzzing::oracles::{Timeout, instantiate}; use wasmtime_fuzzing::single_module_fuzzer::KnownValid; wasmtime_fuzzing::single_module_fuzzer!(execute gen_module); diff --git a/fuzz/fuzz_targets/table_ops.rs b/fuzz/fuzz_targets/table_ops.rs index 93c9cecce714..279d12874c6a 100644 --- a/fuzz/fuzz_targets/table_ops.rs +++ b/fuzz/fuzz_targets/table_ops.rs @@ -1,7 +1,7 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use wasmtime_fuzzing::generators::{table_ops::TableOps, Config}; +use wasmtime_fuzzing::generators::{Config, table_ops::TableOps}; fuzz_target!(|pair: (Config, TableOps)| { let (config, ops) = pair; diff --git a/pulley/examples/objdump.rs b/pulley/examples/objdump.rs index ad7b57b0dd51..0f1c6fa4f0a5 100644 --- a/pulley/examples/objdump.rs +++ b/pulley/examples/objdump.rs @@ -4,7 +4,7 @@ //! //! cargo run --example objdump -F disas -p pulley-interpreter foo.cwasm -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use object::{File, Object as _, ObjectSection, ObjectSymbol, SymbolKind}; use pulley_interpreter::decode::Decoder; use pulley_interpreter::disas::Disassembler; diff --git a/pulley/src/decode.rs b/pulley/src/decode.rs index 25bf25825eb4..bf764883b213 100644 --- a/pulley/src/decode.rs +++ b/pulley/src/decode.rs @@ -3,8 +3,8 @@ use core::ptr::NonNull; use alloc::vec::Vec; -use cranelift_bitset::scalar::ScalarBitSetStorage; use cranelift_bitset::ScalarBitSet; +use cranelift_bitset::scalar::ScalarBitSetStorage; use crate::imms::*; use crate::opcode::*; diff --git a/pulley/src/interp/tail_loop.rs b/pulley/src/interp/tail_loop.rs index d9f63ff6afb8..8145e95a06c2 100644 --- a/pulley/src/interp/tail_loop.rs +++ b/pulley/src/interp/tail_loop.rs @@ -27,9 +27,9 @@ //! at this time but doesn't actually run anywhere. use super::*; -use crate::decode::{unwrap_uninhabited, ExtendedOpVisitor}; -use crate::opcode::Opcode; use crate::ExtendedOpcode; +use crate::decode::{ExtendedOpVisitor, unwrap_uninhabited}; +use crate::opcode::Opcode; type Handler = fn(Interpreter<'_>) -> Done; diff --git a/pulley/tests/all/interp.rs b/pulley/tests/all/interp.rs index c7e4014c992b..d5161e791f1f 100644 --- a/pulley/tests/all/interp.rs +++ b/pulley/tests/all/interp.rs @@ -836,15 +836,12 @@ fn trap() { let dst = XReg::new(0).unwrap(); unsafe { - run( - &mut vm, - &[ - Op::Xconst16(Xconst16 { dst, imm: 1 }), - Op::ExtendedOp(ExtendedOp::Trap(Trap {})), - Op::Xconst16(Xconst16 { dst, imm: 2 }), - Op::Ret(Ret {}), - ], - ) + run(&mut vm, &[ + Op::Xconst16(Xconst16 { dst, imm: 1 }), + Op::ExtendedOp(ExtendedOp::Trap(Trap {})), + Op::Xconst16(Xconst16 { dst, imm: 2 }), + Op::Ret(Ret {}), + ]) .unwrap_err(); } diff --git a/src/commands/compile.rs b/src/commands/compile.rs index f8819de66b77..616b531b2e9a 100644 --- a/src/commands/compile.rs +++ b/src/commands/compile.rs @@ -1,6 +1,6 @@ //! The module that implements the `wasmtime compile` command. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use clap::Parser; use std::fs; use std::path::PathBuf; diff --git a/src/commands/run.rs b/src/commands/run.rs index e154ad50542c..f9bf90280252 100644 --- a/src/commands/run.rs +++ b/src/commands/run.rs @@ -7,13 +7,13 @@ use crate::common::{Profile, RunCommon, RunTarget}; -use anyhow::{anyhow, bail, Context as _, Error, Result}; +use anyhow::{Context as _, Error, Result, anyhow, bail}; use clap::Parser; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::thread; -use wasi_common::sync::{ambient_authority, Dir, TcpListener, WasiCtxBuilder}; +use wasi_common::sync::{Dir, TcpListener, WasiCtxBuilder, ambient_authority}; use wasmtime::{Engine, Func, Module, Store, StoreLimits, Val, ValType}; use wasmtime_wasi::WasiView; @@ -27,7 +27,7 @@ use wasmtime_wasi_threads::WasiThreadsCtx; use wasmtime_wasi_config::{WasiConfig, WasiConfigVariables}; #[cfg(feature = "wasi-http")] use wasmtime_wasi_http::{ - WasiHttpCtx, DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, DEFAULT_OUTGOING_BODY_CHUNK_SIZE, + DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, DEFAULT_OUTGOING_BODY_CHUNK_SIZE, WasiHttpCtx, }; #[cfg(feature = "wasi-keyvalue")] use wasmtime_wasi_keyvalue::{WasiKeyValue, WasiKeyValueCtx, WasiKeyValueCtxBuilder}; @@ -371,9 +371,11 @@ impl RunCommand { store.set_epoch_deadline(1); let engine = store.engine().clone(); - thread::spawn(move || loop { - thread::sleep(interval); - engine.increment_epoch(); + thread::spawn(move || { + loop { + thread::sleep(interval); + engine.increment_epoch(); + } }); let path = path.to_string(); @@ -741,7 +743,9 @@ impl RunCommand { if self.run.common.wasi.keyvalue == Some(true) { #[cfg(not(feature = "wasi-keyvalue"))] { - bail!("Cannot enable wasi-keyvalue when the binary is not compiled with this feature."); + bail!( + "Cannot enable wasi-keyvalue when the binary is not compiled with this feature." + ); } #[cfg(all(feature = "wasi-keyvalue", feature = "component-model"))] { diff --git a/src/commands/serve.rs b/src/commands/serve.rs index 73a7867b81e1..01918bf856ea 100644 --- a/src/commands/serve.rs +++ b/src/commands/serve.rs @@ -1,23 +1,23 @@ use crate::common::{Profile, RunCommon, RunTarget}; -use anyhow::{anyhow, bail, Result}; +use anyhow::{Result, anyhow, bail}; use clap::Parser; use std::net::SocketAddr; use std::{ path::PathBuf, sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, Arc, + atomic::{AtomicBool, AtomicU64, Ordering}, }, }; use wasmtime::component::Linker; use wasmtime::{Engine, Store, StoreLimits}; use wasmtime_wasi::{StreamError, StreamResult, WasiCtx, WasiCtxBuilder, WasiView}; -use wasmtime_wasi_http::bindings::http::types::Scheme; use wasmtime_wasi_http::bindings::ProxyPre; +use wasmtime_wasi_http::bindings::http::types::Scheme; use wasmtime_wasi_http::io::TokioIo; use wasmtime_wasi_http::{ - body::HyperOutgoingBody, WasiHttpCtx, WasiHttpView, DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, - DEFAULT_OUTGOING_BODY_CHUNK_SIZE, + DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, DEFAULT_OUTGOING_BODY_CHUNK_SIZE, WasiHttpCtx, + WasiHttpView, body::HyperOutgoingBody, }; #[cfg(feature = "wasi-config")] diff --git a/src/commands/settings.rs b/src/commands/settings.rs index 23de74bce7d3..1cb7d3c996a2 100644 --- a/src/commands/settings.rs +++ b/src/commands/settings.rs @@ -1,8 +1,8 @@ //! The module that implements the `wasmtime settings` command. -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use clap::Parser; -use serde::{ser::SerializeMap, Serialize}; +use serde::{Serialize, ser::SerializeMap}; use std::collections::BTreeMap; use std::str::FromStr; use wasmtime_environ::{CompilerBuilder, FlagValue, Setting, SettingKind, Tunables}; diff --git a/src/common.rs b/src/common.rs index 0f60335ac197..efd478cc57bc 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,13 +1,13 @@ //! Common functionality shared between command implementations. -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use clap::Parser; use std::net::TcpListener; use std::{fs::File, path::Path, time::Duration}; use wasmtime::{Engine, Module, Precompiled, StoreLimits, StoreLimitsBuilder}; -use wasmtime_cli_flags::{opt::WasmtimeOptionValue, CommonOptions}; -use wasmtime_wasi::bindings::LinkOptions; +use wasmtime_cli_flags::{CommonOptions, opt::WasmtimeOptionValue}; use wasmtime_wasi::WasiCtxBuilder; +use wasmtime_wasi::bindings::LinkOptions; #[cfg(feature = "component-model")] use wasmtime::component::Component; diff --git a/tests/all/arrays.rs b/tests/all/arrays.rs index 3a2d271af0b4..655f1df92aa6 100644 --- a/tests/all/arrays.rs +++ b/tests/all/arrays.rs @@ -113,11 +113,11 @@ fn array_new_fixed_with_elems() -> Result<()> { FieldType::new(Mutability::Const, ValType::I32.into()), ); let pre = ArrayRefPre::new(&mut store, array_ty); - let array = ArrayRef::new_fixed( - &mut store, - &pre, - &[Val::I32(11), Val::I32(22), Val::I32(33)], - )?; + let array = ArrayRef::new_fixed(&mut store, &pre, &[ + Val::I32(11), + Val::I32(22), + Val::I32(33), + ])?; assert_eq!(array.len(&store)?, 3); for i in 0..3 { assert_eq!(array.get(&mut store, i)?.unwrap_i32(), (i as i32 + 1) * 11); @@ -226,11 +226,11 @@ fn array_len_non_empty() -> Result<()> { ); let pre = ArrayRefPre::new(&mut store, array_ty); - let array = ArrayRef::new_fixed( - &mut store, - &pre, - &[Val::I32(11), Val::I32(22), Val::I32(33)], - )?; + let array = ArrayRef::new_fixed(&mut store, &pre, &[ + Val::I32(11), + Val::I32(22), + Val::I32(33), + ])?; assert_eq!(array.len(&store)?, 3); Ok(()) @@ -246,11 +246,11 @@ fn array_get_in_bounds() -> Result<()> { ); let pre = ArrayRefPre::new(&mut store, array_ty); - let array = ArrayRef::new_fixed( - &mut store, - &pre, - &[Val::I32(11), Val::I32(22), Val::I32(33)], - )?; + let array = ArrayRef::new_fixed(&mut store, &pre, &[ + Val::I32(11), + Val::I32(22), + Val::I32(33), + ])?; assert_eq!(array.get(&mut store, 0)?.unwrap_i32(), 11); assert_eq!(array.get(&mut store, 1)?.unwrap_i32(), 22); @@ -269,11 +269,11 @@ fn array_get_out_of_bounds() -> Result<()> { ); let pre = ArrayRefPre::new(&mut store, array_ty); - let array = ArrayRef::new_fixed( - &mut store, - &pre, - &[Val::I32(11), Val::I32(22), Val::I32(33)], - )?; + let array = ArrayRef::new_fixed(&mut store, &pre, &[ + Val::I32(11), + Val::I32(22), + Val::I32(33), + ])?; assert!(array.get(&mut store, 3).is_err()); assert!(array.get(&mut store, 4).is_err()); @@ -425,11 +425,11 @@ fn array_set_immutable_elems() -> Result<()> { ); let pre = ArrayRefPre::new(&mut store, array_ty); - let array = ArrayRef::new_fixed( - &mut store, - &pre, - &[Val::I32(11), Val::I32(22), Val::I32(33)], - )?; + let array = ArrayRef::new_fixed(&mut store, &pre, &[ + Val::I32(11), + Val::I32(22), + Val::I32(33), + ])?; assert!(array.set(&mut store, 0, Val::I32(22)).is_err()); assert!(array.set(&mut store, 1, Val::I32(33)).is_err()); @@ -506,11 +506,11 @@ fn array_elems_non_empty() -> Result<()> { FieldType::new(Mutability::Const, ValType::I32.into()), ); let pre = ArrayRefPre::new(&mut store, array_ty); - let array = ArrayRef::new_fixed( - &mut store, - &pre, - &[Val::I32(11), Val::I32(22), Val::I32(33)], - )?; + let array = ArrayRef::new_fixed(&mut store, &pre, &[ + Val::I32(11), + Val::I32(22), + Val::I32(33), + ])?; let mut elems = array.elems(&mut store)?; assert_eq!(elems.len(), 3); assert_eq!(elems.next().unwrap().unwrap_i32(), 11); diff --git a/tests/all/async_functions.rs b/tests/all/async_functions.rs index fc891e6ea19a..d7696ccb393e 100644 --- a/tests/all/async_functions.rs +++ b/tests/all/async_functions.rs @@ -235,11 +235,10 @@ async fn suspend_while_suspending() { ", ) .unwrap(); - let instance = Instance::new_async( - &mut store, - &module, - &[sync_call_async_thunk.into(), async_import.into()], - ) + let instance = Instance::new_async(&mut store, &module, &[ + sync_call_async_thunk.into(), + async_import.into(), + ]) .await .unwrap(); let func = instance.get_func(&mut store, "").unwrap(); diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs index 7df340064111..2917d17921af 100644 --- a/tests/all/cli_tests.rs +++ b/tests/all/cli_tests.rs @@ -1,6 +1,6 @@ #![cfg(not(miri))] -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; @@ -1109,7 +1109,7 @@ fn increase_stack_size() -> Result<()> { mod test_programs { use super::{get_wasmtime_command, run_wasmtime}; - use anyhow::{bail, Context, Result}; + use anyhow::{Context, Result, bail}; use http_body_util::BodyExt; use hyper::header::HeaderValue; use std::io::{BufRead, BufReader, Read, Write}; @@ -1739,9 +1739,9 @@ mod test_programs { #[tokio::test] #[ignore] // TODO: printing stderr in the child and killing the child at the - // end of this test race so the stderr may be present or not. Need - // to implement a more graceful shutdown routine for `wasmtime - // serve`. + // end of this test race so the stderr may be present or not. Need + // to implement a more graceful shutdown routine for `wasmtime + // serve`. async fn cli_serve_respect_pooling_options() -> Result<()> { let server = WasmtimeServe::new(CLI_SERVE_ECHO_ENV_COMPONENT, |cmd| { cmd.arg("-Opooling-total-memories=0").arg("-Scli"); diff --git a/tests/all/code_too_large.rs b/tests/all/code_too_large.rs index 5c71a518734c..6fa21c8b85b5 100644 --- a/tests/all/code_too_large.rs +++ b/tests/all/code_too_large.rs @@ -55,9 +55,10 @@ fn code_too_large_without_panic() -> Result<()> { let store = Store::new(&engine, ()); let result = Module::new(store.engine(), &module.finish()); match result { - Err(e) => assert!(e - .to_string() - .starts_with("Compilation error: Code for function is too large")), + Err(e) => assert!( + e.to_string() + .starts_with("Compilation error: Code for function is too large") + ), Ok(_) => panic!("Please adjust limits to make the module too large to compile!"), } Ok(()) diff --git a/tests/all/component_model.rs b/tests/all/component_model.rs index bb6ebc98bc36..81598dc7f697 100644 --- a/tests/all/component_model.rs +++ b/tests/all/component_model.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use component_test_util::{async_engine, engine, TypedFuncExt}; +use component_test_util::{TypedFuncExt, async_engine, engine}; use std::fmt::Write; use std::iter; use wasmtime::component::Component; diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rs index 26a2df86a954..b4cb7a4cc999 100644 --- a/tests/all/component_model/async.rs +++ b/tests/all/component_model/async.rs @@ -1,6 +1,6 @@ #![cfg(not(miri))] -use crate::async_functions::{execute_across_threads, PollOnce}; +use crate::async_functions::{PollOnce, execute_across_threads}; use anyhow::Result; use wasmtime::component::*; use wasmtime::{Engine, Store, StoreContextMut, Trap}; diff --git a/tests/all/component_model/bindgen.rs b/tests/all/component_model/bindgen.rs index e89b04f0ca09..a0b9927a195e 100644 --- a/tests/all/component_model/bindgen.rs +++ b/tests/all/component_model/bindgen.rs @@ -4,8 +4,8 @@ use super::engine; use anyhow::Result; use wasmtime::{ - component::{Component, Linker}, Store, + component::{Component, Linker}, }; mod ownership; @@ -598,31 +598,28 @@ mod exported_resources { // call the root export `f` twice let ret = i.call_f(&mut store, Resource::new_own(1), Resource::new_own(2))?; assert_eq!(ret.rep(), 2); - assert_eq!( - mem::take(&mut store.data_mut().hostcalls), - [Hostcall::DropRootX(1)] - ); + assert_eq!(mem::take(&mut store.data_mut().hostcalls), [ + Hostcall::DropRootX(1) + ]); let ret = i.call_f(&mut store, Resource::new_own(3), Resource::new_own(4))?; assert_eq!(ret.rep(), 4); - assert_eq!( - mem::take(&mut store.data_mut().hostcalls), - [Hostcall::DropRootX(3)] - ); + assert_eq!(mem::take(&mut store.data_mut().hostcalls), [ + Hostcall::DropRootX(3) + ]); // interact with the `b` export let b = i.b(); let b_x = b.x().call_constructor(&mut store, Resource::new_own(5))?; - assert_eq!( - mem::take(&mut store.data_mut().hostcalls), - [Hostcall::DropAX(5), Hostcall::NewA] - ); + assert_eq!(mem::take(&mut store.data_mut().hostcalls), [ + Hostcall::DropAX(5), + Hostcall::NewA + ]); b.x().call_foo(&mut store, b_x)?; assert_eq!(mem::take(&mut store.data_mut().hostcalls), []); b_x.resource_drop(&mut store)?; - assert_eq!( - mem::take(&mut store.data_mut().hostcalls), - [Hostcall::DropAX(0)], - ); + assert_eq!(mem::take(&mut store.data_mut().hostcalls), [ + Hostcall::DropAX(0) + ],); Ok(()) } } @@ -688,7 +685,10 @@ mod unstable_import { } fn assert_failure(link_options: &LinkOptions) { let err = run_with_options(link_options).unwrap_err().to_string(); - assert_eq!(err, "component imports instance `foo:foo/my-interface`, but a matching implementation was not found in the linker"); + assert_eq!( + err, + "component imports instance `foo:foo/my-interface`, but a matching implementation was not found in the linker" + ); } fn run_with_options(link_options: &LinkOptions) -> Result<()> { diff --git a/tests/all/component_model/bindgen/ownership.rs b/tests/all/component_model/bindgen/ownership.rs index 14417a3c281c..df1df46d7d1d 100644 --- a/tests/all/component_model/bindgen/ownership.rs +++ b/tests/all/component_model/bindgen/ownership.rs @@ -1,8 +1,8 @@ use super::{super::REALLOC_AND_FREE, engine}; use anyhow::Result; use wasmtime::{ - component::{Component, Linker}, Store, + component::{Component, Linker}, }; fn component() -> String { diff --git a/tests/all/component_model/bindgen/results.rs b/tests/all/component_model/bindgen/results.rs index b330a1269e76..e7950a9812c8 100644 --- a/tests/all/component_model/bindgen/results.rs +++ b/tests/all/component_model/bindgen/results.rs @@ -1,8 +1,8 @@ use super::{super::REALLOC_AND_FREE, engine}; -use anyhow::{anyhow, Error}; +use anyhow::{Error, anyhow}; use wasmtime::{ - component::{Component, Linker}, Store, + component::{Component, Linker}, }; mod empty_error { @@ -548,13 +548,10 @@ mod record_error { .expect("no trap") .err() .expect("error returned"); - assert!(matches!( - e, - record_error::foo::E2 { - line: 420, - col: 1312 - } - )); + assert!(matches!(e, record_error::foo::E2 { + line: 420, + col: 1312 + })); let e = results .foo() diff --git a/tests/all/component_model/call_hook.rs b/tests/all/component_model/call_hook.rs index 91f71151aa48..2a166678b51d 100644 --- a/tests/all/component_model/call_hook.rs +++ b/tests/all/component_model/call_hook.rs @@ -1,8 +1,8 @@ #![cfg(not(miri))] use super::REALLOC_AND_FREE; -use crate::call_hook::{sync_call_hook, Context, State}; -use anyhow::{bail, Result}; +use crate::call_hook::{Context, State, sync_call_hook}; +use anyhow::{Result, bail}; use std::future::Future; use std::pin::Pin; use std::task::{self, Poll}; diff --git a/tests/all/component_model/dynamic.rs b/tests/all/component_model/dynamic.rs index a27fd52df6e2..4b4fdd5b20d2 100644 --- a/tests/all/component_model/dynamic.rs +++ b/tests/all/component_model/dynamic.rs @@ -1,6 +1,6 @@ #![cfg(not(miri))] -use super::{make_echo_component, make_echo_component_with_params, Param, Type}; +use super::{Param, Type, make_echo_component, make_echo_component_with_params}; use anyhow::Result; use component_test_util::FuncExt; use wasmtime::component::types::{self, Case, ComponentItem, Field}; @@ -269,14 +269,11 @@ fn variants() -> Result<()> { let component = Component::new( &engine, - make_echo_component_with_params( - fragment, - &[ - Param(Type::U8, Some(0)), - Param(Type::I64, Some(8)), - Param(Type::I32, None), - ], - ), + make_echo_component_with_params(fragment, &[ + Param(Type::U8, Some(0)), + Param(Type::I64, Some(8)), + Param(Type::I32, None), + ]), )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; let func = instance.get_func(&mut store, "echo").unwrap(); @@ -290,14 +287,11 @@ fn variants() -> Result<()> { let component = Component::new( &engine, - make_echo_component_with_params( - fragment, - &[ - Param(Type::U8, Some(0)), - Param(Type::I64, Some(8)), - Param(Type::I32, Some(12)), - ], - ), + make_echo_component_with_params(fragment, &[ + Param(Type::U8, Some(0)), + Param(Type::I64, Some(8)), + Param(Type::I32, Some(12)), + ]), )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; let func = instance.get_func(&mut store, "echo").unwrap(); @@ -401,10 +395,10 @@ fn flags() -> Result<()> { let component = Component::new( &engine, - make_echo_component_with_params( - r#"(flags "A" "B" "C" "D" "E")"#, - &[Param(Type::U8, Some(0))], - ), + make_echo_component_with_params(r#"(flags "A" "B" "C" "D" "E")"#, &[Param( + Type::U8, + Some(0), + )]), )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; let func = instance.get_func(&mut store, "echo").unwrap(); @@ -792,10 +786,9 @@ fn introspection() -> Result<()> { let ComponentItem::Type(f_ty) = f_ty else { panic!("`f` export item of wrong type") }; - assert_eq!( - f_ty.unwrap_flags().names().collect::>(), - ["G", "H", "I"] - ); + assert_eq!(f_ty.unwrap_flags().names().collect::>(), [ + "G", "H", "I" + ]); let (name, m_ty) = exports.next().unwrap(); assert_eq!(name, "m"); @@ -880,10 +873,10 @@ fn introspection() -> Result<()> { assert_eq!(ty, types::Type::Char); let Field { name, ty } = fields.next().unwrap(); assert_eq!(name, "Y"); - assert_eq!( - ty.unwrap_tuple().types().collect::>(), - [types::Type::U32, types::Type::U32] - ); + assert_eq!(ty.unwrap_tuple().types().collect::>(), [ + types::Type::U32, + types::Type::U32 + ]); let Field { name, ty } = fields.next().unwrap(); assert_eq!(name, "AA"); assert_eq!(ty.unwrap_option().ty(), types::Type::U32); diff --git a/tests/all/component_model/func.rs b/tests/all/component_model/func.rs index 2632a830b348..0f0492ca8579 100644 --- a/tests/all/component_model/func.rs +++ b/tests/all/component_model/func.rs @@ -1,6 +1,6 @@ #![cfg(not(miri))] -use super::{TypedFuncExt, REALLOC_AND_FREE}; +use super::{REALLOC_AND_FREE, TypedFuncExt}; use anyhow::Result; use std::rc::Rc; use std::sync::Arc; @@ -2061,107 +2061,83 @@ fn raw_slice_of_various_types() -> Result<()> { .get_typed_func::<(), (WasmList,)>(&mut store, "list-u8")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, - 0x0e, 0x0f, - ] - ); + assert_eq!(list.as_le_slice(&store), [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-i8")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, - 0x0e, 0x0f, - ] - ); + assert_eq!(list.as_le_slice(&store), [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-u16")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - u16::to_le(0x01_00), - u16::to_le(0x03_02), - u16::to_le(0x05_04), - u16::to_le(0x07_06), - u16::to_le(0x09_08), - u16::to_le(0x0b_0a), - u16::to_le(0x0d_0c), - u16::to_le(0x0f_0e), - ] - ); + assert_eq!(list.as_le_slice(&store), [ + u16::to_le(0x01_00), + u16::to_le(0x03_02), + u16::to_le(0x05_04), + u16::to_le(0x07_06), + u16::to_le(0x09_08), + u16::to_le(0x0b_0a), + u16::to_le(0x0d_0c), + u16::to_le(0x0f_0e), + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-i16")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - i16::to_le(0x01_00), - i16::to_le(0x03_02), - i16::to_le(0x05_04), - i16::to_le(0x07_06), - i16::to_le(0x09_08), - i16::to_le(0x0b_0a), - i16::to_le(0x0d_0c), - i16::to_le(0x0f_0e), - ] - ); + assert_eq!(list.as_le_slice(&store), [ + i16::to_le(0x01_00), + i16::to_le(0x03_02), + i16::to_le(0x05_04), + i16::to_le(0x07_06), + i16::to_le(0x09_08), + i16::to_le(0x0b_0a), + i16::to_le(0x0d_0c), + i16::to_le(0x0f_0e), + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-u32")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - u32::to_le(0x03_02_01_00), - u32::to_le(0x07_06_05_04), - u32::to_le(0x0b_0a_09_08), - u32::to_le(0x0f_0e_0d_0c), - ] - ); + assert_eq!(list.as_le_slice(&store), [ + u32::to_le(0x03_02_01_00), + u32::to_le(0x07_06_05_04), + u32::to_le(0x0b_0a_09_08), + u32::to_le(0x0f_0e_0d_0c), + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-i32")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - i32::to_le(0x03_02_01_00), - i32::to_le(0x07_06_05_04), - i32::to_le(0x0b_0a_09_08), - i32::to_le(0x0f_0e_0d_0c), - ] - ); + assert_eq!(list.as_le_slice(&store), [ + i32::to_le(0x03_02_01_00), + i32::to_le(0x07_06_05_04), + i32::to_le(0x0b_0a_09_08), + i32::to_le(0x0f_0e_0d_0c), + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-u64")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - u64::to_le(0x07_06_05_04_03_02_01_00), - u64::to_le(0x0f_0e_0d_0c_0b_0a_09_08), - ] - ); + assert_eq!(list.as_le_slice(&store), [ + u64::to_le(0x07_06_05_04_03_02_01_00), + u64::to_le(0x0f_0e_0d_0c_0b_0a_09_08), + ]); let list = instance .get_typed_func::<(), (WasmList,)>(&mut store, "list-i64")? .call_and_post_return(&mut store, ())? .0; - assert_eq!( - list.as_le_slice(&store), - [ - i64::to_le(0x07_06_05_04_03_02_01_00), - i64::to_le(0x0f_0e_0d_0c_0b_0a_09_08), - ] - ); + assert_eq!(list.as_le_slice(&store), [ + i64::to_le(0x07_06_05_04_03_02_01_00), + i64::to_le(0x0f_0e_0d_0c_0b_0a_09_08), + ]); Ok(()) } diff --git a/tests/all/component_model/instance.rs b/tests/all/component_model/instance.rs index a398c2e5cfeb..e261cb0f2ac1 100644 --- a/tests/all/component_model/instance.rs +++ b/tests/all/component_model/instance.rs @@ -34,9 +34,11 @@ fn instance_exports() -> Result<()> { .module("m", &Module::new(&engine, "(module)")?)?; let instance = linker.instantiate(&mut store, &component)?; - assert!(instance - .get_export(&mut store, None, "not an instance") - .is_none()); + assert!( + instance + .get_export(&mut store, None, "not an instance") + .is_none() + ); let i = instance.get_export(&mut store, None, "r").unwrap(); assert!(instance.get_export(&mut store, Some(&i), "x").is_none()); instance.get_export(&mut store, None, "i").unwrap(); diff --git a/tests/all/component_model/macros.rs b/tests/all/component_model/macros.rs index 9e7dc50386f9..6297be7aeab2 100644 --- a/tests/all/component_model/macros.rs +++ b/tests/all/component_model/macros.rs @@ -1,6 +1,6 @@ #![cfg(not(miri))] -use super::{make_echo_component, TypedFuncExt}; +use super::{TypedFuncExt, make_echo_component}; use anyhow::Result; use component_macro_test::{add_variants, flags_test}; use wasmtime::component::{Component, ComponentType, Lift, Linker, Lower}; @@ -42,9 +42,11 @@ fn record_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: field count mismatch (too many) @@ -57,9 +59,11 @@ fn record_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: field name mismatch @@ -69,9 +73,11 @@ fn record_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: field type mismatch @@ -81,9 +87,11 @@ fn record_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Happy path redux, with generics this time @@ -155,9 +163,11 @@ fn variant_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: case count mismatch (too many) @@ -170,9 +180,11 @@ fn variant_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: case name mismatch @@ -182,9 +194,11 @@ fn variant_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: case type mismatch @@ -197,9 +211,11 @@ fn variant_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Happy path redux, with generics this time @@ -270,9 +286,11 @@ fn enum_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: case count mismatch (too many) @@ -282,18 +300,22 @@ fn enum_derive() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: case name mismatch let component = Component::new(&engine, make_echo_component(r#"(enum "A" "B" "C")"#, 4))?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Happy path redux, with large enums (i.e. more than 2^8 cases) @@ -396,9 +418,11 @@ fn flags() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: flag count mismatch (too many) @@ -408,18 +432,22 @@ fn flags() -> Result<()> { )?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Sad path: flag name mismatch let component = Component::new(&engine, make_echo_component(r#"(flags "A" "B" "C")"#, 4))?; let instance = Linker::new(&engine).instantiate(&mut store, &component)?; - assert!(instance - .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") - .is_err()); + assert!( + instance + .get_typed_func::<(Foo,), (Foo,)>(&mut store, "echo") + .is_err() + ); // Happy path redux, with large flag count (exactly 8) diff --git a/tests/all/component_model/resources.rs b/tests/all/component_model/resources.rs index c183e47f9548..8d36e0abb36d 100644 --- a/tests/all/component_model/resources.rs +++ b/tests/all/component_model/resources.rs @@ -1070,26 +1070,32 @@ fn type_mismatch() -> Result<()> { let mut store = Store::new(&engine, ()); let i = Linker::new(&engine).instantiate(&mut store, &c)?; - assert!(i - .get_typed_func::<(&Resource,), ()>(&mut store, "f1") - .is_err()); - assert!(i - .get_typed_func::<(&ResourceAny,), ()>(&mut store, "f1") - .is_ok()); - - assert!(i - .get_typed_func::<(&Resource,), ()>(&mut store, "f2") - .is_err()); - assert!(i - .get_typed_func::<(&ResourceAny,), ()>(&mut store, "f2") - .is_ok()); - - assert!(i - .get_typed_func::<(&Resource,), ()>(&mut store, "f3") - .is_err()); - assert!(i - .get_typed_func::<(&ResourceAny,), ()>(&mut store, "f3") - .is_err()); + assert!( + i.get_typed_func::<(&Resource,), ()>(&mut store, "f1") + .is_err() + ); + assert!( + i.get_typed_func::<(&ResourceAny,), ()>(&mut store, "f1") + .is_ok() + ); + + assert!( + i.get_typed_func::<(&Resource,), ()>(&mut store, "f2") + .is_err() + ); + assert!( + i.get_typed_func::<(&ResourceAny,), ()>(&mut store, "f2") + .is_ok() + ); + + assert!( + i.get_typed_func::<(&Resource,), ()>(&mut store, "f3") + .is_err() + ); + assert!( + i.get_typed_func::<(&ResourceAny,), ()>(&mut store, "f3") + .is_err() + ); assert!(i.get_typed_func::<(u32,), ()>(&mut store, "f3").is_ok()); Ok(()) diff --git a/tests/all/custom_code_memory.rs b/tests/all/custom_code_memory.rs index 61afacf61fa6..41ac490f6ef6 100644 --- a/tests/all/custom_code_memory.rs +++ b/tests/all/custom_code_memory.rs @@ -1,6 +1,6 @@ #[cfg(all(not(target_os = "windows"), not(miri)))] mod not_for_windows { - use rustix::mm::{mprotect, MprotectFlags}; + use rustix::mm::{MprotectFlags, mprotect}; use rustix::param::page_size; use std::sync::Arc; use wasmtime::*; diff --git a/tests/all/debug/dump.rs b/tests/all/debug/dump.rs index a7ea8d265375..25610b46e935 100644 --- a/tests/all/debug/dump.rs +++ b/tests/all/debug/dump.rs @@ -1,4 +1,4 @@ -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use std::env; use std::process::Command; diff --git a/tests/all/debug/gdb.rs b/tests/all/debug/gdb.rs index befa0351db05..9d1b1b5d1602 100644 --- a/tests/all/debug/gdb.rs +++ b/tests/all/debug/gdb.rs @@ -1,6 +1,6 @@ #![allow(dead_code)] -use anyhow::{bail, format_err, Result}; +use anyhow::{Result, bail, format_err}; use filecheck::{CheckerBuilder, NO_VARIABLES}; use std::env; use std::io::Write; diff --git a/tests/all/debug/lldb.rs b/tests/all/debug/lldb.rs index 68339e556a73..1548469c27e7 100644 --- a/tests/all/debug/lldb.rs +++ b/tests/all/debug/lldb.rs @@ -1,6 +1,6 @@ #![allow(dead_code)] -use anyhow::{bail, format_err, Result}; +use anyhow::{Result, bail, format_err}; use filecheck::{CheckerBuilder, NO_VARIABLES}; use std::env; use std::io::Write; @@ -427,10 +427,9 @@ check: exited with status = 0 #[test] #[ignore] fn dwarf_imported_memory() -> Result<()> { - test_dwarf_simple( - DWARF_IMPORTED_MEMORY, - &["--preload=env=./tests/all/debug/satisfy_memory_import.wat"], - ) + test_dwarf_simple(DWARF_IMPORTED_MEMORY, &[ + "--preload=env=./tests/all/debug/satisfy_memory_import.wat", + ]) } #[test] diff --git a/tests/all/debug/simulate.rs b/tests/all/debug/simulate.rs index 10571e35fa6e..0d35de264417 100644 --- a/tests/all/debug/simulate.rs +++ b/tests/all/debug/simulate.rs @@ -1,6 +1,6 @@ -use super::dump::{get_dwarfdump, DwarfDumpSection}; +use super::dump::{DwarfDumpSection, get_dwarfdump}; use super::obj::compile_cranelift; -use anyhow::{format_err, Result}; +use anyhow::{Result, format_err}; use filecheck::{CheckerBuilder, NO_VARIABLES}; use tempfile::NamedTempFile; use wat::parse_str; diff --git a/tests/all/debug/translate.rs b/tests/all/debug/translate.rs index 15c314ea2f31..5d549a49b249 100644 --- a/tests/all/debug/translate.rs +++ b/tests/all/debug/translate.rs @@ -1,6 +1,6 @@ -use super::dump::{get_dwarfdump, DwarfDumpSection}; +use super::dump::{DwarfDumpSection, get_dwarfdump}; use super::obj::compile_cranelift; -use anyhow::{format_err, Result}; +use anyhow::{Result, format_err}; use filecheck::{CheckerBuilder, NO_VARIABLES}; use std::fs::read; use tempfile::NamedTempFile; diff --git a/tests/all/epoch_interruption.rs b/tests/all/epoch_interruption.rs index 7cc03c18c17d..12faf8518439 100644 --- a/tests/all/epoch_interruption.rs +++ b/tests/all/epoch_interruption.rs @@ -2,8 +2,8 @@ use crate::async_functions::{CountPending, PollOnce}; use anyhow::anyhow; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use wasmtime::*; use wasmtime_test_macros::wasmtime_test; diff --git a/tests/all/externals.rs b/tests/all/externals.rs index 09b860b4568a..340e970ed451 100644 --- a/tests/all/externals.rs +++ b/tests/all/externals.rs @@ -114,24 +114,30 @@ fn cross_store() -> anyhow::Result<()> { let s1_f = s1_inst.get_func(&mut store1, "f").unwrap(); let s2_f = s2_inst.get_func(&mut store2, "f").unwrap(); - assert!(s1_f - .call(&mut store1, &[Val::FuncRef(None)], &mut []) - .is_ok()); - assert!(s2_f - .call(&mut store2, &[Val::FuncRef(None)], &mut []) - .is_ok()); - assert!(s1_f - .call(&mut store1, &[Some(s1_f).into()], &mut []) - .is_ok()); - assert!(s1_f - .call(&mut store1, &[Some(s2_f).into()], &mut []) - .is_err()); - assert!(s2_f - .call(&mut store2, &[Some(s1_f).into()], &mut []) - .is_err()); - assert!(s2_f - .call(&mut store2, &[Some(s2_f).into()], &mut []) - .is_ok()); + assert!( + s1_f.call(&mut store1, &[Val::FuncRef(None)], &mut []) + .is_ok() + ); + assert!( + s2_f.call(&mut store2, &[Val::FuncRef(None)], &mut []) + .is_ok() + ); + assert!( + s1_f.call(&mut store1, &[Some(s1_f).into()], &mut []) + .is_ok() + ); + assert!( + s1_f.call(&mut store1, &[Some(s2_f).into()], &mut []) + .is_err() + ); + assert!( + s2_f.call(&mut store2, &[Some(s1_f).into()], &mut []) + .is_err() + ); + assert!( + s2_f.call(&mut store2, &[Some(s2_f).into()], &mut []) + .is_ok() + ); let s1_f_t = s1_f.typed::, ()>(&store1)?; let s2_f_t = s2_f.typed::, ()>(&store2)?; @@ -165,10 +171,11 @@ fn get_set_externref_globals_via_api() -> anyhow::Result<()> { let hello = ExternRef::new(&mut store, "hello".to_string())?; global.set(&mut store, hello.into())?; let r = global.get(&mut store).unwrap_externref().cloned().unwrap(); - assert!(r - .data(&store)? - .expect("should have host data") - .is::()); + assert!( + r.data(&store)? + .expect("should have host data") + .is::() + ); assert_eq!( r.data(&store)? .expect("should have host data") @@ -440,13 +447,9 @@ fn dummy_funcs_and_subtypes( ) -> (FuncType, Func, FuncType, Func, FuncType, Func) { let engine = store.engine().clone(); - let c_ty = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [], - [ValType::FUNCREF], - ) + let c_ty = FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [], [ + ValType::FUNCREF, + ]) .unwrap(); let c = Func::new( &mut *store, @@ -454,31 +457,25 @@ fn dummy_funcs_and_subtypes( |_caller, _args, _results| unreachable!(), ); - let b_ty = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&c_ty), - [], - [ValType::Ref(RefType::new( - true, - HeapType::ConcreteFunc(FuncType::new(&engine, None, None)), - ))], - ) - .unwrap(); + let b_ty = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&c_ty), [], [ + ValType::Ref(RefType::new( + true, + HeapType::ConcreteFunc(FuncType::new(&engine, None, None)), + )), + ]) + .unwrap(); let b = Func::new( &mut *store, b_ty.clone(), |_caller, _args, _results| unreachable!(), ); - let a_ty = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&b_ty), - [], - [ValType::NULLFUNCREF], - ) - .unwrap(); + let a_ty = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&b_ty), [], [ + ValType::NULLFUNCREF, + ]) + .unwrap(); let a = Func::new( &mut *store, a_ty.clone(), @@ -787,10 +784,12 @@ fn table_copy_func_subtyping() { if expected { for i in 2..7 { - assert!(dest_table - .get(&mut store, i) - .expect("in bounds") - .is_non_null()); + assert!( + dest_table + .get(&mut store, i) + .expect("in bounds") + .is_non_null() + ); } } } diff --git a/tests/all/func.rs b/tests/all/func.rs index d664765f86f4..e594bcba546b 100644 --- a/tests/all/func.rs +++ b/tests/all/func.rs @@ -1,7 +1,7 @@ use anyhow::bail; +use std::sync::Arc; use std::sync::atomic::Ordering; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; -use std::sync::Arc; use wasmtime::*; use wasmtime_test_macros::wasmtime_test; @@ -76,11 +76,11 @@ fn call_wasm_to_array(config: &mut Config) -> Result<()> { let engine = Engine::new(&config)?; let mut store = Store::<()>::new(&engine, ()); let module = Module::new(store.engine(), &wasm)?; - let func_ty = FuncType::new( - store.engine(), - vec![], - vec![ValType::I32, ValType::I32, ValType::I32], - ); + let func_ty = FuncType::new(store.engine(), vec![], vec![ + ValType::I32, + ValType::I32, + ValType::I32, + ]); let import_func = Func::new(&mut store, func_ty, |_, _params, results| { results[0] = Val::I32(1); results[1] = Val::I32(2); @@ -397,31 +397,61 @@ fn func_constructors() { Func::wrap(&mut store, || -> i64 { 0 }); Func::wrap(&mut store, || -> f32 { 0.0 }); Func::wrap(&mut store, || -> f64 { 0.0 }); - Func::wrap(&mut store, || -> Rooted { loop {} }); + Func::wrap(&mut store, || -> Rooted { + loop {} + }); Func::wrap(&mut store, || -> Option> { None }); - Func::wrap(&mut store, || -> ManuallyRooted { loop {} }); + Func::wrap(&mut store, || -> ManuallyRooted { + loop {} + }); Func::wrap(&mut store, || -> Option> { None }); - Func::wrap(&mut store, || -> Rooted { loop {} }); + Func::wrap(&mut store, || -> Rooted { + loop {} + }); Func::wrap(&mut store, || -> Option> { None }); - Func::wrap(&mut store, || -> ManuallyRooted { loop {} }); + Func::wrap(&mut store, || -> ManuallyRooted { + loop {} + }); Func::wrap(&mut store, || -> Option> { None }); - Func::wrap(&mut store, || -> I31 { loop {} }); + Func::wrap(&mut store, || -> I31 { + loop {} + }); Func::wrap(&mut store, || -> Option { None }); - Func::wrap(&mut store, || -> Func { loop {} }); + Func::wrap(&mut store, || -> Func { + loop {} + }); Func::wrap(&mut store, || -> Option { None }); - Func::wrap(&mut store, || -> NoFunc { loop {} }); + Func::wrap(&mut store, || -> NoFunc { + loop {} + }); Func::wrap(&mut store, || -> Option { None }); - Func::wrap(&mut store, || -> NoExtern { loop {} }); + Func::wrap(&mut store, || -> NoExtern { + loop {} + }); Func::wrap(&mut store, || -> Option { None }); - Func::wrap(&mut store, || -> NoneRef { loop {} }); + Func::wrap(&mut store, || -> NoneRef { + loop {} + }); Func::wrap(&mut store, || -> Option { None }); - Func::wrap(&mut store, || -> Result<()> { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); + Func::wrap(&mut store, || -> Result<()> { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); Func::wrap(&mut store, || -> Result>> { loop {} }); @@ -432,22 +462,48 @@ fn func_constructors() { &mut store, || -> Result>> { loop {} }, ); - Func::wrap(&mut store, || -> Result> { loop {} }); - Func::wrap(&mut store, || -> Result>> { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); + Func::wrap(&mut store, || -> Result>> { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); Func::wrap(&mut store, || -> Result>> { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); - Func::wrap(&mut store, || -> Result { loop {} }); - Func::wrap(&mut store, || -> Result> { loop {} }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); + Func::wrap(&mut store, || -> Result { + loop {} + }); + Func::wrap(&mut store, || -> Result> { + loop {} + }); } #[test] @@ -508,22 +564,30 @@ fn signatures_match() { assert_eq!(f.ty(&store).params().len(), 0); assert_eq!(f.ty(&store).results().len(), 0); - let f = Func::wrap(&mut store, || -> i32 { loop {} }); + let f = Func::wrap(&mut store, || -> i32 { + loop {} + }); assert_eq!(f.ty(&store).params().len(), 0); assert_eq!(f.ty(&store).results().len(), 1); assert!(f.ty(&store).results().nth(0).unwrap().is_i32()); - let f = Func::wrap(&mut store, || -> i64 { loop {} }); + let f = Func::wrap(&mut store, || -> i64 { + loop {} + }); assert_eq!(f.ty(&store).params().len(), 0); assert_eq!(f.ty(&store).results().len(), 1); assert!(f.ty(&store).results().nth(0).unwrap().is_i64()); - let f = Func::wrap(&mut store, || -> f32 { loop {} }); + let f = Func::wrap(&mut store, || -> f32 { + loop {} + }); assert_eq!(f.ty(&store).params().len(), 0); assert_eq!(f.ty(&store).results().len(), 1); assert!(f.ty(&store).results().nth(0).unwrap().is_f32()); - let f = Func::wrap(&mut store, || -> f64 { loop {} }); + let f = Func::wrap(&mut store, || -> f64 { + loop {} + }); assert_eq!(f.ty(&store).params().len(), 0); assert_eq!(f.ty(&store).results().len(), 1); assert!(f.ty(&store).results().nth(0).unwrap().is_f64()); @@ -735,41 +799,71 @@ fn get_from_wrapper() { assert!(f.typed::<(i32, i32), ()>(&store).is_err()); assert!(f.typed::<(i32, i32), i32>(&store).is_err()); - let f = Func::wrap(&mut store, || -> i32 { loop {} }); + let f = Func::wrap(&mut store, || -> i32 { + loop {} + }); assert!(f.typed::<(), i32>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> f32 { loop {} }); + let f = Func::wrap(&mut store, || -> f32 { + loop {} + }); assert!(f.typed::<(), f32>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> f64 { loop {} }); + let f = Func::wrap(&mut store, || -> f64 { + loop {} + }); assert!(f.typed::<(), f64>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Rooted { loop {} }); + let f = Func::wrap(&mut store, || -> Rooted { + loop {} + }); assert!(f.typed::<(), Rooted>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Option> { loop {} }); + let f = Func::wrap(&mut store, || -> Option> { + loop {} + }); assert!(f.typed::<(), Option>>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> ManuallyRooted { loop {} }); + let f = Func::wrap(&mut store, || -> ManuallyRooted { + loop {} + }); assert!(f.typed::<(), ManuallyRooted>(&store).is_ok()); let f = Func::wrap(&mut store, || -> Option> { loop {} }); - assert!(f - .typed::<(), Option>>(&store) - .is_ok()); - let f = Func::wrap(&mut store, || -> Rooted { loop {} }); + assert!( + f.typed::<(), Option>>(&store) + .is_ok() + ); + let f = Func::wrap(&mut store, || -> Rooted { + loop {} + }); assert!(f.typed::<(), Rooted>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Option> { loop {} }); + let f = Func::wrap(&mut store, || -> Option> { + loop {} + }); assert!(f.typed::<(), Option>>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> ManuallyRooted { loop {} }); + let f = Func::wrap(&mut store, || -> ManuallyRooted { + loop {} + }); assert!(f.typed::<(), ManuallyRooted>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Option> { loop {} }); - assert!(f - .typed::<(), Option>>(&store) - .is_ok()); - let f = Func::wrap(&mut store, || -> I31 { loop {} }); + let f = Func::wrap(&mut store, || -> Option> { + loop {} + }); + assert!( + f.typed::<(), Option>>(&store) + .is_ok() + ); + let f = Func::wrap(&mut store, || -> I31 { + loop {} + }); assert!(f.typed::<(), I31>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Option { loop {} }); + let f = Func::wrap(&mut store, || -> Option { + loop {} + }); assert!(f.typed::<(), Option>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Func { loop {} }); + let f = Func::wrap(&mut store, || -> Func { + loop {} + }); assert!(f.typed::<(), Func>(&store).is_ok()); - let f = Func::wrap(&mut store, || -> Option { loop {} }); + let f = Func::wrap(&mut store, || -> Option { + loop {} + }); assert!(f.typed::<(), Option>(&store).is_ok()); let f = Func::wrap(&mut store, |_: i32| {}); @@ -790,9 +884,10 @@ fn get_from_wrapper() { let f = Func::wrap(&mut store, |_: ManuallyRooted| {}); assert!(f.typed::, ()>(&store).is_ok()); let f = Func::wrap(&mut store, |_: Option>| {}); - assert!(f - .typed::>, ()>(&store) - .is_ok()); + assert!( + f.typed::>, ()>(&store) + .is_ok() + ); let f = Func::wrap(&mut store, |_: Rooted| {}); assert!(f.typed::, ()>(&store).is_ok()); let f = Func::wrap(&mut store, |_: Option>| {}); @@ -800,9 +895,10 @@ fn get_from_wrapper() { let f = Func::wrap(&mut store, |_: ManuallyRooted| {}); assert!(f.typed::, ()>(&store).is_ok()); let f = Func::wrap(&mut store, |_: Option>| {}); - assert!(f - .typed::>, ()>(&store) - .is_ok()); + assert!( + f.typed::>, ()>(&store) + .is_ok() + ); let f = Func::wrap(&mut store, |_: I31| {}); assert!(f.typed::(&store).is_ok()); let f = Func::wrap(&mut store, |_: Option| {}); @@ -978,9 +1074,10 @@ fn func_write_nothing() -> anyhow::Result<()> { let ty = FuncType::new(store.engine(), None, Some(ValType::I32)); let f = Func::new(&mut store, ty, |_, _, _| Ok(())); let err = f.call(&mut store, &[], &mut [Val::I32(0)]).unwrap_err(); - assert!(err - .to_string() - .contains("function attempted to return an incompatible value")); + assert!( + err.to_string() + .contains("function attempted to return an incompatible value") + ); Ok(()) } @@ -1028,9 +1125,11 @@ fn pass_cross_store_arg(config: &mut Config) -> anyhow::Result<()> { let store2_func = Func::wrap(&mut store2, || {}); // Using regular `.call` fails with cross-Store arguments. - assert!(store1_func - .call(&mut store1, &[Val::FuncRef(Some(store2_func))], &mut []) - .is_err()); + assert!( + store1_func + .call(&mut store1, &[Val::FuncRef(Some(store2_func))], &mut []) + .is_err() + ); // And using `.get` followed by a function call also fails with cross-Store // arguments. @@ -2151,20 +2250,13 @@ fn wasm_to_host_trampolines_and_subtyping(config: &mut Config) -> Result<()> { let engine = Engine::new(&config)?; - let ft0 = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [], - [ValType::Ref(RefType::new(true, HeapType::Extern))], - )?; - let ft1 = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&ft0), - [], - [ValType::Ref(RefType::new(false, HeapType::Extern))], - )?; + let ft0 = FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [], [ + ValType::Ref(RefType::new(true, HeapType::Extern)), + ])?; + let ft1 = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&ft0), [], [ + ValType::Ref(RefType::new(false, HeapType::Extern)), + ])?; let module = Module::new( &engine, @@ -2228,11 +2320,10 @@ fn wasm_to_host_trampolines_and_subtyping(config: &mut Config) -> Result<()> { }, ); - let instance = Instance::new( - &mut store, - &module, - &[imported_func.into(), return_func.into()], - )?; + let instance = Instance::new(&mut store, &module, &[ + imported_func.into(), + return_func.into(), + ])?; let g = make_func(&mut store); assert!(FuncType::eq(&g.ty(&store), &ft1)); diff --git a/tests/all/funcref.rs b/tests/all/funcref.rs index 09fc5f727ec4..2f4a9449e5aa 100644 --- a/tests/all/funcref.rs +++ b/tests/all/funcref.rs @@ -1,6 +1,6 @@ use super::ref_types_module; -use std::sync::atomic::{AtomicBool, Ordering::SeqCst}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering::SeqCst}; use wasmtime::*; #[test] @@ -68,9 +68,10 @@ fn pass_funcref_in_and_out_of_wasm() -> anyhow::Result<()> { .get_func(&mut other_store, "f") .unwrap(); - assert!(func - .call(&mut store, &[Val::FuncRef(Some(f))], &mut [Val::I32(0)]) - .is_err()); + assert!( + func.call(&mut store, &[Val::FuncRef(Some(f))], &mut [Val::I32(0)]) + .is_err() + ); } Ok(()) diff --git a/tests/all/gc.rs b/tests/all/gc.rs index 73affd6897f5..13129239ecaf 100644 --- a/tests/all/gc.rs +++ b/tests/all/gc.rs @@ -1,7 +1,7 @@ use super::ref_types_module; use super::skip_pooling_allocator_tests; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; use wasmtime::*; struct SetFlagOnDrop(Arc); diff --git a/tests/all/host_funcs.rs b/tests/all/host_funcs.rs index d887c510dc82..f82b3b9250f5 100644 --- a/tests/all/host_funcs.rs +++ b/tests/all/host_funcs.rs @@ -32,15 +32,27 @@ fn wrap_func() -> Result<()> { linker.func_wrap("m3", "", || -> Option> { None })?; linker.func_wrap("m3", "f", || -> Option { None })?; - linker.func_wrap("", "f1", || -> Result<()> { loop {} })?; - linker.func_wrap("", "f2", || -> Result { loop {} })?; - linker.func_wrap("", "f3", || -> Result { loop {} })?; - linker.func_wrap("", "f4", || -> Result { loop {} })?; - linker.func_wrap("", "f5", || -> Result { loop {} })?; + linker.func_wrap("", "f1", || -> Result<()> { + loop {} + })?; + linker.func_wrap("", "f2", || -> Result { + loop {} + })?; + linker.func_wrap("", "f3", || -> Result { + loop {} + })?; + linker.func_wrap("", "f4", || -> Result { + loop {} + })?; + linker.func_wrap("", "f5", || -> Result { + loop {} + })?; linker.func_wrap("", "f6", || -> Result>> { loop {} })?; - linker.func_wrap("", "f7", || -> Result> { loop {} })?; + linker.func_wrap("", "f7", || -> Result> { + loop {} + })?; Ok(()) } @@ -135,10 +147,18 @@ fn signatures_match() -> Result<()> { let mut linker = Linker::<()>::new(&engine); linker.func_wrap("", "f1", || {})?; - linker.func_wrap("", "f2", || -> i32 { loop {} })?; - linker.func_wrap("", "f3", || -> i64 { loop {} })?; - linker.func_wrap("", "f4", || -> f32 { loop {} })?; - linker.func_wrap("", "f5", || -> f64 { loop {} })?; + linker.func_wrap("", "f2", || -> i32 { + loop {} + })?; + linker.func_wrap("", "f3", || -> i64 { + loop {} + })?; + linker.func_wrap("", "f4", || -> f32 { + loop {} + })?; + linker.func_wrap("", "f5", || -> f64 { + loop {} + })?; linker.func_wrap( "", "f6", @@ -618,9 +638,10 @@ fn func_return_nothing() -> Result<()> { let mut store = Store::new(&engine, ()); let f = linker.get(&mut store, "", "").unwrap().into_func().unwrap(); let err = f.call(&mut store, &[], &mut [Val::I32(0)]).unwrap_err(); - assert!(err - .to_string() - .contains("function attempted to return an incompatible value")); + assert!( + err.to_string() + .contains("function attempted to return an incompatible value") + ); Ok(()) } diff --git a/tests/all/limits.rs b/tests/all/limits.rs index 684d76de35dc..0f10b3779f29 100644 --- a/tests/all/limits.rs +++ b/tests/all/limits.rs @@ -125,13 +125,10 @@ async fn test_limits_async() -> Result<()> { } } - let mut store = Store::new( - &engine, - LimitsAsync { - memory_size: 10 * WASM_PAGE_SIZE, - table_elements: 5, - }, - ); + let mut store = Store::new(&engine, LimitsAsync { + memory_size: 10 * WASM_PAGE_SIZE, + table_elements: 5, + }); store.limiter_async(|s| s as &mut dyn ResourceLimiterAsync); diff --git a/tests/all/linker.rs b/tests/all/linker.rs index 888584826d46..bc30ee5ecba0 100644 --- a/tests/all/linker.rs +++ b/tests/all/linker.rs @@ -1,7 +1,7 @@ use std::cell::Cell; use std::rc::Rc; -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use wasmtime::*; #[test] @@ -48,9 +48,11 @@ fn link_twice_bad() -> Result<()> { // functions linker.func_wrap("f", "", || {})?; assert!(linker.func_wrap("f", "", || {}).is_err()); - assert!(linker - .func_wrap("f", "", || -> Result<()> { loop {} }) - .is_err()); + assert!( + linker + .func_wrap("f", "", || -> Result<()> { loop {} }) + .is_err() + ); // globals let ty = GlobalType::new(ValType::I32, Mutability::Const); @@ -276,9 +278,11 @@ fn get_host_function() -> Result<()> { let mut linker = Linker::new(&engine); linker.func_wrap("mod", "f1", || {})?; let mut store = Store::new(&engine, ()); - assert!(linker - .get_by_import(&mut store, &module.imports().nth(0).unwrap()) - .is_some()); + assert!( + linker + .get_by_import(&mut store, &module.imports().nth(0).unwrap()) + .is_some() + ); Ok(()) } @@ -543,20 +547,13 @@ fn linker_defines_func_subtype() -> Result<()> { [], )?; - let ft2 = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [], - [ValType::FUNCREF], - )?; - let ft3 = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&ft2), - [], - [ValType::NULLFUNCREF], - )?; + let ft2 = FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [], [ + ValType::FUNCREF, + ])?; + let ft3 = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&ft2), [], [ + ValType::NULLFUNCREF, + ])?; let nop = FuncType::new(&engine, [], []); let ft4 = FuncType::with_finality_and_supertype( diff --git a/tests/all/memory.rs b/tests/all/memory.rs index fb46d40d0d36..19ddd6225ef4 100644 --- a/tests/all/memory.rs +++ b/tests/all/memory.rs @@ -495,11 +495,13 @@ fn memory64_maximum_minimum(config: &mut Config) -> Result<()> { let engine = Engine::new(&config)?; let mut store = Store::new(&engine, ()); - assert!(MemoryTypeBuilder::default() - .memory64(true) - .min(1 << 48) - .build() - .is_err()); + assert!( + MemoryTypeBuilder::default() + .memory64(true) + .min(1 << 48) + .build() + .is_err() + ); let module = Module::new( &engine, @@ -551,12 +553,14 @@ fn shared_memory_basics() -> Result<()> { assert!(SharedMemory::new(&engine, MemoryType::new(1, Some(1))).is_err()); assert!(SharedMemory::new(&engine, MemoryType::new64(1, None)).is_err()); assert!(SharedMemory::new(&engine, MemoryType::new64(1, Some(1))).is_err()); - assert!(MemoryTypeBuilder::default() - .shared(true) - .min(1) - .max(Some(0)) - .build() - .is_err()); + assert!( + MemoryTypeBuilder::default() + .shared(true) + .min(1) + .max(Some(0)) + .build() + .is_err() + ); let memory = SharedMemory::new(&engine, MemoryType::shared(1, 1))?; assert!(memory.ty().is_shared()); diff --git a/tests/all/memory_creator.rs b/tests/all/memory_creator.rs index fff8a2a700c0..c44c133c897f 100644 --- a/tests/all/memory_creator.rs +++ b/tests/all/memory_creator.rs @@ -3,7 +3,7 @@ mod not_for_windows { use wasmtime::*; use wasmtime_environ::WASM32_MAX_SIZE; - use rustix::mm::{mmap_anonymous, mprotect, munmap, MapFlags, MprotectFlags, ProtFlags}; + use rustix::mm::{MapFlags, MprotectFlags, ProtFlags, mmap_anonymous, mprotect, munmap}; use std::ptr::null_mut; use std::sync::{Arc, Mutex}; diff --git a/tests/all/module.rs b/tests/all/module.rs index 683a93fae5b7..e6c2da5612ba 100644 --- a/tests/all/module.rs +++ b/tests/all/module.rs @@ -1,6 +1,6 @@ use anyhow::Context; -use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; use wasmtime::*; use wasmtime_test_macros::wasmtime_test; diff --git a/tests/all/module_serialize.rs b/tests/all/module_serialize.rs index f3804a046338..cbf8178cddc6 100644 --- a/tests/all/module_serialize.rs +++ b/tests/all/module_serialize.rs @@ -24,9 +24,10 @@ fn test_version_mismatch() -> Result<()> { let custom_version_engine = Engine::new(&config).unwrap(); match unsafe { Module::deserialize(&custom_version_engine, &buffer) } { Ok(_) => bail!("expected deserialization to fail"), - Err(e) => assert!(e - .to_string() - .starts_with("Module was compiled with incompatible version")), + Err(e) => assert!( + e.to_string() + .starts_with("Module was compiled with incompatible version") + ), } let mut config = Config::new(); diff --git a/tests/all/stack_creator.rs b/tests/all/stack_creator.rs index e05629aeebfd..154d8384e08f 100644 --- a/tests/all/stack_creator.rs +++ b/tests/all/stack_creator.rs @@ -1,5 +1,5 @@ #![cfg(all(not(target_os = "windows"), not(miri)))] -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use std::{ alloc::{GlobalAlloc, Layout, System}, ops::Range, diff --git a/tests/all/structs.rs b/tests/all/structs.rs index 2254bd554c39..2dcc485e4ab9 100644 --- a/tests/all/structs.rs +++ b/tests/all/structs.rs @@ -23,33 +23,27 @@ fn struct_new_empty() -> Result<()> { #[test] fn struct_new_with_fields() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [ - FieldType::new(Mutability::Const, StorageType::I8), - FieldType::new(Mutability::Const, StorageType::ValType(ValType::I32)), - FieldType::new(Mutability::Var, StorageType::ValType(ValType::ANYREF)), - ], - )?; + let struct_ty = StructType::new(store.engine(), [ + FieldType::new(Mutability::Const, StorageType::I8), + FieldType::new(Mutability::Const, StorageType::ValType(ValType::I32)), + FieldType::new(Mutability::Var, StorageType::ValType(ValType::ANYREF)), + ])?; let pre = StructRefPre::new(&mut store, struct_ty); - StructRef::new( - store, - &pre, - &[Val::I32(1), Val::I32(2), Val::null_any_ref()], - )?; + StructRef::new(store, &pre, &[ + Val::I32(1), + Val::I32(2), + Val::null_any_ref(), + ])?; Ok(()) } #[test] fn struct_new_unrooted_field() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::ANYREF), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::ANYREF), + )])?; // Passing an unrooted `anyref` to `StructRef::new` results in an error. let anyref = { let mut scope = RootScope::new(&mut store); @@ -65,13 +59,10 @@ fn struct_new_unrooted_field() -> Result<()> { #[should_panic = "wrong store"] fn struct_new_cross_store_field() { let mut store = gc_store().unwrap(); - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::ANYREF), - )], - ) + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::ANYREF), + )]) .unwrap(); let mut other_store = gc_store().unwrap(); @@ -100,10 +91,10 @@ fn struct_new_cross_store_pre() { fn anyref_as_struct() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let pre = StructRefPre::new(&mut store, struct_ty.clone()); let s0 = StructRef::new(&mut store, &pre, &[Val::I32(42)])?; @@ -123,13 +114,10 @@ fn anyref_as_struct() -> Result<()> { #[test] fn struct_field_simple() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::I32(1234)])?; let val = s.field(&mut store, 0)?; @@ -140,13 +128,10 @@ fn struct_field_simple() -> Result<()> { #[test] fn struct_field_out_of_bounds() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::I32(1234)])?; assert!(s.field(&mut store, 1).is_err()); @@ -156,13 +141,10 @@ fn struct_field_out_of_bounds() -> Result<()> { #[test] fn struct_field_on_unrooted() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = { let mut scope = RootScope::new(&mut store); @@ -176,13 +158,10 @@ fn struct_field_on_unrooted() -> Result<()> { #[test] fn struct_set_field_simple() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::I32(1234)])?; s.set_field(&mut store, 0, Val::I32(5678))?; @@ -194,13 +173,10 @@ fn struct_set_field_simple() -> Result<()> { #[test] fn struct_set_field_out_of_bounds() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::I32(1234)])?; assert!(s.set_field(&mut store, 1, Val::I32(1)).is_err()); @@ -210,13 +186,10 @@ fn struct_set_field_out_of_bounds() -> Result<()> { #[test] fn struct_set_field_on_unrooted() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = { let mut scope = RootScope::new(&mut store); @@ -230,13 +203,10 @@ fn struct_set_field_on_unrooted() -> Result<()> { #[test] fn struct_set_field_with_unrooted() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::ANYREF), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::ANYREF), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::null_any_ref()])?; let anyref = { @@ -251,13 +221,10 @@ fn struct_set_field_with_unrooted() -> Result<()> { #[test] fn struct_set_field_cross_store_value() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Var, - StorageType::ValType(ValType::EXTERNREF), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + StorageType::ValType(ValType::EXTERNREF), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::null_extern_ref()])?; @@ -271,13 +238,10 @@ fn struct_set_field_cross_store_value() -> Result<()> { #[test] fn struct_set_field_immutable() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Const, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::I32(1234)])?; assert!(s.set_field(&mut store, 0, Val::I32(5678)).is_err()); @@ -287,13 +251,10 @@ fn struct_set_field_immutable() -> Result<()> { #[test] fn struct_set_field_wrong_type() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new( - Mutability::Const, - StorageType::ValType(ValType::I32), - )], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::ValType(ValType::I32), + )])?; let pre = StructRefPre::new(&mut store, struct_ty); let s = StructRef::new(&mut store, &pre, &[Val::I32(1234)])?; assert!(s.set_field(&mut store, 0, Val::I64(5678)).is_err()); @@ -339,13 +300,10 @@ fn struct_fields_empty() -> Result<()> { #[test] fn struct_fields_non_empty() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [ - FieldType::new(Mutability::Const, StorageType::I8), - FieldType::new(Mutability::Var, StorageType::ValType(ValType::ANYREF)), - ], - )?; + let struct_ty = StructType::new(store.engine(), [ + FieldType::new(Mutability::Const, StorageType::I8), + FieldType::new(Mutability::Var, StorageType::ValType(ValType::ANYREF)), + ])?; let pre = StructRefPre::new(&mut store, struct_ty.clone()); let s = StructRef::new(&mut store, &pre, &[Val::I32(36), Val::null_any_ref()])?; let mut fields = s.fields(&mut store)?; @@ -388,10 +346,10 @@ fn passing_structs_through_wasm_with_untyped_calls() -> Result<()> { "#, )?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let ref_ty = RefType::new(false, HeapType::ConcreteStruct(struct_ty.clone())); let func_ty = FuncType::new(store.engine(), [ref_ty.clone().into()], [ref_ty.into()]); @@ -439,10 +397,10 @@ fn passing_structs_through_wasm_with_typed_calls() -> Result<()> { "#, )?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let func = Func::wrap( &mut store, @@ -487,10 +445,10 @@ fn host_sets_struct_global() -> Result<()> { let instance = Instance::new(&mut store, &module, &[])?; let g = instance.get_global(&mut store, "g").unwrap(); - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let pre = StructRefPre::new(&mut store, struct_ty.clone()); let s0 = StructRef::new(&mut store, &pre, &[Val::I32(42)])?; g.set(&mut store, s0.into())?; @@ -533,10 +491,10 @@ fn wasm_sets_struct_global() -> Result<()> { "#, )?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let pre = StructRefPre::new(&mut store, struct_ty.clone()); let s0 = StructRef::new(&mut store, &pre, &[Val::I32(42)])?; @@ -583,10 +541,10 @@ fn host_sets_struct_in_table() -> Result<()> { let instance = Instance::new(&mut store, &module, &[])?; let t = instance.get_table(&mut store, "t").unwrap(); - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let pre = StructRefPre::new(&mut store, struct_ty.clone()); let s0 = StructRef::new(&mut store, &pre, &[Val::I32(42)])?; t.set(&mut store, 0, s0.into())?; @@ -631,10 +589,10 @@ fn wasm_sets_struct_in_table() -> Result<()> { "#, )?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let pre = StructRefPre::new(&mut store, struct_ty.clone()); let s0 = StructRef::new(&mut store, &pre, &[Val::I32(42)])?; @@ -674,10 +632,10 @@ fn instantiate_with_struct_global() -> Result<()> { "#, )?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Const, StorageType::I8)], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Const, + StorageType::I8, + )])?; let global_ty = GlobalType::new( ValType::Ref(RefType::new( true, @@ -712,10 +670,10 @@ fn instantiate_with_struct_global() -> Result<()> { fn can_put_funcrefs_in_structs() -> Result<()> { let mut store = gc_store()?; - let struct_ty = StructType::new( - store.engine(), - [FieldType::new(Mutability::Var, RefType::FUNCREF.into())], - )?; + let struct_ty = StructType::new(store.engine(), [FieldType::new( + Mutability::Var, + RefType::FUNCREF.into(), + )])?; let f0 = Func::wrap(&mut store, |_caller: Caller<()>| -> u32 { 0x1234 }); let f1 = Func::wrap(&mut store, |_caller: Caller<()>| -> u32 { 0x5678 }); diff --git a/tests/all/table.rs b/tests/all/table.rs index c119dc0152d9..764fd18b69e9 100644 --- a/tests/all/table.rs +++ b/tests/all/table.rs @@ -86,17 +86,13 @@ fn i31ref_table_new() -> Result<()> { let mut store = Store::new(&engine, ()); for (elem_ty, inits) in [ - ( - RefType::I31REF, - vec![ - Ref::Any(None), - AnyRef::from_i31(&mut store, I31::default()).into(), - ], - ), - ( - RefType::new(false, HeapType::I31), - vec![AnyRef::from_i31(&mut store, I31::default()).into()], - ), + (RefType::I31REF, vec![ + Ref::Any(None), + AnyRef::from_i31(&mut store, I31::default()).into(), + ]), + (RefType::new(false, HeapType::I31), vec![ + AnyRef::from_i31(&mut store, I31::default()).into(), + ]), ] { let table_ty = TableType::new(elem_ty, 10, None); for init in inits { @@ -117,17 +113,13 @@ fn i31ref_table_get() -> Result<()> { let mut store = Store::new(&engine, ()); for (elem_ty, inits) in [ - ( - RefType::I31REF, - vec![ - Ref::Any(None), - AnyRef::from_i31(&mut store, I31::default()).into(), - ], - ), - ( - RefType::new(false, HeapType::I31), - vec![AnyRef::from_i31(&mut store, I31::default()).into()], - ), + (RefType::I31REF, vec![ + Ref::Any(None), + AnyRef::from_i31(&mut store, I31::default()).into(), + ]), + (RefType::new(false, HeapType::I31), vec![ + AnyRef::from_i31(&mut store, I31::default()).into(), + ]), ] { let table_ty = TableType::new(elem_ty, 10, None); for init in inits { diff --git a/tests/all/threads.rs b/tests/all/threads.rs index 20fc7d3e34fa..0be92df6d6d4 100644 --- a/tests/all/threads.rs +++ b/tests/all/threads.rs @@ -1,8 +1,8 @@ use std::{ - collections::{hash_map::RandomState, HashSet}, + collections::{HashSet, hash_map::RandomState}, sync::{ - atomic::{AtomicBool, Ordering}, Arc, RwLock, + atomic::{AtomicBool, Ordering}, }, }; use wasmtime::*; diff --git a/tests/all/traps.rs b/tests/all/traps.rs index 23144cbb10f4..2d187eaa09f1 100644 --- a/tests/all/traps.rs +++ b/tests/all/traps.rs @@ -195,11 +195,10 @@ fn test_trap_through_host() -> Result<()> { }, ); - let instance = Instance::new( - &mut store, - &module, - &[host_func_a.into(), host_func_b.into()], - )?; + let instance = Instance::new(&mut store, &module, &[ + host_func_a.into(), + host_func_b.into(), + ])?; let a = instance.get_typed_func::<(), ()>(&mut store, "a")?; let err = a.call(&mut store, ()).unwrap_err(); let trace = err.downcast_ref::().unwrap().frames(); @@ -569,9 +568,10 @@ fn call_signature_mismatch() -> Result<()> { .unwrap() .downcast::() .unwrap(); - assert!(err - .to_string() - .contains("wasm trap: indirect call type mismatch")); + assert!( + err.to_string() + .contains("wasm trap: indirect call type mismatch") + ); Ok(()) } @@ -851,17 +851,21 @@ fn multithreaded_traps() -> Result<()> { )?; let instance = Instance::new(&mut store, &module, &[])?; - assert!(instance - .get_typed_func::<(), ()>(&mut store, "run")? - .call(&mut store, ()) - .is_err()); + assert!( + instance + .get_typed_func::<(), ()>(&mut store, "run")? + .call(&mut store, ()) + .is_err() + ); let handle = std::thread::spawn(move || { - assert!(instance - .get_typed_func::<(), ()>(&mut store, "run") - .unwrap() - .call(&mut store, ()) - .is_err()); + assert!( + instance + .get_typed_func::<(), ()>(&mut store, "run") + .unwrap() + .call(&mut store, ()) + .is_err() + ); }); handle.join().expect("couldn't join thread"); @@ -954,13 +958,10 @@ fn catch_trap_calling_across_stores() -> Result<()> { }, )?; - let mut store = Store::new( - &engine, - ParentCtx { - child_store, - child_instance, - }, - ); + let mut store = Store::new(&engine, ParentCtx { + child_store, + child_instance, + }); let parent_module = Module::new( store.engine(), @@ -1097,13 +1098,10 @@ async fn sync_then_async_trap() -> Result<()> { async_store: Store<()>, } - let mut sync_store = Store::new( - &Engine::default(), - SyncCtx { - async_instance, - async_store, - }, - ); + let mut sync_store = Store::new(&Engine::default(), SyncCtx { + async_instance, + async_store, + }); let sync_module = Module::new(sync_store.engine(), wat)?; diff --git a/tests/all/types.rs b/tests/all/types.rs index d3dc2c4a3626..1e4c0dc1da6c 100644 --- a/tests/all/types.rs +++ b/tests/all/types.rs @@ -88,50 +88,44 @@ fn basic_struct_types() -> Result<()> { fn struct_type_matches() -> Result<()> { let engine = Engine::default(); - let super_ty = StructType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [imm_field(HeapType::Func)], - )?; + let super_ty = + StructType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [imm_field( + HeapType::Func, + )])?; // Depth. - let sub_ty = StructType::with_finality_and_supertype( - &engine, - Finality::Final, - Some(&super_ty), - [imm_field(HeapType::NoFunc)], - )?; + let sub_ty = + StructType::with_finality_and_supertype(&engine, Finality::Final, Some(&super_ty), [ + imm_field(HeapType::NoFunc), + ])?; assert!(sub_ty.matches(&super_ty)); let not_sub_ty = StructType::new(&engine, [imm_field(HeapType::NoFunc)])?; assert!(!not_sub_ty.matches(&super_ty)); // Width. - let sub_ty = StructType::with_finality_and_supertype( - &engine, - Finality::Final, - Some(&super_ty), - [imm_field(HeapType::Func), imm_field(HeapType::Extern)], - )?; + let sub_ty = + StructType::with_finality_and_supertype(&engine, Finality::Final, Some(&super_ty), [ + imm_field(HeapType::Func), + imm_field(HeapType::Extern), + ])?; assert!(sub_ty.matches(&super_ty)); - let not_sub_ty = StructType::new( - &engine, - [imm_field(HeapType::Func), imm_field(HeapType::Extern)], - )?; + let not_sub_ty = StructType::new(&engine, [ + imm_field(HeapType::Func), + imm_field(HeapType::Extern), + ])?; assert!(!not_sub_ty.matches(&super_ty)); // Depth and width. - let sub_ty = StructType::with_finality_and_supertype( - &engine, - Finality::Final, - Some(&super_ty), - [imm_field(HeapType::NoFunc), imm_field(HeapType::Extern)], - )?; + let sub_ty = + StructType::with_finality_and_supertype(&engine, Finality::Final, Some(&super_ty), [ + imm_field(HeapType::NoFunc), + imm_field(HeapType::Extern), + ])?; assert!(sub_ty.matches(&super_ty)); - let not_sub_ty = StructType::new( - &engine, - [imm_field(HeapType::NoFunc), imm_field(HeapType::Extern)], - )?; + let not_sub_ty = StructType::new(&engine, [ + imm_field(HeapType::NoFunc), + imm_field(HeapType::Extern), + ])?; assert!(!not_sub_ty.matches(&super_ty)); // Unrelated structs. @@ -149,32 +143,25 @@ fn struct_type_matches() -> Result<()> { fn struct_subtyping_fields_must_match() -> Result<()> { let engine = Engine::default(); - let a = StructType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [imm_field(HeapType::Any)], - )?; + let a = + StructType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [imm_field( + HeapType::Any, + )])?; for (msg, expected, fields) in [ ("Missing field", false, vec![]), - ( - "Non-matching field", - false, - vec![imm_field(HeapType::Extern)], - ), + ("Non-matching field", false, vec![imm_field( + HeapType::Extern, + )]), ("Wrong mutability field", false, vec![field(HeapType::Any)]), ("Exact match is okay", true, vec![imm_field(HeapType::Any)]), - ( - "Subtype of the field is okay", - true, - vec![imm_field(HeapType::Eq)], - ), - ( - "Extra fields are okay", - true, - vec![imm_field(HeapType::Any), imm_field(HeapType::Extern)], - ), + ("Subtype of the field is okay", true, vec![imm_field( + HeapType::Eq, + )]), + ("Extra fields are okay", true, vec![ + imm_field(HeapType::Any), + imm_field(HeapType::Extern), + ]), ] { let actual = StructType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&a), fields) @@ -243,18 +230,14 @@ fn struct_subtyping() -> Result<()> { // Have to add a field so that `g` doesn't dedupe to `base`. [field(HeapType::Any)], )?; - let h = StructType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&g), - [field(HeapType::Any)], - )?; - let i = StructType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&h), - [field(HeapType::Any)], - )?; + let h = + StructType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&g), [field( + HeapType::Any, + )])?; + let i = + StructType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&h), [field( + HeapType::Any, + )])?; for (expected, sub_name, sub, sup_name, sup) in [ // Identity, at root. @@ -525,21 +508,14 @@ fn func_subtyping_supertype_and_finality() -> Result<()> { let engine = Engine::default(); for (expected, finality) in [(true, Finality::NonFinal), (false, Finality::Final)] { - let superty = FuncType::with_finality_and_supertype( - &engine, - finality, - None, - [], - [valty(HeapType::Any)], - )?; - let actual = FuncType::with_finality_and_supertype( - &engine, - Finality::Final, - Some(&superty), - [], - [valty(HeapType::Any)], - ) - .is_ok(); + let superty = FuncType::with_finality_and_supertype(&engine, finality, None, [], [valty( + HeapType::Any, + )])?; + let actual = + FuncType::with_finality_and_supertype(&engine, Finality::Final, Some(&superty), [], [ + valty(HeapType::Any), + ]) + .is_ok(); assert_eq!(expected, actual); } @@ -561,76 +537,43 @@ fn func_subtyping() -> Result<()> { // e // / // f - let base = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [], - [valty(HeapType::Any)], - )?; - let a = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&base), - [], - [valty(HeapType::Any)], - )?; - let b = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&base), - [], - [valty(HeapType::Eq)], - )?; - let c = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&a), - [], - [valty(HeapType::Any)], - )?; - let d = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&a), - [], - [valty(HeapType::Eq)], - )?; - let e = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&c), - [], - [valty(HeapType::Any)], - )?; - let f = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&e), - [], - [valty(HeapType::Any)], - )?; - let g = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - None, - [], - [valty(HeapType::Eq)], - )?; - let h = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&g), - [], - [valty(HeapType::Eq)], - )?; - let i = FuncType::with_finality_and_supertype( - &engine, - Finality::NonFinal, - Some(&h), - [], - [valty(HeapType::Eq)], - )?; + let base = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [], [valty( + HeapType::Any, + )])?; + let a = FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&base), [], [ + valty(HeapType::Any), + ])?; + let b = FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&base), [], [ + valty(HeapType::Eq), + ])?; + let c = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&a), [], [valty( + HeapType::Any, + )])?; + let d = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&a), [], [valty( + HeapType::Eq, + )])?; + let e = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&c), [], [valty( + HeapType::Any, + )])?; + let f = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&e), [], [valty( + HeapType::Any, + )])?; + let g = FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, None, [], [valty( + HeapType::Eq, + )])?; + let h = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&g), [], [valty( + HeapType::Eq, + )])?; + let i = + FuncType::with_finality_and_supertype(&engine, Finality::NonFinal, Some(&h), [], [valty( + HeapType::Eq, + )])?; for (expected, sub_name, sub, sup_name, sup) in [ // Identity, at root. diff --git a/tests/all/wasi_testsuite.rs b/tests/all/wasi_testsuite.rs index cd96e89c1ba9..587ad13ae5d8 100644 --- a/tests/all/wasi_testsuite.rs +++ b/tests/all/wasi_testsuite.rs @@ -6,7 +6,7 @@ #![cfg(not(miri))] use crate::cli_tests::get_wasmtime_command; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use serde_derive::Deserialize; use std::collections::HashMap; use std::ffi::OsStr; diff --git a/tests/custom_signal_handler.rs b/tests/custom_signal_handler.rs index 6bbce9ae7597..48391fe58851 100644 --- a/tests/custom_signal_handler.rs +++ b/tests/custom_signal_handler.rs @@ -4,9 +4,9 @@ #![cfg(any(target_os = "linux", target_os = "macos"))] #![cfg(not(miri))] -use rustix::mm::{mprotect, MprotectFlags}; -use std::sync::atomic::{AtomicBool, Ordering}; +use rustix::mm::{MprotectFlags, mprotect}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use wasmtime::unix::StoreExt; use wasmtime::*; diff --git a/tests/disas.rs b/tests/disas.rs index c602adcb558b..68de75efe680 100644 --- a/tests/disas.rs +++ b/tests/disas.rs @@ -39,10 +39,10 @@ //! at the start of the file. These comments are then parsed as TOML and //! deserialized into `TestConfig` in this crate. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use clap::Parser; use cranelift_codegen::ir::{Function, UserExternalName, UserFuncName}; -use cranelift_codegen::isa::{lookup_by_name, TargetIsa}; +use cranelift_codegen::isa::{TargetIsa, lookup_by_name}; use cranelift_codegen::settings::{Configurable, Flags, SetError}; use libtest_mimic::{Arguments, Trial}; use pulley_interpreter::decode::OpVisitor; diff --git a/tests/wast.rs b/tests/wast.rs index fc062c39fc45..1b482df136d7 100644 --- a/tests/wast.rs +++ b/tests/wast.rs @@ -1,11 +1,11 @@ -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use libtest_mimic::{Arguments, FormatSetting, Trial}; use std::sync::{Condvar, LazyLock, Mutex}; use wasmtime::{ Config, Engine, InstanceAllocationStrategy, MpkEnabled, PoolingAllocationConfig, Store, }; use wasmtime_wast::{SpectestConfig, WastContext}; -use wasmtime_wast_util::{limits, Collector, Compiler, WastConfig, WastTest}; +use wasmtime_wast_util::{Collector, Compiler, WastConfig, WastTest, limits}; fn main() { env_logger::init(); @@ -54,14 +54,11 @@ fn main() { { let test = test.clone(); move || { - run_wast( - &test, - WastConfig { - compiler, - pooling, - collector, - }, - ) + run_wast(&test, WastConfig { + compiler, + pooling, + collector, + }) .map_err(|e| format!("{e:?}").into()) } }, diff --git a/winch/codegen/src/abi/mod.rs b/winch/codegen/src/abi/mod.rs index d46144489b85..9cce0cdf0e15 100644 --- a/winch/codegen/src/abi/mod.rs +++ b/winch/codegen/src/abi/mod.rs @@ -46,7 +46,7 @@ //! | | ----> Space allocated for calls //! | | use crate::codegen::ptr_type_from_ptr_size; -use crate::isa::{reg::Reg, CallingConvention}; +use crate::isa::{CallingConvention, reg::Reg}; use crate::masm::SPOffset; use smallvec::SmallVec; use std::collections::HashSet; diff --git a/winch/codegen/src/codegen/bounds.rs b/winch/codegen/src/codegen/bounds.rs index 54a293fea73c..29319b54f874 100644 --- a/winch/codegen/src/codegen/bounds.rs +++ b/winch/codegen/src/codegen/bounds.rs @@ -5,7 +5,7 @@ use super::env::HeapData; use crate::{ abi::{scratch, vmctx}, codegen::{CodeGenContext, Emission}, - isa::reg::{writable, Reg}, + isa::reg::{Reg, writable}, masm::{IntCmpKind, MacroAssembler, OperandSize, RegImm, TrapCode}, stack::TypedReg, }; diff --git a/winch/codegen/src/codegen/builtin.rs b/winch/codegen/src/codegen/builtin.rs index 96268ccfd1ef..364e4d33b660 100644 --- a/winch/codegen/src/codegen/builtin.rs +++ b/winch/codegen/src/codegen/builtin.rs @@ -1,9 +1,9 @@ //! Builtin function handling. use crate::{ - abi::{ABISig, ABI}, - codegen::env::ptr_type_from_ptr_size, CallingConvention, + abi::{ABI, ABISig}, + codegen::env::ptr_type_from_ptr_size, }; use cranelift_codegen::ir::LibCall; use std::sync::Arc; diff --git a/winch/codegen/src/codegen/call.rs b/winch/codegen/src/codegen/call.rs index d27ef919dfee..f7f17413bb4d 100644 --- a/winch/codegen/src/codegen/call.rs +++ b/winch/codegen/src/codegen/call.rs @@ -57,18 +57,18 @@ //! └──────────────────────────────────────────────────┘ ------> Stack pointer when emitting the call use crate::{ - abi::{scratch, vmctx, ABIOperand, ABISig, RetArea}, + FuncEnv, + abi::{ABIOperand, ABISig, RetArea, scratch, vmctx}, codegen::{BuiltinFunction, BuiltinType, Callee, CodeGenContext, CodeGenError, Emission}, masm::{ CalleeKind, ContextArgs, MacroAssembler, MemMoveDirection, OperandSize, SPOffset, VMContextLoc, }, - reg::writable, reg::Reg, + reg::writable, stack::Val, - FuncEnv, }; -use anyhow::{ensure, Result}; +use anyhow::{Result, ensure}; use wasmtime_environ::{FuncIndex, PtrSize, VMOffsets}; /// All the information needed to emit a function call. diff --git a/winch/codegen/src/codegen/context.rs b/winch/codegen/src/codegen/context.rs index 648750f47b6a..77024835e804 100644 --- a/winch/codegen/src/codegen/context.rs +++ b/winch/codegen/src/codegen/context.rs @@ -1,14 +1,14 @@ -use anyhow::{bail, ensure, Result}; +use anyhow::{Result, bail, ensure}; use wasmtime_environ::{VMOffsets, WasmHeapType, WasmValType}; use super::ControlStackFrame; use crate::{ - abi::{scratch, vmctx, ABIOperand, ABIResults, RetArea}, + abi::{ABIOperand, ABIResults, RetArea, scratch, vmctx}, codegen::{CodeGenError, CodeGenPhase, Emission, Prologue}, frame::Frame, isa::reg::RegClass, masm::{MacroAssembler, OperandSize, RegImm, SPOffset, ShiftKind, StackSlot}, - reg::{writable, Reg}, + reg::{Reg, writable}, regalloc::RegAlloc, stack::{Stack, TypedReg, Val}, }; diff --git a/winch/codegen/src/codegen/control.rs b/winch/codegen/src/codegen/control.rs index 6d93ab35e4d0..1c0b3bb82cdb 100644 --- a/winch/codegen/src/codegen/control.rs +++ b/winch/codegen/src/codegen/control.rs @@ -8,13 +8,13 @@ //! a conditional jump inline when emitting the control flow instruction. use super::{CodeGenContext, CodeGenError, Emission, OperandSize, Reg, TypedReg}; use crate::{ - abi::{ABIOperand, ABIResults, ABISig, RetArea, ABI}, + CallingConvention, + abi::{ABI, ABIOperand, ABIResults, ABISig, RetArea}, masm::{IntCmpKind, MacroAssembler, MemMoveDirection, RegImm, SPOffset}, reg::writable, stack::Val, - CallingConvention, }; -use anyhow::{anyhow, bail, ensure, Result}; +use anyhow::{Result, anyhow, bail, ensure}; use cranelift_codegen::MachLabel; use wasmtime_environ::{WasmFuncType, WasmValType}; diff --git a/winch/codegen/src/codegen/env.rs b/winch/codegen/src/codegen/env.rs index edae51d4760e..d4b199768877 100644 --- a/winch/codegen/src/codegen/env.rs +++ b/winch/codegen/src/codegen/env.rs @@ -1,12 +1,12 @@ use crate::{ - abi::{wasm_sig, ABISig, ABI}, - codegen::{control, BlockSig, BuiltinFunction, BuiltinFunctions, OperandSize}, + abi::{ABI, ABISig, wasm_sig}, + codegen::{BlockSig, BuiltinFunction, BuiltinFunctions, OperandSize, control}, isa::TargetIsa, }; use cranelift_codegen::ir::{UserExternalName, UserExternalNameRef}; use std::collections::{ - hash_map::Entry::{Occupied, Vacant}, HashMap, + hash_map::Entry::{Occupied, Vacant}, }; use std::mem; use wasmparser::BlockType; diff --git a/winch/codegen/src/codegen/mod.rs b/winch/codegen/src/codegen/mod.rs index 5a80108520d6..39348d2c35fd 100644 --- a/winch/codegen/src/codegen/mod.rs +++ b/winch/codegen/src/codegen/mod.rs @@ -1,13 +1,13 @@ use crate::{ - abi::{scratch, vmctx, ABIOperand, ABISig, RetArea}, + abi::{ABIOperand, ABISig, RetArea, scratch, vmctx}, codegen::BlockSig, - isa::reg::{writable, Reg}, + isa::reg::{Reg, writable}, masm::{ ExtendKind, IntCmpKind, MacroAssembler, OperandSize, RegImm, SPOffset, ShiftKind, TrapCode, }, stack::TypedReg, }; -use anyhow::{anyhow, bail, ensure, Result}; +use anyhow::{Result, anyhow, bail, ensure}; use cranelift_codegen::{ binemit::CodeOffset, ir::{RelSourceLoc, SourceLoc}, @@ -20,8 +20,8 @@ use wasmparser::{ }; use wasmtime_cranelift::{TRAP_BAD_SIGNATURE, TRAP_TABLE_OUT_OF_BOUNDS}; use wasmtime_environ::{ - GlobalIndex, MemoryIndex, PtrSize, TableIndex, Tunables, TypeIndex, WasmHeapType, WasmValType, - FUNCREF_MASK, + FUNCREF_MASK, GlobalIndex, MemoryIndex, PtrSize, TableIndex, Tunables, TypeIndex, WasmHeapType, + WasmValType, }; mod context; diff --git a/winch/codegen/src/frame/mod.rs b/winch/codegen/src/frame/mod.rs index 9dc58339a600..7f7e6d0a9269 100644 --- a/winch/codegen/src/frame/mod.rs +++ b/winch/codegen/src/frame/mod.rs @@ -1,5 +1,5 @@ use crate::{ - abi::{align_to, ABIOperand, ABISig, LocalSlot, ABI}, + abi::{ABI, ABIOperand, ABISig, LocalSlot, align_to}, codegen::{CodeGenPhase, Emission, Prologue}, masm::MacroAssembler, }; diff --git a/winch/codegen/src/isa/aarch64/abi.rs b/winch/codegen/src/isa/aarch64/abi.rs index 242d2c92b822..b9b4a879c015 100644 --- a/winch/codegen/src/isa/aarch64/abi.rs +++ b/winch/codegen/src/isa/aarch64/abi.rs @@ -1,7 +1,7 @@ use super::regs; -use crate::abi::{align_to, ABIOperand, ABIParams, ABIResults, ABISig, ParamsOrReturns, ABI}; -use crate::isa::{reg::Reg, CallingConvention}; use crate::RegIndexEnv; +use crate::abi::{ABI, ABIOperand, ABIParams, ABIResults, ABISig, ParamsOrReturns, align_to}; +use crate::isa::{CallingConvention, reg::Reg}; use wasmtime_environ::{WasmHeapType, WasmRefType, WasmValType}; #[derive(Default)] @@ -155,10 +155,10 @@ impl Aarch64ABI { mod tests { use super::Aarch64ABI; use crate::{ - abi::{ABIOperand, ABI}, + abi::{ABI, ABIOperand}, + isa::CallingConvention, isa::aarch64::regs, isa::reg::Reg, - isa::CallingConvention, }; use wasmtime_environ::{ WasmFuncType, diff --git a/winch/codegen/src/isa/aarch64/address.rs b/winch/codegen/src/isa/aarch64/address.rs index 9e888f9898e7..3cd3ce21f17f 100644 --- a/winch/codegen/src/isa/aarch64/address.rs +++ b/winch/codegen/src/isa/aarch64/address.rs @@ -1,6 +1,6 @@ //! Aarch64 addressing mode. -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result, anyhow}; use cranelift_codegen::{ ir::types, isa::aarch64::inst::{AMode, PairAMode, SImm7Scaled, SImm9}, diff --git a/winch/codegen/src/isa/aarch64/asm.rs b/winch/codegen/src/isa/aarch64/asm.rs index 5440d04e168e..2b47b211ddd8 100644 --- a/winch/codegen/src/isa/aarch64/asm.rs +++ b/winch/codegen/src/isa/aarch64/asm.rs @@ -1,29 +1,29 @@ //! Assembler library implementation for Aarch64. use super::{address::Address, regs}; +use crate::CallingConvention; use crate::aarch64::regs::zero; use crate::masm::{ DivKind, ExtendKind, FloatCmpKind, IntCmpKind, RemKind, RoundingMode, ShiftKind, TruncKind, }; -use crate::CallingConvention; use crate::{ masm::OperandSize, - reg::{writable, Reg, WritableReg}, + reg::{Reg, WritableReg, writable}, }; -use cranelift_codegen::isa::aarch64::inst::{ASIMDFPModImm, FpuToIntOp, UImm5, NZCV}; +use cranelift_codegen::isa::aarch64::inst::{ASIMDFPModImm, FpuToIntOp, NZCV, UImm5}; use cranelift_codegen::{ + Final, MachBuffer, MachBufferFinalized, MachInst, MachInstEmit, MachInstEmitState, MachLabel, + Writable, ir::{ExternalName, LibCall, MemFlags, SourceLoc, TrapCode, UserExternalNameRef}, isa::aarch64::inst::{ - self, - emit::{EmitInfo, EmitState}, - ALUOp, ALUOp3, AMode, BitOp, BranchTarget, Cond, CondBrKind, ExtendOp, FPULeftShiftImm, - FPUOp1, FPUOp2, + self, ALUOp, ALUOp3, AMode, BitOp, BranchTarget, Cond, CondBrKind, ExtendOp, + FPULeftShiftImm, FPUOp1, FPUOp2, FPUOpRI::{self, UShr32, UShr64}, FPUOpRIMod, FPURightShiftImm, FpuRoundMode, Imm12, ImmLogic, ImmShift, Inst, IntToFpuOp, PairAMode, ScalarSize, VecLanesOp, VecMisc2, VectorSize, + emit::{EmitInfo, EmitState}, }, - settings, Final, MachBuffer, MachBufferFinalized, MachInst, MachInstEmit, MachInstEmitState, - MachLabel, Writable, + settings, }; impl From for inst::OperandSize { diff --git a/winch/codegen/src/isa/aarch64/masm.rs b/winch/codegen/src/isa/aarch64/masm.rs index a8c17c514e53..18b0a89cc640 100644 --- a/winch/codegen/src/isa/aarch64/masm.rs +++ b/winch/codegen/src/isa/aarch64/masm.rs @@ -6,10 +6,10 @@ use super::{ }; use crate::{ abi::{self, align_to, calculate_frame_adjustment, local::LocalSlot, vmctx}, - codegen::{ptr_type_from_ptr_size, CodeGenContext, CodeGenError, Emission, FuncEnv}, + codegen::{CodeGenContext, CodeGenError, Emission, FuncEnv, ptr_type_from_ptr_size}, isa::{ - reg::{writable, Reg, WritableReg}, CallingConvention, + reg::{Reg, WritableReg, writable}, }, masm::{ CalleeKind, DivKind, ExtendKind, FloatCmpKind, Imm as I, IntCmpKind, @@ -18,12 +18,13 @@ use crate::{ }, stack::TypedReg, }; -use anyhow::{anyhow, bail, Result}; +use anyhow::{Result, anyhow, bail}; use cranelift_codegen::{ + Final, MachBufferFinalized, MachLabel, binemit::CodeOffset, ir::{RelSourceLoc, SourceLoc}, isa::aarch64::inst::{Cond, VectorSize}, - settings, Final, MachBufferFinalized, MachLabel, + settings, }; use regalloc2::RegClass; use wasmtime_environ::{PtrSize, WasmValType}; diff --git a/winch/codegen/src/isa/aarch64/mod.rs b/winch/codegen/src/isa/aarch64/mod.rs index ed75be845b84..b04e758978fb 100644 --- a/winch/codegen/src/isa/aarch64/mod.rs +++ b/winch/codegen/src/isa/aarch64/mod.rs @@ -1,7 +1,8 @@ use self::regs::{ALL_GPR, MAX_FPR, MAX_GPR, NON_ALLOCATABLE_GPR}; use crate::isa::aarch64::regs::{ALL_FPR, NON_ALLOCATABLE_FPR}; use crate::{ - abi::{wasm_sig, ABI}, + BuiltinFunctions, + abi::{ABI, wasm_sig}, codegen::{CodeGen, CodeGenContext, FuncEnv, TypeConverter}, frame::{DefinedLocals, Frame}, isa::{Builder, TargetIsa}, @@ -9,11 +10,10 @@ use crate::{ regalloc::RegAlloc, regset::RegBitSet, stack::Stack, - BuiltinFunctions, }; use anyhow::Result; use cranelift_codegen::settings::{self, Flags}; -use cranelift_codegen::{isa::aarch64::settings as aarch64_settings, Final, MachBufferFinalized}; +use cranelift_codegen::{Final, MachBufferFinalized, isa::aarch64::settings as aarch64_settings}; use cranelift_codegen::{MachTextSectionBuilder, TextSectionBuilder}; use masm::MacroAssembler as Aarch64Masm; use target_lexicon::Triple; diff --git a/winch/codegen/src/isa/mod.rs b/winch/codegen/src/isa/mod.rs index 7500f876856f..b4ea2560f0ee 100644 --- a/winch/codegen/src/isa/mod.rs +++ b/winch/codegen/src/isa/mod.rs @@ -1,5 +1,5 @@ use crate::BuiltinFunctions; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use core::fmt::Formatter; use cranelift_codegen::isa::unwind::{UnwindInfo, UnwindInfoKind}; use cranelift_codegen::isa::{CallConv, IsaBuilder}; diff --git a/winch/codegen/src/isa/x64/abi.rs b/winch/codegen/src/isa/x64/abi.rs index de60ee1f5654..e525470c6a32 100644 --- a/winch/codegen/src/isa/x64/abi.rs +++ b/winch/codegen/src/isa/x64/abi.rs @@ -1,8 +1,8 @@ use super::regs; use crate::{ - abi::{align_to, ABIOperand, ABIParams, ABIResults, ABISig, ParamsOrReturns, ABI}, - isa::{reg::Reg, CallingConvention}, RegIndexEnv, + abi::{ABI, ABIOperand, ABIParams, ABIResults, ABISig, ParamsOrReturns, align_to}, + isa::{CallingConvention, reg::Reg}, }; use wasmtime_environ::{WasmHeapType, WasmRefType, WasmValType}; @@ -277,8 +277,8 @@ impl X64ABI { mod tests { use super::X64ABI; use crate::{ - abi::{ABIOperand, ABI}, - isa::{reg::Reg, x64::regs, CallingConvention}, + abi::{ABI, ABIOperand}, + isa::{CallingConvention, reg::Reg, x64::regs}, }; use wasmtime_environ::{ WasmFuncType, diff --git a/winch/codegen/src/isa/x64/asm.rs b/winch/codegen/src/isa/x64/asm.rs index 4cae0f512dfb..3dd5e18690d0 100644 --- a/winch/codegen/src/isa/x64/asm.rs +++ b/winch/codegen/src/isa/x64/asm.rs @@ -1,31 +1,33 @@ //! Assembler library implementation for x64. use crate::{ - isa::{reg::Reg, CallingConvention}, + isa::{CallingConvention, reg::Reg}, masm::{ DivKind, ExtendKind, IntCmpKind, MulWideKind, OperandSize, RemKind, RoundingMode, ShiftKind, }, }; use cranelift_codegen::{ + CallInfo, Final, MachBuffer, MachBufferFinalized, MachInstEmit, MachInstEmitState, MachLabel, + PatchRegion, RelocDistance, VCodeConstantData, VCodeConstants, Writable, ir::{ - types, ConstantPool, ExternalName, LibCall, MemFlags, SourceLoc, TrapCode, - UserExternalNameRef, + ConstantPool, ExternalName, LibCall, MemFlags, SourceLoc, TrapCode, UserExternalNameRef, + types, }, isa::{ unwind::UnwindInst, x64::{ + EmitInfo, EmitState, Inst, args::{ - self, AluRmiROpcode, Amode, CmpOpcode, DivSignedness, ExtMode, FromWritableReg, + self, AluRmiROpcode, Amode, CC, CmpOpcode, DivSignedness, ExtMode, FromWritableReg, Gpr, GprMem, GprMemImm, Imm8Gpr, Imm8Reg, RegMem, RegMemImm, ShiftKind as CraneliftShiftKind, SseOpcode, SyntheticAmode, WritableGpr, - WritableXmm, Xmm, XmmMem, XmmMemAligned, CC, + WritableXmm, Xmm, XmmMem, XmmMemAligned, }, - encoding::rex::{encode_modrm, RexFlags}, - settings as x64_settings, EmitInfo, EmitState, Inst, + encoding::rex::{RexFlags, encode_modrm}, + settings as x64_settings, }, }, - settings, CallInfo, Final, MachBuffer, MachBufferFinalized, MachInstEmit, MachInstEmitState, - MachLabel, PatchRegion, RelocDistance, VCodeConstantData, VCodeConstants, Writable, + settings, }; use crate::reg::WritableReg; diff --git a/winch/codegen/src/isa/x64/masm.rs b/winch/codegen/src/isa/x64/masm.rs index 6b16203f202b..9b8938810c50 100644 --- a/winch/codegen/src/isa/x64/masm.rs +++ b/winch/codegen/src/isa/x64/masm.rs @@ -4,38 +4,39 @@ use super::{ asm::{Assembler, PatchableAddToReg}, regs::{self, rbp, rsp}, }; -use anyhow::{anyhow, bail, Result}; +use anyhow::{Result, anyhow, bail}; use crate::masm::{ DivKind, ExtendKind, FloatCmpKind, Imm as I, IntCmpKind, MacroAssembler as Masm, MulWideKind, - OperandSize, RegImm, RemKind, RoundingMode, ShiftKind, TrapCode, TruncKind, TRUSTED_FLAGS, + OperandSize, RegImm, RemKind, RoundingMode, ShiftKind, TRUSTED_FLAGS, TrapCode, TruncKind, UNTRUSTED_FLAGS, }; use crate::{ - abi::{self, align_to, calculate_frame_adjustment, LocalSlot}, - codegen::{ptr_type_from_ptr_size, CodeGenContext, CodeGenError, Emission, FuncEnv}, + abi::{self, LocalSlot, align_to, calculate_frame_adjustment}, + codegen::{CodeGenContext, CodeGenError, Emission, FuncEnv, ptr_type_from_ptr_size}, stack::{TypedReg, Val}, }; use crate::{ - abi::{vmctx, ABI}, + abi::{ABI, vmctx}, masm::{SPOffset, StackSlot}, }; use crate::{ isa::{ - reg::{writable, Reg, RegClass, WritableReg}, CallingConvention, + reg::{Reg, RegClass, WritableReg, writable}, }, masm::CalleeKind, }; use cranelift_codegen::{ + Final, MachBufferFinalized, MachLabel, binemit::CodeOffset, ir::{MemFlags, RelSourceLoc, SourceLoc}, isa::unwind::UnwindInst, isa::x64::{ - args::{ExtMode, CC}, + args::{CC, ExtMode}, settings as x64_settings, }, - settings, Final, MachBufferFinalized, MachLabel, + settings, }; use wasmtime_cranelift::TRAP_UNREACHABLE; use wasmtime_environ::{PtrSize, WasmValType}; diff --git a/winch/codegen/src/isa/x64/mod.rs b/winch/codegen/src/isa/x64/mod.rs index 3c976c631131..9a4841bc6480 100644 --- a/winch/codegen/src/isa/x64/mod.rs +++ b/winch/codegen/src/isa/x64/mod.rs @@ -1,5 +1,5 @@ use crate::{ - abi::{wasm_sig, ABI}, + abi::{ABI, wasm_sig}, codegen::{BuiltinFunctions, CodeGen, CodeGenContext, FuncEnv, TypeConverter}, }; @@ -14,7 +14,7 @@ use crate::{ }; use anyhow::Result; use cranelift_codegen::settings::{self, Flags}; -use cranelift_codegen::{isa::x64::settings as x64_settings, Final, MachBufferFinalized}; +use cranelift_codegen::{Final, MachBufferFinalized, isa::x64::settings as x64_settings}; use cranelift_codegen::{MachTextSectionBuilder, TextSectionBuilder}; use target_lexicon::Triple; use wasmparser::{FuncValidator, FunctionBody, ValidatorResources}; diff --git a/winch/codegen/src/masm.rs b/winch/codegen/src/masm.rs index 42afba43f2b0..53d5d2ded17f 100644 --- a/winch/codegen/src/masm.rs +++ b/winch/codegen/src/masm.rs @@ -1,14 +1,14 @@ -use crate::abi::{self, align_to, scratch, LocalSlot}; +use crate::abi::{self, LocalSlot, align_to, scratch}; use crate::codegen::{CodeGenContext, Emission, FuncEnv}; use crate::isa::{ - reg::{writable, Reg, WritableReg}, CallingConvention, + reg::{Reg, WritableReg, writable}, }; use anyhow::Result; use cranelift_codegen::{ + Final, MachBufferFinalized, MachLabel, binemit::CodeOffset, ir::{Endianness, LibCall, MemFlags, RelSourceLoc, SourceLoc, UserExternalNameRef}, - Final, MachBufferFinalized, MachLabel, }; use std::{fmt::Debug, ops::Range}; use wasmtime_environ::PtrSize; @@ -669,7 +669,7 @@ pub(crate) trait MacroAssembler { /// Perform a conditional move. fn cmov(&mut self, dst: WritableReg, src: Reg, cc: IntCmpKind, size: OperandSize) - -> Result<()>; + -> Result<()>; /// Performs a memory move of bytes from src to dest. /// Bytes are moved in blocks of 8 bytes, where possible. @@ -1133,5 +1133,5 @@ pub(crate) trait MacroAssembler { /// Note that some platforms require special handling of registers in this /// instruction (e.g. x64) so full access to `CodeGenContext` is provided. fn mul_wide(&mut self, context: &mut CodeGenContext, kind: MulWideKind) - -> Result<()>; + -> Result<()>; } diff --git a/winch/codegen/src/regalloc.rs b/winch/codegen/src/regalloc.rs index 2068553c079a..92afff7cc14a 100644 --- a/winch/codegen/src/regalloc.rs +++ b/winch/codegen/src/regalloc.rs @@ -4,7 +4,7 @@ use crate::{ regset::{RegBitSet, RegSet}, }; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; /// The register allocator. /// diff --git a/winch/codegen/src/stack.rs b/winch/codegen/src/stack.rs index e52a4a94a24f..f57b03d3ef0a 100644 --- a/winch/codegen/src/stack.rs +++ b/winch/codegen/src/stack.rs @@ -1,5 +1,5 @@ use crate::{codegen::CodeGenError, isa::reg::Reg, masm::StackSlot}; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use smallvec::SmallVec; use wasmparser::{Ieee32, Ieee64}; use wasmtime_environ::WasmValType; diff --git a/winch/codegen/src/visitor.rs b/winch/codegen/src/visitor.rs index 86e8bfd56f7e..cdbe79a4331b 100644 --- a/winch/codegen/src/visitor.rs +++ b/winch/codegen/src/visitor.rs @@ -6,25 +6,25 @@ use crate::abi::RetArea; use crate::codegen::{ - control_index, Callee, CodeGen, CodeGenError, ControlStackFrame, Emission, FnCall, + Callee, CodeGen, CodeGenError, ControlStackFrame, Emission, FnCall, control_index, }; use crate::masm::{ DivKind, ExtendKind, FloatCmpKind, IntCmpKind, MacroAssembler, MemMoveDirection, MulWideKind, OperandSize, RegImm, RemKind, RoundingMode, SPOffset, ShiftKind, TruncKind, }; -use crate::reg::{writable, Reg}; +use crate::reg::{Reg, writable}; use crate::stack::{TypedReg, Val}; -use anyhow::{anyhow, bail, ensure, Result}; +use anyhow::{Result, anyhow, bail, ensure}; use regalloc2::RegClass; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use wasmparser::{ - BlockType, BrTable, Ieee32, Ieee64, MemArg, VisitOperator, VisitSimdOperator, V128, + BlockType, BrTable, Ieee32, Ieee64, MemArg, V128, VisitOperator, VisitSimdOperator, }; use wasmtime_cranelift::TRAP_INDIRECT_CALL_TO_NULL; use wasmtime_environ::{ - FuncIndex, GlobalIndex, MemoryIndex, TableIndex, TypeIndex, WasmHeapType, WasmValType, - FUNCREF_INIT_BIT, + FUNCREF_INIT_BIT, FuncIndex, GlobalIndex, MemoryIndex, TableIndex, TypeIndex, WasmHeapType, + WasmValType, }; /// A macro to define unsupported WebAssembly operators.