Skip to content

Commit

Permalink
style: fix compiler and clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
portasynthinca3 committed Jul 25, 2024
1 parent e719bd8 commit 24f1934
Show file tree
Hide file tree
Showing 13 changed files with 42 additions and 53 deletions.
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
1 change: 0 additions & 1 deletion src/interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 1 addition & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ fn main(image_handle: Handle, system_table: SystemTable<Boot>) -> 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()
Expand Down Expand Up @@ -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"); }
}
}
6 changes: 3 additions & 3 deletions src/mem_manager/malloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LinkedListAllocator> {
pub unsafe fn new(bottom: VirtAddr, mut address_space: AddressSpace) -> Result<LinkedListAllocator> {
// place first block header
let pages = phys::allocate(1);
if pages.len() < 1 { return Err(MemMgrError::OutOfMemory); }
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions src/mem_manager/phys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ pub fn allocate(mut count: usize) -> DynArr<PhysAddr> {

/// 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<PhysAddr>) -> Result<(), DynArr<PhysAddr>> {
#[cfg(feature = "trace-pmm")]
let orig = pages.clone();
Expand Down
4 changes: 2 additions & 2 deletions src/mem_manager/virt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
15 changes: 8 additions & 7 deletions src/vm/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(())
},
Expand Down Expand Up @@ -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(())
Expand All @@ -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)
},

Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/vm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 4 additions & 4 deletions src/vm/port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand All @@ -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()])
Expand Down
7 changes: 3 additions & 4 deletions src/vm/scheduler.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -265,7 +264,7 @@ impl Schedule for PrimitiveScheduler {
Ok(id)
}

fn remove(&mut self, id: Eid) {
fn remove(&mut self, _id: Eid) {
todo!();
}
}
17 changes: 7 additions & 10 deletions src/vm/state.rs
Original file line number Diff line number Diff line change
@@ -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]
Expand All @@ -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 { }
Expand All @@ -58,16 +55,16 @@ impl core::fmt::Debug for LocalAtomRef {

impl PartialOrd for LocalAtomRef {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
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
}
}

Expand Down
16 changes: 8 additions & 8 deletions src/vm/term.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -74,12 +74,12 @@ impl core::fmt::Debug for MapTerm {

impl PartialOrd for MapTerm {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
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!()
}
}
Expand Down Expand Up @@ -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}>"),
Expand All @@ -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<usize, _> = int.try_into() else { return false };
int >= 32 && int <= 127
(32..=127).contains(&int)
});

if is_probable_charlist {
Expand Down Expand Up @@ -244,13 +244,13 @@ impl From<Eid> 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,
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 24f1934

Please sign in to comment.