2 use rustc::{declare_lint, lint_array};
4 use rustc::hir::def::Def;
5 use crate::utils::sugg::Sugg;
8 use crate::utils::{match_def_path, match_type, span_lint_and_then};
9 use crate::utils::paths::*;
11 /// **What it does:** Checks for expressions that could be replaced by the question mark operator
13 /// **Why is this bad?** Question mark usage is more idiomatic
15 /// **Known problems:** None
19 /// if option.is_none() {
32 "checks for expressions that could be replaced by the question mark operator"
35 #[derive(Copy, Clone)]
36 pub struct QuestionMarkPass;
38 impl LintPass for QuestionMarkPass {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(QUESTION_MARK)
44 impl QuestionMarkPass {
45 /// Check if the given expression on the given context matches the following structure:
48 /// if option.is_none() {
53 /// If it matches, it will suggest to use the question mark operator instead
54 fn check_is_none_and_early_return_none(cx: &LateContext, expr: &Expr) {
56 if let ExprKind::If(ref if_expr, ref body, _) = expr.node;
57 if let ExprKind::MethodCall(ref segment, _, ref args) = if_expr.node;
58 if segment.ident.name == "is_none";
59 if Self::expression_returns_none(cx, body);
60 if let Some(subject) = args.get(0);
61 if Self::is_option(cx, subject);
68 "this block may be rewritten with the `?` operator",
70 let receiver_str = &Sugg::hir(cx, subject, "..");
75 format!("{}?;", receiver_str),
83 fn is_option(cx: &LateContext, expression: &Expr) -> bool {
84 let expr_ty = cx.tables.expr_ty(expression);
86 match_type(cx, expr_ty, &OPTION)
89 fn expression_returns_none(cx: &LateContext, expression: &Expr) -> bool {
90 match expression.node {
91 ExprKind::Block(ref block, _) => {
92 if let Some(return_expression) = Self::return_expression(block) {
93 return Self::expression_returns_none(cx, &return_expression);
98 ExprKind::Ret(Some(ref expr)) => {
99 Self::expression_returns_none(cx, expr)
101 ExprKind::Path(ref qp) => {
102 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
103 return match_def_path(cx.tcx, def_id, &OPTION_NONE);
112 fn return_expression(block: &Block) -> Option<P<Expr>> {
113 // Check if last expression is a return statement. Then, return the expression
115 if block.stmts.len() == 1;
116 if let Some(expr) = block.stmts.iter().last();
117 if let StmtKind::Semi(ref expr, _) = expr.node;
118 if let ExprKind::Ret(ref ret_expr) = expr.node;
119 if let &Some(ref ret_expr) = ret_expr;
122 return Some(ret_expr.clone());
126 // Check if the block has an implicit return expression
127 if let Some(ref ret_expr) = block.expr {
128 return Some(ret_expr.clone());
135 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMarkPass {
136 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
137 Self::check_is_none_and_early_return_none(cx, expr);