aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_syntax/src/validation.rs
blob: fc534df83b954087d48ea1d6e82560504726594e (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
mod byte;
mod byte_string;
mod char;
mod string;
mod block;

use crate::{
    SourceFile, SyntaxError, AstNode, SyntaxNode,
    SyntaxKind::{L_CURLY, R_CURLY, BYTE, BYTE_STRING, STRING, CHAR},
    ast,
    algo::visit::{visitor_ctx, VisitorCtx},
};

pub(crate) fn validate(file: &SourceFile) -> Vec<SyntaxError> {
    let mut errors = Vec::new();
    for node in file.syntax().descendants() {
        let _ = visitor_ctx(&mut errors)
            .visit::<ast::Literal, _>(validate_literal)
            .visit::<ast::Block, _>(block::validate_block_node)
            .accept(node);
    }
    errors
}

// FIXME: kill duplication
fn validate_literal(literal: &ast::Literal, acc: &mut Vec<SyntaxError>) {
    match literal.token().kind() {
        BYTE => byte::validate_byte_node(literal.token(), acc),
        BYTE_STRING => byte_string::validate_byte_string_node(literal.token(), acc),
        STRING => string::validate_string_node(literal.token(), acc),
        CHAR => char::validate_char_node(literal.token(), acc),
        _ => (),
    }
}

pub(crate) fn validate_block_structure(root: &SyntaxNode) {
    let mut stack = Vec::new();
    for node in root.descendants() {
        match node.kind() {
            L_CURLY => stack.push(node),
            R_CURLY => {
                if let Some(pair) = stack.pop() {
                    assert_eq!(
                        node.parent(),
                        pair.parent(),
                        "\nunpaired curleys:\n{}\n{}\n",
                        root.text(),
                        root.debug_dump(),
                    );
                    assert!(
                        node.next_sibling().is_none() && pair.prev_sibling().is_none(),
                        "\nfloating curlys at {:?}\nfile:\n{}\nerror:\n{}\n",
                        node,
                        root.text(),
                        node.text(),
                    );
                }
            }
            _ => (),
        }
    }
}