2 is_type_diagnostic_item, match_qpath, paths, return_ty, snippet, span_lint_and_then,
3 visitors::find_all_ret_expressions,
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::FnKind;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::subst::GenericArgKind;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for private functions that only return `Ok` or `Some`.
17 /// **Why is this bad?** It is not meaningful to wrap values when no `None` or `Err` is returned.
19 /// **Known problems:** Since this lint changes function type signature, you may need to
20 /// adjust some code at callee side.
25 /// fn get_cool_number(a: bool, b: bool) -> Option<i32> {
38 /// fn get_cool_number(a: bool, b: bool) -> i32 {
51 "functions that only return `Ok` or `Some`"
54 declare_lint_pass!(UnnecessaryWrap => [UNNECESSARY_WRAP]);
56 impl<'tcx> LateLintPass<'tcx> for UnnecessaryWrap {
59 cx: &LateContext<'tcx>,
60 fn_kind: FnKind<'tcx>,
61 fn_decl: &FnDecl<'tcx>,
67 FnKind::ItemFn(.., visibility, _) if visibility.node.is_pub() => return,
68 FnKind::Closure(..) => return,
72 let (return_type, path) = if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym!(option_type)) {
73 ("Option", &paths::OPTION_SOME)
74 } else if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym!(result_type)) {
75 ("Result", &paths::RESULT_OK)
80 let mut suggs = Vec::new();
81 let can_sugg = find_all_ret_expressions(cx, &body.value, |ret_expr| {
83 if let ExprKind::Call(ref func, ref args) = ret_expr.kind;
84 if let ExprKind::Path(ref qpath) = func.kind;
85 if match_qpath(qpath, path);
88 suggs.push((ret_expr.span, snippet(cx, args[0].span.source_callsite(), "..").to_string()));
102 "this function's return value is unnecessarily wrapped by `{}`",
107 let inner_ty = return_ty(cx, hir_id)
109 .skip(1) // skip `std::option::Option` or `std::result::Result`
110 .take(1) // take the first outermost inner type
111 .filter_map(|inner| match inner.unpack() {
112 GenericArgKind::Type(inner_ty) => Some(inner_ty.to_string()),
115 inner_ty.for_each(|inner_ty| {
116 diag.span_suggestion(
117 fn_decl.output.span(),
118 format!("remove `{}` from the return type...", return_type).as_str(),
120 Applicability::MachineApplicable,
123 diag.multipart_suggestion(
124 "...and change the returning expressions",
126 Applicability::MachineApplicable,