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