How to write a panic! like macro in Rust? -
for fatal error handling, i'm using panic!
macro, prefer have macro did not print file/line information, error message.
i read the macro documentation, understanding bit shaky.
i looked @ source of panic!
macro, it's calling functions work file , line information integral part of operation, can't tweak that.
i looked @ println!
macro, looks more promising, have 2 problems unaware of how solve.
macro_rules! die { () => (print!("\n")); ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*); exit(-1)); }
if put exit()
call in, have on last line, syntax errors when trying call it.
if remove exit()
, don't complaints macro, code fails compile:
let file = match file::open(&path) { err(why) => die!("couldn't open {}: {}", display, why.description()), ok(file) => file, };
whereas compile when die!
replaced panic!
. assume there magic panic!
tells compiler never returns?
first, if put
exit()
call in, have on last line, syntax errors when trying call it.
that because macro should expand single item, , here expands two. can wrap invocation in block {}
, it'll work... once qualify call exit
.
({ print!(concat!($fmt, "\n"), $($arg)*); std::process::exit(-1) });
if remove
exit()
, don't complaints macro, code fails compile. whereas compile whendie
replacedpanic
. assume there magicpanic
tells compiler never returns?
it's not magic !
type. panic
, exit
functions both return !
type no value: cannot ever constructed.
this sufficient compiler know functions never return (they diverge), point of view of type-checking, !
considered subtype of types , not cause issues.
Comments
Post a Comment