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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use std::cell::RefCell;
use std::cmp::Ordering;
use std::fs::{read, File};
use std::io::{stdout, Write};
use std::mem::take;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};

use anyhow::Result;
use encoding::all::{UTF_8, WINDOWS_1252};
use encoding::{DecoderTrap, Encoding};
use fnv::{FnvHashMap, FnvHashSet};
use once_cell::sync::Lazy;

use crate::fileset::FileKind;
use crate::report::error_loc::ErrorLoc;
use crate::report::filter::ReportFilter;
use crate::report::writer::log_report;
use crate::report::writer_json::log_report_json;
use crate::report::{
    err, tips, warn, ErrorKey, FilterRule, LogReport, OutputStyle, PointedMessage,
};
use crate::token::Loc;

static ERRORS: Lazy<Mutex<Errors>> = Lazy::new(|| Mutex::new(Errors::default()));

#[allow(missing_debug_implementations)]
pub struct Errors {
    pub(crate) output: RefCell<Box<dyn Write + Send>>,

    /// The base game directory
    vanilla_root: PathBuf,
    /// Extra base game directory loaded before `vanilla_root`
    clausewitz_root: PathBuf,
    /// Extra base game directory loaded before `vanilla_root`
    jomini_root: PathBuf,
    /// The mod directory
    mod_root: PathBuf,
    /// Extra loaded mods' directories
    loaded_mods: Vec<PathBuf>,
    /// Extra loaded mods' error tags
    pub(crate) loaded_mods_labels: Vec<String>,

    filecache: FnvHashMap<PathBuf, String>,

    /// Determines whether a report should be printed.
    pub(crate) filter: ReportFilter,
    /// Output color and style configuration.
    pub(crate) styles: OutputStyle,
    pub(crate) max_line_length: Option<usize>,

    /// All reports that passed the checks, stored here to be sorted before being emitted all at once.
    /// The "abbreviated" reports don't participate in this. They are still emitted immediately.
    /// It's a `HashSet` because duplicate reports are fairly common due to macro expansion and other revalidations.
    storage: FnvHashSet<LogReport>,
}

impl Default for Errors {
    fn default() -> Self {
        Errors {
            output: RefCell::new(Box::new(stdout())),
            vanilla_root: PathBuf::default(),
            clausewitz_root: PathBuf::default(),
            jomini_root: PathBuf::default(),
            mod_root: PathBuf::default(),
            loaded_mods: Vec::default(),
            loaded_mods_labels: Vec::default(),
            filecache: FnvHashMap::default(),
            filter: ReportFilter::default(),
            styles: OutputStyle::default(),
            max_line_length: None,
            storage: FnvHashSet::default(),
        }
    }
}

impl Errors {
    pub(crate) fn get_fullpath(&mut self, kind: FileKind, path: &Path) -> PathBuf {
        match kind {
            FileKind::Internal => path.to_path_buf(),
            FileKind::Clausewitz => self.clausewitz_root.join(path),
            FileKind::Jomini => self.jomini_root.join(path),
            FileKind::Vanilla => self.vanilla_root.join(path),
            FileKind::LoadedMod(idx) => self.loaded_mods[idx as usize].join(path),
            FileKind::Mod => self.mod_root.join(path),
        }
    }

    pub(crate) fn get_line(&mut self, loc: &Loc) -> Option<String> {
        if loc.line == 0 {
            return None;
        }
        let pathname = self.get_fullpath(loc.kind, loc.pathname());
        if let Some(contents) = self.filecache.get(&pathname) {
            return contents.lines().nth(loc.line as usize - 1).map(str::to_string);
        }
        let bytes = read(&pathname).ok()?;
        let contents = match UTF_8.decode(&bytes, DecoderTrap::Strict) {
            Ok(contents) => contents,
            Err(_) => WINDOWS_1252.decode(&bytes, DecoderTrap::Strict).ok()?,
        };
        let line = contents.lines().nth(loc.line as usize - 1).map(str::to_string);
        self.filecache.insert(pathname, contents);
        line
    }

