wasm_rs_dbg/
lib.rs

1//! # dbg!() for wasm32
2//!
3//! This is a drop-in replacement for [`std::dbg`], here's how it can be used:
4//!
5//! ```
6//! use wasm_rs_dbg::dbg;
7//!
8//! fn test() {
9//!   dbg!();
10//!   dbg!(Some(1));
11//! }
12//! // ...
13//! ```
14//!
15#[cfg(all(
16    target_arch = "wasm32",
17    target_os = "unknown",
18    feature = "console-debug"
19))]
20pub use web_sys::console::debug_1 as log;
21#[cfg(all(
22    target_arch = "wasm32",
23    target_os = "unknown",
24    feature = "console-error"
25))]
26pub use web_sys::console::error_1 as log;
27#[cfg(all(
28    target_arch = "wasm32",
29    target_os = "unknown",
30    feature = "console-info"
31))]
32pub use web_sys::console::info_1 as log;
33#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "console-log"))]
34pub use web_sys::console::log_1 as log;
35#[cfg(all(
36    target_arch = "wasm32",
37    target_os = "unknown",
38    feature = "console-trace"
39))]
40pub use web_sys::console::trace_1 as log;
41#[cfg(all(
42    target_arch = "wasm32",
43    target_os = "unknown",
44    feature = "console-warn"
45))]
46pub use web_sys::console::warn_1 as log;
47
48/// This `dbg!` macro is a drop-in replacement for [`std::dbg`]
49///
50/// It will use [`web_sys::console`] on `wasm32-unknown-unknown`. On all
51/// other architectures it will call [`std::dbg`]. It will log at `debug` level by default, and
52/// this can configured with this crate's feature flags. For example, specifying `features =
53/// ["console-log"]` will send output at `log` level instead. Supported flags are:
54///
55/// * `console-debug` (default)
56/// * `console-log`
57/// * `console-error`
58/// * `console-info`
59/// * `console-trace`
60/// * `console-warn`
61///
62/// ## Note
63///
64/// These flags are **exclusive**, so it's important to set `default-features` to `false`
65#[macro_export]
66macro_rules! dbg {
67    () => {{
68        #[cfg(any(target_os = "wasi", not(target_arch = "wasm32")))]
69        std::dbg!();
70        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
71        $crate::log(&format!("[{}:{}]", std::file!(), std::line!()).into());
72    }};
73    ($val: expr $(,)?) => {{
74        #[cfg(any(target_os = "wasi", not(target_arch = "wasm32")))]
75        std::dbg!($val);
76        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
77        // Use of `match` here is intentional because it affects the lifetimes
78        // of temporaries - https://stackoverflow.com/a/48732525/1063961
79        match $val {
80            tmp => {
81                $crate::log(&format!("[{}:{}] {} = {:#?}",
82                    std::file!(), std::line!(), std::stringify!($val), &tmp).into());
83                tmp
84            }
85        }
86    }};
87    ($($val: expr),+ $(,)?) => {{
88        ($($crate::dbg!($val)),+,)
89    }}
90}