1use std::fmt;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "lowercase")]
8pub enum Severity {
9 Error,
11 Warning,
13}
14
15impl fmt::Display for Severity {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 f.write_str(match self {
18 Severity::Error => "error",
19 Severity::Warning => "warning",
20 })
21 }
22}
23
24#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
26pub struct Problem {
27 pub file: String,
29 pub line: u32,
31 pub column: u32,
33 pub key: String,
35 pub message: String,
37 pub severity: Severity,
39}
40
41impl fmt::Display for Problem {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 let mut parts = Vec::with_capacity(3);
45 parts.push(if self.line > 0 { format!("{}:{}", self.file, self.line) } else { self.file.clone() });
46 if !self.key.is_empty() {
47 parts.push(self.key.clone());
48 }
49 if !self.message.is_empty() {
50 parts.push(self.message.clone());
51 }
52 f.write_str(&parts.join(" "))
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Default)]
58pub struct Place {
59 pub file: String,
61 pub line: u32,
63 pub column: u32,
65 pub key: String,
67}
68
69#[derive(Debug, Clone, Default)]
71pub struct Problems {
72 pub list: Vec<Problem>,
74}
75
76impl Problems {
77 pub fn error(&mut self, at: &Place, message: impl Into<String>) {
79 self.add(at, message, Severity::Error);
80 }
81
82 pub fn warning(&mut self, at: &Place, message: impl Into<String>) {
84 self.add(at, message, Severity::Warning);
85 }
86
87 pub fn add(&mut self, at: &Place, message: impl Into<String>, severity: Severity) {
89 self.list.push(Problem {
90 file: at.file.clone(),
91 line: at.line,
92 column: at.column,
93 key: at.key.clone(),
94 message: message.into(),
95 severity,
96 });
97 }
98
99 pub fn sort(&mut self) {
101 let mut files: Vec<String> = Vec::new();
102 for p in &self.list {
103 if !files.contains(&p.file) {
104 files.push(p.file.clone());
105 }
106 }
107 self.list.sort_by_key(|p| (files.iter().position(|f| *f == p.file).unwrap_or(0), p.line));
108 }
109
110 pub fn strict(&mut self) {
112 for p in &mut self.list {
113 p.severity = Severity::Error;
114 }
115 }
116
117 pub fn failed(&self) -> bool {
119 self.list.iter().any(|p| p.severity == Severity::Error)
120 }
121}
122
123pub fn error_text(problems: &[Problem]) -> String {
125 problems.iter().filter(|p| p.severity == Severity::Error).map(|p| p.to_string()).collect::<Vec<_>>().join("\n")
126}