Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a Callable trait that is implemented for unsafe functions, too #107123

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions compiler/rustc_error_codes/src/error_codes/E0183.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ impl FnOnce<()> for MyClosure { // ok!
println!("{}", self.foo);
}
}

impl std::ops::Callable<()> for MyClosure {}
```

The arguments must be a tuple representing the argument list.
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ language_item_table! {
Fn, kw::Fn, fn_trait, Target::Trait, GenericRequirement::Exact(1);
FnMut, sym::fn_mut, fn_mut_trait, Target::Trait, GenericRequirement::Exact(1);
FnOnce, sym::fn_once, fn_once_trait, Target::Trait, GenericRequirement::Exact(1);
Callable, sym::callable, callable_trait, Target::Trait, GenericRequirement::Exact(1);

FnOnceOutput, sym::fn_once_output, fn_once_output, Target::AssocTy, GenericRequirement::None;

Expand Down
73 changes: 61 additions & 12 deletions compiler/rustc_hir_typeck/src/callee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ use super::method::MethodCallee;
use super::{Expectation, FnCtxt, TupleArgumentsFlag};

use crate::type_error_struct;
use hir::LangItem;
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed, StashKey};
use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, Namespace, Res};
use rustc_hir::def_id::DefId;
use rustc_hir_analysis::autoderef::Autoderef;
use rustc_infer::traits::ObligationCauseCode;
use rustc_infer::{
infer,
traits::{self, Obligation},
Expand All @@ -22,7 +24,6 @@ use rustc_middle::ty::adjustment::{
};
use rustc_middle::ty::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::{sym, Ident};
use rustc_span::Span;
use rustc_target::spec::abi;
Expand Down Expand Up @@ -66,7 +67,7 @@ pub fn check_legal_trait_for_method_call(
#[derive(Debug)]
enum CallStep<'tcx> {
Builtin(Ty<'tcx>),
DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
DeferredClosure(Ty<'tcx>, ty::FnSig<'tcx>),
/// E.g., enum variant constructors.
Overloaded(MethodCallee<'tcx>),
}
Expand Down Expand Up @@ -173,7 +174,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
closure_substs: substs,
},
);
return Some(CallStep::DeferredClosure(def_id, closure_sig));
return Some(CallStep::DeferredClosure(adjusted_ty, closure_sig));
}
}

Expand Down Expand Up @@ -375,7 +376,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
arg_exprs: &'tcx [hir::Expr<'tcx>],
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let (fn_sig, def_id) = match *callee_ty.kind() {
let fn_sig = match *callee_ty.kind() {
ty::FnDef(def_id, subst) => {
let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, subst);

Expand Down Expand Up @@ -403,9 +404,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.emit();
}
}
(fn_sig, Some(def_id))
fn_sig
}
ty::FnPtr(sig) => (sig, None),
ty::FnPtr(sig) => sig,
_ => {
for arg in arg_exprs {
self.check_expr(arg);
Expand Down Expand Up @@ -451,6 +452,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn_sig.output(),
fn_sig.inputs(),
);
// FIXME(callable_trait): make this work automatically with `check_callable`
self.check_argument_types(
call_expr.span,
call_expr,
Expand All @@ -459,7 +461,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
arg_exprs,
fn_sig.c_variadic,
TupleArgumentsFlag::DontTupleArguments,
def_id,
callee_ty,
);

self.check_callable(
call_expr.hir_id,
call_expr.span,
callee_ty,
fn_sig.inputs().iter().copied(),
);

if fn_sig.abi == abi::Abi::RustCall {
Expand All @@ -473,9 +482,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.require_type_is_sized(ty, sp, traits::RustCall);
} else {
self.tcx.sess.span_err(
sp,
"functions with the \"rust-call\" ABI must take a single non-self tuple argument",
);
sp,
"functions with the \"rust-call\" ABI must take a single non-self tuple argument",
);
}
}

Expand Down Expand Up @@ -705,12 +714,37 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.emit()
}

/// Enforces that things being called actually are callable
#[instrument(skip(self, arguments))]
pub(super) fn check_callable(
&self,
hir_id: hir::HirId,
span: Span,
callable_ty: Ty<'tcx>,
arguments: impl IntoIterator<Item = Ty<'tcx>>,
) {
if callable_ty.references_error() {
return;
}

let cause = self.cause(span, ObligationCauseCode::MiscObligation);

let arguments_tuple = self.tcx.mk_tup_from_iter(arguments.into_iter());
let pred = ty::Binder::dummy(ty::TraitRef::from_lang_item(
self.tcx,
LangItem::Callable,
span,
[callable_ty, arguments_tuple],
));
self.register_predicate(Obligation::new(self.tcx, cause, self.param_env, pred));
}

fn confirm_deferred_closure_call(
&self,
call_expr: &'tcx hir::Expr<'tcx>,
arg_exprs: &'tcx [hir::Expr<'tcx>],
expected: Expectation<'tcx>,
closure_def_id: LocalDefId,
closure_ty: Ty<'tcx>,
fn_sig: ty::FnSig<'tcx>,
) -> Ty<'tcx> {
// `fn_sig` is the *signature* of the closure being called. We
Expand All @@ -725,6 +759,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn_sig.inputs(),
);

// FIXME(callable_trait): make this work just with `check_callable`
self.check_argument_types(
call_expr.span,
call_expr,
Expand All @@ -733,7 +768,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
arg_exprs,
fn_sig.c_variadic,
TupleArgumentsFlag::TupleArguments,
Some(closure_def_id.to_def_id()),
closure_ty,
);

self.check_callable(
call_expr.hir_id,
call_expr.span,
closure_ty,
fn_sig.inputs()[0].tuple_fields(),
);

fn_sig.output()
Expand Down Expand Up @@ -793,6 +835,7 @@ impl<'a, 'tcx> DeferredCallResolution<'tcx> {

debug!("attempt_resolution: method_callee={:?}", method_callee);

// FIXME(callable_trait): this argument check is now unnecessary
for (method_arg_ty, self_arg_ty) in
iter::zip(method_sig.inputs().iter().skip(1), self.fn_sig.inputs())
{
Expand All @@ -804,6 +847,12 @@ impl<'a, 'tcx> DeferredCallResolution<'tcx> {
let mut adjustments = self.adjustments;
adjustments.extend(autoref);
fcx.apply_adjustments(self.callee_expr, adjustments);
fcx.check_callable(
self.callee_expr.hir_id,
self.callee_expr.span,
fcx.tcx.mk_fn_def(method_callee.def_id, method_callee.substs),
method_sig.inputs().iter().copied(),
);

fcx.write_method_call(self.call_expr.hir_id, method_callee);
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
result
}

#[instrument(level = "trace", skip(self, span), ret)]
pub(in super::super) fn normalize<T>(&self, span: Span, value: T) -> T
where
T: TypeFoldable<TyCtxt<'tcx>>,
Expand Down
41 changes: 27 additions & 14 deletions compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
tuple_arguments: TupleArgumentsFlag,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let has_error = match method {
Ok(method) => method.substs.references_error() || method.sig.references_error(),
Err(_) => true,
};
if has_error {
let method = method.ok().filter(|method| !method.references_error());
let Some(method) = method else {
let err_inputs = self.err_args(args_no_rcvr.len());

let err_inputs = match tuple_arguments {
DontTupleArguments => err_inputs,
TupleArguments => vec![self.tcx.mk_tup(&err_inputs)],
};

let err = self.tcx.ty_error_misc();
let callee_ty = method.map_or(err, |method| self.tcx.mk_fn_def(method.def_id, method.substs));

// FIXME(callable_trait): make this work automatically with `check_callable`
self.check_argument_types(
sp,
expr,
Expand All @@ -113,19 +114,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
args_no_rcvr,
false,
tuple_arguments,
method.ok().map(|method| method.def_id),
callee_ty,
);
return self.tcx.ty_error_misc();
}
self.check_callable(expr.hir_id, sp, callee_ty, std::iter::once(err).chain(err_inputs));
return err;
};

let method = method.unwrap();
// HACK(eddyb) ignore self in the definition (see above).
let expected_input_tys = self.expected_inputs_for_expected_output(
sp,
expected,
method.sig.output(),
&method.sig.inputs()[1..],
);
let callee_ty = self.tcx.mk_fn_def(method.def_id, method.substs);

// FIXME(callable_trait): make this work automatically with `check_callable`
self.check_argument_types(
sp,
expr,
Expand All @@ -134,14 +138,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
args_no_rcvr,
method.sig.c_variadic,
tuple_arguments,
Some(method.def_id),
callee_ty,
);

self.check_callable(expr.hir_id, sp, callee_ty, method.sig.inputs().iter().copied());

method.sig.output()
}

/// Generic function that factors out common logic from function calls,
/// method calls and overloaded operators.
#[instrument(level = "trace", skip(self, call_expr, provided_args))]
pub(in super::super) fn check_argument_types(
&self,
// Span enclosing the call site
Expand All @@ -158,8 +165,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
c_variadic: bool,
// Whether the arguments have been bundled in a tuple (ex: closures)
tuple_arguments: TupleArgumentsFlag,
// The DefId for the function being called, for better error messages
fn_def_id: Option<DefId>,
// The callee type (e.g. function item ZST, function pointer or closure).
oli-obk marked this conversation as resolved.
Show resolved Hide resolved
// Note that this may have surprising function definitions, like often just
// referring to `FnOnce::call_once`, but with an appropriate `Self` type.
callee_ty: Ty<'tcx>,
) {
let tcx = self.tcx;

Expand Down Expand Up @@ -234,7 +243,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let minimum_input_count = expected_input_tys.len();
let provided_arg_count = provided_args.len();

let is_const_eval_select = matches!(fn_def_id, Some(def_id) if
let is_const_eval_select = matches!(*callee_ty.kind(), ty::FnDef(def_id, _) if
self.tcx.def_kind(def_id) == hir::def::DefKind::Fn
&& self.tcx.is_intrinsic(def_id)
&& self.tcx.item_name(def_id) == sym::const_eval_select);
Expand Down Expand Up @@ -460,7 +469,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
provided_args,
c_variadic,
err_code,
fn_def_id,
match *callee_ty.kind() {
ty::Generator(did, ..) | ty::Closure(did, _) | ty::FnDef(did, _) => Some(did),
ty::FnPtr(..) | ty::Error(_) => None,
ref kind => span_bug!(call_span, "invalid call argument type: {kind:?}"),
},
call_span,
call_expr,
);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ fn report_unexpected_variant_res(
/// # fn f(x: (isize, isize)) {}
/// f((1, 2));
/// ```
#[derive(Copy, Clone, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum TupleArgumentsFlag {
DontTupleArguments,
TupleArguments,
Expand Down
17 changes: 12 additions & 5 deletions compiler/rustc_hir_typeck/src/method/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
ConfirmContext { fcx, span, self_expr, call_expr, skip_record_for_diagnostics: false }
}

