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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! Backtrace support

use std::{
    env,
    fmt::Debug,
    marker::PhantomData,
};

/// Log agent.
pub trait LogAgent {
    type Item;

    fn new() -> Self;
    fn create_log( item: Self::Item ) -> Self;
    fn append_log( &mut self, item: Self::Item );
}

impl<T> LogAgent for Vec<T> {
    type Item = T;

    fn new() -> Self { Vec::new() }
    fn create_log( item: T ) -> Self { vec![ item ] }
    fn append_log( &mut self, item: T ) { self.push( item ); }
}

impl<T> LogAgent for PhantomData<T> {
    type Item = T;

    fn new() -> Self { PhantomData }
    fn create_log( _item: T ) -> Self { PhantomData }
    fn append_log( &mut self, _item: T ) {}
}

impl LogAgent for String {
    type Item = String;

    fn new() -> Self { String::new() }
    fn create_log( item: String ) -> Self { item }
    fn append_log( &mut self, item: String ) { self.push_str( &format!( "\n{}", item )); }
}

/// A wrapper struct for logging error value.
#[derive( PartialEq,Eq )]
pub struct Log<Inner, Agent: LogAgent = Vec<Frame>> {
    pub error : Inner, // the error
    pub agent : Agent, // log agent
}

#[cfg( not( feature = "pretty_log" ))]
impl<Inner,Agent> Debug for Log<Inner,Agent>
    where Inner: Debug
        , Agent: Debug + LogAgent
{
    fn fmt( &self, f: &mut std::fmt::Formatter ) -> std::fmt::Result {
        f.debug_struct("Log")
         .field( "error", &self.error )
         .field( "agent", &self.agent )
         .finish()
    }
}

#[cfg( feature = "pretty_log" )]
impl<Inner,Agent> Debug for Log<Inner,Agent>
    where Inner: Debug
        , Agent: Debug + LogAgent
{
    fn fmt( &self, f: &mut std::fmt::Formatter ) -> std::fmt::Result {
        if f.alternate() {
            f.debug_struct("Log")
             .field( "error", &self.error )
             .field( "agent", &self.agent )
             .finish()
        } else {
            write!( f, "{:#?}", self )
        }
    }
}

/// A type alias for opt-out logging at compile time.
pub type NoLog<Inner,Item=Frame> = Log<Inner,PhantomData<Item>>;

/// Wraps a type with Log.
pub trait ToLog<Agent> : Sized
    where Agent : LogAgent
{
    fn new_log( self ) -> Log<Self,Agent>;
    fn to_log( self, item: Agent::Item ) -> Log<Self,Agent>;
}

impl<Inner,Agent> ToLog<Agent> for Inner
    where Agent : LogAgent
{
    fn new_log( self ) -> Log<Self,Agent> {
        Log{ error: self, agent: Agent::new() }
    }

    fn to_log( self, item: Agent::Item ) -> Log<Inner,Agent> {
        Log{ error: self, agent: Agent::create_log( item )}
    }
}

/// Appends a log item.
pub trait Logger<Agent> : Sized
    where Agent : LogAgent
{
    fn log( self, item: Agent::Item ) -> Self;
}

impl<Agent,E> Logger<Agent> for Log<E,Agent>
    where Agent : LogAgent
{
    fn log( mut self, item: Agent::Item ) -> Self {
        self.agent.append_log( item );
        self
    }
}

macro_rules! impl_logger_for_predefined_enumx {
    ($($enumx:ident => $($_index:ident $gen:ident)*;)+) => {
        use enumx::prelude::*;
        $(
            impl<Agent$(,$gen)*> Logger<Agent> for $enumx<$($gen),*>
                where Agent : LogAgent
                  $(, $gen  : Logger<Agent> )*
            {
                fn log( self, _item: Agent::Item ) -> Self {
                    match self {
                        $( $enumx::$_index( $_index ) => $enumx::$_index( Logger::<Agent>::log( $_index, _item )), )*
                    }
                }
            }
        )+
    };
}

impl_logger_for_predefined_enumx! {
    Enum0  => ;
    Enum1  => _0 T0;
    Enum2  => _0 T0 _1 T1;
    Enum3  => _0 T0 _1 T1 _2 T2;
    Enum4  => _0 T0 _1 T1 _2 T2 _3 T3;
    Enum5  => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4;
    Enum6  => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5;
    Enum7  => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6;
    Enum8  => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7;
    Enum9  => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8;
    Enum10 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9;
    Enum11 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9 _10 T10;
    Enum12 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9 _10 T10 _11 T11;
    Enum13 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9 _10 T10 _11 T11 _12 T12;
    Enum14 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9 _10 T10 _11 T11 _12 T12 _13 T13;
    Enum15 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9 _10 T10 _11 T11 _12 T12 _13 T13 _14 T14;
    Enum16 => _0 T0 _1 T1 _2 T2 _3 T3 _4 T4 _5 T5 _6 T6 _7 T7 _8 T8 _9 T9 _10 T10 _11 T11 _12 T12 _13 T13 _14 T14 _15 T15;
}

