transitioning to log crate

This commit is contained in:
Jakub Doka 2024-09-30 19:27:00 +02:00
parent 136bba1631
commit 8b6d9b5de3
No known key found for this signature in database
GPG key ID: C6E9A89936B8C143
8 changed files with 38 additions and 85 deletions

1
Cargo.lock generated
View file

@ -126,6 +126,7 @@ dependencies = [
"hashbrown", "hashbrown",
"hbbytecode", "hbbytecode",
"hbvm", "hbvm",
"log",
"regalloc2", "regalloc2",
] ]

View file

@ -11,6 +11,7 @@ path = "src/main.rs"
hashbrown = { version = "0.14.5", default-features = false } hashbrown = { version = "0.14.5", default-features = false }
hbbytecode = { version = "0.1.0", path = "../hbbytecode" } hbbytecode = { version = "0.1.0", path = "../hbbytecode" }
hbvm = { path = "../hbvm", features = ["nightly"] } hbvm = { path = "../hbvm", features = ["nightly"] }
log = { version = "0.4.22", features = ["release_max_level_error"] }
regalloc2 = { git = "https://github.com/jakubDoka/regalloc2", branch = "reuse-allocations", features = [] } regalloc2 = { git = "https://github.com/jakubDoka/regalloc2", branch = "reuse-allocations", features = [] }
[dev-dependencies] [dev-dependencies]

View file

