mod gather;
#[cfg(test)]
pub(crate) mod test;
#[cfg(test)]
mod test_assert_warnings;
#[cfg(test)]
mod test_contains;
#[cfg(test)]
mod test_failure_unwrap;
#[cfg(test)]
mod test_find;
#[cfg(test)]
mod test_gather;
#[cfg(test)]
mod test_group_by_elem;
#[cfg(test)]
mod test_id_path_map;
#[cfg(test)]
mod test_ids;
#[cfg(test)]
mod test_iter_warnings;
#[cfg(test)]
mod test_path_map;
#[cfg(test)]
mod test_warnings_at;
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashSet, btree_map},
fmt,
ops::Deref,
vec,
};
use tracing::{debug, info};
use crate::json;
pub(crate) use gather::{Converting, Gather, Gatherer};
#[doc(hidden)]
#[macro_export]
macro_rules! from_warning_all {
($($source_kind:path => $target_kind:ident::$target_variant:ident),+) => {
$(
impl From<$source_kind> for $target_kind {
fn from(warning: $source_kind) -> Self {
$target_kind::$target_variant(warning)
}
}
)+
};
}
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Id(Cow<'static, str>);
impl Id {
pub(crate) const fn from_static(s: &'static str) -> Self {
Self(Cow::Borrowed(s))
}
pub(crate) const fn from_string(s: String) -> Self {
Self(Cow::Owned(s))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
pub type Verdict<T, W> = Result<Caveat<T, W>, Failure<W>>;
#[derive(Debug)]
pub struct Caveat<T, W: Warning> {
value: T,
warnings: Set<W>,
}
impl<T, W> Deref for Caveat<T, W>
where
W: Warning,
{
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T, W> Caveat<T, W>
where
W: Warning,
{
pub(crate) fn new(value: T, warnings: Set<W>) -> Self {
Self { value, warnings }
}
pub fn warnings(&self) -> &Set<W> {
&self.warnings
}
pub fn into_parts(self) -> (T, Set<W>) {
let Self { value, warnings } = self;
(value, warnings)
}
pub fn ignore_warnings(self) -> T {
self.value
}
pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Caveat<U, W> {
let Self { value, warnings } = self;
Caveat {
value: op(value),
warnings,
}
}
}
pub trait VerdictExt<T, W: Warning> {
fn only_error(self) -> Result<Caveat<T, W>, Error<W>>;
}
#[expect(dead_code, reason = "for debugging")]
pub(crate) trait VerdictTrace<T, W: Warning> {
fn info_verdict(self, msg: &'static str) -> Self;
fn debug_verdict(self, msg: &'static str) -> Self;
}
#[expect(dead_code, reason = "for debugging")]
pub(crate) trait ResultTrace<T, W: Warning> {
fn info_result(self, msg: &'static str) -> Self;
fn debug_result(self, msg: &'static str) -> Self;
}
impl<T, W: Warning> VerdictExt<T, W> for Verdict<T, W> {
fn only_error(self) -> Result<Caveat<T, W>, Error<W>> {
match self {
Ok(c) => Ok(c),
Err(failure) => Err(failure.ignore_warnings()),
}
}
}
impl<T, W: Warning> VerdictTrace<T, W> for Verdict<T, W>
where
T: fmt::Debug,
{
fn info_verdict(self, msg: &'static str) -> Self {
match self {
Ok(c) => {
info!("{msg}: {c:#?}");
Ok(c)
}
Err(failure) => {
info!("{msg}: {failure:#?}");
Err(failure)
}
}
}
fn debug_verdict(self, msg: &'static str) -> Self {
match self {
Ok(c) => {
debug!("{msg}: {c:#?}");
Ok(c)
}
Err(failure) => {
debug!("{msg}: {failure:#?}");
Err(failure)
}
}
}
}
impl<T, W: Warning> ResultTrace<T, W> for Result<T, Failure<W>>
where
T: fmt::Debug,
{
fn info_result(self, msg: &'static str) -> Self {
match self {
Ok(c) => {
info!("{msg}: {c:#?}");
Ok(c)
}
Err(failure) => {
info!("{msg}: {failure:#?}");
Err(failure)
}
}
}
fn debug_result(self, msg: &'static str) -> Self {
match self {
Ok(c) => {
debug!("{msg}: {c:#?}");
Ok(c)
}
Err(failure) => {
debug!("{msg}: {failure:#?}");
Err(failure)
}
}
}
}
#[derive(Debug)]
pub struct Error<W: Warning> {
warning: W,
element: Element,
}
impl<W: Warning> Error<W> {
pub(crate) fn new(element: &json::Element<'_>, warning: W) -> Self {
Self {
warning,
element: Element::from_json(element),
}
}
pub(crate) fn at(element: Element, warning: W) -> Self {
Self { warning, element }
}
pub fn warning(&self) -> &W {
&self.warning
}
pub fn into_warning(self) -> W {
self.warning
}
pub fn element(&self) -> &Element {
&self.element
}
pub fn parts(&self) -> (&W, &Element) {
(&self.warning, &self.element)
}
pub fn into_parts(self) -> (W, Element) {
let Self { warning, element } = self;
(warning, element)
}
pub(crate) fn into_other<WA>(self) -> Error<WA>
where
W: Into<WA>,
WA: Warning,
{
let Self { warning, element } = self;
Error {
warning: warning.into(),
element,
}
}
}
impl<W: Warning> std::error::Error for Error<W> {}
impl<W: Warning> fmt::Display for Error<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"A warning for element at `{}` was upgraded to an `error`: {}",
self.element.path, self.warning
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Element {
pub id: json::ElemId,
pub span: json::Span,
pub path: json::Path,
pub location: json::Location,
}
impl Element {
pub(crate) fn from_json(element: &json::Element<'_>) -> Element {
Self {
id: element.id(),
span: element.span(),
path: element.path(),
location: element.location(),
}
}
}
pub trait Warning: Sized + fmt::Debug + fmt::Display + Send + Sync {
fn id(&self) -> Id;
fn is_rejected(&self) -> bool {
false
}
}
#[derive(Clone, Copy, Debug)]
pub struct Rejected;
#[derive(Debug)]
struct Source<W: Warning> {
#[cfg(test)]
#[expect(
dead_code,
reason = "only the derived `Debug` reads it, to show where a failing test's warning was raised"
)]
location: &'static std::panic::Location<'static>,
warning: W,
}
impl<W: Warning> Source<W> {
#[track_caller]
fn new(warning: W) -> Self {
#[cfg(test)]
{
Self {
location: std::panic::Location::caller(),
warning,
}
}
#[expect(
clippy::cfg_not_test,
reason = "This is code that is designed for use in tests"
)]
#[cfg(not(test))]
{
Self { warning }
}
}
fn into_warning(self) -> W {
self.warning
}
}
impl<W: Warning> Deref for Source<W> {
type Target = W;
fn deref(&self) -> &Self::Target {
&self.warning
}
}
#[derive(Debug)]
pub struct Set<W: Warning>(BTreeMap<json::ElemId, Group<W>>);
impl<W: Warning> Set<W> {
pub fn remove_rejected(&mut self) {
self.retain(|warning| !warning.is_rejected());
}
pub fn retain<F>(&mut self, mut keep: F)
where
F: FnMut(&W) -> bool,
{
self.0.retain(|_elem_id, group| {
group.warnings.retain(|source| keep(&source.warning));
!group.warnings.is_empty()
});
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn iter_warnings(&self) -> impl Iterator<Item = (&Element, &W)> {
self.iter().flat_map(|group| {
group
.warnings
.iter()
.map(|source| (&group.element, &source.warning))
})
}
pub fn contains<F>(&self, predicate: F) -> bool
where
F: FnMut(&W) -> bool,
{
self.find(predicate).is_some()
}
pub fn find<F>(&self, mut predicate: F) -> Option<(&Element, &W)>
where
F: FnMut(&W) -> bool,
{
self.iter_warnings()
.find(|(_element, warning)| predicate(warning))
}
pub fn ids(&self) -> BTreeSet<Id> {
self.iter_warnings()
.map(|(_element, warning)| warning.id())
.collect()
}
pub fn warnings_at<'set>(&'set self, path: &str) -> impl Iterator<Item = &'set W> {
self.iter_warnings()
.filter(move |(element, _warning)| element.path.as_str() == path)
.map(|(_element, warning)| warning)
}
pub fn len_elements(&self) -> usize {
self.0.len()
}
pub fn len_warnings(&self) -> usize {
self.0
.values()
.fold(0, |acc, group| acc.saturating_add(group.warnings.len()))
}
pub fn iter(&self) -> Iter<'_, W> {
Iter {
warnings: self.0.iter(),
}
}
pub fn id_path_map(&self, config: Limit) -> IdPathMap<'_> {
let report = match config {
Limit::None => limit_none(&self.0),
Limit::WarningTypes(max_warning_types) => {
limit_warning_types(max_warning_types, &self.0)
}
Limit::ElemPathsPerId(max_elem_paths_per_warning_id) => {
limit_elem_paths_per_id(max_elem_paths_per_warning_id, &self.0)
}
Limit::All {
max_warning_types,
max_elem_paths_per_warning_id,
} => limit_all(max_warning_types, max_elem_paths_per_warning_id, &self.0),
};
let LimitReport {
elements_filtered,
warning_distinct_types_filtered,
warnings,
} = report;
IdPathMap {
total_warnings: self.len_warnings(),
total_elements: self.len_elements(),
elements_filtered,
warning_distinct_types_filtered,
warnings,
}
}
pub fn msg_path_map(&self, config: Limit) -> MsgPathMap<'_> {
let IdPathMap {
total_warnings,
total_elements,
elements_filtered,
warning_distinct_types_filtered,
warnings,
} = self.id_path_map(config);
let warnings = warnings
.into_iter()
.map(|(id, paths)| (id.to_string(), paths))
.collect();
MsgPathMap {
total_warnings,
total_elements,
elements_filtered,
warning_distinct_types_filtered,
warnings,
}
}
pub fn path_map(&self) -> BTreeMap<&str, Vec<&W>> {
self.0
.values()
.map(|Group { element, warnings }| {
let path = element.path.as_str();
let warnings = warnings.iter().map(|w| &**w).collect();
(path, warnings)
})
.collect()
}
pub fn into_path_map(self) -> BTreeMap<json::Path, Vec<W>> {
self.0
.into_values()
.map(|Group { element, warnings }| {
let warnings = warnings.into_iter().map(Source::into_warning).collect();
(element.path, warnings)
})
.collect()
}
pub fn path_id_map(&self) -> BTreeMap<&str, Vec<Id>> {
self.0
.values()
.map(|group| {
let warnings = group.warnings.iter().map(|w| w.id()).collect();
(group.element.path.as_str(), warnings)
})
.collect()
}
pub fn path_msg_map(&self) -> BTreeMap<&str, Vec<String>> {
self.0
.values()
.map(|group| {
let warnings = group.warnings.iter().map(|w| w.to_string()).collect();
(group.element.path.as_str(), warnings)
})
.collect()
}
}
#[derive(Debug)]
struct LimitReport<'set> {
pub elements_filtered: usize,
pub warning_distinct_types_filtered: usize,
pub warnings: BTreeMap<Id, Vec<&'set str>>,
}
fn limit_none<W: Warning>(warnings: &BTreeMap<json::ElemId, Group<W>>) -> LimitReport<'_> {
let mut out = BTreeMap::new();
for group in warnings.values() {
let Group { element, warnings } = group;
let path = element.path.as_str();
for w in warnings {
match out.entry(w.id()) {
btree_map::Entry::Vacant(entry) => {
entry.insert(vec![path]);
}
btree_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(path);
}
}
}
}
LimitReport {
warnings: out,
elements_filtered: 0,
warning_distinct_types_filtered: 0,
}
}
fn limit_warning_types<W: Warning>(
max_warning_types: usize,
warnings: &BTreeMap<json::ElemId, Group<W>>,
) -> LimitReport<'_> {
let mut out = BTreeMap::new();
let mut elements_filtered = HashSet::new();
let mut warning_distinct_types_filtered = HashSet::new();
for group in warnings.values() {
let Group { element, warnings } = group;
let path = element.path.as_str();
let mut filtered = false;
for w in warnings {
let len = out.len();
let id = w.id();
match out.entry(id.clone()) {
btree_map::Entry::Vacant(entry) => {
if len < max_warning_types {
entry.insert(vec![path]);
} else {
warning_distinct_types_filtered.insert(id);
filtered = true;
}
}
btree_map::Entry::Occupied(mut entry) => {
entry.get_mut().push(path);
}
}
}
if filtered {
elements_filtered.insert(path);
}
}
LimitReport {
warnings: out,
elements_filtered: elements_filtered.len(),
warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
}
}
fn limit_elem_paths_per_id<W: Warning>(
max_elem_paths_per_warning_id: usize,
warnings: &BTreeMap<json::ElemId, Group<W>>,
) -> LimitReport<'_> {
let mut out = BTreeMap::new();
let mut elements_filtered = HashSet::new();
if max_elem_paths_per_warning_id == 0 {
for group in warnings.values() {
let Group { element, warnings } = group;
for w in warnings {
if let btree_map::Entry::Vacant(entry) = out.entry(w.id()) {
entry.insert(vec![]);
}
}
elements_filtered.insert(element.path.as_str());
}
} else {
for group in warnings.values() {
let Group { element, warnings } = group;
let path = element.path.as_str();
for w in warnings {
let id = w.id();
match out.entry(id.clone()) {
btree_map::Entry::Vacant(entry) => {
entry.insert(vec![path]);
}
btree_map::Entry::Occupied(mut entry) => {
if entry.get().len() < max_elem_paths_per_warning_id {
entry.get_mut().push(path);
} else {
elements_filtered.insert(path);
}
}
}
}
}
}
LimitReport {
warnings: out,
elements_filtered: elements_filtered.len(),
warning_distinct_types_filtered: 0,
}
}
fn limit_all<W: Warning>(
max_warning_types: usize,
max_elem_paths_per_warning_id: usize,
warnings: &BTreeMap<json::ElemId, Group<W>>,
) -> LimitReport<'_> {
let mut out = BTreeMap::new();
let mut elements_filtered = HashSet::new();
let mut warning_distinct_types_filtered = HashSet::new();
if max_warning_types > 0 && max_elem_paths_per_warning_id == 0 {
for group in warnings.values() {
let Group { element, warnings } = group;
let path = element.path.as_str();
for w in warnings {
let len = out.len();
let id = w.id();
if let btree_map::Entry::Vacant(entry) = out.entry(id.clone()) {
if len < max_warning_types {
entry.insert(vec![]);
} else {
warning_distinct_types_filtered.insert(id);
}
}
}
elements_filtered.insert(path);
}
} else {
for group in warnings.values() {
let Group { element, warnings } = group;
let path = element.path.as_str();
for w in warnings {
let len = out.len();
let id = w.id();
match out.entry(id.clone()) {
btree_map::Entry::Vacant(entry) => {
if len < max_warning_types {
entry.insert(vec![path]);
} else {
warning_distinct_types_filtered.insert(id);
elements_filtered.insert(path);
}
}
btree_map::Entry::Occupied(mut entry) => {
if entry.get().len() < max_elem_paths_per_warning_id {
entry.get_mut().push(path);
} else {
elements_filtered.insert(path);
}
}
}
}
}
}
LimitReport {
warnings: out,
elements_filtered: elements_filtered.len(),
warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
}
}
#[derive(Debug)]
pub struct IdPathMap<'set> {
pub total_warnings: usize,
pub total_elements: usize,
pub elements_filtered: usize,
pub warning_distinct_types_filtered: usize,
pub warnings: BTreeMap<Id, Vec<&'set str>>,
}
#[derive(Debug)]
pub struct MsgPathMap<'set> {
pub total_warnings: usize,
pub total_elements: usize,
pub elements_filtered: usize,
pub warning_distinct_types_filtered: usize,
pub warnings: BTreeMap<String, Vec<&'set str>>,
}
#[derive(Copy, Clone, Debug)]
pub enum Limit {
None,
WarningTypes(usize),
ElemPathsPerId(usize),
All {
max_warning_types: usize,
max_elem_paths_per_warning_id: usize,
},
}
#[derive(Debug)]
pub struct Failure<W: Warning> {
error: Box<Error<W>>,
warnings: Set<W>,
}
impl<W> Failure<W>
where
W: Warning,
{
pub fn warnings(&self) -> &Set<W> {
&self.warnings
}
pub fn into_parts(self) -> (Error<W>, Set<W>) {
let Self { error, warnings } = self;
(*error, warnings)
}
pub fn ignore_warnings(self) -> Error<W> {
*self.error
}
}
#[derive(Debug)]
pub struct Group<W: Warning> {
element: Element,
warnings: Vec<Source<W>>,
}
impl<W> Group<W>
where
W: Warning,
{
pub fn into_parts(self) -> (Element, Vec<W>) {
let Self { element, warnings } = self;
let warnings = warnings.into_iter().map(Source::into_warning).collect();
(element, warnings)
}
pub fn to_parts(&self) -> (&Element, Vec<&W>) {
let Self { element, warnings } = self;
let warnings = warnings.iter().map(|w| &**w).collect();
(element, warnings)
}
pub fn warnings(&self) -> Vec<&W> {
self.warnings.iter().map(|w| &**w).collect()
}
pub fn into_warnings(self) -> Vec<W> {
let Self {
element: _,
warnings,
} = self;
warnings.into_iter().map(Source::into_warning).collect()
}
}
pub struct Iter<'caller, W>
where
W: Warning,
{
warnings: btree_map::Iter<'caller, json::ElemId, Group<W>>,
}
impl<W> Iter<'_, W> where W: Warning {}
impl<'caller, W: Warning> Iterator for Iter<'caller, W> {
type Item = &'caller Group<W>;
fn next(&mut self) -> Option<Self::Item> {
let (_elem_id, group) = self.warnings.next()?;
Some(group)
}
}
pub struct IntoIter<W>
where
W: Warning,
{
warnings: btree_map::IntoIter<json::ElemId, Group<W>>,
}
impl<W: Warning> Iterator for IntoIter<W> {
type Item = Group<W>;
fn next(&mut self) -> Option<Self::Item> {
let (_elem_id, group) = self.warnings.next()?;
Some(group)
}
}
impl<W: Warning> IntoIterator for Set<W> {
type Item = Group<W>;
type IntoIter = IntoIter<W>;
fn into_iter(self) -> Self::IntoIter {
let Set(warnings) = self;
IntoIter {
warnings: warnings.into_iter(),
}
}
}
impl<'a, W: Warning> IntoIterator for &'a Set<W> {
type Item = &'a Group<W>;
type IntoIter = Iter<'a, W>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}