diff options
Diffstat (limited to 'bin/src/fix/all.rs')
-rw-r--r-- | bin/src/fix/all.rs | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/bin/src/fix/all.rs b/bin/src/fix/all.rs new file mode 100644 index 0000000..8c0770d --- /dev/null +++ b/bin/src/fix/all.rs | |||
@@ -0,0 +1,86 @@ | |||
1 | use std::borrow::Cow; | ||
2 | |||
3 | use lib::{Report, LINTS}; | ||
4 | use rnix::{parser::ParseError as RnixParseErr, WalkEvent}; | ||
5 | |||
6 | use crate::fix::{Fixed, FixResult}; | ||
7 | |||
8 | fn collect_fixes(source: &str) -> Result<Vec<Report>, RnixParseErr> { | ||
9 | let parsed = rnix::parse(source).as_result()?; | ||
10 | |||
11 | Ok(parsed | ||
12 | .node() | ||
13 | .preorder_with_tokens() | ||
14 | .filter_map(|event| match event { | ||
15 | WalkEvent::Enter(child) => LINTS.get(&child.kind()).map(|rules| { | ||
16 | rules | ||
17 | .iter() | ||
18 | .filter_map(|rule| rule.validate(&child)) | ||
19 | .filter(|report| report.total_suggestion_range().is_some()) | ||
20 | .collect::<Vec<_>>() | ||
21 | }), | ||
22 | _ => None, | ||
23 | }) | ||
24 | .flatten() | ||
25 | .collect()) | ||
26 | } | ||
27 | |||
28 | fn reorder(mut reports: Vec<Report>) -> Vec<Report> { | ||
29 | use std::collections::VecDeque; | ||
30 | |||
31 | reports.sort_by(|a, b| { | ||
32 | let a_range = a.range(); | ||
33 | let b_range = b.range(); | ||
34 | a_range.end().partial_cmp(&b_range.end()).unwrap() | ||
35 | }); | ||
36 | |||
37 | reports | ||
38 | .into_iter() | ||
39 | .fold(VecDeque::new(), |mut deque: VecDeque<Report>, new_elem| { | ||
40 | let front = deque.front(); | ||
41 | let new_range = new_elem.range(); | ||
42 | if let Some(front_range) = front.map(|f| f.range()) { | ||
43 | if new_range.start() > front_range.end() { | ||
44 | deque.push_front(new_elem); | ||
45 | } | ||
46 | } else { | ||
47 | deque.push_front(new_elem); | ||
48 | } | ||
49 | deque | ||
50 | }) | ||
51 | .into() | ||
52 | } | ||
53 | |||
54 | impl<'a> Iterator for FixResult<'a> { | ||
55 | type Item = FixResult<'a>; | ||
56 | fn next(&mut self) -> Option<Self::Item> { | ||
57 | let all_reports = collect_fixes(&self.src).ok()?; | ||
58 | if all_reports.is_empty() { | ||
59 | return None; | ||
60 | } | ||
61 | |||
62 | let reordered = reorder(all_reports); | ||
63 | let fixed = reordered | ||
64 | .iter() | ||
65 | .map(|r| Fixed { | ||
66 | at: r.range(), | ||
67 | code: r.code, | ||
68 | }) | ||
69 | .collect::<Vec<_>>(); | ||
70 | for report in reordered { | ||
71 | report.apply(self.src.to_mut()); | ||
72 | } | ||
73 | |||
74 | Some(FixResult { | ||
75 | src: self.src.clone(), | ||
76 | fixed | ||
77 | }) | ||
78 | } | ||
79 | } | ||
80 | |||
81 | pub fn all(src: &str) -> Option<FixResult> { | ||
82 | let src = Cow::from(src); | ||
83 | let _ = rnix::parse(&src).as_result().ok()?; | ||
84 | let initial = FixResult::empty(src); | ||
85 | initial.into_iter().last() | ||
86 | } | ||