1use std::fmt;
4
5use sva_ast::Refusal;
6use sva_engine::EngineError;
7
8use crate::lint_code::LintCode;
9use crate::output::{Diagnostic, Severity};
10
11#[derive(Debug)]
13pub struct LintViolation {
14 pub code: LintCode,
15 pub severity: Severity,
16 pub subject: String,
17 pub message: String,
18 pub line: Option<usize>,
19}
20
21#[derive(Debug)]
23pub enum CliError {
24 Usage {
26 code: &'static str,
27 message: String,
28 },
29 Refusals(Vec<Refusal>),
30 Engine(EngineError),
31 BadTempo(String),
32 BadProbe(String),
33 Io(String),
34 NotFound(String),
36 Conflict {
38 by: &'static str,
39 message: String,
40 },
41 LintRefused(Vec<LintViolation>),
43}
44
45impl CliError {
46 pub fn usage(code: &'static str, message: impl Into<String>) -> CliError {
47 CliError::Usage {
48 code,
49 message: message.into(),
50 }
51 }
52}
53
54impl From<EngineError> for CliError {
55 fn from(e: EngineError) -> CliError {
56 CliError::Engine(e)
57 }
58}
59
60fn engine_error_path(e: &EngineError) -> Option<String> {
61 match e {
62 EngineError::Binding { node, .. } => Some(node.clone()),
63 EngineError::UnknownNode(p)
64 | EngineError::AmbiguousNode(p, _)
65 | EngineError::RefAboveRoot(p, _) => Some(p.clone()),
66 other => other.at().map(|at| at.node.clone()),
67 }
68}
69
70fn engine_error_span(e: &EngineError) -> Option<(usize, usize)> {
71 let span = match e {
72 EngineError::Binding { span, .. } => *span,
73 other => other.at().and_then(|at| at.span),
74 }?;
75 Some((span.start, span.end - span.start))
76}
77
78fn names_no_node(e: &EngineError) -> bool {
79 matches!(e, EngineError::UnknownNode(_))
80}
81
82impl CliError {
83 pub fn exit_code(&self) -> u8 {
84 match self {
85 CliError::Engine(e) if names_no_node(e) => 24,
86 CliError::Usage { .. }
87 | CliError::Refusals(_)
88 | CliError::Engine(_)
89 | CliError::BadTempo(_)
90 | CliError::BadProbe(_)
91 | CliError::LintRefused(_) => 3,
92 CliError::Conflict { .. } => 4,
93 CliError::NotFound(_) => 24,
94 CliError::Io(_) => 1,
95 }
96 }
97
98 pub fn code(&self) -> &'static str {
99 match self {
100 CliError::Engine(e) if names_no_node(e) => "not_found",
101 CliError::Usage { .. }
102 | CliError::Refusals(_)
103 | CliError::Engine(_)
104 | CliError::BadTempo(_)
105 | CliError::BadProbe(_)
106 | CliError::LintRefused(_) => "validation_error",
107 CliError::Conflict { .. } => "conflict",
108 CliError::NotFound(_) => "not_found",
109 CliError::Io(_) => "internal_error",
110 }
111 }
112
113 pub fn message(&self) -> String {
114 match self {
115 CliError::Usage { message, .. } => message.clone(),
116 CliError::Refusals(rs) => format!("{} refusal(s) parsing the composition", rs.len()),
117 CliError::Engine(e) => e.to_string(),
118 CliError::BadTempo(m) | CliError::BadProbe(m) | CliError::Io(m) => m.clone(),
119 CliError::NotFound(m) => m.clone(),
120 CliError::Conflict { message, .. } => message.clone(),
121 CliError::LintRefused(vs) => format!(
122 "{} lint violation(s)",
123 vs.iter().filter(|v| v.severity == Severity::Error).count()
124 ),
125 }
126 }
127
128 pub fn diagnostics(&self) -> Vec<Diagnostic> {
130 match self {
131 CliError::Refusals(rs) => rs
132 .iter()
133 .map(|r| {
134 Diagnostic::new(r.code.code_str(), r.reason.clone())
135 .at(
136 Some(r.at.path.clone()),
137 Some((r.at.span.start, r.at.span.end - r.at.span.start)),
138 )
139 .placed(r.at.start)
140 })
141 .collect(),
142 CliError::Engine(e) => vec![engine_diagnostic(e)],
143 CliError::BadTempo(m) => vec![
144 Diagnostic::new("tempo.invalid_bpm_meter", m.clone()).helped(
145 "state `variables/bpm` as a positive number and `variables/meter` as \
146 `<beats>/<note>`, e.g. `4/4`",
147 ),
148 ],
149 CliError::BadProbe(m) => vec![Diagnostic::new("probe.invalid_expression", m.clone())
150 .helped("name a node path that exists, or an expression in the same grammar a node file holds")],
151 CliError::Usage { code, message } => vec![Diagnostic::new(*code, message.clone())
152 .helped("`sva-cli --help` states every subcommand, its arguments and their defaults")],
153 CliError::Conflict { by, message } => vec![
154 Diagnostic::new(format!("{by}.already_exists"), message.clone())
155 .helped("pick a name nothing occupies, or remove what is there first"),
156 ],
157 CliError::NotFound(m) => vec![
158 Diagnostic::new("io.no_such_path", m.clone())
159 .helped("name a path that exists; `sva-cli lint` says what a composition holds"),
160 ],
161 CliError::LintRefused(vs) => vs
162 .iter()
163 .map(|v| lint_diagnostic(v.code, &v.subject, &v.message, v.severity, v.line))
164 .collect(),
165 CliError::Io(_) => Vec::new(),
166 }
167 }
168}
169
170pub fn warning_diagnostic(w: &sva_ast::song::Warning) -> Diagnostic {
172 Diagnostic::new(w.code, w.message.clone())
173 .with_severity(Severity::Warning)
174 .at(Some(w.file.clone()), Some((w.span.start, 0)))
175 .placed(Some(w.start))
176}
177
178fn engine_diagnostic(e: &EngineError) -> Diagnostic {
180 let held = match e {
181 EngineError::Refused(d) => {
182 Diagnostic::new(d.code.clone(), d.message.clone()).helped(d.help.clone())
183 }
184 other => Diagnostic::new(other.code(), other.to_string()),
185 };
186 held.at(engine_error_path(e), engine_error_span(e))
187}
188
189pub fn lint_diagnostic(
192 code: LintCode,
193 subject: &str,
194 message: &str,
195 severity: Severity,
196 line: Option<usize>,
197) -> Diagnostic {
198 Diagnostic::new(
199 format!("lint.{}", code.code_str()).replace('-', "_"),
200 message,
201 )
202 .with_severity(severity)
203 .at(Some(subject.to_string()), None)
204 .on_line(line)
205 .helped(code.help())
206}
207
208impl fmt::Display for CliError {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 write!(f, "{}", self.message())
211 }
212}
213
214impl std::error::Error for CliError {}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 #[test]
222 fn every_variant_answers_the_standards_own_code_and_exit_code() {
223 let cases: [(CliError, &str, u8); 7] = [
224 (CliError::NotFound("gone".to_string()), "not_found", 24),
225 (
226 CliError::Engine(EngineError::UnknownNode("gone".to_string())),
227 "not_found",
228 24,
229 ),
230 (
231 CliError::usage("cli.unknown_flag", "bad flag"),
232 "validation_error",
233 3,
234 ),
235 (
236 CliError::BadTempo("bad bpm".to_string()),
237 "validation_error",
238 3,
239 ),
240 (
241 CliError::Conflict {
242 by: "new",
243 message: "taken".to_string(),
244 },
245 "conflict",
246 4,
247 ),
248 (CliError::Io("disk".to_string()), "internal_error", 1),
249 (CliError::LintRefused(Vec::new()), "validation_error", 3),
250 ];
251 for (err, code, exit) in cases {
252 assert_eq!(err.code(), code, "{err:?}");
253 assert_eq!(err.exit_code(), exit, "{err:?}");
254 }
255 }
256
257 #[test]
259 fn an_argument_mistake_is_one_diagnostic_under_its_own_code() {
260 let refused = CliError::usage("query.unknown_argument", "`lines` takes no arguments");
261 assert_eq!(refused.message(), "`lines` takes no arguments");
262 let [d] = &refused.diagnostics()[..] else {
263 panic!("an argument mistake carries exactly one diagnostic");
264 };
265 assert_eq!(d.code, "query.unknown_argument");
266 assert_eq!(d.message, "`lines` takes no arguments");
267 assert!(d.help.is_some(), "and says where to look");
268 }
269}