From 24f193480545182e747e9d67c914ec4fde1bb510 Mon Sep 17 00:00:00 2001 From: Anna Antonenko Date: Thu, 25 Jul 2024 06:56:34 +0300 Subject: [PATCH] style: fix compiler and clippy warnings --- Makefile | 6 +++--- build.rs | 2 +- src/interrupt.rs | 1 - src/main.rs | 10 +--------- src/mem_manager/malloc.rs | 6 +++--- src/mem_manager/phys.rs | 1 + src/mem_manager/virt.rs | 4 ++-- src/vm/interpreter.rs | 15 ++++++++------- src/vm/mod.rs | 2 +- src/vm/port.rs | 8 ++++---- src/vm/scheduler.rs | 7 +++---- src/vm/state.rs | 17 +++++++---------- src/vm/term.rs | 16 ++++++++-------- 13 files changed, 42 insertions(+), 53 deletions(-) diff --git a/Makefile b/Makefile index 534c6e4..7dd66fa 100644 --- a/Makefile +++ b/Makefile @@ -8,9 +8,9 @@ clean: mkdir build # Emulator (the EFI executable) -PROFILE=dev -PROFILE_DIR=debug -CARGOFLAGS=--target x86_64-unknown-uefi-debug.json -Zbuild-std=core,compiler_builtins,alloc -Zbuild-std-features=compiler-builtins-mem --features=trace-messages +PROFILE=release +PROFILE_DIR=release +CARGOFLAGS=--target x86_64-unknown-uefi-debug.json -Zbuild-std=core,compiler_builtins,alloc -Zbuild-std-features=compiler-builtins-mem MAGIC_SECTION_OFFSET=0x141000000 RELOC_SECTION_OFFSET=0x141001000 emu: diff --git a/build.rs b/build.rs index 356c575..9f64552 100644 --- a/build.rs +++ b/build.rs @@ -47,7 +47,7 @@ fn main() { impl_str.push_str(format!(" Self::{name} => {arity},\n").as_str()); } - enum_str.push_str("}"); + enum_str.push('}'); impl_str.push_str(" }\n }\n}"); fs::write(dest_path, format!( diff --git a/src/interrupt.rs b/src/interrupt.rs index f8b6177..45baa10 100644 --- a/src/interrupt.rs +++ b/src/interrupt.rs @@ -43,7 +43,6 @@ use strum::VariantArray; use crate::mem_manager::{phys, reloc::Relocatable, PAGE_SIZE, VirtAddr, virt::AddressSpace}; use crate::segment::*; use crate::virt::TableAttrs; -use crate::hal::io_port::Port; /// Disables interrupts. It is recommended to only keep them that way for a very /// short amount of time, enabling them back with [`enable_external`] as soon as diff --git a/src/main.rs b/src/main.rs index 1ff14cf..27c48cb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -65,7 +65,7 @@ fn main(image_handle: Handle, system_table: SystemTable) -> Status { LOGGER = Some(SerialLogger::new(0)); log::set_logger(LOGGER.as_ref().unwrap()).unwrap(); } - log::set_max_level(log::LevelFilter::Trace); + log::set_max_level(log::LevelFilter::Info); // print our address let loaded_image = system_table.boot_services() @@ -121,12 +121,4 @@ extern "C" fn after_reloc(_data: &()) -> ! { // start the VM vm::init(bosbaima::get()).unwrap(); - // unsafe { vm::executor::Pls::init() }; - // let date = core::str::from_utf8(bosbaima::get().read_file("date").unwrap()).unwrap().trim(); - // log::info!("base image built on {date}"); - // let main_mod = vm::module::Module::new(bosbaima::get().read_file("ebin/main.beam").unwrap()).unwrap(); - - loop { - unsafe { asm!("hlt"); } - } } diff --git a/src/mem_manager/malloc.rs b/src/mem_manager/malloc.rs index 4953e4f..ebf7cd1 100644 --- a/src/mem_manager/malloc.rs +++ b/src/mem_manager/malloc.rs @@ -101,7 +101,7 @@ impl LinkedListAllocator { /// # Safety /// The function is unsafe in case there are other objects at any address /// above `bottom`. - pub unsafe fn new<'a>(bottom: VirtAddr, mut address_space: AddressSpace) -> Result { + pub unsafe fn new(bottom: VirtAddr, mut address_space: AddressSpace) -> Result { // place first block header let pages = phys::allocate(1); if pages.len() < 1 { return Err(MemMgrError::OutOfMemory); } @@ -151,7 +151,7 @@ impl core::fmt::Debug for LinkedListAllocator { if current.size > 64 * 8 { write!(f, "...")?; } - writeln!(f, "")?; + writeln!(f)?; display_capacity += display_size; if current.used { display_used += display_size }; previous = previous.next.as_ref().unwrap(); @@ -237,7 +237,7 @@ unsafe impl Allocator for LinkedListAllocator { }; previous.next = Some(blk_ref); - (&mut previous).next.as_mut().unwrap() + previous.next.as_mut().unwrap() } else { // last block is free but small: need to extend it let target_size = pre_padding + layout.size() + post_padding; diff --git a/src/mem_manager/phys.rs b/src/mem_manager/phys.rs index 880c9b8..596a3e9 100644 --- a/src/mem_manager/phys.rs +++ b/src/mem_manager/phys.rs @@ -355,6 +355,7 @@ pub fn allocate(mut count: usize) -> DynArr { /// Deallocates a number of physical pages using their physical addresses. /// Returns unrecognized addresses that failed to deallocate. +#[allow(clippy::result_large_err)] pub fn deallocate(mut pages: DynArr) -> Result<(), DynArr> { #[cfg(feature = "trace-pmm")] let orig = pages.clone(); diff --git a/src/mem_manager/virt.rs b/src/mem_manager/virt.rs index 129c001..80574bf 100644 --- a/src/mem_manager/virt.rs +++ b/src/mem_manager/virt.rs @@ -892,10 +892,10 @@ impl<'guard, 'r> AddressSpaceGuard<'guard, 'r> { // find unused mutex slot let mut slot: Option<(usize, &Mutex<()>)> = None; let mut guard = SUBSPACE_REGISTRY_SLOTS.write(); - for i in 0..MAX_SUBSPACES { + for (i, entry) in SUBSPACE_REGISTRY.iter().enumerate().take(MAX_SUBSPACES) { if !(*guard)[i] { (*guard)[i] = true; - slot = Some((i, &SUBSPACE_REGISTRY[i])); + slot = Some((i, entry)); break; } } diff --git a/src/vm/interpreter.rs b/src/vm/interpreter.rs index 23d2b38..017e40b 100644 --- a/src/vm/interpreter.rs +++ b/src/vm/interpreter.rs @@ -3,7 +3,7 @@ use core::iter; use alloc::vec; -use alloc::{borrow::ToOwned, boxed::Box, rc::Rc, vec::Vec}; +use alloc::{boxed::Box, rc::Rc, vec::Vec}; use crate::vm::scheduler::{ExecuteStatus, TransferAgent}; @@ -72,7 +72,7 @@ enum Terminate { impl BeamState { /// Creates a new state that starts execution at the specified entry point - fn new<'a>(entry: InstructionPtr, args: &'a [LocalTerm]) -> BeamState { + fn new(entry: InstructionPtr, args: &[LocalTerm]) -> BeamState { BeamState { x: Vec::from(args), y: Vec::new(), @@ -205,7 +205,7 @@ impl BeamInterpreter { let YRegister::StkFrame(ref cp, stop) = self.state.y[self.state.stop - 1] else { panic!("corrupted stack frame"); }; - self.state.cp = cp.clone(); + self.state.cp.clone_from(cp); self.state.stop = stop; Ok(()) }, @@ -307,8 +307,8 @@ impl BeamInterpreter { // the value corresponding to K is fetched and put into V let (chunks, []) = spec.as_chunks::<2>() else { bad_insn!() }; for [left, right] in chunks { - let ref left = self.state.get_operand(left)?; - let Some(value) = src.0.get(left) else { jump!(self, *fail) }; + let left = self.state.get_operand(left)?; + let Some(value) = src.0.get(&left) else { jump!(self, *fail) }; self.state.assign_to_operand(right, value.clone())?; } Ok(()) @@ -321,11 +321,11 @@ impl BeamInterpreter { let arity: usize = arity.try_into().map_err(|_| Terminate::BadInsn)?; let LocalTerm::Tuple(src) = src else { jump!(self, *fail) }; if src.len() != arity { jump!(self, *fail) }; - if src.get(0) != Some(&tag) { jump!(self, *fail) }; + if src.first() != Some(&tag) { jump!(self, *fail) }; Ok(()) }, - (Opcode::Badmatch, [Some(arg), ..]) => { // TODO: not ignore arg + (Opcode::Badmatch, [Some(_arg), ..]) => { // TODO: not ignore arg Err(Terminate::Badmatch) }, @@ -362,6 +362,7 @@ impl BeamInterpreter { /// The errors of [BeamInterpreter::new] #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(clippy::enum_variant_names)] pub enum BeamInterpreterMakeError { /// Application not found in local context NoApp, diff --git a/src/vm/mod.rs b/src/vm/mod.rs index 01b9a6f..41972a1 100644 --- a/src/vm/mod.rs +++ b/src/vm/mod.rs @@ -3,7 +3,7 @@ //! implement. Everything else around this module and its descendants is more or //! less just a generic microkernel. -use alloc::{format, boxed::Box, rc::Rc}; +use alloc::{format, rc::Rc}; use app::Application; use hashbrown::HashMap; diff --git a/src/vm/port.rs b/src/vm/port.rs index 2fdadb1..8c25ceb 100644 --- a/src/vm/port.rs +++ b/src/vm/port.rs @@ -31,10 +31,10 @@ impl Execute for LogPort { // deconstruct message let LocalTerm::Tuple(message) = message else { continue }; - let Some(LocalTerm::Pid(sender)) = message.get(0) else { continue }; + let Some(sender_term @ LocalTerm::Pid(sender)) = message.first() else { continue }; let Some(message) = message.get(1) else { continue }; let LocalTerm::Tuple(message) = message else { continue }; - let Some(conversation) = message.get(0) else { continue }; + let Some(conversation) = message.first() else { continue }; let LocalTerm::Reference(_) = conversation else { continue }; let Some(request) = message.get(1) else { continue }; let Some(token) = message.get(2) else { continue }; @@ -51,9 +51,9 @@ impl Execute for LogPort { LocalTerm::Tuple(vec![error_atom.clone(), instantiated_atom.clone()]) }, r if *r == write_atom && Some(token) == self.token.as_ref() => { - if let Some(LocalTerm::BitString(_, message)) = args.get(0) + if let Some(LocalTerm::BitString(_, message)) = args.first() && let Ok(message) = core::str::from_utf8(message) { - log::info!("process {sender:?} says: {message}"); + log::info!("process {sender_term:?} says: {message}"); ok_atom.clone() } else { LocalTerm::Tuple(vec![error_atom.clone(), badarg_atom.clone()]) diff --git a/src/vm/scheduler.rs b/src/vm/scheduler.rs index 2edf2eb..2faa5bd 100644 --- a/src/vm/scheduler.rs +++ b/src/vm/scheduler.rs @@ -1,7 +1,6 @@ //! Execution and scheduling -use alloc::{boxed::Box, collections::VecDeque, rc::Rc, vec::Vec}; -use core::cell::RefCell; +use alloc::{boxed::Box, collections::VecDeque}; use hashbrown::{HashMap, HashSet}; @@ -221,7 +220,7 @@ impl Schedule for PrimitiveScheduler { match status { ExecuteStatus::Exited => { self.context.messenger.as_mut().unwrap().local_executables.remove(&exec_id); - self.executables.remove(&exec_id); () + self.executables.remove(&exec_id); }, ExecuteStatus::Running => { exec.get_common_state_mut().status = ExecuteStatus::Ready; @@ -265,7 +264,7 @@ impl Schedule for PrimitiveScheduler { Ok(id) } - fn remove(&mut self, id: Eid) { + fn remove(&mut self, _id: Eid) { todo!(); } } diff --git a/src/vm/state.rs b/src/vm/state.rs index 0a72fc1..421f1ad 100644 --- a/src/vm/state.rs +++ b/src/vm/state.rs @@ -1,11 +1,11 @@ //! Common VM state structures use core::{fmt::Debug, hash::Hash}; -use alloc::{boxed::Box, rc::{Rc, Weak}, vec::Vec}; +use alloc::rc::{Rc, Weak}; use hashbrown::HashMap; -use super::{app::Application, module::Module, scheduler::{Eid, LocalTransferAgent, TransferAgent}, term::LocalTerm}; +use super::{app::Application, scheduler::LocalTransferAgent, term::LocalTerm}; /// Opaque reference to an entry in the atom table. For more information, refer /// to [LocalTerm::Atom] @@ -30,9 +30,6 @@ impl PartialEq for LocalAtomRef { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } - fn ne(&self, other: &Self) -> bool { - self.0 != other.0 - } } impl Eq for LocalAtomRef { } @@ -58,16 +55,16 @@ impl core::fmt::Debug for LocalAtomRef { impl PartialOrd for LocalAtomRef { fn partial_cmp(&self, other: &Self) -> Option { - use core::cmp::Ordering; - if self == other { return Some(Ordering::Equal) }; - if self.get_str() > other.get_str() { return Some(Ordering::Greater) }; - Some(Ordering::Less) + Some(self.cmp(other)) } } impl Ord for LocalAtomRef { fn cmp(&self, other: &Self) -> core::cmp::Ordering { - self.partial_cmp(other).unwrap() + use core::cmp::Ordering; + if self == other { return Ordering::Equal }; + if self.get_str() > other.get_str() { return Ordering::Greater }; + Ordering::Less } } diff --git a/src/vm/term.rs b/src/vm/term.rs index 9aee4f7..883c007 100644 --- a/src/vm/term.rs +++ b/src/vm/term.rs @@ -1,6 +1,6 @@ //! Erlang Term implementation -use core::{array::TryFromSliceError, hash::{Hash, Hasher, SipHasher}, ops::Deref}; +use core::{array::TryFromSliceError, hash::{Hash, Hasher, SipHasher}}; use alloc::{boxed::Box, string::String, vec::Vec}; use hashbrown::HashMap; @@ -74,12 +74,12 @@ impl core::fmt::Debug for MapTerm { impl PartialOrd for MapTerm { fn partial_cmp(&self, other: &Self) -> Option { - todo!() + Some(self.cmp(other)) } } impl Ord for MapTerm { - fn cmp(&self, other: &Self) -> core::cmp::Ordering { + fn cmp(&self, _other: &Self) -> core::cmp::Ordering { todo!() } } @@ -164,7 +164,7 @@ impl core::fmt::Debug for LocalTerm { Reference(parts) => { let mut hash = SipHasher::default(); parts.hash(&mut hash); - write!(f, "#Ref<{:016x}>", hash.finish()) + write!(f, "#Ref<{:04x}>", hash.finish() & 0xffff) }, Pid(Eid(sched, seq)) => write!(f, "<{sched}.{seq}>"), Port(Eid(sched, seq)) => write!(f, "#Port<{sched}.{seq}>"), @@ -183,7 +183,7 @@ impl core::fmt::Debug for LocalTerm { let is_probable_charlist = elements.iter().all(|elem| { let LocalTerm::Integer(int) = elem else { return false }; let Ok(int): Result = int.try_into() else { return false }; - int >= 32 && int <= 127 + (32..=127).contains(&int) }); if is_probable_charlist { @@ -244,13 +244,13 @@ impl From for LocalTerm { if value.1 >= PORT_START { Self::Port(value) } else { - Self::Port(value) + Self::Pid(value) } } } #[derive(Clone, Copy, PartialEq, Eq, FromRepr, Debug)] -enum EtfTag { +pub enum EtfTag { SmallInteger = 97, Integer = 98, Float = 99, @@ -336,7 +336,7 @@ impl LocalTerm { return Err(TermError::TagError); } - return Ok((&tuple[1 .. tuple.len()]).try_into().unwrap()); + Ok((&tuple[1 .. tuple.len()]).try_into().unwrap()) } /// Returns an atom reference if the term is an atom