Skip to main content

adam_lsp/
diagnostics.rs

1//! Checks Adam source text without executing it or opening an LSP transport.
2//!
3//! ```rust
4//! let diagnostics = adam_lsp::diagnostics::diagnostics_for_source(
5//!     "sheet example { cell x: i32 = true; }",
6//! );
7//! assert!(!diagnostics.is_empty());
8//! ```
9
10use adam_lang::{
11    AdamAstParser, ModuleDiagnostic, ModulePath, ModuleSet, TypeRegistry, ast, check_module,
12    check_sheet,
13};
14use cel_parser::{CELError, SourceSpan};
15use lsp_types::{Diagnostic, DiagnosticSeverity, Position, Range};
16
17/// Parses and checks one complete Adam module without executing its expressions.
18///
19/// Returns every recovered syntax error. Checks syntactically clean modules,
20/// including local component definitions and named bindings, with [`check_module`].
21/// A single root without component uses retains [`check_sheet`]'s recovered
22/// syntax/type diagnostics and expression-level ranges.
23/// External imports require the explicit source collection accepted by
24/// [`diagnostics_for_module`]; this convenience checker does no source discovery.
25///
26/// The environment explicitly includes the standard library and optional Euclid geometry,
27/// matching the executing web/book hosts. Unresolved call-result shapes remain best-effort.
28/// Diagnostic columns count UTF-16 code units in the supplied text.
29///
30/// - Complexity: parsing, environment setup and module checking costs plus O(en + b)
31///   diagnostic projection time for source bytes n, e errors and b message bytes;
32///   space for parsed/checker state and returned diagnostics, with no caching.
33///
34/// # Examples
35///
36/// ```
37/// use adam_lsp::diagnostics::diagnostics_for_source;
38///
39/// assert!(diagnostics_for_source("sheet s { cell x: i32 = 1; }").is_empty());
40/// assert_eq!(diagnostics_for_source("sheet s { cell x: i32 = 1.0; }").len(), 1);
41/// ```
42pub fn diagnostics_for_source(source: &str) -> Vec<Diagnostic> {
43    let mut parser = AdamAstParser::new();
44    let module = match parser.parse_module_str(source) {
45        Ok(module) => module,
46        Err(e) => return vec![to_diagnostic(e.into(), source)],
47    };
48    if let [ast::ModuleItem::Sheet(sheet)] = module.items.as_slice()
49        && !requires_module_checking(sheet)
50    {
51        let (types, lookup) = configured_environment();
52        return sheet
53            .errors
54            .iter()
55            .cloned()
56            .chain(check_sheet(sheet, &types, &lookup))
57            .map(|error| to_diagnostic(error.into(), source))
58            .collect();
59    }
60    if !module.errors.is_empty() {
61        return module
62            .errors
63            .into_iter()
64            .map(|e| to_diagnostic(e.into(), source))
65            .collect();
66    }
67    drop(module);
68    let path: ModulePath = "document".parse().expect("valid internal module path");
69    let mut modules = ModuleSet::new();
70    if let Err(error) = modules.insert_source(path.clone(), "<document>", source) {
71        return vec![to_module_diagnostic(error)];
72    }
73    diagnostics_for_module(&path, &modules)
74        .into_iter()
75        .map(to_module_diagnostic)
76        .collect()
77}
78
79/// Identifies component definitions and uses, including conditional/default branches.
80///
81/// - Complexity: O(n) time for n sheet and branch items; O(1) additional space.
82fn requires_module_checking(sheet: &ast::Sheet) -> bool {
83    sheet.parameters.is_some()
84        || sheet.items.iter().any(|item| match item {
85            ast::SheetItem::RelationshipUse(_) => true,
86            ast::SheetItem::Conditional(conditional) => conditional
87                .branches
88                .iter()
89                .map(|branch| &branch.relationships)
90                .chain(
91                    conditional
92                        .default
93                        .iter()
94                        .map(|branch| &branch.relationships),
95                )
96                .flatten()
97                .any(|item| matches!(item, ast::BranchItem::RelationshipUse(_))),
98            _ => false,
99        })
100}
101
102/// Checks a registered module collection without executing defaults, methods or match keys.
103///
104/// Uses the same standard and Euclid libraries as [`diagnostics_for_source`].
105/// Includes all registered definitions and retains the actual source owners.
106/// An unknown requested module returns a diagnostic, never a source-only fallback.
107/// - Complexity: the configured libraries' setup plus [`check_module`]'s analysis cost.
108///
109/// # Examples
110///
111/// ```
112/// let path = "app".parse().unwrap();
113/// let mut modules = adam_lang::ModuleSet::new();
114/// modules.insert_source(path, "file:///app.adm2", "sheet app {}").unwrap();
115/// assert!(adam_lsp::diagnostics::diagnostics_for_module(
116///     &"app".parse().unwrap(), &modules
117/// ).is_empty());
118/// ```
119pub fn diagnostics_for_module(module: &ModulePath, modules: &ModuleSet) -> Vec<ModuleDiagnostic> {
120    let (types, lookup) = configured_environment();
121    check_module(module, modules, &types, &lookup)
122}
123
124/// Creates the common source-only and module-aware nonexecuting type environment.
125///
126/// - Complexity: O(s²) for s installed operation signatures.
127fn configured_environment() -> (TypeRegistry, cel_parser::OpLookup) {
128    let mut types = TypeRegistry::new();
129    cel_euclid::register_adam_types(&mut types);
130    let mut lookup = cel_parser::OpLookup::new();
131    cel_std::install(&mut lookup);
132    cel_euclid::install(&mut lookup);
133    (types, lookup)
134}
135
136/// Converts a [`CELError`] against its original text into an LSP diagnostic.
137///
138/// - Complexity: O(n + m) time for source-prefix bytes n and message bytes m;
139///   O(m) additional space.
140fn to_diagnostic(error: CELError, source: &str) -> Diagnostic {
141    Diagnostic {
142        range: source_range(source, error.span()),
143        severity: Some(DiagnosticSeverity::ERROR),
144        message: error.message().to_string(),
145        ..Default::default()
146    }
147}
148
149/// Projects a single-source module error without inventing an editor URI.
150///
151/// - Complexity: O(n + b) time and O(b) space for source-prefix bytes n and
152///   message/label bytes b.
153fn to_module_diagnostic(error: ModuleDiagnostic) -> Diagnostic {
154    let range = error
155        .labels
156        .iter()
157        .find_map(|label| label.location.as_ref())
158        .map(|location| source_range(location.source.text(), location.span))
159        .unwrap_or_default();
160    let mut message = error.message;
161    for label in error.labels {
162        if label.location.is_none() {
163            message.push('\n');
164            message.push_str(&label.label);
165        }
166    }
167    Diagnostic {
168        range,
169        severity: Some(DiagnosticSeverity::ERROR),
170        message,
171        ..Default::default()
172    }
173}
174
175/// Converts character columns in the original text to UTF-16 LSP positions.
176///
177/// - Precondition: `span` refers to `source`.
178/// - Complexity: O(n) time for the source prefix ending at the span; O(1) space.
179pub(crate) fn source_range(source: &str, span: SourceSpan) -> Range {
180    debug_assert!((span.start.line, span.start.column) <= (span.end.line, span.end.column));
181    let position = |line: usize, column: usize| {
182        let character = source
183            .lines()
184            .nth(line.saturating_sub(1))
185            .unwrap_or("")
186            .chars()
187            .take(column)
188            .map(char::len_utf16)
189            .sum::<usize>();
190        Position::new(line.saturating_sub(1) as u32, character as u32)
191    };
192    Range::new(
193        position(span.start.line, span.start.column),
194        position(span.end.line, span.end.column),
195    )
196}
197
198/// Verifies syntax/type diagnostic content and original-source UTF-16 projection.
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    /// Converts parsed type and lexical error columns to exact UTF-16 offsets.
204    #[test]
205    fn source_diagnostics_preserve_unicode_locations() {
206        for (source, token, length) in [
207            (
208                "// first line\n/* 😀 é */ sheet s { cell café: i32 = 1.0; }",
209                "1.0",
210                3,
211            ),
212            // Lexical failures identify a point rather than a complete token.
213            (
214                "// first line\n/* 😀 é */ sheet s { cell café: i32 = `; }",
215                "`",
216                0,
217            ),
218        ] {
219            let diagnostics = diagnostics_for_source(source);
220            assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
221            let offset = source.find(token).unwrap();
222            let column = source[..offset]
223                .rsplit('\n')
224                .next()
225                .unwrap()
226                .encode_utf16()
227                .count() as u32;
228            assert_eq!(diagnostics[0].range.start, Position::new(1, column));
229            assert_eq!(diagnostics[0].range.end, Position::new(1, column + length));
230        }
231    }
232
233    /// The LSP uses the same standard and Euclid metadata as executing hosts.
234    #[test]
235    fn lsp_geometry_fields_and_members_have_matching_diagnostics() {
236        let valid = "sheet s { out x := (|p: Point2D| p.x)(Point2D { y: 2.0, x: 1.0 }); out n := min(3.0, 4.0); }";
237        assert!(
238            diagnostics_for_source(valid).is_empty(),
239            "{:?}",
240            diagnostics_for_source(valid)
241        );
242        let invalid = "sheet s { out p := Point2D { x: true, y: 1.0 }; }";
243        let diagnostics = diagnostics_for_source(invalid);
244        assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
245        let invalid = "sheet s { out p := Point2D { x: 1.0, y: 1.0 }.translate(1.0); }";
246        assert!(!diagnostics_for_source(invalid).is_empty());
247        for actual in [
248            include_str!("../../cel-euclid/examples/crop_straighten.adm2"),
249            include_str!("../../cel-euclid/examples/pan_zoom.adm2"),
250        ] {
251            let diagnostics = diagnostics_for_source(actual);
252            assert!(diagnostics.is_empty(), "{diagnostics:?}");
253        }
254    }
255
256    /// Reports missing host schemas and still checks field expressions through the LSP path.
257    #[test]
258    fn unknown_record_and_child_errors_reach_lsp_diagnostics() {
259        let diagnostics =
260            diagnostics_for_source("sheet s {\n    out value := Missing { x: true + 1 }.x;\n}");
261        assert_eq!(diagnostics.len(), 2);
262        let missing = diagnostics
263            .iter()
264            .find(|d| d.message.contains("Missing"))
265            .unwrap();
266        assert_eq!(missing.range.start, Position::new(1, 17));
267        assert_eq!(missing.range.end, Position::new(1, 24));
268        assert!(diagnostics.iter().any(|d| d.message.contains("operand")));
269    }
270
271    /// Accepts a clean typed initializer.
272    #[test]
273    fn clean_sheet_has_no_diagnostics() {
274        assert!(diagnostics_for_source("sheet s { cell x: i32 = 1; }").is_empty());
275    }
276
277    /// Checks local component definitions and named bindings in an unregistered file.
278    #[test]
279    fn source_modules_support_component_definitions_and_named_bindings() {
280        let source = "sheet copy(input: i32, result: i32) {
281            relationship { result := input; }
282        }
283        sheet app {
284            source x: i32 = 1;
285            cell y: i32;
286            relationship copy(result: y, input: x);
287        }";
288        let diagnostics = diagnostics_for_source(source);
289        assert!(diagnostics.is_empty(), "{diagnostics:?}");
290
291        let diagnostics = diagnostics_for_source(&source.replace("result: y", "result: absent"));
292        assert!(
293            diagnostics
294                .iter()
295                .any(|error| error.message.contains("absent")),
296            "{diagnostics:?}"
297        );
298    }
299
300    /// Reports an unresolved import as a semantic error rather than rejecting `use`.
301    #[test]
302    fn source_modules_report_unresolved_imports() {
303        let diagnostics =
304            diagnostics_for_source("/* 😀 */ use missing::ordered as ord; sheet app {}");
305        assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
306        assert!(
307            diagnostics[0].message.contains("missing"),
308            "{diagnostics:?}"
309        );
310        assert_eq!(
311            diagnostics[0].range,
312            Range::new(Position::new(0, 9), Position::new(0, 37))
313        );
314    }
315
316    /// Checks named uses in a single root, including inactive and default branches.
317    #[test]
318    fn source_modules_check_single_root_component_uses() {
319        for body in [
320            "relationship missing();",
321            "conditional false { true => { relationship missing(); } }",
322            "conditional false { _ => { relationship missing(); } }",
323        ] {
324            let diagnostics = diagnostics_for_source(&format!("sheet app {{ {body} }}"));
325            assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
326            assert!(
327                diagnostics[0].message.contains("missing"),
328                "{diagnostics:?}"
329            );
330        }
331    }
332
333    /// Retains every recovered syntax error after a valid import declaration.
334    #[test]
335    fn source_modules_recover_errors_after_imports() {
336        let diagnostics = diagnostics_for_source(
337            "use missing::ordered;
338             sheet app { cell x unknown_syntax; cell y unknown_syntax; }",
339        );
340        assert_eq!(diagnostics.len(), 2, "{diagnostics:?}");
341        assert!(diagnostics.iter().all(|error| error.range.start.line == 1));
342    }
343
344    /// Reports a mismatched initializer with error severity.
345    #[test]
346    fn type_mismatched_cell_initializer_is_a_diagnostic() {
347        // Unsuffixed float literal defaults to f64, not the declared i32 — same fixture used by
348        // adam-lang's own `check_sheet` test suite (adam-lang/src/typecheck.rs).
349        let diags = diagnostics_for_source("sheet s { cell x: i32 = 1.0; }");
350        assert_eq!(diags.len(), 1);
351        assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
352    }
353
354    /// Publishes a recovered declaration error.
355    #[test]
356    fn recovered_syntax_error_is_a_diagnostic() {
357        // Malformed cell declaration; AdamAstParser recovers it as one `Sheet.errors` entry
358        // (adam-lang/src/ast_parser.rs's `parse_malformed_cell_is_recorded_as_an_error_item`).
359        assert_eq!(
360            diagnostics_for_source("sheet s { cell x unknown_syntax }").len(),
361            1
362        );
363    }
364
365    /// Publishes every file-level recovery error for malformed module declarations.
366    #[test]
367    fn malformed_module_declarations_are_diagnostics() {
368        assert_eq!(diagnostics_for_source("not a sheet at all").len(), 2);
369    }
370
371    /// Accepts a correctly typed placeholder filter.
372    #[test]
373    fn filter_clause_with_matching_types_has_no_diagnostics() {
374        assert!(diagnostics_for_source("sheet s { cell a: i32 = 1 filter _; }").is_empty());
375    }
376
377    /// Rejects a filter that omits its placeholder.
378    #[test]
379    fn filter_clause_without_underscore_is_a_diagnostic() {
380        let diags = diagnostics_for_source("sheet s { cell a: i32 = 1 filter 1; }");
381        assert_eq!(diags.len(), 1);
382    }
383}