1
// Basic syntactic error detection helpers for the LSP API.
2

            
3
use crate::diagnostics::diagnostics_api::{Diagnostic, Position, Range, Severity};
4
use crate::errors::RecoverableParseError;
5
use crate::parse_essence_with_context_and_map;
6
use conjure_cp_core::context::Context;
7
use std::sync::{Arc, RwLock};
8
use tree_sitter::Tree;
9

            
10
999
pub fn detect_errors(source: &str, cst: &Tree) -> Vec<Diagnostic> {
11
999
    let mut diagnostics: Vec<Diagnostic> = Vec::new();
12
999
    let mut errors: Vec<RecoverableParseError> = vec![];
13
999
    let context = Arc::new(RwLock::new(Context::default()));
14

            
15
999
    let _ = parse_essence_with_context_and_map(source, context, &mut errors, Some(cst));
16

            
17
999
    diagnostics.extend(errors.into_iter().map(|e| error_to_diagnostic(&e)));
18

            
19
999
    diagnostics
20
999
}
21

            
22
999
pub fn error_to_diagnostic(err: &RecoverableParseError) -> Diagnostic {
23
999
    let (start, end) = range_to_position(&err.range);
24
999
    Diagnostic {
25
999
        range: Range { start, end },
26
999
        severity: Severity::Error,
27
999
        source: "semantic error detection",
28
999
        message: err.msg.clone(),
29
999
    }
30
999
}
31

            
32
999
fn range_to_position(range: &Option<tree_sitter::Range>) -> (Position, Position) {
33
999
    match range {
34
999
        Some(r) => (
35
999
            Position {
36
999
                line: r.start_point.row as u32,
37
999
                character: r.start_point.column as u32,
38
999
            },
39
999
            Position {
40
999
                line: r.end_point.row as u32,
41
999
                character: r.end_point.column as u32,
42
999
            },
43
999
        ),
44
        None => (
45
            Position {
46
                line: 0,
47
                character: 0,
48
            },
49
            Position {
50
                line: 0,
51
                character: 0,
52
            },
53
        ),
54
    }
55
999
}
56

            
57
/// Helper function for tests to compare the actual diagnostic with the expected one.
58
999
pub fn check_diagnostic(
59
999
    diag: &Diagnostic,
60
999
    line_start: u32,
61
999
    char_start: u32,
62
999
    line_end: u32,
63
999
    char_end: u32,
64
999
    msg: &str,
65
999
) {
66
    // Checking range
67
999
    assert_eq!(diag.range.start.line, line_start);
68
999
    assert_eq!(diag.range.start.character, char_start);
69
999
    assert_eq!(diag.range.end.line, line_end);
70
999
    assert_eq!(diag.range.end.character, char_end);
71

            
72
    // Check the message
73
999
    assert_eq!(diag.message, msg);
74
999
}