#[instrument(level = "trace", skip(self), ret)]
fn confirm(
&mut self,
unadjusted_self_ty: Ty<'tcx>,
Expand All @@ -99,7 +100,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
let rcvr_substs = self.fresh_receiver_substs(self_ty, &pick);
let all_substs = self.instantiate_method_substs(&pick, segment, rcvr_substs);

debug!("rcvr_substs={rcvr_substs:?}, all_substs={all_substs:?}");
debug!(?rcvr_substs);
debug!(?all_substs);

// Create the final signature for the method, replacing late-bound regions.
let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_substs);
Expand All @@ -125,11 +127,9 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
// could alter our Self-type, except for normalizing the receiver from the
// signature (which is also done during probing).
let method_sig_rcvr = self.normalize(self.span, method_sig.inputs()[0]);
debug!(
"confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}",
self_ty, method_sig_rcvr, method_sig, method_predicates
);
debug!(?self_ty, ?method_sig_rcvr, ?pick);
self.unify_receivers(self_ty, method_sig_rcvr, &pick, all_substs);
let inputs = method_sig.inputs();

let (method_sig, method_predicates) =
self.normalize(self.span, (method_sig, method_predicates));
Expand All @@ -150,6 +150,13 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
);
}

self.check_callable(
self.call_expr.hir_id,
self.span,
self.tcx.mk_fn_def(pick.item.def_id, all_substs),
inputs.iter().copied(),
);

// Create the final `MethodCallee`.
let callee = MethodCallee {
def_id: pick.item.def_id,
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_hir_typeck/src/method/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Namespace};
use rustc_hir::def_id::DefId;
use rustc_infer::infer::{self, InferOk};
use rustc_macros::TypeVisitable;
use rustc_middle::query::Providers;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
Expand All @@ -33,7 +34,7 @@ pub fn provide(providers: &mut Providers) {
probe::provide(providers);
}

#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, TypeVisitable)]
pub struct MethodCallee<'tcx> {
/// Impl method ID, for inherent methods, or trait method ID, otherwise.
pub def_id: DefId,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/consts/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ impl TryFrom<ScalarInt> for char {

#[inline]
fn try_from(int: ScalarInt) -> Result<Self, Self::Error> {
let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else {
let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else {
return Err(CharTryFromScalarInt);
};
match char::from_u32(bits.try_into().unwrap()) {
Expand Down
Loading