1use lsp_types::{
2 Diagnostic, DiagnosticRelatedInformation, DiagnosticSeverity, Location, Range, Url,
3};
4
5use logicaffeine_base::Interner;
6use logicaffeine_language::error::{socratic_explanation, ParseError, ParseErrorKind};
7use logicaffeine_language::token::{Token, TokenType};
8
9use crate::index::{find_cause_keyword_span, find_last_token_span_for_name};
10use crate::line_index::LineIndex;
11use crate::pipeline::AnalysisError;
12
13pub fn convert_errors(
19 errors: &[ParseError],
20 tokens: &[Token],
21 interner: &Interner,
22 line_index: &LineIndex,
23 uri: Option<&Url>,
24) -> Vec<Diagnostic> {
25 errors
26 .iter()
27 .map(|e| error_to_diagnostic(e, tokens, interner, line_index, uri))
28 .collect()
29}
30
31fn error_to_diagnostic(
32 error: &ParseError,
33 tokens: &[Token],
34 interner: &Interner,
35 line_index: &LineIndex,
36 uri: Option<&Url>,
37) -> Diagnostic {
38 let start = line_index.position(error.span.start);
39 let end = line_index.position(error.span.end.max(error.span.start + 1));
40
41 let message = socratic_explanation(error, interner);
42 let decision = decision_for(&error.kind);
43 let related_information =
44 uri.and_then(|u| parse_error_related_info(error, tokens, interner, line_index, u));
45
46 Diagnostic {
47 range: Range { start, end },
48 severity: Some(decision.severity),
49 code: decision
50 .code
51 .map(|c| lsp_types::NumberOrString::String(c.to_string())),
52 code_description: match decision.docs {
53 DocsLink::Anchor(anchor) => code_description_for(anchor),
54 DocsLink::None(_) => None,
55 },
56 source: Some("logicaffeine".to_string()),
57 message,
58 related_information,
59 ..Default::default()
60 }
61}
62
63pub fn unused_variable_hints(
72 index: &crate::index::SymbolIndex,
73 line_index: &LineIndex,
74) -> Vec<Diagnostic> {
75 let mut hints = Vec::new();
76 for (def_idx, def) in index.definitions.iter().enumerate() {
77 if def.kind != crate::index::DefinitionKind::Variable {
78 continue;
79 }
80 if def.span == logicaffeine_language::token::Span::default() || def.name.starts_with('_') {
81 continue;
82 }
83 let used = index
84 .references
85 .iter()
86 .any(|r| r.definition_idx == Some(def_idx) && r.span.start != def.span.start);
87 if used {
88 continue;
89 }
90 hints.push(Diagnostic {
91 range: Range {
92 start: line_index.position(def.span.start),
93 end: line_index.position(def.span.end),
94 },
95 severity: Some(DiagnosticSeverity::HINT),
96 code: Some(lsp_types::NumberOrString::String(
97 "unused-variable".to_string(),
98 )),
99 code_description: code_description_for("2-variables--mutation"),
100 source: Some("logicaffeine".to_string()),
101 message: format!(
102 "'{name}' is never used.\n\nNothing reads '{name}' after this Let. \
103 Remove the statement, or use the value.",
104 name = def.name
105 ),
106 tags: Some(vec![lsp_types::DiagnosticTag::UNNECESSARY]),
107 ..Default::default()
108 });
109 }
110 hints
111}
112
113pub const ANALYSIS_DECISIONS: &[(&str, DiagnosticSeverity, &str)] = &[
116 (
117 "unused-variable",
118 DiagnosticSeverity::HINT,
119 "a faded nudge — an unused binding is often work in progress, never a failure",
120 ),
121 (
122 "shadowed-variable",
123 DiagnosticSeverity::WARNING,
124 "legal but usually unintended — the earlier binding silently becomes unreachable",
125 ),
126 (
127 "unused-function",
128 DiagnosticSeverity::HINT,
129 "a faded nudge, and only in programs with a Main — a library file's functions are its API",
130 ),
131 (
132 REFUSAL_CODE,
133 DiagnosticSeverity::ERROR,
134 "`largo build` stops at it — a page the browser build refuses does not ship, whatever the \
135 tree-walker runs",
136 ),
137];
138
139pub fn lgx_finding_diagnostics(
145 findings: &[logicaffeine_language::lgx::check::Finding],
146 line_index: &LineIndex,
147) -> Vec<Diagnostic> {
148 use logicaffeine_language::lgx::check::Severity;
149 findings
150 .iter()
151 .map(|f| Diagnostic {
152 range: Range {
153 start: line_index.position(f.span.start),
154 end: line_index.position(f.span.end.max(f.span.start + 1)),
155 },
156 severity: Some(match f.severity {
157 Severity::Error => DiagnosticSeverity::ERROR,
158 Severity::Warning => DiagnosticSeverity::WARNING,
159 }),
160 code: Some(lsp_types::NumberOrString::String(lgx_finding_code(&f.kind))),
161 source: Some("logicaffeine".to_string()),
162 message: f.message.clone(),
163 ..Default::default()
164 })
165 .collect()
166}
167
168pub fn lgx_finding_code(kind: &logicaffeine_language::lgx::check::FindingKind) -> String {
173 let debug = format!("{kind:?}");
174 let variant = debug
175 .split(|c: char| !c.is_ascii_alphanumeric())
176 .next()
177 .unwrap_or("");
178 let mut code = String::from("lgx");
179 for c in variant.chars() {
180 if c.is_ascii_uppercase() {
181 code.push('-');
182 }
183 code.push(c.to_ascii_lowercase());
184 }
185 code
186}
187
188pub fn copy_finding_diagnostics(
195 findings: &[logicaffeine_language::lint::Finding],
196 line_index: &LineIndex,
197) -> Vec<Diagnostic> {
198 use logicaffeine_language::lint::Severity;
199 findings
200 .iter()
201 .map(|f| Diagnostic {
202 range: Range {
203 start: line_index.position(f.span.start),
204 end: line_index.position(f.span.end.max(f.span.start + 1)),
205 },
206 severity: Some(match f.severity {
207 Severity::Warning => DiagnosticSeverity::WARNING,
208 }),
209 code: Some(lsp_types::NumberOrString::String(copy_finding_code(
210 &f.kind,
211 ))),
212 source: Some("logicaffeine".to_string()),
213 message: f.message.clone(),
214 ..Default::default()
215 })
216 .collect()
217}
218
219pub fn copy_finding_code(kind: &logicaffeine_language::lint::FindingKind) -> String {
222 let debug = format!("{kind:?}");
223 let variant = debug
224 .split(|c: char| !c.is_ascii_alphanumeric())
225 .next()
226 .unwrap_or("");
227 let mut code = String::from("copy");
228 for c in variant.chars() {
229 if c.is_ascii_uppercase() {
230 code.push('-');
231 }
232 code.push(c.to_ascii_lowercase());
233 }
234 code
235}
236
237pub fn refusal_diagnostics(
242 refusals: &[logicaffeine_compile::vm::compiler::Refusal],
243 line_index: &LineIndex,
244) -> Vec<Diagnostic> {
245 refusals
246 .iter()
247 .filter_map(|r| {
248 let at = r.at?;
249 Some(Diagnostic {
250 range: Range {
251 start: line_index.position(at.start),
252 end: line_index.position(at.end.max(at.start + 1)),
253 },
254 severity: Some(DiagnosticSeverity::ERROR),
255 code: Some(lsp_types::NumberOrString::String(REFUSAL_CODE.to_string())),
256 source: Some("logicaffeine".to_string()),
257 message: r.message.clone(),
258 ..Default::default()
259 })
260 })
261 .collect()
262}
263
264pub const REFUSAL_CODE: &str = "browser-tier-refusal";
266
267pub fn shadowing_warnings(
271 index: &crate::index::SymbolIndex,
272 line_index: &LineIndex,
273 uri: Option<&Url>,
274) -> Vec<Diagnostic> {
275 use std::collections::HashMap;
276 let mut by_name: HashMap<(&str, Option<usize>), Vec<&crate::index::Definition>> =
277 HashMap::new();
278 for def in &index.definitions {
279 if def.kind != crate::index::DefinitionKind::Variable
280 || def.span == logicaffeine_language::token::Span::default()
281 {
282 continue;
283 }
284 by_name
285 .entry((def.name.as_str(), def.scope.block_idx))
286 .or_default()
287 .push(def);
288 }
289
290 let mut warnings = Vec::new();
291 for ((name, _), mut defs) in by_name {
292 if defs.len() < 2 {
293 continue;
294 }
295 defs.sort_by_key(|d| d.span.start);
296 let first = defs[0];
297 for shadow in defs.iter().skip(1).filter(|d| d.span != first.span) {
298 warnings.push(Diagnostic {
299 range: Range {
300 start: line_index.position(shadow.span.start),
301 end: line_index.position(shadow.span.end),
302 },
303 severity: Some(DiagnosticSeverity::WARNING),
304 code: Some(lsp_types::NumberOrString::String(
305 "shadowed-variable".to_string(),
306 )),
307 code_description: code_description_for("2-variables--mutation"),
308 source: Some("logicaffeine".to_string()),
309 message: format!(
310 "'{name}' is declared again — the earlier '{name}' above becomes \
311 unreachable from here on. Did you mean to update it with \
312 'Set {name} to …', or does this new value deserve its own name?"
313 ),
314 related_information: uri.map(|u| {
315 vec![DiagnosticRelatedInformation {
316 location: Location {
317 uri: u.clone(),
318 range: Range {
319 start: line_index.position(first.span.start),
320 end: line_index.position(first.span.end),
321 },
322 },
323 message: format!("the earlier '{name}' is declared here"),
324 }]
325 }),
326 ..Default::default()
327 });
328 }
329 }
330 warnings
331}
332
333pub fn unused_function_hints(
336 index: &crate::index::SymbolIndex,
337 line_index: &LineIndex,
338) -> Vec<Diagnostic> {
339 let has_main = index.block_spans.iter().any(|(_, block_type, _)| {
340 matches!(block_type, logicaffeine_language::token::BlockType::Main)
341 });
342 if !has_main {
343 return Vec::new();
344 }
345
346 let mut hints = Vec::new();
347 for (def_idx, def) in index.definitions.iter().enumerate() {
348 if def.kind != crate::index::DefinitionKind::Function
349 || def.span == logicaffeine_language::token::Span::default()
350 {
351 continue;
352 }
353 let called = index
354 .references
355 .iter()
356 .any(|r| r.definition_idx == Some(def_idx) && r.span.start != def.span.start);
357 if called {
358 continue;
359 }
360 hints.push(Diagnostic {
361 range: Range {
362 start: line_index.position(def.span.start),
363 end: line_index.position(def.span.end),
364 },
365 severity: Some(DiagnosticSeverity::HINT),
366 code: Some(lsp_types::NumberOrString::String(
367 "unused-function".to_string(),
368 )),
369 code_description: code_description_for("7-functions--closures"),
370 source: Some("logicaffeine".to_string()),
371 message: format!(
372 "'{name}' is never called.\n\nNothing in this program calls '{name}'. \
373 Is it wired up yet, or left over from a refactor?",
374 name = def.name
375 ),
376 tags: Some(vec![lsp_types::DiagnosticTag::UNNECESSARY]),
377 ..Default::default()
378 });
379 }
380 hints
381}
382
383fn parse_error_related_info(
385 error: &ParseError,
386 tokens: &[Token],
387 interner: &Interner,
388 line_index: &LineIndex,
389 uri: &Url,
390) -> Option<Vec<DiagnosticRelatedInformation>> {
391 match &error.kind {
392 ParseErrorKind::UseAfterMove { name } => {
393 let cause_span =
394 find_cause_keyword_span(tokens, TokenType::Give, name, interner, error.span.start)?;
395 Some(vec![DiagnosticRelatedInformation {
396 location: Location {
397 uri: uri.clone(),
398 range: Range {
399 start: line_index.position(cause_span.start),
400 end: line_index.position(cause_span.end),
401 },
402 },
403 message: format!("'{}' was given away here", name),
404 }])
405 }
406 _ => None,
407 }
408}
409
410pub fn convert_analysis_errors(
415 errors: &[AnalysisError],
416 tokens: &[Token],
417 interner: &Interner,
418 line_index: &LineIndex,
419 uri: Option<&Url>,
420) -> Vec<Diagnostic> {
421 errors
422 .iter()
423 .filter(|e| !logicaffeine_language::parser::lgx_lower::is_compiler_written(&e.variable))
434 .map(|e| analysis_error_to_diagnostic(e, tokens, interner, line_index, uri))
435 .collect()
436}
437
438fn analysis_error_to_diagnostic(
439 error: &AnalysisError,
440 tokens: &[Token],
441 interner: &Interner,
442 line_index: &LineIndex,
443 uri: Option<&Url>,
444) -> Diagnostic {
445 let primary = error
448 .use_span
449 .and_then(|stmt| {
450 tokens
451 .iter()
452 .filter(|t| t.span.start >= stmt.start && t.span.end <= stmt.end)
453 .find(|t| {
454 crate::index::resolve_token_name(t, interner)
455 .map(|n| n == error.variable)
456 .unwrap_or(false)
457 })
458 .map(|t| t.span)
459 .or(Some(stmt))
460 })
461 .or_else(|| find_last_token_span_for_name(tokens, &error.variable, interner));
462 let (start, end) = if let Some(span) = primary {
463 (
464 line_index.position(span.start),
465 line_index.position(span.end),
466 )
467 } else {
468 let zero = lsp_types::Position {
470 line: 0,
471 character: 0,
472 };
473 (zero, zero)
474 };
475
476 let use_offset = primary.map(|s| s.start).unwrap_or(usize::MAX);
478 let related_information = uri.and_then(|u| {
479 build_related_information(error, tokens, interner, line_index, u, use_offset)
480 });
481
482 Diagnostic {
483 range: Range { start, end },
484 severity: Some(DiagnosticSeverity::ERROR),
485 code: Some(lsp_types::NumberOrString::String(error.code.to_string())),
486 code_description: docs_anchor_for_analysis_code(error.code).and_then(code_description_for),
487 source: Some("logicaffeine".to_string()),
488 message: error.message.clone(),
489 related_information,
490 ..Default::default()
491 }
492}
493
494fn build_related_information(
496 error: &AnalysisError,
497 tokens: &[Token],
498 interner: &Interner,
499 line_index: &LineIndex,
500 uri: &Url,
501 use_offset: usize,
502) -> Option<Vec<DiagnosticRelatedInformation>> {
503 let cause_message = error.cause_context.as_ref()?;
504
505 let keyword = match error.code {
507 "use-after-move" | "double-move" | "maybe-moved" => TokenType::Give,
508 "escape-return" | "escape-assignment" => TokenType::Zone,
509 _ => return None,
510 };
511
512 let cause_span = error.cause_span.or_else(|| {
515 find_cause_keyword_span(tokens, keyword, &error.variable, interner, use_offset)
516 })?;
517 let cause_start = line_index.position(cause_span.start);
518 let cause_end = line_index.position(cause_span.end);
519
520 Some(vec![DiagnosticRelatedInformation {
521 location: Location {
522 uri: uri.clone(),
523 range: Range {
524 start: cause_start,
525 end: cause_end,
526 },
527 },
528 message: cause_message.clone(),
529 }])
530}
531
532pub struct ErrorDecision {
539 pub severity: DiagnosticSeverity,
540 pub code: Option<&'static str>,
542 pub quickfix: Quickfix,
543 pub docs: DocsLink,
545}
546
547pub enum Quickfix {
549 Provided(&'static str),
551 None(&'static str),
553}
554
555pub enum DocsLink {
557 Anchor(&'static str),
561 None(&'static str),
563}
564
565fn docs_anchor_for_analysis_code(code: &str) -> Option<&'static str> {
568 match code {
569 "use-after-move" | "double-move" | "maybe-moved" => Some("13-output"),
570 "escape-return" | "escape-assignment" => {
571 Some("12-distributed-crdt-concurrency-networking-zones")
572 }
573 _ => None,
574 }
575}
576
577fn code_description_for(anchor: &str) -> Option<lsp_types::CodeDescription> {
579 Url::parse(&crate::teach_md::guide_url(anchor))
580 .ok()
581 .map(|href| lsp_types::CodeDescription { href })
582}
583
584pub fn decision_for(kind: &ParseErrorKind) -> ErrorDecision {
585 use DiagnosticSeverity as S;
586 let (severity, code, quickfix, docs) = match kind {
587 ParseErrorKind::IsValueEquality { .. } => (
589 S::WARNING,
590 Some("is-value-equality"),
591 Quickfix::Provided("Use 'equals' for value comparison"),
592 DocsLink::Anchor("3-arithmetic-comparison-logic-bitwise"),
593 ),
594 ParseErrorKind::GrammarError(_) => (
595 S::WARNING,
596 Some("grammar-error"),
597 Quickfix::None("the message itself names the correction; no single edit is safe"),
598 DocsLink::None("the guide documents constructs, not English orthography"),
599 ),
600
601 ParseErrorKind::ZeroIndex => (
603 S::INFORMATION,
604 Some("zero-index"),
605 Quickfix::Provided("Use 1-based indexing"),
606 DocsLink::Anchor("5-collections"),
607 ),
608
609 ParseErrorKind::UseAfterMove { .. } => (
611 S::ERROR,
612 Some("use-after-move"),
613 Quickfix::Provided("Use 'a copy of …' instead"),
614 DocsLink::Anchor("13-output"),
615 ),
616
617 ParseErrorKind::UndefinedVariable { .. } => (
619 S::ERROR,
620 Some("undefined-variable"),
621 Quickfix::Provided("Did you mean '<nearest definition>'?"),
622 DocsLink::Anchor("2-variables--mutation"),
623 ),
624
625 ParseErrorKind::TypeMismatch { .. } | ParseErrorKind::TypeMismatchDetailed { .. } => (
627 S::ERROR,
628 Some("type-mismatch"),
629 Quickfix::None("no conversion is safe for arbitrary expected/found pairs"),
630 DocsLink::Anchor("2-variables--mutation"),
631 ),
632 ParseErrorKind::InfiniteType { .. } => (
633 S::ERROR,
634 Some("infinite-type"),
635 Quickfix::None("breaking a type cycle requires restructuring, not an edit"),
636 DocsLink::None("the fix is structural; no guide section teaches type cycles"),
637 ),
638 ParseErrorKind::ArityMismatch { .. } => (
639 S::ERROR,
640 Some("arity-mismatch"),
641 Quickfix::None("which argument to add or drop is the author's call"),
642 DocsLink::Anchor("7-functions--closures"),
643 ),
644 ParseErrorKind::FieldNotFound { .. } => (
645 S::ERROR,
646 Some("field-not-found"),
647 Quickfix::None(
648 "the diagnostic anchors on the whole statement; the message lists the fields that exist",
649 ),
650 DocsLink::Anchor("8-structs-enums--field-access"),
651 ),
652 ParseErrorKind::NotAFunction { .. } => (
653 S::ERROR,
654 Some("not-a-function"),
655 Quickfix::None("the intended callee is unknowable from the call site"),
656 DocsLink::Anchor("7-functions--closures"),
657 ),
658 ParseErrorKind::InvalidRefinementPredicate => (
659 S::ERROR,
660 None,
661 Quickfix::None("a refinement predicate must be rethought, not patched"),
662 DocsLink::None("no diagnostic code to hang a codeDescription on"),
663 ),
664 ParseErrorKind::AstTooDeep { .. } => (
665 S::ERROR,
666 Some("ast-too-deep"),
667 Quickfix::None("nesting past the engine's recursion gate needs restructuring, not an edit"),
668 DocsLink::None("the depth limit is an engine gate, not a construct the guide teaches"),
669 ),
670
671 ParseErrorKind::UnexpectedToken { .. }
674 | ParseErrorKind::ExpectedContentWord { .. }
675 | ParseErrorKind::ExpectedCopula
676 | ParseErrorKind::UnknownQuantifier { .. }
677 | ParseErrorKind::UnknownModal { .. }
678 | ParseErrorKind::ExpectedVerb { .. }
679 | ParseErrorKind::ExpectedTemporalAdverb
680 | ParseErrorKind::ExpectedPresuppositionTrigger
681 | ParseErrorKind::ExpectedFocusParticle
682 | ParseErrorKind::ExpectedScopalAdverb
683 | ParseErrorKind::ExpectedSuperlativeAdjective
684 | ParseErrorKind::ExpectedComparativeAdjective
685 | ParseErrorKind::ExpectedThan
686 | ParseErrorKind::ExpectedNumber
687 | ParseErrorKind::ExpectedStatement
688 | ParseErrorKind::ExpectedKeyword { .. }
689 | ParseErrorKind::ExpectedExpression
690 | ParseErrorKind::ExpectedIdentifier
691 | ParseErrorKind::TrailingTokens { .. } => (
692 S::ERROR,
693 None,
694 Quickfix::None("word choice is the author's; the message lists examples"),
695 DocsLink::None("no diagnostic code; the socratic message already names example words"),
696 ),
697
698 ParseErrorKind::EmptyRestriction
700 | ParseErrorKind::GappingResolutionFailed
701 | ParseErrorKind::StativeProgressiveConflict
702 | ParseErrorKind::RespectivelyLengthMismatch { .. }
703 | ParseErrorKind::ScopeViolation(_)
704 | ParseErrorKind::UnresolvedPronoun { .. } => (
705 S::ERROR,
706 None,
707 Quickfix::None("requires restructuring the sentence, not a mechanical edit"),
708 DocsLink::None("no diagnostic code; logic-mode phenomena are beyond the quickguide"),
709 ),
710
711 ParseErrorKind::Custom(_) => (
714 S::ERROR,
715 None,
716 Quickfix::None("a catch-all message carries no structure to key a fix on"),
717 DocsLink::None("caller prose carries no stable identity to link"),
718 ),
719 };
720 ErrorDecision {
721 severity,
722 code,
723 quickfix,
724 docs,
725 }
726}
727
728#[cfg(test)]
729#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/diagnostics/tests.rs"]
730mod tests;
731
732#[cfg(test)]
733#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/diagnostics/squiggle_anchor_tests.rs"]
734mod squiggle_anchor_tests;