Files
aho_corasick
atty
beef
bitflags
bstr
byteorder
cfg_if
clap
clap_derive
codespan
codespan_reporting
crc_any
crypto_hash
csv
csv_core
debug_helper
filepath
fixed
fixed_macro
fixed_macro_impl
fixed_macro_types
fnv
foreign_types
foreign_types_shared
getrandom
glob
hashbrown
heck
hex
indexmap
itoa
lazy_static
libc
linked_hash_map
linked_hash_set
logos
logos_derive
lrl_test_compiler
maplit
memchr
memoffset
once_cell
openssl
openssl_sys
os_str_bytes
paste
pest
pest_derive
pest_generator
pest_meta
phf
phf_generator
phf_macros
phf_shared
ppv_lite86
proc_macro2
proc_macro_error
proc_macro_error_attr
proc_macro_hack
quote
rand
rand_chacha
rand_core
regex
regex_automata
regex_syntax
remove_dir_all
ring
rowan
rustc_hash
ryu
semver
semver_parser
serde
serde_derive
serde_json
siphasher
smallvec
smawk
smol_str
spin
stable_deref_trait
strsim
syn
taplo
tempfile
termcolor
text_size
textwrap
toml
triomphe
typenum
ucd_trie
unicode_linebreak
unicode_segmentation
unicode_width
unicode_xid
untrusted
utf8_ranges
vec_map
  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
use std::sync::{ Arc, RwLock, RwLockReadGuard, RwLockWriteGuard };
use std::fmt::Display;

use linked_hash_set::LinkedHashSet;

use pest::error::Error as PestError;
use pest::RuleType;

#[derive(Debug, Clone)]
pub struct TaskHandle {
    inner: Arc<RwLock<HandlerInner>>,
    task_index: usize
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct HandlerInner {
    tasks: Vec<TaskRecord>,
    total_warnings: usize,
    total_errors: usize
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct TaskRecord {
    parent_task_index: usize,

    task_name: &'static str,
    file_name: Option<String>,

    errors:   LinkedHashSet<String>,
    warnings: LinkedHashSet<String>
}

impl HandlerInner {
    fn add_warning(&mut self, task_index: usize, warning: String) {
        self.tasks[task_index].warnings.insert(warning);
        self.total_warnings += 1;
    }

    fn add_error(&mut self, task_index: usize, error: String) {
        self.tasks[task_index].errors.insert(error);
        self.total_errors += 1;
    }

    fn get_label(&self, task_index: usize) -> String {
        let mut task_indices = Vec::new();

        let mut current_index = task_index;
        let mut last_index = None;

        while last_index != Some(current_index) {
            task_indices.push(current_index);
            last_index = Some(current_index);
            current_index = self.tasks[current_index].parent_task_index;
        }

        task_indices.iter().rev()
            .map(|i| self.tasks[*i].task_name)
            .collect::<Vec<&str>>()
            .join(".")
    }

    fn get_file(&self, task_index: usize) -> Option<&str> {
        let mut current_index = task_index;
        let mut last_index = None;

        while last_index != Some(current_index) {
            if let Some(fname) = &self.tasks[current_index].file_name {
                return Some(fname);
            }
            last_index = Some(current_index);
            current_index = self.tasks[current_index].parent_task_index;
        }
        None
    }
}

impl TaskHandle {
    pub fn new(root_task_name: &'static str) -> Self {
        let warnings = LinkedHashSet::new();
        let errors = LinkedHashSet::new();

        let root_task = TaskRecord {
            parent_task_index: 0,
            task_name: root_task_name,
            file_name: None,
            errors,
            warnings
        };

        let tasks = vec![root_task];

        TaskHandle {
            inner: Arc::new(RwLock::new(HandlerInner {
                tasks,
                total_errors: 0,
                total_warnings: 0
            })),
            task_index: 0
        }
    }

    pub fn sub_task(&self, task_name: &'static str, file_name: Option<String>) -> Self {
        let sub_task = TaskRecord {
            parent_task_index: self.task_index,
            task_name, file_name,
            errors: LinkedHashSet::new(),
            warnings: LinkedHashSet::new()
        };

        let mut inner = self.get_inner_ref_mut();

        let sub_task_index = inner.tasks.len();
        inner.tasks.push(sub_task);

        TaskHandle {
            inner: self.inner.clone(),
            task_index: sub_task_index
        }
    }

    #[inline]
    fn get_inner_ref(&self) -> RwLockReadGuard<HandlerInner> {
        self.inner.as_ref().read().unwrap()
    }

    #[inline]
    fn get_inner_ref_mut(&self) -> RwLockWriteGuard<HandlerInner> {
        self.inner.as_ref().write().unwrap()
    }

    /// Handle a warning
    pub fn warning<W: Display>(&self, warning: W) {
        self.get_inner_ref_mut()
            .add_warning(self.task_index, format!("{}", warning));
    }
    
    /// Convert a Result to an Option by handling the Err case as a warning
    pub fn res_warning<T, W: Display>(&self, res: Result<T, W>) -> Option<T> {
        match res {
            Ok(value) => Some(value),
            Err(warning) => {
                self.warning(warning);
                None
            }
        }
    }

    /// Handle an error
    pub fn error<E: Display>(&self, error: E) {
        self.get_inner_ref_mut()
            .add_error(self.task_index, format!("{}", error));
    }

    pub fn pest_error<R: RuleType>(&self, error: PestError<R>) {
        let mut inner = self.get_inner_ref_mut();

        let fname_opt = inner.get_file(self.task_index);
        
        let error = match fname_opt {
            Some(fname) => error.with_path(fname),
            None => error
        };

        inner.add_error(self.task_index, format!("{}", error));
    }

    /// Convert a Result to an Option by handling the Err case as an error
    pub fn res_error<T, E: Display>(&self, res: Result<T, E>) -> Option<T> {
        match res {
            Ok(value) => Some(value),
            Err(error) => {
                self.error(error);
                None
            }
        }
    }

    pub fn none_error<T, E: Display>(&self, opt: Option<T>, error: E) -> Option<T> {
        if opt.is_none() {
            self.error(error);
        }
        opt
    }

    pub fn print_starting(&self) {
        let inner = self.get_inner_ref();
        println!("Starting {}...", inner.get_label(self.task_index));
    }

    pub fn print_finished(&self) {
        let inner = self.get_inner_ref();
        println!("Finished {}\n", inner.get_label(self.task_index));
    }

    pub fn report_results(&self) {
        let inner = self.get_inner_ref();
        let root_task = inner.tasks[0].task_name;

        for (i, task) in inner.tasks.iter().enumerate() {
            if task.errors.len() > 0 || task.warnings.len() > 0 {
                println!("{}:", inner.get_label(i));

                for error in task.errors.iter() {
                    println!("{}\n", error);
                }

                for warning in task.warnings.iter() {
                    println!("{}\n", warning);
                }
            }
        }

        if inner.total_errors == 0 {
            println!("{} Succeeded!", root_task);
        } else {
            println!("{} Failed!", root_task);
        }
        
        println!("Errors: {}",   inner.total_errors);
        println!("Warnings: {}", inner.total_warnings);
    }
}