Skip to main content

dive_api/
analyze.rs

1//! Semantic analysis reports (`dive analyze`).
2
3use dive_sema::model::{DefKind, Model, NodeKind};
4use dive_sema::{Analysis, FileId, Options, SearchPath, Severity};
5use dive_syntax::diagnostics::line_col;
6use serde_json::{Value, json};
7use std::path::{Path, PathBuf};
8
9/// Version of the JSON document produced by [`AnalyzeReport::to_json`].
10///
11/// It follows the conventions of [`crate::PARSE_SCHEMA_VERSION`]: the same
12/// diagnostic and span shapes, with a `file` on every diagnostic because an
13/// analysis spans several files. Bump it on any incompatible change.
14pub const ANALYZE_SCHEMA_VERSION: u32 = crate::REPORT_SCHEMA_VERSION;
15
16/// Where `dive analyze` looks for modules besides the root file's directory.
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
18pub struct AnalyzeOptions {
19    /// Searched before the standard modules (SANY's `TLA-Library`).
20    pub library_paths: Vec<PathBuf>,
21    /// Searched after the standard modules (where TLC finds modules on its
22    /// Java classpath, such as the `CommunityModules` jar).
23    pub after_standard: Vec<PathBuf>,
24}
25
26/// The outcome of analysing a specification.
27#[derive(Debug, Clone)]
28pub struct AnalyzeReport {
29    file: String,
30    analysis: Analysis,
31}
32
33/// Analyses the specification rooted at `path`: module resolution, name
34/// resolution, arity and level checking, as SANY's `-error-codes` run.
35///
36/// # Errors
37///
38/// [`crate::ApiError`] if the root file cannot be read.
39pub fn analyze_file(
40    path: &Path,
41    options: &AnalyzeOptions,
42) -> Result<AnalyzeReport, crate::ApiError> {
43    let opts = Options {
44        search: SearchPath {
45            library_paths: options.library_paths.clone(),
46            after_standard: options.after_standard.clone(),
47        },
48        ..Options::default()
49    };
50    let shown = path.display().to_string();
51    let analysis = dive_sema::analyze_file(path, &opts).map_err(|error| crate::ApiError::Io {
52        path: shown.clone(),
53        error,
54    })?;
55    Ok(AnalyzeReport {
56        file: shown,
57        analysis,
58    })
59}
60
61/// Analyses source text as the root module; other modules come only from
62/// `options` and the standard modules.
63#[must_use]
64pub fn analyze_source(file: &str, source: &str, options: &AnalyzeOptions) -> AnalyzeReport {
65    let opts = Options {
66        search: SearchPath {
67            library_paths: options.library_paths.clone(),
68            after_standard: options.after_standard.clone(),
69        },
70        ..Options::default()
71    };
72    AnalyzeReport {
73        file: file.to_owned(),
74        analysis: dive_sema::analyze_source(file, source, &opts),
75    }
76}
77
78/// One diagnostic of either kind, flattened for output.
79struct Flat {
80    code: String,
81    severity: Severity,
82    message: String,
83    help: Option<String>,
84    sany: Option<u16>,
85    file: Option<FileId>,
86    range: Option<dive_syntax::TextRange>,
87    related: Vec<(FileId, dive_syntax::TextRange, String)>,
88}
89
90impl AnalyzeReport {
91    /// A report of an analysis made elsewhere (`dive check`).
92    pub(crate) fn from_analysis(file: String, analysis: Analysis) -> Self {
93        Self { file, analysis }
94    }
95
96    /// Whether SANY would accept the specification.
97    #[must_use]
98    pub fn accepted(&self) -> bool {
99        self.analysis.accepted()
100    }
101
102    /// The underlying analysis, including the semantic model.
103    #[must_use]
104    pub fn analysis(&self) -> &Analysis {
105        &self.analysis
106    }
107
108    /// The loaded modules' names in analysis order (root last).
109    #[must_use]
110    pub fn modules(&self) -> Vec<String> {
111        let m = self.analysis.model();
112        m.modules()
113            .iter()
114            .filter_map(|&id| m.symbol_name(id).map(str::to_owned))
115            .collect()
116    }
117
118    fn flat(&self) -> Vec<Flat> {
119        let mut out = Vec::new();
120        for (f, d) in self.analysis.syntax_diagnostics() {
121            out.push(Flat {
122                code: d.code.as_str().to_owned(),
123                severity: if d.is_error() {
124                    Severity::Error
125                } else {
126                    Severity::Warning
127                },
128                message: d.message.clone(),
129                help: d.help.clone(),
130                sany: None,
131                file: Some(*f),
132                range: Some(d.range),
133                related: Vec::new(),
134            });
135        }
136        for d in self.analysis.diagnostics() {
137            out.push(Flat {
138                code: d.code.as_str().to_owned(),
139                severity: d.severity,
140                message: d.message.clone(),
141                help: crate::diagnostics::semantic_help(d.code, d.help.as_deref()),
142                sany: d.sany,
143                file: d.span.map(|s| s.file),
144                range: d.span.map(|s| s.range),
145                related: d
146                    .related
147                    .iter()
148                    .map(|r| (r.span.file, r.span.range, r.message.clone()))
149                    .collect(),
150            });
151        }
152        out
153    }
154
155    fn file_name(&self, f: FileId) -> String {
156        self.analysis
157            .file(f)
158            .map_or_else(|| self.file.clone(), |s| s.display.clone())
159    }
160
161    fn line_col(&self, f: FileId, at: dive_syntax::TextSize) -> (u32, u32) {
162        self.analysis
163            .file(f)
164            .map_or((0, 0), |s| line_col(&s.text, at))
165    }
166
167    /// The diagnostics in a human-readable form, one per line, like
168    /// `file:3:7: error[DIVE-E0100] (SANY 4200): message`.
169    #[must_use]
170    pub fn render_human(&self) -> String {
171        use std::fmt::Write as _;
172        let mut s = String::new();
173        for d in self.flat() {
174            let sev = match d.severity {
175                Severity::Error => "error",
176                Severity::Warning => "warning",
177            };
178            let loc = match (d.file, d.range) {
179                (Some(fid), Some(range)) => {
180                    let (line, col) = self.line_col(fid, range.start());
181                    format!("{}:{line}:{col}", self.file_name(fid))
182                }
183                _ => self.file.clone(),
184            };
185            let sany = d.sany.map(|c| format!(" (SANY {c})")).unwrap_or_default();
186            let _ = writeln!(s, "{loc}: {sev}[{}]{sany}: {}", d.code, d.message);
187            for (f, r, m) in &d.related {
188                let (l, c) = self.line_col(*f, r.start());
189                let _ = writeln!(s, "  note: {}:{l}:{c}: {m}", self.file_name(*f));
190            }
191            if let Some(h) = &d.help {
192                let _ = writeln!(s, "  help: {h}");
193            }
194        }
195        s
196    }
197
198    fn span_json(&self, f: FileId, r: dive_syntax::TextRange) -> Value {
199        let (line, column) = self.line_col(f, r.start());
200        let (end_line, end_column) = self.line_col(f, r.end());
201        json!({
202            "start": u32::from(r.start()),
203            "end": u32::from(r.end()),
204            "line": line,
205            "column": column,
206            "end_line": end_line,
207            "end_column": end_column,
208        })
209    }
210
211    /// The versioned JSON report.
212    ///
213    /// Shape (schema version 3):
214    ///
215    /// ```text
216    /// { "schema_version": 3, "command": "analyze", "file": "...",
217    ///   "accepted": bool, "module": "Root" | null, "modules": ["Dep", ..., "Root"],
218    ///   "files": [ { "id", "path", "origin": "file"|"standard"|"monolith"|"text" } ],
219    ///   "diagnostics": [ { "code", "severity", "message", "help", "sany_code",
220    ///                      "file", "span": { "start", "end", "line", "column",
221    ///                                        "end_line", "end_column" } | null,
222    ///                      "related": [ { "file", "span", "message" } ] } ],
223    ///   "definitions": [ { "name", "arity", "level" } ]   // root module, when accepted
224    /// }
225    /// ```
226    ///
227    /// `file` fields are indexes into `files`. Offsets are bytes; lines and
228    /// columns are 1-based, columns count Unicode scalar values. Levels are
229    /// `"constant"`, `"state"`, `"action"` or `"temporal"`.
230    #[must_use]
231    pub fn to_json(&self) -> Value {
232        let files: Vec<Value> = self
233            .analysis
234            .files()
235            .iter()
236            .enumerate()
237            .map(|(i, f)| {
238                let origin = match &f.origin {
239                    dive_sema::Origin::File(_) => "file",
240                    dive_sema::Origin::Standard => "standard",
241                    dive_sema::Origin::Bundled => "bundled",
242                    dive_sema::Origin::Monolith(_) => "monolith",
243                    dive_sema::Origin::Text => "text",
244                    _ => "unknown",
245                };
246                json!({ "id": i, "path": f.display, "origin": origin })
247            })
248            .collect();
249        let diagnostics: Vec<Value> = self
250            .flat()
251            .into_iter()
252            .map(|d| {
253                let span = match (d.file, d.range) {
254                    (Some(f), Some(r)) => self.span_json(f, r),
255                    _ => Value::Null,
256                };
257                let related: Vec<Value> = d
258                    .related
259                    .iter()
260                    .map(|(f, r, m)| json!({ "file": f.index(), "span": self.span_json(*f, *r), "message": m }))
261                    .collect();
262                json!({
263                    "code": d.code,
264                    "severity": match d.severity { Severity::Error => "error", Severity::Warning => "warning" },
265                    "message": d.message,
266                    "help": d.help,
267                    "sany_code": d.sany,
268                    "file": d.file.map(FileId::index),
269                    "span": span,
270                    "related": related,
271                })
272            })
273            .collect();
274        let modules = self.modules();
275        json!({
276            "schema_version": ANALYZE_SCHEMA_VERSION,
277            "command": "analyze",
278            "file": self.file,
279            "accepted": self.accepted(),
280            "module": modules.last(),
281            "modules": modules,
282            "files": files,
283            "diagnostics": diagnostics,
284            "definitions": if self.accepted() { definitions(self.analysis.model()) } else { Vec::new() },
285        })
286    }
287}
288
289/// The root module's own top-level definitions with their levels.
290fn definitions(m: &Model) -> Vec<Value> {
291    let Some(root) = m.root() else {
292        return Vec::new();
293    };
294    let NodeKind::Module(md) = &m.node(root).kind else {
295        return Vec::new();
296    };
297    m.context(md.ctx)
298        .entries()
299        .filter_map(|(_, d)| match &m.node(d).kind {
300            NodeKind::OpDef(od) if od.kind == DefKind::UserDefined && od.module == Some(root) => {
301                Some(json!({
302                    "name": m.name(od.name),
303                    "arity": od.arity,
304                    "level": level_name(m.level(d)),
305                }))
306            }
307            NodeKind::ThmOrAssumpDef(td) if td.module == Some(root) => Some(json!({
308                "name": m.name(td.name),
309                "arity": td.params.len(),
310                "level": level_name(m.level(d)),
311            })),
312            _ => None,
313        })
314        .collect()
315}
316
317fn level_name(l: dive_sema::Level) -> &'static str {
318    match l {
319        dive_sema::Level::Constant => "constant",
320        dive_sema::Level::State => "state",
321        dive_sema::Level::Action => "action",
322        dive_sema::Level::Temporal => "temporal",
323    }
324}