mod confirm;
pub mod probe;
mod suggest;
pub use self::suggest::{SelfSource, TraitInfo};
pub use self::CandidateSource::*;
pub use self::MethodError::*;
use crate::check::FnCtxt;
use rustc_data_structures::sync::Lrc;
use rustc_errors::{Applicability, DiagnosticBuilder};
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_middle::ty::subst::Subst;
use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
use rustc_middle::ty::GenericParamDefKind;
use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TypeFoldable, WithConstness};
use rustc_span::symbol::Ident;
use rustc_span::Span;
use rustc_trait_selection::traits;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use self::probe::{IsSuggestion, ProbeScope};
pub fn provide(providers: &mut ty::query::Providers) {
suggest::provide(providers);
probe::provide(providers);
}
#[derive(Clone, Copy, Debug)]
pub struct MethodCallee<'tcx> {
pub def_id: DefId,
pub substs: SubstsRef<'tcx>,
pub sig: ty::FnSig<'tcx>,
}
pub enum MethodError<'tcx> {
NoMatch(NoMatchData<'tcx>),
Ambiguity(Vec<CandidateSource>),
PrivateMatch(DefKind, DefId, Vec<DefId>),
IllegalSizedBound(Vec<DefId>, bool, Span),
BadReturnType,
}
pub struct NoMatchData<'tcx> {
pub static_candidates: Vec<CandidateSource>,
pub unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
pub out_of_scope_traits: Vec<DefId>,
pub lev_candidate: Option<ty::AssocItem>,
pub mode: probe::Mode,
}
impl<'tcx> NoMatchData<'tcx> {
pub fn new(
static_candidates: Vec<CandidateSource>,
unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
out_of_scope_traits: Vec<DefId>,
lev_candidate: Option<ty::AssocItem>,
mode: probe::Mode,
) -> Self {
NoMatchData {
static_candidates,
unsatisfied_predicates,
out_of_scope_traits,
lev_candidate,
mode,
}
}
}
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum CandidateSource {
ImplSource(DefId),
TraitSource(DefId ),
}
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn method_exists(
&self,
method_name: Ident,
self_ty: Ty<'tcx>,
call_expr_id: hir::HirId,
allow_private: bool,
) -> bool {
let mode = probe::Mode::MethodCall;
match self.probe_for_name(
method_name.span,
mode,
method_name,
IsSuggestion(false),
self_ty,
call_expr_id,
ProbeScope::TraitsInScope,
) {
Ok(..) => true,
Err(NoMatch(..)) => false,
Err(Ambiguity(..)) => true,
Err(PrivateMatch(..)) => allow_private,
Err(IllegalSizedBound(..)) => true,
Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
}
}
crate fn suggest_method_call(
&self,
err: &mut DiagnosticBuilder<'a>,
msg: &str,
method_name: Ident,
self_ty: Ty<'tcx>,
call_expr: &hir::Expr<'_>,
) {
let params = self
.probe_for_name(
method_name.span,
probe::Mode::MethodCall,
method_name,
IsSuggestion(false),
self_ty,
call_expr.hir_id,
ProbeScope::TraitsInScope,
)
.map(|pick| {
let sig = self.tcx.fn_sig(pick.item.def_id);
sig.inputs().skip_binder().len().saturating_sub(1)
})
.unwrap_or(0);
let sugg_span = call_expr.span.shrink_to_hi();
let (suggestion, applicability) = (
format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
);
err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
}
pub fn lookup_method(
&self,
self_ty: Ty<'tcx>,
segment: &hir::PathSegment<'_>,
span: Span,
call_expr: &'tcx hir::Expr<'tcx>,
self_expr: &'tcx hir::Expr<'tcx>,
) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
debug!(
"lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
segment.ident, self_ty, call_expr, self_expr
);
let pick =
self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
for import_id in &pick.import_ids {
debug!("used_trait_import: {:?}", import_id);
Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
.unwrap()
.insert(*import_id);
}
self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span);
let result =
self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
if let Some(span) = result.illegal_sized_bound {
let mut needs_mut = false;
if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
let trait_type = self
.tcx
.mk_ref(region, ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() });
match self.lookup_probe(
span,
segment.ident,
trait_type,
call_expr,
ProbeScope::TraitsInScope,
) {
Ok(ref new_pick) if *new_pick != pick => {
needs_mut = true;
}
_ => {}
}
}
let candidates = match self.lookup_probe(
span,
segment.ident,
self_ty,
call_expr,
ProbeScope::AllTraits,
) {
Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
Err(Ambiguity(ref sources)) => sources
.iter()
.filter_map(|source| {
match *source {
ImplSource(def) => self.tcx.trait_id_of_impl(def),
TraitSource(_) => None,
}
})
.collect(),
_ => Vec::new(),
};
return Err(IllegalSizedBound(candidates, needs_mut, span));
}
Ok(result.callee)
}
pub fn lookup_probe(
&self,
span: Span,
method_name: Ident,
self_ty: Ty<'tcx>,
call_expr: &'tcx hir::Expr<'tcx>,
scope: ProbeScope,
) -> probe::PickResult<'tcx> {
let mode = probe::Mode::MethodCall;
let self_ty = self.resolve_vars_if_possible(self_ty);
self.probe_for_name(
span,
mode,
method_name,
IsSuggestion(false),
self_ty,
call_expr.hir_id,
scope,
)
}
pub fn lookup_method_in_trait(
&self,
span: Span,
m_name: Ident,
trait_def_id: DefId,
self_ty: Ty<'tcx>,
opt_input_types: Option<&[Ty<'tcx>]>,
) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
debug!(
"lookup_in_trait_adjusted(self_ty={:?}, m_name={}, trait_def_id={:?})",
self_ty, m_name, trait_def_id
);
let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
match param.kind {
GenericParamDefKind::Lifetime | GenericParamDefKind::Const => {}
GenericParamDefKind::Type { .. } => {
if param.index == 0 {
return self_ty.into();
} else if let Some(ref input_types) = opt_input_types {
return input_types[param.index as usize - 1].into();
}
}
}
self.var_for_def(span, param)
});
let trait_ref = ty::TraitRef::new(trait_def_id, substs);
let poly_trait_ref = trait_ref.to_poly_trait_ref();
let obligation = traits::Obligation::misc(
span,
self.body_id,
self.param_env,
poly_trait_ref.without_const().to_predicate(self.tcx),
);
if !self.predicate_may_hold(&obligation) {
debug!("--> Cannot match obligation");
return None;
}
let tcx = self.tcx;
let method_item = match self.associated_item(trait_def_id, m_name, Namespace::ValueNS) {
Some(method_item) => method_item,
None => {
tcx.sess.delay_span_bug(
span,
"operator trait does not have corresponding operator method",
);
return None;
}
};
let def_id = method_item.def_id;
let generics = tcx.generics_of(def_id);
assert_eq!(generics.params.len(), 0);
debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
let mut obligations = vec![];
let fn_sig = tcx.fn_sig(def_id);
let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig).0;
let fn_sig = fn_sig.subst(self.tcx, substs);
let InferOk { value, obligations: o } =
self.normalize_associated_types_in_as_infer_ok(span, fn_sig);
let fn_sig = {
obligations.extend(o);
value
};
let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
let InferOk { value, obligations: o } =
self.normalize_associated_types_in_as_infer_ok(span, bounds);
let bounds = {
obligations.extend(o);
value
};
assert!(!bounds.has_escaping_bound_vars());
let cause = traits::ObligationCause::misc(span, self.body_id);
obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, bounds));
let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig));
debug!(
"lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
method_ty, obligation
);
obligations.push(traits::Obligation::new(
cause,
self.param_env,
ty::PredicateAtom::WellFormed(method_ty.into()).to_predicate(tcx),
));
let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig };
debug!("callee = {:?}", callee);
Some(InferOk { obligations, value: callee })
}
pub fn resolve_ufcs(
&self,
span: Span,
method_name: Ident,
self_ty: Ty<'tcx>,
expr_id: hir::HirId,
) -> Result<(DefKind, DefId), MethodError<'tcx>> {
debug!(
"resolve_ufcs: method_name={:?} self_ty={:?} expr_id={:?}",
method_name, self_ty, expr_id,
);
let tcx = self.tcx;
if let ty::Adt(adt_def, _) = self_ty.kind() {
if adt_def.is_enum() {
let variant_def = adt_def
.variants
.iter()
.find(|vd| tcx.hygienic_eq(method_name, vd.ident, adt_def.did));
if let Some(variant_def) = variant_def {
let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
tcx.check_stability(ctor_def_id, Some(expr_id), span);
return Ok((
DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
ctor_def_id,
));
}
}
}
let pick = self.probe_for_name(
span,
probe::Mode::Path,
method_name,
IsSuggestion(false),
self_ty,
expr_id,
ProbeScope::TraitsInScope,
)?;
debug!("resolve_ufcs: pick={:?}", pick);
{
let mut typeck_results = self.typeck_results.borrow_mut();
let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
for import_id in pick.import_ids {
debug!("resolve_ufcs: used_trait_import: {:?}", import_id);
used_trait_imports.insert(import_id);
}
}
let def_kind = pick.item.kind.as_def_kind();
debug!("resolve_ufcs: def_kind={:?}, def_id={:?}", def_kind, pick.item.def_id);
tcx.check_stability(pick.item.def_id, Some(expr_id), span);
Ok((def_kind, pick.item.def_id))
}
pub fn associated_item(
&self,
def_id: DefId,
item_name: Ident,
ns: Namespace,
) -> Option<ty::AssocItem> {
self.tcx
.associated_items(def_id)
.find_by_name_and_namespace(self.tcx, item_name, ns, def_id)
.copied()
}
}