1use 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
17pub 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
79fn 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
102pub 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
124fn 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
136fn 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
149fn 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
175pub(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#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[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 (
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 #[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 #[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 #[test]
273 fn clean_sheet_has_no_diagnostics() {
274 assert!(diagnostics_for_source("sheet s { cell x: i32 = 1; }").is_empty());
275 }
276
277 #[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 #[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 #[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 #[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 #[test]
346 fn type_mismatched_cell_initializer_is_a_diagnostic() {
347 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 #[test]
356 fn recovered_syntax_error_is_a_diagnostic() {
357 assert_eq!(
360 diagnostics_for_source("sheet s { cell x unknown_syntax }").len(),
361 1
362 );
363 }
364
365 #[test]
367 fn malformed_module_declarations_are_diagnostics() {
368 assert_eq!(diagnostics_for_source("not a sheet at all").len(), 2);
369 }
370
371 #[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 #[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}