Skip to main content

sva_core/
cli_error.rs

1// Concern: enumerates the pipeline error variants, exit codes, JSON codes and diagnostics | Non-concern: JSON envelope framing (output.rs), argv (sva-cli) | IO: none
2
3use std::fmt;
4
5use sva_ast::Refusal;
6use sva_engine::EngineError;
7
8use crate::lint_code::LintCode;
9use crate::output::{Diagnostic, Severity};
10
11/// One `lint` finding: its code, how hard it lands, and the node it is against.
12#[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/// Every expected failure mode this crate can hit; none of them a panic.
22#[derive(Debug)]
23pub enum CliError {
24    /// An argument mistake: `code` names which, `message` quotes the text it refuses.
25    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    /// A path the caller named that nothing answers for; an `Io` is one that is there.
35    NotFound(String),
36    /// A name already taken, as opposed to an `Io` the filesystem raised.
37    Conflict {
38        by: &'static str,
39        message: String,
40    },
41    /// Every `LintViolation` the scan found, not just the first.
42    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    /// Per-finding detail; empty only where the failure has no subject to locate it against.
129    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()).at(
135                        Some(r.at.path.clone()),
136                        Some((r.at.span.start, r.at.span.end - r.at.span.start)),
137                    )
138                })
139                .collect(),
140            CliError::Engine(e) => vec![engine_diagnostic(e)],
141            CliError::BadTempo(m) => vec![
142                Diagnostic::new("tempo.invalid_bpm_meter", m.clone()).helped(
143                    "state `variables/bpm` as a positive number and `variables/meter` as \
144                     `<beats>/<note>`, e.g. `4/4`",
145                ),
146            ],
147            CliError::BadProbe(m) => vec![Diagnostic::new("probe.invalid_expression", m.clone())
148                .helped("name a node path that exists, or an expression in the same grammar a node file holds")],
149            CliError::Usage { code, message } => vec![Diagnostic::new(*code, message.clone())
150                .helped("`sva-cli --help` states every subcommand, its arguments and their defaults")],
151            CliError::Conflict { by, message } => vec![
152                Diagnostic::new(format!("{by}.already_exists"), message.clone())
153                    .helped("pick a name nothing occupies, or remove what is there first"),
154            ],
155            CliError::NotFound(m) => vec![
156                Diagnostic::new("io.no_such_path", m.clone())
157                    .helped("name a path that exists; `sva-cli lint` says what a composition holds"),
158            ],
159            CliError::LintRefused(vs) => vs
160                .iter()
161                .map(|v| lint_diagnostic(v.code, &v.subject, &v.message, v.severity, v.line))
162                .collect(),
163            CliError::Io(_) => Vec::new(),
164        }
165    }
166}
167
168/// `Display` runs a refusal's three parts together; a diagnostic keeps each apart.
169fn engine_diagnostic(e: &EngineError) -> Diagnostic {
170    let held = match e {
171        EngineError::Refused(d) => {
172            Diagnostic::new(d.code.clone(), d.message.clone()).helped(d.help.clone())
173        }
174        other => Diagnostic::new(other.code(), other.to_string()),
175    };
176    held.at(engine_error_path(e), engine_error_span(e))
177}
178
179/// The one place a `lint` code becomes a diagnostic, so both of `lint`'s response paths
180/// namespace it, locate it and help against it identically.
181pub fn lint_diagnostic(
182    code: LintCode,
183    subject: &str,
184    message: &str,
185    severity: Severity,
186    line: Option<usize>,
187) -> Diagnostic {
188    Diagnostic::new(
189        format!("lint.{}", code.code_str()).replace('-', "_"),
190        message,
191    )
192    .with_severity(severity)
193    .at(Some(subject.to_string()), None)
194    .on_line(line)
195    .helped(code.help())
196}
197
198impl fmt::Display for CliError {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        write!(f, "{}", self.message())
201    }
202}
203
204impl std::error::Error for CliError {}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    /// The `cli` standard's table, and its rule that code and exit code always agree.
211    #[test]
212    fn every_variant_answers_the_standards_own_code_and_exit_code() {
213        let cases: [(CliError, &str, u8); 7] = [
214            (CliError::NotFound("gone".to_string()), "not_found", 24),
215            (
216                CliError::Engine(EngineError::UnknownNode("gone".to_string())),
217                "not_found",
218                24,
219            ),
220            (
221                CliError::usage("cli.unknown_flag", "bad flag"),
222                "validation_error",
223                3,
224            ),
225            (
226                CliError::BadTempo("bad bpm".to_string()),
227                "validation_error",
228                3,
229            ),
230            (
231                CliError::Conflict {
232                    by: "new",
233                    message: "taken".to_string(),
234                },
235                "conflict",
236                4,
237            ),
238            (CliError::Io("disk".to_string()), "internal_error", 1),
239            (CliError::LintRefused(Vec::new()), "validation_error", 3),
240        ];
241        for (err, code, exit) in cases {
242            assert_eq!(err.code(), code, "{err:?}");
243            assert_eq!(err.exit_code(), exit, "{err:?}");
244        }
245    }
246
247    /// Each argument mistake is its own code, its message the one line that names the text.
248    #[test]
249    fn an_argument_mistake_is_one_diagnostic_under_its_own_code() {
250        let refused = CliError::usage("query.unknown_argument", "`lines` takes no arguments");
251        assert_eq!(refused.message(), "`lines` takes no arguments");
252        let [d] = &refused.diagnostics()[..] else {
253            panic!("an argument mistake carries exactly one diagnostic");
254        };
255        assert_eq!(d.code, "query.unknown_argument");
256        assert_eq!(d.message, "`lines` takes no arguments");
257        assert!(d.help.is_some(), "and says where to look");
258    }
259}