Skip to main content

codeint_lang_rust/
rules.rs

1use std::collections::BTreeSet;
2
3use codeint_model::language::FlaggedLine;
4use syn::spanned::Spanned;
5use syn::visit::{self, Visit};
6use syn::{
7    Arm, Block, Expr, ExprClosure, ExprIf, ExprMatch, File, ImplItemFn, Item, ItemFn, Lit, Pat,
8    Stmt, TraitItemFn,
9};
10
11use crate::cfg_test::{has_cfg_test, item_attrs};
12use crate::functions::CodeLines;
13
14const RULE_IDS: [&str; 6] = [
15    "else-after-return",
16    "if-else-returns-boolean",
17    "trailing-return",
18    "match-only-propagates",
19    "match-yields-boolean",
20    "redundant-closure",
21];
22
23pub fn flagged_line_rules() -> impl Iterator<Item = &'static str> {
24    RULE_IDS.into_iter()
25}
26
27pub(crate) fn flag(
28    file: &File,
29    code_lines: &CodeLines,
30    exclude_cfg_test: bool,
31) -> Vec<FlaggedLine> {
32    let mut visitor = RuleVisitor {
33        exclude_cfg_test,
34        flagged: BTreeSet::new(),
35        code_lines,
36    };
37    visitor.visit_file(file);
38    visitor
39        .flagged
40        .into_iter()
41        .map(|(line, rule)| FlaggedLine {
42            line,
43            rule: rule.to_owned(),
44        })
45        .collect()
46}
47
48struct RuleVisitor<'a> {
49    exclude_cfg_test: bool,
50    flagged: BTreeSet<(u32, &'static str)>,
51    code_lines: &'a CodeLines,
52}
53
54impl RuleVisitor<'_> {
55    fn flag_span(&mut self, span: proc_macro2::Span, rule: &'static str) {
56        let start = span.start().line as u32;
57        let end = span.end().line as u32;
58        for line in self.code_lines.lines_in_range(start, end) {
59            self.flagged.insert((line, rule));
60        }
61    }
62
63    fn check_trailing_return(&mut self, block: &Block) {
64        let Some(last) = block.stmts.last() else {
65            return;
66        };
67        if let Stmt::Expr(Expr::Return(ret), _) = last {
68            self.flag_span(ret.span(), "trailing-return");
69        }
70    }
71
72    fn check_if(&mut self, expr_if: &ExprIf) {
73        if let Some((_, else_branch)) = &expr_if.else_branch {
74            if is_if_else_boolean(expr_if) {
75                self.flag_span(expr_if.span(), "if-else-returns-boolean");
76            } else if block_unconditionally_exits(&expr_if.then_branch) {
77                self.flag_span(else_branch.span(), "else-after-return");
78            }
79        }
80    }
81
82    fn check_match(&mut self, expr_match: &ExprMatch) {
83        if is_match_only_propagates(expr_match) {
84            self.flag_span(expr_match.span(), "match-only-propagates");
85        } else if is_match_yields_boolean(expr_match) {
86            self.flag_span(expr_match.span(), "match-yields-boolean");
87        }
88    }
89
90    fn check_closure(&mut self, closure: &ExprClosure) {
91        if is_redundant_closure(closure) {
92            self.flag_span(closure.span(), "redundant-closure");
93        }
94    }
95}
96
97impl<'ast> Visit<'ast> for RuleVisitor<'_> {
98    fn visit_item(&mut self, item: &'ast Item) {
99        if self.exclude_cfg_test && has_cfg_test(item_attrs(item)) {
100            return;
101        }
102        visit::visit_item(self, item);
103    }
104
105    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
106        if self.exclude_cfg_test && has_cfg_test(&node.attrs) {
107            return;
108        }
109        self.check_trailing_return(&node.block);
110        visit::visit_item_fn(self, node);
111    }
112
113    fn visit_impl_item_fn(&mut self, node: &'ast ImplItemFn) {
114        if self.exclude_cfg_test && has_cfg_test(&node.attrs) {
115            return;
116        }
117        self.check_trailing_return(&node.block);
118        visit::visit_impl_item_fn(self, node);
119    }
120
121    fn visit_trait_item_fn(&mut self, node: &'ast TraitItemFn) {
122        if self.exclude_cfg_test && has_cfg_test(&node.attrs) {
123            return;
124        }
125        if let Some(block) = &node.default {
126            self.check_trailing_return(block);
127        }
128        visit::visit_trait_item_fn(self, node);
129    }
130
131    fn visit_expr_if(&mut self, node: &'ast ExprIf) {
132        self.check_if(node);
133        visit::visit_expr_if(self, node);
134    }
135
136    fn visit_expr_match(&mut self, node: &'ast ExprMatch) {
137        self.check_match(node);
138        visit::visit_expr_match(self, node);
139    }
140
141    fn visit_expr_closure(&mut self, node: &'ast ExprClosure) {
142        self.check_closure(node);
143        visit::visit_expr_closure(self, node);
144    }
145}
146
147fn block_unconditionally_exits(block: &Block) -> bool {
148    let Some(last) = block.stmts.last() else {
149        return false;
150    };
151    matches!(
152        last,
153        Stmt::Expr(Expr::Return(_) | Expr::Break(_) | Expr::Continue(_), _)
154    )
155}
156
157fn single_bool_expr(expr: &Expr) -> Option<bool> {
158    match expr {
159        Expr::Lit(lit) => match &lit.lit {
160            Lit::Bool(b) => Some(b.value),
161            _ => None,
162        },
163        Expr::Return(ret) => ret.expr.as_deref().and_then(single_bool_expr),
164        Expr::Block(block) => block_single_bool(&block.block),
165        _ => None,
166    }
167}
168
169fn block_single_bool(block: &Block) -> Option<bool> {
170    if block.stmts.len() != 1 {
171        return None;
172    }
173    match &block.stmts[0] {
174        Stmt::Expr(expr, _) => single_bool_expr(expr),
175        _ => None,
176    }
177}
178
179fn is_if_else_boolean(expr_if: &ExprIf) -> bool {
180    if matches!(*expr_if.cond, Expr::Let(_)) {
181        return false;
182    }
183    let Some((_, else_expr)) = &expr_if.else_branch else {
184        return false;
185    };
186    if matches!(**else_expr, Expr::If(_)) {
187        return false;
188    }
189    match (
190        block_single_bool(&expr_if.then_branch),
191        single_bool_expr(else_expr),
192    ) {
193        (Some(then_val), Some(else_val)) => then_val != else_val,
194        _ => false,
195    }
196}
197
198fn is_match_only_propagates(expr_match: &ExprMatch) -> bool {
199    if expr_match.arms.len() != 2 || expr_match.arms.iter().any(|arm| arm.guard.is_some()) {
200        return false;
201    }
202    let (first, second) = (&expr_match.arms[0], &expr_match.arms[1]);
203    (is_ok_unwrap_arm(first) && is_err_return_arm(second))
204        || (is_err_return_arm(first) && is_ok_unwrap_arm(second))
205        || (is_some_unwrap_arm(first) && is_none_return_arm(second))
206        || (is_none_return_arm(first) && is_some_unwrap_arm(second))
207}
208
209fn tuple_variant_single_ident(pat: &Pat, variant: &str) -> Option<String> {
210    let Pat::TupleStruct(ts) = pat else {
211        return None;
212    };
213    let last_seg = ts.path.segments.last()?;
214    if last_seg.ident != variant || ts.elems.len() != 1 {
215        return None;
216    }
217    let Pat::Ident(ident) = &ts.elems[0] else {
218        return None;
219    };
220    if ident.mutability.is_some() || ident.by_ref.is_some() || ident.subpat.is_some() {
221        return None;
222    }
223    Some(ident.ident.to_string())
224}
225
226fn expr_single_ident(expr: &Expr) -> Option<String> {
227    let Expr::Path(path) = expr else {
228        return None;
229    };
230    path.path.get_ident().map(ToString::to_string)
231}
232
233fn is_ok_unwrap_arm(arm: &Arm) -> bool {
234    let Some(bound) = tuple_variant_single_ident(&arm.pat, "Ok") else {
235        return false;
236    };
237    expr_single_ident(&arm.body).is_some_and(|name| name == bound)
238}
239
240fn is_err_return_arm(arm: &Arm) -> bool {
241    let Some(bound) = tuple_variant_single_ident(&arm.pat, "Err") else {
242        return false;
243    };
244    let Expr::Return(ret) = &*arm.body else {
245        return false;
246    };
247    let Some(Expr::Call(call)) = ret.expr.as_deref() else {
248        return false;
249    };
250    let Expr::Path(func_path) = &*call.func else {
251        return false;
252    };
253    let Some(last) = func_path.path.segments.last() else {
254        return false;
255    };
256    last.ident == "Err"
257        && call.args.len() == 1
258        && expr_single_ident(&call.args[0]).is_some_and(|name| name == bound)
259}
260
261fn is_some_unwrap_arm(arm: &Arm) -> bool {
262    let Some(bound) = tuple_variant_single_ident(&arm.pat, "Some") else {
263        return false;
264    };
265    expr_single_ident(&arm.body).is_some_and(|name| name == bound)
266}
267
268fn is_none_return_arm(arm: &Arm) -> bool {
269    let is_none_pat = match &arm.pat {
270        Pat::Ident(ident) => ident.ident == "None",
271        Pat::Path(path) => path
272            .path
273            .segments
274            .last()
275            .is_some_and(|seg| seg.ident == "None"),
276        _ => false,
277    };
278    if !is_none_pat {
279        return false;
280    }
281    let Expr::Return(ret) = &*arm.body else {
282        return false;
283    };
284    let Some(Expr::Path(path)) = ret.expr.as_deref() else {
285        return false;
286    };
287    path.path
288        .segments
289        .last()
290        .is_some_and(|seg| seg.ident == "None")
291}
292
293fn is_match_yields_boolean(expr_match: &ExprMatch) -> bool {
294    if expr_match.arms.len() != 2 || expr_match.arms.iter().any(|arm| arm.guard.is_some()) {
295        return false;
296    }
297    let first_pat_bool =
298        matches!(&expr_match.arms[0].pat, Pat::Lit(lit) if matches!(lit.lit, Lit::Bool(_)));
299    let second_pat_bool_or_wild = matches!(
300        &expr_match.arms[1].pat,
301        Pat::Wild(_)
302            | Pat::Lit(syn::ExprLit {
303                lit: Lit::Bool(_),
304                ..
305            })
306    );
307    if !(first_pat_bool && second_pat_bool_or_wild) {
308        return false;
309    }
310    match (
311        single_bool_expr(&expr_match.arms[0].body),
312        single_bool_expr(&expr_match.arms[1].body),
313    ) {
314        (Some(a), Some(b)) => a != b,
315        _ => false,
316    }
317}
318
319fn is_redundant_closure(closure: &ExprClosure) -> bool {
320    if closure.asyncness.is_some()
321        || closure.capture.is_some()
322        || closure.lifetimes.is_some()
323        || closure.inputs.is_empty()
324    {
325        return false;
326    }
327    let mut params = Vec::with_capacity(closure.inputs.len());
328    for input in &closure.inputs {
329        let Pat::Ident(ident) = input else {
330            return false;
331        };
332        if ident.mutability.is_some() || ident.by_ref.is_some() || ident.subpat.is_some() {
333            return false;
334        }
335        params.push(ident.ident.to_string());
336    }
337    let Expr::Call(call) = &*closure.body else {
338        return false;
339    };
340    if !matches!(&*call.func, Expr::Path(_)) || call.args.len() != params.len() {
341        return false;
342    }
343    call.args
344        .iter()
345        .zip(&params)
346        .all(|(arg, param)| expr_single_ident(arg).is_some_and(|name| name == *param))
347}