From efbddeaeeea4475e53f2ada273a73102a5d8b833 Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Thu, 2 Apr 2026 15:55:45 -0400 Subject: [PATCH 01/10] Issue 3223: First phase of migration to Rust Edition 2024 Update cargo dependencies Apply cargo fix --edition Change cargo.toml edition property to `2024` ^ Conflicts: ^ Cargo.lock ^ src/ffi.rs ^ Conflicts: ^ src/offset_table.rs ^ src/raw_block.rs --- Cargo.lock | 144 +++++++++++++------------- Cargo.toml | 2 +- benches/setup.rs | 2 +- src/arena.rs | 8 +- src/arithmetic.rs | 32 +++--- src/atom_table.rs | 10 +- src/codegen.rs | 30 +++--- src/debray_allocator.rs | 14 +-- src/ffi.rs | 34 +++---- src/forms.rs | 34 +++---- src/heap_print.rs | 4 +- src/indexing.rs | 82 +++++++-------- src/instructions.rs | 16 +-- src/iterators.rs | 6 +- src/machine/attributed_variables.rs | 2 +- src/machine/compile.rs | 40 ++++---- src/machine/dispatch.rs | 58 +++++------ src/machine/heap.rs | 16 +-- src/machine/load_state.rs | 22 ++-- src/machine/loader.rs | 10 +- src/machine/machine_errors.rs | 2 +- src/machine/machine_indices.rs | 8 +- src/machine/machine_state.rs | 2 +- src/machine/mod.rs | 4 +- src/machine/preprocessor.rs | 2 +- src/machine/stack.rs | 4 +- src/machine/streams.rs | 150 ++++++++++++++-------------- src/machine/system_calls.rs | 20 ++-- src/offset_table.rs | 12 +-- src/parser/ast.rs | 6 +- src/types.rs | 4 +- src/variable_records.rs | 4 +- 32 files changed, 389 insertions(+), 395 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 480ba916..3c30bc10 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,9 +204,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a" [[package]] name = "bitvec" @@ -279,12 +279,12 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.2.62" +version = "1.2.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" +checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f" dependencies = [ "find-msvc-tools", - "shlex", + "shlex 2.0.1", ] [[package]] @@ -525,7 +525,7 @@ version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "crossterm_winapi", "mio", "parking_lot", @@ -613,9 +613,9 @@ checksum = "a74858bcfe44b22016cb49337d7b6f04618c58e5dbfdef61b06b8c434324a0bc" [[package]] name = "dashu" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b3e5ac1e23ff1995ef05b912e2b012a8784506987a2651552db2c73fb3d7e0" +checksum = "dc8621924e1a1d2e19f3ea55c7b553a90b1f63a0a5c0a3f5b44afce841d08aa0" dependencies = [ "dashu-base", "dashu-float", @@ -627,15 +627,15 @@ dependencies = [ [[package]] name = "dashu-base" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b80bf6b85aa68c58ffea2ddb040109943049ce3fbdf4385d0380aef08ef289" +checksum = "fab3f0756c8585395280bd81b384cd28bbd66d6b00e66124ecfd1f644938b38c" [[package]] name = "dashu-float" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85078445a8dbd2e1bd21f04a816f352db8d333643f0c9b78ca7c3d1df71063e7" +checksum = "85d913daa4f8193f709a2b5cc87a8be649dac8d816f7f049fb0a38e8b9e5d23b" dependencies = [ "dashu-base", "dashu-int", @@ -648,9 +648,9 @@ dependencies = [ [[package]] name = "dashu-int" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee99d08031ca34a4d044efbbb21dff9b8c54bb9d8c82a189187c0651ffdb9fbf" +checksum = "d6a93d93dc2aca9a071e6ecb2af883441e8b34357a1037bc536e1c52b0d3c713" dependencies = [ "cfg-if", "dashu-base", @@ -663,15 +663,15 @@ dependencies = [ [[package]] name = "dashu-macros" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93381c3ef6366766f6e9ed9cf09e4ef9dec69499baf04f0c60e70d653cf0ab10" +checksum = "a89dbf51c81b22b30a0a30a4fcff84c4af8bdcd7a6159a556007b0b2dabc1e79" dependencies = [ "dashu-base", "dashu-float", "dashu-int", "dashu-ratio", - "paste", + "pastey", "proc-macro2", "quote", "rustversion", @@ -679,9 +679,9 @@ dependencies = [ [[package]] name = "dashu-ratio" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e33b04dd7ce1ccf8a02a69d3419e354f2bbfdf4eb911a0b7465487248764c9" +checksum = "b689daf8ea2221461973a29752a648e2971a377acefbf20df88e063f491032c7" dependencies = [ "dashu-base", "dashu-float", @@ -758,7 +758,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "block2", "libc", "objc2", @@ -766,9 +766,9 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", @@ -1711,9 +1711,9 @@ dependencies = [ [[package]] name = "libredox" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" +checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" dependencies = [ "libc", ] @@ -1747,9 +1747,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.30" +version = "0.4.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5" +checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f" [[package]] name = "mac" @@ -1790,9 +1790,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" [[package]] name = "memmap2" @@ -1830,9 +1830,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" dependencies = [ "libc", "log", @@ -1928,7 +1928,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "cfg-if", "cfg_aliases", "libc", @@ -2031,7 +2031,7 @@ version = "0.10.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a45fa2aa886c42762255da344f0a0d313e254066c46aad76f300c3d3da62d967" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "cfg-if", "foreign-types", "libc", @@ -2135,10 +2135,10 @@ dependencies = [ ] [[package]] -name = "paste" -version = "1.0.15" +name = "pastey" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" [[package]] name = "percent-encoding" @@ -2472,7 +2472,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", ] [[package]] @@ -2614,7 +2614,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "errno", "libc", "linux-raw-sys 0.4.15", @@ -2627,7 +2627,7 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "errno", "libc", "linux-raw-sys 0.12.1", @@ -2698,7 +2698,7 @@ version = "18.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a990b25f351b25139ddc7f21ee3f6f56f86d6846b74ac8fad3a719a287cd4a0" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "cfg-if", "clipboard-win", "home", @@ -2728,15 +2728,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scc" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46e6f046b7fef48e2660c57ed794263155d713de679057f2d0c169bfc6e756cc" -dependencies = [ - "sdd", -] - [[package]] name = "schannel" version = "0.1.29" @@ -2848,19 +2839,13 @@ dependencies = [ "web-sys", ] -[[package]] -name = "sdd" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca" - [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -2883,7 +2868,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd568a4c9bb598e291a08244a5c1f5a8a6650bee243b5b0f8dbb3d9cc1d87fe8" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "cssparser", "derive_more", "fxhash", @@ -2979,24 +2964,23 @@ dependencies = [ [[package]] name = "serial_test" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "911bd979bf1070a3f3aa7b691a3b3e9968f339ceeec89e08c280a8a22207a32f" +checksum = "699f4197115b8a7e7ff19c9a315a4bd6fffec26cc4626ef45ecaea389e081c6d" dependencies = [ "futures-executor", "futures-util", "log", "once_cell", "parking_lot", - "scc", "serial_test_derive", ] [[package]] name = "serial_test_derive" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a7d91949b85b0d2fb687445e448b40d322b6b3e4af6b44a29b21d9a5f33e6d9" +checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c" dependencies = [ "proc-macro2", "quote", @@ -3050,6 +3034,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signal-hook" version = "0.3.18" @@ -3148,9 +3138,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", "windows-sys 0.61.2", @@ -3415,7 +3405,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.3", + "socket2 0.6.4", "tokio-macros", "windows-sys 0.61.2", ] @@ -3561,7 +3551,7 @@ dependencies = [ "humantime-serde", "rayon", "serde", - "shlex", + "shlex 1.3.0", "snapbox", "toml_edit", ] @@ -3587,9 +3577,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.20.0" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicase" @@ -3605,9 +3595,9 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-segmentation" -version = "1.13.2" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" @@ -3659,9 +3649,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.23.1" +version = "1.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" dependencies = [ "js-sys", "wasm-bindgen", @@ -3845,7 +3835,7 @@ version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.12.1", "hashbrown 0.15.5", "indexmap", "semver", @@ -4271,7 +4261,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", - "bitflags 2.11.1", + "bitflags 2.12.1", "indexmap", "log", "serde", @@ -4347,18 +4337,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index f7511677..8d0961be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "scryer-prolog" version = "0.10.0" authors = ["Mark Thom "] -edition = "2021" +edition = "2024" description = "A modern Prolog implementation written mostly in Rust." readme = "README.md" repository = "https://github.com/mthom/scryer-prolog" diff --git a/benches/setup.rs b/benches/setup.rs index ac055c08..859ec3fd 100644 --- a/benches/setup.rs +++ b/benches/setup.rs @@ -70,7 +70,7 @@ impl PrologBenchmark { } #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] - pub fn setup(&self) -> impl FnMut() -> Vec { + pub fn setup(&self) -> impl FnMut() -> Vec + use<> { let mut machine = self.make_machine(); let query = self.query; move || { diff --git a/src/arena.rs b/src/arena.rs index 01c2d697..aae81e4e 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -281,14 +281,14 @@ pub trait ArenaAllocated { unsafe fn typed_ptr(ptr: UntypedArenaPtr) -> TypedArenaPtr where Self::Payload: Sized, - { + { unsafe { TypedArenaPtr(NonNull::new_unchecked( ptr.get_ptr() .byte_add(Self::header_offset_from_payload()) .cast_mut() .cast::(), )) - } + }} #[allow(clippy::missing_safety_doc)] fn alloc(arena: &mut Arena, value: Self::Payload) -> TypedArenaPtr @@ -496,7 +496,7 @@ impl Arena { } } -unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { +unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { unsafe { macro_rules! drop_typed_slab_in_place { ($payload: ty, $value: expr) => { <$payload as ArenaAllocated>::dealloc($value.cast::>()) @@ -580,7 +580,7 @@ unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { unreachable!("NullStream is never arena allocated!"); } } -} +}} impl Drop for Arena { fn drop(&mut self) { diff --git a/src/arithmetic.rs b/src/arithmetic.rs index a0cf61b0..df5b6268 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -361,7 +361,7 @@ pub(crate) fn rnd_i(n: &'_ Number, arena: &mut Arena) -> Result { + Number::Rational(r) => { let floor = r.floor(); if let Ok(value) = Fixnum::build_with_checked(&floor) { @@ -384,9 +384,9 @@ impl From for Integer { pub(crate) fn rnd_f(n: &Number) -> f64 { match n { &Number::Fixnum(n) => n.get_num() as f64, - Number::Integer(ref n) => n.to_f64().value(), + Number::Integer(n) => n.to_f64().value(), &Number::Float(OrderedFloat(f)) => f, - Number::Rational(ref r) => r.to_f64().value(), + Number::Rational(r) => r.to_f64().value(), } } @@ -514,33 +514,33 @@ impl PartialEq for Number { fn eq(&self, rhs: &Self) -> bool { match (self, rhs) { (&Number::Fixnum(n1), &Number::Fixnum(n2)) => n1.eq(&n2), - (&Number::Fixnum(n1), Number::Integer(ref n2)) => n1.get_num().num_eq(&**n2), - (Number::Integer(ref n1), &Number::Fixnum(n2)) => n1.num_eq(&n2.get_num()), - (&Number::Fixnum(n1), Number::Rational(ref n2)) => { + (&Number::Fixnum(n1), Number::Integer(n2)) => n1.get_num().num_eq(&**n2), + (Number::Integer(n1), &Number::Fixnum(n2)) => n1.num_eq(&n2.get_num()), + (&Number::Fixnum(n1), Number::Rational(n2)) => { Integer::from(n1.get_num()).num_eq(&**n2) } - (Number::Rational(ref n1), &Number::Fixnum(n2)) => { + (Number::Rational(n1), &Number::Fixnum(n2)) => { n1.num_eq(&Integer::from(n2.get_num())) } (&Number::Fixnum(n1), &Number::Float(n2)) => OrderedFloat(n1.get_num() as f64).eq(&n2), (&Number::Float(n1), &Number::Fixnum(n2)) => n1.eq(&OrderedFloat(n2.get_num() as f64)), - (Number::Integer(ref n1), Number::Integer(ref n2)) => n1.eq(n2), - (Number::Integer(ref n1), Number::Float(n2)) => { + (Number::Integer(n1), Number::Integer(n2)) => n1.eq(n2), + (Number::Integer(n1), Number::Float(n2)) => { OrderedFloat(n1.to_f64().value()).eq(n2) } - (&Number::Float(n1), Number::Integer(ref n2)) => { + (&Number::Float(n1), Number::Integer(n2)) => { n1.eq(&OrderedFloat(n2.to_f64().value())) } - (Number::Integer(ref n1), Number::Rational(ref n2)) => n1.num_eq(&**n2), - (Number::Rational(ref n1), Number::Integer(ref n2)) => n1.num_eq(&**n2), - (Number::Rational(ref n1), &Number::Float(n2)) => { + (Number::Integer(n1), Number::Rational(n2)) => n1.num_eq(&**n2), + (Number::Rational(n1), Number::Integer(n2)) => n1.num_eq(&**n2), + (Number::Rational(n1), &Number::Float(n2)) => { OrderedFloat(n1.to_f64().value()).eq(&n2) } - (&Number::Float(n1), Number::Rational(ref n2)) => { + (&Number::Float(n1), Number::Rational(n2)) => { n1.eq(&OrderedFloat(n2.to_f64().value())) } (&Number::Float(f1), &Number::Float(f2)) => f1.eq(&f2), - (Number::Rational(ref r1), Number::Rational(ref r2)) => r1.eq(r2), + (Number::Rational(r1), Number::Rational(r2)) => r1.eq(r2), } } } @@ -607,7 +607,7 @@ impl Ord for Number { (&Number::Float(n1), &Number::Fixnum(n2)) => n1.cmp(&OrderedFloat(n2.get_num() as f64)), (&Number::Integer(n1), &Number::Integer(n2)) => (*n1).cmp(&*n2), (&Number::Integer(n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).cmp(n2), - (&Number::Float(n1), Number::Integer(ref n2)) => { + (&Number::Float(n1), Number::Integer(n2)) => { n1.cmp(&OrderedFloat(n2.to_f64().value())) } (&Number::Integer(n1), &Number::Rational(n2)) => { diff --git a/src/atom_table.rs b/src/atom_table.rs index 155aeb9a..5526b1ff 100644 --- a/src/atom_table.rs +++ b/src/atom_table.rs @@ -387,10 +387,12 @@ impl Atom { } } -unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { - ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); - let str_ptr = ptr.add(mem::size_of::()); - ptr::copy_nonoverlapping(string.as_ptr(), str_ptr, string.len()); +unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { + unsafe { ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); } + unsafe { + let str_ptr = ptr.add(mem::size_of::()); + ptr::copy_nonoverlapping(string.as_ptr(), str_ptr, string.len()); + } } impl PartialOrd for Atom { diff --git a/src/codegen.rs b/src/codegen.rs index b19dc8ae..dfedf725 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -345,10 +345,10 @@ impl<'a> AddToFreeList<'a, QueryInstruction> for CodeGenerator { fn structure_cell(term: &Term) -> Option<&Cell> { match term { - &Term::Cons(ref cell, ..) - | &Term::Clause(ref cell, ..) - | Term::PartialString(ref cell, ..) - | Term::CompleteString(ref cell, ..) => Some(cell), + Term::Cons(cell, ..) + | Term::Clause(cell, ..) + | Term::PartialString(cell, ..) + | Term::CompleteString(cell, ..) => Some(cell), _ => None, } } @@ -401,18 +401,18 @@ impl CodeGenerator { &Term::AnonVar => { Self::add_or_increment_void_instr::(target); } - &Term::Cons(ref cell, ..) - | &Term::Clause(ref cell, ..) - | Term::PartialString(ref cell, ..) - | Term::CompleteString(ref cell, ..) => { + Term::Cons(cell, ..) + | Term::Clause(cell, ..) + | Term::PartialString(cell, ..) + | Term::CompleteString(cell, ..) => { self.marker .mark_non_var::(Level::Deep, term_loc, cell, target); target.push_back(Target::clause_arg_to_instr(cell.get())); } - Term::Literal(_, ref constant) => { + Term::Literal(_, constant) => { target.push_back(Target::constant_subterm(*constant)); } - Term::Var(ref cell, ref var_ptr) => { + Term::Var(cell, var_ptr) => { self.deep_var_instr::( cell, var_ptr.to_var_num().unwrap(), @@ -572,7 +572,7 @@ impl CodeGenerator { Term::Literal(_, Literal::Atom(..)) => { instr!("$succeed") } - Term::Var(ref vr, ref name) => { + Term::Var(vr, name) => { self.marker.reset_arg(1); let r = self.marker.mark_non_callable( @@ -600,7 +600,7 @@ impl CodeGenerator { Term::Literal(..) => { instr!("$succeed") } - Term::Var(ref vr, ref name) => { + Term::Var(vr, name) => { self.marker.reset_arg(1); let r = self.marker.mark_non_callable( @@ -621,7 +621,7 @@ impl CodeGenerator { | Term::CompleteString(..) => { instr!("$succeed") } - Term::Var(ref vr, ref name) => { + Term::Var(vr, name) => { self.marker.reset_arg(1); let r = self.marker.mark_non_callable( @@ -733,7 +733,7 @@ impl CodeGenerator { Term::Literal(_, Literal::Integer(_)) | Term::Literal(_, Literal::Fixnum(_)) => { instr!("$succeed") } - Term::Var(ref vr, name) => { + Term::Var(vr, name) => { self.marker.reset_arg(1); let r = self.marker.mark_non_callable( @@ -828,7 +828,7 @@ impl CodeGenerator { self.marker .mark_anon_var::(Level::Shallow, term_loc, code); - if let Term::Var(ref vr, ref var) = &terms[1] { + if let Term::Var(vr, var) = &terms[1] { let var_num = var.to_var_num().unwrap(); // if var is an anonymous variable, insert diff --git a/src/debray_allocator.rs b/src/debray_allocator.rs index d6cd50bd..39d37820 100644 --- a/src/debray_allocator.rs +++ b/src/debray_allocator.rs @@ -158,7 +158,7 @@ impl DebrayAllocator { for var_num in subsumed_hits { match &mut self.var_data.records[var_num].allocation { - VarAlloc::Perm(_, ref mut allocation) => { + VarAlloc::Perm(_, allocation) => { if let PermVarAllocation::Done { shallow_safety, deep_safety, @@ -551,7 +551,7 @@ impl DebrayAllocator { } else if let Some(&temp_var_num) = self.shallow_temp_mappings.get(&self.arg_c) { match &mut self.var_data.records[temp_var_num].allocation { VarAlloc::Temp { - ref mut to_perm_var_num, + to_perm_var_num, .. } => { *to_perm_var_num = Some(var_num); @@ -560,7 +560,7 @@ impl DebrayAllocator { } } } - VarAlloc::Temp { ref mut safety, .. } => { + VarAlloc::Temp { safety, .. } => { *safety = VarSafetyStatus::GloballyUnneeded; } _ => { @@ -581,7 +581,7 @@ impl DebrayAllocator { VarAlloc::Perm( _, PermVarAllocation::Done { - ref mut shallow_safety, + shallow_safety, .. }, ) => { @@ -617,7 +617,7 @@ impl DebrayAllocator { VarAlloc::Perm( _, PermVarAllocation::Done { - ref mut deep_safety, + deep_safety, .. }, ) => { @@ -631,7 +631,7 @@ impl DebrayAllocator { Target::unsafe_subterm_to_value(r) } } - VarAlloc::Temp { ref mut safety, .. } => { + VarAlloc::Temp { safety, .. } => { if self .branch_stack .safety_unneeded_in_branch(safety, &branch_designator) @@ -874,7 +874,7 @@ impl Allocator for DebrayAllocator { self.arity = args.len(); for (idx, arg) in args.iter().enumerate() { - if let Term::Var(_, ref var) = arg { + if let Term::Var(_, var) = arg { let var_num = var.to_var_num().unwrap(); let r = self.get_binding(var_num); diff --git a/src/ffi.rs b/src/ffi.rs index e7957dec..3a4f9dde 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -53,27 +53,27 @@ pub struct FunctionImpl { } impl FunctionImpl { - unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { + unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { unsafe { self.cif.call_return_into(self.code_ptr, args, Ret::void()); Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) - } + }} unsafe fn call_int(&self, args: &[Arg], arena: &mut Arena) -> Result where Integer: From, T: Copy + TryInto + MightNotFitInFixnum, - { + { unsafe { let n = self.cif.call::(self.code_ptr, args); Ok(Value::Number(fixnum!(Number, n, arena))) - } + }} unsafe fn call_float(&self, args: &[Arg], _: &mut Arena) -> Result where T: Into, - { + { unsafe { let n = self.cif.call::(self.code_ptr, args); Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - } + }} unsafe fn call_ptr(&self, args: &[Arg], arena: &mut Arena) -> Result { let ptr = unsafe { self.cif.call::<*mut c_void>(self.code_ptr, args) }; @@ -197,14 +197,14 @@ impl StructImpl { ptr: NonNull, layout: &mut Layout, val: T, - ) -> Result<(), FfiError> { + ) -> Result<(), FfiError> { unsafe { let (new_layout, offset) = layout .extend(Layout::new::()) .map_err(|_| FfiError::LayoutError)?; *layout = new_layout; ptr.byte_offset(offset as isize).cast::().write(val); Ok(()) - } + }} for arg in args { unsafe { @@ -258,14 +258,14 @@ impl StructImpl { unsafe fn read_primitive( ptr: *mut c_void, layout: &mut Layout, - ) -> Result { + ) -> Result { unsafe { let (new_layout, offset) = layout .extend(Layout::new::()) .map_err(|_| FfiError::LayoutError)?; *layout = new_layout; let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); Ok(n) - } + }} unsafe fn read_int( ptr: *mut c_void, @@ -275,10 +275,10 @@ impl StructImpl { where T: Copy + TryInto + MightNotFitInFixnum, Integer: From, - { + { unsafe { let n = read_primitive::(ptr, layout)?; Ok(Value::Number(fixnum!(Number, n, arena))) - } + }} unsafe fn read_float( ptr: *mut c_void, @@ -286,10 +286,10 @@ impl StructImpl { ) -> Result where T: Into, - { + { unsafe { let n = read_primitive::(ptr, layout)?; Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - } + }} let mut layout = Layout::from_size_align(0, 1).map_err(|_| FfiError::LayoutError)?; @@ -788,10 +788,10 @@ impl ForeignFunctionTable { where T: Copy + TryInto + MightNotFitInFixnum, Integer: From, - { + { unsafe { let n = ptr.cast::().read(); Value::Number(fixnum!(Number, n, arena)) - } + }} let ptr = ptr.as_ptr()?; @@ -924,7 +924,7 @@ impl Value { fn as_ptr(&mut self) -> Result<*mut c_void, FfiError> { match self { - Value::CString(ref mut cstr) => Ok(cstr.as_ptr().cast_mut().cast()), + Value::CString(cstr) => Ok(cstr.as_ptr().cast_mut().cast()), Value::Number(Number::Fixnum(fixnum)) => Ok(std::ptr::with_exposed_provenance_mut( fixnum.get_num() as usize, )), diff --git a/src/forms.rs b/src/forms.rs index 9f9d00a3..9269c60b 100644 --- a/src/forms.rs +++ b/src/forms.rs @@ -389,15 +389,15 @@ impl ClauseInfo for Rule { impl ClauseInfo for PredicateClause { fn name(&self) -> Option { match self { - PredicateClause::Fact(ref term, ..) => term.head.name(), - PredicateClause::Rule(ref rule, ..) => rule.name(), + PredicateClause::Fact(term, ..) => term.head.name(), + PredicateClause::Rule(rule, ..) => rule.name(), } } fn arity(&self) -> usize { match self { - PredicateClause::Fact(ref term, ..) => term.head.arity(), - PredicateClause::Rule(ref rule, ..) => rule.arity(), + PredicateClause::Fact(term, ..) => term.head.arity(), + PredicateClause::Rule(rule, ..) => rule.arity(), } } } @@ -582,7 +582,7 @@ pub(crate) fn fetch_op_spec_from_existing( op_desc: Option, op_dir: &OpDir, ) -> Option { - if let Some(ref op_desc) = &op_desc { + if let Some(op_desc) = &op_desc { if op_desc.arity() != arity { /* it's possible to extend operator functors with * additional terms. When that happens, @@ -843,9 +843,9 @@ impl Number { pub(crate) fn is_positive(&self) -> bool { match self { Number::Fixnum(n) => n.get_num() > 0, - Number::Integer(ref n) => n.is_positive(), + Number::Integer(n) => n.is_positive(), Number::Float(f) => f.is_sign_positive(), - Number::Rational(ref r) => r.is_positive(), + Number::Rational(r) => r.is_positive(), } } @@ -853,9 +853,9 @@ impl Number { pub(crate) fn is_negative(&self) -> bool { match self { Number::Fixnum(n) => n.get_num() < 0, - Number::Integer(ref n) => n.is_negative(), + Number::Integer(n) => n.is_negative(), &Number::Float(OrderedFloat(f)) => f.is_sign_negative() && f != -0f64, - Number::Rational(ref r) => r.is_negative(), + Number::Rational(r) => r.is_negative(), } } @@ -863,9 +863,9 @@ impl Number { pub(crate) fn is_zero(&self) -> bool { match self { Number::Fixnum(n) => n.get_num() == 0, - Number::Integer(ref n) => n.is_zero(), + Number::Integer(n) => n.is_zero(), &Number::Float(OrderedFloat(f)) => f == 0.0 || f == -0.0, - Number::Rational(ref r) => r.is_zero(), + Number::Rational(r) => r.is_zero(), } } @@ -920,9 +920,9 @@ impl OptArgIndexKey { #[inline] pub(crate) fn set_switch_on_term_loc(&mut self, value: usize) { match self { - OptArgIndexKey::Literal(_, ref mut loc, ..) - | OptArgIndexKey::Structure(_, ref mut loc, ..) - | OptArgIndexKey::List(_, ref mut loc) => { + OptArgIndexKey::Literal(_, loc, ..) + | OptArgIndexKey::Structure(_, loc, ..) + | OptArgIndexKey::List(_, loc) => { *loc = value; } OptArgIndexKey::None => {} @@ -934,9 +934,9 @@ impl AddAssign for OptArgIndexKey { #[inline] fn add_assign(&mut self, n: usize) { match self { - OptArgIndexKey::Literal(_, ref mut o, ..) - | OptArgIndexKey::List(_, ref mut o) - | OptArgIndexKey::Structure(_, ref mut o, ..) => { + OptArgIndexKey::Literal(_, o, ..) + | OptArgIndexKey::List(_, o) + | OptArgIndexKey::Structure(_, o, ..) => { *o += n; } OptArgIndexKey::None => {} diff --git a/src/heap_print.rs b/src/heap_print.rs index 3f5b2564..fcc0cc0c 100644 --- a/src/heap_print.rs +++ b/src/heap_print.rs @@ -387,7 +387,7 @@ fn negated_op_needs_bracketing( op_dir: &OpDir, op: &Option, ) -> bool { - if let Some(ref op) = op { + if let Some(op) = op { op.is_negative_sign() && iter.leftmost_leaf_has_property(op_dir, |addr| { match Number::try_from((addr, f64_tbl)) { @@ -1452,7 +1452,7 @@ impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> { }); for op in &[op, parent_op] { - if let Some(ref op) = &op { + if let Some(op) = &op { if op.is_left() && (op.is_prefix() || requires_space(&op.as_atom().as_str(), "(")) { diff --git a/src/indexing.rs b/src/indexing.rs index a1105fdf..2b5b9767 100644 --- a/src/indexing.rs +++ b/src/indexing.rs @@ -167,7 +167,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { .push(IndexingLine::IndexedChoice(third_level_index)); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref mut constants)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => { constants.insert( constant, IndexingCodePtr::Internal(indexing_code_len - self.offset), @@ -196,7 +196,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { .push(IndexingLine::DynamicIndexedChoice(third_level_index)); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref mut constants)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => { constants.insert( constant, IndexingCodePtr::Internal(indexing_code_len - self.offset), @@ -210,22 +210,22 @@ impl<'a> IndexingCodeMergingPtr<'a> { fn extend_indexed_choice(&mut self, index: usize) { match &mut self.indexing_code[self.offset] { - IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) + IndexingLine::IndexedChoice(indexed_choice_instrs) if self.append_or_prepend.is_append() => { uncap_choice_seq_with_trust(indexed_choice_instrs.make_contiguous()); indexed_choice_instrs.push_back(IndexedChoiceInstruction::Trust(index)); } - IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::IndexedChoice(indexed_choice_instrs) => { uncap_choice_seq_with_try(indexed_choice_instrs.make_contiguous()); indexed_choice_instrs.push_front(IndexedChoiceInstruction::Try(index)); } - IndexingLine::DynamicIndexedChoice(ref mut indexed_choice_instrs) + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) if self.append_or_prepend.is_append() => { indexed_choice_instrs.push_back(index); } - IndexingLine::DynamicIndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { indexed_choice_instrs.push_front(index); } _ => { @@ -244,7 +244,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => { match *c { IndexingCodePtr::Fail if self.is_dynamic => { *c = IndexingCodePtr::DynamicExternal(index); @@ -322,7 +322,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => { match *c { IndexingCodePtr::Fail if self.is_dynamic => { *c = IndexingCodePtr::DynamicExternal(index); @@ -445,7 +445,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { .push(IndexingLine::IndexedChoice(third_level_index)); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(structures)) => { structures.insert( key, IndexingCodePtr::Internal(indexing_code_len - self.offset), @@ -474,7 +474,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { .push(IndexingLine::DynamicIndexedChoice(third_level_index)); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(structures)) => { structures.insert( key, IndexingCodePtr::Internal(indexing_code_len - self.offset), @@ -496,7 +496,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { _, _, _, - ref mut s, + s, )) => match *s { IndexingCodePtr::Fail if self.is_dynamic => { *s = IndexingCodePtr::DynamicExternal(index); @@ -559,7 +559,7 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => { match *l { IndexingCodePtr::Fail if self.is_dynamic => { *l = IndexingCodePtr::DynamicExternal(index); @@ -632,7 +632,7 @@ pub(crate) fn merge_clause_index( ); match &opt_arg_index_key { - OptArgIndexKey::Literal(_, index_loc, constant, ref overlapping_constants) => { + OptArgIndexKey::Literal(_, index_loc, constant, overlapping_constants) => { let offset = new_clause_loc - index_loc + 1; merging_ptr.index_constant(HeapCellValue::from(*constant), offset); @@ -676,7 +676,7 @@ pub(crate) fn remove_constant_indices( let iter = once(&constant).chain(overlapping_constants.iter()); match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => { match *c { IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { *c = IndexingCodePtr::Fail; @@ -701,7 +701,7 @@ pub(crate) fn remove_constant_indices( loop { match &mut indexing_code[index] { IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( - ref mut constants, + constants, )) => { constants_index = index; @@ -720,7 +720,7 @@ pub(crate) fn remove_constant_indices( } } } - IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::IndexedChoice(indexed_choice_instrs) => { StaticCodeIndices::remove_instruction_with_offset( indexed_choice_instrs, offset, @@ -734,13 +734,13 @@ pub(crate) fn remove_constant_indices( IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( _, _, - ref mut c, + c, .., )) => { *c = ext; } IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( - ref mut constants, + constants, )) => { constants.insert(constant, ext); } @@ -753,7 +753,7 @@ pub(crate) fn remove_constant_indices( break; } - IndexingLine::DynamicIndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { DynamicCodeIndices::remove_instruction_with_offset( indexed_choice_instrs, offset, @@ -767,13 +767,13 @@ pub(crate) fn remove_constant_indices( IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( _, _, - ref mut c, + c, .., )) => { *c = ext; } IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( - ref mut constants, + constants, )) => { constants.insert(constant, ext); } @@ -794,11 +794,11 @@ pub(crate) fn remove_constant_indices( } match &indexing_code[constants_index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref constants)) + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) if constants.is_empty() => { match &mut indexing_code[0] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, ref mut c, ..)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => { *c = IndexingCodePtr::Fail; } _ => { @@ -819,7 +819,7 @@ pub(crate) fn remove_structure_index( let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, ref mut s)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { match *s { IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { *s = IndexingCodePtr::Fail; @@ -842,7 +842,7 @@ pub(crate) fn remove_structure_index( loop { match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(structures)) => { structures_index = index; match structures.get(&(name, arity)).cloned() { @@ -859,7 +859,7 @@ pub(crate) fn remove_structure_index( } } } - IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::IndexedChoice(indexed_choice_instrs) => { StaticCodeIndices::remove_instruction_with_offset(indexed_choice_instrs, offset); if indexed_choice_instrs.len() == 1 { @@ -872,12 +872,12 @@ pub(crate) fn remove_structure_index( _, _, _, - ref mut s, + s, )) => { *s = ext; } IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure( - ref mut structures, + structures, )) => { structures.insert((name, arity), ext); } @@ -890,7 +890,7 @@ pub(crate) fn remove_structure_index( break; } - IndexingLine::DynamicIndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { DynamicCodeIndices::remove_instruction_with_offset(indexed_choice_instrs, offset); if indexed_choice_instrs.len() == 1 { @@ -903,12 +903,12 @@ pub(crate) fn remove_structure_index( _, _, _, - ref mut s, + s, )) => { *s = ext; } IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure( - ref mut structures, + structures, )) => { structures.insert((name, arity), ext); } @@ -928,7 +928,7 @@ pub(crate) fn remove_structure_index( } match &indexing_code[structures_index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref structures)) + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(structures)) if structures.is_empty() => { match &mut indexing_code[0] { @@ -937,7 +937,7 @@ pub(crate) fn remove_structure_index( _, _, _, - ref mut s, + s, )) => { *s = IndexingCodePtr::Fail; } @@ -954,7 +954,7 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, ref mut l, _)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => { match *l { IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { *l = IndexingCodePtr::Fail; @@ -974,7 +974,7 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz } match &mut indexing_code[index] { - IndexingLine::IndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::IndexedChoice(indexed_choice_instrs) => { StaticCodeIndices::remove_instruction_with_offset(indexed_choice_instrs, offset); if indexed_choice_instrs.len() == 1 { @@ -986,7 +986,7 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz _, _, _, - ref mut l, + l, _, )) => { *l = ext; @@ -998,7 +998,7 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz } } } - IndexingLine::DynamicIndexedChoice(ref mut indexed_choice_instrs) => { + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { DynamicCodeIndices::remove_instruction_with_offset(indexed_choice_instrs, offset); if indexed_choice_instrs.len() == 1 { @@ -1010,7 +1010,7 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz _, _, _, - ref mut l, + l, _, )) => { *l = ext; @@ -1034,7 +1034,7 @@ pub(crate) fn remove_index( clause_loc: usize, ) { match opt_arg_index_key { - OptArgIndexKey::Literal(_, _, constant, ref overlapping_constants) => { + OptArgIndexKey::Literal(_, _, constant, overlapping_constants) => { remove_constant_indices(*constant, *overlapping_constants, indexing_code, clause_loc); } OptArgIndexKey::Structure(_, _, name, arity) => { @@ -1525,11 +1525,11 @@ impl CodeOffsets { &mut prelude, ); - if let IndexingCodePtr::Internal(ref mut i) = &mut str_loc { + if let IndexingCodePtr::Internal(i) = &mut str_loc { *i += emitted_switch_on_constant as usize; // con_loc.is_internal() as usize; } - if let IndexingCodePtr::Internal(ref mut i) = &mut lst_loc { + if let IndexingCodePtr::Internal(i) = &mut lst_loc { *i += emitted_switch_on_constant as usize; // con_loc.is_internal() as usize; *i += emitted_switch_on_structure as usize; // str_loc.is_internal() as usize; } diff --git a/src/instructions.rs b/src/instructions.rs index 2fc94c63..e6d9b97f 100644 --- a/src/instructions.rs +++ b/src/instructions.rs @@ -251,7 +251,7 @@ impl Instruction { #[inline] pub fn to_indexing_line_mut(&mut self) -> Option<&mut Vec> { match self { - Instruction::IndexingCode(ref mut indexing_code) => Some(indexing_code), + Instruction::IndexingCode(indexing_code) => Some(indexing_code), _ => None, } } @@ -259,7 +259,7 @@ impl Instruction { #[inline] pub fn to_indexing_line(&self) -> Option<&Vec> { match self { - Instruction::IndexingCode(ref indexing_code) => Some(indexing_code), + Instruction::IndexingCode(indexing_code) => Some(indexing_code), _ => None, } } @@ -1372,12 +1372,12 @@ impl Instruction { impl CompareNumber { pub fn set_terms(&mut self, l_at_1: ArithmeticTerm, l_at_2: ArithmeticTerm) { match self { - CompareNumber::NumberGreaterThan(ref mut at_1, ref mut at_2) - | CompareNumber::NumberLessThan(ref mut at_1, ref mut at_2) - | CompareNumber::NumberGreaterThanOrEqual(ref mut at_1, ref mut at_2) - | CompareNumber::NumberLessThanOrEqual(ref mut at_1, ref mut at_2) - | CompareNumber::NumberNotEqual(ref mut at_1, ref mut at_2) - | CompareNumber::NumberEqual(ref mut at_1, ref mut at_2) => { + CompareNumber::NumberGreaterThan(at_1, at_2) + | CompareNumber::NumberLessThan(at_1, at_2) + | CompareNumber::NumberGreaterThanOrEqual(at_1, at_2) + | CompareNumber::NumberLessThanOrEqual(at_1, at_2) + | CompareNumber::NumberNotEqual(at_1, at_2) + | CompareNumber::NumberEqual(at_1, at_2) => { *at_1 = l_at_1; *at_2 = l_at_2; } diff --git a/src/iterators.rs b/src/iterators.rs index d457740a..eadeb093 100644 --- a/src/iterators.rs +++ b/src/iterators.rs @@ -103,11 +103,11 @@ impl<'a> QueryIterator<'a> { fn extend_state(&mut self, lvl: Level, term: &'a QueryTerm) { match term { - QueryTerm::Clause(ref cell, ClauseType::CallN(_), ref terms, _) => { + QueryTerm::Clause(cell, ClauseType::CallN(_), terms, _) => { self.state_stack .push(TermIterState::Clause(lvl, 1, cell, atom!("$call"), terms)); } - QueryTerm::Clause(ref cell, ref ct, ref terms, _) => { + QueryTerm::Clause(cell, ct, terms, _) => { self.state_stack .push(TermIterState::Clause(lvl, 0, cell, ct.name(), terms)); } @@ -419,7 +419,7 @@ impl<'a> Iterator for ClauseIterator<'a> { self.state_stack .push(ClauseIteratorState::RemainingBranches(branch_nums, arms, 0)); } - ChunkedTerms::Chunk { ref terms } => { + ChunkedTerms::Chunk { terms } => { return Some(ClauseItem::Chunk { terms }); } } diff --git a/src/machine/attributed_variables.rs b/src/machine/attributed_variables.rs index 6b822b95..b4ea4954 100644 --- a/src/machine/attributed_variables.rs +++ b/src/machine/attributed_variables.rs @@ -62,7 +62,7 @@ impl MachineState { .attr_var_init .bindings .iter() - .map(|(ref h, _)| attr_var_as_cell!(*h)); + .map(|(h, _)| attr_var_as_cell!(*h)); let var_list_addr = sized_iter_to_heap_list(&mut self.heap, size, iter)?; let iter = self.attr_var_init.bindings.drain(0..).map(|(_, ref v)| *v); diff --git a/src/machine/compile.rs b/src/machine/compile.rs index 61243bc6..c4789328 100644 --- a/src/machine/compile.rs +++ b/src/machine/compile.rs @@ -80,19 +80,19 @@ fn derelictize_try_me_else( ) -> Option { match &mut code[index] { Instruction::DynamicElse(_, _, NextOrFail::Next(0)) => None, - Instruction::DynamicElse(_, _, NextOrFail::Next(ref mut o)) => { + Instruction::DynamicElse(_, _, NextOrFail::Next(o)) => { retraction_info.push_record(RetractionRecord::ReplacedDynamicElseOffset(index, *o)); Some(mem::replace(o, 0)) } Instruction::DynamicInternalElse(_, _, NextOrFail::Next(0)) => None, - Instruction::DynamicInternalElse(_, _, NextOrFail::Next(ref mut o)) => { + Instruction::DynamicInternalElse(_, _, NextOrFail::Next(o)) => { retraction_info.push_record(RetractionRecord::ReplacedDynamicElseOffset(index, *o)); Some(mem::replace(o, 0)) } Instruction::DynamicElse(_, _, NextOrFail::Fail(_)) | Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(_)) => None, Instruction::TryMeElse(0) => None, - Instruction::TryMeElse(ref mut o) => { + Instruction::TryMeElse(o) => { retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(index, *o)); Some(mem::replace(o, 0)) } @@ -275,7 +275,7 @@ fn merge_indexed_subsequences( .unwrap(), ); - if let Instruction::TryMeElse(ref mut o) = &mut code[inner_try_me_else_loc] { + if let Instruction::TryMeElse(o) = &mut code[inner_try_me_else_loc] { retraction_info.push_record(RetractionRecord::ModifiedTryMeElse( inner_try_me_else_loc, *o, @@ -324,7 +324,7 @@ fn merge_indexed_subsequences( ); } None => { - if let Instruction::TryMeElse(ref mut o) = &mut code[outer_threaded_choice_instr_loc] { + if let Instruction::TryMeElse(o) = &mut code[outer_threaded_choice_instr_loc] { retraction_info .push_record(RetractionRecord::ModifiedTryMeElse(inner_trust_me_loc, *o)); @@ -472,7 +472,7 @@ fn set_switch_var_offset( let target_indexing_line = code[index_loc].to_indexing_line_mut().unwrap(); let old_v = match &mut target_indexing_line[0] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, ref mut v, ..)) => match *v { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, ..)) => match *v { IndexingCodePtr::DynamicExternal(_) => { mem::replace(v, IndexingCodePtr::DynamicExternal(offset)) } @@ -497,7 +497,7 @@ fn internalize_choice_instr_at( match &mut code[instr_loc] { Instruction::DynamicElse(_, _, NextOrFail::Fail(_)) | Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(_)) => {} - Instruction::DynamicElse(_, _, ref mut o @ NextOrFail::Next(0)) => { + Instruction::DynamicElse(_, _, o @ NextOrFail::Next(0)) => { retraction_info.push_record(RetractionRecord::ReplacedDynamicElseOffset(instr_loc, 0)); *o = NextOrFail::Fail(0); } @@ -516,7 +516,7 @@ fn internalize_choice_instr_at( } } } - Instruction::DynamicInternalElse(_, _, ref mut o @ NextOrFail::Next(0)) => { + Instruction::DynamicInternalElse(_, _, o @ NextOrFail::Next(0)) => { retraction_info.push_record(RetractionRecord::ReplacedDynamicElseOffset(instr_loc, 0)); *o = NextOrFail::Fail(0); } @@ -564,7 +564,7 @@ fn thread_choice_instr_at_to( ) { loop { match &mut code[instr_loc] { - Instruction::TryMeElse(ref mut o) | Instruction::RetryMeElse(ref mut o) + Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) if target_loc >= instr_loc => { retraction_info.push_record(RetractionRecord::ReplacedChoiceOffset(instr_loc, *o)); @@ -572,8 +572,8 @@ fn thread_choice_instr_at_to( *o = target_loc - instr_loc; return; } - Instruction::DynamicElse(_, _, NextOrFail::Next(ref mut o)) - | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(ref mut o)) + Instruction::DynamicElse(_, _, NextOrFail::Next(o)) + | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(o)) if target_loc >= instr_loc => { retraction_info @@ -588,7 +588,7 @@ fn thread_choice_instr_at_to( Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) => { instr_loc += *o; } - Instruction::RevJmpBy(ref mut o) if instr_loc >= target_loc => { + Instruction::RevJmpBy(o) if instr_loc >= target_loc => { retraction_info.push_record(RetractionRecord::ModifiedRevJmpBy(instr_loc, *o)); *o = instr_loc - target_loc; @@ -631,7 +631,7 @@ fn thread_choice_instr_at_to( Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(o)) if *o > 0 => { instr_loc += *o; } - Instruction::TrustMe(ref mut o) if target_loc >= instr_loc => { + Instruction::TrustMe(o) if target_loc >= instr_loc => { retraction_info.push_record( RetractionRecord::AppendedTrustMe(instr_loc, *o, false), //choice_instr.is_default()), @@ -657,7 +657,7 @@ fn remove_non_leading_clause( retraction_info: &mut RetractionInfo, ) -> Option { match &mut code[non_indexed_choice_instr_loc] { - Instruction::RetryMeElse(ref mut o) => { + Instruction::RetryMeElse(o) => { let o = *o; thread_choice_instr_at_to( @@ -680,7 +680,7 @@ fn remove_non_leading_clause( None } - Instruction::TryMeElse(ref mut o) => { + Instruction::TryMeElse(o) => { retraction_info.push_record(RetractionRecord::ModifiedTryMeElse( preceding_choice_instr_loc, *o, @@ -730,7 +730,7 @@ fn remove_leading_unindexed_clause( retraction_info: &mut RetractionInfo, ) -> Option { match &mut code[non_indexed_choice_instr_loc] { - Instruction::TryMeElse(ref mut o) => { + Instruction::TryMeElse(o) => { if *o > 0 { retraction_info.push_record(RetractionRecord::ModifiedTryMeElse( non_indexed_choice_instr_loc, @@ -935,10 +935,10 @@ fn prepend_compiled_clause( let prepend_queue_len = prepend_queue.len(); match &mut prepend_queue[1] { - Instruction::TryMeElse(ref mut o) if *o == 0 => { + Instruction::TryMeElse(o) if *o == 0 => { *o = prepend_queue_len - 2; } - Instruction::DynamicInternalElse(_, _, ref mut o @ NextOrFail::Next(0)) => { + Instruction::DynamicInternalElse(_, _, o @ NextOrFail::Next(0)) => { *o = NextOrFail::Fail(prepend_queue_len - 2); } _ => { @@ -1632,8 +1632,8 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { }; match &mut self.wam_prelude.code[clause_loc] { - Instruction::DynamicElse(_, ref mut d, _) - | Instruction::DynamicInternalElse(_, ref mut d, _) => { + Instruction::DynamicElse(_, d, _) + | Instruction::DynamicInternalElse(_, d, _) => { *d = Death::Finite(LS::machine_st(&mut self.payload).global_clock); } _ => unreachable!(), diff --git a/src/machine/dispatch.rs b/src/machine/dispatch.rs index e356bc38..f0184122 100644 --- a/src/machine/dispatch.rs +++ b/src/machine/dispatch.rs @@ -1365,8 +1365,8 @@ impl Machine { let p = self.machine_st.p; let indexed_choice_instrs = match &self.code[p] { - Instruction::IndexingCode(ref indexing_code) => match &indexing_code[oi as usize] { - IndexingLine::DynamicIndexedChoice(ref indexed_choice_instrs) => { + Instruction::IndexingCode(indexing_code) => match &indexing_code[oi as usize] { + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { indexed_choice_instrs } _ => unreachable!(), @@ -1376,7 +1376,7 @@ impl Machine { loop { match &indexed_choice_instrs.get(ii as usize) { - Some(&offset) => match &self.code[p + offset - 1] { + &Some(&offset) => match &self.code[p + offset - 1] { &Instruction::DynamicInternalElse(birth, death, next_or_fail) => { if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death { @@ -2670,7 +2670,7 @@ impl Machine { self.machine_st.backtrack(); } } - Instruction::CallNumberLessThanOrEqual(ref at_1, ref at_2) => { + Instruction::CallNumberLessThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2692,7 +2692,7 @@ impl Machine { } } } - Instruction::ExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => { + Instruction::ExecuteNumberLessThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2714,7 +2714,7 @@ impl Machine { } } } - Instruction::CallNumberEqual(ref at_1, ref at_2) => { + Instruction::CallNumberEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2736,7 +2736,7 @@ impl Machine { } } } - Instruction::ExecuteNumberEqual(ref at_1, ref at_2) => { + Instruction::ExecuteNumberEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2758,7 +2758,7 @@ impl Machine { } } } - Instruction::CallNumberNotEqual(ref at_1, ref at_2) => { + Instruction::CallNumberNotEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2780,7 +2780,7 @@ impl Machine { } } } - Instruction::ExecuteNumberNotEqual(ref at_1, ref at_2) => { + Instruction::ExecuteNumberNotEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2802,7 +2802,7 @@ impl Machine { } } } - Instruction::CallNumberGreaterThanOrEqual(ref at_1, ref at_2) => { + Instruction::CallNumberGreaterThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2824,7 +2824,7 @@ impl Machine { } } } - Instruction::ExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => { + Instruction::ExecuteNumberGreaterThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2846,7 +2846,7 @@ impl Machine { } } } - Instruction::CallNumberGreaterThan(ref at_1, ref at_2) => { + Instruction::CallNumberGreaterThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2868,7 +2868,7 @@ impl Machine { } } } - Instruction::ExecuteNumberGreaterThan(ref at_1, ref at_2) => { + Instruction::ExecuteNumberGreaterThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2890,7 +2890,7 @@ impl Machine { } } } - Instruction::CallNumberLessThan(ref at_1, ref at_2) => { + Instruction::CallNumberLessThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2912,7 +2912,7 @@ impl Machine { } } } - Instruction::ExecuteNumberLessThan(ref at_1, ref at_2) => { + Instruction::ExecuteNumberLessThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2934,7 +2934,7 @@ impl Machine { } } } - Instruction::DefaultCallNumberLessThanOrEqual(ref at_1, ref at_2) => { + Instruction::DefaultCallNumberLessThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2955,7 +2955,7 @@ impl Machine { } } } - Instruction::DefaultExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => { + Instruction::DefaultExecuteNumberLessThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2976,7 +2976,7 @@ impl Machine { } } } - Instruction::DefaultCallNumberNotEqual(ref at_1, ref at_2) => { + Instruction::DefaultCallNumberNotEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -2997,7 +2997,7 @@ impl Machine { } } } - Instruction::DefaultExecuteNumberNotEqual(ref at_1, ref at_2) => { + Instruction::DefaultExecuteNumberNotEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3018,7 +3018,7 @@ impl Machine { } } } - Instruction::DefaultCallNumberEqual(ref at_1, ref at_2) => { + Instruction::DefaultCallNumberEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3039,7 +3039,7 @@ impl Machine { } } } - Instruction::DefaultExecuteNumberEqual(ref at_1, ref at_2) => { + Instruction::DefaultExecuteNumberEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3060,7 +3060,7 @@ impl Machine { } } } - Instruction::DefaultCallNumberGreaterThanOrEqual(ref at_1, ref at_2) => { + Instruction::DefaultCallNumberGreaterThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3081,7 +3081,7 @@ impl Machine { } } } - Instruction::DefaultExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => { + Instruction::DefaultExecuteNumberGreaterThanOrEqual(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3102,7 +3102,7 @@ impl Machine { } } } - Instruction::DefaultCallNumberGreaterThan(ref at_1, ref at_2) => { + Instruction::DefaultCallNumberGreaterThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3123,7 +3123,7 @@ impl Machine { } } } - Instruction::DefaultExecuteNumberGreaterThan(ref at_1, ref at_2) => { + Instruction::DefaultExecuteNumberGreaterThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3144,7 +3144,7 @@ impl Machine { } } } - Instruction::DefaultCallNumberLessThan(ref at_1, ref at_2) => { + Instruction::DefaultCallNumberLessThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3165,7 +3165,7 @@ impl Machine { } } } - Instruction::DefaultExecuteNumberLessThan(ref at_1, ref at_2) => { + Instruction::DefaultExecuteNumberLessThan(at_1, at_2) => { let n1 = try_or_throw!( self.machine_st, self.machine_st.get_number(at_1), @@ -3640,7 +3640,7 @@ impl Machine { &Instruction::Proceed => { self.machine_st.p = self.machine_st.cp; } - Instruction::IndexingCode(ref indexing_lines) => { + Instruction::IndexingCode(indexing_lines) => { match &indexing_lines[self.machine_st.oip as usize] { IndexingLine::Indexing(_) => { self.execute_switch_on_term(); @@ -3649,7 +3649,7 @@ impl Machine { self.machine_st.backtrack(); } } - IndexingLine::IndexedChoice(ref indexed_choice) => { + IndexingLine::IndexedChoice(indexed_choice) => { match indexed_choice[self.machine_st.iip as usize] { IndexedChoiceInstruction::Try(offset) => { backtrack_on_resource_error!( diff --git a/src/machine/heap.rs b/src/machine/heap.rs index 7902b9e2..37a30315 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -57,7 +57,7 @@ struct InnerHeap { } impl InnerHeap { - unsafe fn grow(&mut self) -> bool { + unsafe fn grow(&mut self) -> bool { unsafe { let new_cap = if self.byte_cap == 0 { 256 * 256 * 8 } else { @@ -88,7 +88,7 @@ impl InnerHeap { } else { false } - } + }} } unsafe impl Send for Heap {} @@ -101,7 +101,7 @@ pub struct HeapStringScan<'a> { } // The heap_slice should be inside the heap -unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { +unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { unsafe { let string_len = heap_slice .iter() .position(|b| *b == 0u8) @@ -120,11 +120,11 @@ unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { string: std::str::from_utf8_unchecked(str_slice), tail_idx, } -} +}} // Same as scan_slice_to_str but assumes that the slice is from the start of a string. // Can be used on strings out of the heap. -unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { +unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { unsafe { let string_len = heap_slice .iter() .position(|b| *b == 0u8) @@ -142,7 +142,7 @@ unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> string: std::str::from_utf8_unchecked(str_slice), tail_idx, } -} +}} #[derive(Debug, Clone, Copy)] pub(crate) enum PStrContinuable { @@ -585,9 +585,9 @@ impl Heap { } #[inline(always)] - unsafe fn grow(&mut self) -> bool { + unsafe fn grow(&mut self) -> bool { unsafe { self.inner.grow() - } + }} #[inline] fn resource_error_offset(&self) -> usize { diff --git a/src/machine/load_state.rs b/src/machine/load_state.rs index 89c50153..7b445dbe 100644 --- a/src/machine/load_state.rs +++ b/src/machine/load_state.rs @@ -34,7 +34,7 @@ pub(super) fn set_code_index<'a, LS: LoadState<'a>>( RetractionRecord::ReplacedUserPredicate(key, replaced) } } - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { if IndexPtrTag::Undefined == code_idx_ptr.tag() { *code_idx_ptr = code_ptr; RetractionRecord::AddedModulePredicate(*module_name, key) @@ -98,7 +98,7 @@ pub(super) fn add_op_decl( CompilationTarget::User => { retraction_info.push_record(RetractionRecord::ReplacedUserOp(*op_decl, op_desc)); } - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { retraction_info.push_record(RetractionRecord::ReplacedModuleOp( *module_name, *op_decl, @@ -110,7 +110,7 @@ pub(super) fn add_op_decl( CompilationTarget::User => { retraction_info.push_record(RetractionRecord::AddedUserOp(*op_decl)); } - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { retraction_info .push_record(RetractionRecord::AddedModuleOp(*module_name, *op_decl)); } @@ -167,7 +167,7 @@ pub(super) fn import_module_exports<'a, LS: LoadState<'a>>( )); } } - ModuleExport::OpDecl(ref op_decl) => { + ModuleExport::OpDecl(op_decl) => { add_op_decl( &mut payload.retraction_info, compilation_target, @@ -221,7 +221,7 @@ fn import_module_exports_into_module<'a, LS: LoadState<'a>>( )); } } - ModuleExport::OpDecl(ref op_decl) => { + ModuleExport::OpDecl(op_decl) => { add_op_decl_as_module_export::(payload, op_dir, wam_op_dir, op_decl); } } @@ -276,7 +276,7 @@ fn import_qualified_module_exports<'a, LS: LoadState<'a>>( )); } } - ModuleExport::OpDecl(ref op_decl) => { + ModuleExport::OpDecl(op_decl) => { add_op_decl( &mut payload.retraction_info, compilation_target, @@ -336,7 +336,7 @@ fn import_qualified_module_exports_into_module<'a, LS: LoadState<'a>>( )); } } - ModuleExport::OpDecl(ref op_decl) => { + ModuleExport::OpDecl(op_decl) => { add_op_decl_as_module_export::(payload, op_dir, wam_op_dir, op_decl); } } @@ -545,7 +545,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { ) { for export in removed_module.module_decl.exports.iter() { match export { - ModuleExport::PredicateKey(ref key) => { + ModuleExport::PredicateKey(key) => { if let (Some(module_code_idx), Some(target_code_idx)) = ( removed_module.code_dir.get(key).cloned(), code_dir.get_mut(key).cloned(), @@ -1050,7 +1050,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { ); for export in &module.module_decl.exports { - if let ModuleExport::OpDecl(ref op_decl) = export { + if let ModuleExport::OpDecl(op_decl) = export { add_op_decl_as_module_export::( &mut self.payload, &mut module.op_dir, @@ -1084,7 +1084,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { &mut self.wam_prelude.indices.meta_predicates, )?; } - CompilationTarget::Module(ref defining_module_name) => { + CompilationTarget::Module(defining_module_name) => { match self .wam_prelude .indices @@ -1137,7 +1137,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { &exports, &mut self.wam_prelude, ), - CompilationTarget::Module(ref defining_module_name) => { + CompilationTarget::Module(defining_module_name) => { match self .wam_prelude .indices diff --git a/src/machine/loader.rs b/src/machine/loader.rs index 1ad46c88..26508756 100644 --- a/src/machine/loader.rs +++ b/src/machine/loader.rs @@ -160,7 +160,7 @@ impl fmt::Display for CompilationTarget { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CompilationTarget::User => write!(f, "user"), - CompilationTarget::Module(ref module_name) => write!(f, "{}", module_name.as_str()), + CompilationTarget::Module(module_name) => write!(f, "{}", module_name.as_str()), } } } @@ -821,7 +821,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { { if let IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( _, - ref mut v, + v, .., )) = &mut indexing_code[0] { @@ -1110,7 +1110,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { } } } - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { match self.wam_prelude.indices.modules.get_mut(module_name) { Some(ref mut module) => match module.extensible_predicates.get_mut(&key) { Some(ref mut skeleton) => { @@ -1364,7 +1364,7 @@ impl<'a> MachinePreludeView<'a> { ) -> CompositeOpDir<'_, '_> { match compilation_target { CompilationTarget::User => CompositeOpDir::new(&self.indices.op_dir, None), - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { match self.indices.modules.get(module_name) { Some(module) => CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir)), None => { @@ -2374,7 +2374,7 @@ impl Machine { MetaSpec::Plus => atom_as_cell!(atom!("-")), MetaSpec::Either => atom_as_cell!(atom!("?")), MetaSpec::Colon => atom_as_cell!(atom!(":")), - MetaSpec::RequiresExpansionWithArgument(ref arg_num) => { + MetaSpec::RequiresExpansionWithArgument(arg_num) => { fixnum_as_cell!(/* FIXME this is not safe */ unsafe { Fixnum::build_with_unchecked(*arg_num as i64) }) diff --git a/src/machine/machine_errors.rs b/src/machine/machine_errors.rs index ec1a280d..c07e18ce 100644 --- a/src/machine/machine_errors.rs +++ b/src/machine/machine_errors.rs @@ -900,7 +900,7 @@ impl CompilationError { CompilationError::InvalidUseModuleDecl => { functor!(atom!("invalid_use_module_declaration")) } - CompilationError::ParserError(ref err) => { + CompilationError::ParserError(err) => { functor!(err.as_atom()) } CompilationError::FiniteMemoryInHeap(_) => { diff --git a/src/machine/machine_indices.rs b/src/machine/machine_indices.rs index bfb8a2f3..e452786b 100644 --- a/src/machine/machine_indices.rs +++ b/src/machine/machine_indices.rs @@ -292,7 +292,7 @@ impl IndexStore { ) -> Option<&mut PredicateSkeleton> { match compilation_target { CompilationTarget::User => self.extensible_predicates.get_mut(key), - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { if let Some(module) = self.modules.get_mut(module_name) { module.extensible_predicates.get_mut(key) } else { @@ -309,7 +309,7 @@ impl IndexStore { ) -> Option<&PredicateSkeleton> { match compilation_target { CompilationTarget::User => self.extensible_predicates.get(key), - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { if let Some(module) = self.modules.get(module_name) { module.extensible_predicates.get(key) } else { @@ -380,7 +380,7 @@ impl IndexStore { ) -> Option { match compilation_target { CompilationTarget::User => self.extensible_predicates.swap_remove(key), - CompilationTarget::Module(ref module_name) => { + CompilationTarget::Module(module_name) => { if let Some(module) = self.modules.get_mut(module_name) { module.extensible_predicates.swap_remove(key) } else { @@ -413,7 +413,7 @@ impl IndexStore { ) -> Option<&Vec> { match compilation_target { CompilationTarget::User => self.meta_predicates.get(&(name, arity)), - CompilationTarget::Module(ref module_name) => match self.modules.get(module_name) { + CompilationTarget::Module(module_name) => match self.modules.get(module_name) { Some(module) => module .meta_predicates .get(&(name, arity)) diff --git a/src/machine/machine_state.rs b/src/machine/machine_state.rs index 0bfb65a7..32b86aeb 100644 --- a/src/machine/machine_state.rs +++ b/src/machine/machine_state.rs @@ -1133,7 +1133,7 @@ impl CWIL { limit = limit.strict_add(self.local_count); match self.limits.last() { - Some((ref inner_limit, _)) if *inner_limit <= limit => {} + Some((inner_limit, _)) if *inner_limit <= limit => {} _ => self.limits.push((limit, block)), } diff --git a/src/machine/mod.rs b/src/machine/mod.rs index 57de1f96..f7a21bf8 100644 --- a/src/machine/mod.rs +++ b/src/machine/mod.rs @@ -1224,7 +1224,7 @@ impl Machine { let key = Atom::from(h as u64); match self.indices.global_variables.get_mut(&key) { - Some((_, ref mut loc)) => *loc = None, + Some((_, loc)) => *loc = None, None => unreachable!(), } } @@ -1233,7 +1233,7 @@ impl Machine { let value_cell = HeapCellValue::from(u64::from(self.machine_st.trail[i + 1])); match self.indices.global_variables.get_mut(&key) { - Some((_, ref mut loc)) => *loc = Some(value_cell), + Some((_, loc)) => *loc = Some(value_cell), None => unreachable!(), } } diff --git a/src/machine/preprocessor.rs b/src/machine/preprocessor.rs index 2968d66d..1cfa8bb0 100644 --- a/src/machine/preprocessor.rs +++ b/src/machine/preprocessor.rs @@ -82,7 +82,7 @@ fn setup_op_decl(mut terms: Vec) -> Result { fn setup_predicate_indicator(term: &mut Term) -> Result { match term { - Term::Clause(_, slash, ref mut terms) + Term::Clause(_, slash, terms) if (*slash == atom!("/") || *slash == atom!("//")) && terms.len() == 2 => { let arity = terms.pop().unwrap(); diff --git a/src/machine/stack.rs b/src/machine/stack.rs index 15944356..258cfdd2 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -175,7 +175,7 @@ impl Stack { } #[inline(always)] - unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { + unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { unsafe { loop { let ptr = self.buf.alloc(frame_size); if let Some(ptr) = NonNull::new(ptr) { @@ -183,7 +183,7 @@ impl Stack { } self.buf.grow()?; } - } + }} pub(crate) fn allocate_and_frame(&mut self, num_cells: usize) -> Result { let frame_size = AndFrame::size_of(num_cells); diff --git a/src/machine/streams.rs b/src/machine/streams.rs index a956a00c..5fdf5c01 100644 --- a/src/machine/streams.rs +++ b/src/machine/streams.rs @@ -750,49 +750,49 @@ impl Stream { pub fn options(&self) -> &StreamOptions { match self { - Stream::Byte(ref ptr) => &ptr.options, - Stream::InputFile(ref ptr) => &ptr.options, - Stream::OutputFile(ref ptr) => &ptr.options, - Stream::StaticString(ref ptr) => &ptr.options, - Stream::NamedTcp(ref ptr) => &ptr.options, + Stream::Byte(ptr) => &ptr.options, + Stream::InputFile(ptr) => &ptr.options, + Stream::OutputFile(ptr) => &ptr.options, + Stream::StaticString(ptr) => &ptr.options, + Stream::NamedTcp(ptr) => &ptr.options, #[cfg(feature = "tls")] - Stream::NamedTls(ref ptr) => &ptr.options, + Stream::NamedTls(ptr) => &ptr.options, #[cfg(feature = "http")] - Stream::HttpRead(ref ptr) => &ptr.options, + Stream::HttpRead(ptr) => &ptr.options, #[cfg(feature = "http")] - Stream::HttpWrite(ref ptr) => &ptr.options, - Stream::Null(ref options) => options, - Stream::Readline(ref ptr) => &ptr.options, - Stream::StandardOutput(ref ptr) => &ptr.options, - Stream::StandardError(ref ptr) => &ptr.options, - Stream::Callback(ref ptr) => &ptr.options, - Stream::InputChannel(ref ptr) => &ptr.options, - Stream::PipeReader(ref ptr) => &ptr.options, - Stream::PipeWriter(ref ptr) => &ptr.options, + Stream::HttpWrite(ptr) => &ptr.options, + Stream::Null(options) => options, + Stream::Readline(ptr) => &ptr.options, + Stream::StandardOutput(ptr) => &ptr.options, + Stream::StandardError(ptr) => &ptr.options, + Stream::Callback(ptr) => &ptr.options, + Stream::InputChannel(ptr) => &ptr.options, + Stream::PipeReader(ptr) => &ptr.options, + Stream::PipeWriter(ptr) => &ptr.options, } } pub(super) fn options_mut(&mut self) -> &mut StreamOptions { match self { - Stream::Byte(ref mut ptr) => &mut ptr.options, - Stream::InputFile(ref mut ptr) => &mut ptr.options, - Stream::OutputFile(ref mut ptr) => &mut ptr.options, - Stream::StaticString(ref mut ptr) => &mut ptr.options, - Stream::NamedTcp(ref mut ptr) => &mut ptr.options, + Stream::Byte(ptr) => &mut ptr.options, + Stream::InputFile(ptr) => &mut ptr.options, + Stream::OutputFile(ptr) => &mut ptr.options, + Stream::StaticString(ptr) => &mut ptr.options, + Stream::NamedTcp(ptr) => &mut ptr.options, #[cfg(feature = "tls")] - Stream::NamedTls(ref mut ptr) => &mut ptr.options, + Stream::NamedTls(ptr) => &mut ptr.options, #[cfg(feature = "http")] - Stream::HttpRead(ref mut ptr) => &mut ptr.options, + Stream::HttpRead(ptr) => &mut ptr.options, #[cfg(feature = "http")] - Stream::HttpWrite(ref mut ptr) => &mut ptr.options, - Stream::Null(ref mut options) => options, - Stream::Readline(ref mut ptr) => &mut ptr.options, - Stream::StandardOutput(ref mut ptr) => &mut ptr.options, - Stream::StandardError(ref mut ptr) => &mut ptr.options, - Stream::Callback(ref mut ptr) => &mut ptr.options, - Stream::InputChannel(ref mut ptr) => &mut ptr.options, - Stream::PipeReader(ref mut ptr) => &mut ptr.options, - Stream::PipeWriter(ref mut ptr) => &mut ptr.options, + Stream::HttpWrite(ptr) => &mut ptr.options, + Stream::Null(options) => options, + Stream::Readline(ptr) => &mut ptr.options, + Stream::StandardOutput(ptr) => &mut ptr.options, + Stream::StandardError(ptr) => &mut ptr.options, + Stream::Callback(ptr) => &mut ptr.options, + Stream::InputChannel(ptr) => &mut ptr.options, + Stream::PipeReader(ptr) => &mut ptr.options, + Stream::PipeWriter(ptr) => &mut ptr.options, } } @@ -960,17 +960,17 @@ impl CharRead for Stream { fn consume(&mut self, nread: usize) { match self { - Stream::InputFile(ref mut file) => file.consume(nread), - Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.consume(nread), + Stream::InputFile(file) => file.consume(nread), + Stream::NamedTcp(tcp_stream) => tcp_stream.consume(nread), #[cfg(feature = "tls")] - Stream::NamedTls(ref mut tls_stream) => tls_stream.consume(nread), + Stream::NamedTls(tls_stream) => tls_stream.consume(nread), #[cfg(feature = "http")] - Stream::HttpRead(ref mut http_stream) => http_stream.consume(nread), - Stream::Readline(ref mut rl_stream) => rl_stream.consume(nread), - Stream::StaticString(ref mut src) => src.consume(nread), - Stream::Byte(ref mut cursor) => cursor.consume(nread), - Stream::InputChannel(ref mut cursor) => cursor.consume(nread), - Stream::PipeReader(ref mut cursor) => cursor.consume(nread), + Stream::HttpRead(http_stream) => http_stream.consume(nread), + Stream::Readline(rl_stream) => rl_stream.consume(nread), + Stream::StaticString(src) => src.consume(nread), + Stream::Byte(cursor) => cursor.consume(nread), + Stream::InputChannel(cursor) => cursor.consume(nread), + Stream::PipeReader(cursor) => cursor.consume(nread), #[cfg(feature = "http")] Stream::HttpWrite(_) => {} Stream::OutputFile(_) @@ -1019,17 +1019,17 @@ impl Read for Stream { impl Write for Stream { fn write(&mut self, buf: &[u8]) -> std::io::Result { match self { - Stream::OutputFile(ref mut file) => file.write(buf), - Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.get_mut().write(buf), + Stream::OutputFile(file) => file.write(buf), + Stream::NamedTcp(tcp_stream) => tcp_stream.get_mut().write(buf), #[cfg(feature = "tls")] - Stream::NamedTls(ref mut tls_stream) => tls_stream.get_mut().write(buf), - Stream::Byte(ref mut cursor) => cursor.get_mut().write(buf), - Stream::Callback(ref mut callback_stream) => callback_stream.get_mut().write(buf), + Stream::NamedTls(tls_stream) => tls_stream.get_mut().write(buf), + Stream::Byte(cursor) => cursor.get_mut().write(buf), + Stream::Callback(callback_stream) => callback_stream.get_mut().write(buf), Stream::StandardOutput(stream) => stream.write(buf), Stream::StandardError(stream) => stream.write(buf), #[cfg(feature = "http")] - Stream::HttpWrite(ref mut stream) => stream.get_mut().write(buf), - Stream::PipeWriter(ref mut stream) => stream.get_mut().write(buf), + Stream::HttpWrite(stream) => stream.get_mut().write(buf), + Stream::PipeWriter(stream) => stream.get_mut().write(buf), #[cfg(feature = "http")] Stream::HttpRead(_) => Err(std::io::Error::new( ErrorKind::PermissionDenied, @@ -1049,17 +1049,17 @@ impl Write for Stream { fn flush(&mut self) -> std::io::Result<()> { match self { - Stream::OutputFile(ref mut file) => file.stream.flush(), - Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.stream.get_mut().flush(), + Stream::OutputFile(file) => file.stream.flush(), + Stream::NamedTcp(tcp_stream) => tcp_stream.stream.get_mut().flush(), #[cfg(feature = "tls")] - Stream::NamedTls(ref mut tls_stream) => tls_stream.stream.get_mut().flush(), - Stream::Byte(ref mut cursor) => cursor.stream.get_mut().flush(), - Stream::Callback(ref mut callback_stream) => callback_stream.stream.get_mut().flush(), + Stream::NamedTls(tls_stream) => tls_stream.stream.get_mut().flush(), + Stream::Byte(cursor) => cursor.stream.get_mut().flush(), + Stream::Callback(callback_stream) => callback_stream.stream.get_mut().flush(), Stream::StandardError(stream) => stream.stream.flush(), Stream::StandardOutput(stream) => stream.stream.flush(), - Stream::PipeWriter(ref mut stream) => stream.stream.get_mut().flush(), + Stream::PipeWriter(stream) => stream.stream.get_mut().flush(), #[cfg(feature = "http")] - Stream::HttpWrite(ref mut stream) => stream.stream.get_mut().flush(), + Stream::HttpWrite(stream) => stream.stream.get_mut().flush(), #[cfg(feature = "http")] Stream::HttpRead(_) => Err(std::io::Error::new( ErrorKind::PermissionDenied, @@ -1530,58 +1530,58 @@ impl Stream { #[inline] pub(crate) fn close(&mut self) -> Result<(), std::io::Error> { match self { - Stream::NamedTcp(ref mut tcp_stream) => { + Stream::NamedTcp(tcp_stream) => { tcp_stream.inner_mut().tcp_stream.shutdown(Shutdown::Both) } #[cfg(feature = "tls")] - Stream::NamedTls(ref mut tls_stream) => tls_stream.inner_mut().tls_stream.shutdown(), + Stream::NamedTls(tls_stream) => tls_stream.inner_mut().tls_stream.shutdown(), #[cfg(feature = "http")] - Stream::HttpRead(ref mut http_stream) => { + Stream::HttpRead(http_stream) => { http_stream.drop_payload(); Ok(()) } #[cfg(feature = "http")] - Stream::HttpWrite(mut http_stream) => { + &mut Stream::HttpWrite(mut http_stream) => { http_stream.drop_payload(); Ok(()) } - Stream::InputFile(mut file_stream) => { + &mut Stream::InputFile(mut file_stream) => { // close the stream by dropping the inner File. file_stream.drop_payload(); Ok(()) } - Stream::OutputFile(mut file_stream) => { + &mut Stream::OutputFile(mut file_stream) => { // close the stream by dropping the inner File. file_stream.drop_payload(); Ok(()) } - Stream::Byte(mut stream) => { + &mut Stream::Byte(mut stream) => { stream.drop_payload(); Ok(()) } - Stream::Callback(mut stream) => { + &mut Stream::Callback(mut stream) => { stream.drop_payload(); Ok(()) } - Stream::InputChannel(mut stream) => { + &mut Stream::InputChannel(mut stream) => { stream.drop_payload(); Ok(()) } - Stream::StaticString(mut stream) => { + &mut Stream::StaticString(mut stream) => { stream.drop_payload(); Ok(()) } - Stream::PipeReader(mut stream) => { + &mut Stream::PipeReader(mut stream) => { stream.drop_payload(); Ok(()) } - Stream::PipeWriter(mut stream) => { + &mut Stream::PipeWriter(mut stream) => { stream.drop_payload(); Ok(()) } @@ -1644,11 +1644,11 @@ impl Stream { self.set_past_end_of_stream(false); match self { - Stream::Byte(ref mut cursor) => { + Stream::Byte(cursor) => { cursor.stream.get_mut().0.set_position(0); true } - Stream::InputFile(ref mut file_stream) => { + Stream::InputFile(file_stream) => { file_stream .stream .get_mut() @@ -1657,11 +1657,11 @@ impl Stream { .unwrap(); true } - Stream::Readline(ref mut readline_stream) => { + Stream::Readline(readline_stream) => { readline_stream.reset(); true } - Stream::InputChannel(ref mut input_channel_stream) => { + Stream::InputChannel(input_channel_stream) => { input_channel_stream.stream.get_mut().inner.set_position(0); true } @@ -1672,7 +1672,7 @@ impl Stream { #[inline] pub(crate) fn peek_byte(&mut self) -> std::io::Result { match self { - Stream::Byte(ref mut cursor) => { + Stream::Byte(cursor) => { let mut b = [0u8; 1]; let pos = cursor.stream.get_mut().0.position(); @@ -1684,15 +1684,15 @@ impl Stream { _ => Err(std::io::Error::new(ErrorKind::UnexpectedEof, "end of file")), } } - Stream::InputFile(ref mut file) => match file.peek_byte() { + Stream::InputFile(file) => match file.peek_byte() { Some(result) => Ok(result?), _ => Err(std::io::Error::new( ErrorKind::UnexpectedEof, StreamError::PeekByteFailed, )), }, - Stream::Readline(ref mut stream) => stream.stream.peek_byte(), - Stream::NamedTcp(ref mut stream) => { + Stream::Readline(stream) => stream.stream.peek_byte(), + Stream::NamedTcp(stream) => { let mut b = [0u8; 1]; stream.stream.get_mut().tcp_stream.peek(&mut b)?; Ok(b[0]) diff --git a/src/machine/system_calls.rs b/src/machine/system_calls.rs index 0e36d1ad..5c859ba4 100644 --- a/src/machine/system_calls.rs +++ b/src/machine/system_calls.rs @@ -1252,7 +1252,7 @@ impl Machine { loop { match &self.code[bp] { - Instruction::IndexingCode(ref indexing_code) => { + Instruction::IndexingCode(indexing_code) => { let indexing_code_ptr = match &indexing_code[0] { &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( _, @@ -1275,10 +1275,10 @@ impl Machine { let boip = extract_ptr!(indexing_code_ptr); let boip = match &indexing_code[boip] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref hm)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(hm)) => { boip + extract_ptr!(hm.get(&key).cloned().unwrap()) } - IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref hm)) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(hm)) => { boip + extract_ptr!(hm.get(&atom_as_cell!(key.0)).cloned().unwrap()) } _ => boip, @@ -3138,7 +3138,7 @@ impl Machine { let addr = self.machine_st.registers[2]; match self.indices.global_variables.get_mut(&key) { - Some((ref ball, ref mut loc)) => match loc { + Some(&mut (ref ball, ref mut loc)) => match loc { Some(value_loc) => { unify_fn!(self.machine_st, addr, *value_loc); } @@ -4319,7 +4319,7 @@ impl Machine { #[inline(always)] pub(crate) fn maybe(&mut self) { - self.machine_st.fail = self.rng.gen(); + self.machine_st.fail = self.rng.r#gen(); } #[cfg(not(target_arch = "wasm32"))] @@ -7522,8 +7522,8 @@ impl Machine { let new_value = self.deref_register(2); match self.indices.global_variables.get_mut(&key) { - Some((_, ref mut loc)) => match loc { - Some(ref mut value) => { + Some((_, loc)) => match loc { + Some(value) => { self.machine_st .trail(TrailRef::BlackboardOffset(key, *value)); *value = new_value; @@ -8667,7 +8667,8 @@ impl Machine { .value_to_str_like(self.machine_st.registers[2]) .unwrap(); - env::set_var(&*key.as_str(), &*value.as_str()); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::set_var(&*key.as_str(), &*value.as_str()) }; } #[inline(always)] @@ -8676,7 +8677,8 @@ impl Machine { .machine_st .value_to_str_like(self.machine_st.registers[1]) .unwrap(); - env::remove_var(&*key.as_str()); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::remove_var(&*key.as_str()) }; } #[inline(always)] diff --git a/src/offset_table.rs b/src/offset_table.rs index f09a3583..f496ca54 100644 --- a/src/offset_table.rs +++ b/src/offset_table.rs @@ -211,7 +211,7 @@ impl SerialOffsetTable { }) } - unsafe fn build_with(&mut self, value: T) -> usize { + unsafe fn build_with(&mut self, value: T) -> usize { unsafe { let mut ptr; loop { @@ -228,17 +228,17 @@ impl SerialOffsetTable { ptr::write(ptr as *mut T, value); // SAFETY: `ptr` was obtained from `self.block.alloc()` self.block.get_offset(ptr) - } + }} #[inline] - unsafe fn lookup(&self, offset: usize) -> &T { + unsafe fn lookup(&self, offset: usize) -> &T { unsafe { &*self.block.get_unchecked(offset).cast::() - } + }} #[inline] - unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { + unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { unsafe { &mut *self.block.get_unchecked(offset).cast::().cast_mut() - } + }} #[allow(clippy::wrong_self_convention)] fn to_concurrent(&mut self) -> ConcurrentOffsetTable diff --git a/src/parser/ast.rs b/src/parser/ast.rs index dbfd011e..fb835611 100644 --- a/src/parser/ast.rs +++ b/src/parser/ast.rs @@ -877,7 +877,7 @@ pub enum Term { impl Term { pub fn first_arg(&self) -> Option<&Term> { match self { - Term::Clause(_, _, ref terms) => terms.first(), + Term::Clause(_, _, terms) => terms.first(), _ => None, } } @@ -892,14 +892,14 @@ impl Term { pub fn arity(&self) -> usize { match self { - Term::Clause(_, _, ref child_terms, ..) => child_terms.len(), + Term::Clause(_, _, child_terms, ..) => child_terms.len(), _ => 0, } } } pub(crate) fn unfold_by_str_once(term: &mut Term, s: Atom) -> Option<(Term, Term)> { - if let Term::Clause(_, ref name, ref mut subterms) = term { + if let &mut Term::Clause(_, ref name, ref mut subterms) = term { if let Some(Term::Literal(_, Literal::CodeIndexOffset(_))) = subterms.last() { subterms.pop(); } diff --git a/src/types.rs b/src/types.rs index bcf67a4a..9cec6926 100644 --- a/src/types.rs +++ b/src/types.rs @@ -761,9 +761,9 @@ impl UntypedArenaPtr { pub unsafe fn as_typed_ptr(self) -> TypedArenaPtr where T::Payload: Sized, - { + { unsafe { T::typed_ptr(self) - } + }} #[inline] pub fn get_mark_bit(self) -> bool { diff --git a/src/variable_records.rs b/src/variable_records.rs index fde9fbcf..2e05634a 100644 --- a/src/variable_records.rs +++ b/src/variable_records.rs @@ -105,9 +105,9 @@ impl VarAlloc { #[inline] pub(crate) fn set_register(&mut self, reg_num: usize) { match self { - VarAlloc::Perm(ref mut p, _) => *p = reg_num, + VarAlloc::Perm(p, _) => *p = reg_num, VarAlloc::Temp { - ref mut temp_reg, .. + temp_reg, .. } => *temp_reg = reg_num, }; } From fcd6c3f127f6e8f88bd3929c42349eaeda291ab5 Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Thu, 2 Apr 2026 16:08:06 -0400 Subject: [PATCH 02/10] Issue 3223: Second phase of migration to Rust Edition Reformat via `cargo fmt` --- benches/run_criterion.rs | 2 +- build/instructions_template.rs | 2 +- build/main.rs | 2 +- src/arena.rs | 190 ++++++++++---------- src/arithmetic.rs | 26 +-- src/atom_table.rs | 14 +- src/debray_allocator.rs | 19 +- src/ffi.rs | 102 ++++++----- src/functor_macro.rs | 2 +- src/heap_print.rs | 2 +- src/http.rs | 2 +- src/indexing.rs | 220 +++++++++++------------ src/iterators.rs | 6 +- src/lib.rs | 2 +- src/machine/arithmetic_ops.rs | 2 +- src/machine/compile.rs | 7 +- src/machine/config.rs | 8 +- src/machine/dispatch.rs | 4 +- src/machine/heap.rs | 133 +++++++------- src/machine/lib_machine/mod.rs | 8 +- src/machine/loader.rs | 103 ++++++----- src/machine/machine_errors.rs | 4 +- src/machine/machine_indices.rs | 6 +- src/machine/machine_state.rs | 2 +- src/machine/mod.rs | 2 +- src/machine/preprocessor.rs | 2 +- src/machine/stack.rs | 16 +- src/machine/streams.rs | 4 +- src/machine/system_calls.rs | 8 +- src/machine/system_calls/special_math.rs | 2 +- src/machine/unify.rs | 2 +- src/macros.rs | 4 +- src/offset_table.rs | 14 +- src/parser/ast.rs | 6 +- src/parser/lexer.rs | 4 +- src/read.rs | 8 +- src/read/user_interaction.rs | 2 +- src/types.rs | 6 +- src/variable_records.rs | 4 +- tests/scryer/issues.rs | 12 +- 40 files changed, 468 insertions(+), 496 deletions(-) diff --git a/benches/run_criterion.rs b/benches/run_criterion.rs index 4622e039..09efbc10 100644 --- a/benches/run_criterion.rs +++ b/benches/run_criterion.rs @@ -1,5 +1,5 @@ #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] -use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] #[cfg(not(target_os = "windows"))] diff --git a/build/instructions_template.rs b/build/instructions_template.rs index 2dad5291..f1015215 100644 --- a/build/instructions_template.rs +++ b/build/instructions_template.rs @@ -4,7 +4,7 @@ // use proc_macro2::TokenStream; -use quote::{format_ident, quote, ToTokens, TokenStreamExt}; +use quote::{ToTokens, TokenStreamExt, format_ident, quote}; use strum_macros::{EnumDiscriminants, EnumProperty, EnumString}; use syn::*; use to_syn_value_derive::ToDeriveInput; diff --git a/build/main.rs b/build/main.rs index fd2f8c46..e762929c 100644 --- a/build/main.rs +++ b/build/main.rs @@ -8,9 +8,9 @@ use std::collections::BTreeMap; use std::env; use std::fs::File; use std::io::Write; +use std::path::MAIN_SEPARATOR_STR; use std::path::Path; use std::path::PathBuf; -use std::path::MAIN_SEPARATOR_STR; use std::process::{Command, Stdio}; fn find_prolog_files(path_prefix: &str, current_dir: &Path) -> Vec<(String, PathBuf)> { diff --git a/src/arena.rs b/src/arena.rs index aae81e4e..f8cd9695 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -21,8 +21,8 @@ use std::net::TcpListener; use std::ops::{Deref, DerefMut}; use std::process::Child; use std::ptr; -use std::ptr::addr_of_mut; use std::ptr::NonNull; +use std::ptr::addr_of_mut; macro_rules! arena_alloc { ($e:expr, $arena:expr) => {{ @@ -32,9 +32,7 @@ macro_rules! arena_alloc { } macro_rules! float_alloc { - ($e:expr, $arena:expr) => {{ - $arena.f64_tbl.build_with(OrderedFloat($e)) - }}; + ($e:expr, $arena:expr) => {{ $arena.f64_tbl.build_with(OrderedFloat($e)) }}; } pub fn header_offset_from_payload() -> usize @@ -281,14 +279,16 @@ pub trait ArenaAllocated { unsafe fn typed_ptr(ptr: UntypedArenaPtr) -> TypedArenaPtr where Self::Payload: Sized, - { unsafe { - TypedArenaPtr(NonNull::new_unchecked( - ptr.get_ptr() - .byte_add(Self::header_offset_from_payload()) - .cast_mut() - .cast::(), - )) - }} + { + unsafe { + TypedArenaPtr(NonNull::new_unchecked( + ptr.get_ptr() + .byte_add(Self::header_offset_from_payload()) + .cast_mut() + .cast::(), + )) + } + } #[allow(clippy::missing_safety_doc)] fn alloc(arena: &mut Arena, value: Self::Payload) -> TypedArenaPtr @@ -496,91 +496,93 @@ impl Arena { } } -unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { unsafe { - macro_rules! drop_typed_slab_in_place { - ($payload: ty, $value: expr) => { - <$payload as ArenaAllocated>::dealloc($value.cast::>()) - }; - } +unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { + unsafe { + macro_rules! drop_typed_slab_in_place { + ($payload: ty, $value: expr) => { + <$payload as ArenaAllocated>::dealloc($value.cast::>()) + }; + } - match tag { - ArenaHeaderTag::Integer => { - drop_typed_slab_in_place!(Integer, value); - } - ArenaHeaderTag::Rational => { - drop_typed_slab_in_place!(Rational, value); - } - ArenaHeaderTag::InputFileStream => { - drop_typed_slab_in_place!(InputFileStream, value); - } - ArenaHeaderTag::OutputFileStream => { - drop_typed_slab_in_place!(OutputFileStream, value); - } - ArenaHeaderTag::NamedTcpStream => { - drop_typed_slab_in_place!(NamedTcpStream, value); - } - ArenaHeaderTag::NamedTlsStream => { - #[cfg(feature = "tls")] - drop_typed_slab_in_place!(NamedTlsStream, value); - } - ArenaHeaderTag::HttpReadStream => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpReadStream, value); - } - ArenaHeaderTag::HttpWriteStream => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpWriteStream, value); - } - ArenaHeaderTag::ReadlineStream => { - drop_typed_slab_in_place!(ReadlineStream, value); - } - ArenaHeaderTag::StaticStringStream => { - drop_typed_slab_in_place!(StaticStringStream, value); - } - ArenaHeaderTag::ByteStream => { - drop_typed_slab_in_place!(ByteStream, value); - } - ArenaHeaderTag::CallbackStream => { - drop_typed_slab_in_place!(CallbackStream, value); - } - ArenaHeaderTag::InputChannelStream => { - drop_typed_slab_in_place!(InputChannelStream, value); - } - ArenaHeaderTag::LiveLoadState | ArenaHeaderTag::InactiveLoadState => { - drop_typed_slab_in_place!(LiveLoadState, value); - } - ArenaHeaderTag::Dropped => {} - ArenaHeaderTag::TcpListener => { - drop_typed_slab_in_place!(TcpListener, value); - } - ArenaHeaderTag::HttpListener => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpListener, value); - } - ArenaHeaderTag::HttpResponse => { - #[cfg(feature = "http")] - drop_typed_slab_in_place!(HttpResponse, value); - } - ArenaHeaderTag::StandardOutputStream => { - drop_typed_slab_in_place!(StandardOutputStream, value); - } - ArenaHeaderTag::StandardErrorStream => { - drop_typed_slab_in_place!(StandardErrorStream, value); - } - ArenaHeaderTag::PipeReader => { - drop_typed_slab_in_place!(PipeReader, value); - } - ArenaHeaderTag::PipeWriter => { - drop_typed_slab_in_place!(PipeWriter, value); - } - ArenaHeaderTag::ChildProcess => { - drop_typed_slab_in_place!(Child, value); - } - ArenaHeaderTag::NullStream => { - unreachable!("NullStream is never arena allocated!"); + match tag { + ArenaHeaderTag::Integer => { + drop_typed_slab_in_place!(Integer, value); + } + ArenaHeaderTag::Rational => { + drop_typed_slab_in_place!(Rational, value); + } + ArenaHeaderTag::InputFileStream => { + drop_typed_slab_in_place!(InputFileStream, value); + } + ArenaHeaderTag::OutputFileStream => { + drop_typed_slab_in_place!(OutputFileStream, value); + } + ArenaHeaderTag::NamedTcpStream => { + drop_typed_slab_in_place!(NamedTcpStream, value); + } + ArenaHeaderTag::NamedTlsStream => { + #[cfg(feature = "tls")] + drop_typed_slab_in_place!(NamedTlsStream, value); + } + ArenaHeaderTag::HttpReadStream => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpReadStream, value); + } + ArenaHeaderTag::HttpWriteStream => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpWriteStream, value); + } + ArenaHeaderTag::ReadlineStream => { + drop_typed_slab_in_place!(ReadlineStream, value); + } + ArenaHeaderTag::StaticStringStream => { + drop_typed_slab_in_place!(StaticStringStream, value); + } + ArenaHeaderTag::ByteStream => { + drop_typed_slab_in_place!(ByteStream, value); + } + ArenaHeaderTag::CallbackStream => { + drop_typed_slab_in_place!(CallbackStream, value); + } + ArenaHeaderTag::InputChannelStream => { + drop_typed_slab_in_place!(InputChannelStream, value); + } + ArenaHeaderTag::LiveLoadState | ArenaHeaderTag::InactiveLoadState => { + drop_typed_slab_in_place!(LiveLoadState, value); + } + ArenaHeaderTag::Dropped => {} + ArenaHeaderTag::TcpListener => { + drop_typed_slab_in_place!(TcpListener, value); + } + ArenaHeaderTag::HttpListener => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpListener, value); + } + ArenaHeaderTag::HttpResponse => { + #[cfg(feature = "http")] + drop_typed_slab_in_place!(HttpResponse, value); + } + ArenaHeaderTag::StandardOutputStream => { + drop_typed_slab_in_place!(StandardOutputStream, value); + } + ArenaHeaderTag::StandardErrorStream => { + drop_typed_slab_in_place!(StandardErrorStream, value); + } + ArenaHeaderTag::PipeReader => { + drop_typed_slab_in_place!(PipeReader, value); + } + ArenaHeaderTag::PipeWriter => { + drop_typed_slab_in_place!(PipeWriter, value); + } + ArenaHeaderTag::ChildProcess => { + drop_typed_slab_in_place!(Child, value); + } + ArenaHeaderTag::NullStream => { + unreachable!("NullStream is never arena allocated!"); + } } } -}} +} impl Drop for Arena { fn drop(&mut self) { diff --git a/src/arithmetic.rs b/src/arithmetic.rs index df5b6268..b714ddc1 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -64,7 +64,7 @@ impl<'a> ArithInstructionIterator<'a> { return Err(ArithmeticError::NonEvaluableFunctor( Literal::Atom(atom!(".")), 2, - )) + )); } Term::Var(cell, var_ptr) => TermIterState::Var(Level::Shallow, cell, var_ptr.clone()), }; @@ -519,26 +519,16 @@ impl PartialEq for Number { (&Number::Fixnum(n1), Number::Rational(n2)) => { Integer::from(n1.get_num()).num_eq(&**n2) } - (Number::Rational(n1), &Number::Fixnum(n2)) => { - n1.num_eq(&Integer::from(n2.get_num())) - } + (Number::Rational(n1), &Number::Fixnum(n2)) => n1.num_eq(&Integer::from(n2.get_num())), (&Number::Fixnum(n1), &Number::Float(n2)) => OrderedFloat(n1.get_num() as f64).eq(&n2), (&Number::Float(n1), &Number::Fixnum(n2)) => n1.eq(&OrderedFloat(n2.get_num() as f64)), (Number::Integer(n1), Number::Integer(n2)) => n1.eq(n2), - (Number::Integer(n1), Number::Float(n2)) => { - OrderedFloat(n1.to_f64().value()).eq(n2) - } - (&Number::Float(n1), Number::Integer(n2)) => { - n1.eq(&OrderedFloat(n2.to_f64().value())) - } + (Number::Integer(n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).eq(n2), + (&Number::Float(n1), Number::Integer(n2)) => n1.eq(&OrderedFloat(n2.to_f64().value())), (Number::Integer(n1), Number::Rational(n2)) => n1.num_eq(&**n2), (Number::Rational(n1), Number::Integer(n2)) => n1.num_eq(&**n2), - (Number::Rational(n1), &Number::Float(n2)) => { - OrderedFloat(n1.to_f64().value()).eq(&n2) - } - (&Number::Float(n1), Number::Rational(n2)) => { - n1.eq(&OrderedFloat(n2.to_f64().value())) - } + (Number::Rational(n1), &Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).eq(&n2), + (&Number::Float(n1), Number::Rational(n2)) => n1.eq(&OrderedFloat(n2.to_f64().value())), (&Number::Float(f1), &Number::Float(f2)) => f1.eq(&f2), (Number::Rational(r1), Number::Rational(r2)) => r1.eq(r2), } @@ -607,9 +597,7 @@ impl Ord for Number { (&Number::Float(n1), &Number::Fixnum(n2)) => n1.cmp(&OrderedFloat(n2.get_num() as f64)), (&Number::Integer(n1), &Number::Integer(n2)) => (*n1).cmp(&*n2), (&Number::Integer(n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).cmp(n2), - (&Number::Float(n1), Number::Integer(n2)) => { - n1.cmp(&OrderedFloat(n2.to_f64().value())) - } + (&Number::Float(n1), Number::Integer(n2)) => n1.cmp(&OrderedFloat(n2.to_f64().value())), (&Number::Integer(n1), &Number::Rational(n2)) => { (*n1).num_partial_cmp(&*n2).unwrap_or(Ordering::Less) } diff --git a/src/atom_table.rs b/src/atom_table.rs index 5526b1ff..5292d208 100644 --- a/src/atom_table.rs +++ b/src/atom_table.rs @@ -14,10 +14,10 @@ use std::sync::Mutex; use std::sync::RwLock; use std::sync::Weak; +use arcu::Rcu; use arcu::atomic::Arcu; use arcu::epoch_counters::GlobalEpochCounterPool; use arcu::rcu_ref::RcuRef; -use arcu::Rcu; use indexmap::IndexSet; use modular_bitfield::prelude::*; @@ -344,11 +344,7 @@ impl Atom { let c1 = it.next(); let c2 = it.next(); - if c2.is_none() { - c1 - } else { - None - } + if c2.is_none() { c1 } else { None } } #[inline] @@ -387,8 +383,10 @@ impl Atom { } } -unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { - unsafe { ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); } +unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { + unsafe { + ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); + } unsafe { let str_ptr = ptr.add(mem::size_of::()); ptr::copy_nonoverlapping(string.as_ptr(), str_ptr, string.len()); diff --git a/src/debray_allocator.rs b/src/debray_allocator.rs index 39d37820..e901fc6e 100644 --- a/src/debray_allocator.rs +++ b/src/debray_allocator.rs @@ -551,8 +551,7 @@ impl DebrayAllocator { } else if let Some(&temp_var_num) = self.shallow_temp_mappings.get(&self.arg_c) { match &mut self.var_data.records[temp_var_num].allocation { VarAlloc::Temp { - to_perm_var_num, - .. + to_perm_var_num, .. } => { *to_perm_var_num = Some(var_num); } @@ -578,13 +577,7 @@ impl DebrayAllocator { let branch_designator = Arc::new(self.branch_stack.current_branch_designator()); match &mut self.var_data.records[var_num].allocation { - VarAlloc::Perm( - _, - PermVarAllocation::Done { - shallow_safety, - .. - }, - ) => { + VarAlloc::Perm(_, PermVarAllocation::Done { shallow_safety, .. }) => { if !self.in_tail_position || self .branch_stack @@ -614,13 +607,7 @@ impl DebrayAllocator { let branch_designator = Arc::new(self.branch_stack.current_branch_designator()); match &mut self.var_data.records[var_num].allocation { - VarAlloc::Perm( - _, - PermVarAllocation::Done { - deep_safety, - .. - }, - ) => { + VarAlloc::Perm(_, PermVarAllocation::Done { deep_safety, .. }) => { if self .branch_stack .safety_unneeded_in_branch(deep_safety, &branch_designator) diff --git a/src/ffi.rs b/src/ffi.rs index 3a4f9dde..d319cfc7 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -32,7 +32,7 @@ use ordered_float::OrderedFloat; use std::alloc::{self, Layout}; use std::collections::HashMap; use std::error::Error; -use std::ffi::{c_char, c_void, CStr, CString}; +use std::ffi::{CStr, CString, c_char, c_void}; use std::fmt::Debug; use std::marker::PhantomData; use std::mem::ManuallyDrop; @@ -53,27 +53,33 @@ pub struct FunctionImpl { } impl FunctionImpl { - unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { unsafe { - self.cif.call_return_into(self.code_ptr, args, Ret::void()); - Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) - }} + unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { + unsafe { + self.cif.call_return_into(self.code_ptr, args, Ret::void()); + Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) + } + } unsafe fn call_int(&self, args: &[Arg], arena: &mut Arena) -> Result where Integer: From, T: Copy + TryInto + MightNotFitInFixnum, - { unsafe { - let n = self.cif.call::(self.code_ptr, args); - Ok(Value::Number(fixnum!(Number, n, arena))) - }} + { + unsafe { + let n = self.cif.call::(self.code_ptr, args); + Ok(Value::Number(fixnum!(Number, n, arena))) + } + } unsafe fn call_float(&self, args: &[Arg], _: &mut Arena) -> Result where T: Into, - { unsafe { - let n = self.cif.call::(self.code_ptr, args); - Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - }} + { + unsafe { + let n = self.cif.call::(self.code_ptr, args); + Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) + } + } unsafe fn call_ptr(&self, args: &[Arg], arena: &mut Arena) -> Result { let ptr = unsafe { self.cif.call::<*mut c_void>(self.code_ptr, args) }; @@ -147,7 +153,7 @@ impl FunctionImpl { FfiType::Ptr => FunctionImpl::call_ptr, FfiType::CStr => FunctionImpl::call_cstr, FfiType::Struct(name) => { - return unsafe { self.call_struct(name, args, arena, structs_table) } + return unsafe { self.call_struct(name, args, arena, structs_table) }; } }; unsafe { call_fn(self, args, arena) } @@ -197,14 +203,16 @@ impl StructImpl { ptr: NonNull, layout: &mut Layout, val: T, - ) -> Result<(), FfiError> { unsafe { - let (new_layout, offset) = layout - .extend(Layout::new::()) - .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; - ptr.byte_offset(offset as isize).cast::().write(val); - Ok(()) - }} + ) -> Result<(), FfiError> { + unsafe { + let (new_layout, offset) = layout + .extend(Layout::new::()) + .map_err(|_| FfiError::LayoutError)?; + *layout = new_layout; + ptr.byte_offset(offset as isize).cast::().write(val); + Ok(()) + } + } for arg in args { unsafe { @@ -258,14 +266,16 @@ impl StructImpl { unsafe fn read_primitive( ptr: *mut c_void, layout: &mut Layout, - ) -> Result { unsafe { - let (new_layout, offset) = layout - .extend(Layout::new::()) - .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; - let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); - Ok(n) - }} + ) -> Result { + unsafe { + let (new_layout, offset) = layout + .extend(Layout::new::()) + .map_err(|_| FfiError::LayoutError)?; + *layout = new_layout; + let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); + Ok(n) + } + } unsafe fn read_int( ptr: *mut c_void, @@ -275,10 +285,12 @@ impl StructImpl { where T: Copy + TryInto + MightNotFitInFixnum, Integer: From, - { unsafe { - let n = read_primitive::(ptr, layout)?; - Ok(Value::Number(fixnum!(Number, n, arena))) - }} + { + unsafe { + let n = read_primitive::(ptr, layout)?; + Ok(Value::Number(fixnum!(Number, n, arena))) + } + } unsafe fn read_float( ptr: *mut c_void, @@ -286,10 +298,12 @@ impl StructImpl { ) -> Result where T: Into, - { unsafe { - let n = read_primitive::(ptr, layout)?; - Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - }} + { + unsafe { + let n = read_primitive::(ptr, layout)?; + Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) + } + } let mut layout = Layout::from_size_align(0, 1).map_err(|_| FfiError::LayoutError)?; @@ -332,7 +346,7 @@ impl StructImpl { Ok(struct_val) } FfiType::Void => { - return Err(FfiError::UnsupportedArgumentType(Some(atom!("void")))) + return Err(FfiError::UnsupportedArgumentType(Some(atom!("void")))); } }; returns.push(val?); @@ -788,10 +802,12 @@ impl ForeignFunctionTable { where T: Copy + TryInto + MightNotFitInFixnum, Integer: From, - { unsafe { - let n = ptr.cast::().read(); - Value::Number(fixnum!(Number, n, arena)) - }} + { + unsafe { + let n = ptr.cast::().read(); + Value::Number(fixnum!(Number, n, arena)) + } + } let ptr = ptr.as_ptr()?; diff --git a/src/functor_macro.rs b/src/functor_macro.rs index 82d6d98e..37daf72b 100644 --- a/src/functor_macro.rs +++ b/src/functor_macro.rs @@ -230,9 +230,9 @@ pub(crate) fn variadic_functor( #[allow(unused_parens)] mod tests { use super::*; + use FunctorElement::*; use indexmap::indexmap; use std::string::String; - use FunctorElement::*; #[test] fn basic_terms() { diff --git a/src/heap_print.rs b/src/heap_print.rs index fcc0cc0c..8f0cd7fe 100644 --- a/src/heap_print.rs +++ b/src/heap_print.rs @@ -3,7 +3,7 @@ use crate::atom_table::*; use crate::parser::ast::*; use crate::parser::dashu::base::RemEuclid; use crate::parser::dashu::integer::Sign; -use crate::parser::dashu::{ibig, Integer, Rational}; +use crate::parser::dashu::{Integer, Rational, ibig}; use crate::forms::*; use crate::heap_iter::*; diff --git a/src/http.rs b/src/http.rs index d9f669d7..241b2e10 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,4 +1,4 @@ -use bytes::{buf::Reader, Bytes}; +use bytes::{Bytes, buf::Reader}; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::Notify; diff --git a/src/indexing.rs b/src/indexing.rs index 2b5b9767..d6c3247e 100644 --- a/src/indexing.rs +++ b/src/indexing.rs @@ -491,33 +491,29 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( - _, - _, - _, - _, - s, - )) => match *s { - IndexingCodePtr::Fail if self.is_dynamic => { - *s = IndexingCodePtr::DynamicExternal(index); - break; + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { + match *s { + IndexingCodePtr::Fail if self.is_dynamic => { + *s = IndexingCodePtr::DynamicExternal(index); + break; + } + IndexingCodePtr::Fail => { + *s = IndexingCodePtr::External(index); + break; + } + IndexingCodePtr::DynamicExternal(o) => { + *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); + self.internalize_structure(IndexingCodePtr::DynamicExternal(o)); + } + IndexingCodePtr::External(o) => { + *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); + self.internalize_structure(IndexingCodePtr::External(o)); + } + IndexingCodePtr::Internal(o) => { + self.offset += o; + } } - IndexingCodePtr::Fail => { - *s = IndexingCodePtr::External(index); - break; - } - IndexingCodePtr::DynamicExternal(o) => { - *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); - self.internalize_structure(IndexingCodePtr::DynamicExternal(o)); - } - IndexingCodePtr::External(o) => { - *s = IndexingCodePtr::Internal(indexing_code_len - self.offset); - self.internalize_structure(IndexingCodePtr::External(o)); - } - IndexingCodePtr::Internal(o) => { - self.offset += o; - } - }, + } IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(structures)) => { match structures.get(&key).cloned() { None | Some(IndexingCodePtr::Fail) if self.is_dynamic => { @@ -559,52 +555,50 @@ impl<'a> IndexingCodeMergingPtr<'a> { let indexing_code_len = self.indexing_code.len(); match &mut self.indexing_code[self.offset] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => { - match *l { - IndexingCodePtr::Fail if self.is_dynamic => { - *l = IndexingCodePtr::DynamicExternal(index); - } - IndexingCodePtr::Fail => { - *l = IndexingCodePtr::External(index); - } - IndexingCodePtr::DynamicExternal(o) => { - *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); - - let third_level_index = if self.append_or_prepend.is_append() { - vec![o, index].into() - } else { - vec![index, o].into() - }; - - self.indexing_code - .push(IndexingLine::DynamicIndexedChoice(third_level_index)); - } - IndexingCodePtr::External(o) => { - *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); - - let third_level_index = if self.append_or_prepend.is_append() { - vec![ - IndexedChoiceInstruction::Try(o), - IndexedChoiceInstruction::Trust(index), - ] - .into() - } else { - vec![ - IndexedChoiceInstruction::Try(index), - IndexedChoiceInstruction::Trust(o), - ] - .into() - }; - - self.indexing_code - .push(IndexingLine::IndexedChoice(third_level_index)); - } - IndexingCodePtr::Internal(o) => { - self.offset += o; - self.extend_indexed_choice(index); - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => match *l { + IndexingCodePtr::Fail if self.is_dynamic => { + *l = IndexingCodePtr::DynamicExternal(index); } - } + IndexingCodePtr::Fail => { + *l = IndexingCodePtr::External(index); + } + IndexingCodePtr::DynamicExternal(o) => { + *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); + + let third_level_index = if self.append_or_prepend.is_append() { + vec![o, index].into() + } else { + vec![index, o].into() + }; + + self.indexing_code + .push(IndexingLine::DynamicIndexedChoice(third_level_index)); + } + IndexingCodePtr::External(o) => { + *l = IndexingCodePtr::Internal(indexing_code_len - self.offset); + + let third_level_index = if self.append_or_prepend.is_append() { + vec![ + IndexedChoiceInstruction::Try(o), + IndexedChoiceInstruction::Trust(index), + ] + .into() + } else { + vec![ + IndexedChoiceInstruction::Try(index), + IndexedChoiceInstruction::Trust(o), + ] + .into() + }; + + self.indexing_code + .push(IndexingLine::IndexedChoice(third_level_index)); + } + IndexingCodePtr::Internal(o) => { + self.offset += o; + self.extend_indexed_choice(index); + } + }, _ => { unreachable!() } @@ -676,20 +670,18 @@ pub(crate) fn remove_constant_indices( let iter = once(&constant).chain(overlapping_constants.iter()); match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => { - match *c { - IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { - *c = IndexingCodePtr::Fail; - return; - } - IndexingCodePtr::Internal(o) => { - index += o; - } - IndexingCodePtr::Fail => { - return; - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, ..)) => match *c { + IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { + *c = IndexingCodePtr::Fail; + return; } - } + IndexingCodePtr::Internal(o) => { + index += o; + } + IndexingCodePtr::Fail => { + return; + } + }, _ => { unreachable!() } @@ -700,9 +692,7 @@ pub(crate) fn remove_constant_indices( for constant in iter.map(|l| HeapCellValue::from(*l)) { loop { match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant( - constants, - )) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => { constants_index = index; match constants.get(&constant).cloned() { @@ -819,20 +809,18 @@ pub(crate) fn remove_structure_index( let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { - match *s { - IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { - *s = IndexingCodePtr::Fail; - return; - } - IndexingCodePtr::Internal(o) => { - index += o; - } - IndexingCodePtr::Fail => { - return; - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => match *s { + IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { + *s = IndexingCodePtr::Fail; + return; } - } + IndexingCodePtr::Internal(o) => { + index += o; + } + IndexingCodePtr::Fail => { + return; + } + }, _ => { unreachable!() } @@ -932,13 +920,7 @@ pub(crate) fn remove_structure_index( if structures.is_empty() => { match &mut indexing_code[0] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( - _, - _, - _, - _, - s, - )) => { + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, _, s)) => { *s = IndexingCodePtr::Fail; } _ => { @@ -954,20 +936,18 @@ pub(crate) fn remove_list_index(indexing_code: &mut [IndexingLine], offset: usiz let mut index = 0; match &mut indexing_code[index] { - IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => { - match *l { - IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { - *l = IndexingCodePtr::Fail; - return; - } - IndexingCodePtr::Internal(o) => { - index += o; - } - IndexingCodePtr::Fail => { - return; - } + IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, _, l, _)) => match *l { + IndexingCodePtr::DynamicExternal(_) | IndexingCodePtr::External(_) => { + *l = IndexingCodePtr::Fail; + return; } - } + IndexingCodePtr::Internal(o) => { + index += o; + } + IndexingCodePtr::Fail => { + return; + } + }, _ => { unreachable!() } diff --git a/src/iterators.rs b/src/iterators.rs index eadeb093..fb318a44 100644 --- a/src/iterators.rs +++ b/src/iterators.rs @@ -90,7 +90,7 @@ impl<'a> QueryIterator<'a> { | Term::CompleteString(..) => { return QueryIterator { state_stack: vec![], - } + }; } Term::Clause(r, name, terms) => TermIterState::Clause(Level::Root, 0, r, *name, terms), Term::Var(cell, var_ptr) => TermIterState::Var(Level::Root, cell, var_ptr.clone()), @@ -143,7 +143,7 @@ impl<'a> Iterator for QueryIterator<'a> { return match lvl { Level::Root => None, lvl => Some(TermRef::Clause(lvl, cell, name, child_terms)), - } + }; } }; } else { @@ -293,7 +293,7 @@ impl<'a> Iterator for FactIterator<'a> { return Some(TermRef::CompleteString(lvl, cell, atom)); } TermIterState::Literal(lvl, cell, constant) => { - return Some(TermRef::Literal(lvl, cell, constant)) + return Some(TermRef::Literal(lvl, cell, constant)); } TermIterState::Var(lvl, cell, var_ptr) => { return Some(TermRef::Var(lvl, cell, var_ptr)); diff --git a/src/lib.rs b/src/lib.rs index ee73d4f2..d1677c43 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,9 +43,9 @@ mod targets; pub(crate) mod types; // Re-exports +pub use machine::Machine; pub use machine::config::*; pub use machine::lib_machine::*; -pub use machine::Machine; #[cfg(target_arch = "wasm32")] pub mod wasm; diff --git a/src/machine/arithmetic_ops.rs b/src/machine/arithmetic_ops.rs index 84105a38..92aa0ca9 100644 --- a/src/machine/arithmetic_ops.rs +++ b/src/machine/arithmetic_ops.rs @@ -1,6 +1,6 @@ use dashu::base::{Abs, Gcd, Signed, UnsignedAbs}; -use dashu::integer::fast_div::ConstDivisor; use dashu::integer::IBig; +use dashu::integer::fast_div::ConstDivisor; use divrem::*; use num_order::NumOrd; diff --git a/src/machine/compile.rs b/src/machine/compile.rs index c4789328..40b5275f 100644 --- a/src/machine/compile.rs +++ b/src/machine/compile.rs @@ -564,9 +564,7 @@ fn thread_choice_instr_at_to( ) { loop { match &mut code[instr_loc] { - Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) - if target_loc >= instr_loc => - { + Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) if target_loc >= instr_loc => { retraction_info.push_record(RetractionRecord::ReplacedChoiceOffset(instr_loc, *o)); *o = target_loc - instr_loc; @@ -1632,8 +1630,7 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { }; match &mut self.wam_prelude.code[clause_loc] { - Instruction::DynamicElse(_, d, _) - | Instruction::DynamicInternalElse(_, d, _) => { + Instruction::DynamicElse(_, d, _) | Instruction::DynamicInternalElse(_, d, _) => { *d = Death::Finite(LS::machine_st(&mut self.payload).global_clock); } _ => unreachable!(), diff --git a/src/machine/config.rs b/src/machine/config.rs index d4839d69..0471dcf4 100644 --- a/src/machine/config.rs +++ b/src/machine/config.rs @@ -1,14 +1,14 @@ use std::borrow::Cow; use std::io::Write; -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::{Receiver, Sender, channel}; -use rand::{rngs::StdRng, SeedableRng}; +use rand::{SeedableRng, rngs::StdRng}; use crate::Machine; use super::{ - bootstrapping_compile, current_dir, import_builtin_impls, libraries, load_module, Arena, Atom, - Callback, CompilationTarget, IndexStore, ListingSource, MachineArgs, MachineState, Stream, + Arena, Atom, Callback, CompilationTarget, IndexStore, ListingSource, MachineArgs, MachineState, + Stream, bootstrapping_compile, current_dir, import_builtin_impls, libraries, load_module, }; #[derive(Default)] diff --git a/src/machine/dispatch.rs b/src/machine/dispatch.rs index f0184122..46f9af13 100644 --- a/src/machine/dispatch.rs +++ b/src/machine/dispatch.rs @@ -1366,9 +1366,7 @@ impl Machine { let indexed_choice_instrs = match &self.code[p] { Instruction::IndexingCode(indexing_code) => match &indexing_code[oi as usize] { - IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => { - indexed_choice_instrs - } + IndexingLine::DynamicIndexedChoice(indexed_choice_instrs) => indexed_choice_instrs, _ => unreachable!(), }, _ => unreachable!(), diff --git a/src/machine/heap.rs b/src/machine/heap.rs index 37a30315..3353056f 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -57,38 +57,41 @@ struct InnerHeap { } impl InnerHeap { - unsafe fn grow(&mut self) -> bool { unsafe { - let new_cap = if self.byte_cap == 0 { - 256 * 256 * 8 - } else { - 2 * self.byte_cap - }; + unsafe fn grow(&mut self) -> bool { + unsafe { + let new_cap = if self.byte_cap == 0 { + 256 * 256 * 8 + } else { + 2 * self.byte_cap + }; - let new_layout = - alloc::Layout::from_size_align(new_cap, size_of::()).unwrap(); + let new_layout = + alloc::Layout::from_size_align(new_cap, size_of::()).unwrap(); - assert!( - new_layout.size() <= isize::MAX as usize, - "Allocation too large. We should probably GC (TODO)" - ); + assert!( + new_layout.size() <= isize::MAX as usize, + "Allocation too large. We should probably GC (TODO)" + ); - let new_ptr = if self.byte_cap == 0 { - alloc::alloc(new_layout) - } else { - let old_layout = - alloc::Layout::from_size_align(self.byte_cap, size_of::()).unwrap(); - alloc::realloc(self.ptr, old_layout, new_layout.size()) - }; + let new_ptr = if self.byte_cap == 0 { + alloc::alloc(new_layout) + } else { + let old_layout = + alloc::Layout::from_size_align(self.byte_cap, size_of::()) + .unwrap(); + alloc::realloc(self.ptr, old_layout, new_layout.size()) + }; - if !new_ptr.is_null() { - self.ptr = new_ptr; - self.byte_cap = new_cap; + if !new_ptr.is_null() { + self.ptr = new_ptr; + self.byte_cap = new_cap; - true - } else { - false + true + } else { + false + } } - }} + } } unsafe impl Send for Heap {} @@ -101,48 +104,52 @@ pub struct HeapStringScan<'a> { } // The heap_slice should be inside the heap -unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { unsafe { - let string_len = heap_slice - .iter() - .position(|b| *b == 0u8) - .unwrap_or(heap_slice.len()); - let zero_byte_addr = heap_slice.as_ptr().add(string_len); +unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { + unsafe { + let string_len = heap_slice + .iter() + .position(|b| *b == 0u8) + .unwrap_or(heap_slice.len()); + let zero_byte_addr = heap_slice.as_ptr().add(string_len); - let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); - let tail_idx = cell_index!( - (string_len + sentinel_len).next_multiple_of(ALIGN) - + if sentinel_len <= 1 { heap_index!(1) } else { 0 } - ); + let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); + let tail_idx = cell_index!( + (string_len + sentinel_len).next_multiple_of(ALIGN) + + if sentinel_len <= 1 { heap_index!(1) } else { 0 } + ); - let str_slice = &heap_slice[..string_len]; + let str_slice = &heap_slice[..string_len]; - HeapStringScan { - string: std::str::from_utf8_unchecked(str_slice), - tail_idx, + HeapStringScan { + string: std::str::from_utf8_unchecked(str_slice), + tail_idx, + } } -}} +} // Same as scan_slice_to_str but assumes that the slice is from the start of a string. // Can be used on strings out of the heap. -unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { unsafe { - let string_len = heap_slice - .iter() - .position(|b| *b == 0u8) - .unwrap_or(heap_slice.len()); +unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { + unsafe { + let string_len = heap_slice + .iter() + .position(|b| *b == 0u8) + .unwrap_or(heap_slice.len()); - let sentinel_len = pstr_sentinel_length(string_len); - let tail_idx = cell_index!( - (string_len + sentinel_len).next_multiple_of(ALIGN) - + if sentinel_len <= 1 { heap_index!(1) } else { 0 } - ); + let sentinel_len = pstr_sentinel_length(string_len); + let tail_idx = cell_index!( + (string_len + sentinel_len).next_multiple_of(ALIGN) + + if sentinel_len <= 1 { heap_index!(1) } else { 0 } + ); - let str_slice = &heap_slice[..string_len]; + let str_slice = &heap_slice[..string_len]; - HeapStringScan { - string: std::str::from_utf8_unchecked(str_slice), - tail_idx, + HeapStringScan { + string: std::str::from_utf8_unchecked(str_slice), + tail_idx, + } } -}} +} #[derive(Debug, Clone, Copy)] pub(crate) enum PStrContinuable { @@ -450,11 +457,7 @@ fn pstr_sentinel_length(chunk_len: usize) -> usize { let res = chunk_len.next_multiple_of(ALIGN) - chunk_len; // No bytes available in last chunk - if res == 0 { - ALIGN - } else { - res - } + if res == 0 { ALIGN } else { res } } #[must_use] @@ -585,9 +588,9 @@ impl Heap { } #[inline(always)] - unsafe fn grow(&mut self) -> bool { unsafe { - self.inner.grow() - }} + unsafe fn grow(&mut self) -> bool { + unsafe { self.inner.grow() } + } #[inline] fn resource_error_offset(&self) -> usize { diff --git a/src/machine/lib_machine/mod.rs b/src/machine/lib_machine/mod.rs index 75aeffc6..069cf3e7 100644 --- a/src/machine/lib_machine/mod.rs +++ b/src/machine/lib_machine/mod.rs @@ -3,23 +3,23 @@ use std::collections::BTreeMap; use std::rc::Rc; use crate::atom_table; -use crate::heap_iter::{stackful_post_order_iter, NonListElider}; +use crate::heap_iter::{NonListElider, stackful_post_order_iter}; use crate::machine::heap::AllocError; use crate::machine::machine_indices::VarKey; use crate::machine::mock_wam::CompositeOpDir; use crate::machine::{ - ArenaHeaderTag, Fixnum, Number, BREAK_FROM_DISPATCH_LOOP_LOC, LIB_QUERY_SUCCESS, + ArenaHeaderTag, BREAK_FROM_DISPATCH_LOOP_LOC, Fixnum, LIB_QUERY_SUCCESS, Number, }; use crate::offset_table::*; use crate::parser::ast::{Var, VarPtr}; use crate::parser::parser::{Parser, Tokens}; -use crate::read::{write_term_to_heap, TermWriteResult}; +use crate::read::{TermWriteResult, write_term_to_heap}; use crate::types::UntypedArenaPtr; use dashu::{Integer, Rational}; use indexmap::IndexMap; -use super::{streams::Stream, Atom, AtomCell, HeapCellValue, HeapCellValueTag, Machine}; +use super::{Atom, AtomCell, HeapCellValue, HeapCellValueTag, Machine, streams::Stream}; #[cfg(test)] mod tests; diff --git a/src/machine/loader.rs b/src/machine/loader.rs index 26508756..0e31e8a0 100644 --- a/src/machine/loader.rs +++ b/src/machine/loader.rs @@ -819,11 +819,8 @@ impl<'a, LS: LoadState<'a>> Loader<'a, LS> { if let Instruction::IndexingCode(ref mut indexing_code) = self.wam_prelude.code[index_loc] { - if let IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm( - _, - v, - .., - )) = &mut indexing_code[0] + if let IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, ..)) = + &mut indexing_code[0] { *v = old_v; } @@ -1364,14 +1361,12 @@ impl<'a> MachinePreludeView<'a> { ) -> CompositeOpDir<'_, '_> { match compilation_target { CompilationTarget::User => CompositeOpDir::new(&self.indices.op_dir, None), - CompilationTarget::Module(module_name) => { - match self.indices.modules.get(module_name) { - Some(module) => CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir)), - None => { - unreachable!() - } + CompilationTarget::Module(module_name) => match self.indices.modules.get(module_name) { + Some(module) => CompositeOpDir::new(&self.indices.op_dir, Some(&module.op_dir)), + None => { + unreachable!() } - } + }, } } } @@ -1504,9 +1499,10 @@ impl Machine { } pub(crate) fn load_compiled_library(&mut self) -> CallResult { - let library = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let library = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); if let Some(module) = self.indices.modules.get(&library) { if let ListingSource::DynamicallyGenerated = module.listing_src { @@ -1537,9 +1533,10 @@ impl Machine { } pub(crate) fn declare_module(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let mut loader = self.loader_from_heap_evacuable(temp_v!(3)); @@ -1649,9 +1646,10 @@ impl Machine { } pub(crate) fn add_goal_expansion_clause(&mut self) -> CallResult { - let target_module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let target_module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let mut loader = self.loader_from_heap_evacuable(temp_v!(3)); @@ -1744,9 +1742,10 @@ impl Machine { &mut self, r: RegType, ) -> Loader<'_, LiveLoadAndMachineState<'_>> { - let mut load_state = cell_as_load_state_payload!(self - .machine_st - .store(self.machine_st.deref(self.machine_st[r]))); + let mut load_state = cell_as_load_state_payload!( + self.machine_st + .store(self.machine_st.deref(self.machine_st[r])) + ); load_state.set_tag(ArenaHeaderTag::LiveLoadState); @@ -2098,9 +2097,10 @@ impl Machine { } pub(crate) fn abolish_clause(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2214,9 +2214,10 @@ impl Machine { _ => unreachable!(), }; - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[4]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[4])) + ); let compilation_target = match module_name { atom!("user") => CompilationTarget::User, @@ -2269,9 +2270,10 @@ impl Machine { } pub(crate) fn is_consistent_with_term_queue(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2309,9 +2311,10 @@ impl Machine { } pub(crate) fn remove_module_exports(&mut self) -> CallResult { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let mut loader = self.loader_from_heap_evacuable(temp_v!(2)); @@ -2337,9 +2340,10 @@ impl Machine { } pub(crate) fn meta_predicate_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let (predicate_name, arity) = self .machine_st @@ -2401,9 +2405,10 @@ impl Machine { } pub(crate) fn dynamic_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2428,9 +2433,10 @@ impl Machine { } pub(crate) fn multifile_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st @@ -2455,9 +2461,10 @@ impl Machine { } pub(crate) fn discontiguous_property(&mut self) { - let module_name = cell_as_atom!(self - .machine_st - .store(self.machine_st.deref(self.machine_st.registers[1]))); + let module_name = cell_as_atom!( + self.machine_st + .store(self.machine_st.deref(self.machine_st.registers[1])) + ); let key = self .machine_st diff --git a/src/machine/machine_errors.rs b/src/machine/machine_errors.rs index c07e18ce..26320951 100644 --- a/src/machine/machine_errors.rs +++ b/src/machine/machine_errors.rs @@ -777,7 +777,9 @@ impl MachineState { // throw an error pre-allocated in the heap pub(super) fn throw_resource_error(&mut self, err: AllocError) { if self.throwing_resource_error { - panic!("attempted to throw `error(resource_error(memory), [])` while attempting to throw `error(resource_error(memory), [])`"); + panic!( + "attempted to throw `error(resource_error(memory), [])` while attempting to throw `error(resource_error(memory), [])`" + ); } self.throwing_resource_error = true; diff --git a/src/machine/machine_indices.rs b/src/machine/machine_indices.rs index e452786b..5b69986d 100644 --- a/src/machine/machine_indices.rs +++ b/src/machine/machine_indices.rs @@ -2,17 +2,17 @@ use crate::parser::ast::*; use crate::atom_table::*; use crate::forms::*; +use crate::machine::ClauseType; +use crate::machine::MachineStubGen; use crate::machine::loader::*; use crate::machine::machine_state::*; use crate::machine::streams::{Stream, StreamOptions}; -use crate::machine::ClauseType; -use crate::machine::MachineStubGen; use crate::offset_table::*; use fxhash::FxBuildHasher; use indexmap::{IndexMap, IndexSet}; use modular_bitfield::specifiers::*; -use modular_bitfield::{bitfield, Specifier}; +use modular_bitfield::{Specifier, bitfield}; use std::cmp::Ordering; use std::collections::BTreeSet; diff --git a/src/machine/machine_state.rs b/src/machine/machine_state.rs index 32b86aeb..d9f95cbf 100644 --- a/src/machine/machine_state.rs +++ b/src/machine/machine_state.rs @@ -3,6 +3,7 @@ use crate::atom_table::*; use crate::forms::*; use crate::heap_iter::*; use crate::heap_print::*; +use crate::machine::Machine; use crate::machine::attributed_variables::*; use crate::machine::copier::*; use crate::machine::heap::AllocError; @@ -11,7 +12,6 @@ use crate::machine::machine_errors::*; use crate::machine::machine_indices::*; use crate::machine::stack::*; use crate::machine::streams::*; -use crate::machine::Machine; use crate::parser::ast::*; use crate::read::TermWriteResult; use crate::types::*; diff --git a/src/machine/mod.rs b/src/machine/mod.rs index f7a21bf8..ed4de159 100644 --- a/src/machine/mod.rs +++ b/src/machine/mod.rs @@ -61,8 +61,8 @@ use std::env; use std::io::Read; use std::path::PathBuf; use std::process::ExitCode; -use std::sync::atomic::AtomicBool; use std::sync::OnceLock; +use std::sync::atomic::AtomicBool; pub static INTERRUPT: AtomicBool = AtomicBool::new(false); diff --git a/src/machine/preprocessor.rs b/src/machine/preprocessor.rs index 1cfa8bb0..c1b3d344 100644 --- a/src/machine/preprocessor.rs +++ b/src/machine/preprocessor.rs @@ -37,7 +37,7 @@ fn setup_op_decl(mut terms: Vec) -> Result { other => { return Err(CompilationError::InvalidDirective( DirectiveError::InvalidOpDeclSpecDomain(other), - )) + )); } }; diff --git a/src/machine/stack.rs b/src/machine/stack.rs index 258cfdd2..df9cd111 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -175,15 +175,17 @@ impl Stack { } #[inline(always)] - unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { unsafe { - loop { - let ptr = self.buf.alloc(frame_size); - if let Some(ptr) = NonNull::new(ptr) { - return Ok(ptr); + unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { + unsafe { + loop { + let ptr = self.buf.alloc(frame_size); + if let Some(ptr) = NonNull::new(ptr) { + return Ok(ptr); + } + self.buf.grow()?; } - self.buf.grow()?; } - }} + } pub(crate) fn allocate_and_frame(&mut self, num_cells: usize) -> Result { let frame_size = AndFrame::size_of(num_cells); diff --git a/src/machine/streams.rs b/src/machine/streams.rs index 5fdf5c01..26afde37 100644 --- a/src/machine/streams.rs +++ b/src/machine/streams.rs @@ -15,7 +15,7 @@ use crate::types::*; pub use modular_bitfield::prelude::*; #[cfg(feature = "http")] -use bytes::{buf::Reader as BufReader, Buf, Bytes}; +use bytes::{Buf, Bytes, buf::Reader as BufReader}; use std::cmp::Ordering; use std::error::Error; use std::fmt; @@ -2195,8 +2195,8 @@ mod test { use crate::*; use std::{cell::RefCell, io::Read, io::Write, rc::Rc}; - use crate::machine::config::*; use crate::LeafAnswer; + use crate::machine::config::*; use super::{Stream, StreamOptions}; diff --git a/src/machine/system_calls.rs b/src/machine/system_calls.rs index 5c859ba4..18fb8896 100644 --- a/src/machine/system_calls.rs +++ b/src/machine/system_calls.rs @@ -24,7 +24,7 @@ use crate::machine::machine_state::*; use crate::machine::partial_string::*; use crate::machine::stack::*; use crate::machine::streams::*; -use crate::machine::{get_structure_index, Machine}; +use crate::machine::{Machine, get_structure_index}; use crate::parser::ast::*; use crate::parser::char_reader::*; use crate::parser::dashu::Integer; @@ -48,7 +48,7 @@ use std::ffi::CString; use std::fs; use std::hash::{BuildHasher, BuildHasherDefault}; use std::io::{ErrorKind, Read, Write}; -use std::iter::{once, FromIterator}; +use std::iter::{FromIterator, once}; use std::mem; #[cfg(feature = "http")] use std::net::{SocketAddr, ToSocketAddrs}; @@ -63,13 +63,13 @@ use std::sync::LazyLock; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::Notify; -use chrono::{offset::Local, DateTime}; +use chrono::{DateTime, offset::Local}; #[cfg(not(target_arch = "wasm32"))] use cpu_time::ProcessTime; use std::time::{Duration, SystemTime}; #[cfg(feature = "repl")] -use crate::read::user_interaction::{get_key, KeyCode, KeyModifiers}; +use crate::read::user_interaction::{KeyCode, KeyModifiers, get_key}; use blake2::{Blake2b512, Blake2s256}; diff --git a/src/machine/system_calls/special_math.rs b/src/machine/system_calls/special_math.rs index 57e933f9..925345f1 100644 --- a/src/machine/system_calls/special_math.rs +++ b/src/machine/system_calls/special_math.rs @@ -1,5 +1,5 @@ -use crate::machine::Number; use crate::Machine; +use crate::machine::Number; use ordered_float::OrderedFloat; use puruspe::beta::*; use puruspe::error::*; diff --git a/src/machine/unify.rs b/src/machine/unify.rs index 58015ea6..4b28cd36 100644 --- a/src/machine/unify.rs +++ b/src/machine/unify.rs @@ -1,6 +1,6 @@ use crate::arena::*; use crate::forms::*; -use crate::heap_iter::{stackful_preorder_iter, NonListElider}; +use crate::heap_iter::{NonListElider, stackful_preorder_iter}; use crate::machine::machine_state::*; use crate::machine::*; use crate::offset_table::*; diff --git a/src/macros.rs b/src/macros.rs index 659eef4b..3cd39596 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -138,9 +138,7 @@ macro_rules! typed_arena_ptr_as_cell { } macro_rules! raw_ptr_as_cell { - ($ptr:expr) => {{ - HeapCellValue::from_arena_header_ptr($ptr) - }}; + ($ptr:expr) => {{ HeapCellValue::from_arena_header_ptr($ptr) }}; } macro_rules! untyped_arena_ptr_as_cell { diff --git a/src/offset_table.rs b/src/offset_table.rs index f496ca54..849fead6 100644 --- a/src/offset_table.rs +++ b/src/offset_table.rs @@ -2,10 +2,10 @@ use std::cell::UnsafeCell; use std::sync::Arc; use std::{fmt, mem, ptr}; +use arcu::Rcu; use arcu::atomic::Arcu; use arcu::epoch_counters::GlobalEpochCounterPool; use arcu::rcu_ref::RcuRef; -use arcu::Rcu; use fxhash::FxBuildHasher; use indexmap::IndexMap; use parking_lot::{Mutex, RwLock}; @@ -211,7 +211,7 @@ impl SerialOffsetTable { }) } - unsafe fn build_with(&mut self, value: T) -> usize { unsafe { + unsafe fn build_with(&mut self, value: T) -> usize { let mut ptr; loop { @@ -228,17 +228,17 @@ impl SerialOffsetTable { ptr::write(ptr as *mut T, value); // SAFETY: `ptr` was obtained from `self.block.alloc()` self.block.get_offset(ptr) - }} + } #[inline] - unsafe fn lookup(&self, offset: usize) -> &T { unsafe { + unsafe fn lookup(&self, offset: usize) -> &T { &*self.block.get_unchecked(offset).cast::() - }} + } #[inline] - unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { unsafe { + unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { &mut *self.block.get_unchecked(offset).cast::().cast_mut() - }} + } #[allow(clippy::wrong_self_convention)] fn to_concurrent(&mut self) -> ConcurrentOffsetTable diff --git a/src/parser/ast.rs b/src/parser/ast.rs index fb835611..4e4bf052 100644 --- a/src/parser/ast.rs +++ b/src/parser/ast.rs @@ -362,11 +362,7 @@ impl OpDesc { #[inline] pub fn arity(self) -> usize { - if !self.get_spec().is_infix() { - 1 - } else { - 2 - } + if !self.get_spec().is_infix() { 1 } else { 2 } } } diff --git a/src/parser/lexer.rs b/src/parser/lexer.rs index e617c7d9..3cbde243 100644 --- a/src/parser/lexer.rs +++ b/src/parser/lexer.rs @@ -85,7 +85,7 @@ macro_rules! try_nt { Ok(NumberToken::Partial($token)) } else { Err(e) - } + }; } } }}; @@ -771,7 +771,7 @@ impl<'a, R: CharRead> Lexer<'a, R> { Err(_) => { return self .vacate_with_float(token) - .map(|(offset, fl)| NumberToken::Float(offset, fl)) + .map(|(offset, fl)| NumberToken::Float(offset, fl)); } Ok(c) => c, }; diff --git a/src/read.rs b/src/read.rs index f0346ad2..45a06f7e 100644 --- a/src/read.rs +++ b/src/read.rs @@ -102,13 +102,7 @@ pub(crate) fn set_prompt(value: bool) { #[cfg(feature = "repl")] #[inline] fn get_prompt() -> &'static str { - unsafe { - if PROMPT { - "?- " - } else { - "" - } - } + unsafe { if PROMPT { "?- " } else { "" } } } thread_local! { diff --git a/src/read/user_interaction.rs b/src/read/user_interaction.rs index e6eab103..a0c96511 100644 --- a/src/read/user_interaction.rs +++ b/src/read/user_interaction.rs @@ -1,4 +1,4 @@ -use crossterm::event::{read, Event, KeyEventKind}; +use crossterm::event::{Event, KeyEventKind, read}; pub(crate) use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::tty::IsTty; diff --git a/src/types.rs b/src/types.rs index 9cec6926..7de134a5 100644 --- a/src/types.rs +++ b/src/types.rs @@ -761,9 +761,9 @@ impl UntypedArenaPtr { pub unsafe fn as_typed_ptr(self) -> TypedArenaPtr where T::Payload: Sized, - { unsafe { - T::typed_ptr(self) - }} + { + unsafe { T::typed_ptr(self) } + } #[inline] pub fn get_mark_bit(self) -> bool { diff --git a/src/variable_records.rs b/src/variable_records.rs index 2e05634a..9565b2da 100644 --- a/src/variable_records.rs +++ b/src/variable_records.rs @@ -106,9 +106,7 @@ impl VarAlloc { pub(crate) fn set_register(&mut self, reg_num: usize) { match self { VarAlloc::Perm(p, _) => *p = reg_num, - VarAlloc::Temp { - temp_reg, .. - } => *temp_reg = reg_num, + VarAlloc::Temp { temp_reg, .. } => *temp_reg = reg_num, }; } } diff --git a/tests/scryer/issues.rs b/tests/scryer/issues.rs index ac8c21d9..bfbd5303 100644 --- a/tests/scryer/issues.rs +++ b/tests/scryer/issues.rs @@ -16,7 +16,10 @@ fn call_0() { #[test] #[cfg_attr(miri, ignore = "unsupported operation when isolation is enabled")] fn issue2588_load_html() { - load_module_test("tests-pl/issue2588.pl", "[element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])]"); + load_module_test( + "tests-pl/issue2588.pl", + "[element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])]", + ); } // issue #2914 @@ -38,7 +41,10 @@ fn issue3256_load_xml_returns_list() { #[test] #[cfg_attr(miri, ignore = "unsupported operation when isolation is enabled")] fn issue2949_load_html() { - load_module_test("tests-pl/issue2949.pl", "[doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])][doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]]),comment([ ,c,o,m,m,e,n,t, ])]),element(body,[],[])])][comment([]),element(html,[],[element(head,[],[]),element(body,[],[])])]"); + load_module_test( + "tests-pl/issue2949.pl", + "[doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]])]),element(body,[],[])])][doctype([h,t,m,l]),element(html,[],[element(head,[],[element(title,[],[[H,e,l,l,o,!]]),comment([ ,c,o,m,m,e,n,t, ])]),element(body,[],[])])][comment([]),element(html,[],[element(head,[],[]),element(body,[],[])])]", + ); } // issue #2361 @@ -168,7 +174,7 @@ async fn http_open_hanging() { load_module_test_with_input( "tests-pl/issue-http_open-hanging.pl", format!("PROLOG={:?}.", env!("CARGO_BIN_EXE_scryer-prolog")), - "received response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\n" + "received response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\nreceived response with status code:200\n", ); } From 83218bf0dab4950e4736f848a5d7f434b0e26a3d Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Sat, 4 Apr 2026 13:37:42 -0400 Subject: [PATCH 03/10] Issue 3223: make `unsafe` scopes tighter --- src/arena.rs | 5 ++--- src/atom_table.rs | 2 -- src/ffi.rs | 20 ++++++++++---------- src/machine/heap.rs | 10 +++++----- src/machine/stack.rs | 2 +- src/read.rs | 2 +- 6 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index f8cd9695..53bf5cc2 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -496,14 +496,13 @@ impl Arena { } } -unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { - unsafe { +unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { macro_rules! drop_typed_slab_in_place { ($payload: ty, $value: expr) => { <$payload as ArenaAllocated>::dealloc($value.cast::>()) }; } - + unsafe { match tag { ArenaHeaderTag::Integer => { drop_typed_slab_in_place!(Integer, value); diff --git a/src/atom_table.rs b/src/atom_table.rs index 5292d208..3e156b35 100644 --- a/src/atom_table.rs +++ b/src/atom_table.rs @@ -386,8 +386,6 @@ impl Atom { unsafe fn write_to_ptr(string: &str, ptr: *mut u8) { unsafe { ptr::write(ptr as *mut _, AtomHeader::build_with(string.len() as u64)); - } - unsafe { let str_ptr = ptr.add(mem::size_of::()); ptr::copy_nonoverlapping(string.as_ptr(), str_ptr, string.len()); } diff --git a/src/ffi.rs b/src/ffi.rs index d319cfc7..8cfc2979 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -56,8 +56,8 @@ impl FunctionImpl { unsafe fn call_void(&self, args: &[Arg], _: &mut Arena) -> Result { unsafe { self.cif.call_return_into(self.code_ptr, args, Ret::void()); - Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) } + Ok(Value::Number(Number::Fixnum(Fixnum::build_with(0)))) } unsafe fn call_int(&self, args: &[Arg], arena: &mut Arena) -> Result @@ -204,14 +204,14 @@ impl StructImpl { layout: &mut Layout, val: T, ) -> Result<(), FfiError> { + let (new_layout, offset) = layout + .extend(Layout::new::()) + .map_err(|_| FfiError::LayoutError)?; + *layout = new_layout; unsafe { - let (new_layout, offset) = layout - .extend(Layout::new::()) - .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; ptr.byte_offset(offset as isize).cast::().write(val); - Ok(()) } + Ok(()) } for arg in args { @@ -267,11 +267,11 @@ impl StructImpl { ptr: *mut c_void, layout: &mut Layout, ) -> Result { + let (new_layout, offset) = layout + .extend(Layout::new::()) + .map_err(|_| FfiError::LayoutError)?; + *layout = new_layout; unsafe { - let (new_layout, offset) = layout - .extend(Layout::new::()) - .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); Ok(n) } diff --git a/src/machine/heap.rs b/src/machine/heap.rs index 3353056f..ba39c028 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -58,7 +58,6 @@ struct InnerHeap { impl InnerHeap { unsafe fn grow(&mut self) -> bool { - unsafe { let new_cap = if self.byte_cap == 0 { 256 * 256 * 8 } else { @@ -72,7 +71,7 @@ impl InnerHeap { new_layout.size() <= isize::MAX as usize, "Allocation too large. We should probably GC (TODO)" ); - + unsafe { let new_ptr = if self.byte_cap == 0 { alloc::alloc(new_layout) } else { @@ -105,11 +104,12 @@ pub struct HeapStringScan<'a> { // The heap_slice should be inside the heap unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { - unsafe { let string_len = heap_slice .iter() .position(|b| *b == 0u8) .unwrap_or(heap_slice.len()); + + unsafe { let zero_byte_addr = heap_slice.as_ptr().add(string_len); let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); @@ -130,7 +130,6 @@ unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { // Same as scan_slice_to_str but assumes that the slice is from the start of a string. // Can be used on strings out of the heap. unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { - unsafe { let string_len = heap_slice .iter() .position(|b| *b == 0u8) @@ -143,7 +142,8 @@ unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> ); let str_slice = &heap_slice[..string_len]; - + + unsafe { HeapStringScan { string: std::str::from_utf8_unchecked(str_slice), tail_idx, diff --git a/src/machine/stack.rs b/src/machine/stack.rs index df9cd111..598a4846 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -176,8 +176,8 @@ impl Stack { #[inline(always)] unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { - unsafe { loop { + unsafe { let ptr = self.buf.alloc(frame_size); if let Some(ptr) = NonNull::new(ptr) { return Ok(ptr); diff --git a/src/read.rs b/src/read.rs index 45a06f7e..7ff88f41 100644 --- a/src/read.rs +++ b/src/read.rs @@ -102,7 +102,7 @@ pub(crate) fn set_prompt(value: bool) { #[cfg(feature = "repl")] #[inline] fn get_prompt() -> &'static str { - unsafe { if PROMPT { "?- " } else { "" } } + if unsafe { PROMPT } { "?- " } else { "" } } thread_local! { From 9d49415449b39216aa9b5cf66814efe2f7425bfb Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Sat, 4 Apr 2026 13:41:52 -0400 Subject: [PATCH 04/10] Issue 3223: reformat via `cargo fmt` --- src/arena.rs | 12 ++++----- src/machine/heap.rs | 58 ++++++++++++++++++++++---------------------- src/machine/stack.rs | 4 +-- src/read.rs | 2 +- 4 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/arena.rs b/src/arena.rs index 53bf5cc2..7f656772 100644 --- a/src/arena.rs +++ b/src/arena.rs @@ -496,12 +496,12 @@ impl Arena { } } -unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { - macro_rules! drop_typed_slab_in_place { - ($payload: ty, $value: expr) => { - <$payload as ArenaAllocated>::dealloc($value.cast::>()) - }; - } +unsafe fn drop_slab_in_place(value: NonNull, tag: ArenaHeaderTag) { + macro_rules! drop_typed_slab_in_place { + ($payload: ty, $value: expr) => { + <$payload as ArenaAllocated>::dealloc($value.cast::>()) + }; + } unsafe { match tag { ArenaHeaderTag::Integer => { diff --git a/src/machine/heap.rs b/src/machine/heap.rs index ba39c028..a59bdb16 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -58,20 +58,20 @@ struct InnerHeap { impl InnerHeap { unsafe fn grow(&mut self) -> bool { - let new_cap = if self.byte_cap == 0 { - 256 * 256 * 8 - } else { - 2 * self.byte_cap - }; + let new_cap = if self.byte_cap == 0 { + 256 * 256 * 8 + } else { + 2 * self.byte_cap + }; - let new_layout = - alloc::Layout::from_size_align(new_cap, size_of::()).unwrap(); + let new_layout = + alloc::Layout::from_size_align(new_cap, size_of::()).unwrap(); - assert!( - new_layout.size() <= isize::MAX as usize, - "Allocation too large. We should probably GC (TODO)" - ); - unsafe { + assert!( + new_layout.size() <= isize::MAX as usize, + "Allocation too large. We should probably GC (TODO)" + ); + unsafe { let new_ptr = if self.byte_cap == 0 { alloc::alloc(new_layout) } else { @@ -104,12 +104,12 @@ pub struct HeapStringScan<'a> { // The heap_slice should be inside the heap unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { - let string_len = heap_slice - .iter() - .position(|b| *b == 0u8) - .unwrap_or(heap_slice.len()); - - unsafe { + let string_len = heap_slice + .iter() + .position(|b| *b == 0u8) + .unwrap_or(heap_slice.len()); + + unsafe { let zero_byte_addr = heap_slice.as_ptr().add(string_len); let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); @@ -130,19 +130,19 @@ unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { // Same as scan_slice_to_str but assumes that the slice is from the start of a string. // Can be used on strings out of the heap. unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> { - let string_len = heap_slice - .iter() - .position(|b| *b == 0u8) - .unwrap_or(heap_slice.len()); + let string_len = heap_slice + .iter() + .position(|b| *b == 0u8) + .unwrap_or(heap_slice.len()); - let sentinel_len = pstr_sentinel_length(string_len); - let tail_idx = cell_index!( - (string_len + sentinel_len).next_multiple_of(ALIGN) - + if sentinel_len <= 1 { heap_index!(1) } else { 0 } - ); + let sentinel_len = pstr_sentinel_length(string_len); + let tail_idx = cell_index!( + (string_len + sentinel_len).next_multiple_of(ALIGN) + + if sentinel_len <= 1 { heap_index!(1) } else { 0 } + ); + + let str_slice = &heap_slice[..string_len]; - let str_slice = &heap_slice[..string_len]; - unsafe { HeapStringScan { string: std::str::from_utf8_unchecked(str_slice), diff --git a/src/machine/stack.rs b/src/machine/stack.rs index 598a4846..b942557a 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -176,8 +176,8 @@ impl Stack { #[inline(always)] unsafe fn alloc(&mut self, frame_size: usize) -> Result, AllocError> { - loop { - unsafe { + loop { + unsafe { let ptr = self.buf.alloc(frame_size); if let Some(ptr) = NonNull::new(ptr) { return Ok(ptr); diff --git a/src/read.rs b/src/read.rs index 7ff88f41..efa9d547 100644 --- a/src/read.rs +++ b/src/read.rs @@ -102,7 +102,7 @@ pub(crate) fn set_prompt(value: bool) { #[cfg(feature = "repl")] #[inline] fn get_prompt() -> &'static str { - if unsafe { PROMPT } { "?- " } else { "" } + if unsafe { PROMPT } { "?- " } else { "" } } thread_local! { From fbc5345c9a602a696b8903c3892148911c678bb4 Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Wed, 8 Apr 2026 19:39:05 -0400 Subject: [PATCH 05/10] Issue 3223: more `unsafe` scope refinements --- src/ffi.rs | 27 ++++++++------------------ src/machine/heap.rs | 46 +++++++++++++++++++++------------------------ 2 files changed, 29 insertions(+), 44 deletions(-) diff --git a/src/ffi.rs b/src/ffi.rs index 8cfc2979..125930eb 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -65,20 +65,16 @@ impl FunctionImpl { Integer: From, T: Copy + TryInto + MightNotFitInFixnum, { - unsafe { - let n = self.cif.call::(self.code_ptr, args); + let n = unsafe { self.cif.call::(self.code_ptr, args) }; Ok(Value::Number(fixnum!(Number, n, arena))) - } } unsafe fn call_float(&self, args: &[Arg], _: &mut Arena) -> Result where T: Into, { - unsafe { - let n = self.cif.call::(self.code_ptr, args); + let n = unsafe { self.cif.call::(self.code_ptr, args) }; Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - } } unsafe fn call_ptr(&self, args: &[Arg], arena: &mut Arena) -> Result { @@ -270,11 +266,9 @@ impl StructImpl { let (new_layout, offset) = layout .extend(Layout::new::()) .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; - unsafe { - let n = std::ptr::read::(ptr.byte_offset(offset as isize).cast()); + *layout = new_layout; + let n = unsafe { std::ptr::read::(ptr.byte_offset(offset as isize).cast()) }; Ok(n) - } } unsafe fn read_int( @@ -286,10 +280,9 @@ impl StructImpl { T: Copy + TryInto + MightNotFitInFixnum, Integer: From, { - unsafe { - let n = read_primitive::(ptr, layout)?; + + let n = unsafe { read_primitive::(ptr, layout)? }; Ok(Value::Number(fixnum!(Number, n, arena))) - } } unsafe fn read_float( @@ -299,10 +292,8 @@ impl StructImpl { where T: Into, { - unsafe { - let n = read_primitive::(ptr, layout)?; + let n = unsafe { read_primitive::(ptr, layout)? }; Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) - } } let mut layout = Layout::from_size_align(0, 1).map_err(|_| FfiError::LayoutError)?; @@ -803,10 +794,8 @@ impl ForeignFunctionTable { T: Copy + TryInto + MightNotFitInFixnum, Integer: From, { - unsafe { - let n = ptr.cast::().read(); + let n = unsafe { ptr.cast::().read() }; Value::Number(fixnum!(Number, n, arena)) - } } let ptr = ptr.as_ptr()?; diff --git a/src/machine/heap.rs b/src/machine/heap.rs index a59bdb16..12a0e40a 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -71,14 +71,16 @@ impl InnerHeap { new_layout.size() <= isize::MAX as usize, "Allocation too large. We should probably GC (TODO)" ); - unsafe { - let new_ptr = if self.byte_cap == 0 { - alloc::alloc(new_layout) - } else { - let old_layout = - alloc::Layout::from_size_align(self.byte_cap, size_of::()) - .unwrap(); - alloc::realloc(self.ptr, old_layout, new_layout.size()) + + let new_ptr = unsafe { + if self.byte_cap == 0 { + alloc::alloc(new_layout) + } else { + let old_layout = + alloc::Layout::from_size_align(self.byte_cap, size_of::()) + .unwrap(); + alloc::realloc(self.ptr, old_layout, new_layout.size()) + } }; if !new_ptr.is_null() { @@ -89,7 +91,6 @@ impl InnerHeap { } else { false } - } } } @@ -109,8 +110,7 @@ unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { .position(|b| *b == 0u8) .unwrap_or(heap_slice.len()); - unsafe { - let zero_byte_addr = heap_slice.as_ptr().add(string_len); + let zero_byte_addr = unsafe { heap_slice.as_ptr().add(string_len) }; let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); let tail_idx = cell_index!( @@ -121,10 +121,9 @@ unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { let str_slice = &heap_slice[..string_len]; HeapStringScan { - string: std::str::from_utf8_unchecked(str_slice), + string: unsafe { std::str::from_utf8_unchecked(str_slice) }, tail_idx, } - } } // Same as scan_slice_to_str but assumes that the slice is from the start of a string. @@ -143,12 +142,10 @@ unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> let str_slice = &heap_slice[..string_len]; - unsafe { HeapStringScan { - string: std::str::from_utf8_unchecked(str_slice), + string: unsafe { std::str::from_utf8_unchecked(str_slice) }, tail_idx, } - } } #[derive(Debug, Clone, Copy)] @@ -282,19 +279,21 @@ impl ReservedHeapSection { src.as_ptr(), self.heap_ptr.add(heap_index!(self.heap_cell_len)), str_byte_len, - ); + ) + }; let zero_region_idx = heap_index!(self.heap_cell_len) + str_byte_len; let align_offset = pstr_sentinel_length(zero_region_idx); - ptr::write_bytes(self.heap_ptr.add(zero_region_idx), 0u8, align_offset); + unsafe { ptr::write_bytes(self.heap_ptr.add(zero_region_idx), 0u8, align_offset) }; cells_written = if align_offset == 1 { - ptr::write_bytes( + unsafe { ptr::write_bytes( self.heap_ptr.add(zero_region_idx + 1), 0u8, size_of::(), - ); + ) + }; // ensure there are at least two bytes in the boundary // buffer separating the string data from the tail @@ -305,7 +304,6 @@ impl ReservedHeapSection { }; self.heap_cell_len += cells_written; - } cells_written } @@ -629,17 +627,15 @@ impl Heap { let len = heap_index_checked!(num_cells).ok_or(AllocError)?; loop { - unsafe { if self.free_space() >= len { section = ReservedHeapSection { heap_ptr: self.inner.ptr, heap_cell_len: self.cell_len(), }; break; - } else if !self.grow() { + } else if unsafe { !self.grow() } { return Err(AllocError); } - } } Ok(HeapWriter { @@ -868,8 +864,8 @@ impl Heap { let align_offset = pstr_sentinel_length(s_len); let copy_size = s_len + align_offset; - unsafe { loop { + unsafe { if self.free_space() >= copy_size { let slice = std::slice::from_raw_parts_mut(self.inner.ptr, self.inner.byte_len + s_len); From 091af28368654e9a4c9d0e6eb34fc4dd25dd3e30 Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Wed, 8 Apr 2026 19:39:48 -0400 Subject: [PATCH 06/10] Issue 3223: reformat via `cargo fmt` --- src/ffi.rs | 27 +++++------ src/machine/heap.rs | 113 ++++++++++++++++++++++---------------------- 2 files changed, 70 insertions(+), 70 deletions(-) diff --git a/src/ffi.rs b/src/ffi.rs index 125930eb..15f77a7f 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -65,16 +65,16 @@ impl FunctionImpl { Integer: From, T: Copy + TryInto + MightNotFitInFixnum, { - let n = unsafe { self.cif.call::(self.code_ptr, args) }; - Ok(Value::Number(fixnum!(Number, n, arena))) + let n = unsafe { self.cif.call::(self.code_ptr, args) }; + Ok(Value::Number(fixnum!(Number, n, arena))) } unsafe fn call_float(&self, args: &[Arg], _: &mut Arena) -> Result where T: Into, { - let n = unsafe { self.cif.call::(self.code_ptr, args) }; - Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) + let n = unsafe { self.cif.call::(self.code_ptr, args) }; + Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) } unsafe fn call_ptr(&self, args: &[Arg], arena: &mut Arena) -> Result { @@ -266,9 +266,9 @@ impl StructImpl { let (new_layout, offset) = layout .extend(Layout::new::()) .map_err(|_| FfiError::LayoutError)?; - *layout = new_layout; - let n = unsafe { std::ptr::read::(ptr.byte_offset(offset as isize).cast()) }; - Ok(n) + *layout = new_layout; + let n = unsafe { std::ptr::read::(ptr.byte_offset(offset as isize).cast()) }; + Ok(n) } unsafe fn read_int( @@ -280,9 +280,8 @@ impl StructImpl { T: Copy + TryInto + MightNotFitInFixnum, Integer: From, { - - let n = unsafe { read_primitive::(ptr, layout)? }; - Ok(Value::Number(fixnum!(Number, n, arena))) + let n = unsafe { read_primitive::(ptr, layout)? }; + Ok(Value::Number(fixnum!(Number, n, arena))) } unsafe fn read_float( @@ -292,8 +291,8 @@ impl StructImpl { where T: Into, { - let n = unsafe { read_primitive::(ptr, layout)? }; - Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) + let n = unsafe { read_primitive::(ptr, layout)? }; + Ok(Value::Number(Number::Float(OrderedFloat(n.into())))) } let mut layout = Layout::from_size_align(0, 1).map_err(|_| FfiError::LayoutError)?; @@ -794,8 +793,8 @@ impl ForeignFunctionTable { T: Copy + TryInto + MightNotFitInFixnum, Integer: From, { - let n = unsafe { ptr.cast::().read() }; - Value::Number(fixnum!(Number, n, arena)) + let n = unsafe { ptr.cast::().read() }; + Value::Number(fixnum!(Number, n, arena)) } let ptr = ptr.as_ptr()?; diff --git a/src/machine/heap.rs b/src/machine/heap.rs index 12a0e40a..11cc8497 100644 --- a/src/machine/heap.rs +++ b/src/machine/heap.rs @@ -71,26 +71,26 @@ impl InnerHeap { new_layout.size() <= isize::MAX as usize, "Allocation too large. We should probably GC (TODO)" ); - - let new_ptr = unsafe { - if self.byte_cap == 0 { - alloc::alloc(new_layout) - } else { - let old_layout = - alloc::Layout::from_size_align(self.byte_cap, size_of::()) - .unwrap(); - alloc::realloc(self.ptr, old_layout, new_layout.size()) - } - }; - if !new_ptr.is_null() { - self.ptr = new_ptr; - self.byte_cap = new_cap; - - true + let new_ptr = unsafe { + if self.byte_cap == 0 { + alloc::alloc(new_layout) } else { - false + let old_layout = + alloc::Layout::from_size_align(self.byte_cap, size_of::()) + .unwrap(); + alloc::realloc(self.ptr, old_layout, new_layout.size()) } + }; + + if !new_ptr.is_null() { + self.ptr = new_ptr; + self.byte_cap = new_cap; + + true + } else { + false + } } } @@ -110,20 +110,20 @@ unsafe fn scan_slice_to_str(heap_slice: &[u8]) -> HeapStringScan<'_> { .position(|b| *b == 0u8) .unwrap_or(heap_slice.len()); - let zero_byte_addr = unsafe { heap_slice.as_ptr().add(string_len) }; + let zero_byte_addr = unsafe { heap_slice.as_ptr().add(string_len) }; - let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); - let tail_idx = cell_index!( - (string_len + sentinel_len).next_multiple_of(ALIGN) - + if sentinel_len <= 1 { heap_index!(1) } else { 0 } - ); + let sentinel_len = pstr_sentinel_length(zero_byte_addr.addr()); + let tail_idx = cell_index!( + (string_len + sentinel_len).next_multiple_of(ALIGN) + + if sentinel_len <= 1 { heap_index!(1) } else { 0 } + ); - let str_slice = &heap_slice[..string_len]; + let str_slice = &heap_slice[..string_len]; - HeapStringScan { - string: unsafe { std::str::from_utf8_unchecked(str_slice) }, - tail_idx, - } + HeapStringScan { + string: unsafe { std::str::from_utf8_unchecked(str_slice) }, + tail_idx, + } } // Same as scan_slice_to_str but assumes that the slice is from the start of a string. @@ -142,10 +142,10 @@ unsafe fn scan_slice_to_str_from_start(heap_slice: &[u8]) -> HeapStringScan<'_> let str_slice = &heap_slice[..string_len]; - HeapStringScan { - string: unsafe { std::str::from_utf8_unchecked(str_slice) }, - tail_idx, - } + HeapStringScan { + string: unsafe { std::str::from_utf8_unchecked(str_slice) }, + tail_idx, + } } #[derive(Debug, Clone, Copy)] @@ -282,28 +282,29 @@ impl ReservedHeapSection { ) }; - let zero_region_idx = heap_index!(self.heap_cell_len) + str_byte_len; - let align_offset = pstr_sentinel_length(zero_region_idx); + let zero_region_idx = heap_index!(self.heap_cell_len) + str_byte_len; + let align_offset = pstr_sentinel_length(zero_region_idx); - unsafe { ptr::write_bytes(self.heap_ptr.add(zero_region_idx), 0u8, align_offset) }; + unsafe { ptr::write_bytes(self.heap_ptr.add(zero_region_idx), 0u8, align_offset) }; - cells_written = if align_offset == 1 { - unsafe { ptr::write_bytes( + cells_written = if align_offset == 1 { + unsafe { + ptr::write_bytes( self.heap_ptr.add(zero_region_idx + 1), 0u8, size_of::(), ) }; - // ensure there are at least two bytes in the boundary - // buffer separating the string data from the tail - // cell - cell_index!(src.len() + align_offset + size_of::()) - } else { - cell_index!(src.len() + align_offset) - }; + // ensure there are at least two bytes in the boundary + // buffer separating the string data from the tail + // cell + cell_index!(src.len() + align_offset + size_of::()) + } else { + cell_index!(src.len() + align_offset) + }; - self.heap_cell_len += cells_written; + self.heap_cell_len += cells_written; cells_written } @@ -627,15 +628,15 @@ impl Heap { let len = heap_index_checked!(num_cells).ok_or(AllocError)?; loop { - if self.free_space() >= len { - section = ReservedHeapSection { - heap_ptr: self.inner.ptr, - heap_cell_len: self.cell_len(), - }; - break; - } else if unsafe { !self.grow() } { - return Err(AllocError); - } + if self.free_space() >= len { + section = ReservedHeapSection { + heap_ptr: self.inner.ptr, + heap_cell_len: self.cell_len(), + }; + break; + } else if unsafe { !self.grow() } { + return Err(AllocError); + } } Ok(HeapWriter { @@ -864,8 +865,8 @@ impl Heap { let align_offset = pstr_sentinel_length(s_len); let copy_size = s_len + align_offset; - loop { - unsafe { + loop { + unsafe { if self.free_space() >= copy_size { let slice = std::slice::from_raw_parts_mut(self.inner.ptr, self.inner.byte_len + s_len); From 71ea74a077a1c9662250e953e991ed5e96478491 Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Wed, 3 Jun 2026 17:34:41 -0400 Subject: [PATCH 07/10] Issue 3223: repair for the failing wasm32 build Removed `ref` modifier due to not being allowed when implicitly borrowing. --- src/wasm.rs | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/src/wasm.rs b/src/wasm.rs index 22234e16..ccb226eb 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -129,23 +129,21 @@ impl WasmQueryState { let mut error = None; let mut to_drop = false; match &mut self.inner { - Some(ref mut inner) => { - inner.with_query_state_mut(|query_state| match query_state.next() { - Some(Ok(leaf_answer)) => { - js_sys::Reflect::set(&ret, &"value".into(), &leaf_answer.into()).unwrap(); - js_sys::Reflect::set(&ret, &"done".into(), &false.into()).unwrap(); - } - Some(Err(error_term)) => { - let js_error = js_sys::Error::new("Prolog error"); - js_error.set_cause(&error_term.into()); - error = Some(js_error); - } - None => { - js_sys::Reflect::set(&ret, &"done".into(), &true.into()).unwrap(); - to_drop = true; - } - }) - } + Some(mut inner) => inner.with_query_state_mut(|query_state| match query_state.next() { + Some(Ok(leaf_answer)) => { + js_sys::Reflect::set(&ret, &"value".into(), &leaf_answer.into()).unwrap(); + js_sys::Reflect::set(&ret, &"done".into(), &false.into()).unwrap(); + } + Some(Err(error_term)) => { + let js_error = js_sys::Error::new("Prolog error"); + js_error.set_cause(&error_term.into()); + error = Some(js_error); + } + None => { + js_sys::Reflect::set(&ret, &"done".into(), &true.into()).unwrap(); + to_drop = true; + } + }), None => return Err(js_sys::Error::new("This query was already dropped").into()), } From 7a636b03946a405f4d4725f41126bb948d28fb27 Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Wed, 3 Jun 2026 17:57:10 -0400 Subject: [PATCH 08/10] Issue 3223: trying again repair for the failing wasm32 build Removed `mut` modifier completely. --- src/wasm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wasm.rs b/src/wasm.rs index ccb226eb..95206f83 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -129,7 +129,7 @@ impl WasmQueryState { let mut error = None; let mut to_drop = false; match &mut self.inner { - Some(mut inner) => inner.with_query_state_mut(|query_state| match query_state.next() { + Some(inner) => inner.with_query_state_mut(|query_state| match query_state.next() { Some(Ok(leaf_answer)) => { js_sys::Reflect::set(&ret, &"value".into(), &leaf_answer.into()).unwrap(); js_sys::Reflect::set(&ret, &"done".into(), &false.into()).unwrap(); From eabbf67e864499103a71c3457e865b48bf36a30b Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Tue, 16 Jun 2026 21:14:43 -0400 Subject: [PATCH 09/10] Issue 3223: add more `unsafe` scopes --- src/offset_table.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/offset_table.rs b/src/offset_table.rs index 849fead6..732420fa 100644 --- a/src/offset_table.rs +++ b/src/offset_table.rs @@ -211,7 +211,7 @@ impl SerialOffsetTable { }) } - unsafe fn build_with(&mut self, value: T) -> usize { + unsafe fn build_with(&mut self, value: T) -> usize { unsafe { let mut ptr; loop { @@ -228,17 +228,17 @@ impl SerialOffsetTable { ptr::write(ptr as *mut T, value); // SAFETY: `ptr` was obtained from `self.block.alloc()` self.block.get_offset(ptr) - } + }} #[inline] - unsafe fn lookup(&self, offset: usize) -> &T { + unsafe fn lookup(&self, offset: usize) -> &T { unsafe { &*self.block.get_unchecked(offset).cast::() - } + }} #[inline] - unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { + unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { unsafe { &mut *self.block.get_unchecked(offset).cast::().cast_mut() - } + }} #[allow(clippy::wrong_self_convention)] fn to_concurrent(&mut self) -> ConcurrentOffsetTable From ea88ca552d34eaf24dcfeb557866232b0b519bcd Mon Sep 17 00:00:00 2001 From: Alexander McLin Date: Tue, 16 Jun 2026 21:18:49 -0400 Subject: [PATCH 10/10] Issue 3223: reformat via `cargo fmt` --- src/offset_table.rs | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/src/offset_table.rs b/src/offset_table.rs index 732420fa..2db36628 100644 --- a/src/offset_table.rs +++ b/src/offset_table.rs @@ -211,34 +211,36 @@ impl SerialOffsetTable { }) } - unsafe fn build_with(&mut self, value: T) -> usize { unsafe { - let mut ptr; + unsafe fn build_with(&mut self, value: T) -> usize { + unsafe { + let mut ptr; - loop { - ptr = self.block.alloc(size_of::()); + loop { + ptr = self.block.alloc(size_of::()); - if ptr.is_null() { - let new_block = self.block.grow_new().unwrap(); - self.block = new_block; - } else { - break; + if ptr.is_null() { + let new_block = self.block.grow_new().unwrap(); + self.block = new_block; + } else { + break; + } } + + ptr::write(ptr as *mut T, value); + // SAFETY: `ptr` was obtained from `self.block.alloc()` + self.block.get_offset(ptr) } - - ptr::write(ptr as *mut T, value); - // SAFETY: `ptr` was obtained from `self.block.alloc()` - self.block.get_offset(ptr) - }} + } #[inline] - unsafe fn lookup(&self, offset: usize) -> &T { unsafe { - &*self.block.get_unchecked(offset).cast::() - }} + unsafe fn lookup(&self, offset: usize) -> &T { + unsafe { &*self.block.get_unchecked(offset).cast::() } + } #[inline] - unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { unsafe { - &mut *self.block.get_unchecked(offset).cast::().cast_mut() - }} + unsafe fn lookup_mut(&mut self, offset: usize) -> &mut T { + unsafe { &mut *self.block.get_unchecked(offset).cast::().cast_mut() } + } #[allow(clippy::wrong_self_convention)] fn to_concurrent(&mut self) -> ConcurrentOffsetTable