summaryrefslogtreecommitdiff
path: root/support/texlab/crates/diagnostics/src/labels.rs
blob: 9a39f3f24b7b7a0fceba403ab545461a97d45f40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use base_db::{
    semantics::tex::{Label, LabelKind},
    util::queries,
    DocumentData, Workspace,
};
use itertools::Itertools;
use rustc_hash::{FxHashMap, FxHashSet};
use url::Url;

use crate::types::{Diagnostic, TexError};

pub fn detect_undefined_and_unused_labels(
    workspace: &Workspace,
    results: &mut FxHashMap<Url, Vec<Diagnostic>>,
) {
    let graphs: Vec<_> = workspace
        .iter()
        .map(|start| base_db::graph::Graph::new(workspace, start))
        .collect();

    for document in workspace.iter() {
        let DocumentData::Tex(data) = &document.data else {
            continue;
        };

        let mut label_refs = FxHashSet::default();
        let mut label_defs = FxHashSet::default();
        let project = graphs
            .iter()
            .filter(|graph| graph.preorder().contains(&document))
            .flat_map(|graph| graph.preorder());

        for label in project
            .filter_map(|child| child.data.as_tex())
            .flat_map(|data| data.semantics.labels.iter())
        {
            if label.kind == LabelKind::Definition {
                label_defs.insert(&label.name.text);
            } else {
                label_refs.insert(&label.name.text);
            }
        }

        for label in &data.semantics.labels {
            if label.kind != LabelKind::Definition && !label_defs.contains(&label.name.text) {
                let diagnostic = Diagnostic::Tex(label.name.range, TexError::UndefinedLabel);
                results
                    .entry(document.uri.clone())
                    .or_default()
                    .push(diagnostic);
            }

            if label.kind == LabelKind::Definition && !label_refs.contains(&label.name.text) {
                let diagnostic = Diagnostic::Tex(label.name.range, TexError::UnusedLabel);
                results
                    .entry(document.uri.clone())
                    .or_default()
                    .push(diagnostic);
            }
        }
    }
}

pub fn detect_duplicate_labels(
    workspace: &Workspace,
    results: &mut FxHashMap<Url, Vec<Diagnostic>>,
) {
    for conflict in queries::Conflict::find_all::<Label>(workspace) {
        let others = conflict
            .rest
            .iter()
            .map(|location| (location.document.uri.clone(), location.range))
            .collect();

        let diagnostic = Diagnostic::Tex(conflict.main.range, TexError::DuplicateLabel(others));
        results
            .entry(conflict.main.document.uri.clone())
            .or_default()
            .push(diagnostic);
    }
}