/// Environment variable `RUST_BACKTRACE` controlled log agent.
#[derive( Debug, PartialEq, Eq )]
pub struct Env<Agent: LogAgent>( Agent );

impl<Agent> LogAgent for Env<Agent>
    where Agent : LogAgent
{
    type Item = <Agent as LogAgent>::Item;

    fn new() -> Self {
        Env( Agent::new() )
    }

    fn append_log( &mut self, item: Self::Item ) {
        if env_log_enabled() {
            self.0.append_log( item );
        }
    }

    fn create_log( item: Self::Item ) -> Self {
        if env_log_enabled() {
            Env( Agent::create_log( item ))
        } else {
            Env( Agent::new() )
        }
    }
}

fn env_log_enabled() -> bool {
    env::var( "RUST_BACKTRACE" )
        .map( |value| value == "1" || value == "full" )
        .unwrap_or( false )
}

/// Wraps the `Ok` variant with Log
pub trait MapToLog<Agent> : Sized
    where Agent : LogAgent
{
    type Output;

    fn map_to_log( self, item: Agent::Item ) -> Self::Output;
}

impl<Agent,T,E> MapToLog<Agent> for Result<T,E>
    where E     : ToLog<Agent>
        , Agent : LogAgent
{
    type Output = Result<Log<T,Agent>, E>;

    fn map_to_log( self, item: Agent::Item ) -> Self::Output {
        self.map( |v| v.to_log( item ))
    }
}

/// Wraps the `Err` variant with Log
pub trait MapErrToLog<Agent> : Sized
    where Agent : LogAgent
{
    type Output;

    fn map_err_to_log( self, item: Agent::Item ) -> Self::Output;
}

impl<Agent,T,E> MapErrToLog<Agent> for Result<T,E>
    where E     : ToLog<Agent>
        , Agent : LogAgent
{
    type Output = Result<T, Log<E,Agent>>;

    fn map_err_to_log( self, item: Agent::Item ) -> Self::Output {
        self.map_err( |e| e.to_log( item ))
    }
}

/// Appends a log item to the `Ok` variant.
pub trait MapLog<Agent> : Sized
    where Agent : LogAgent
{
    type Output;

    fn map_log( self, item: Agent::Item ) -> Self::Output;
}

impl<Agent,T,E> MapLog<Agent> for Result<T,E>
    where T     : Logger<Agent>
        , Agent : LogAgent
{
    type Output = Self;

    fn map_log( self, item: Agent::Item ) -> Self::Output {
        self.map( |e| e.log( item ))
    }
}

/// Appends a log item to the `Err` variant.
pub trait MapErrLog<Agent> : Sized
    where Agent : LogAgent
{
    type Output;

    fn map_err_log( self, item: Agent::Item ) -> Self::Output;
}

impl<Agent,T,E> MapErrLog<Agent> for Result<T,E>
    where E     : Logger<Agent>
        , Agent : LogAgent
{
    type Output = Self;

    fn map_err_log( self, item: Agent::Item ) -> Self::Output {
        self.map_err( |e| e.log( item ))
    }
}

/// A struct for store one frame for backtrace.
#[derive( Debug,Default,PartialEq,Eq,PartialOrd,Ord )]
pub struct Frame {
    pub module : &'static str,
    pub file   : &'static str,
    pub line   : u32,
    pub column : u32,
    pub info   : Option<String>,
}

impl Frame {
    pub fn new( module: &'static str, file: &'static str, line: u32, column: u32, info: Option<String> ) -> Self {
        Frame{ module, file, line, column, info }
    }
}

/// A macro to generate a `Frame`, to store the source of the error with file
/// name, module path, line/column numbers, and an optional context info, using
/// the same syntax with `format!()`.
///
/// An example: `frame!( "An unexpected {:?} was detect.", local_var ))`
#[macro_export]
macro_rules! frame {
    ( $expr:expr ) => {
        Frame::new( module_path!(), file!(), line!(), column!(), Some( String::from( $expr )))
    };
    () => {
        Frame::new( module_path!(), file!(), line!(), column!(), None )
    };
}