From dd4d4e29c3295ed8e371f1dc5d1d463f56999ecb Mon Sep 17 00:00:00 2001 From: Ayrton Date: Wed, 19 Aug 2020 00:30:49 -0400 Subject: [PATCH 1/8] added a lint against function references this lint suggests casting function references to `*const ()` --- compiler/rustc_lint/src/builtin.rs | 32 ++++++++++++++++++++++++++++++ compiler/rustc_lint/src/lib.rs | 1 + 2 files changed, 33 insertions(+) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index e5f66611d0f9b..b089d4dcfba4e 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2942,3 +2942,35 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations { } } } + +declare_lint! { + FUNCTION_REFERENCES, + Warn, + "suggest casting functions to pointers when attempting to take references" +} + +declare_lint_pass!(FunctionReferences => [FUNCTION_REFERENCES]); + +impl<'tcx> LateLintPass<'tcx> for FunctionReferences { + fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { + if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, referent) = e.kind { + if let hir::ExprKind::Path(qpath) = &referent.kind { + if let Some(def_id) = cx.qpath_res(qpath, referent.hir_id).opt_def_id() { + cx.tcx.hir().get_if_local(def_id).map(|node| { + if node.fn_decl().is_some() { + if let Some(ident) = node.ident() { + cx.struct_span_lint(FUNCTION_REFERENCES, referent.span, |lint| { + lint.build(&format!( + "cast {} with `as *const ()` to use it as a pointer", + ident.to_string() + )) + .emit() + }); + } + } + }); + } + } + } + } +} diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 1db59bfc39dce..b574a7da0aa46 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -194,6 +194,7 @@ macro_rules! late_lint_mod_passes { UnreachablePub: UnreachablePub, ExplicitOutlivesRequirements: ExplicitOutlivesRequirements, InvalidValue: InvalidValue, + FunctionReferences: FunctionReferences, ] ); }; From 975547d475fcb3a7c6e440be5f8de3bf0497d383 Mon Sep 17 00:00:00 2001 From: Ayrton Date: Fri, 4 Sep 2020 09:45:09 -0400 Subject: [PATCH 2/8] changed lint to suggest casting to the proper function type and added a test --- compiler/rustc_lint/src/builtin.rs | 10 ++++++---- src/test/ui/lint/function-references.rs | 22 +++++++++++++++++++++ src/test/ui/lint/function-references.stderr | 22 +++++++++++++++++++++ 3 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 src/test/ui/lint/function-references.rs create mode 100644 src/test/ui/lint/function-references.stderr diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b089d4dcfba4e..86cf4ebb18743 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2957,17 +2957,19 @@ impl<'tcx> LateLintPass<'tcx> for FunctionReferences { if let hir::ExprKind::Path(qpath) = &referent.kind { if let Some(def_id) = cx.qpath_res(qpath, referent.hir_id).opt_def_id() { cx.tcx.hir().get_if_local(def_id).map(|node| { - if node.fn_decl().is_some() { + node.fn_decl().map(|decl| { if let Some(ident) = node.ident() { cx.struct_span_lint(FUNCTION_REFERENCES, referent.span, |lint| { + let num_args = decl.inputs.len(); lint.build(&format!( - "cast {} with `as *const ()` to use it as a pointer", - ident.to_string() + "cast `{}` with `as *const fn({}) -> _` to use it as a pointer", + ident.to_string(), + vec!["_"; num_args].join(", ") )) .emit() }); } - } + }); }); } } diff --git a/src/test/ui/lint/function-references.rs b/src/test/ui/lint/function-references.rs new file mode 100644 index 0000000000000..748f2560caa3a --- /dev/null +++ b/src/test/ui/lint/function-references.rs @@ -0,0 +1,22 @@ +// check-pass +fn foo() -> usize { 42 } +fn bar(x: usize) -> usize { x } +fn baz(x: usize, y: usize) -> usize { x + y } + +fn main() { + println!("{:p}", &foo); + //~^ WARN cast `foo` with `as *const fn() -> _` to use it as a pointer + println!("{:p}", &bar); + //~^ WARN cast `bar` with `as *const fn(_) -> _` to use it as a pointer + println!("{:p}", &baz); + //~^ WARN cast `baz` with `as *const fn(_, _) -> _` to use it as a pointer + + //should not produce any warnings + println!("{:p}", foo as *const fn() -> usize); + println!("{:p}", bar as *const fn(usize) -> usize); + println!("{:p}", baz as *const fn(usize, usize) -> usize); + + //should not produce any warnings + let fn_thing = foo; + println!("{:p}", &fn_thing); +} diff --git a/src/test/ui/lint/function-references.stderr b/src/test/ui/lint/function-references.stderr new file mode 100644 index 0000000000000..bd2da6e1167a7 --- /dev/null +++ b/src/test/ui/lint/function-references.stderr @@ -0,0 +1,22 @@ +warning: cast `foo` with `as *const fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:7:23 + | +LL | println!("{:p}", &foo); + | ^^^ + | + = note: `#[warn(function_references)]` on by default + +warning: cast `bar` with `as *const fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:9:23 + | +LL | println!("{:p}", &bar); + | ^^^ + +warning: cast `baz` with `as *const fn(_, _) -> _` to use it as a pointer + --> $DIR/function-references.rs:11:23 + | +LL | println!("{:p}", &baz); + | ^^^ + +warning: 3 warnings emitted + From 3214de735969602ddf2625ca500ff8d3ec57a745 Mon Sep 17 00:00:00 2001 From: Ayrton Date: Thu, 10 Sep 2020 22:53:14 -0400 Subject: [PATCH 3/8] modified lint to work with MIR Working with MIR let's us exclude expressions like `&fn_name as &dyn Something` and `(&fn_name)()`. Also added ABI, unsafety and whether a function is variadic in the lint suggestion, included the `&` in the span of the lint and updated the test. --- compiler/rustc_lint/src/builtin.rs | 34 ---- compiler/rustc_lint/src/lib.rs | 1 - .../src/transform/function_references.rs | 158 ++++++++++++++++++ compiler/rustc_mir/src/transform/mod.rs | 2 + compiler/rustc_session/src/lint/builtin.rs | 6 + src/test/ui/lint/function-references.rs | 75 +++++++-- src/test/ui/lint/function-references.stderr | 105 ++++++++++-- 7 files changed, 322 insertions(+), 59 deletions(-) create mode 100644 compiler/rustc_mir/src/transform/function_references.rs diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 86cf4ebb18743..e5f66611d0f9b 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2942,37 +2942,3 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations { } } } - -declare_lint! { - FUNCTION_REFERENCES, - Warn, - "suggest casting functions to pointers when attempting to take references" -} - -declare_lint_pass!(FunctionReferences => [FUNCTION_REFERENCES]); - -impl<'tcx> LateLintPass<'tcx> for FunctionReferences { - fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { - if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, referent) = e.kind { - if let hir::ExprKind::Path(qpath) = &referent.kind { - if let Some(def_id) = cx.qpath_res(qpath, referent.hir_id).opt_def_id() { - cx.tcx.hir().get_if_local(def_id).map(|node| { - node.fn_decl().map(|decl| { - if let Some(ident) = node.ident() { - cx.struct_span_lint(FUNCTION_REFERENCES, referent.span, |lint| { - let num_args = decl.inputs.len(); - lint.build(&format!( - "cast `{}` with `as *const fn({}) -> _` to use it as a pointer", - ident.to_string(), - vec!["_"; num_args].join(", ") - )) - .emit() - }); - } - }); - }); - } - } - } - } -} diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index b574a7da0aa46..1db59bfc39dce 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -194,7 +194,6 @@ macro_rules! late_lint_mod_passes { UnreachablePub: UnreachablePub, ExplicitOutlivesRequirements: ExplicitOutlivesRequirements, InvalidValue: InvalidValue, - FunctionReferences: FunctionReferences, ] ); }; diff --git a/compiler/rustc_mir/src/transform/function_references.rs b/compiler/rustc_mir/src/transform/function_references.rs new file mode 100644 index 0000000000000..2daa468136f2a --- /dev/null +++ b/compiler/rustc_mir/src/transform/function_references.rs @@ -0,0 +1,158 @@ +use rustc_hir::def_id::DefId; +use rustc_middle::mir::visit::Visitor; +use rustc_middle::mir::*; +use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_session::lint::builtin::FUNCTION_REFERENCES; +use rustc_span::Span; +use rustc_target::spec::abi::Abi; + +use crate::transform::{MirPass, MirSource}; + +pub struct FunctionReferences; + +impl<'tcx> MirPass<'tcx> for FunctionReferences { + fn run_pass(&self, tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut Body<'tcx>) { + let source_info = SourceInfo::outermost(body.span); + let mut checker = FunctionRefChecker { + tcx, + body, + potential_lints: Vec::new(), + casts: Vec::new(), + calls: Vec::new(), + source_info, + }; + checker.visit_body(&body); + } +} + +struct FunctionRefChecker<'a, 'tcx> { + tcx: TyCtxt<'tcx>, + body: &'a Body<'tcx>, + potential_lints: Vec, + casts: Vec, + calls: Vec, + source_info: SourceInfo, +} + +impl<'a, 'tcx> Visitor<'tcx> for FunctionRefChecker<'a, 'tcx> { + fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) { + self.super_basic_block_data(block, data); + for cast_span in self.casts.drain(..) { + self.potential_lints.retain(|lint| lint.source_info.span != cast_span); + } + for call_span in self.calls.drain(..) { + self.potential_lints.retain(|lint| lint.source_info.span != call_span); + } + for lint in self.potential_lints.drain(..) { + lint.emit(self.tcx, self.body); + } + } + fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) { + self.source_info = statement.source_info; + self.super_statement(statement, location); + } + fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { + self.source_info = terminator.source_info; + if let TerminatorKind::Call { + func, + args: _, + destination: _, + cleanup: _, + from_hir_call: _, + fn_span: _, + } = &terminator.kind + { + let span = match func { + Operand::Copy(place) | Operand::Move(place) => { + self.body.local_decls[place.local].source_info.span + } + Operand::Constant(constant) => constant.span, + }; + self.calls.push(span); + }; + self.super_terminator(terminator, location); + } + fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { + match rvalue { + Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { + let decl = &self.body.local_decls[place.local]; + if let ty::FnDef(def_id, _) = decl.ty.kind { + let ident = self + .body + .var_debug_info + .iter() + .find(|info| info.source_info.span == decl.source_info.span) + .map(|info| info.name.to_ident_string()) + .unwrap_or(self.tcx.def_path_str(def_id)); + let lint = FunctionRefLint { ident, def_id, source_info: self.source_info }; + self.potential_lints.push(lint); + } + } + Rvalue::Cast(_, op, _) => { + let op_ty = op.ty(self.body, self.tcx); + if self.is_fn_ref(op_ty) { + self.casts.push(self.source_info.span); + } + } + _ => {} + } + self.super_rvalue(rvalue, location); + } +} + +impl<'a, 'tcx> FunctionRefChecker<'a, 'tcx> { + fn is_fn_ref(&self, ty: Ty<'tcx>) -> bool { + let referent_ty = match ty.kind { + ty::Ref(_, referent_ty, _) => Some(referent_ty), + ty::RawPtr(ty_and_mut) => Some(ty_and_mut.ty), + _ => None, + }; + referent_ty + .map(|ref_ty| if let ty::FnDef(..) = ref_ty.kind { true } else { false }) + .unwrap_or(false) + } +} + +struct FunctionRefLint { + ident: String, + def_id: DefId, + source_info: SourceInfo, +} + +impl<'tcx> FunctionRefLint { + fn emit(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { + let def_id = self.def_id; + let source_info = self.source_info; + let lint_root = body.source_scopes[source_info.scope] + .local_data + .as_ref() + .assert_crate_local() + .lint_root; + let fn_sig = tcx.fn_sig(def_id); + let unsafety = fn_sig.unsafety().prefix_str(); + let abi = match fn_sig.abi() { + Abi::Rust => String::from(""), + other_abi => { + let mut s = String::from("extern \""); + s.push_str(other_abi.name()); + s.push_str("\" "); + s + } + }; + let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); + let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; + let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; + tcx.struct_span_lint_hir(FUNCTION_REFERENCES, lint_root, source_info.span, |lint| { + lint.build(&format!( + "cast `{}` with `as {}{}fn({}{}){}` to use it as a pointer", + self.ident, + unsafety, + abi, + vec!["_"; num_args].join(", "), + variadic, + ret, + )) + .emit() + }); + } +} diff --git a/compiler/rustc_mir/src/transform/mod.rs b/compiler/rustc_mir/src/transform/mod.rs index 20b8c90a9dcad..3f50420b86b11 100644 --- a/compiler/rustc_mir/src/transform/mod.rs +++ b/compiler/rustc_mir/src/transform/mod.rs @@ -27,6 +27,7 @@ pub mod dest_prop; pub mod dump_mir; pub mod early_otherwise_branch; pub mod elaborate_drops; +pub mod function_references; pub mod generator; pub mod inline; pub mod instcombine; @@ -266,6 +267,7 @@ fn mir_const<'tcx>( // MIR-level lints. &check_packed_ref::CheckPackedRef, &check_const_item_mutation::CheckConstItemMutation, + &function_references::FunctionReferences, // What we need to do constant evaluation. &simplify::SimplifyCfg::new("initial"), &rustc_peek::SanityCheck, diff --git a/compiler/rustc_session/src/lint/builtin.rs b/compiler/rustc_session/src/lint/builtin.rs index ab56a0a566757..4cfd3277202b7 100644 --- a/compiler/rustc_session/src/lint/builtin.rs +++ b/compiler/rustc_session/src/lint/builtin.rs @@ -2645,6 +2645,11 @@ declare_lint! { reference: "issue #76200 ", edition: None, }; + +declare_lint! { + pub FUNCTION_REFERENCES, + Warn, + "suggest casting functions to pointers when attempting to take references", } declare_lint! { @@ -2762,6 +2767,7 @@ declare_lint_pass! { CONST_EVALUATABLE_UNCHECKED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL, UNINHABITED_STATIC, + FUNCTION_REFERENCES, ] } diff --git a/src/test/ui/lint/function-references.rs b/src/test/ui/lint/function-references.rs index 748f2560caa3a..ad0380375d63b 100644 --- a/src/test/ui/lint/function-references.rs +++ b/src/test/ui/lint/function-references.rs @@ -1,22 +1,71 @@ // check-pass -fn foo() -> usize { 42 } -fn bar(x: usize) -> usize { x } -fn baz(x: usize, y: usize) -> usize { x + y } +#![feature(c_variadic)] +#![allow(dead_code)] + +fn foo() -> u32 { 42 } +fn bar(x: u32) -> u32 { x } +fn baz(x: u32, y: u32) -> u32 { x + y } +unsafe fn unsafe_fn() { } +extern "C" fn c_fn() { } +unsafe extern "C" fn unsafe_c_fn() { } +unsafe extern fn variadic_fn(_x: u32, _args: ...) { } +fn call_fn(f: &dyn Fn(u32) -> u32, x: u32) { f(x); } +fn parameterized_call_fn u32>(f: &F, x: u32) { f(x); } fn main() { + let _zst_ref = &foo; + //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + let fn_item = foo; + let _indirect_ref = &fn_item; + //~^ WARN cast `fn_item` with `as fn() -> _` to use it as a pointer + let _cast_zst_ptr = &foo as *const _; + //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + let _coerced_zst_ptr: *const _ = &foo; + //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + + let _zst_ref = &mut foo; + //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + let mut mut_fn_item = foo; + let _indirect_ref = &mut mut_fn_item; + //~^ WARN cast `fn_item` with `as fn() -> _` to use it as a pointer + let _cast_zst_ptr = &mut foo as *mut _; + //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + let _coerced_zst_ptr: *mut _ = &mut foo; + //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + + let _cast_zst_ref = &foo as &dyn Fn() -> u32; + let _coerced_zst_ref: &dyn Fn() -> u32 = &foo; + + let _cast_zst_ref = &mut foo as &mut dyn Fn() -> u32; + let _coerced_zst_ref: &mut dyn Fn() -> u32 = &mut foo; + let _fn_ptr = foo as fn() -> u32; + println!("{:p}", &foo); - //~^ WARN cast `foo` with `as *const fn() -> _` to use it as a pointer + //~^ WARN cast `foo` with as fn() -> _` to use it as a pointer println!("{:p}", &bar); - //~^ WARN cast `bar` with `as *const fn(_) -> _` to use it as a pointer + //~^ WARN cast `bar` with as fn(_) -> _` to use it as a pointer println!("{:p}", &baz); - //~^ WARN cast `baz` with `as *const fn(_, _) -> _` to use it as a pointer + //~^ WARN cast `baz` with as fn(_, _) -> _` to use it as a pointer + println!("{:p}", &unsafe_fn); + //~^ WARN cast `baz` with as unsafe fn()` to use it as a pointer + println!("{:p}", &c_fn); + //~^ WARN cast `baz` with as extern "C" fn()` to use it as a pointer + println!("{:p}", &unsafe_c_fn); + //~^ WARN cast `baz` with as unsafe extern "C" fn()` to use it as a pointer + println!("{:p}", &variadic_fn); + //~^ WARN cast `baz` with as unsafe extern "C" fn(_, ...) -> _` to use it as a pointer + println!("{:p}", &std::env::var::); + //~^ WARN cast `std::env::var` with as fn(_) -> _` to use it as a pointer + + println!("{:p}", foo as fn() -> u32); - //should not produce any warnings - println!("{:p}", foo as *const fn() -> usize); - println!("{:p}", bar as *const fn(usize) -> usize); - println!("{:p}", baz as *const fn(usize, usize) -> usize); + unsafe { + std::mem::transmute::<_, usize>(&foo); + //~^ WARN cast `foo` with as fn() -> _` to use it as a pointer + std::mem::transmute::<_, usize>(foo as fn() -> u32); + } - //should not produce any warnings - let fn_thing = foo; - println!("{:p}", &fn_thing); + (&bar)(1); + call_fn(&bar, 1); + parameterized_call_fn(&bar, 1); } diff --git a/src/test/ui/lint/function-references.stderr b/src/test/ui/lint/function-references.stderr index bd2da6e1167a7..62dbf7f835dc9 100644 --- a/src/test/ui/lint/function-references.stderr +++ b/src/test/ui/lint/function-references.stderr @@ -1,22 +1,105 @@ -warning: cast `foo` with `as *const fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:7:23 +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:16:20 | -LL | println!("{:p}", &foo); - | ^^^ +LL | let _zst_ref = &foo; + | ^^^^ | = note: `#[warn(function_references)]` on by default -warning: cast `bar` with `as *const fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:9:23 +warning: cast `fn_item` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:19:25 + | +LL | let _indirect_ref = &fn_item; + | ^^^^^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:21:25 + | +LL | let _cast_zst_ptr = &foo as *const _; + | ^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:23:38 + | +LL | let _coerced_zst_ptr: *const _ = &foo; + | ^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:26:20 + | +LL | let _zst_ref = &mut foo; + | ^^^^^^^^ + +warning: cast `mut_fn_item` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:29:25 + | +LL | let _indirect_ref = &mut mut_fn_item; + | ^^^^^^^^^^^^^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:31:25 + | +LL | let _cast_zst_ptr = &mut foo as *mut _; + | ^^^^^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:33:36 + | +LL | let _coerced_zst_ptr: *mut _ = &mut foo; + | ^^^^^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:43:22 + | +LL | println!("{:p}", &foo); + | ^^^^ + +warning: cast `bar` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:45:22 | LL | println!("{:p}", &bar); - | ^^^ + | ^^^^ -warning: cast `baz` with `as *const fn(_, _) -> _` to use it as a pointer - --> $DIR/function-references.rs:11:23 +warning: cast `baz` with `as fn(_, _) -> _` to use it as a pointer + --> $DIR/function-references.rs:47:22 | LL | println!("{:p}", &baz); - | ^^^ + | ^^^^ + +warning: cast `unsafe_fn` with `as unsafe fn()` to use it as a pointer + --> $DIR/function-references.rs:49:22 + | +LL | println!("{:p}", &unsafe_fn); + | ^^^^^^^^^^ + +warning: cast `c_fn` with `as extern "C" fn()` to use it as a pointer + --> $DIR/function-references.rs:51:22 + | +LL | println!("{:p}", &c_fn); + | ^^^^^ -warning: 3 warnings emitted +warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to use it as a pointer + --> $DIR/function-references.rs:53:22 + | +LL | println!("{:p}", &unsafe_c_fn); + | ^^^^^^^^^^^^ + +warning: cast `variadic_fn` with `as unsafe extern "C" fn(_, ...)` to use it as a pointer + --> $DIR/function-references.rs:55:22 + | +LL | println!("{:p}", &variadic_fn); + | ^^^^^^^^^^^^ + +warning: cast `std::env::var` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:57:22 + | +LL | println!("{:p}", &std::env::var::); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:63:41 + | +LL | std::mem::transmute::<_, usize>(&foo); + | ^^^^ +warning: 17 warnings emitted From 511fe048b4ee2535961014b1be3294a771cc7e87 Mon Sep 17 00:00:00 2001 From: Ayrton Date: Tue, 6 Oct 2020 09:51:10 -0400 Subject: [PATCH 4/8] Changed lint to check for `std::fmt::Pointer` and `transmute` The lint checks arguments in calls to `transmute` or functions that have `Pointer` as a trait bound and displays a warning if the argument is a function reference. Also checks for `std::fmt::Pointer::fmt` to handle formatting macros although it doesn't depend on the exact expansion of the macro or formatting internals. `std::fmt::Pointer` and `std::fmt::Pointer::fmt` were also added as diagnostic items and symbols. --- .../src/transform/function_references.rs | 204 ++++++++++-------- compiler/rustc_mir/src/transform/mod.rs | 2 +- compiler/rustc_session/src/lint/builtin.rs | 5 +- compiler/rustc_span/src/symbol.rs | 2 + library/core/src/fmt/mod.rs | 2 + src/test/ui/lint/function-references.rs | 134 +++++++++--- src/test/ui/lint/function-references.stderr | 143 ++++++++---- 7 files changed, 324 insertions(+), 168 deletions(-) diff --git a/compiler/rustc_mir/src/transform/function_references.rs b/compiler/rustc_mir/src/transform/function_references.rs index 2daa468136f2a..8adeac7623bad 100644 --- a/compiler/rustc_mir/src/transform/function_references.rs +++ b/compiler/rustc_mir/src/transform/function_references.rs @@ -1,134 +1,154 @@ use rustc_hir::def_id::DefId; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_session::lint::builtin::FUNCTION_REFERENCES; -use rustc_span::Span; +use rustc_middle::ty::{self, subst::GenericArgKind, PredicateAtom, Ty, TyCtxt, TyS}; +use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; +use rustc_span::{symbol::sym, Span}; use rustc_target::spec::abi::Abi; -use crate::transform::{MirPass, MirSource}; +use crate::transform::MirPass; -pub struct FunctionReferences; +pub struct FunctionItemReferences; -impl<'tcx> MirPass<'tcx> for FunctionReferences { - fn run_pass(&self, tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut Body<'tcx>) { - let source_info = SourceInfo::outermost(body.span); - let mut checker = FunctionRefChecker { - tcx, - body, - potential_lints: Vec::new(), - casts: Vec::new(), - calls: Vec::new(), - source_info, - }; +impl<'tcx> MirPass<'tcx> for FunctionItemReferences { + fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { + let mut checker = FunctionItemRefChecker { tcx, body }; checker.visit_body(&body); } } -struct FunctionRefChecker<'a, 'tcx> { +struct FunctionItemRefChecker<'a, 'tcx> { tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, - potential_lints: Vec, - casts: Vec, - calls: Vec, - source_info: SourceInfo, } -impl<'a, 'tcx> Visitor<'tcx> for FunctionRefChecker<'a, 'tcx> { - fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) { - self.super_basic_block_data(block, data); - for cast_span in self.casts.drain(..) { - self.potential_lints.retain(|lint| lint.source_info.span != cast_span); - } - for call_span in self.calls.drain(..) { - self.potential_lints.retain(|lint| lint.source_info.span != call_span); - } - for lint in self.potential_lints.drain(..) { - lint.emit(self.tcx, self.body); - } - } - fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) { - self.source_info = statement.source_info; - self.super_statement(statement, location); - } +impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { - self.source_info = terminator.source_info; if let TerminatorKind::Call { func, - args: _, + args, destination: _, cleanup: _, from_hir_call: _, fn_span: _, } = &terminator.kind { - let span = match func { - Operand::Copy(place) | Operand::Move(place) => { - self.body.local_decls[place.local].source_info.span + let func_ty = func.ty(self.body, self.tcx); + if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() { + //check arguments for `std::mem::transmute` + if self.tcx.is_diagnostic_item(sym::transmute, def_id) { + let arg_ty = args[0].ty(self.body, self.tcx); + for generic_inner_ty in arg_ty.walk() { + if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { + if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(inner_ty) { + let ident = self.tcx.item_name(fn_id).to_ident_string(); + let source_info = *self.body.source_info(location); + let span = self.nth_arg_span(&args, 0); + self.emit_lint(ident, fn_id, source_info, span); + } + } + } + } else { + //check arguments for any function with `std::fmt::Pointer` as a bound trait + let param_env = self.tcx.param_env(def_id); + let bounds = param_env.caller_bounds(); + for bound in bounds { + if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { + let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); + for (arg_num, arg_def) in arg_defs.iter().enumerate() { + for generic_inner_ty in arg_def.walk() { + if let GenericArgKind::Type(inner_ty) = + generic_inner_ty.unpack() + { + //if any type reachable from the argument types in the fn sig matches the type bound by `Pointer` + if TyS::same_type(inner_ty, bound_ty) { + //check if this type is a function reference in the function call + let norm_ty = + self.tcx.subst_and_normalize_erasing_regions( + substs_ref, param_env, &inner_ty, + ); + if let Some(fn_id) = + FunctionItemRefChecker::is_fn_ref(norm_ty) + { + let ident = + self.tcx.item_name(fn_id).to_ident_string(); + let source_info = *self.body.source_info(location); + let span = self.nth_arg_span(&args, arg_num); + self.emit_lint(ident, fn_id, source_info, span); + } + } + } + } + } + } + } } - Operand::Constant(constant) => constant.span, - }; - self.calls.push(span); - }; + } + } self.super_terminator(terminator, location); } - fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { - match rvalue { - Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { - let decl = &self.body.local_decls[place.local]; - if let ty::FnDef(def_id, _) = decl.ty.kind { - let ident = self - .body - .var_debug_info - .iter() - .find(|info| info.source_info.span == decl.source_info.span) - .map(|info| info.name.to_ident_string()) - .unwrap_or(self.tcx.def_path_str(def_id)); - let lint = FunctionRefLint { ident, def_id, source_info: self.source_info }; - self.potential_lints.push(lint); - } - } - Rvalue::Cast(_, op, _) => { - let op_ty = op.ty(self.body, self.tcx); - if self.is_fn_ref(op_ty) { - self.casts.push(self.source_info.span); + //check for `std::fmt::Pointer::::fmt` where T is a function reference + //this is used in formatting macros, but doesn't rely on the specific expansion + fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) { + let op_ty = operand.ty(self.body, self.tcx); + if let ty::FnDef(def_id, substs_ref) = *op_ty.kind() { + if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) { + let param_ty = substs_ref.type_at(0); + if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(param_ty) { + let source_info = *self.body.source_info(location); + let callsite_ctxt = source_info.span.source_callsite().ctxt(); + let span = source_info.span.with_ctxt(callsite_ctxt); + let ident = self.tcx.item_name(fn_id).to_ident_string(); + self.emit_lint(ident, fn_id, source_info, span); } } - _ => {} } - self.super_rvalue(rvalue, location); + self.super_operand(operand, location); } } -impl<'a, 'tcx> FunctionRefChecker<'a, 'tcx> { - fn is_fn_ref(&self, ty: Ty<'tcx>) -> bool { - let referent_ty = match ty.kind { +impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { + //return the bound parameter type if the trait is `std::fmt::Pointer` + fn is_pointer_trait(&self, bound: &PredicateAtom<'tcx>) -> Option> { + if let ty::PredicateAtom::Trait(predicate, _) = bound { + if self.tcx.is_diagnostic_item(sym::pointer_trait, predicate.def_id()) { + Some(predicate.trait_ref.self_ty()) + } else { + None + } + } else { + None + } + } + fn is_fn_ref(ty: Ty<'tcx>) -> Option { + let referent_ty = match ty.kind() { ty::Ref(_, referent_ty, _) => Some(referent_ty), - ty::RawPtr(ty_and_mut) => Some(ty_and_mut.ty), + ty::RawPtr(ty_and_mut) => Some(&ty_and_mut.ty), _ => None, }; referent_ty - .map(|ref_ty| if let ty::FnDef(..) = ref_ty.kind { true } else { false }) - .unwrap_or(false) + .map( + |ref_ty| { + if let ty::FnDef(def_id, _) = *ref_ty.kind() { Some(def_id) } else { None } + }, + ) + .unwrap_or(None) } -} - -struct FunctionRefLint { - ident: String, - def_id: DefId, - source_info: SourceInfo, -} - -impl<'tcx> FunctionRefLint { - fn emit(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { - let def_id = self.def_id; - let source_info = self.source_info; - let lint_root = body.source_scopes[source_info.scope] + fn nth_arg_span(&self, args: &Vec>, n: usize) -> Span { + match &args[n] { + Operand::Copy(place) | Operand::Move(place) => { + self.body.local_decls[place.local].source_info.span + } + Operand::Constant(constant) => constant.span, + } + } + fn emit_lint(&self, ident: String, fn_id: DefId, source_info: SourceInfo, span: Span) { + let lint_root = self.body.source_scopes[source_info.scope] .local_data .as_ref() .assert_crate_local() .lint_root; - let fn_sig = tcx.fn_sig(def_id); + let fn_sig = self.tcx.fn_sig(fn_id); let unsafety = fn_sig.unsafety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(""), @@ -142,17 +162,17 @@ impl<'tcx> FunctionRefLint { let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; - tcx.struct_span_lint_hir(FUNCTION_REFERENCES, lint_root, source_info.span, |lint| { + self.tcx.struct_span_lint_hir(FUNCTION_ITEM_REFERENCES, lint_root, span, |lint| { lint.build(&format!( "cast `{}` with `as {}{}fn({}{}){}` to use it as a pointer", - self.ident, + ident, unsafety, abi, vec!["_"; num_args].join(", "), variadic, ret, )) - .emit() + .emit(); }); } } diff --git a/compiler/rustc_mir/src/transform/mod.rs b/compiler/rustc_mir/src/transform/mod.rs index 3f50420b86b11..e43a238c1bad1 100644 --- a/compiler/rustc_mir/src/transform/mod.rs +++ b/compiler/rustc_mir/src/transform/mod.rs @@ -267,7 +267,7 @@ fn mir_const<'tcx>( // MIR-level lints. &check_packed_ref::CheckPackedRef, &check_const_item_mutation::CheckConstItemMutation, - &function_references::FunctionReferences, + &function_references::FunctionItemReferences, // What we need to do constant evaluation. &simplify::SimplifyCfg::new("initial"), &rustc_peek::SanityCheck, diff --git a/compiler/rustc_session/src/lint/builtin.rs b/compiler/rustc_session/src/lint/builtin.rs index 4cfd3277202b7..41abdacb54c86 100644 --- a/compiler/rustc_session/src/lint/builtin.rs +++ b/compiler/rustc_session/src/lint/builtin.rs @@ -2645,9 +2645,10 @@ declare_lint! { reference: "issue #76200 ", edition: None, }; +} declare_lint! { - pub FUNCTION_REFERENCES, + pub FUNCTION_ITEM_REFERENCES, Warn, "suggest casting functions to pointers when attempting to take references", } @@ -2767,7 +2768,7 @@ declare_lint_pass! { CONST_EVALUATABLE_UNCHECKED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL, UNINHABITED_STATIC, - FUNCTION_REFERENCES, + FUNCTION_ITEM_REFERENCES, ] } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 080afdcd2c036..ef0f09ae81895 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -796,6 +796,8 @@ symbols! { plugin_registrar, plugins, pointer, + pointer_trait, + pointer_trait_fmt, poll, position, post_dash_lto: "post-lto", diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 0963c6d6cd7ea..506d778068682 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -920,9 +920,11 @@ pub trait UpperHex { /// assert_eq!(&l_ptr[..2], "0x"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] +#[rustc_diagnostic_item = "pointer_trait"] pub trait Pointer { /// Formats the value using the given formatter. #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "pointer_trait_fmt"] fn fmt(&self, f: &mut Formatter<'_>) -> Result; } diff --git a/src/test/ui/lint/function-references.rs b/src/test/ui/lint/function-references.rs index ad0380375d63b..1a8dde857909b 100644 --- a/src/test/ui/lint/function-references.rs +++ b/src/test/ui/lint/function-references.rs @@ -1,7 +1,9 @@ // check-pass #![feature(c_variadic)] -#![allow(dead_code)] +#![warn(function_item_references)] +use std::fmt::Pointer; +fn nop() { } fn foo() -> u32 { 42 } fn bar(x: u32) -> u32 { x } fn baz(x: u32, y: u32) -> u32 { x + y } @@ -9,63 +11,127 @@ unsafe fn unsafe_fn() { } extern "C" fn c_fn() { } unsafe extern "C" fn unsafe_c_fn() { } unsafe extern fn variadic_fn(_x: u32, _args: ...) { } + +//function references passed to these functions should never lint fn call_fn(f: &dyn Fn(u32) -> u32, x: u32) { f(x); } fn parameterized_call_fn u32>(f: &F, x: u32) { f(x); } +//function references passed to these functions should lint +fn print_ptr(f: F) { println!("{:p}", f); } +fn bound_by_ptr_trait(_f: F) { } +fn bound_by_ptr_trait_tuple(_t: (F, G)) { } +fn implicit_ptr_trait(f: &F) { println!("{:p}", f); } + fn main() { - let _zst_ref = &foo; - //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + //`let` bindings with function references shouldn't lint + let _ = &foo; + let _ = &mut foo; + + let zst_ref = &foo; let fn_item = foo; - let _indirect_ref = &fn_item; - //~^ WARN cast `fn_item` with `as fn() -> _` to use it as a pointer - let _cast_zst_ptr = &foo as *const _; - //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer - let _coerced_zst_ptr: *const _ = &foo; - //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer - - let _zst_ref = &mut foo; - //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + let indirect_ref = &fn_item; + + let _mut_zst_ref = &mut foo; let mut mut_fn_item = foo; - let _indirect_ref = &mut mut_fn_item; - //~^ WARN cast `fn_item` with `as fn() -> _` to use it as a pointer - let _cast_zst_ptr = &mut foo as *mut _; - //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer - let _coerced_zst_ptr: *mut _ = &mut foo; - //~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer + let _mut_indirect_ref = &mut mut_fn_item; + + let cast_zst_ptr = &foo as *const _; + let coerced_zst_ptr: *const _ = &foo; + + let _mut_cast_zst_ptr = &mut foo as *mut _; + let _mut_coerced_zst_ptr: *mut _ = &mut foo; let _cast_zst_ref = &foo as &dyn Fn() -> u32; let _coerced_zst_ref: &dyn Fn() -> u32 = &foo; - let _cast_zst_ref = &mut foo as &mut dyn Fn() -> u32; - let _coerced_zst_ref: &mut dyn Fn() -> u32 = &mut foo; - let _fn_ptr = foo as fn() -> u32; + let _mut_cast_zst_ref = &mut foo as &mut dyn Fn() -> u32; + let _mut_coerced_zst_ref: &mut dyn Fn() -> u32 = &mut foo; + //the suggested way to cast to a function pointer + let fn_ptr = foo as fn() -> u32; + + //correct ways to print function pointers + println!("{:p}", foo as fn() -> u32); + println!("{:p}", fn_ptr); + + //potential ways to incorrectly try printing function pointers println!("{:p}", &foo); - //~^ WARN cast `foo` with as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + print!("{:p}", &foo); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + format!("{:p}", &foo); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + + println!("{:p}", &foo as *const _); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + println!("{:p}", zst_ref); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + println!("{:p}", cast_zst_ptr); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + println!("{:p}", coerced_zst_ptr); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + + println!("{:p}", &fn_item); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + println!("{:p}", indirect_ref); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + + println!("{:p}", &nop); + //~^ WARNING cast `nop` with `as fn()` to use it as a pointer println!("{:p}", &bar); - //~^ WARN cast `bar` with as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer println!("{:p}", &baz); - //~^ WARN cast `baz` with as fn(_, _) -> _` to use it as a pointer + //~^ WARNING cast `baz` with `as fn(_, _) -> _` to use it as a pointer println!("{:p}", &unsafe_fn); - //~^ WARN cast `baz` with as unsafe fn()` to use it as a pointer + //~^ WARNING cast `unsafe_fn` with `as unsafe fn()` to use it as a pointer println!("{:p}", &c_fn); - //~^ WARN cast `baz` with as extern "C" fn()` to use it as a pointer + //~^ WARNING cast `c_fn` with `as extern "C" fn()` to use it as a pointer println!("{:p}", &unsafe_c_fn); - //~^ WARN cast `baz` with as unsafe extern "C" fn()` to use it as a pointer + //~^ WARNING cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to use it as a pointer println!("{:p}", &variadic_fn); - //~^ WARN cast `baz` with as unsafe extern "C" fn(_, ...) -> _` to use it as a pointer + //~^ WARNING cast `variadic_fn` with `as unsafe extern "C" fn(_, ...)` to use it as a pointer println!("{:p}", &std::env::var::); - //~^ WARN cast `std::env::var` with as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `var` with `as fn(_) -> _` to use it as a pointer - println!("{:p}", foo as fn() -> u32); + println!("{:p} {:p} {:p}", &nop, &foo, &bar); + //~^ WARNING cast `nop` with `as fn()` to use it as a pointer + //~^^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^^^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + + //using a function reference to call a function shouldn't lint + (&bar)(1); + + //passing a function reference to an arbitrary function shouldn't lint + call_fn(&bar, 1); + parameterized_call_fn(&bar, 1); + std::mem::size_of_val(&foo); unsafe { + //potential ways to incorrectly try transmuting function pointers std::mem::transmute::<_, usize>(&foo); - //~^ WARN cast `foo` with as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + + //the correct way to transmute function pointers std::mem::transmute::<_, usize>(foo as fn() -> u32); + std::mem::transmute::<_, (usize, usize)>((foo as fn() -> u32, bar as fn(u32) -> u32)); } - (&bar)(1); - call_fn(&bar, 1); - parameterized_call_fn(&bar, 1); + //function references as arguments required to be bound by std::fmt::Pointer should lint + print_ptr(&bar); + //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + bound_by_ptr_trait(&bar); + //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + bound_by_ptr_trait_tuple((&foo, &bar)); + //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + implicit_ptr_trait(&bar); + //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + + //correct ways to pass function pointers as arguments bound by std::fmt::Pointer + print_ptr(bar as fn(u32) -> u32); + bound_by_ptr_trait(bar as fn(u32) -> u32); + bound_by_ptr_trait_tuple((foo as fn() -> u32, bar as fn(u32) -> u32)); } diff --git a/src/test/ui/lint/function-references.stderr b/src/test/ui/lint/function-references.stderr index 62dbf7f835dc9..bc4947b3d7061 100644 --- a/src/test/ui/lint/function-references.stderr +++ b/src/test/ui/lint/function-references.stderr @@ -1,105 +1,170 @@ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:16:20 + --> $DIR/function-references.rs:58:22 | -LL | let _zst_ref = &foo; - | ^^^^ +LL | println!("{:p}", &foo); + | ^^^^ | - = note: `#[warn(function_references)]` on by default +note: the lint level is defined here + --> $DIR/function-references.rs:3:9 + | +LL | #![warn(function_item_references)] + | ^^^^^^^^^^^^^^^^^^^^^^^^ -warning: cast `fn_item` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:19:25 +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:60:20 | -LL | let _indirect_ref = &fn_item; - | ^^^^^^^^ +LL | print!("{:p}", &foo); + | ^^^^ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:21:25 + --> $DIR/function-references.rs:62:21 | -LL | let _cast_zst_ptr = &foo as *const _; - | ^^^^ +LL | format!("{:p}", &foo); + | ^^^^ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:23:38 + --> $DIR/function-references.rs:65:22 | -LL | let _coerced_zst_ptr: *const _ = &foo; - | ^^^^ +LL | println!("{:p}", &foo as *const _); + | ^^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:26:20 + --> $DIR/function-references.rs:67:22 | -LL | let _zst_ref = &mut foo; - | ^^^^^^^^ +LL | println!("{:p}", zst_ref); + | ^^^^^^^ -warning: cast `mut_fn_item` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:29:25 +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:69:22 | -LL | let _indirect_ref = &mut mut_fn_item; - | ^^^^^^^^^^^^^^^^ +LL | println!("{:p}", cast_zst_ptr); + | ^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:31:25 + --> $DIR/function-references.rs:71:22 | -LL | let _cast_zst_ptr = &mut foo as *mut _; - | ^^^^^^^^ +LL | println!("{:p}", coerced_zst_ptr); + | ^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:33:36 + --> $DIR/function-references.rs:74:22 | -LL | let _coerced_zst_ptr: *mut _ = &mut foo; - | ^^^^^^^^ +LL | println!("{:p}", &fn_item); + | ^^^^^^^^ warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:43:22 + --> $DIR/function-references.rs:76:22 | -LL | println!("{:p}", &foo); +LL | println!("{:p}", indirect_ref); + | ^^^^^^^^^^^^ + +warning: cast `nop` with `as fn()` to use it as a pointer + --> $DIR/function-references.rs:79:22 + | +LL | println!("{:p}", &nop); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:45:22 + --> $DIR/function-references.rs:81:22 | LL | println!("{:p}", &bar); | ^^^^ warning: cast `baz` with `as fn(_, _) -> _` to use it as a pointer - --> $DIR/function-references.rs:47:22 + --> $DIR/function-references.rs:83:22 | LL | println!("{:p}", &baz); | ^^^^ warning: cast `unsafe_fn` with `as unsafe fn()` to use it as a pointer - --> $DIR/function-references.rs:49:22 + --> $DIR/function-references.rs:85:22 | LL | println!("{:p}", &unsafe_fn); | ^^^^^^^^^^ warning: cast `c_fn` with `as extern "C" fn()` to use it as a pointer - --> $DIR/function-references.rs:51:22 + --> $DIR/function-references.rs:87:22 | LL | println!("{:p}", &c_fn); | ^^^^^ warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to use it as a pointer - --> $DIR/function-references.rs:53:22 + --> $DIR/function-references.rs:89:22 | LL | println!("{:p}", &unsafe_c_fn); | ^^^^^^^^^^^^ warning: cast `variadic_fn` with `as unsafe extern "C" fn(_, ...)` to use it as a pointer - --> $DIR/function-references.rs:55:22 + --> $DIR/function-references.rs:91:22 | LL | println!("{:p}", &variadic_fn); | ^^^^^^^^^^^^ -warning: cast `std::env::var` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:57:22 +warning: cast `var` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:93:22 | LL | println!("{:p}", &std::env::var::); | ^^^^^^^^^^^^^^^^^^^^^^^^ +warning: cast `nop` with `as fn()` to use it as a pointer + --> $DIR/function-references.rs:96:32 + | +LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); + | ^^^^ + warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:63:41 + --> $DIR/function-references.rs:96:38 + | +LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); + | ^^^^ + +warning: cast `bar` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:96:44 + | +LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); + | ^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:111:41 | LL | std::mem::transmute::<_, usize>(&foo); | ^^^^ -warning: 17 warnings emitted +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:113:50 + | +LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); + | ^^^^^^^^^^^^ + +warning: cast `bar` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:113:50 + | +LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); + | ^^^^^^^^^^^^ + +warning: cast `bar` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:123:15 + | +LL | print_ptr(&bar); + | ^^^^ + +warning: cast `bar` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:125:24 + | +LL | bound_by_ptr_trait(&bar); + | ^^^^ + +warning: cast `bar` with `as fn(_) -> _` to use it as a pointer + --> $DIR/function-references.rs:127:30 + | +LL | bound_by_ptr_trait_tuple((&foo, &bar)); + | ^^^^^^^^^^^^ + +warning: cast `foo` with `as fn() -> _` to use it as a pointer + --> $DIR/function-references.rs:127:30 + | +LL | bound_by_ptr_trait_tuple((&foo, &bar)); + | ^^^^^^^^^^^^ + +warning: 27 warnings emitted + From 432ebd57efe38e691acc25570cb79acbe4956651 Mon Sep 17 00:00:00 2001 From: Ayrton Date: Tue, 6 Oct 2020 11:59:14 -0400 Subject: [PATCH 5/8] Removed test for unhandled case in function_item_references lint Removed test for the unhandled case of calls to `fn f(x: &T)` where `x` is a function reference and is formatted as a pointer in `f`. This compiles since `&T` implements `Pointer`, but is unlikely to occur in practice. Also tweaked the lint's wording and modified tests accordingly. --- .../src/transform/function_references.rs | 2 +- src/test/ui/lint/function-references.rs | 61 +++++----- src/test/ui/lint/function-references.stderr | 112 +++++++++--------- 3 files changed, 86 insertions(+), 89 deletions(-) diff --git a/compiler/rustc_mir/src/transform/function_references.rs b/compiler/rustc_mir/src/transform/function_references.rs index 8adeac7623bad..97688c3ea162f 100644 --- a/compiler/rustc_mir/src/transform/function_references.rs +++ b/compiler/rustc_mir/src/transform/function_references.rs @@ -164,7 +164,7 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; self.tcx.struct_span_lint_hir(FUNCTION_ITEM_REFERENCES, lint_root, span, |lint| { lint.build(&format!( - "cast `{}` with `as {}{}fn({}{}){}` to use it as a pointer", + "cast `{}` with `as {}{}fn({}{}){}` to obtain a function pointer", ident, unsafety, abi, diff --git a/src/test/ui/lint/function-references.rs b/src/test/ui/lint/function-references.rs index 1a8dde857909b..9ec3871e48218 100644 --- a/src/test/ui/lint/function-references.rs +++ b/src/test/ui/lint/function-references.rs @@ -10,7 +10,7 @@ fn baz(x: u32, y: u32) -> u32 { x + y } unsafe fn unsafe_fn() { } extern "C" fn c_fn() { } unsafe extern "C" fn unsafe_c_fn() { } -unsafe extern fn variadic_fn(_x: u32, _args: ...) { } +unsafe extern fn variadic(_x: u32, _args: ...) { } //function references passed to these functions should never lint fn call_fn(f: &dyn Fn(u32) -> u32, x: u32) { f(x); } @@ -20,7 +20,6 @@ fn parameterized_call_fn u32>(f: &F, x: u32) { f(x); } fn print_ptr(f: F) { println!("{:p}", f); } fn bound_by_ptr_trait(_f: F) { } fn bound_by_ptr_trait_tuple(_t: (F, G)) { } -fn implicit_ptr_trait(f: &F) { println!("{:p}", f); } fn main() { //`let` bindings with function references shouldn't lint @@ -56,47 +55,47 @@ fn main() { //potential ways to incorrectly try printing function pointers println!("{:p}", &foo); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer print!("{:p}", &foo); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer format!("{:p}", &foo); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", &foo as *const _); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", zst_ref); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", cast_zst_ptr); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", coerced_zst_ptr); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", &fn_item); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", indirect_ref); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer println!("{:p}", &nop); - //~^ WARNING cast `nop` with `as fn()` to use it as a pointer + //~^ WARNING cast `nop` with `as fn()` to obtain a function pointer println!("{:p}", &bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer println!("{:p}", &baz); - //~^ WARNING cast `baz` with `as fn(_, _) -> _` to use it as a pointer + //~^ WARNING cast `baz` with `as fn(_, _) -> _` to obtain a function pointer println!("{:p}", &unsafe_fn); - //~^ WARNING cast `unsafe_fn` with `as unsafe fn()` to use it as a pointer + //~^ WARNING cast `unsafe_fn` with `as unsafe fn()` to obtain a function pointer println!("{:p}", &c_fn); - //~^ WARNING cast `c_fn` with `as extern "C" fn()` to use it as a pointer + //~^ WARNING cast `c_fn` with `as extern "C" fn()` to obtain a function pointer println!("{:p}", &unsafe_c_fn); - //~^ WARNING cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to use it as a pointer - println!("{:p}", &variadic_fn); - //~^ WARNING cast `variadic_fn` with `as unsafe extern "C" fn(_, ...)` to use it as a pointer + //~^ WARNING cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to obtain a function pointer + println!("{:p}", &variadic); + //~^ WARNING cast `variadic` with `as unsafe extern "C" fn(_, ...)` to obtain a function pointer println!("{:p}", &std::env::var::); - //~^ WARNING cast `var` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `var` with `as fn(_) -> _` to obtain a function pointer println!("{:p} {:p} {:p}", &nop, &foo, &bar); - //~^ WARNING cast `nop` with `as fn()` to use it as a pointer - //~^^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer - //~^^^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `nop` with `as fn()` to obtain a function pointer + //~^^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer //using a function reference to call a function shouldn't lint (&bar)(1); @@ -109,10 +108,10 @@ fn main() { unsafe { //potential ways to incorrectly try transmuting function pointers std::mem::transmute::<_, usize>(&foo); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer - //~^^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer //the correct way to transmute function pointers std::mem::transmute::<_, usize>(foo as fn() -> u32); @@ -121,14 +120,12 @@ fn main() { //function references as arguments required to be bound by std::fmt::Pointer should lint print_ptr(&bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer bound_by_ptr_trait(&bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer bound_by_ptr_trait_tuple((&foo, &bar)); - //~^ WARNING cast `foo` with `as fn() -> _` to use it as a pointer - //~^^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer - implicit_ptr_trait(&bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to use it as a pointer + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer //correct ways to pass function pointers as arguments bound by std::fmt::Pointer print_ptr(bar as fn(u32) -> u32); diff --git a/src/test/ui/lint/function-references.stderr b/src/test/ui/lint/function-references.stderr index bc4947b3d7061..71940a1d4cf8a 100644 --- a/src/test/ui/lint/function-references.stderr +++ b/src/test/ui/lint/function-references.stderr @@ -1,5 +1,5 @@ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:58:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:57:22 | LL | println!("{:p}", &foo); | ^^^^ @@ -10,158 +10,158 @@ note: the lint level is defined here LL | #![warn(function_item_references)] | ^^^^^^^^^^^^^^^^^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:60:20 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:59:20 | LL | print!("{:p}", &foo); | ^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:62:21 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:61:21 | LL | format!("{:p}", &foo); | ^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:65:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:64:22 | LL | println!("{:p}", &foo as *const _); | ^^^^^^^^^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:67:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:66:22 | LL | println!("{:p}", zst_ref); | ^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:69:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:68:22 | LL | println!("{:p}", cast_zst_ptr); | ^^^^^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:71:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:70:22 | LL | println!("{:p}", coerced_zst_ptr); | ^^^^^^^^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:74:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:73:22 | LL | println!("{:p}", &fn_item); | ^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:76:22 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:75:22 | LL | println!("{:p}", indirect_ref); | ^^^^^^^^^^^^ -warning: cast `nop` with `as fn()` to use it as a pointer - --> $DIR/function-references.rs:79:22 +warning: cast `nop` with `as fn()` to obtain a function pointer + --> $DIR/function-references.rs:78:22 | LL | println!("{:p}", &nop); | ^^^^ -warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:81:22 +warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:80:22 | LL | println!("{:p}", &bar); | ^^^^ -warning: cast `baz` with `as fn(_, _) -> _` to use it as a pointer - --> $DIR/function-references.rs:83:22 +warning: cast `baz` with `as fn(_, _) -> _` to obtain a function pointer + --> $DIR/function-references.rs:82:22 | LL | println!("{:p}", &baz); | ^^^^ -warning: cast `unsafe_fn` with `as unsafe fn()` to use it as a pointer - --> $DIR/function-references.rs:85:22 +warning: cast `unsafe_fn` with `as unsafe fn()` to obtain a function pointer + --> $DIR/function-references.rs:84:22 | LL | println!("{:p}", &unsafe_fn); | ^^^^^^^^^^ -warning: cast `c_fn` with `as extern "C" fn()` to use it as a pointer - --> $DIR/function-references.rs:87:22 +warning: cast `c_fn` with `as extern "C" fn()` to obtain a function pointer + --> $DIR/function-references.rs:86:22 | LL | println!("{:p}", &c_fn); | ^^^^^ -warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to use it as a pointer - --> $DIR/function-references.rs:89:22 +warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to obtain a function pointer + --> $DIR/function-references.rs:88:22 | LL | println!("{:p}", &unsafe_c_fn); | ^^^^^^^^^^^^ -warning: cast `variadic_fn` with `as unsafe extern "C" fn(_, ...)` to use it as a pointer - --> $DIR/function-references.rs:91:22 +warning: cast `variadic` with `as unsafe extern "C" fn(_, ...)` to obtain a function pointer + --> $DIR/function-references.rs:90:22 | -LL | println!("{:p}", &variadic_fn); - | ^^^^^^^^^^^^ +LL | println!("{:p}", &variadic); + | ^^^^^^^^^ -warning: cast `var` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:93:22 +warning: cast `var` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:92:22 | LL | println!("{:p}", &std::env::var::); | ^^^^^^^^^^^^^^^^^^^^^^^^ -warning: cast `nop` with `as fn()` to use it as a pointer - --> $DIR/function-references.rs:96:32 +warning: cast `nop` with `as fn()` to obtain a function pointer + --> $DIR/function-references.rs:95:32 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:96:38 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:95:38 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ -warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:96:44 +warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:95:44 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:111:41 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:110:41 | LL | std::mem::transmute::<_, usize>(&foo); | ^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:113:50 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:112:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ -warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:113:50 +warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:112:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ -warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:123:15 +warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:122:15 | LL | print_ptr(&bar); | ^^^^ -warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:125:24 +warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:124:24 | LL | bound_by_ptr_trait(&bar); | ^^^^ -warning: cast `bar` with `as fn(_) -> _` to use it as a pointer - --> $DIR/function-references.rs:127:30 +warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer + --> $DIR/function-references.rs:126:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to use it as a pointer - --> $DIR/function-references.rs:127:30 +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:126:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ From d6fa7e15d6679a1c01a6b4c32400f571d04c6a6c Mon Sep 17 00:00:00 2001 From: Ayrton Date: Tue, 6 Oct 2020 17:55:46 -0400 Subject: [PATCH 6/8] Fixed compiler error in lint checker triggered by associated types When a function argument bound by `Pointer` is an associated type, we only perform substitutions using the parameters from the callsite but don't attempt to normalize since it may not succeed. A simplified version of the scenario that triggered this error was added as a test case. Also fixed `Pointer::fmt` which was being double-counted when called outside of macros and added a test case for this. --- .../src/transform/function_references.rs | 118 ++++++++++-------- src/test/ui/lint/function-references.rs | 21 ++++ src/test/ui/lint/function-references.stderr | 66 +++++----- 3 files changed, 122 insertions(+), 83 deletions(-) diff --git a/compiler/rustc_mir/src/transform/function_references.rs b/compiler/rustc_mir/src/transform/function_references.rs index 97688c3ea162f..6e94fad5d0d75 100644 --- a/compiler/rustc_mir/src/transform/function_references.rs +++ b/compiler/rustc_mir/src/transform/function_references.rs @@ -1,7 +1,11 @@ use rustc_hir::def_id::DefId; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; -use rustc_middle::ty::{self, subst::GenericArgKind, PredicateAtom, Ty, TyCtxt, TyS}; +use rustc_middle::ty::{ + self, + subst::{GenericArgKind, Subst}, + PredicateAtom, Ty, TyCtxt, TyS, +}; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; use rustc_span::{symbol::sym, Span}; use rustc_target::spec::abi::Abi; @@ -33,48 +37,50 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { fn_span: _, } = &terminator.kind { - let func_ty = func.ty(self.body, self.tcx); - if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() { - //check arguments for `std::mem::transmute` - if self.tcx.is_diagnostic_item(sym::transmute, def_id) { - let arg_ty = args[0].ty(self.body, self.tcx); - for generic_inner_ty in arg_ty.walk() { - if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { - if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(inner_ty) { - let ident = self.tcx.item_name(fn_id).to_ident_string(); - let source_info = *self.body.source_info(location); - let span = self.nth_arg_span(&args, 0); - self.emit_lint(ident, fn_id, source_info, span); + let source_info = *self.body.source_info(location); + //this handles all function calls outside macros + if !source_info.span.from_expansion() { + let func_ty = func.ty(self.body, self.tcx); + if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() { + //handle `std::mem::transmute` + if self.tcx.is_diagnostic_item(sym::transmute, def_id) { + let arg_ty = args[0].ty(self.body, self.tcx); + for generic_inner_ty in arg_ty.walk() { + if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { + if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(inner_ty) { + let ident = self.tcx.item_name(fn_id).to_ident_string(); + let span = self.nth_arg_span(&args, 0); + self.emit_lint(ident, fn_id, source_info, span); + } } } - } - } else { - //check arguments for any function with `std::fmt::Pointer` as a bound trait - let param_env = self.tcx.param_env(def_id); - let bounds = param_env.caller_bounds(); - for bound in bounds { - if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { - let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); - for (arg_num, arg_def) in arg_defs.iter().enumerate() { - for generic_inner_ty in arg_def.walk() { - if let GenericArgKind::Type(inner_ty) = - generic_inner_ty.unpack() - { - //if any type reachable from the argument types in the fn sig matches the type bound by `Pointer` - if TyS::same_type(inner_ty, bound_ty) { - //check if this type is a function reference in the function call - let norm_ty = - self.tcx.subst_and_normalize_erasing_regions( - substs_ref, param_env, &inner_ty, - ); - if let Some(fn_id) = - FunctionItemRefChecker::is_fn_ref(norm_ty) - { - let ident = - self.tcx.item_name(fn_id).to_ident_string(); - let source_info = *self.body.source_info(location); - let span = self.nth_arg_span(&args, arg_num); - self.emit_lint(ident, fn_id, source_info, span); + } else { + //handle any function call with `std::fmt::Pointer` as a bound trait + //this includes calls to `std::fmt::Pointer::fmt` outside of macros + let param_env = self.tcx.param_env(def_id); + let bounds = param_env.caller_bounds(); + for bound in bounds { + if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { + //get the argument types as they appear in the function signature + let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); + for (arg_num, arg_def) in arg_defs.iter().enumerate() { + //for all types reachable from the argument type in the fn sig + for generic_inner_ty in arg_def.walk() { + if let GenericArgKind::Type(inner_ty) = + generic_inner_ty.unpack() + { + //if the inner type matches the type bound by `Pointer` + if TyS::same_type(inner_ty, bound_ty) { + //do a substitution using the parameters from the callsite + let subst_ty = inner_ty.subst(self.tcx, substs_ref); + if let Some(fn_id) = + FunctionItemRefChecker::is_fn_ref(subst_ty) + { + let ident = + self.tcx.item_name(fn_id).to_ident_string(); + let span = self.nth_arg_span(&args, arg_num); + self.emit_lint(ident, fn_id, source_info, span); + } } } } @@ -87,19 +93,25 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { } self.super_terminator(terminator, location); } - //check for `std::fmt::Pointer::::fmt` where T is a function reference - //this is used in formatting macros, but doesn't rely on the specific expansion + //This handles `std::fmt::Pointer::fmt` when it's used in the formatting macros. + //It's handled as an operand instead of a Call terminator so it won't depend on + //whether the formatting macros call `fmt` directly, transmute it first or other + //internal fmt details. fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) { - let op_ty = operand.ty(self.body, self.tcx); - if let ty::FnDef(def_id, substs_ref) = *op_ty.kind() { - if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) { - let param_ty = substs_ref.type_at(0); - if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(param_ty) { - let source_info = *self.body.source_info(location); - let callsite_ctxt = source_info.span.source_callsite().ctxt(); - let span = source_info.span.with_ctxt(callsite_ctxt); - let ident = self.tcx.item_name(fn_id).to_ident_string(); - self.emit_lint(ident, fn_id, source_info, span); + let source_info = *self.body.source_info(location); + if source_info.span.from_expansion() { + let op_ty = operand.ty(self.body, self.tcx); + if let ty::FnDef(def_id, substs_ref) = *op_ty.kind() { + if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) { + let param_ty = substs_ref.type_at(0); + if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(param_ty) { + //the operand's ctxt wouldn't display the lint since it's inside a macro + //so we have to use the callsite's ctxt + let callsite_ctxt = source_info.span.source_callsite().ctxt(); + let span = source_info.span.with_ctxt(callsite_ctxt); + let ident = self.tcx.item_name(fn_id).to_ident_string(); + self.emit_lint(ident, fn_id, source_info, span); + } } } } diff --git a/src/test/ui/lint/function-references.rs b/src/test/ui/lint/function-references.rs index 9ec3871e48218..28c66a31322c4 100644 --- a/src/test/ui/lint/function-references.rs +++ b/src/test/ui/lint/function-references.rs @@ -2,6 +2,7 @@ #![feature(c_variadic)] #![warn(function_item_references)] use std::fmt::Pointer; +use std::fmt::Formatter; fn nop() { } fn foo() -> u32 { 42 } @@ -20,6 +21,25 @@ fn parameterized_call_fn u32>(f: &F, x: u32) { f(x); } fn print_ptr(f: F) { println!("{:p}", f); } fn bound_by_ptr_trait(_f: F) { } fn bound_by_ptr_trait_tuple(_t: (F, G)) { } +fn implicit_ptr_trait(f: &F) { println!("{:p}", f); } + +//case found in tinyvec that triggered a compiler error in an earlier version of the lint checker +trait HasItem { + type Item; + fn assoc_item(&self) -> Self::Item; +} +fn _format_assoc_item(data: T, f: &mut Formatter) -> std::fmt::Result + where T::Item: Pointer { + //when the arg type bound by `Pointer` is an associated type, we shouldn't attempt to normalize + Pointer::fmt(&data.assoc_item(), f) +} + +//simple test to make sure that calls to `Pointer::fmt` aren't double counted +fn _call_pointer_fmt(f: &mut Formatter) -> std::fmt::Result { + let zst_ref = &foo; + Pointer::fmt(&zst_ref, f) + //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer +} fn main() { //`let` bindings with function references shouldn't lint @@ -126,6 +146,7 @@ fn main() { bound_by_ptr_trait_tuple((&foo, &bar)); //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer //~^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + implicit_ptr_trait(&bar); // ignore //correct ways to pass function pointers as arguments bound by std::fmt::Pointer print_ptr(bar as fn(u32) -> u32); diff --git a/src/test/ui/lint/function-references.stderr b/src/test/ui/lint/function-references.stderr index 71940a1d4cf8a..5e399c163050f 100644 --- a/src/test/ui/lint/function-references.stderr +++ b/src/test/ui/lint/function-references.stderr @@ -1,8 +1,8 @@ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:57:22 + --> $DIR/function-references.rs:40:18 | -LL | println!("{:p}", &foo); - | ^^^^ +LL | Pointer::fmt(&zst_ref, f) + | ^^^^^^^^ | note: the lint level is defined here --> $DIR/function-references.rs:3:9 @@ -11,160 +11,166 @@ LL | #![warn(function_item_references)] | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:59:20 + --> $DIR/function-references.rs:77:22 + | +LL | println!("{:p}", &foo); + | ^^^^ + +warning: cast `foo` with `as fn() -> _` to obtain a function pointer + --> $DIR/function-references.rs:79:20 | LL | print!("{:p}", &foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:61:21 + --> $DIR/function-references.rs:81:21 | LL | format!("{:p}", &foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:64:22 + --> $DIR/function-references.rs:84:22 | LL | println!("{:p}", &foo as *const _); | ^^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:66:22 + --> $DIR/function-references.rs:86:22 | LL | println!("{:p}", zst_ref); | ^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:68:22 + --> $DIR/function-references.rs:88:22 | LL | println!("{:p}", cast_zst_ptr); | ^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:70:22 + --> $DIR/function-references.rs:90:22 | LL | println!("{:p}", coerced_zst_ptr); | ^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:73:22 + --> $DIR/function-references.rs:93:22 | LL | println!("{:p}", &fn_item); | ^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:75:22 + --> $DIR/function-references.rs:95:22 | LL | println!("{:p}", indirect_ref); | ^^^^^^^^^^^^ warning: cast `nop` with `as fn()` to obtain a function pointer - --> $DIR/function-references.rs:78:22 + --> $DIR/function-references.rs:98:22 | LL | println!("{:p}", &nop); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:80:22 + --> $DIR/function-references.rs:100:22 | LL | println!("{:p}", &bar); | ^^^^ warning: cast `baz` with `as fn(_, _) -> _` to obtain a function pointer - --> $DIR/function-references.rs:82:22 + --> $DIR/function-references.rs:102:22 | LL | println!("{:p}", &baz); | ^^^^ warning: cast `unsafe_fn` with `as unsafe fn()` to obtain a function pointer - --> $DIR/function-references.rs:84:22 + --> $DIR/function-references.rs:104:22 | LL | println!("{:p}", &unsafe_fn); | ^^^^^^^^^^ warning: cast `c_fn` with `as extern "C" fn()` to obtain a function pointer - --> $DIR/function-references.rs:86:22 + --> $DIR/function-references.rs:106:22 | LL | println!("{:p}", &c_fn); | ^^^^^ warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to obtain a function pointer - --> $DIR/function-references.rs:88:22 + --> $DIR/function-references.rs:108:22 | LL | println!("{:p}", &unsafe_c_fn); | ^^^^^^^^^^^^ warning: cast `variadic` with `as unsafe extern "C" fn(_, ...)` to obtain a function pointer - --> $DIR/function-references.rs:90:22 + --> $DIR/function-references.rs:110:22 | LL | println!("{:p}", &variadic); | ^^^^^^^^^ warning: cast `var` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:92:22 + --> $DIR/function-references.rs:112:22 | LL | println!("{:p}", &std::env::var::); | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: cast `nop` with `as fn()` to obtain a function pointer - --> $DIR/function-references.rs:95:32 + --> $DIR/function-references.rs:115:32 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:95:38 + --> $DIR/function-references.rs:115:38 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:95:44 + --> $DIR/function-references.rs:115:44 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:110:41 + --> $DIR/function-references.rs:130:41 | LL | std::mem::transmute::<_, usize>(&foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:112:50 + --> $DIR/function-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:112:50 + --> $DIR/function-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:122:15 + --> $DIR/function-references.rs:142:15 | LL | print_ptr(&bar); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:124:24 + --> $DIR/function-references.rs:144:24 | LL | bound_by_ptr_trait(&bar); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:126:30 + --> $DIR/function-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:126:30 + --> $DIR/function-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ -warning: 27 warnings emitted +warning: 28 warnings emitted From 935fc3642a61e1545e1b98bf4716acbb7bf12e91 Mon Sep 17 00:00:00 2001 From: Ayrton Date: Wed, 21 Oct 2020 17:19:21 -0400 Subject: [PATCH 7/8] Added documentation for `function_item_references` lint Added documentation for `function_item_references` lint to the rustc book and fixed comments in the lint checker itself. --- ...erences.rs => function_item_references.rs} | 92 ++++++++++--------- compiler/rustc_mir/src/transform/mod.rs | 4 +- compiler/rustc_session/src/lint/builtin.rs | 24 +++++ ...erences.rs => function-item-references.rs} | 0 ...stderr => function-item-references.stderr} | 58 ++++++------ 5 files changed, 105 insertions(+), 73 deletions(-) rename compiler/rustc_mir/src/transform/{function_references.rs => function_item_references.rs} (66%) rename src/test/ui/lint/{function-references.rs => function-item-references.rs} (100%) rename src/test/ui/lint/{function-references.stderr => function-item-references.stderr} (77%) diff --git a/compiler/rustc_mir/src/transform/function_references.rs b/compiler/rustc_mir/src/transform/function_item_references.rs similarity index 66% rename from compiler/rustc_mir/src/transform/function_references.rs rename to compiler/rustc_mir/src/transform/function_item_references.rs index 6e94fad5d0d75..3a30b41d6816f 100644 --- a/compiler/rustc_mir/src/transform/function_references.rs +++ b/compiler/rustc_mir/src/transform/function_item_references.rs @@ -3,7 +3,7 @@ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use rustc_middle::ty::{ self, - subst::{GenericArgKind, Subst}, + subst::{GenericArgKind, Subst, SubstsRef}, PredicateAtom, Ty, TyCtxt, TyS, }; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; @@ -27,6 +27,9 @@ struct FunctionItemRefChecker<'a, 'tcx> { } impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { + /// Emits a lint for function reference arguments bound by `fmt::Pointer` or passed to + /// `transmute`. This only handles arguments in calls outside macro expansions to avoid double + /// counting function references formatted as pointers by macros. fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { if let TerminatorKind::Call { func, @@ -38,11 +41,11 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { } = &terminator.kind { let source_info = *self.body.source_info(location); - //this handles all function calls outside macros + // Only handle function calls outside macros if !source_info.span.from_expansion() { let func_ty = func.ty(self.body, self.tcx); if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() { - //handle `std::mem::transmute` + // Handle calls to `transmute` if self.tcx.is_diagnostic_item(sym::transmute, def_id) { let arg_ty = args[0].ty(self.body, self.tcx); for generic_inner_ty in arg_ty.walk() { @@ -55,48 +58,16 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { } } } else { - //handle any function call with `std::fmt::Pointer` as a bound trait - //this includes calls to `std::fmt::Pointer::fmt` outside of macros - let param_env = self.tcx.param_env(def_id); - let bounds = param_env.caller_bounds(); - for bound in bounds { - if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { - //get the argument types as they appear in the function signature - let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); - for (arg_num, arg_def) in arg_defs.iter().enumerate() { - //for all types reachable from the argument type in the fn sig - for generic_inner_ty in arg_def.walk() { - if let GenericArgKind::Type(inner_ty) = - generic_inner_ty.unpack() - { - //if the inner type matches the type bound by `Pointer` - if TyS::same_type(inner_ty, bound_ty) { - //do a substitution using the parameters from the callsite - let subst_ty = inner_ty.subst(self.tcx, substs_ref); - if let Some(fn_id) = - FunctionItemRefChecker::is_fn_ref(subst_ty) - { - let ident = - self.tcx.item_name(fn_id).to_ident_string(); - let span = self.nth_arg_span(&args, arg_num); - self.emit_lint(ident, fn_id, source_info, span); - } - } - } - } - } - } - } + self.check_bound_args(def_id, substs_ref, &args, source_info); } } } } self.super_terminator(terminator, location); } - //This handles `std::fmt::Pointer::fmt` when it's used in the formatting macros. - //It's handled as an operand instead of a Call terminator so it won't depend on - //whether the formatting macros call `fmt` directly, transmute it first or other - //internal fmt details. + /// Emits a lint for function references formatted with `fmt::Pointer::fmt` by macros. These + /// cases are handled as operands instead of call terminators to avoid any dependence on + /// unstable, internal formatting details like whether `fmt` is called directly or not. fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) { let source_info = *self.body.source_info(location); if source_info.span.from_expansion() { @@ -105,8 +76,8 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) { let param_ty = substs_ref.type_at(0); if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(param_ty) { - //the operand's ctxt wouldn't display the lint since it's inside a macro - //so we have to use the callsite's ctxt + // The operand's ctxt wouldn't display the lint since it's inside a macro so + // we have to use the callsite's ctxt. let callsite_ctxt = source_info.span.source_callsite().ctxt(); let span = source_info.span.with_ctxt(callsite_ctxt); let ident = self.tcx.item_name(fn_id).to_ident_string(); @@ -120,7 +91,42 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { } impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { - //return the bound parameter type if the trait is `std::fmt::Pointer` + /// Emits a lint for function reference arguments bound by `fmt::Pointer` in calls to the + /// function defined by `def_id` with the substitutions `substs_ref`. + fn check_bound_args( + &self, + def_id: DefId, + substs_ref: SubstsRef<'tcx>, + args: &Vec>, + source_info: SourceInfo, + ) { + let param_env = self.tcx.param_env(def_id); + let bounds = param_env.caller_bounds(); + for bound in bounds { + if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { + // Get the argument types as they appear in the function signature. + let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); + for (arg_num, arg_def) in arg_defs.iter().enumerate() { + // For all types reachable from the argument type in the fn sig + for generic_inner_ty in arg_def.walk() { + if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { + // If the inner type matches the type bound by `Pointer` + if TyS::same_type(inner_ty, bound_ty) { + // Do a substitution using the parameters from the callsite + let subst_ty = inner_ty.subst(self.tcx, substs_ref); + if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(subst_ty) { + let ident = self.tcx.item_name(fn_id).to_ident_string(); + let span = self.nth_arg_span(args, arg_num); + self.emit_lint(ident, fn_id, source_info, span); + } + } + } + } + } + } + } + } + /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. fn is_pointer_trait(&self, bound: &PredicateAtom<'tcx>) -> Option> { if let ty::PredicateAtom::Trait(predicate, _) = bound { if self.tcx.is_diagnostic_item(sym::pointer_trait, predicate.def_id()) { @@ -132,6 +138,8 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { None } } + /// If a type is a reference or raw pointer to the anonymous type of a function definition, + /// returns that function's `DefId`. fn is_fn_ref(ty: Ty<'tcx>) -> Option { let referent_ty = match ty.kind() { ty::Ref(_, referent_ty, _) => Some(referent_ty), diff --git a/compiler/rustc_mir/src/transform/mod.rs b/compiler/rustc_mir/src/transform/mod.rs index e43a238c1bad1..89db6bb13cad3 100644 --- a/compiler/rustc_mir/src/transform/mod.rs +++ b/compiler/rustc_mir/src/transform/mod.rs @@ -27,7 +27,7 @@ pub mod dest_prop; pub mod dump_mir; pub mod early_otherwise_branch; pub mod elaborate_drops; -pub mod function_references; +pub mod function_item_references; pub mod generator; pub mod inline; pub mod instcombine; @@ -267,7 +267,7 @@ fn mir_const<'tcx>( // MIR-level lints. &check_packed_ref::CheckPackedRef, &check_const_item_mutation::CheckConstItemMutation, - &function_references::FunctionItemReferences, + &function_item_references::FunctionItemReferences, // What we need to do constant evaluation. &simplify::SimplifyCfg::new("initial"), &rustc_peek::SanityCheck, diff --git a/compiler/rustc_session/src/lint/builtin.rs b/compiler/rustc_session/src/lint/builtin.rs index 41abdacb54c86..806f79af277b0 100644 --- a/compiler/rustc_session/src/lint/builtin.rs +++ b/compiler/rustc_session/src/lint/builtin.rs @@ -2648,6 +2648,30 @@ declare_lint! { } declare_lint! { + /// The `function_item_references` lint detects function references that are + /// formatted with [`fmt::Pointer`] or transmuted. + /// + /// [`fmt::Pointer`]: https://doc.rust-lang.org/std/fmt/trait.Pointer.html + /// + /// ### Example + /// + /// ```rust + /// fn foo() { } + /// + /// fn main() { + /// println!("{:p}", &foo); + /// } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Taking a reference to a function may be mistaken as a way to obtain a + /// pointer to that function. This can give unexpected results when + /// formatting the reference as a pointer or transmuting it. This lint is + /// issued when function references are formatted as pointers, passed as + /// arguments bound by [`fmt::Pointer`] or transmuted. pub FUNCTION_ITEM_REFERENCES, Warn, "suggest casting functions to pointers when attempting to take references", diff --git a/src/test/ui/lint/function-references.rs b/src/test/ui/lint/function-item-references.rs similarity index 100% rename from src/test/ui/lint/function-references.rs rename to src/test/ui/lint/function-item-references.rs diff --git a/src/test/ui/lint/function-references.stderr b/src/test/ui/lint/function-item-references.stderr similarity index 77% rename from src/test/ui/lint/function-references.stderr rename to src/test/ui/lint/function-item-references.stderr index 5e399c163050f..a96b134ed580f 100644 --- a/src/test/ui/lint/function-references.stderr +++ b/src/test/ui/lint/function-item-references.stderr @@ -1,173 +1,173 @@ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:40:18 + --> $DIR/function-item-references.rs:40:18 | LL | Pointer::fmt(&zst_ref, f) | ^^^^^^^^ | note: the lint level is defined here - --> $DIR/function-references.rs:3:9 + --> $DIR/function-item-references.rs:3:9 | LL | #![warn(function_item_references)] | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:77:22 + --> $DIR/function-item-references.rs:77:22 | LL | println!("{:p}", &foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:79:20 + --> $DIR/function-item-references.rs:79:20 | LL | print!("{:p}", &foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:81:21 + --> $DIR/function-item-references.rs:81:21 | LL | format!("{:p}", &foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:84:22 + --> $DIR/function-item-references.rs:84:22 | LL | println!("{:p}", &foo as *const _); | ^^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:86:22 + --> $DIR/function-item-references.rs:86:22 | LL | println!("{:p}", zst_ref); | ^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:88:22 + --> $DIR/function-item-references.rs:88:22 | LL | println!("{:p}", cast_zst_ptr); | ^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:90:22 + --> $DIR/function-item-references.rs:90:22 | LL | println!("{:p}", coerced_zst_ptr); | ^^^^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:93:22 + --> $DIR/function-item-references.rs:93:22 | LL | println!("{:p}", &fn_item); | ^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:95:22 + --> $DIR/function-item-references.rs:95:22 | LL | println!("{:p}", indirect_ref); | ^^^^^^^^^^^^ warning: cast `nop` with `as fn()` to obtain a function pointer - --> $DIR/function-references.rs:98:22 + --> $DIR/function-item-references.rs:98:22 | LL | println!("{:p}", &nop); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:100:22 + --> $DIR/function-item-references.rs:100:22 | LL | println!("{:p}", &bar); | ^^^^ warning: cast `baz` with `as fn(_, _) -> _` to obtain a function pointer - --> $DIR/function-references.rs:102:22 + --> $DIR/function-item-references.rs:102:22 | LL | println!("{:p}", &baz); | ^^^^ warning: cast `unsafe_fn` with `as unsafe fn()` to obtain a function pointer - --> $DIR/function-references.rs:104:22 + --> $DIR/function-item-references.rs:104:22 | LL | println!("{:p}", &unsafe_fn); | ^^^^^^^^^^ warning: cast `c_fn` with `as extern "C" fn()` to obtain a function pointer - --> $DIR/function-references.rs:106:22 + --> $DIR/function-item-references.rs:106:22 | LL | println!("{:p}", &c_fn); | ^^^^^ warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to obtain a function pointer - --> $DIR/function-references.rs:108:22 + --> $DIR/function-item-references.rs:108:22 | LL | println!("{:p}", &unsafe_c_fn); | ^^^^^^^^^^^^ warning: cast `variadic` with `as unsafe extern "C" fn(_, ...)` to obtain a function pointer - --> $DIR/function-references.rs:110:22 + --> $DIR/function-item-references.rs:110:22 | LL | println!("{:p}", &variadic); | ^^^^^^^^^ warning: cast `var` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:112:22 + --> $DIR/function-item-references.rs:112:22 | LL | println!("{:p}", &std::env::var::); | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: cast `nop` with `as fn()` to obtain a function pointer - --> $DIR/function-references.rs:115:32 + --> $DIR/function-item-references.rs:115:32 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:115:38 + --> $DIR/function-item-references.rs:115:38 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:115:44 + --> $DIR/function-item-references.rs:115:44 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:130:41 + --> $DIR/function-item-references.rs:130:41 | LL | std::mem::transmute::<_, usize>(&foo); | ^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:132:50 + --> $DIR/function-item-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:132:50 + --> $DIR/function-item-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:142:15 + --> $DIR/function-item-references.rs:142:15 | LL | print_ptr(&bar); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:144:24 + --> $DIR/function-item-references.rs:144:24 | LL | bound_by_ptr_trait(&bar); | ^^^^ warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer - --> $DIR/function-references.rs:146:30 + --> $DIR/function-item-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ warning: cast `foo` with `as fn() -> _` to obtain a function pointer - --> $DIR/function-references.rs:146:30 + --> $DIR/function-item-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ From c791c64e8434b0477de667c1a0fdbe18c928274c Mon Sep 17 00:00:00 2001 From: Ayrton Date: Tue, 27 Oct 2020 09:00:19 -0400 Subject: [PATCH 8/8] Added suggestion to `function_item_references` lint and fixed warning message Also updated tests accordingly and tweaked some wording in the lint declaration. --- .../src/transform/function_item_references.rs | 27 +++-- compiler/rustc_session/src/lint/builtin.rs | 2 +- src/test/ui/lint/function-item-references.rs | 56 ++++----- .../ui/lint/function-item-references.stderr | 112 +++++++++--------- 4 files changed, 102 insertions(+), 95 deletions(-) diff --git a/compiler/rustc_mir/src/transform/function_item_references.rs b/compiler/rustc_mir/src/transform/function_item_references.rs index 3a30b41d6816f..61427422e4b59 100644 --- a/compiler/rustc_mir/src/transform/function_item_references.rs +++ b/compiler/rustc_mir/src/transform/function_item_references.rs @@ -1,3 +1,4 @@ +use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; @@ -183,16 +184,22 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; self.tcx.struct_span_lint_hir(FUNCTION_ITEM_REFERENCES, lint_root, span, |lint| { - lint.build(&format!( - "cast `{}` with `as {}{}fn({}{}){}` to obtain a function pointer", - ident, - unsafety, - abi, - vec!["_"; num_args].join(", "), - variadic, - ret, - )) - .emit(); + lint.build("taking a reference to a function item does not give a function pointer") + .span_suggestion( + span, + &format!("cast `{}` to obtain a function pointer", ident), + format!( + "{} as {}{}fn({}{}){}", + ident, + unsafety, + abi, + vec!["_"; num_args].join(", "), + variadic, + ret, + ), + Applicability::Unspecified, + ) + .emit(); }); } } diff --git a/compiler/rustc_session/src/lint/builtin.rs b/compiler/rustc_session/src/lint/builtin.rs index 806f79af277b0..b8826a548b8be 100644 --- a/compiler/rustc_session/src/lint/builtin.rs +++ b/compiler/rustc_session/src/lint/builtin.rs @@ -2674,7 +2674,7 @@ declare_lint! { /// arguments bound by [`fmt::Pointer`] or transmuted. pub FUNCTION_ITEM_REFERENCES, Warn, - "suggest casting functions to pointers when attempting to take references", + "suggest casting to a function pointer when attempting to take references to function items", } declare_lint! { diff --git a/src/test/ui/lint/function-item-references.rs b/src/test/ui/lint/function-item-references.rs index 28c66a31322c4..439b56967d072 100644 --- a/src/test/ui/lint/function-item-references.rs +++ b/src/test/ui/lint/function-item-references.rs @@ -38,7 +38,7 @@ fn _format_assoc_item(data: T, f: &mut Formatter) -> std::fmt::Resul fn _call_pointer_fmt(f: &mut Formatter) -> std::fmt::Result { let zst_ref = &foo; Pointer::fmt(&zst_ref, f) - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer } fn main() { @@ -75,47 +75,47 @@ fn main() { //potential ways to incorrectly try printing function pointers println!("{:p}", &foo); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer print!("{:p}", &foo); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer format!("{:p}", &foo); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &foo as *const _); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", zst_ref); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", cast_zst_ptr); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", coerced_zst_ptr); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &fn_item); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", indirect_ref); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &nop); - //~^ WARNING cast `nop` with `as fn()` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &baz); - //~^ WARNING cast `baz` with `as fn(_, _) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &unsafe_fn); - //~^ WARNING cast `unsafe_fn` with `as unsafe fn()` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &c_fn); - //~^ WARNING cast `c_fn` with `as extern "C" fn()` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &unsafe_c_fn); - //~^ WARNING cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &variadic); - //~^ WARNING cast `variadic` with `as unsafe extern "C" fn(_, ...)` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &std::env::var::); - //~^ WARNING cast `var` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p} {:p} {:p}", &nop, &foo, &bar); - //~^ WARNING cast `nop` with `as fn()` to obtain a function pointer - //~^^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer - //~^^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer + //~^^ WARNING taking a reference to a function item does not give a function pointer + //~^^^ WARNING taking a reference to a function item does not give a function pointer //using a function reference to call a function shouldn't lint (&bar)(1); @@ -128,10 +128,10 @@ fn main() { unsafe { //potential ways to incorrectly try transmuting function pointers std::mem::transmute::<_, usize>(&foo); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer - //~^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer + //~^^ WARNING taking a reference to a function item does not give a function pointer //the correct way to transmute function pointers std::mem::transmute::<_, usize>(foo as fn() -> u32); @@ -140,12 +140,12 @@ fn main() { //function references as arguments required to be bound by std::fmt::Pointer should lint print_ptr(&bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer bound_by_ptr_trait(&bar); - //~^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer bound_by_ptr_trait_tuple((&foo, &bar)); - //~^ WARNING cast `foo` with `as fn() -> _` to obtain a function pointer - //~^^ WARNING cast `bar` with `as fn(_) -> _` to obtain a function pointer + //~^ WARNING taking a reference to a function item does not give a function pointer + //~^^ WARNING taking a reference to a function item does not give a function pointer implicit_ptr_trait(&bar); // ignore //correct ways to pass function pointers as arguments bound by std::fmt::Pointer diff --git a/src/test/ui/lint/function-item-references.stderr b/src/test/ui/lint/function-item-references.stderr index a96b134ed580f..610dff04e6edf 100644 --- a/src/test/ui/lint/function-item-references.stderr +++ b/src/test/ui/lint/function-item-references.stderr @@ -1,8 +1,8 @@ -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:40:18 | LL | Pointer::fmt(&zst_ref, f) - | ^^^^^^^^ + | ^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` | note: the lint level is defined here --> $DIR/function-item-references.rs:3:9 @@ -10,167 +10,167 @@ note: the lint level is defined here LL | #![warn(function_item_references)] | ^^^^^^^^^^^^^^^^^^^^^^^^ -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:77:22 | LL | println!("{:p}", &foo); - | ^^^^ + | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:79:20 | LL | print!("{:p}", &foo); - | ^^^^ + | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:81:21 | LL | format!("{:p}", &foo); - | ^^^^ + | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:84:22 | LL | println!("{:p}", &foo as *const _); - | ^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:86:22 | LL | println!("{:p}", zst_ref); - | ^^^^^^^ + | ^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:88:22 | LL | println!("{:p}", cast_zst_ptr); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:90:22 | LL | println!("{:p}", coerced_zst_ptr); - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:93:22 | LL | println!("{:p}", &fn_item); - | ^^^^^^^^ + | ^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:95:22 | LL | println!("{:p}", indirect_ref); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `nop` with `as fn()` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:98:22 | LL | println!("{:p}", &nop); - | ^^^^ + | ^^^^ help: cast `nop` to obtain a function pointer: `nop as fn()` -warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:100:22 | LL | println!("{:p}", &bar); - | ^^^^ + | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` -warning: cast `baz` with `as fn(_, _) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:102:22 | LL | println!("{:p}", &baz); - | ^^^^ + | ^^^^ help: cast `baz` to obtain a function pointer: `baz as fn(_, _) -> _` -warning: cast `unsafe_fn` with `as unsafe fn()` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:104:22 | LL | println!("{:p}", &unsafe_fn); - | ^^^^^^^^^^ + | ^^^^^^^^^^ help: cast `unsafe_fn` to obtain a function pointer: `unsafe_fn as unsafe fn()` -warning: cast `c_fn` with `as extern "C" fn()` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:106:22 | LL | println!("{:p}", &c_fn); - | ^^^^^ + | ^^^^^ help: cast `c_fn` to obtain a function pointer: `c_fn as extern "C" fn()` -warning: cast `unsafe_c_fn` with `as unsafe extern "C" fn()` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:108:22 | LL | println!("{:p}", &unsafe_c_fn); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `unsafe_c_fn` to obtain a function pointer: `unsafe_c_fn as unsafe extern "C" fn()` -warning: cast `variadic` with `as unsafe extern "C" fn(_, ...)` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:110:22 | LL | println!("{:p}", &variadic); - | ^^^^^^^^^ + | ^^^^^^^^^ help: cast `variadic` to obtain a function pointer: `variadic as unsafe extern "C" fn(_, ...)` -warning: cast `var` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:112:22 | LL | println!("{:p}", &std::env::var::); - | ^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `var` to obtain a function pointer: `var as fn(_) -> _` -warning: cast `nop` with `as fn()` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:115:32 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); - | ^^^^ + | ^^^^ help: cast `nop` to obtain a function pointer: `nop as fn()` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:115:38 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); - | ^^^^ + | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:115:44 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); - | ^^^^ + | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:130:41 | LL | std::mem::transmute::<_, usize>(&foo); - | ^^^^ + | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` -warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:142:15 | LL | print_ptr(&bar); - | ^^^^ + | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` -warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:144:24 | LL | bound_by_ptr_trait(&bar); - | ^^^^ + | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` -warning: cast `bar` with `as fn(_) -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` -warning: cast `foo` with `as fn() -> _` to obtain a function pointer +warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); - | ^^^^^^^^^^^^ + | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: 28 warnings emitted