    /// Perform some checks to see whether the report should actually be logged.
    /// If yes, it will do so.
    fn push_report(&mut self, report: LogReport) {
        if !self.filter.should_print_report(&report) {
            return;
        }
        self.storage.insert(report);
    }

    pub fn log_abbreviated(&mut self, loc: &Loc, key: ErrorKey) {
        if loc.line == 0 {
            _ = writeln!(self.output.get_mut(), "({key}) {}", loc.pathname().to_string_lossy());
        } else if let Some(line) = self.get_line(loc) {
            _ = writeln!(self.output.get_mut(), "({key}) {line}");
        }
    }

    pub fn push_abbreviated<E: ErrorLoc>(&mut self, eloc: E, key: ErrorKey) {
        let loc = eloc.into_loc();
        self.log_abbreviated(&loc, key);
    }

    pub fn push_header(&mut self, _key: ErrorKey, msg: &str) {
        _ = writeln!(self.output.get_mut(), "{msg}");
    }

    pub fn emit_reports(&mut self, json: bool) {
        let mut reports: Vec<LogReport> = take(&mut self.storage).into_iter().collect();
        reports.sort_unstable_by(|a, b| {
            // Severity in descending order
            let mut cmp = b.severity.cmp(&a.severity);
            if cmp != Ordering::Equal {
                return cmp;
            }
            // Confidence in descending order too
            cmp = b.confidence.cmp(&a.confidence);
            if cmp != Ordering::Equal {
                return cmp;
            }
            // If severity and confidence are the same, order by loc. Check all locs in order.
            for (a, b) in a.pointers.iter().zip(b.pointers.iter()) {
                cmp = a.loc.cmp(&b.loc);
                if cmp != Ordering::Equal {
                    return cmp;
                }
            }
            // Shorter chain goes first, if it comes to that.
            cmp = b.pointers.len().cmp(&a.pointers.len());
            if cmp != Ordering::Equal {
                return cmp;
            }
            // Fallback: order by message text.
            if cmp == Ordering::Equal {
                cmp = a.msg.cmp(&b.msg);
            }
            cmp
        });
        if json {
            _ = writeln!(self.output.get_mut(), "[");
            let mut first = true;
            for report in &reports {
                if !first {
                    _ = writeln!(self.output.get_mut(), ",");
                }
                first = false;
                log_report_json(self, report);
            }
            _ = writeln!(self.output.get_mut(), "\n]");
        } else {
            for report in &reports {
                log_report(self, report);
            }
        }
    }

    /// Get a mutable lock on the global ERRORS struct.
    ///
    /// # Panics
    /// May panic when the mutex has been poisoned by another thread.
    pub fn get_mut() -> MutexGuard<'static, Errors> {
        ERRORS.lock().unwrap()
    }

    /// Like [`self.get_mut`] but intended for read-only access.
    ///
    /// # Panics
    /// May panic when the mutex has been poisoned by another thread.
    pub fn get() -> MutexGuard<'static, Errors> {
        ERRORS.lock().unwrap()
    }
}

pub fn set_vanilla_dir(dir: PathBuf) {
    let mut game = dir.clone();
    game.push("game");
    Errors::get_mut().vanilla_root = game;

    let mut clausewitz = dir.clone();
    clausewitz.push("clausewitz");
    Errors::get_mut().clausewitz_root = clausewitz;

    let mut jomini = dir;
    jomini.push("jomini");
    Errors::get_mut().jomini_root = jomini;
}

pub fn set_mod_root(root: PathBuf) {
    Errors::get_mut().mod_root = root;
}

pub fn add_loaded_mod_root(label: String, root: PathBuf) {
    let mut errors = Errors::get_mut();
    errors.loaded_mods_labels.push(label);
    errors.loaded_mods.push(root);
}

pub fn set_output_file(file: &Path) -> Result<()> {
    let file = File::create(file)?;
    Errors::get_mut().output = RefCell::new(Box::new(file));
    Ok(())
}

pub fn log(mut report: LogReport) {
    let mut vec = Vec::new();
    report.pointers.drain(..).for_each(|pointer| {
        let index = vec.len();
        recursive_pointed_msg_expansion(&mut vec, &pointer);
        vec.insert(index, pointer);
    });
    report.pointers.extend(vec);
    Errors::get_mut().push_report(report);
}

