aboutsummaryrefslogtreecommitdiff
path: root/bin/src/fix/single.rs
blob: 67b6b8fa2f811a0eca9c18d570a41b7ab5917495 (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
use std::{borrow::Cow, convert::TryFrom};

use lib::{session::SessionInfo, Report};
use rnix::{TextSize, WalkEvent};

use crate::{err::SingleFixErr, fix::Source, utils};

pub struct SingleFixResult<'δ> {
    pub src: Source<'δ>,
}

fn pos_to_byte(line: usize, col: usize, src: &str) -> Result<TextSize, SingleFixErr> {
    let mut byte: TextSize = TextSize::of("");
    for (l, _) in src
        .split_inclusive('\n')
        .zip(1..)
        .take_while(|(_, i)| *i < line)
    {
        byte += TextSize::of(l);
    }
    byte += TextSize::try_from(col).map_err(|_| SingleFixErr::Conversion(col))?;

    if usize::from(byte) >= src.len() {
        Err(SingleFixErr::OutOfBounds(line, col))
    } else {
        Ok(byte)
    }
}

fn find(offset: TextSize, src: &str, sess: &SessionInfo) -> Result<Report, SingleFixErr> {
    // we don't really need the source to form a completely parsed tree
    let parsed = rnix::parse(src);
    let lints = utils::lint_map();

    parsed
        .node()
        .preorder_with_tokens()
        .filter_map(|event| match event {
            WalkEvent::Enter(child) => lints.get(&child.kind()).map(|rules| {
                rules
                    .iter()
                    .filter_map(|rule| rule.validate(&child, sess))
                    .find(|report| report.total_suggestion_range().is_some())
            }),
            _ => None,
        })
        .flatten()
        .find(|report| report.total_diagnostic_range().unwrap().contains(offset))
        .ok_or(SingleFixErr::NoOp)
}

pub fn single<'a, 'b>(
    line: usize,
    col: usize,
    src: &'a str,
    sess: &'b SessionInfo,
) -> Result<SingleFixResult<'a>, SingleFixErr> {
    let mut src = Cow::from(src);
    let offset = pos_to_byte(line, col, &*src)?;
    let report = find(offset, &*src, &sess)?;

    report.apply(src.to_mut());

    Ok(SingleFixResult { src })
}