1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::rustc::hir::*;
12 use crate::rustc::hir::intravisit as visit;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc::middle::expr_use_visitor::*;
16 use crate::rustc::middle::mem_categorization::{cmt_, Categorization};
17 use crate::rustc::ty::{self, Ty};
18 use crate::rustc::ty::layout::LayoutOf;
19 use crate::rustc::util::nodemap::NodeSet;
20 use crate::syntax::ast::NodeId;
21 use crate::syntax::source_map::Span;
22 use crate::utils::span_lint;
25 pub too_large_for_stack: u64,
28 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
31 /// **Why is this bad?** This is an unnecessary allocation, and bad for
32 /// performance. It is only necessary to allocate if you wish to move the box
35 /// **Known problems:** None.
40 /// let x = Box::new(1);
42 /// println!("{}", *x);
45 declare_clippy_lint! {
48 "using `Box<T>` where unnecessary"
51 fn is_non_trait_box(ty: Ty<'_>) -> bool {
52 ty.is_box() && !ty.boxed_ty().is_trait()
55 struct EscapeDelegate<'a, 'tcx: 'a> {
56 cx: &'a LateContext<'a, 'tcx>,
58 too_large_for_stack: u64,
61 impl LintPass for Pass {
62 fn get_lints(&self) -> LintArray {
63 lint_array!(BOXED_LOCAL)
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
71 cx: &LateContext<'a, 'tcx>,
72 _: visit::FnKind<'tcx>,
78 // If the method is an impl for a trait, don't warn
79 let parent_id = cx.tcx.hir.get_parent(node_id);
80 let parent_node = cx.tcx.hir.find(parent_id);
82 if let Some(Node::Item(item)) = parent_node {
83 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
88 let mut v = EscapeDelegate {
91 too_large_for_stack: self.too_large_for_stack,
94 let fn_def_id = cx.tcx.hir.local_def_id(node_id);
95 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
96 ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).consume_body(body);
102 cx.tcx.hir.span(node),
103 "local variable doesn't need to be boxed here",
109 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
110 fn consume(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, mode: ConsumeMode) {
111 if let Categorization::Local(lid) = cmt.cat {
112 if let Move(DirectRefMove) = mode {
113 // moved out or in. clearly can't be localized
114 self.set.remove(&lid);
118 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
119 fn consume_pat(&mut self, consume_pat: &Pat, cmt: &cmt_<'tcx>, _: ConsumeMode) {
120 let map = &self.cx.tcx.hir;
121 if map.is_argument(consume_pat.id) {
122 // Skip closure arguments
123 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
126 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
127 self.set.insert(consume_pat.id);
131 if let Categorization::Rvalue(..) = cmt.cat {
132 let id = map.hir_to_node_id(cmt.hir_id);
133 if let Some(Node::Stmt(st)) = map.find(map.get_parent_node(id)) {
134 if let StmtKind::Decl(ref decl, _) = st.node {
135 if let DeclKind::Local(ref loc) = decl.node {
136 if let Some(ref ex) = loc.init {
137 if let ExprKind::Box(..) = ex.node {
138 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
140 self.set.insert(consume_pat.id);
144 // TODO "foo".to_owned() and friends
151 if let Categorization::Local(lid) = cmt.cat {
152 if self.set.contains(&lid) {
153 // let y = x where x is known
154 // remove x, insert y
155 self.set.insert(consume_pat.id);
156 self.set.remove(&lid);
160 fn borrow(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, _: ty::BorrowKind, loan_cause: LoanCause) {
161 if let Categorization::Local(lid) = cmt.cat {
164 // Used without autodereffing (i.e. x.clone())
168 // foo(&x) where no extra autoreffing is happening
171 // `match x` can move
172 LoanCause::MatchDiscriminant => {
173 self.set.remove(&lid);
176 // do nothing for matches, etc. These can't escape
181 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
182 fn mutate(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: MutateMode) {}
185 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
186 fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
187 // Large types need to be boxed to avoid stack
190 self.cx.layout_of(ty.boxed_ty()).ok().map_or(0, |l| l.size.bytes()) > self.too_large_for_stack