summaryrefslogtreecommitdiff
path: root/support/texlab/crates/base-db/src/diagnostics/bib.rs
blob: f931a43c5107f1c86894b69d8582a41a4d1e6cf2 (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
use rowan::{ast::AstNode, TextRange};
use syntax::bibtex::{self, HasDelims, HasEq, HasName, HasType, HasValue};

use crate::{Document, DocumentData};

use super::{Diagnostic, ErrorCode};

pub fn analyze(document: &mut Document) {
    let DocumentData::Bib(data) = &document.data else { return };

    for node in bibtex::SyntaxNode::new_root(data.green.clone()).descendants() {
        if let Some(entry) = bibtex::Entry::cast(node.clone()) {
            analyze_entry(document, entry);
        } else if let Some(field) = bibtex::Field::cast(node.clone()) {
            analyze_field(document, field);
        }
    }
}

fn analyze_entry(document: &mut Document, entry: bibtex::Entry) {
    if entry.left_delim_token().is_none() {
        document.diagnostics.push(Diagnostic {
            range: entry.type_token().unwrap().text_range(),
            code: ErrorCode::ExpectingLCurly,
        });

        return;
    }

    if entry.name_token().is_none() {
        document.diagnostics.push(Diagnostic {
            range: entry.left_delim_token().unwrap().text_range(),
            code: ErrorCode::ExpectingKey,
        });

        return;
    }

    if entry.right_delim_token().is_none() {
        document.diagnostics.push(Diagnostic {
            range: TextRange::empty(entry.syntax().text_range().end()),
            code: ErrorCode::ExpectingRCurly,
        });

        return;
    }
}

fn analyze_field(document: &mut Document, field: bibtex::Field) {
    if field.eq_token().is_none() {
        let code = ErrorCode::ExpectingEq;
        document.diagnostics.push(Diagnostic {
            range: field.name_token().unwrap().text_range(),
            code,
        });

        return;
    }

    if field.value().is_none() {
        let code = ErrorCode::ExpectingFieldValue;
        document.diagnostics.push(Diagnostic {
            range: field.name_token().unwrap().text_range(),
            code,
        });

        return;
    }
}