1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#[macro_use]
pub extern crate log;
#[cfg(feature = "impl")]
pub extern crate chrono;
#[cfg(feature = "impl")]
pub extern crate fern;
#[cfg(feature = "fail")]
pub extern crate failure;
#[cfg(feature = "fail")]
#[macro_use]
pub extern crate failure_derive;

pub use log::*;

#[cfg(feature = "fail")]
pub use failure_derive::*;

#[derive(Debug)]
pub struct Position {
    pub file: &'static str,
    pub line: u32,
    pub column: u32,
}

impl std::fmt::Display for Position {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "{}:{}:{}", self.file, self.line, self.column)
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "fail", derive(Fail))]
pub enum DiagError {
    #[cfg_attr(feature = "fail", fail(display = "unreachable code reached at {}", pos))]
    UnreachableCodeReached { pos: Position },
    #[cfg_attr(feature = "fail", fail(display = "unimplemented code reached at {}", pos))]
    UnimplementedCodeReached { pos: Position },
}

impl DiagError {

    pub fn unimplemented(pos: Position) -> Self {
        DiagError::UnimplementedCodeReached { pos }
    }

    pub fn unreachable(pos: Position) -> Self {
        DiagError::UnreachableCodeReached { pos }
    }

}

#[macro_export]
macro_rules! diag_position {
    () => {{
        Position {
            file: file!(),
            line: line!(),
            column: column!(),
        }
    }};
}

#[macro_export]
macro_rules! diag {
    ($($arg:tt)+) => (error!(target: "diagnostics", $($arg)*));
}

#[macro_export]
macro_rules! diag_unreachable {
    () => {{
        debug_assert!(false, "unreachable code reached");
        diag!("unreachable code reached at {}", diag_position!());
    }};
    ($($arg:tt)+) => {{
        debug_assert!(false, $($arg)*);
        diag!($($arg)*);
    }}
}

#[macro_export]
macro_rules! diag_unreachable_err {
    () => {{
        diag_unreachable!();
        return Err(::DiagError::UnreachableCodeReached { pos: diag_position!() }.into());
    }};
    ($($arg:tt)+) => {{
        diag_unreachable!($($arg)*);
        return Err(::DiagError::UnreachableCodeReached { pos: diag_position!() }.into());
    }}
}

#[macro_export]
macro_rules! diag_unimplemented {
    () => {{
        debug_assert!(false, "unimplemented code reached");
        diag!("unimplemented code reached at {}", diag_position!());
    }};
    ($($arg:tt)+) => {{
        debug_assert!(false, $($arg)*);
        diag!($($arg)*);
    }}
}

#[macro_export]
macro_rules! diag_unimplemented_err {
    () => {{
        diag_unreachable!();
        return Err(::DiagError::Unimplemented { pos: diag_position!() }.into());
    }};
    ($($arg:tt)+) => {{
        diag_unreachable!($($arg)*);
        return Err(::DiagError::Unimplemented { pos: diag_position!() }.into());
    }}
}

#[cfg(feature = "impl")]
pub fn stdout_dispatch() -> fern::Dispatch {
    use fern::colors::Color;
    let colors = fern::colors::ColoredLevelConfig::new()
        .trace(Color::White)
        .debug(Color::Blue)
        .info(Color::Green)
        .warn(Color::Yellow)
        .error(Color::Red);
    fern::Dispatch::new()
        .format(move |out, message, record| {
            out.finish(format_args!(
                "{} {}{} {}: {}",
                chrono::Local::now().format("[%Y-%m-%d %H:%M:%S]"),
                colors.color(record.level()),
                if record.level() == log::Level::Info {
                    " "
                } else {
                    ""
                },
                record.target(),
                message,
            ))
        })
        .level(log::LevelFilter::Info)
        .level_for("diagnostics", log::LevelFilter::Off)
}

#[cfg(feature = "impl")]
pub fn diag_dispatch() -> fern::Dispatch {
    fern::Dispatch::new()
        .format(move |out, message, record| {
            out.finish(format_args!(
                "{} {}{} {}: {}",
                chrono::Local::now().format("[%Y-%m-%d %H:%M:%S%.9f]"),
                record.level(),
                if record.level() == log::Level::Info {
                    " "
                } else {
                    ""
                },
                record.target(),
                message,
            ))
        })
        .level(log::LevelFilter::Info)
        .level_for("diagnostics", log::LevelFilter::Trace)
}

#[cfg(feature = "impl")]
pub fn init_logger(log_file: Option<impl AsRef<std::path::Path>>) -> std::io::Result<fern::Dispatch> {
    let mut dispatch = fern::Dispatch::new().chain(stdout_dispatch().chain(std::io::stdout()));
    let log_file = if let Some(log_file) = log_file {
        Some(log_file.as_ref().to_owned())
    } else if let Ok(exe_path) = std::env::current_exe() {
        exe_path.parent().map(|exe_dir| exe_dir.join(".diag.log"))
    } else {
        None
    };
    if let Some(log_file) = log_file {
        let log_file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(log_file)?;
        dispatch = dispatch.chain(diag_dispatch().chain(log_file))
    }
    Ok(dispatch)
}

#[cfg(test)]
mod tests;