Skip to main content

dayzmake_core/
warning.rs

1//! Warnings raised by the library. A function that can warn takes a `WarningSink`; the library
2//! never prints, and nothing is shared between calls.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fmt;
6
7use crate::error::printable;
8
9/// Per-name quota of kept warnings in [`Warnings::new`].
10const DEFAULT_QUOTA: u32 = 10;
11
12/// What a [`Warning`] is.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14#[non_exhaustive]
15pub enum WarningKind {
16    /// A real warning: it has a name, can be muted and is subject to the per-name quota.
17    #[default]
18    Warning,
19    /// A plain message for the user (progress, tool output): never muted, never counted against
20    /// a quota, shown as the bare message.
21    Note,
22}
23
24/// One warning: a message with an optional name (for muting), file and line.
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct Warning {
28    /// Warning or note.
29    pub kind: WarningKind,
30    /// The warning type, used for muting and the per-name quota.
31    pub name: Option<&'static str>,
32    /// What went wrong.
33    pub message: String,
34    /// The file the warning is about.
35    pub file: Option<String>,
36    /// The line the warning is about.
37    pub line: Option<u32>,
38}
39
40impl Warning {
41    /// A warning without location.
42    #[must_use]
43    pub fn new(name: Option<&'static str>, message: impl Into<String>) -> Warning {
44        Warning {
45            kind: WarningKind::Warning,
46            name,
47            message: message.into(),
48            file: None,
49            line: None,
50        }
51    }
52
53    /// A note: a plain message that is not a warning (see [`WarningKind::Note`]).
54    #[must_use]
55    pub fn note(message: impl Into<String>) -> Warning {
56        Warning {
57            kind: WarningKind::Note,
58            name: None,
59            message: message.into(),
60            file: None,
61            line: None,
62        }
63    }
64
65    /// Sets the file.
66    #[must_use]
67    pub fn in_file(mut self, file: impl Into<String>) -> Warning {
68        self.file = Some(file.into());
69        self
70    }
71
72    /// Sets the line.
73    #[must_use]
74    pub fn at_line(mut self, line: u32) -> Warning {
75        self.line = Some(line);
76        self
77    }
78
79    /// The location prefix (the file name is escaped with [`printable`]): `In file f:l: `, `In file f: `, `In line l: ` or nothing.
80    #[must_use]
81    pub fn location(&self) -> String {
82        match (self.file.as_deref().map(printable), self.line) {
83            (Some(file), Some(line)) => format!("In file {file}:{line}: "),
84            (Some(file), None) => format!("In file {file}: "),
85            (None, Some(line)) => format!("In line {line}: "),
86            (None, None) => String::new(),
87        }
88    }
89}
90
91impl fmt::Display for Warning {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        if self.kind == WarningKind::Note {
94            return f.write_str(&self.message);
95        }
96        write!(f, "{}warning: {}", self.location(), self.message)?;
97        if let Some(name) = self.name {
98            write!(f, " [{name}]")?;
99        }
100        Ok(())
101    }
102}
103
104/// Receives the warnings a library call raises.
105pub trait WarningSink {
106    /// Takes one warning.
107    fn warn(&mut self, warning: Warning);
108
109    /// True if warnings with this name would be dropped (muted or over quota); callers use it to
110    /// skip work that only builds a warning.
111    fn is_suppressed(&self, _name: Option<&str>) -> bool {
112        false
113    }
114}
115
116/// A sink that keeps warnings, with muted names and a per-name quota.
117#[derive(Debug, Clone)]
118pub struct Warnings {
119    muted: BTreeSet<String>,
120    quota: u32,
121    raised: BTreeMap<String, u32>,
122    kept: Vec<Warning>,
123}
124
125impl Default for Warnings {
126    fn default() -> Self {
127        Warnings::new()
128    }
129}
130
131impl Warnings {
132    /// Keeps at most 10 warnings per name; unnamed warnings have no quota.
133    #[must_use]
134    pub fn new() -> Warnings {
135        Warnings {
136            muted: BTreeSet::new(),
137            quota: DEFAULT_QUOTA,
138            raised: BTreeMap::new(),
139            kept: Vec::new(),
140        }
141    }
142
143    /// Drops all warnings with this name.
144    pub fn mute(&mut self, name: impl Into<String>) {
145        self.muted.insert(name.into());
146    }
147
148    /// Lifts the quota.
149    pub fn unlimited(&mut self) {
150        self.quota = u32::MAX;
151    }
152
153    /// Counts the warning and keeps it unless muted or over quota (notes are always kept); returns the kept warning.
154    pub fn record(&mut self, warning: Warning) -> Option<&Warning> {
155        if warning.kind == WarningKind::Note {
156            self.kept.push(warning);
157            return self.kept.last();
158        }
159        if let Some(name) = warning.name {
160            if self.muted.contains(name) {
161                return None;
162            }
163            let raised = self.raised.entry(name.to_string()).or_insert(0);
164            *raised = raised.saturating_add(1);
165            if *raised > self.quota {
166                return None;
167            }
168        }
169        self.kept.push(warning);
170        self.kept.last()
171    }
172
173    /// The kept warnings in the order they were raised.
174    #[must_use]
175    pub fn warnings(&self) -> &[Warning] {
176        &self.kept
177    }
178
179    /// The kept warnings, consuming the sink.
180    #[must_use]
181    pub fn into_warnings(self) -> Vec<Warning> {
182        self.kept
183    }
184
185    /// `(name, count)` for every name that went over its quota, sorted by name; muted names are
186    /// not listed.
187    #[must_use]
188    pub fn suppressed(&self) -> Vec<(String, u32)> {
189        self.raised
190            .iter()
191            .filter(|(name, raised)| !self.muted.contains(*name) && **raised > self.quota)
192            .map(|(name, raised)| (name.clone(), *raised - self.quota))
193            .collect()
194    }
195}
196
197impl WarningSink for Warnings {
198    fn warn(&mut self, warning: Warning) {
199        self.record(warning);
200    }
201
202    fn is_suppressed(&self, name: Option<&str>) -> bool {
203        let Some(name) = name else { return false };
204        self.muted.contains(name) || self.raised.get(name).is_some_and(|r| *r >= self.quota)
205    }
206}