|
| 1 | +// Part of the Crubit project, under the Apache License v2.0 with LLVM |
| 2 | +// Exceptions. See /LICENSE for license information. |
| 3 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 4 | + |
| 5 | +use crate::liberate_and_deanonymize_late_bound_regions; |
| 6 | +use arc_anyhow::{anyhow, bail, ensure, Result}; |
| 7 | +use database::BindingsGenerator; |
| 8 | +use rustc_infer::traits::{Obligation, ObligationCause}; |
| 9 | +use rustc_middle::ty::{self, Ty, TyCtxt}; |
| 10 | +use rustc_span::def_id::DefId; |
| 11 | +use rustc_span::symbol::sym; |
| 12 | +use rustc_trait_selection::infer::canonical::ir::TypingMode; |
| 13 | +use rustc_trait_selection::infer::TyCtxtInferExt; |
| 14 | +use rustc_trait_selection::traits::ObligationCtxt; |
| 15 | +use std::collections::{HashMap, HashSet}; |
| 16 | + |
| 17 | +/// Implementation of `BindingsGenerator::get_generic_args`. |
| 18 | +pub fn get_generic_args<'tcx>( |
| 19 | + db: &BindingsGenerator<'tcx>, |
| 20 | + fn_def_id: DefId, |
| 21 | +) -> Result<ty::GenericArgsRef<'tcx>> { |
| 22 | + let tcx = db.tcx(); |
| 23 | + let generics = tcx.generics_of(fn_def_id); |
| 24 | + let predicates = tcx.predicates_of(fn_def_id); |
| 25 | + |
| 26 | + // See the doc comment for `unused_generic_param` in |
| 27 | + // `test/functions/functions.rs` for an explanation why we currently don't |
| 28 | + // support unused generic params. |
| 29 | + let indices_of_actually_used_generic_params = { |
| 30 | + let mut finder = GenericParamsFinder::default(); |
| 31 | + let fn_sig = tcx.fn_sig(fn_def_id).instantiate_identity(); |
| 32 | + let fn_sig = liberate_and_deanonymize_late_bound_regions(tcx, fn_sig, fn_def_id); |
| 33 | + use rustc_type_ir::TypeVisitable; |
| 34 | + fn_sig.visit_with(&mut finder); |
| 35 | + finder.generic_param_indices |
| 36 | + }; |
| 37 | + |
| 38 | + let replacements: HashMap<usize, ty::GenericArg<'tcx>> = (0..generics.count()) |
| 39 | + .map(|idx| { |
| 40 | + let param_def = generics.param_at(idx, tcx); |
| 41 | + let replacement = match param_def.kind { |
| 42 | + ty::GenericParamDefKind::Const { .. } => { |
| 43 | + bail!("`const`-generic functions are not supported (b/259749023)"); |
| 44 | + } |
| 45 | + ty::GenericParamDefKind::Lifetime => tcx.mk_param_from_def(param_def), |
| 46 | + ty::GenericParamDefKind::Type { .. } => { |
| 47 | + ensure!( |
| 48 | + indices_of_actually_used_generic_params.contains(¶m_def.index), |
| 49 | + "No support for replacing an _unused_ generic type param: `{}`", |
| 50 | + param_def.name, |
| 51 | + ); |
| 52 | + get_replacement_for_generic_type_param(tcx, fn_def_id, predicates, param_def) |
| 53 | + .map(|ty| ty.into()) |
| 54 | + .ok_or_else(|| { |
| 55 | + anyhow!( |
| 56 | + "No valid non-generic replacement for generic type param `{}`", |
| 57 | + param_def.name, |
| 58 | + ) |
| 59 | + })? |
| 60 | + } |
| 61 | + }; |
| 62 | + Ok((idx, replacement)) |
| 63 | + }) |
| 64 | + .collect::<Result<Vec<_>>>()? |
| 65 | + .into_iter() |
| 66 | + .collect(); |
| 67 | + |
| 68 | + Ok(ty::GenericArgs::for_item(tcx, fn_def_id, |param_def, _old_generic_args| { |
| 69 | + *replacements |
| 70 | + .get(&(param_def.index as usize)) |
| 71 | + .expect("All errors should have been handled above") |
| 72 | + })) |
| 73 | +} |
| 74 | + |
| 75 | +/// Given a generic constraint of the form `T: Trait`, returns the type that can potentially |
| 76 | +/// replace `T` in the generated bindings. |
| 77 | +/// |
| 78 | +/// If the returned type needs to use a new anonymous lifetime, then it will be generated |
| 79 | +/// using the given `def_id` as its scope. |
| 80 | +fn get_replacement_for_trait_predicate<'tcx>( |
| 81 | + tcx: TyCtxt<'tcx>, |
| 82 | + trait_predicate: ty::TraitPredicate<'tcx>, |
| 83 | +) -> Option<Ty<'tcx>> { |
| 84 | + if trait_predicate.polarity != ty::PredicatePolarity::Positive { |
| 85 | + return None; |
| 86 | + } |
| 87 | + let trait_ref = trait_predicate.trait_ref; |
| 88 | + |
| 89 | + // `args[0]` is `Self` / `T`. And when working with `Into<U>`, `AsRef<U>`, etc. |
| 90 | + // we typically want the first and only other generic argument - `U`. |
| 91 | + let ty1 = trait_ref.args.get(1).and_then(|generic_arg| generic_arg.as_type())?; |
| 92 | + |
| 93 | + // `T: Into<U>` => `U` |
| 94 | + if tcx.is_diagnostic_item(sym::Into, trait_ref.def_id) { |
| 95 | + return Some(ty1); |
| 96 | + } |
| 97 | + |
| 98 | + // TODO(b/281542952): Implement other replacements as needed. |
| 99 | + None |
| 100 | +} |
| 101 | + |
| 102 | +/// Returns `true` if `new_ty` can be used as a replacement for `generic_param` |
| 103 | +/// in a generic item identified by `def_id` and constrained by the given `predicates`. |
| 104 | +fn is_valid_replacement_for_generic_type_param<'tcx>( |
| 105 | + tcx: TyCtxt<'tcx>, |
| 106 | + def_id: DefId, |
| 107 | + predicates: ty::GenericPredicates<'tcx>, |
| 108 | + generic_param: &ty::GenericParamDef, |
| 109 | + new_ty: Ty<'tcx>, |
| 110 | +) -> bool { |
| 111 | + let generic_args = ty::GenericArgs::for_item(tcx, def_id, |param_def, _old_generic_args| { |
| 112 | + if param_def.index == generic_param.index { |
| 113 | + new_ty.into() |
| 114 | + } else { |
| 115 | + tcx.mk_param_from_def(param_def) |
| 116 | + } |
| 117 | + }); |
| 118 | + |
| 119 | + let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis()); |
| 120 | + let ocx = ObligationCtxt::new(&infcx); |
| 121 | + let param_env = tcx.param_env(def_id); |
| 122 | + for (predicate, _span) in predicates.instantiate(tcx, generic_args) { |
| 123 | + let cause = ObligationCause::dummy(); |
| 124 | + let predicate = ocx.normalize(&cause, param_env, predicate); |
| 125 | + ocx.register_obligation(Obligation::new(tcx, cause, param_env, predicate)); |
| 126 | + } |
| 127 | + let errors = ocx.evaluate_obligations_error_on_ambiguity(); |
| 128 | + errors.is_empty() |
| 129 | +} |
| 130 | + |
| 131 | +/// Given a `generic_type_param` (e.g. `T` in `fn foo<T>(...)`) tries to find |
| 132 | +/// a non-generic type which can be used instead. For example, `T: Into<U>` may |
| 133 | +/// be potentially replaced with `U`, if `U` meets all the other `predicates` |
| 134 | +/// that may be constraining `T`. When multiple answers are possible, returns |
| 135 | +/// the first one. |
| 136 | +fn get_replacement_for_generic_type_param<'tcx>( |
| 137 | + tcx: TyCtxt<'tcx>, |
| 138 | + def_id: DefId, |
| 139 | + predicates: ty::GenericPredicates<'tcx>, |
| 140 | + generic_type_param: &ty::GenericParamDef, |
| 141 | +) -> Option<Ty<'tcx>> { |
| 142 | + // Look only at trait predicates involving this param (e.g. `T: SomeTrait`). |
| 143 | + let trait_predicates_for_this_generic_param = predicates |
| 144 | + .predicates |
| 145 | + .iter() |
| 146 | + .filter_map(|(clause, _)| match clause.kind().skip_binder() { |
| 147 | + ty::ClauseKind::Trait(trait_predicate) => Some(trait_predicate), |
| 148 | + _ => None, |
| 149 | + }) |
| 150 | + .filter(|trait_predicate| match trait_predicate.trait_ref.self_ty().kind() { |
| 151 | + ty::Param(p) => p.index == generic_type_param.index, |
| 152 | + _ => false, |
| 153 | + }); |
| 154 | + |
| 155 | + // Find the first replacement that fits all the constraints. |
| 156 | + trait_predicates_for_this_generic_param |
| 157 | + .filter_map(|trait_predicate| get_replacement_for_trait_predicate(tcx, trait_predicate)) |
| 158 | + .find(|new_ty| { |
| 159 | + is_valid_replacement_for_generic_type_param( |
| 160 | + tcx, |
| 161 | + def_id, |
| 162 | + predicates, |
| 163 | + generic_type_param, |
| 164 | + *new_ty, |
| 165 | + ) |
| 166 | + }) |
| 167 | +} |
| 168 | + |
| 169 | +#[derive(Default)] |
| 170 | +struct GenericParamsFinder { |
| 171 | + generic_param_indices: HashSet<u32>, |
| 172 | +} |
| 173 | + |
| 174 | +impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for GenericParamsFinder { |
| 175 | + fn visit_ty(&mut self, t: Ty<'tcx>) { |
| 176 | + if let ty::Param(p) = t.kind() { |
| 177 | + self.generic_param_indices.insert(p.index); |
| 178 | + } |
| 179 | + |
| 180 | + // Visit nested types (e.g., `&T` or `&[T]`) |
| 181 | + use ty::TypeSuperVisitable; |
| 182 | + t.super_visit_with(self) |
| 183 | + } |
| 184 | +} |
0 commit comments