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.
10 use crate::rustc::hir::intravisit as visit;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::middle::expr_use_visitor::*;
14 use crate::rustc::middle::mem_categorization::{cmt_, Categorization};
15 use crate::rustc::ty::layout::LayoutOf;
16 use crate::rustc::ty::{self, Ty};
17 use crate::rustc::util::nodemap::NodeSet;
18 use crate::rustc::{declare_tool_lint, lint_array};
19 use crate::syntax::ast::NodeId;
20 use crate::syntax::source_map::Span;
21 use crate::utils::span_lint;
24 pub too_large_for_stack: u64,
27 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
30 /// **Why is this bad?** This is an unnecessary allocation, and bad for
31 /// performance. It is only necessary to allocate if you wish to move the box
34 /// **Known problems:** None.
39 /// let x = Box::new(1);
41 /// println!("{}", *x);
44 declare_clippy_lint! {
47 "using `Box<T>` where unnecessary"
50 fn is_non_trait_box(ty: Ty<'_>) -> bool {
51 ty.is_box() && !ty.boxed_ty().is_trait()
54 struct EscapeDelegate<'a, 'tcx: 'a> {
55 cx: &'a LateContext<'a, 'tcx>,
57 too_large_for_stack: u64,
60 impl LintPass for Pass {
61 fn get_lints(&self) -> LintArray {
62 lint_array!(BOXED_LOCAL)
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
69 cx: &LateContext<'a, 'tcx>,
70 _: visit::FnKind<'tcx>,
76 // If the method is an impl for a trait, don't warn
77 let parent_id = cx.tcx.hir().get_parent(node_id);
78 let parent_node = cx.tcx.hir().find(parent_id);
80 if let Some(Node::Item(item)) = parent_node {
81 if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
86 let mut v = EscapeDelegate {
88 set: NodeSet::default(),
89 too_large_for_stack: self.too_large_for_stack,
92 let fn_def_id = cx.tcx.hir().local_def_id(node_id);
93 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
94 ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).consume_body(body);
100 cx.tcx.hir().span(node),
101 "local variable doesn't need to be boxed here",
107 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
108 fn consume(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, mode: ConsumeMode) {
109 if let Categorization::Local(lid) = cmt.cat {
110 if let Move(DirectRefMove) = mode {
111 // moved out or in. clearly can't be localized
112 self.set.remove(&lid);
116 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
117 fn consume_pat(&mut self, consume_pat: &Pat, cmt: &cmt_<'tcx>, _: ConsumeMode) {
118 let map = &self.cx.tcx.hir();
119 if map.is_argument(consume_pat.id) {
120 // Skip closure arguments
121 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
124 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
125 self.set.insert(consume_pat.id);
129 if let Categorization::Rvalue(..) = cmt.cat {
130 let id = map.hir_to_node_id(cmt.hir_id);
131 if let Some(Node::Stmt(st)) = map.find(map.get_parent_node(id)) {
132 if let StmtKind::Decl(ref decl, _) = st.node {
133 if let DeclKind::Local(ref loc) = decl.node {
134 if let Some(ref ex) = loc.init {
135 if let ExprKind::Box(..) = ex.node {
136 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
138 self.set.insert(consume_pat.id);
142 // TODO "foo".to_owned() and friends
149 if let Categorization::Local(lid) = cmt.cat {
150 if self.set.contains(&lid) {
151 // let y = x where x is known
152 // remove x, insert y
153 self.set.insert(consume_pat.id);
154 self.set.remove(&lid);
165 loan_cause: LoanCause,
167 if let Categorization::Local(lid) = cmt.cat {
170 // Used without autodereffing (i.e. x.clone())
174 // foo(&x) where no extra autoreffing is happening
177 // `match x` can move
178 LoanCause::MatchDiscriminant => {
179 self.set.remove(&lid);
182 // do nothing for matches, etc. These can't escape
187 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
188 fn mutate(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: MutateMode) {}
191 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
192 fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
193 // Large types need to be boxed to avoid stack
196 self.cx.layout_of(ty.boxed_ty()).ok().map_or(0, |l| l.size.bytes()) > self.too_large_for_stack