@ -4,7 +4,6 @@ use {
ident::{self, Ident}, ident::{self, Ident},
instrs::{self, *}, instrs::{self, *},
lexer::TokenKind, lexer::TokenKind,
log,
parser::{ parser::{
self, find_symbol, idfl, CommentOr, CtorField, Expr, ExprRef, FileId, Pos, StructField, self, find_symbol, idfl, CommentOr, CtorField, Expr, ExprRef, FileId, Pos, StructField,
}, },
@ -1305,7 +1304,7 @@ impl Codegen {
self.assign_pattern(left, value) self.assign_pattern(left, value)
} }
E::Call { func: fast, args, .. } => { E::Call { func: fast, args, .. } => {
log::trc!("call {}", self.ast_display(fast)); log::trace!("call {}", self.ast_display(fast));
let func_ty = self.ty(fast); let func_ty = self.ty(fast);
let ty::Kind::Func(mut func) = func_ty.expand() else { let ty::Kind::Func(mut func) = func_ty.expand() else {
self.report(fast.pos(), "can't call this, maybe in the future"); self.report(fast.pos(), "can't call this, maybe in the future");
@ -2408,7 +2407,7 @@ impl Codegen {
name: Result<Ident, &str>, name: Result<Ident, &str>,
lit_name: &str, lit_name: &str,
) -> ty::Kind { ) -> ty::Kind {
log::trc!("find_or_declare: {lit_name} {file}"); log::trace!("find_or_declare: {lit_name} {file}");
let f = self.files[file as usize].clone(); let f = self.files[file as usize].clone();
let Some((expr, ident)) = f.find_decl(name) else { let Some((expr, ident)) = f.find_decl(name) else {
match name { match name {
@ -2539,7 +2538,7 @@ impl Codegen {
ci: ItemCtx, ci: ItemCtx,
compile: impl FnOnce(&mut Self, &mut ItemCtx) -> Result<T, E>, compile: impl FnOnce(&mut Self, &mut ItemCtx) -> Result<T, E>,
) -> Result<T, E> { ) -> Result<T, E> {
log::trc!("eval"); log::trace!("eval");
let mut prev_ci = core::mem::replace(&mut self.ci, ci); let mut prev_ci = core::mem::replace(&mut self.ci, ci);
self.ci.task_base = self.tasks.len(); self.ci.task_base = self.tasks.len();
@ -2584,7 +2583,7 @@ impl Codegen {
}) { }) {
panic!("{e} {}", vc); panic!("{e} {}", vc);
} else { } else {
log::trc!("{}", vc); log::trace!("{}", vc);
} }
} }
@ -2596,7 +2595,7 @@ impl Codegen {
self.pool.cis.push(core::mem::replace(&mut self.ci, prev_ci)); self.pool.cis.push(core::mem::replace(&mut self.ci, prev_ci));
log::trc!("eval-end"); log::trace!("eval-end");
ret ret
} }
@ -2650,7 +2649,7 @@ impl Codegen {
fn report_log(&self, pos: Pos, msg: impl core::fmt::Display) { fn report_log(&self, pos: Pos, msg: impl core::fmt::Display) {
let mut out = String::new(); let mut out = String::new();
self.cfile().report_to(pos, msg, &mut out); self.cfile().report_to(pos, msg, &mut out);
crate::log::eprintln!("{out}"); log::error!("{out}");
} }
#[track_caller] #[track_caller]

View file

@ -8,6 +8,7 @@ use {
hashbrown::hash_map, hashbrown::hash_map,
std::{ std::{
collections::VecDeque, collections::VecDeque,
eprintln,
ffi::OsStr, ffi::OsStr,
io, io,
path::{Path, PathBuf}, path::{Path, PathBuf},
@ -16,6 +17,20 @@ use {
}, },
}; };
pub struct Logger;
impl log::Log for Logger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
log::max_level() >= metadata.level()
}
fn log(&self, record: &log::Record) {
eprintln!("{}", record.args())
}
fn flush(&self) {}
}
#[derive(Default)] #[derive(Default)]
pub struct Options { pub struct Options {
pub fmt: bool, pub fmt: bool,

View file

@ -116,74 +116,6 @@ mod ident {
} }
} }
mod log {
#![allow(unused_macros)]
#[derive(PartialOrd, PartialEq, Ord, Eq, Debug)]
pub enum Level {
Err,
Wrn,
Inf,
Dbg,
Trc,
}
pub const LOG_LEVEL: Level = match option_env!("LOG_LEVEL") {
Some(val) => match val.as_bytes()[0] {
b'e' => Level::Err,
b'w' => Level::Wrn,
b'i' => Level::Inf,
b'd' => Level::Dbg,
b't' => Level::Trc,
_ => panic!("Invalid log level."),
},
None => {
if cfg!(debug_assertions) {
Level::Dbg
} else {
Level::Err
}
}
};
macro_rules! eprintln {
($($tt:tt)*) => {
#[cfg(test)]
{
//std::eprintln!($($tt)*)
format_args!($($tt)*)
}
#[cfg(not(test))]
{
format_args!($($tt)*)
}
};
}
macro_rules! log {
($level:expr, $fmt:literal $($expr:tt)*) => {
if $level <= $crate::log::LOG_LEVEL {
$crate::log::eprintln!("{:?}: {}", $level, format_args!($fmt $($expr)*));
}
};
($level:expr, $($arg:expr),+) => {
if $level <= $crate::log::LOG_LEVEL {
$(eprintln!("[{}:{}:{}][{:?}]: {} = {:?}", line!(), column!(), file!(), $level, stringify!($arg), $arg);)*
}
};
}
macro_rules! err { ($($arg:tt)*) => { $crate::log::log!($crate::log::Level::Err, $($arg)*) }; }
macro_rules! wrn { ($($arg:tt)*) => { $crate::log::log!($crate::log::Level::Wrn, $($arg)*) }; }
macro_rules! inf { ($($arg:tt)*) => { $crate::log::log!($crate::log::Level::Inf, $($arg)*) }; }
macro_rules! dbg { ($($arg:tt)*) => { $crate::log::log!($crate::log::Level::Dbg, $($arg)*) }; }
macro_rules! trc { ($($arg:tt)*) => { $crate::log::log!($crate::log::Level::Trc, $($arg)*) }; }
#[allow(unused_imports)]
pub(crate) use {dbg, eprintln, err, inf, log, trc, wrn};
}
mod ty { mod ty {
use { use {
crate::{ crate::{
@ -1318,7 +1250,7 @@ impl LoggedMem {
write!(self.disp_buf, "({})", regs[r as usize].0).unwrap() write!(self.disp_buf, "({})", regs[r as usize].0).unwrap()
} }
} }
log::trc!("read-typed: {:x}: {}", addr.get(), self.disp_buf); log::trace!("read-typed: {:x}: {}", addr.get(), self.disp_buf);
} }
} }
@ -1329,7 +1261,7 @@ impl hbvm::mem::Memory for LoggedMem {
target: *mut u8, target: *mut u8,
count: usize, count: usize,
) -> Result<(), hbvm::mem::LoadError> { ) -> Result<(), hbvm::mem::LoadError> {
log::trc!( log::trace!(
"load: {:x} {}", "load: {:x} {}",
addr.get(), addr.get(),
AsHex(core::slice::from_raw_parts(addr.get() as *const u8, count)) AsHex(core::slice::from_raw_parts(addr.get() as *const u8, count))
@ -1343,12 +1275,16 @@ impl hbvm::mem::Memory for LoggedMem {
source: *const u8, source: *const u8,
count: usize, count: usize,
) -> Result<(), hbvm::mem::StoreError> { ) -> Result<(), hbvm::mem::StoreError> {
log::trc!("store: {:x} {}", addr.get(), AsHex(core::slice::from_raw_parts(source, count))); log::trace!(
"store: {:x} {}",
addr.get(),
AsHex(core::slice::from_raw_parts(source, count))
);
self.mem.store(addr, source, count) self.mem.store(addr, source, count)
} }
unsafe fn prog_read<T: Copy + 'static>(&mut self, addr: hbvm::mem::Address) -> T { unsafe fn prog_read<T: Copy + 'static>(&mut self, addr: hbvm::mem::Address) -> T {
if log::LOG_LEVEL == log::Level::Trc { if log::log_enabled!(log::Level::Trace) {
if core::any::TypeId::of::<u8>() == core::any::TypeId::of::<T>() { if core::any::TypeId::of::<u8>() == core::any::TypeId::of::<T>() {
if let Some(instr) = self.prev_instr { if let Some(instr) = self.prev_instr {
self.display_instr::<()>(instr, addr); self.display_instr::<()>(instr, addr);

View file

@ -2,6 +2,8 @@
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
use std::{io::Write, num::NonZeroUsize}; use std::{io::Write, num::NonZeroUsize};
log::set_logger(&hblang::Logger).unwrap();
let args = std::env::args().collect::<Vec<_>>(); let args = std::env::args().collect::<Vec<_>>();
let args = args.iter().map(String::as_str).collect::<Vec<_>>(); let args = args.iter().map(String::as_str).collect::<Vec<_>>();

View file

@ -108,7 +108,7 @@ impl<'a, 'b> Parser<'a, 'b> {
if !errors.is_empty() { if !errors.is_empty() {
// TODO: we need error recovery // TODO: we need error recovery
crate::log::eprintln!("{errors}"); log::error!("{errors}");
unreachable!(); unreachable!();
} }
@ -576,7 +576,7 @@ impl<'a, 'b> Parser<'a, 'b> {
fn report(&self, pos: Pos, msg: impl fmt::Display) -> ! { fn report(&self, pos: Pos, msg: impl fmt::Display) -> ! {
let mut str = String::new(); let mut str = String::new();
report_to(self.lexer.source(), self.path, pos, msg, &mut str); report_to(self.lexer.source(), self.path, pos, msg, &mut str);
crate::log::eprintln!("{str}"); log::error!("{str}");
unreachable!(); unreachable!();
} }

View file

@ -3,7 +3,6 @@ use {
ident::Ident, ident::Ident,
instrs, instrs,
lexer::{self, TokenKind}, lexer::{self, TokenKind},
log,
parser::{ parser::{
self, self,
idfl::{self}, idfl::{self},
@ -568,14 +567,14 @@ impl Nodes {
let mut out = String::new(); let mut out = String::new();
self.visited.clear(self.values.len()); self.visited.clear(self.values.len());
self.basic_blocks_low(&mut out, VOID).unwrap(); self.basic_blocks_low(&mut out, VOID).unwrap();
log::inf!("{out}"); log::info!("{out}");
} }
#[allow(dead_code)] #[allow(dead_code)]
fn graphviz(&self) { fn graphviz(&self) {
let out = &mut String::new(); let out = &mut String::new();
_ = self.graphviz_low(out); _ = self.graphviz_low(out);
log::inf!("{out}"); log::info!("{out}");
} }
fn is_cfg(&self, o: Nid) -> bool { fn is_cfg(&self, o: Nid) -> bool {
@ -2016,7 +2015,7 @@ impl Codegen {
name: Option<Ident>, name: Option<Ident>,
lit_name: &str, lit_name: &str,
) -> ty::Kind { ) -> ty::Kind {
log::trc!("find_or_declare: {lit_name} {file}"); log::trace!("find_or_declare: {lit_name} {file}");
let f = self.files[file as usize].clone(); let f = self.files[file as usize].clone();
let Some((expr, ident)) = f.find_decl(name.ok_or(lit_name)) else { let Some((expr, ident)) = f.find_decl(name.ok_or(lit_name)) else {