1 use crate::path_to_local_id;
3 use rustc_hir::def::{DefKind, Res};
4 use rustc_hir::intravisit::{self, walk_block, walk_expr, NestedVisitorMap, Visitor};
6 Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Stmt, UnOp, Unsafety,
8 use rustc_lint::LateContext;
9 use rustc_middle::hir::map::Map;
12 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
13 /// bodies (i.e. closures) are visited.
14 /// If the callback returns `true`, the expr just provided to the callback is walked.
16 pub fn expr_visitor<'tcx>(cx: &LateContext<'tcx>, f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
21 impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<'tcx, F> {
23 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
24 NestedVisitorMap::OnlyBodies(self.hir)
27 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
29 walk_expr(self, expr);
33 V { hir: cx.tcx.hir(), f }
36 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
37 /// bodies (i.e. closures) are not visited.
38 /// If the callback returns `true`, the expr just provided to the callback is walked.
40 pub fn expr_visitor_no_bodies<'tcx>(f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
42 impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<F> {
43 type Map = intravisit::ErasedMap<'tcx>;
44 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
45 NestedVisitorMap::None
48 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
57 /// returns `true` if expr contains match expr desugared from try
58 fn contains_try(expr: &hir::Expr<'_>) -> bool {
59 let mut found = false;
60 expr_visitor_no_bodies(|e| {
62 found = matches!(e.kind, hir::ExprKind::Match(_, _, hir::MatchSource::TryDesugar));
70 pub fn find_all_ret_expressions<'hir, F>(_cx: &LateContext<'_>, expr: &'hir hir::Expr<'hir>, callback: F) -> bool
72 F: FnMut(&'hir hir::Expr<'hir>) -> bool,
80 struct WithStmtGuarg<'a, F> {
81 val: &'a mut RetFinder<F>,
85 impl<F> RetFinder<F> {
86 fn inside_stmt(&mut self, in_stmt: bool) -> WithStmtGuarg<'_, F> {
87 let prev_in_stmt = std::mem::replace(&mut self.in_stmt, in_stmt);
95 impl<F> std::ops::Deref for WithStmtGuarg<'_, F> {
96 type Target = RetFinder<F>;
98 fn deref(&self) -> &Self::Target {
103 impl<F> std::ops::DerefMut for WithStmtGuarg<'_, F> {
104 fn deref_mut(&mut self) -> &mut Self::Target {
109 impl<F> Drop for WithStmtGuarg<'_, F> {
111 self.val.in_stmt = self.prev_in_stmt;
115 impl<'hir, F: FnMut(&'hir hir::Expr<'hir>) -> bool> intravisit::Visitor<'hir> for RetFinder<F> {
116 type Map = Map<'hir>;
118 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
119 intravisit::NestedVisitorMap::None
122 fn visit_stmt(&mut self, stmt: &'hir hir::Stmt<'_>) {
123 intravisit::walk_stmt(&mut *self.inside_stmt(true), stmt);
126 fn visit_expr(&mut self, expr: &'hir hir::Expr<'_>) {
132 hir::ExprKind::Ret(Some(expr)) => self.inside_stmt(false).visit_expr(expr),
133 _ => intravisit::walk_expr(self, expr),
137 hir::ExprKind::If(cond, then, else_opt) => {
138 self.inside_stmt(true).visit_expr(cond);
139 self.visit_expr(then);
140 if let Some(el) = else_opt {
144 hir::ExprKind::Match(cond, arms, _) => {
145 self.inside_stmt(true).visit_expr(cond);
147 self.visit_expr(arm.body);
150 hir::ExprKind::Block(..) => intravisit::walk_expr(self, expr),
151 hir::ExprKind::Ret(Some(expr)) => self.visit_expr(expr),
152 _ => self.failed |= !(self.cb)(expr),
158 !contains_try(expr) && {
159 let mut ret_finder = RetFinder {
164 ret_finder.visit_expr(expr);
169 /// A type which can be visited.
170 pub trait Visitable<'tcx> {
171 /// Calls the corresponding `visit_*` function on the visitor.
172 fn visit<V: Visitor<'tcx>>(self, visitor: &mut V);
174 macro_rules! visitable_ref {
175 ($t:ident, $f:ident) => {
176 impl Visitable<'tcx> for &'tcx $t<'tcx> {
177 fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
183 visitable_ref!(Arm, visit_arm);
184 visitable_ref!(Block, visit_block);
185 visitable_ref!(Body, visit_body);
186 visitable_ref!(Expr, visit_expr);
187 visitable_ref!(Stmt, visit_stmt);
189 // impl<'tcx, I: IntoIterator> Visitable<'tcx> for I
191 // I::Item: Visitable<'tcx>,
193 // fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
200 /// Checks if the given resolved path is used in the given body.
201 pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool {
202 let mut found = false;
203 expr_visitor(cx, |e| {
208 if let ExprKind::Path(p) = &e.kind {
209 if cx.qpath_res(p, e.hir_id) == res {
215 .visit_expr(&cx.tcx.hir().body(body).value);
219 /// Checks if the given local is used.
220 pub fn is_local_used(cx: &LateContext<'tcx>, visitable: impl Visitable<'tcx>, id: HirId) -> bool {
221 let mut is_used = false;
222 let mut visitor = expr_visitor(cx, |expr| {
224 is_used = path_to_local_id(expr, id);
228 visitable.visit(&mut visitor);
233 /// Checks if the given expression is a constant.
234 pub fn is_const_evaluatable(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
236 cx: &'a LateContext<'tcx>,
239 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
240 type Map = Map<'tcx>;
241 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
242 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
245 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
250 ExprKind::ConstBlock(_) => return,
253 kind: ExprKind::Path(ref p),
260 .qpath_res(p, hir_id)
262 .map_or(false, |id| self.cx.tcx.is_const_fn_raw(id)) => {},
263 ExprKind::MethodCall(..)
267 .type_dependent_def_id(e.hir_id)
268 .map_or(false, |id| self.cx.tcx.is_const_fn_raw(id)) => {},
269 ExprKind::Binary(_, lhs, rhs)
270 if self.cx.typeck_results().expr_ty(lhs).peel_refs().is_primitive_ty()
271 && self.cx.typeck_results().expr_ty(rhs).peel_refs().is_primitive_ty() => {},
272 ExprKind::Unary(UnOp::Deref, e) if self.cx.typeck_results().expr_ty(e).is_ref() => (),
273 ExprKind::Unary(_, e) if self.cx.typeck_results().expr_ty(e).peel_refs().is_primitive_ty() => (),
274 ExprKind::Index(base, _)
276 self.cx.typeck_results().expr_ty(base).peel_refs().kind(),
277 ty::Slice(_) | ty::Array(..)
279 ExprKind::Path(ref p)
281 self.cx.qpath_res(p, e.hir_id),
284 | DefKind::AssocConst
286 | DefKind::ConstParam
296 | ExprKind::Block(..)
298 | ExprKind::DropTemps(_)
299 | ExprKind::Field(..)
303 | ExprKind::Match(..)
304 | ExprKind::Repeat(..)
305 | ExprKind::Struct(..)
307 | ExprKind::Type(..) => (),
310 self.is_const = false;
318 let mut v = V { cx, is_const: true };
323 /// Checks if the given expression performs an unsafe operation outside of an unsafe block.
324 pub fn is_expr_unsafe(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
326 cx: &'a LateContext<'tcx>,
329 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
330 type Map = Map<'tcx>;
331 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
332 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
334 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
339 ExprKind::Unary(UnOp::Deref, e) if self.cx.typeck_results().expr_ty(e).is_unsafe_ptr() => {
340 self.is_unsafe = true;
342 ExprKind::MethodCall(..)
346 .type_dependent_def_id(e.hir_id)
347 .map_or(false, |id| self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe) =>
349 self.is_unsafe = true;
351 ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() {
352 ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe => self.is_unsafe = true,
353 ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true,
354 _ => walk_expr(self, e),
356 ExprKind::Path(ref p)
359 .qpath_res(p, e.hir_id)
361 .map_or(false, |id| self.cx.tcx.is_mutable_static(id)) =>
363 self.is_unsafe = true;
365 _ => walk_expr(self, e),
368 fn visit_block(&mut self, b: &'tcx Block<'_>) {
369 if !matches!(b.rules, BlockCheckMode::UnsafeBlock(_)) {
373 fn visit_nested_item(&mut self, id: ItemId) {
374 if let ItemKind::Impl(i) = &self.cx.tcx.hir().item(id).kind {
375 self.is_unsafe = i.unsafety == Unsafety::Unsafe;
379 let mut v = V { cx, is_unsafe: false };