/// Expand `PointedMessage` recursively.
/// That is; for the given `PointedMessage`, follow its location's link until such link is no
/// longer available, adding a newly created `PointedMessage` to the given `Vec` for each linked
/// location.
fn recursive_pointed_msg_expansion(vec: &mut Vec<PointedMessage>, pointer: &PointedMessage) {
    if let Some(link) = &pointer.loc.link {
        let from_here = PointedMessage {
            loc: link.as_ref().into_loc(),
            length: 0,
            msg: Some("from here".to_owned()),
        };
        let index = vec.len();
        recursive_pointed_msg_expansion(vec, &from_here);
        vec.insert(index, from_here);
    }
}

/// Tests whether the report might be printed. If false, the report will definitely not be printed.
pub fn will_maybe_log<E: ErrorLoc>(eloc: E, key: ErrorKey) -> bool {
    Errors::get().filter.should_maybe_print(key, &eloc.into_loc())
}

pub fn emit_reports(json: bool) {
    Errors::get_mut().emit_reports(json);
}

// =================================================================================================
// =============== Deprecated legacy calls to submit reports:
// =================================================================================================

pub fn error<E: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str) {
    err(key).msg(msg).loc(eloc).push();
}

pub fn error_info<E: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str, info: &str) {
    err(key).msg(msg).info(info).loc(eloc).push();
}

pub fn old_warn<E: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str) {
    warn(key).msg(msg).loc(eloc).push();
}

pub fn warn2<E: ErrorLoc, F: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str, eloc2: F, msg2: &str) {
    warn(key).msg(msg).loc(eloc).loc(eloc2, msg2).push();
}

pub fn warn3<E: ErrorLoc, E2: ErrorLoc, E3: ErrorLoc>(
    eloc: E,
    key: ErrorKey,
    msg: &str,
    eloc2: E2,
    msg2: &str,
    eloc3: E3,
    msg3: &str,
) {
    warn(key).msg(msg).loc(eloc).loc(eloc2, msg2).loc(eloc3, msg3).push();
}

pub fn warn_info<E: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str, info: &str) {
    warn(key).msg(msg).info(info).loc(eloc).push();
}

pub fn advice<E: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str) {
    tips(key).msg(msg).loc(eloc).push();
}

pub fn advice2<E: ErrorLoc, F: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str, eloc2: F, msg2: &str) {
    tips(key).msg(msg).loc(eloc).loc(eloc2, msg2).push();
}

pub fn advice_info<E: ErrorLoc>(eloc: E, key: ErrorKey, msg: &str, info: &str) {
    tips(key).msg(msg).info(info).loc(eloc).push();
}

pub fn warn_header(key: ErrorKey, msg: &str) {
    Errors::get_mut().push_header(key, msg);
}

pub fn warn_abbreviated<E: ErrorLoc>(eloc: E, key: ErrorKey) {
    Errors::get_mut().push_abbreviated(eloc, key);
}

// =================================================================================================
// =============== Configuration (Output style):
// =================================================================================================

/// Override the default `OutputStyle`. (Controls ansi colors)
pub fn set_output_style(style: OutputStyle) {
    Errors::get_mut().styles = style;
}

/// Disable color in the output.
pub fn disable_ansi_colors() {
    Errors::get_mut().styles = OutputStyle::no_color();
}

/// TODO:
pub fn set_max_line_length(max_line_length: usize) {
    Errors::get_mut().max_line_length =
        if max_line_length == 0 { None } else { Some(max_line_length) };
}

// =================================================================================================
// =============== Configuration (Filter):
// =================================================================================================

pub fn set_show_vanilla(v: bool) {
    Errors::get_mut().filter.show_vanilla = v;
}

pub fn set_show_loaded_mods(v: bool) {
    Errors::get_mut().filter.show_loaded_mods = v;
}

pub fn set_predicate(predicate: FilterRule) {
    Errors::get_mut().filter.predicate = predicate;
}