]>
Commit | Line | Data |
---|---|---|
0731742a XL |
1 | //! Conversion from AST representation of types to the `ty.rs` representation. |
2 | //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an | |
3 | //! instance of `AstConv`. | |
1a4d82fc | 4 | |
3dfed10e XL |
5 | mod errors; |
6 | mod generics; | |
dfeec247 | 7 | |
3dfed10e | 8 | use crate::bounds::Bounds; |
dfeec247 | 9 | use crate::collect::PlaceholderHirTyCollector; |
1b1a35ee XL |
10 | use crate::errors::{ |
11 | AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits, | |
12 | TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified, | |
13 | }; | |
9fa01778 | 14 | use crate::middle::resolve_lifetime as rl; |
dfeec247 | 15 | use crate::require_c_abi_if_c_variadic; |
dfeec247 | 16 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
3dfed10e | 17 | use rustc_errors::{struct_span_err, Applicability, ErrorReported, FatalError}; |
dfeec247 | 18 | use rustc_hir as hir; |
74b04a01 | 19 | use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; |
f9f354fc | 20 | use rustc_hir::def_id::{DefId, LocalDefId}; |
ba9703b0 | 21 | use rustc_hir::intravisit::{walk_generics, Visitor as _}; |
3dfed10e | 22 | use rustc_hir::lang_items::LangItem; |
ba9703b0 XL |
23 | use rustc_hir::{Constness, GenericArg, GenericArgs}; |
24 | use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef}; | |
3dfed10e XL |
25 | use rustc_middle::ty::GenericParamDefKind; |
26 | use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable}; | |
27 | use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS; | |
fc512014 | 28 | use rustc_span::lev_distance::find_best_match_for_name; |
3dfed10e XL |
29 | use rustc_span::symbol::{Ident, Symbol}; |
30 | use rustc_span::{Span, DUMMY_SP}; | |
83c7162d | 31 | use rustc_target::spec::abi; |
ba9703b0 XL |
32 | use rustc_trait_selection::traits; |
33 | use rustc_trait_selection::traits::astconv_object_safety_violations; | |
34 | use rustc_trait_selection::traits::error_reporting::report_object_safety_error; | |
35 | use rustc_trait_selection::traits::wf::object_region_bounds; | |
0731742a | 36 | |
ba9703b0 | 37 | use smallvec::SmallVec; |
29967ef6 | 38 | use std::array; |
0731742a | 39 | use std::collections::BTreeSet; |
0731742a XL |
40 | use std::slice; |
41 | ||
0731742a XL |
42 | #[derive(Debug)] |
43 | pub struct PathSeg(pub DefId, pub usize); | |
e9174d1e | 44 | |
dc9dc135 XL |
45 | pub trait AstConv<'tcx> { |
46 | fn tcx<'a>(&'a self) -> TyCtxt<'tcx>; | |
1a4d82fc | 47 | |
60c5eb7d XL |
48 | fn item_def_id(&self) -> Option<DefId>; |
49 | ||
dfeec247 XL |
50 | fn default_constness_for_trait_bounds(&self) -> Constness; |
51 | ||
6a06907d XL |
52 | /// Returns predicates in scope of the form `X: Foo<T>`, where `X` |
53 | /// is a type parameter `X` with the given id `def_id` and T | |
54 | /// matches `assoc_name`. This is a subset of the full set of | |
55 | /// predicates. | |
416331ca XL |
56 | /// |
57 | /// This is used for one specific purpose: resolving "short-hand" | |
58 | /// associated type references like `T::Item`. In principle, we | |
59 | /// would do that by first getting the full set of predicates in | |
60 | /// scope and then filtering down to find those that apply to `T`, | |
61 | /// but this can lead to cycle errors. The problem is that we have | |
62 | /// to do this resolution *in order to create the predicates in | |
63 | /// the first place*. Hence, we have this "special pass". | |
6a06907d XL |
64 | fn get_type_parameter_bounds( |
65 | &self, | |
66 | span: Span, | |
67 | def_id: DefId, | |
68 | assoc_name: Ident, | |
69 | ) -> ty::GenericPredicates<'tcx>; | |
c34b1796 | 70 | |
dc9dc135 | 71 | /// Returns the lifetime to use when a lifetime is omitted (and not elided). |
dfeec247 XL |
72 | fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) |
73 | -> Option<ty::Region<'tcx>>; | |
32a655c1 | 74 | |
dc9dc135 XL |
75 | /// Returns the type to use when a type is omitted. |
76 | fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>; | |
9e0c209e | 77 | |
dfeec247 XL |
78 | /// Returns `true` if `_` is allowed in type signatures in the current context. |
79 | fn allow_ty_infer(&self) -> bool; | |
80 | ||
dc9dc135 XL |
81 | /// Returns the const to use when a const is omitted. |
82 | fn ct_infer( | |
83 | &self, | |
84 | ty: Ty<'tcx>, | |
85 | param: Option<&ty::GenericParamDef>, | |
86 | span: Span, | |
87 | ) -> &'tcx Const<'tcx>; | |
1a4d82fc JJ |
88 | |
89 | /// Projecting an associated type from a (potentially) | |
90 | /// higher-ranked trait reference is more complicated, because of | |
91 | /// the possibility of late-bound regions appearing in the | |
92 | /// associated type binding. This is not legal in function | |
93 | /// signatures for that reason. In a function body, we can always | |
94 | /// handle it because we can use inference variables to remove the | |
95 | /// late-bound regions. | |
dfeec247 XL |
96 | fn projected_ty_from_poly_trait_ref( |
97 | &self, | |
98 | span: Span, | |
99 | item_def_id: DefId, | |
100 | item_segment: &hir::PathSegment<'_>, | |
101 | poly_trait_ref: ty::PolyTraitRef<'tcx>, | |
102 | ) -> Ty<'tcx>; | |
1a4d82fc | 103 | |
8bb4bdeb XL |
104 | /// Normalize an associated type coming from the user. |
105 | fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>; | |
a7813a04 XL |
106 | |
107 | /// Invoked when we encounter an error from some prior pass | |
0731742a | 108 | /// (e.g., resolve) that is translated into a ty-error. This is |
a7813a04 XL |
109 | /// used to help suppress derived errors typeck might otherwise |
110 | /// report. | |
111 | fn set_tainted_by_errors(&self); | |
ea8adc8c XL |
112 | |
113 | fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span); | |
a7813a04 XL |
114 | } |
115 | ||
dc9dc135 XL |
116 | pub enum SizedByDefault { |
117 | Yes, | |
118 | No, | |
119 | } | |
120 | ||
5869c6ff | 121 | #[derive(Debug)] |
dc9dc135 | 122 | struct ConvertedBinding<'a, 'tcx> { |
17df50a5 | 123 | hir_id: hir::HirId, |
f9f354fc | 124 | item_name: Ident, |
dc9dc135 | 125 | kind: ConvertedBindingKind<'a, 'tcx>, |
5869c6ff | 126 | gen_args: &'a GenericArgs<'a>, |
a7813a04 | 127 | span: Span, |
1a4d82fc JJ |
128 | } |
129 | ||
5869c6ff | 130 | #[derive(Debug)] |
dc9dc135 XL |
131 | enum ConvertedBindingKind<'a, 'tcx> { |
132 | Equality(Ty<'tcx>), | |
dfeec247 | 133 | Constraint(&'a [hir::GenericBound<'a>]), |
dc9dc135 XL |
134 | } |
135 | ||
f9f354fc XL |
136 | /// New-typed boolean indicating whether explicit late-bound lifetimes |
137 | /// are present in a set of generic arguments. | |
138 | /// | |
139 | /// For example if we have some method `fn f<'a>(&'a self)` implemented | |
140 | /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a` | |
141 | /// is late-bound so should not be provided explicitly. Thus, if `f` is | |
142 | /// instantiated with some generic arguments providing `'a` explicitly, | |
143 | /// we taint those arguments with `ExplicitLateBound::Yes` so that we | |
144 | /// can provide an appropriate diagnostic later. | |
145 | #[derive(Copy, Clone, PartialEq)] | |
146 | pub enum ExplicitLateBound { | |
147 | Yes, | |
148 | No, | |
149 | } | |
150 | ||
5869c6ff XL |
151 | #[derive(Copy, Clone, PartialEq)] |
152 | pub enum IsMethodCall { | |
153 | Yes, | |
154 | No, | |
155 | } | |
156 | ||
3dfed10e XL |
157 | /// Denotes the "position" of a generic argument, indicating if it is a generic type, |
158 | /// generic function or generic method call. | |
f9f354fc | 159 | #[derive(Copy, Clone, PartialEq)] |
3dfed10e | 160 | pub(crate) enum GenericArgPosition { |
b7449926 | 161 | Type, |
0731742a | 162 | Value, // e.g., functions |
b7449926 | 163 | MethodCall, |
94b46f34 XL |
164 | } |
165 | ||
74b04a01 XL |
166 | /// A marker denoting that the generic arguments that were |
167 | /// provided did not match the respective generic parameters. | |
f9f354fc | 168 | #[derive(Clone, Default)] |
74b04a01 XL |
169 | pub struct GenericArgCountMismatch { |
170 | /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`). | |
171 | pub reported: Option<ErrorReported>, | |
172 | /// A list of spans of arguments provided that were not valid. | |
173 | pub invalid_args: Vec<Span>, | |
174 | } | |
175 | ||
f9f354fc XL |
176 | /// Decorates the result of a generic argument count mismatch |
177 | /// check with whether explicit late bounds were provided. | |
178 | #[derive(Clone)] | |
179 | pub struct GenericArgCountResult { | |
180 | pub explicit_late_bound: ExplicitLateBound, | |
181 | pub correct: Result<(), GenericArgCountMismatch>, | |
182 | } | |
183 | ||
fc512014 XL |
184 | pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> { |
185 | fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool); | |
186 | ||
187 | fn provided_kind( | |
188 | &mut self, | |
189 | param: &ty::GenericParamDef, | |
190 | arg: &GenericArg<'_>, | |
191 | ) -> subst::GenericArg<'tcx>; | |
192 | ||
193 | fn inferred_kind( | |
194 | &mut self, | |
195 | substs: Option<&[subst::GenericArg<'tcx>]>, | |
196 | param: &ty::GenericParamDef, | |
197 | infer_args: bool, | |
198 | ) -> subst::GenericArg<'tcx>; | |
199 | } | |
200 | ||
dc9dc135 | 201 | impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { |
cdc7bbd5 | 202 | #[tracing::instrument(level = "debug", skip(self))] |
dfeec247 XL |
203 | pub fn ast_region_to_region( |
204 | &self, | |
32a655c1 | 205 | lifetime: &hir::Lifetime, |
dfeec247 XL |
206 | def: Option<&ty::GenericParamDef>, |
207 | ) -> ty::Region<'tcx> { | |
32a655c1 | 208 | let tcx = self.tcx(); |
3dfed10e | 209 | let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id)); |
ea8adc8c | 210 | |
9fa01778 | 211 | let r = match tcx.named_region(lifetime.hir_id) { |
dfeec247 | 212 | Some(rl::Region::Static) => tcx.lifetimes.re_static, |
32a655c1 | 213 | |
cdc7bbd5 XL |
214 | Some(rl::Region::LateBound(debruijn, index, def_id, _)) => { |
215 | let name = lifetime_name(def_id.expect_local()); | |
216 | let br = ty::BoundRegion { | |
217 | var: ty::BoundVar::from_u32(index), | |
218 | kind: ty::BrNamed(def_id, name), | |
219 | }; | |
fc512014 | 220 | tcx.mk_region(ty::ReLateBound(debruijn, br)) |
32a655c1 SL |
221 | } |
222 | ||
cdc7bbd5 XL |
223 | Some(rl::Region::LateBoundAnon(debruijn, index, anon_index)) => { |
224 | let br = ty::BoundRegion { | |
225 | var: ty::BoundVar::from_u32(index), | |
226 | kind: ty::BrAnon(anon_index), | |
227 | }; | |
fc512014 | 228 | tcx.mk_region(ty::ReLateBound(debruijn, br)) |
32a655c1 SL |
229 | } |
230 | ||
ff7c6d11 | 231 | Some(rl::Region::EarlyBound(index, id, _)) => { |
f9f354fc | 232 | let name = lifetime_name(id.expect_local()); |
dfeec247 | 233 | tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name })) |
32a655c1 SL |
234 | } |
235 | ||
ea8adc8c | 236 | Some(rl::Region::Free(scope, id)) => { |
f9f354fc | 237 | let name = lifetime_name(id.expect_local()); |
32a655c1 | 238 | tcx.mk_region(ty::ReFree(ty::FreeRegion { |
7cac9316 | 239 | scope, |
dfeec247 | 240 | bound_region: ty::BrNamed(id, name), |
32a655c1 | 241 | })) |
5bcae85e | 242 | |
0bf4aa26 | 243 | // (*) -- not late-bound, won't change |
32a655c1 | 244 | } |
5bcae85e | 245 | |
32a655c1 | 246 | None => { |
dfeec247 | 247 | self.re_infer(def, lifetime.span).unwrap_or_else(|| { |
cdc7bbd5 XL |
248 | debug!(?lifetime, "unelided lifetime in signature"); |
249 | ||
dfeec247 XL |
250 | // This indicates an illegal lifetime |
251 | // elision. `resolve_lifetime` should have | |
252 | // reported an error in this case -- but if | |
253 | // not, let's error out. | |
254 | tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature"); | |
255 | ||
256 | // Supply some dummy value. We don't have an | |
257 | // `re_error`, annoyingly, so use `'static`. | |
258 | tcx.lifetimes.re_static | |
259 | }) | |
32a655c1 | 260 | } |
a7813a04 | 261 | }; |
1a4d82fc | 262 | |
dfeec247 | 263 | debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r); |
1a4d82fc | 264 | |
a7813a04 XL |
265 | r |
266 | } | |
1a4d82fc | 267 | |
a7813a04 XL |
268 | /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`, |
269 | /// returns an appropriate set of substitutions for this particular reference to `I`. | |
dfeec247 XL |
270 | pub fn ast_path_substs_for_ty( |
271 | &self, | |
a7813a04 | 272 | span: Span, |
9e0c209e | 273 | def_id: DefId, |
dfeec247 XL |
274 | item_segment: &hir::PathSegment<'_>, |
275 | ) -> SubstsRef<'tcx> { | |
cdc7bbd5 | 276 | let (substs, _) = self.create_substs_for_ast_path( |
dc9dc135 XL |
277 | span, |
278 | def_id, | |
dfeec247 | 279 | &[], |
5869c6ff XL |
280 | item_segment, |
281 | item_segment.args(), | |
dc9dc135 XL |
282 | item_segment.infer_args, |
283 | None, | |
284 | ); | |
cdc7bbd5 | 285 | let assoc_bindings = self.create_assoc_bindings_for_generic_args(item_segment.args()); |
1a4d82fc | 286 | |
f9f354fc XL |
287 | if let Some(b) = assoc_bindings.first() { |
288 | Self::prohibit_assoc_ty_binding(self.tcx(), b.span); | |
289 | } | |
1a4d82fc | 290 | |
9e0c209e | 291 | substs |
a7813a04 | 292 | } |
c34b1796 | 293 | |
48663c56 | 294 | /// Given the type/lifetime/const arguments provided to some path (along with |
dc9dc135 | 295 | /// an implicit `Self`, if this is a trait reference), returns the complete |
9e0c209e | 296 | /// set of substitutions. This may involve applying defaulted type parameters. |
74b04a01 | 297 | /// Also returns back constraints on associated types. |
dc9dc135 XL |
298 | /// |
299 | /// Example: | |
300 | /// | |
301 | /// ``` | |
302 | /// T: std::ops::Index<usize, Output = u32> | |
303 | /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4 | |
304 | /// ``` | |
305 | /// | |
306 | /// 1. The `self_ty` here would refer to the type `T`. | |
307 | /// 2. The path in question is the path to the trait `std::ops::Index`, | |
308 | /// which will have been resolved to a `def_id` | |
309 | /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type | |
310 | /// parameters are returned in the `SubstsRef`, the associated type bindings like | |
311 | /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result. | |
9e0c209e SL |
312 | /// |
313 | /// Note that the type listing given here is *exactly* what the user provided. | |
dfeec247 XL |
314 | /// |
315 | /// For (generic) associated types | |
316 | /// | |
317 | /// ``` | |
318 | /// <Vec<u8> as Iterable<u8>>::Iter::<'a> | |
319 | /// ``` | |
320 | /// | |
321 | /// We have the parent substs are the substs for the parent trait: | |
322 | /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated | |
323 | /// type itself: `['a]`. The returned `SubstsRef` concatenates these two | |
324 | /// lists: `[Vec<u8>, u8, 'a]`. | |
cdc7bbd5 | 325 | #[tracing::instrument(level = "debug", skip(self, span))] |
dfeec247 XL |
326 | fn create_substs_for_ast_path<'a>( |
327 | &self, | |
a7813a04 | 328 | span: Span, |
9e0c209e | 329 | def_id: DefId, |
dfeec247 | 330 | parent_substs: &[subst::GenericArg<'tcx>], |
5869c6ff | 331 | seg: &hir::PathSegment<'_>, |
dfeec247 | 332 | generic_args: &'a hir::GenericArgs<'_>, |
dc9dc135 | 333 | infer_args: bool, |
dfeec247 | 334 | self_ty: Option<Ty<'tcx>>, |
cdc7bbd5 | 335 | ) -> (SubstsRef<'tcx>, GenericArgCountResult) { |
a7813a04 XL |
336 | // If the type is parameterized by this region, then replace this |
337 | // region with the current anon region binding (in other words, | |
338 | // whatever & would get replaced with). | |
94b46f34 | 339 | |
b7449926 | 340 | let tcx = self.tcx(); |
5869c6ff XL |
341 | let generics = tcx.generics_of(def_id); |
342 | debug!("generics: {:?}", generics); | |
85aaf69f | 343 | |
5869c6ff XL |
344 | if generics.has_self { |
345 | if generics.parent.is_some() { | |
dfeec247 XL |
346 | // The parent is a trait so it should have at least one subst |
347 | // for the `Self` type. | |
348 | assert!(!parent_substs.is_empty()) | |
349 | } else { | |
350 | // This item (presumably a trait) needs a self-type. | |
351 | assert!(self_ty.is_some()); | |
352 | } | |
353 | } else { | |
354 | assert!(self_ty.is_none() && parent_substs.is_empty()); | |
355 | } | |
a7813a04 | 356 | |
f9f354fc | 357 | let arg_count = Self::check_generic_arg_count( |
0731742a | 358 | tcx, |
b7449926 | 359 | span, |
5869c6ff XL |
360 | def_id, |
361 | seg, | |
362 | &generics, | |
b7449926 XL |
363 | &generic_args, |
364 | GenericArgPosition::Type, | |
dfeec247 | 365 | self_ty.is_some(), |
dc9dc135 | 366 | infer_args, |
b7449926 | 367 | ); |
1a4d82fc | 368 | |
fc512014 XL |
369 | // Skip processing if type has no generic parameters. |
370 | // Traits always have `Self` as a generic parameter, which means they will not return early | |
371 | // here and so associated type bindings will be handled regardless of whether there are any | |
372 | // non-`Self` generic parameters. | |
5869c6ff | 373 | if generics.params.len() == 0 { |
cdc7bbd5 | 374 | return (tcx.intern_substs(&[]), arg_count); |
fc512014 XL |
375 | } |
376 | ||
dfeec247 | 377 | let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self); |
fc512014 XL |
378 | |
379 | struct SubstsForAstPathCtxt<'a, 'tcx> { | |
380 | astconv: &'a (dyn AstConv<'tcx> + 'a), | |
381 | def_id: DefId, | |
382 | generic_args: &'a GenericArgs<'a>, | |
383 | span: Span, | |
384 | missing_type_params: Vec<String>, | |
385 | inferred_params: Vec<Span>, | |
386 | infer_args: bool, | |
387 | is_object: bool, | |
388 | } | |
389 | ||
390 | impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> { | |
391 | fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool { | |
392 | let tcx = self.astconv.tcx(); | |
393 | if let GenericParamDefKind::Type { has_default, .. } = param.kind { | |
394 | if self.is_object && has_default { | |
395 | let default_ty = tcx.at(self.span).type_of(param.def_id); | |
396 | let self_param = tcx.types.self_param; | |
397 | if default_ty.walk().any(|arg| arg == self_param.into()) { | |
398 | // There is no suitable inference default for a type parameter | |
399 | // that references self, in an object type. | |
400 | return true; | |
401 | } | |
94b46f34 | 402 | } |
9e0c209e | 403 | } |
9e0c209e | 404 | |
fc512014 XL |
405 | false |
406 | } | |
407 | } | |
9e0c209e | 408 | |
fc512014 XL |
409 | impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> { |
410 | fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) { | |
411 | if did == self.def_id { | |
412 | (Some(self.generic_args), self.infer_args) | |
74b04a01 XL |
413 | } else { |
414 | // The last component of this tuple is unimportant. | |
415 | (None, false) | |
416 | } | |
fc512014 XL |
417 | } |
418 | ||
419 | fn provided_kind( | |
420 | &mut self, | |
421 | param: &ty::GenericParamDef, | |
422 | arg: &GenericArg<'_>, | |
423 | ) -> subst::GenericArg<'tcx> { | |
424 | let tcx = self.astconv.tcx(); | |
425 | match (¶m.kind, arg) { | |
426 | (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { | |
427 | self.astconv.ast_region_to_region(<, Some(param)).into() | |
428 | } | |
429 | (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => { | |
430 | if has_default { | |
431 | tcx.check_optional_stability( | |
432 | param.def_id, | |
433 | Some(arg.id()), | |
434 | arg.span(), | |
17df50a5 | 435 | None, |
fc512014 XL |
436 | |_, _| { |
437 | // Default generic parameters may not be marked | |
438 | // with stability attributes, i.e. when the | |
439 | // default parameter was defined at the same time | |
440 | // as the rest of the type. As such, we ignore missing | |
441 | // stability attributes. | |
442 | }, | |
443 | ) | |
444 | } | |
445 | if let (hir::TyKind::Infer, false) = | |
446 | (&ty.kind, self.astconv.allow_ty_infer()) | |
447 | { | |
448 | self.inferred_params.push(ty.span); | |
449 | tcx.ty_error().into() | |
450 | } else { | |
451 | self.astconv.ast_ty_to_ty(&ty).into() | |
452 | } | |
453 | } | |
cdc7bbd5 | 454 | (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => { |
fc512014 XL |
455 | ty::Const::from_opt_const_arg_anon_const( |
456 | tcx, | |
457 | ty::WithOptConstParam { | |
458 | did: tcx.hir().local_def_id(ct.value.hir_id), | |
459 | const_param_did: Some(param.def_id), | |
1b1a35ee XL |
460 | }, |
461 | ) | |
fc512014 | 462 | .into() |
1b1a35ee | 463 | } |
fc512014 | 464 | _ => unreachable!(), |
dfeec247 | 465 | } |
fc512014 XL |
466 | } |
467 | ||
468 | fn inferred_kind( | |
469 | &mut self, | |
470 | substs: Option<&[subst::GenericArg<'tcx>]>, | |
471 | param: &ty::GenericParamDef, | |
472 | infer_args: bool, | |
473 | ) -> subst::GenericArg<'tcx> { | |
474 | let tcx = self.astconv.tcx(); | |
b7449926 | 475 | match param.kind { |
48663c56 | 476 | GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(), |
b7449926 | 477 | GenericParamDefKind::Type { has_default, .. } => { |
dc9dc135 | 478 | if !infer_args && has_default { |
b7449926 XL |
479 | // No type parameter provided, but a default exists. |
480 | ||
481 | // If we are converting an object type, then the | |
482 | // `Self` parameter is unknown. However, some of the | |
483 | // other type parameters may reference `Self` in their | |
484 | // defaults. This will lead to an ICE if we are not | |
485 | // careful! | |
fc512014 XL |
486 | if self.default_needs_object_self(param) { |
487 | self.missing_type_params.push(param.name.to_string()); | |
f035d41b | 488 | tcx.ty_error().into() |
b7449926 XL |
489 | } else { |
490 | // This is a default type parameter. | |
fc512014 XL |
491 | self.astconv |
492 | .normalize_ty( | |
493 | self.span, | |
494 | tcx.at(self.span).type_of(param.def_id).subst_spanned( | |
495 | tcx, | |
496 | substs.unwrap(), | |
497 | Some(self.span), | |
498 | ), | |
499 | ) | |
500 | .into() | |
b7449926 | 501 | } |
dc9dc135 | 502 | } else if infer_args { |
b7449926 | 503 | // No type parameters were provided, we can infer all. |
fc512014 XL |
504 | let param = if !self.default_needs_object_self(param) { |
505 | Some(param) | |
506 | } else { | |
507 | None | |
508 | }; | |
509 | self.astconv.ty_infer(param, self.span).into() | |
94b46f34 | 510 | } else { |
b7449926 | 511 | // We've already errored above about the mismatch. |
f035d41b | 512 | tcx.ty_error().into() |
94b46f34 | 513 | } |
94b46f34 | 514 | } |
cdc7bbd5 | 515 | GenericParamDefKind::Const { has_default } => { |
fc512014 | 516 | let ty = tcx.at(self.span).type_of(param.def_id); |
cdc7bbd5 XL |
517 | if !infer_args && has_default { |
518 | tcx.const_param_default(param.def_id) | |
519 | .subst_spanned(tcx, substs.unwrap(), Some(self.span)) | |
520 | .into() | |
dc9dc135 | 521 | } else { |
cdc7bbd5 XL |
522 | if infer_args { |
523 | self.astconv.ct_infer(ty, Some(param), self.span).into() | |
524 | } else { | |
525 | // We've already errored above about the mismatch. | |
526 | tcx.const_error(ty).into() | |
527 | } | |
dc9dc135 | 528 | } |
532ac7d7 | 529 | } |
a7813a04 | 530 | } |
fc512014 XL |
531 | } |
532 | } | |
533 | ||
534 | let mut substs_ctx = SubstsForAstPathCtxt { | |
535 | astconv: self, | |
536 | def_id, | |
537 | span, | |
538 | generic_args, | |
539 | missing_type_params: vec![], | |
540 | inferred_params: vec![], | |
541 | infer_args, | |
542 | is_object, | |
543 | }; | |
544 | let substs = Self::create_substs_for_generic_args( | |
545 | tcx, | |
546 | def_id, | |
547 | parent_substs, | |
548 | self_ty.is_some(), | |
549 | self_ty, | |
cdc7bbd5 | 550 | &arg_count, |
fc512014 | 551 | &mut substs_ctx, |
b7449926 | 552 | ); |
1a4d82fc | 553 | |
dfeec247 | 554 | self.complain_about_missing_type_params( |
fc512014 | 555 | substs_ctx.missing_type_params, |
dfeec247 XL |
556 | def_id, |
557 | span, | |
558 | generic_args.args.is_empty(), | |
559 | ); | |
560 | ||
cdc7bbd5 XL |
561 | debug!( |
562 | "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}", | |
563 | generics, self_ty, substs | |
564 | ); | |
565 | ||
566 | (substs, arg_count) | |
567 | } | |
568 | ||
569 | fn create_assoc_bindings_for_generic_args<'a>( | |
570 | &self, | |
571 | generic_args: &'a hir::GenericArgs<'_>, | |
572 | ) -> Vec<ConvertedBinding<'a, 'tcx>> { | |
dc9dc135 XL |
573 | // Convert associated-type bindings or constraints into a separate vector. |
574 | // Example: Given this: | |
575 | // | |
576 | // T: Iterator<Item = u32> | |
577 | // | |
578 | // The `T` is passed in as a self-type; the `Item = u32` is | |
579 | // not a "type parameter" of the `Iterator` trait, but rather | |
580 | // a restriction on `<T as Iterator>::Item`, so it is passed | |
581 | // back separately. | |
dfeec247 XL |
582 | let assoc_bindings = generic_args |
583 | .bindings | |
584 | .iter() | |
dc9dc135 XL |
585 | .map(|binding| { |
586 | let kind = match binding.kind { | |
dfeec247 XL |
587 | hir::TypeBindingKind::Equality { ref ty } => { |
588 | ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty)) | |
589 | } | |
590 | hir::TypeBindingKind::Constraint { ref bounds } => { | |
591 | ConvertedBindingKind::Constraint(bounds) | |
592 | } | |
dc9dc135 | 593 | }; |
5869c6ff | 594 | ConvertedBinding { |
17df50a5 | 595 | hir_id: binding.hir_id, |
5869c6ff XL |
596 | item_name: binding.ident, |
597 | kind, | |
598 | gen_args: binding.gen_args, | |
599 | span: binding.span, | |
600 | } | |
dc9dc135 XL |
601 | }) |
602 | .collect(); | |
a7813a04 | 603 | |
cdc7bbd5 | 604 | assoc_bindings |
e9174d1e | 605 | } |
e9174d1e | 606 | |
dfeec247 XL |
607 | crate fn create_substs_for_associated_item( |
608 | &self, | |
609 | tcx: TyCtxt<'tcx>, | |
610 | span: Span, | |
611 | item_def_id: DefId, | |
612 | item_segment: &hir::PathSegment<'_>, | |
613 | parent_substs: SubstsRef<'tcx>, | |
614 | ) -> SubstsRef<'tcx> { | |
17df50a5 XL |
615 | debug!( |
616 | "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}", | |
617 | span, item_def_id, item_segment | |
618 | ); | |
dfeec247 XL |
619 | if tcx.generics_of(item_def_id).params.is_empty() { |
620 | self.prohibit_generics(slice::from_ref(item_segment)); | |
621 | ||
622 | parent_substs | |
623 | } else { | |
624 | self.create_substs_for_ast_path( | |
625 | span, | |
626 | item_def_id, | |
627 | parent_substs, | |
5869c6ff XL |
628 | item_segment, |
629 | item_segment.args(), | |
dfeec247 XL |
630 | item_segment.infer_args, |
631 | None, | |
632 | ) | |
633 | .0 | |
634 | } | |
635 | } | |
636 | ||
a7813a04 | 637 | /// Instantiates the path for the given trait reference, assuming that it's |
dc9dc135 | 638 | /// bound to a valid trait type. Returns the `DefId` of the defining trait. |
0531ce1d | 639 | /// The type _cannot_ be a type other than a trait type. |
a7813a04 | 640 | /// |
9fa01778 | 641 | /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>` |
a7813a04 | 642 | /// are disallowed. Otherwise, they are pushed onto the vector given. |
dfeec247 XL |
643 | pub fn instantiate_mono_trait_ref( |
644 | &self, | |
645 | trait_ref: &hir::TraitRef<'_>, | |
646 | self_ty: Ty<'tcx>, | |
647 | ) -> ty::TraitRef<'tcx> { | |
8faf50e0 | 648 | self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1); |
7cac9316 | 649 | |
dfeec247 XL |
650 | self.ast_path_to_mono_trait_ref( |
651 | trait_ref.path.span, | |
ba9703b0 | 652 | trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()), |
dfeec247 XL |
653 | self_ty, |
654 | trait_ref.path.segments.last().unwrap(), | |
655 | ) | |
1a4d82fc | 656 | } |
c34b1796 | 657 | |
cdc7bbd5 XL |
658 | /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct |
659 | /// a full trait reference. The resulting trait reference is returned. This may also generate | |
660 | /// auxiliary bounds, which are added to `bounds`. | |
661 | /// | |
662 | /// Example: | |
663 | /// | |
664 | /// ``` | |
665 | /// poly_trait_ref = Iterator<Item = u32> | |
666 | /// self_ty = Foo | |
667 | /// ``` | |
668 | /// | |
669 | /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`. | |
670 | /// | |
671 | /// **A note on binders:** against our usual convention, there is an implied bounder around | |
672 | /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions. | |
673 | /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>` | |
674 | /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be | |
675 | /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly, | |
676 | /// however. | |
677 | #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))] | |
678 | pub fn instantiate_poly_trait_ref( | |
dfeec247 XL |
679 | &self, |
680 | trait_ref: &hir::TraitRef<'_>, | |
416331ca | 681 | span: Span, |
dfeec247 | 682 | constness: Constness, |
9e0c209e | 683 | self_ty: Ty<'tcx>, |
dc9dc135 XL |
684 | bounds: &mut Bounds<'tcx>, |
685 | speculative: bool, | |
f9f354fc | 686 | ) -> GenericArgCountResult { |
ba9703b0 | 687 | let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()); |
32a655c1 | 688 | |
8faf50e0 | 689 | self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1); |
7cac9316 | 690 | |
cdc7bbd5 XL |
691 | let tcx = self.tcx(); |
692 | let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id); | |
693 | debug!(?bound_vars); | |
694 | ||
695 | let (substs, arg_count) = self.create_substs_for_ast_trait_ref( | |
f9f354fc | 696 | trait_ref.path.span, |
a1dfa0c6 XL |
697 | trait_def_id, |
698 | self_ty, | |
699 | trait_ref.path.segments.last().unwrap(), | |
700 | ); | |
cdc7bbd5 XL |
701 | let assoc_bindings = self |
702 | .create_assoc_bindings_for_generic_args(trait_ref.path.segments.last().unwrap().args()); | |
703 | ||
704 | let poly_trait_ref = | |
705 | ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars); | |
a7813a04 | 706 | |
cdc7bbd5 | 707 | debug!(?poly_trait_ref, ?assoc_bindings); |
dfeec247 | 708 | bounds.trait_bounds.push((poly_trait_ref, span, constness)); |
416331ca | 709 | |
94b46f34 | 710 | let mut dup_bindings = FxHashMap::default(); |
dc9dc135 XL |
711 | for binding in &assoc_bindings { |
712 | // Specify type to assert that error was already reported in `Err` case. | |
dfeec247 XL |
713 | let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding( |
714 | trait_ref.hir_ref_id, | |
715 | poly_trait_ref, | |
716 | binding, | |
717 | bounds, | |
718 | speculative, | |
719 | &mut dup_bindings, | |
ba9703b0 | 720 | binding.span, |
dfeec247 | 721 | ); |
dc9dc135 XL |
722 | // Okay to ignore `Err` because of `ErrorReported` (see above). |
723 | } | |
724 | ||
f9f354fc | 725 | arg_count |
c34b1796 AL |
726 | } |
727 | ||
3dfed10e XL |
728 | pub fn instantiate_lang_item_trait_ref( |
729 | &self, | |
730 | lang_item: hir::LangItem, | |
731 | span: Span, | |
732 | hir_id: hir::HirId, | |
733 | args: &GenericArgs<'_>, | |
734 | self_ty: Ty<'tcx>, | |
735 | bounds: &mut Bounds<'tcx>, | |
736 | ) { | |
737 | let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span)); | |
738 | ||
cdc7bbd5 | 739 | let (substs, _) = self.create_substs_for_ast_path( |
5869c6ff XL |
740 | span, |
741 | trait_def_id, | |
742 | &[], | |
743 | &hir::PathSegment::invalid(), | |
744 | args, | |
745 | false, | |
746 | Some(self_ty), | |
747 | ); | |
cdc7bbd5 XL |
748 | let assoc_bindings = self.create_assoc_bindings_for_generic_args(args); |
749 | let tcx = self.tcx(); | |
750 | let bound_vars = tcx.late_bound_vars(hir_id); | |
751 | let poly_trait_ref = | |
752 | ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars); | |
3dfed10e XL |
753 | bounds.trait_bounds.push((poly_trait_ref, span, Constness::NotConst)); |
754 | ||
755 | let mut dup_bindings = FxHashMap::default(); | |
756 | for binding in assoc_bindings { | |
757 | let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding( | |
758 | hir_id, | |
759 | poly_trait_ref, | |
760 | &binding, | |
761 | bounds, | |
762 | false, | |
763 | &mut dup_bindings, | |
764 | span, | |
765 | ); | |
766 | } | |
767 | } | |
768 | ||
dfeec247 XL |
769 | fn ast_path_to_mono_trait_ref( |
770 | &self, | |
dc9dc135 XL |
771 | span: Span, |
772 | trait_def_id: DefId, | |
773 | self_ty: Ty<'tcx>, | |
dfeec247 XL |
774 | trait_segment: &hir::PathSegment<'_>, |
775 | ) -> ty::TraitRef<'tcx> { | |
cdc7bbd5 | 776 | let (substs, _) = |
dfeec247 | 777 | self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment); |
cdc7bbd5 | 778 | let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args()); |
f9f354fc | 779 | if let Some(b) = assoc_bindings.first() { |
3dfed10e | 780 | Self::prohibit_assoc_ty_binding(self.tcx(), b.span); |
f9f354fc | 781 | } |
a7813a04 XL |
782 | ty::TraitRef::new(trait_def_id, substs) |
783 | } | |
c34b1796 | 784 | |
cdc7bbd5 | 785 | #[tracing::instrument(level = "debug", skip(self, span))] |
dfeec247 XL |
786 | fn create_substs_for_ast_trait_ref<'a>( |
787 | &self, | |
788 | span: Span, | |
789 | trait_def_id: DefId, | |
790 | self_ty: Ty<'tcx>, | |
791 | trait_segment: &'a hir::PathSegment<'a>, | |
cdc7bbd5 | 792 | ) -> (SubstsRef<'tcx>, GenericArgCountResult) { |
dfeec247 XL |
793 | self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment); |
794 | ||
795 | self.create_substs_for_ast_path( | |
796 | span, | |
797 | trait_def_id, | |
798 | &[], | |
5869c6ff XL |
799 | trait_segment, |
800 | trait_segment.args(), | |
dfeec247 XL |
801 | trait_segment.infer_args, |
802 | Some(self_ty), | |
803 | ) | |
a7813a04 | 804 | } |
1a4d82fc | 805 | |
f9f354fc | 806 | fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool { |
74b04a01 XL |
807 | self.tcx() |
808 | .associated_items(trait_def_id) | |
809 | .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id) | |
810 | .is_some() | |
476ff2be SL |
811 | } |
812 | ||
dc9dc135 | 813 | // Returns `true` if a bounds list includes `?Sized`. |
cdc7bbd5 | 814 | pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool { |
dc9dc135 XL |
815 | let tcx = self.tcx(); |
816 | ||
817 | // Try to find an unbound in bounds. | |
818 | let mut unbound = None; | |
819 | for ab in ast_bounds { | |
5869c6ff | 820 | if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab { |
dc9dc135 XL |
821 | if unbound.is_none() { |
822 | unbound = Some(&ptr.trait_ref); | |
823 | } else { | |
1b1a35ee | 824 | tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span }); |
dc9dc135 XL |
825 | } |
826 | } | |
827 | } | |
828 | ||
3dfed10e | 829 | let kind_id = tcx.lang_items().require(LangItem::Sized); |
dc9dc135 XL |
830 | match unbound { |
831 | Some(tpb) => { | |
832 | // FIXME(#8559) currently requires the unbound to be built-in. | |
833 | if let Ok(kind_id) = kind_id { | |
834 | if tpb.path.res != Res::Def(DefKind::Trait, kind_id) { | |
835 | tcx.sess.span_warn( | |
836 | span, | |
837 | "default bound relaxed for a type parameter, but \ | |
e74abb32 XL |
838 | this does nothing because the given bound is not \ |
839 | a default; only `?Sized` is supported", | |
dc9dc135 XL |
840 | ); |
841 | } | |
842 | } | |
843 | } | |
844 | _ if kind_id.is_ok() => { | |
845 | return false; | |
846 | } | |
847 | // No lang item for `Sized`, so we can't add it as a bound. | |
848 | None => {} | |
849 | } | |
850 | ||
851 | true | |
852 | } | |
853 | ||
854 | /// This helper takes a *converted* parameter type (`param_ty`) | |
855 | /// and an *unconverted* list of bounds: | |
856 | /// | |
ba9703b0 | 857 | /// ```text |
dc9dc135 XL |
858 | /// fn foo<T: Debug> |
859 | /// ^ ^^^^^ `ast_bounds` parameter, in HIR form | |
860 | /// | | |
861 | /// `param_ty`, in ty form | |
862 | /// ``` | |
863 | /// | |
864 | /// It adds these `ast_bounds` into the `bounds` structure. | |
865 | /// | |
866 | /// **A note on binders:** there is an implied binder around | |
867 | /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref` | |
868 | /// for more details. | |
cdc7bbd5 | 869 | #[tracing::instrument(level = "debug", skip(self, bounds))] |
dfeec247 XL |
870 | fn add_bounds( |
871 | &self, | |
dc9dc135 | 872 | param_ty: Ty<'tcx>, |
cdc7bbd5 | 873 | ast_bounds: &[hir::GenericBound<'_>], |
dc9dc135 | 874 | bounds: &mut Bounds<'tcx>, |
cdc7bbd5 | 875 | bound_vars: &'tcx ty::List<ty::BoundVariableKind>, |
dc9dc135 | 876 | ) { |
dfeec247 | 877 | let constness = self.default_constness_for_trait_bounds(); |
dc9dc135 XL |
878 | for ast_bound in ast_bounds { |
879 | match *ast_bound { | |
dfeec247 | 880 | hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => { |
cdc7bbd5 XL |
881 | self.instantiate_poly_trait_ref( |
882 | &b.trait_ref, | |
883 | b.span, | |
884 | constness, | |
885 | param_ty, | |
886 | bounds, | |
887 | false, | |
888 | ); | |
dfeec247 XL |
889 | } |
890 | hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => { | |
cdc7bbd5 XL |
891 | self.instantiate_poly_trait_ref( |
892 | &b.trait_ref, | |
893 | b.span, | |
894 | Constness::NotConst, | |
895 | param_ty, | |
896 | bounds, | |
897 | false, | |
898 | ); | |
dfeec247 | 899 | } |
dc9dc135 | 900 | hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {} |
3dfed10e XL |
901 | hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => self |
902 | .instantiate_lang_item_trait_ref( | |
cdc7bbd5 | 903 | lang_item, span, hir_id, args, param_ty, bounds, |
3dfed10e | 904 | ), |
cdc7bbd5 XL |
905 | hir::GenericBound::Outlives(ref l) => bounds.region_bounds.push(( |
906 | ty::Binder::bind_with_vars(self.ast_region_to_region(l, None), bound_vars), | |
907 | l.span, | |
908 | )), | |
dc9dc135 XL |
909 | } |
910 | } | |
dc9dc135 XL |
911 | } |
912 | ||
913 | /// Translates a list of bounds from the HIR into the `Bounds` data structure. | |
914 | /// The self-type for the bounds is given by `param_ty`. | |
915 | /// | |
916 | /// Example: | |
917 | /// | |
918 | /// ``` | |
919 | /// fn foo<T: Bar + Baz>() { } | |
920 | /// ^ ^^^^^^^^^ ast_bounds | |
921 | /// param_ty | |
922 | /// ``` | |
923 | /// | |
924 | /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be | |
925 | /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the | |
926 | /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`. | |
927 | /// | |
928 | /// `span` should be the declaration size of the parameter. | |
dfeec247 XL |
929 | pub fn compute_bounds( |
930 | &self, | |
dc9dc135 | 931 | param_ty: Ty<'tcx>, |
dfeec247 | 932 | ast_bounds: &[hir::GenericBound<'_>], |
dc9dc135 XL |
933 | sized_by_default: SizedByDefault, |
934 | span: Span, | |
6a06907d | 935 | ) -> Bounds<'tcx> { |
6a06907d XL |
936 | self.compute_bounds_inner(param_ty, &ast_bounds, sized_by_default, span) |
937 | } | |
938 | ||
939 | /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type | |
940 | /// named `assoc_name` into ty::Bounds. Ignore the rest. | |
941 | pub fn compute_bounds_that_match_assoc_type( | |
942 | &self, | |
943 | param_ty: Ty<'tcx>, | |
944 | ast_bounds: &[hir::GenericBound<'_>], | |
945 | sized_by_default: SizedByDefault, | |
946 | span: Span, | |
947 | assoc_name: Ident, | |
948 | ) -> Bounds<'tcx> { | |
949 | let mut result = Vec::new(); | |
950 | ||
951 | for ast_bound in ast_bounds { | |
952 | if let Some(trait_ref) = ast_bound.trait_ref() { | |
953 | if let Some(trait_did) = trait_ref.trait_def_id() { | |
954 | if self.tcx().trait_may_define_assoc_type(trait_did, assoc_name) { | |
cdc7bbd5 | 955 | result.push(ast_bound.clone()); |
6a06907d XL |
956 | } |
957 | } | |
958 | } | |
959 | } | |
960 | ||
961 | self.compute_bounds_inner(param_ty, &result, sized_by_default, span) | |
962 | } | |
963 | ||
964 | fn compute_bounds_inner( | |
965 | &self, | |
966 | param_ty: Ty<'tcx>, | |
cdc7bbd5 | 967 | ast_bounds: &[hir::GenericBound<'_>], |
6a06907d XL |
968 | sized_by_default: SizedByDefault, |
969 | span: Span, | |
dc9dc135 XL |
970 | ) -> Bounds<'tcx> { |
971 | let mut bounds = Bounds::default(); | |
972 | ||
cdc7bbd5 | 973 | self.add_bounds(param_ty, ast_bounds, &mut bounds, ty::List::empty()); |
dc9dc135 XL |
974 | |
975 | bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default { | |
dfeec247 | 976 | if !self.is_unsized(ast_bounds, span) { Some(span) } else { None } |
dc9dc135 XL |
977 | } else { |
978 | None | |
979 | }; | |
980 | ||
981 | bounds | |
982 | } | |
983 | ||
984 | /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates | |
985 | /// onto `bounds`. | |
986 | /// | |
987 | /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the | |
988 | /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside* | |
989 | /// the binder (e.g., `&'a u32`) and hence may reference bound regions. | |
cdc7bbd5 XL |
990 | #[tracing::instrument( |
991 | level = "debug", | |
992 | skip(self, bounds, speculative, dup_bindings, path_span) | |
993 | )] | |
dc9dc135 | 994 | fn add_predicates_for_ast_type_binding( |
a7813a04 | 995 | &self, |
532ac7d7 | 996 | hir_ref_id: hir::HirId, |
9e0c209e | 997 | trait_ref: ty::PolyTraitRef<'tcx>, |
dc9dc135 XL |
998 | binding: &ConvertedBinding<'_, 'tcx>, |
999 | bounds: &mut Bounds<'tcx>, | |
94b46f34 | 1000 | speculative: bool, |
dc9dc135 | 1001 | dup_bindings: &mut FxHashMap<DefId, Span>, |
dfeec247 | 1002 | path_span: Span, |
dc9dc135 | 1003 | ) -> Result<(), ErrorReported> { |
5869c6ff XL |
1004 | // Given something like `U: SomeTrait<T = X>`, we want to produce a |
1005 | // predicate like `<U as SomeTrait>::T = X`. This is somewhat | |
1006 | // subtle in the event that `T` is defined in a supertrait of | |
1007 | // `SomeTrait`, because in that case we need to upcast. | |
1008 | // | |
1009 | // That is, consider this case: | |
1010 | // | |
1011 | // ``` | |
1012 | // trait SubTrait: SuperTrait<i32> { } | |
1013 | // trait SuperTrait<A> { type T; } | |
1014 | // | |
1015 | // ... B: SubTrait<T = foo> ... | |
1016 | // ``` | |
1017 | // | |
1018 | // We want to produce `<B as SuperTrait<i32>>::T == foo`. | |
3dfed10e | 1019 | |
5869c6ff | 1020 | let tcx = self.tcx(); |
a7813a04 | 1021 | |
dfeec247 XL |
1022 | let candidate = |
1023 | if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) { | |
1024 | // Simple case: X is defined in the current trait. | |
1025 | trait_ref | |
1026 | } else { | |
1027 | // Otherwise, we have to walk through the supertraits to find | |
1028 | // those that do. | |
1029 | self.one_bound_for_assoc_type( | |
1030 | || traits::supertraits(tcx, trait_ref), | |
1031 | || trait_ref.print_only_trait_path().to_string(), | |
1032 | binding.item_name, | |
1033 | path_span, | |
1034 | || match binding.kind { | |
1035 | ConvertedBindingKind::Equality(ty) => Some(ty.to_string()), | |
1036 | _ => None, | |
1037 | }, | |
1038 | )? | |
1039 | }; | |
ff7c6d11 | 1040 | |
94b46f34 | 1041 | let (assoc_ident, def_scope) = |
dc9dc135 | 1042 | tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id); |
74b04a01 | 1043 | |
ba9703b0 | 1044 | // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead |
74b04a01 | 1045 | // of calling `filter_by_name_and_kind`. |
dfeec247 XL |
1046 | let assoc_ty = tcx |
1047 | .associated_items(candidate.def_id()) | |
74b04a01 | 1048 | .filter_by_name_unhygienic(assoc_ident.name) |
ba9703b0 XL |
1049 | .find(|i| { |
1050 | i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident | |
1051 | }) | |
dfeec247 | 1052 | .expect("missing associated type"); |
ff7c6d11 XL |
1053 | |
1054 | if !assoc_ty.vis.is_accessible_from(def_scope, tcx) { | |
ba9703b0 XL |
1055 | tcx.sess |
1056 | .struct_span_err( | |
1057 | binding.span, | |
1058 | &format!("associated type `{}` is private", binding.item_name), | |
1059 | ) | |
1060 | .span_label(binding.span, "private associated type") | |
1061 | .emit(); | |
a7813a04 | 1062 | } |
17df50a5 | 1063 | tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span, None); |
a7813a04 | 1064 | |
94b46f34 | 1065 | if !speculative { |
dfeec247 XL |
1066 | dup_bindings |
1067 | .entry(assoc_ty.def_id) | |
94b46f34 | 1068 | .and_modify(|prev_span| { |
1b1a35ee XL |
1069 | self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified { |
1070 | span: binding.span, | |
1071 | prev_span: *prev_span, | |
1072 | item_name: binding.item_name, | |
1073 | def_path: tcx.def_path_str(assoc_ty.container.id()), | |
1074 | }); | |
94b46f34 XL |
1075 | }) |
1076 | .or_insert(binding.span); | |
1077 | } | |
1078 | ||
5869c6ff XL |
1079 | // Include substitutions for generic parameters of associated types |
1080 | let projection_ty = candidate.map_bound(|trait_ref| { | |
17df50a5 | 1081 | let ident = Ident::new(assoc_ty.ident.name, binding.item_name.span); |
5869c6ff | 1082 | let item_segment = hir::PathSegment { |
17df50a5 XL |
1083 | ident, |
1084 | hir_id: Some(binding.hir_id), | |
5869c6ff XL |
1085 | res: None, |
1086 | args: Some(binding.gen_args), | |
1087 | infer_args: false, | |
1088 | }; | |
1089 | ||
1090 | let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item( | |
1091 | tcx, | |
1092 | path_span, | |
1093 | assoc_ty.def_id, | |
1094 | &item_segment, | |
1095 | trait_ref.substs, | |
1096 | ); | |
1097 | ||
1098 | debug!( | |
1099 | "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}", | |
1100 | substs_trait_ref_and_assoc_item | |
1101 | ); | |
1102 | ||
1103 | ty::ProjectionTy { | |
1104 | item_def_id: assoc_ty.def_id, | |
1105 | substs: substs_trait_ref_and_assoc_item, | |
1106 | } | |
1107 | }); | |
1108 | ||
1109 | if !speculative { | |
1110 | // Find any late-bound regions declared in `ty` that are not | |
1111 | // declared in the trait-ref or assoc_ty. These are not well-formed. | |
1112 | // | |
1113 | // Example: | |
1114 | // | |
1115 | // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad | |
1116 | // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok | |
1117 | if let ConvertedBindingKind::Equality(ty) = binding.kind { | |
1118 | let late_bound_in_trait_ref = | |
1119 | tcx.collect_constrained_late_bound_regions(&projection_ty); | |
1120 | let late_bound_in_ty = | |
cdc7bbd5 | 1121 | tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty)); |
5869c6ff XL |
1122 | debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref); |
1123 | debug!("late_bound_in_ty = {:?}", late_bound_in_ty); | |
1124 | ||
1125 | // FIXME: point at the type params that don't have appropriate lifetimes: | |
1126 | // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F); | |
1127 | // ---- ---- ^^^^^^^ | |
1128 | self.validate_late_bound_regions( | |
1129 | late_bound_in_trait_ref, | |
1130 | late_bound_in_ty, | |
1131 | |br_name| { | |
1132 | struct_span_err!( | |
1133 | tcx.sess, | |
1134 | binding.span, | |
1135 | E0582, | |
1136 | "binding for associated type `{}` references {}, \ | |
1137 | which does not appear in the trait input types", | |
1138 | binding.item_name, | |
1139 | br_name | |
1140 | ) | |
1141 | }, | |
1142 | ); | |
1143 | } | |
1144 | } | |
1145 | ||
dc9dc135 XL |
1146 | match binding.kind { |
1147 | ConvertedBindingKind::Equality(ref ty) => { | |
1148 | // "Desugar" a constraint like `T: Iterator<Item = u32>` this to | |
1149 | // the "projection predicate" for: | |
1150 | // | |
1151 | // `<T as Iterator>::Item = u32` | |
dfeec247 | 1152 | bounds.projection_bounds.push(( |
5869c6ff XL |
1153 | projection_ty.map_bound(|projection_ty| { |
1154 | debug!( | |
1155 | "add_predicates_for_ast_type_binding: projection_ty {:?}, substs: {:?}", | |
1156 | projection_ty, projection_ty.substs | |
1157 | ); | |
1158 | ty::ProjectionPredicate { projection_ty, ty } | |
dfeec247 XL |
1159 | }), |
1160 | binding.span, | |
1161 | )); | |
9e0c209e | 1162 | } |
dc9dc135 XL |
1163 | ConvertedBindingKind::Constraint(ast_bounds) => { |
1164 | // "Desugar" a constraint like `T: Iterator<Item: Debug>` to | |
1165 | // | |
1166 | // `<T as Iterator>::Item: Debug` | |
1167 | // | |
1168 | // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty` | |
1169 | // parameter to have a skipped binder. | |
cdc7bbd5 XL |
1170 | let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder())); |
1171 | self.add_bounds(param_ty, ast_bounds, bounds, candidate.bound_vars()); | |
dc9dc135 XL |
1172 | } |
1173 | } | |
1174 | Ok(()) | |
1a4d82fc JJ |
1175 | } |
1176 | ||
dfeec247 XL |
1177 | fn ast_path_to_ty( |
1178 | &self, | |
a7813a04 | 1179 | span: Span, |
a7813a04 | 1180 | did: DefId, |
dfeec247 XL |
1181 | item_segment: &hir::PathSegment<'_>, |
1182 | ) -> Ty<'tcx> { | |
32a655c1 | 1183 | let substs = self.ast_path_substs_for_ty(span, did, item_segment); |
dfeec247 | 1184 | self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs)) |
1a4d82fc JJ |
1185 | } |
1186 | ||
dfeec247 XL |
1187 | fn conv_object_ty_poly_trait_ref( |
1188 | &self, | |
32a655c1 | 1189 | span: Span, |
dfeec247 XL |
1190 | trait_bounds: &[hir::PolyTraitRef<'_>], |
1191 | lifetime: &hir::Lifetime, | |
3dfed10e | 1192 | borrowed: bool, |
dfeec247 | 1193 | ) -> Ty<'tcx> { |
a7813a04 | 1194 | let tcx = self.tcx(); |
9e0c209e | 1195 | |
dc9dc135 XL |
1196 | let mut bounds = Bounds::default(); |
1197 | let mut potential_assoc_types = Vec::new(); | |
532ac7d7 | 1198 | let dummy_self = self.tcx().types.trait_object_dummy_self; |
416331ca | 1199 | for trait_bound in trait_bounds.iter().rev() { |
f9f354fc XL |
1200 | if let GenericArgCountResult { |
1201 | correct: | |
1202 | Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }), | |
1203 | .. | |
1204 | } = self.instantiate_poly_trait_ref( | |
cdc7bbd5 XL |
1205 | &trait_bound.trait_ref, |
1206 | trait_bound.span, | |
dfeec247 | 1207 | Constness::NotConst, |
416331ca XL |
1208 | dummy_self, |
1209 | &mut bounds, | |
cdc7bbd5 | 1210 | false, |
74b04a01 | 1211 | ) { |
5869c6ff | 1212 | potential_assoc_types.extend(cur_potential_assoc_types); |
74b04a01 | 1213 | } |
416331ca | 1214 | } |
dc9dc135 XL |
1215 | |
1216 | // Expand trait aliases recursively and check that only one regular (non-auto) trait | |
1217 | // is used and no 'maybe' bounds are used. | |
74b04a01 XL |
1218 | let expanded_traits = |
1219 | traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b))); | |
dc9dc135 XL |
1220 | let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = |
1221 | expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id())); | |
1222 | if regular_traits.len() > 1 { | |
1223 | let first_trait = ®ular_traits[0]; | |
1224 | let additional_trait = ®ular_traits[1]; | |
dfeec247 XL |
1225 | let mut err = struct_span_err!( |
1226 | tcx.sess, | |
1227 | additional_trait.bottom().1, | |
1228 | E0225, | |
dc9dc135 XL |
1229 | "only auto traits can be used as additional traits in a trait object" |
1230 | ); | |
dfeec247 XL |
1231 | additional_trait.label_with_exp_info( |
1232 | &mut err, | |
1233 | "additional non-auto trait", | |
1234 | "additional use", | |
1235 | ); | |
1236 | first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use"); | |
3dfed10e XL |
1237 | err.help(&format!( |
1238 | "consider creating a new trait with all of these as super-traits and using that \ | |
1239 | trait here instead: `trait NewTrait: {} {{}}`", | |
1240 | regular_traits | |
1241 | .iter() | |
1242 | .map(|t| t.trait_ref().print_only_trait_path().to_string()) | |
1243 | .collect::<Vec<_>>() | |
1244 | .join(" + "), | |
1245 | )); | |
1246 | err.note( | |
1247 | "auto-traits like `Send` and `Sync` are traits that have special properties; \ | |
1248 | for more information on them, visit \ | |
1249 | <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>", | |
1250 | ); | |
dc9dc135 | 1251 | err.emit(); |
7cac9316 XL |
1252 | } |
1253 | ||
dc9dc135 | 1254 | if regular_traits.is_empty() && auto_traits.is_empty() { |
1b1a35ee | 1255 | tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span }); |
f035d41b | 1256 | return tcx.ty_error(); |
9e0c209e SL |
1257 | } |
1258 | ||
a1dfa0c6 XL |
1259 | // Check that there are no gross object safety violations; |
1260 | // most importantly, that the supertraits don't contain `Self`, | |
1261 | // to avoid ICEs. | |
dc9dc135 XL |
1262 | for item in ®ular_traits { |
1263 | let object_safety_violations = | |
dfeec247 | 1264 | astconv_object_safety_violations(tcx, item.trait_ref().def_id()); |
dc9dc135 | 1265 | if !object_safety_violations.is_empty() { |
dfeec247 XL |
1266 | report_object_safety_error( |
1267 | tcx, | |
dc9dc135 XL |
1268 | span, |
1269 | item.trait_ref().def_id(), | |
ba9703b0 | 1270 | &object_safety_violations[..], |
dfeec247 XL |
1271 | ) |
1272 | .emit(); | |
f035d41b | 1273 | return tcx.ty_error(); |
dc9dc135 | 1274 | } |
a7813a04 XL |
1275 | } |
1276 | ||
a1dfa0c6 | 1277 | // Use a `BTreeSet` to keep output in a more consistent order. |
dfeec247 | 1278 | let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default(); |
b7449926 | 1279 | |
dfeec247 XL |
1280 | let regular_traits_refs_spans = bounds |
1281 | .trait_bounds | |
dc9dc135 | 1282 | .into_iter() |
dfeec247 | 1283 | .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id())); |
a7813a04 | 1284 | |
dfeec247 | 1285 | for (base_trait_ref, span, constness) in regular_traits_refs_spans { |
74b04a01 | 1286 | assert_eq!(constness, Constness::NotConst); |
a7813a04 | 1287 | |
ba9703b0 | 1288 | for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) { |
dfeec247 XL |
1289 | debug!( |
1290 | "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", | |
ba9703b0 | 1291 | obligation.predicate |
a1dfa0c6 | 1292 | ); |
3dfed10e | 1293 | |
5869c6ff | 1294 | let bound_predicate = obligation.predicate.kind(); |
29967ef6 | 1295 | match bound_predicate.skip_binder() { |
5869c6ff | 1296 | ty::PredicateKind::Trait(pred, _) => { |
29967ef6 | 1297 | let pred = bound_predicate.rebind(pred); |
dfeec247 XL |
1298 | associated_types.entry(span).or_default().extend( |
1299 | tcx.associated_items(pred.def_id()) | |
74b04a01 | 1300 | .in_definition_order() |
dfeec247 XL |
1301 | .filter(|item| item.kind == ty::AssocKind::Type) |
1302 | .map(|item| item.def_id), | |
1303 | ); | |
1304 | } | |
5869c6ff | 1305 | ty::PredicateKind::Projection(pred) => { |
29967ef6 | 1306 | let pred = bound_predicate.rebind(pred); |
dfeec247 XL |
1307 | // A `Self` within the original bound will be substituted with a |
1308 | // `trait_object_dummy_self`, so check for that. | |
ba9703b0 XL |
1309 | let references_self = |
1310 | pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into()); | |
dfeec247 XL |
1311 | |
1312 | // If the projection output contains `Self`, force the user to | |
1313 | // elaborate it explicitly to avoid a lot of complexity. | |
1314 | // | |
1315 | // The "classicaly useful" case is the following: | |
1316 | // ``` | |
1317 | // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput { | |
1318 | // type MyOutput; | |
1319 | // } | |
1320 | // ``` | |
1321 | // | |
1322 | // Here, the user could theoretically write `dyn MyTrait<Output = X>`, | |
1323 | // but actually supporting that would "expand" to an infinitely-long type | |
1324 | // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`. | |
1325 | // | |
1326 | // Instead, we force the user to write | |
1327 | // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See | |
1328 | // the discussion in #56288 for alternatives. | |
1329 | if !references_self { | |
1330 | // Include projections defined on supertraits. | |
1331 | bounds.projection_bounds.push((pred, span)); | |
1332 | } | |
a1dfa0c6 | 1333 | } |
dfeec247 | 1334 | _ => (), |
a1dfa0c6 XL |
1335 | } |
1336 | } | |
dfeec247 XL |
1337 | } |
1338 | ||
1339 | for (projection_bound, _) in &bounds.projection_bounds { | |
74b04a01 | 1340 | for def_ids in associated_types.values_mut() { |
dfeec247 | 1341 | def_ids.remove(&projection_bound.projection_def_id()); |
a1dfa0c6 | 1342 | } |
a7813a04 | 1343 | } |
9346a6ac | 1344 | |
dfeec247 XL |
1345 | self.complain_about_missing_associated_types( |
1346 | associated_types, | |
1347 | potential_assoc_types, | |
1348 | trait_bounds, | |
1349 | ); | |
1350 | ||
dc9dc135 XL |
1351 | // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as |
1352 | // `dyn Trait + Send`. | |
6a06907d XL |
1353 | // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering |
1354 | // the bounds | |
1355 | let mut duplicates = FxHashSet::default(); | |
1356 | auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id())); | |
dc9dc135 XL |
1357 | debug!("regular_traits: {:?}", regular_traits); |
1358 | debug!("auto_traits: {:?}", auto_traits); | |
1359 | ||
532ac7d7 | 1360 | // Erase the `dummy_self` (`trait_object_dummy_self`) used above. |
6a06907d XL |
1361 | let existential_trait_refs = regular_traits.iter().map(|i| { |
1362 | i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| { | |
1363 | if trait_ref.self_ty() != dummy_self { | |
1364 | // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`, | |
1365 | // which picks up non-supertraits where clauses - but also, the object safety | |
1366 | // completely ignores trait aliases, which could be object safety hazards. We | |
1367 | // `delay_span_bug` here to avoid an ICE in stable even when the feature is | |
1368 | // disabled. (#66420) | |
1369 | tcx.sess.delay_span_bug( | |
1370 | DUMMY_SP, | |
1371 | &format!( | |
1372 | "trait_ref_to_existential called on {:?} with non-dummy Self", | |
1373 | trait_ref, | |
1374 | ), | |
1375 | ); | |
1376 | } | |
1377 | ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref) | |
1378 | }) | |
1379 | }); | |
dc9dc135 | 1380 | let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| { |
a1dfa0c6 | 1381 | bound.map_bound(|b| { |
6a06907d XL |
1382 | if b.projection_ty.self_ty() != dummy_self { |
1383 | tcx.sess.delay_span_bug( | |
1384 | DUMMY_SP, | |
1385 | &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b), | |
1386 | ); | |
a1dfa0c6 | 1387 | } |
6a06907d | 1388 | ty::ExistentialProjection::erase_self_ty(tcx, b) |
a1dfa0c6 XL |
1389 | }) |
1390 | }); | |
1391 | ||
5869c6ff XL |
1392 | let regular_trait_predicates = existential_trait_refs |
1393 | .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait)); | |
fc512014 XL |
1394 | let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| { |
1395 | ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id())) | |
1396 | }); | |
17df50a5 XL |
1397 | // N.b. principal, projections, auto traits |
1398 | // FIXME: This is actually wrong with multiple principals in regards to symbol mangling | |
dfeec247 | 1399 | let mut v = regular_trait_predicates |
dfeec247 | 1400 | .chain( |
5869c6ff | 1401 | existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)), |
dfeec247 | 1402 | ) |
17df50a5 | 1403 | .chain(auto_trait_predicates) |
b7449926 | 1404 | .collect::<SmallVec<[_; 8]>>(); |
fc512014 | 1405 | v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder())); |
0731742a | 1406 | v.dedup(); |
fc512014 | 1407 | let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter()); |
476ff2be | 1408 | |
a1dfa0c6 | 1409 | // Use explicitly-specified region bound. |
32a655c1 SL |
1410 | let region_bound = if !lifetime.is_elided() { |
1411 | self.ast_region_to_region(lifetime, None) | |
1412 | } else { | |
1413 | self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| { | |
9fa01778 | 1414 | if tcx.named_region(lifetime.hir_id).is_some() { |
32a655c1 SL |
1415 | self.ast_region_to_region(lifetime, None) |
1416 | } else { | |
dc9dc135 | 1417 | self.re_infer(None, span).unwrap_or_else(|| { |
3dfed10e | 1418 | let mut err = struct_span_err!( |
dfeec247 XL |
1419 | tcx.sess, |
1420 | span, | |
1421 | E0228, | |
dc9dc135 | 1422 | "the lifetime bound for this object type cannot be deduced \ |
dfeec247 | 1423 | from context; please supply an explicit bound" |
3dfed10e XL |
1424 | ); |
1425 | if borrowed { | |
1426 | // We will have already emitted an error E0106 complaining about a | |
1427 | // missing named lifetime in `&dyn Trait`, so we elide this one. | |
1428 | err.delay_as_bug(); | |
1429 | } else { | |
1430 | err.emit(); | |
1431 | } | |
48663c56 | 1432 | tcx.lifetimes.re_static |
32a655c1 SL |
1433 | }) |
1434 | } | |
1435 | }) | |
476ff2be | 1436 | }; |
476ff2be SL |
1437 | debug!("region_bound: {:?}", region_bound); |
1438 | ||
1439 | let ty = tcx.mk_dynamic(existential_predicates, region_bound); | |
9e0c209e SL |
1440 | debug!("trait_object_type: {:?}", ty); |
1441 | ty | |
9346a6ac AL |
1442 | } |
1443 | ||
48663c56 XL |
1444 | fn report_ambiguous_associated_type( |
1445 | &self, | |
1446 | span: Span, | |
1447 | type_str: &str, | |
1448 | trait_str: &str, | |
f9f354fc | 1449 | name: Symbol, |
48663c56 XL |
1450 | ) { |
1451 | let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type"); | |
6a06907d XL |
1452 | if let (true, Ok(snippet)) = ( |
1453 | self.tcx() | |
1454 | .sess | |
1455 | .confused_type_with_std_module | |
1456 | .borrow() | |
1457 | .keys() | |
1458 | .any(|full_span| full_span.contains(span)), | |
48663c56 | 1459 | self.tcx().sess.source_map().span_to_snippet(span), |
dfeec247 | 1460 | ) { |
48663c56 | 1461 | err.span_suggestion( |
0bf4aa26 | 1462 | span, |
48663c56 XL |
1463 | "you are looking for the module in `std`, not the primitive type", |
1464 | format!("std::{}", snippet), | |
1465 | Applicability::MachineApplicable, | |
1466 | ); | |
1467 | } else { | |
1468 | err.span_suggestion( | |
dfeec247 XL |
1469 | span, |
1470 | "use fully-qualified syntax", | |
1471 | format!("<{} as {}>::{}", type_str, trait_str, name), | |
1472 | Applicability::HasPlaceholders, | |
48663c56 XL |
1473 | ); |
1474 | } | |
1475 | err.emit(); | |
a7813a04 | 1476 | } |
9346a6ac | 1477 | |
a7813a04 | 1478 | // Search for a bound on a type parameter which includes the associated item |
dc9dc135 | 1479 | // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter |
8bb4bdeb | 1480 | // This function will fail if there are no suitable bounds or there is |
a7813a04 | 1481 | // any ambiguity. |
dfeec247 XL |
1482 | fn find_bound_for_assoc_item( |
1483 | &self, | |
f9f354fc XL |
1484 | ty_param_def_id: LocalDefId, |
1485 | assoc_name: Ident, | |
dfeec247 XL |
1486 | span: Span, |
1487 | ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> { | |
a7813a04 | 1488 | let tcx = self.tcx(); |
c34b1796 | 1489 | |
416331ca XL |
1490 | debug!( |
1491 | "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})", | |
dfeec247 | 1492 | ty_param_def_id, assoc_name, span, |
416331ca XL |
1493 | ); |
1494 | ||
6a06907d XL |
1495 | let predicates = &self |
1496 | .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name) | |
1497 | .predicates; | |
416331ca XL |
1498 | |
1499 | debug!("find_bound_for_assoc_item: predicates={:#?}", predicates); | |
1500 | ||
3dfed10e | 1501 | let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id); |
532ac7d7 | 1502 | let param_name = tcx.hir().ty_param_name(param_hir_id); |
dfeec247 XL |
1503 | self.one_bound_for_assoc_type( |
1504 | || { | |
6a06907d | 1505 | traits::transitive_bounds_that_define_assoc_type( |
dfeec247 | 1506 | tcx, |
fc512014 XL |
1507 | predicates.iter().filter_map(|(p, _)| { |
1508 | p.to_opt_poly_trait_ref().map(|trait_ref| trait_ref.value) | |
1509 | }), | |
6a06907d | 1510 | assoc_name, |
dfeec247 XL |
1511 | ) |
1512 | }, | |
1513 | || param_name.to_string(), | |
1514 | assoc_name, | |
1515 | span, | |
1516 | || None, | |
1517 | ) | |
9346a6ac AL |
1518 | } |
1519 | ||
a1dfa0c6 | 1520 | // Checks that `bounds` contains exactly one element and reports appropriate |
a7813a04 | 1521 | // errors otherwise. |
dfeec247 XL |
1522 | fn one_bound_for_assoc_type<I>( |
1523 | &self, | |
1524 | all_candidates: impl Fn() -> I, | |
1525 | ty_param_name: impl Fn() -> String, | |
f9f354fc | 1526 | assoc_name: Ident, |
dfeec247 XL |
1527 | span: Span, |
1528 | is_equality: impl Fn() -> Option<String>, | |
1529 | ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> | |
1530 | where | |
1531 | I: Iterator<Item = ty::PolyTraitRef<'tcx>>, | |
a7813a04 | 1532 | { |
dfeec247 XL |
1533 | let mut matching_candidates = all_candidates() |
1534 | .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name)); | |
1535 | ||
1536 | let bound = match matching_candidates.next() { | |
476ff2be SL |
1537 | Some(bound) => bound, |
1538 | None => { | |
dfeec247 XL |
1539 | self.complain_about_assoc_type_not_found( |
1540 | all_candidates, | |
1541 | &ty_param_name(), | |
1542 | assoc_name, | |
1543 | span, | |
1544 | ); | |
476ff2be SL |
1545 | return Err(ErrorReported); |
1546 | } | |
1547 | }; | |
c30ab7b3 | 1548 | |
416331ca XL |
1549 | debug!("one_bound_for_assoc_type: bound = {:?}", bound); |
1550 | ||
dfeec247 | 1551 | if let Some(bound2) = matching_candidates.next() { |
416331ca XL |
1552 | debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2); |
1553 | ||
dfeec247 | 1554 | let is_equality = is_equality(); |
29967ef6 | 1555 | let bounds = array::IntoIter::new([bound, bound2]).chain(matching_candidates); |
dfeec247 XL |
1556 | let mut err = if is_equality.is_some() { |
1557 | // More specific Error Index entry. | |
1558 | struct_span_err!( | |
1559 | self.tcx().sess, | |
1560 | span, | |
1561 | E0222, | |
1562 | "ambiguous associated type `{}` in bounds of `{}`", | |
1563 | assoc_name, | |
1564 | ty_param_name() | |
1565 | ) | |
1566 | } else { | |
1567 | struct_span_err!( | |
1568 | self.tcx().sess, | |
1569 | span, | |
1570 | E0221, | |
1571 | "ambiguous associated type `{}` in bounds of `{}`", | |
1572 | assoc_name, | |
1573 | ty_param_name() | |
1574 | ) | |
1575 | }; | |
7cac9316 | 1576 | err.span_label(span, format!("ambiguous associated type `{}`", assoc_name)); |
9346a6ac | 1577 | |
dfeec247 | 1578 | let mut where_bounds = vec![]; |
476ff2be | 1579 | for bound in bounds { |
74b04a01 | 1580 | let bound_id = bound.def_id(); |
dfeec247 XL |
1581 | let bound_span = self |
1582 | .tcx() | |
74b04a01 XL |
1583 | .associated_items(bound_id) |
1584 | .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id) | |
416331ca | 1585 | .and_then(|item| self.tcx().hir().span_if_local(item.def_id)); |
476ff2be | 1586 | |
dfeec247 XL |
1587 | if let Some(bound_span) = bound_span { |
1588 | err.span_label( | |
1589 | bound_span, | |
1590 | format!( | |
1591 | "ambiguous `{}` from `{}`", | |
1592 | assoc_name, | |
1593 | bound.print_only_trait_path(), | |
1594 | ), | |
1595 | ); | |
1596 | if let Some(constraint) = &is_equality { | |
1597 | where_bounds.push(format!( | |
1598 | " T: {trait}::{assoc} = {constraint}", | |
1599 | trait=bound.print_only_trait_path(), | |
1600 | assoc=assoc_name, | |
1601 | constraint=constraint, | |
1602 | )); | |
1603 | } else { | |
1604 | err.span_suggestion( | |
1605 | span, | |
1606 | "use fully qualified syntax to disambiguate", | |
1607 | format!( | |
1608 | "<{} as {}>::{}", | |
1609 | ty_param_name(), | |
1610 | bound.print_only_trait_path(), | |
1611 | assoc_name, | |
1612 | ), | |
1613 | Applicability::MaybeIncorrect, | |
1614 | ); | |
1615 | } | |
c30ab7b3 | 1616 | } else { |
dfeec247 XL |
1617 | err.note(&format!( |
1618 | "associated type `{}` could derive from `{}`", | |
1619 | ty_param_name(), | |
1620 | bound.print_only_trait_path(), | |
1621 | )); | |
c30ab7b3 | 1622 | } |
a7813a04 | 1623 | } |
dfeec247 XL |
1624 | if !where_bounds.is_empty() { |
1625 | err.help(&format!( | |
1626 | "consider introducing a new type parameter `T` and adding `where` constraints:\ | |
1627 | \n where\n T: {},\n{}", | |
1628 | ty_param_name(), | |
1629 | where_bounds.join(",\n"), | |
1630 | )); | |
1631 | } | |
a7813a04 | 1632 | err.emit(); |
dfeec247 XL |
1633 | if !where_bounds.is_empty() { |
1634 | return Err(ErrorReported); | |
1635 | } | |
9346a6ac | 1636 | } |
ba9703b0 | 1637 | Ok(bound) |
9346a6ac AL |
1638 | } |
1639 | ||
a7813a04 | 1640 | // Create a type from a path to an associated type. |
9fa01778 | 1641 | // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C` |
a1dfa0c6 | 1642 | // and item_segment is the path segment for `D`. We return a type and a def for |
a7813a04 | 1643 | // the whole path. |
9fa01778 | 1644 | // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type |
a1dfa0c6 | 1645 | // parameter or `Self`. |
6a06907d XL |
1646 | // NOTE: When this function starts resolving `Trait::AssocTy` successfully |
1647 | // it should also start reportint the `BARE_TRAIT_OBJECTS` lint. | |
9fa01778 XL |
1648 | pub fn associated_path_to_ty( |
1649 | &self, | |
532ac7d7 | 1650 | hir_ref_id: hir::HirId, |
9fa01778 XL |
1651 | span: Span, |
1652 | qself_ty: Ty<'tcx>, | |
48663c56 | 1653 | qself_res: Res, |
dfeec247 | 1654 | assoc_segment: &hir::PathSegment<'_>, |
9fa01778 | 1655 | permit_variants: bool, |
48663c56 | 1656 | ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> { |
a7813a04 | 1657 | let tcx = self.tcx(); |
9fa01778 | 1658 | let assoc_ident = assoc_segment.ident; |
a7813a04 | 1659 | |
9fa01778 | 1660 | debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident); |
a7813a04 | 1661 | |
9fa01778 XL |
1662 | // Check if we have an enum variant. |
1663 | let mut variant_resolution = None; | |
1b1a35ee | 1664 | if let ty::Adt(adt_def, _) = qself_ty.kind() { |
9fa01778 | 1665 | if adt_def.is_enum() { |
dfeec247 XL |
1666 | let variant_def = adt_def |
1667 | .variants | |
1668 | .iter() | |
1669 | .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)); | |
9fa01778 | 1670 | if let Some(variant_def) = variant_def { |
9fa01778 | 1671 | if permit_variants { |
17df50a5 | 1672 | tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None); |
dfeec247 | 1673 | self.prohibit_generics(slice::from_ref(assoc_segment)); |
48663c56 | 1674 | return Ok((qself_ty, DefKind::Variant, variant_def.def_id)); |
9fa01778 | 1675 | } else { |
48663c56 | 1676 | variant_resolution = Some(variant_def.def_id); |
9fa01778 XL |
1677 | } |
1678 | } | |
1679 | } | |
1680 | } | |
a7813a04 XL |
1681 | |
1682 | // Find the type of the associated item, and the trait where the associated | |
1683 | // item is declared. | |
1b1a35ee XL |
1684 | let bound = match (&qself_ty.kind(), qself_res) { |
1685 | (_, Res::SelfTy(Some(_), Some((impl_def_id, _)))) => { | |
0731742a | 1686 | // `Self` in an impl of a trait -- we have a concrete self type and a |
a7813a04 | 1687 | // trait reference. |
8bb4bdeb XL |
1688 | let trait_ref = match tcx.impl_trait_ref(impl_def_id) { |
1689 | Some(trait_ref) => trait_ref, | |
1690 | None => { | |
1691 | // A cycle error occurred, most likely. | |
48663c56 | 1692 | return Err(ErrorReported); |
8bb4bdeb XL |
1693 | } |
1694 | }; | |
1695 | ||
dfeec247 | 1696 | self.one_bound_for_assoc_type( |
cdc7bbd5 | 1697 | || traits::supertraits(tcx, ty::Binder::bind(trait_ref, tcx)), |
dfeec247 XL |
1698 | || "Self".to_string(), |
1699 | assoc_ident, | |
1700 | span, | |
1701 | || None, | |
1702 | )? | |
c1a9b12d | 1703 | } |
ba9703b0 XL |
1704 | ( |
1705 | &ty::Param(_), | |
1706 | Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did), | |
f9f354fc | 1707 | ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?, |
9fa01778 XL |
1708 | _ => { |
1709 | if variant_resolution.is_some() { | |
1710 | // Variant in type position | |
1711 | let msg = format!("expected type, found variant `{}`", assoc_ident); | |
1712 | tcx.sess.span_err(span, &msg); | |
1713 | } else if qself_ty.is_enum() { | |
dfeec247 XL |
1714 | let mut err = struct_span_err!( |
1715 | tcx.sess, | |
48663c56 | 1716 | assoc_ident.span, |
dfeec247 XL |
1717 | E0599, |
1718 | "no variant named `{}` found for enum `{}`", | |
1719 | assoc_ident, | |
1720 | qself_ty, | |
a1dfa0c6 | 1721 | ); |
48663c56 | 1722 | |
9fa01778 XL |
1723 | let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT"); |
1724 | if let Some(suggested_name) = find_best_match_for_name( | |
fc512014 XL |
1725 | &adt_def |
1726 | .variants | |
1727 | .iter() | |
1728 | .map(|variant| variant.ident.name) | |
1729 | .collect::<Vec<Symbol>>(), | |
3dfed10e | 1730 | assoc_ident.name, |
9fa01778 XL |
1731 | None, |
1732 | ) { | |
1733 | err.span_suggestion( | |
48663c56 XL |
1734 | assoc_ident.span, |
1735 | "there is a variant with a similar name", | |
1736 | suggested_name.to_string(), | |
9fa01778 XL |
1737 | Applicability::MaybeIncorrect, |
1738 | ); | |
1739 | } else { | |
416331ca XL |
1740 | err.span_label( |
1741 | assoc_ident.span, | |
1742 | format!("variant not found in `{}`", qself_ty), | |
1743 | ); | |
48663c56 XL |
1744 | } |
1745 | ||
1746 | if let Some(sp) = tcx.hir().span_if_local(adt_def.did) { | |
ba9703b0 | 1747 | let sp = tcx.sess.source_map().guess_head_span(sp); |
48663c56 | 1748 | err.span_label(sp, format!("variant `{}` not found here", assoc_ident)); |
9fa01778 | 1749 | } |
48663c56 | 1750 | |
9fa01778 XL |
1751 | err.emit(); |
1752 | } else if !qself_ty.references_error() { | |
1753 | // Don't print `TyErr` to the user. | |
48663c56 XL |
1754 | self.report_ambiguous_associated_type( |
1755 | span, | |
1756 | &qself_ty.to_string(), | |
1757 | "Trait", | |
e1599b0c | 1758 | assoc_ident.name, |
48663c56 | 1759 | ); |
9e0c209e | 1760 | } |
48663c56 | 1761 | return Err(ErrorReported); |
9346a6ac | 1762 | } |
a7813a04 | 1763 | }; |
c34b1796 | 1764 | |
83c7162d | 1765 | let trait_did = bound.def_id(); |
dc9dc135 XL |
1766 | let (assoc_ident, def_scope) = |
1767 | tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id); | |
74b04a01 | 1768 | |
ba9703b0 | 1769 | // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead |
74b04a01 | 1770 | // of calling `filter_by_name_and_kind`. |
dfeec247 XL |
1771 | let item = tcx |
1772 | .associated_items(trait_did) | |
74b04a01 | 1773 | .in_definition_order() |
ba9703b0 XL |
1774 | .find(|i| { |
1775 | i.kind.namespace() == Namespace::TypeNS | |
1776 | && i.ident.normalize_to_macros_2_0() == assoc_ident | |
1777 | }) | |
dfeec247 | 1778 | .expect("missing associated type"); |
041b39d2 | 1779 | |
dfeec247 | 1780 | let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound); |
041b39d2 XL |
1781 | let ty = self.normalize_ty(span, ty); |
1782 | ||
dc9dc135 | 1783 | let kind = DefKind::AssocTy; |
7cac9316 | 1784 | if !item.vis.is_accessible_from(def_scope, tcx) { |
ba9703b0 XL |
1785 | let kind = kind.descr(item.def_id); |
1786 | let msg = format!("{} `{}` is private", kind, assoc_ident); | |
1787 | tcx.sess | |
1788 | .struct_span_err(span, &msg) | |
1789 | .span_label(span, &format!("private {}", kind)) | |
1790 | .emit(); | |
7cac9316 | 1791 | } |
17df50a5 | 1792 | tcx.check_stability(item.def_id, Some(hir_ref_id), span, None); |
7cac9316 | 1793 | |
48663c56 | 1794 | if let Some(variant_def_id) = variant_resolution { |
74b04a01 XL |
1795 | tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| { |
1796 | let mut err = lint.build("ambiguous associated item"); | |
1797 | let mut could_refer_to = |kind: DefKind, def_id, also| { | |
1798 | let note_msg = format!( | |
1799 | "`{}` could{} refer to the {} defined here", | |
1800 | assoc_ident, | |
1801 | also, | |
1802 | kind.descr(def_id) | |
1803 | ); | |
1804 | err.span_note(tcx.def_span(def_id), ¬e_msg); | |
1805 | }; | |
9fa01778 | 1806 | |
74b04a01 XL |
1807 | could_refer_to(DefKind::Variant, variant_def_id, ""); |
1808 | could_refer_to(kind, item.def_id, " also"); | |
1809 | ||
1810 | err.span_suggestion( | |
1811 | span, | |
1812 | "use fully-qualified syntax", | |
1813 | format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident), | |
1814 | Applicability::MachineApplicable, | |
dfeec247 | 1815 | ); |
9fa01778 | 1816 | |
74b04a01 XL |
1817 | err.emit(); |
1818 | }); | |
9fa01778 | 1819 | } |
48663c56 | 1820 | Ok((ty, kind, item.def_id)) |
a7813a04 | 1821 | } |
1a4d82fc | 1822 | |
dfeec247 XL |
1823 | fn qpath_to_ty( |
1824 | &self, | |
1825 | span: Span, | |
1826 | opt_self_ty: Option<Ty<'tcx>>, | |
1827 | item_def_id: DefId, | |
1828 | trait_segment: &hir::PathSegment<'_>, | |
1829 | item_segment: &hir::PathSegment<'_>, | |
1830 | ) -> Ty<'tcx> { | |
a7813a04 | 1831 | let tcx = self.tcx(); |
60c5eb7d | 1832 | |
532ac7d7 | 1833 | let trait_def_id = tcx.parent(item_def_id).unwrap(); |
1a4d82fc | 1834 | |
60c5eb7d XL |
1835 | debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id); |
1836 | ||
a7813a04 XL |
1837 | let self_ty = if let Some(ty) = opt_self_ty { |
1838 | ty | |
1839 | } else { | |
532ac7d7 | 1840 | let path_str = tcx.def_path_str(trait_def_id); |
60c5eb7d XL |
1841 | |
1842 | let def_id = self.item_def_id(); | |
1843 | ||
1844 | debug!("qpath_to_ty: self.item_def_id()={:?}", def_id); | |
1845 | ||
dfeec247 | 1846 | let parent_def_id = def_id |
f9f354fc | 1847 | .and_then(|def_id| { |
3dfed10e | 1848 | def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)) |
f9f354fc | 1849 | }) |
ba9703b0 | 1850 | .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id()); |
60c5eb7d XL |
1851 | |
1852 | debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id); | |
1853 | ||
1854 | // If the trait in segment is the same as the trait defining the item, | |
1855 | // use the `<Self as ..>` syntax in the error. | |
1856 | let is_part_of_self_trait_constraints = def_id == Some(trait_def_id); | |
1857 | let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id); | |
1858 | ||
1859 | let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait { | |
1860 | "Self" | |
1861 | } else { | |
1862 | "Type" | |
1863 | }; | |
1864 | ||
48663c56 XL |
1865 | self.report_ambiguous_associated_type( |
1866 | span, | |
60c5eb7d | 1867 | type_name, |
48663c56 | 1868 | &path_str, |
e1599b0c | 1869 | item_segment.ident.name, |
48663c56 | 1870 | ); |
f035d41b | 1871 | return tcx.ty_error(); |
a7813a04 | 1872 | }; |
1a4d82fc | 1873 | |
a7813a04 | 1874 | debug!("qpath_to_ty: self_type={:?}", self_ty); |
1a4d82fc | 1875 | |
dfeec247 XL |
1876 | let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment); |
1877 | ||
1878 | let item_substs = self.create_substs_for_associated_item( | |
1879 | tcx, | |
1880 | span, | |
1881 | item_def_id, | |
1882 | item_segment, | |
1883 | trait_ref.substs, | |
1884 | ); | |
1a4d82fc | 1885 | |
a7813a04 | 1886 | debug!("qpath_to_ty: trait_ref={:?}", trait_ref); |
85aaf69f | 1887 | |
dfeec247 | 1888 | self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs)) |
8bb4bdeb XL |
1889 | } |
1890 | ||
dfeec247 XL |
1891 | pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>( |
1892 | &self, | |
1893 | segments: T, | |
1894 | ) -> bool { | |
0731742a | 1895 | let mut has_err = false; |
8bb4bdeb | 1896 | for segment in segments { |
dc9dc135 | 1897 | let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false); |
5869c6ff | 1898 | for arg in segment.args().args { |
dc9dc135 XL |
1899 | let (span, kind) = match arg { |
1900 | hir::GenericArg::Lifetime(lt) => { | |
dfeec247 XL |
1901 | if err_for_lt { |
1902 | continue; | |
1903 | } | |
dc9dc135 XL |
1904 | err_for_lt = true; |
1905 | has_err = true; | |
1906 | (lt.span, "lifetime") | |
8faf50e0 | 1907 | } |
dc9dc135 | 1908 | hir::GenericArg::Type(ty) => { |
dfeec247 XL |
1909 | if err_for_ty { |
1910 | continue; | |
1911 | } | |
dc9dc135 XL |
1912 | err_for_ty = true; |
1913 | has_err = true; | |
1914 | (ty.span, "type") | |
1915 | } | |
1916 | hir::GenericArg::Const(ct) => { | |
dfeec247 XL |
1917 | if err_for_ct { |
1918 | continue; | |
1919 | } | |
dc9dc135 | 1920 | err_for_ct = true; |
ba9703b0 | 1921 | has_err = true; |
dc9dc135 XL |
1922 | (ct.span, "const") |
1923 | } | |
1924 | }; | |
1925 | let mut err = struct_span_err!( | |
1926 | self.tcx().sess, | |
1927 | span, | |
1928 | E0109, | |
1929 | "{} arguments are not allowed for this type", | |
1930 | kind, | |
1931 | ); | |
1932 | err.span_label(span, format!("{} argument not allowed", kind)); | |
1933 | err.emit(); | |
1934 | if err_for_lt && err_for_ty && err_for_ct { | |
ea8adc8c XL |
1935 | break; |
1936 | } | |
dc9dc135 | 1937 | } |
74b04a01 XL |
1938 | |
1939 | // Only emit the first error to avoid overloading the user with error messages. | |
5869c6ff | 1940 | if let [binding, ..] = segment.args().bindings { |
dc9dc135 XL |
1941 | has_err = true; |
1942 | Self::prohibit_assoc_ty_binding(self.tcx(), binding.span); | |
dc9dc135 | 1943 | } |
8bb4bdeb | 1944 | } |
0731742a | 1945 | has_err |
8bb4bdeb XL |
1946 | } |
1947 | ||
48663c56 XL |
1948 | // FIXME(eddyb, varkor) handle type paths here too, not just value ones. |
1949 | pub fn def_ids_for_value_path_segments( | |
1950 | &self, | |
dfeec247 | 1951 | segments: &[hir::PathSegment<'_>], |
48663c56 XL |
1952 | self_ty: Option<Ty<'tcx>>, |
1953 | kind: DefKind, | |
1954 | def_id: DefId, | |
1955 | ) -> Vec<PathSeg> { | |
0731742a XL |
1956 | // We need to extract the type parameters supplied by the user in |
1957 | // the path `path`. Due to the current setup, this is a bit of a | |
1958 | // tricky-process; the problem is that resolve only tells us the | |
1959 | // end-point of the path resolution, and not the intermediate steps. | |
1960 | // Luckily, we can (at least for now) deduce the intermediate steps | |
1961 | // just from the end-point. | |
1962 | // | |
1963 | // There are basically five cases to consider: | |
1964 | // | |
1965 | // 1. Reference to a constructor of a struct: | |
1966 | // | |
1967 | // struct Foo<T>(...) | |
1968 | // | |
1969 | // In this case, the parameters are declared in the type space. | |
1970 | // | |
1971 | // 2. Reference to a constructor of an enum variant: | |
1972 | // | |
1973 | // enum E<T> { Foo(...) } | |
1974 | // | |
1975 | // In this case, the parameters are defined in the type space, | |
1976 | // but may be specified either on the type or the variant. | |
1977 | // | |
1978 | // 3. Reference to a fn item or a free constant: | |
1979 | // | |
1980 | // fn foo<T>() { } | |
1981 | // | |
1982 | // In this case, the path will again always have the form | |
1983 | // `a::b::foo::<T>` where only the final segment should have | |
1984 | // type parameters. However, in this case, those parameters are | |
1985 | // declared on a value, and hence are in the `FnSpace`. | |
1986 | // | |
1987 | // 4. Reference to a method or an associated constant: | |
1988 | // | |
1989 | // impl<A> SomeStruct<A> { | |
1990 | // fn foo<B>(...) | |
1991 | // } | |
1992 | // | |
1993 | // Here we can have a path like | |
1994 | // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters | |
1995 | // may appear in two places. The penultimate segment, | |
1996 | // `SomeStruct::<A>`, contains parameters in TypeSpace, and the | |
1997 | // final segment, `foo::<B>` contains parameters in fn space. | |
1998 | // | |
0731742a XL |
1999 | // The first step then is to categorize the segments appropriately. |
2000 | ||
2001 | let tcx = self.tcx(); | |
2002 | ||
2003 | assert!(!segments.is_empty()); | |
2004 | let last = segments.len() - 1; | |
2005 | ||
2006 | let mut path_segs = vec![]; | |
2007 | ||
48663c56 | 2008 | match kind { |
0731742a | 2009 | // Case 1. Reference to a struct constructor. |
48663c56 | 2010 | DefKind::Ctor(CtorOf::Struct, ..) => { |
0731742a XL |
2011 | // Everything but the final segment should have no |
2012 | // parameters at all. | |
2013 | let generics = tcx.generics_of(def_id); | |
2014 | // Variant and struct constructors use the | |
2015 | // generics of their parent type definition. | |
2016 | let generics_def_id = generics.parent.unwrap_or(def_id); | |
2017 | path_segs.push(PathSeg(generics_def_id, last)); | |
2018 | } | |
2019 | ||
2020 | // Case 2. Reference to a variant constructor. | |
dfeec247 | 2021 | DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => { |
0731742a XL |
2022 | let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap()); |
2023 | let (generics_def_id, index) = if let Some(adt_def) = adt_def { | |
2024 | debug_assert!(adt_def.is_enum()); | |
2025 | (adt_def.did, last) | |
2026 | } else if last >= 1 && segments[last - 1].args.is_some() { | |
2027 | // Everything but the penultimate segment should have no | |
2028 | // parameters at all. | |
532ac7d7 XL |
2029 | let mut def_id = def_id; |
2030 | ||
48663c56 XL |
2031 | // `DefKind::Ctor` -> `DefKind::Variant` |
2032 | if let DefKind::Ctor(..) = kind { | |
532ac7d7 XL |
2033 | def_id = tcx.parent(def_id).unwrap() |
2034 | } | |
2035 | ||
48663c56 | 2036 | // `DefKind::Variant` -> `DefKind::Enum` |
532ac7d7 | 2037 | let enum_def_id = tcx.parent(def_id).unwrap(); |
0731742a XL |
2038 | (enum_def_id, last - 1) |
2039 | } else { | |
2040 | // FIXME: lint here recommending `Enum::<...>::Variant` form | |
2041 | // instead of `Enum::Variant::<...>` form. | |
2042 | ||
2043 | // Everything but the final segment should have no | |
2044 | // parameters at all. | |
2045 | let generics = tcx.generics_of(def_id); | |
2046 | // Variant and struct constructors use the | |
2047 | // generics of their parent type definition. | |
2048 | (generics.parent.unwrap_or(def_id), last) | |
2049 | }; | |
2050 | path_segs.push(PathSeg(generics_def_id, index)); | |
2051 | } | |
2052 | ||
2053 | // Case 3. Reference to a top-level value. | |
dfeec247 | 2054 | DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => { |
0731742a XL |
2055 | path_segs.push(PathSeg(def_id, last)); |
2056 | } | |
2057 | ||
2058 | // Case 4. Reference to a method or associated const. | |
ba9703b0 | 2059 | DefKind::AssocFn | DefKind::AssocConst => { |
0731742a XL |
2060 | if segments.len() >= 2 { |
2061 | let generics = tcx.generics_of(def_id); | |
2062 | path_segs.push(PathSeg(generics.parent.unwrap(), last - 1)); | |
2063 | } | |
2064 | path_segs.push(PathSeg(def_id, last)); | |
2065 | } | |
2066 | ||
48663c56 | 2067 | kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id), |
0731742a XL |
2068 | } |
2069 | ||
2070 | debug!("path_segs = {:?}", path_segs); | |
2071 | ||
2072 | path_segs | |
2073 | } | |
2074 | ||
a1dfa0c6 | 2075 | // Check a type `Path` and convert it to a `Ty`. |
dfeec247 XL |
2076 | pub fn res_to_ty( |
2077 | &self, | |
2078 | opt_self_ty: Option<Ty<'tcx>>, | |
2079 | path: &hir::Path<'_>, | |
2080 | permit_variants: bool, | |
2081 | ) -> Ty<'tcx> { | |
a7813a04 XL |
2082 | let tcx = self.tcx(); |
2083 | ||
dfeec247 XL |
2084 | debug!( |
2085 | "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})", | |
2086 | path.res, opt_self_ty, path.segments | |
2087 | ); | |
a7813a04 | 2088 | |
476ff2be | 2089 | let span = path.span; |
48663c56 | 2090 | match path.res { |
416331ca | 2091 | Res::Def(DefKind::OpaqueTy, did) => { |
dc9dc135 | 2092 | // Check for desugared `impl Trait`. |
0bf4aa26 | 2093 | assert!(ty::is_impl_trait_defn(tcx, did).is_none()); |
8faf50e0 XL |
2094 | let item_segment = path.segments.split_last().unwrap(); |
2095 | self.prohibit_generics(item_segment.1); | |
2096 | let substs = self.ast_path_substs_for_ty(span, did, item_segment.0); | |
dfeec247 | 2097 | self.normalize_ty(span, tcx.mk_opaque(did, substs)) |
8faf50e0 | 2098 | } |
ba9703b0 XL |
2099 | Res::Def( |
2100 | DefKind::Enum | |
2101 | | DefKind::TyAlias | |
2102 | | DefKind::Struct | |
2103 | | DefKind::Union | |
2104 | | DefKind::ForeignTy, | |
2105 | did, | |
2106 | ) => { | |
476ff2be | 2107 | assert_eq!(opt_self_ty, None); |
8faf50e0 | 2108 | self.prohibit_generics(path.segments.split_last().unwrap().1); |
32a655c1 | 2109 | self.ast_path_to_ty(span, did, path.segments.last().unwrap()) |
a7813a04 | 2110 | } |
48663c56 | 2111 | Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => { |
c30ab7b3 SL |
2112 | // Convert "variant type" as if it were a real type. |
2113 | // The resulting `Ty` is type of the variant's enum for now. | |
476ff2be | 2114 | assert_eq!(opt_self_ty, None); |
0731742a | 2115 | |
48663c56 XL |
2116 | let path_segs = |
2117 | self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id); | |
0731742a XL |
2118 | let generic_segs: FxHashSet<_> = |
2119 | path_segs.iter().map(|PathSeg(_, index)| index).collect(); | |
dfeec247 XL |
2120 | self.prohibit_generics(path.segments.iter().enumerate().filter_map( |
2121 | |(index, seg)| { | |
2122 | if !generic_segs.contains(&index) { Some(seg) } else { None } | |
2123 | }, | |
2124 | )); | |
0731742a XL |
2125 | |
2126 | let PathSeg(def_id, index) = path_segs.last().unwrap(); | |
2127 | self.ast_path_to_ty(span, *def_id, &path.segments[*index]) | |
c30ab7b3 | 2128 | } |
dc9dc135 | 2129 | Res::Def(DefKind::TyParam, def_id) => { |
476ff2be | 2130 | assert_eq!(opt_self_ty, None); |
dfeec247 | 2131 | self.prohibit_generics(path.segments); |
9e0c209e | 2132 | |
3dfed10e | 2133 | let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); |
dc9dc135 | 2134 | let item_id = tcx.hir().get_parent_node(hir_id); |
416331ca | 2135 | let item_def_id = tcx.hir().local_def_id(item_id); |
7cac9316 | 2136 | let generics = tcx.generics_of(item_def_id); |
dc9dc135 | 2137 | let index = generics.param_def_id_to_index[&def_id]; |
e74abb32 | 2138 | tcx.mk_ty_param(index, tcx.hir().name(hir_id)) |
a7813a04 | 2139 | } |
dc9dc135 XL |
2140 | Res::SelfTy(Some(_), None) => { |
2141 | // `Self` in trait or type alias. | |
476ff2be | 2142 | assert_eq!(opt_self_ty, None); |
dfeec247 | 2143 | self.prohibit_generics(path.segments); |
e1599b0c | 2144 | tcx.types.self_param |
9346a6ac | 2145 | } |
1b1a35ee | 2146 | Res::SelfTy(_, Some((def_id, forbid_generic))) => { |
dc9dc135 | 2147 | // `Self` in impl (we know the concrete type). |
476ff2be | 2148 | assert_eq!(opt_self_ty, None); |
dfeec247 | 2149 | self.prohibit_generics(path.segments); |
dc9dc135 | 2150 | // Try to evaluate any array length constants. |
1b1a35ee XL |
2151 | let normalized_ty = self.normalize_ty(span, tcx.at(span).type_of(def_id)); |
2152 | if forbid_generic && normalized_ty.needs_subst() { | |
2153 | let mut err = tcx.sess.struct_span_err( | |
2154 | path.span, | |
2155 | "generic `Self` types are currently not permitted in anonymous constants", | |
2156 | ); | |
2157 | if let Some(hir::Node::Item(&hir::Item { | |
5869c6ff | 2158 | kind: hir::ItemKind::Impl(ref impl_), |
1b1a35ee XL |
2159 | .. |
2160 | })) = tcx.hir().get_if_local(def_id) | |
2161 | { | |
5869c6ff | 2162 | err.span_note(impl_.self_ty.span, "not a concrete type"); |
1b1a35ee XL |
2163 | } |
2164 | err.emit(); | |
2165 | tcx.ty_error() | |
2166 | } else { | |
2167 | normalized_ty | |
2168 | } | |
a7813a04 | 2169 | } |
dc9dc135 | 2170 | Res::Def(DefKind::AssocTy, def_id) => { |
0731742a XL |
2171 | debug_assert!(path.segments.len() >= 2); |
2172 | self.prohibit_generics(&path.segments[..path.segments.len() - 2]); | |
dfeec247 XL |
2173 | self.qpath_to_ty( |
2174 | span, | |
2175 | opt_self_ty, | |
2176 | def_id, | |
2177 | &path.segments[path.segments.len() - 2], | |
2178 | path.segments.last().unwrap(), | |
2179 | ) | |
a7813a04 | 2180 | } |
48663c56 | 2181 | Res::PrimTy(prim_ty) => { |
476ff2be | 2182 | assert_eq!(opt_self_ty, None); |
dfeec247 | 2183 | self.prohibit_generics(path.segments); |
8bb4bdeb | 2184 | match prim_ty { |
dfeec247 XL |
2185 | hir::PrimTy::Bool => tcx.types.bool, |
2186 | hir::PrimTy::Char => tcx.types.char, | |
5869c6ff XL |
2187 | hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)), |
2188 | hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)), | |
2189 | hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)), | |
f035d41b | 2190 | hir::PrimTy::Str => tcx.types.str_, |
8bb4bdeb | 2191 | } |
a7813a04 | 2192 | } |
48663c56 | 2193 | Res::Err => { |
a7813a04 | 2194 | self.set_tainted_by_errors(); |
f035d41b | 2195 | self.tcx().ty_error() |
a7813a04 | 2196 | } |
dfeec247 | 2197 | _ => span_bug!(span, "unexpected resolution: {:?}", path.res), |
c34b1796 | 2198 | } |
9346a6ac | 2199 | } |
c34b1796 | 2200 | |
a7813a04 XL |
2201 | /// Parses the programmer's textual representation of a type into our |
2202 | /// internal notion of a type. | |
dfeec247 | 2203 | pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> { |
3dfed10e XL |
2204 | self.ast_ty_to_ty_inner(ast_ty, false) |
2205 | } | |
2206 | ||
2207 | /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait | |
2208 | /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors. | |
cdc7bbd5 | 2209 | #[tracing::instrument(level = "debug", skip(self))] |
3dfed10e | 2210 | fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx> { |
a7813a04 | 2211 | let tcx = self.tcx(); |
1a4d82fc | 2212 | |
e74abb32 | 2213 | let result_ty = match ast_ty.kind { |
dfeec247 | 2214 | hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)), |
8faf50e0 | 2215 | hir::TyKind::Ptr(ref mt) => { |
dfeec247 | 2216 | tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl }) |
a7813a04 | 2217 | } |
8faf50e0 | 2218 | hir::TyKind::Rptr(ref region, ref mt) => { |
32a655c1 | 2219 | let r = self.ast_region_to_region(region, None); |
cdc7bbd5 | 2220 | debug!(?r); |
3dfed10e | 2221 | let t = self.ast_ty_to_ty_inner(&mt.ty, true); |
dfeec247 | 2222 | tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl }) |
a7813a04 | 2223 | } |
dfeec247 | 2224 | hir::TyKind::Never => tcx.types.never, |
8faf50e0 | 2225 | hir::TyKind::Tup(ref fields) => { |
0531ce1d | 2226 | tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t))) |
a7813a04 | 2227 | } |
8faf50e0 | 2228 | hir::TyKind::BareFn(ref bf) => { |
532ac7d7 | 2229 | require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span); |
6a06907d | 2230 | |
74b04a01 | 2231 | tcx.mk_fn_ptr(self.ty_of_fn( |
cdc7bbd5 | 2232 | ast_ty.hir_id, |
74b04a01 XL |
2233 | bf.unsafety, |
2234 | bf.abi, | |
2235 | &bf.decl, | |
2236 | &hir::Generics::empty(), | |
2237 | None, | |
6a06907d | 2238 | Some(ast_ty), |
74b04a01 | 2239 | )) |
1a4d82fc | 2240 | } |
6a06907d | 2241 | hir::TyKind::TraitObject(ref bounds, ref lifetime, _) => { |
3dfed10e | 2242 | self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed) |
a7813a04 | 2243 | } |
8faf50e0 | 2244 | hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => { |
cdc7bbd5 | 2245 | debug!(?maybe_qself, ?path); |
dfeec247 | 2246 | let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself)); |
48663c56 | 2247 | self.res_to_ty(opt_self_ty, path, false) |
476ff2be | 2248 | } |
f035d41b | 2249 | hir::TyKind::OpaqueDef(item_id, ref lifetimes) => { |
6a06907d XL |
2250 | let opaque_ty = tcx.hir().item(item_id); |
2251 | let def_id = item_id.def_id.to_def_id(); | |
f035d41b XL |
2252 | |
2253 | match opaque_ty.kind { | |
2254 | hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => { | |
2255 | self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some()) | |
2256 | } | |
2257 | ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), | |
2258 | } | |
dc9dc135 | 2259 | } |
8faf50e0 | 2260 | hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => { |
cdc7bbd5 | 2261 | debug!(?qself, ?segment); |
32a655c1 | 2262 | let ty = self.ast_ty_to_ty(qself); |
c34b1796 | 2263 | |
e74abb32 | 2264 | let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind { |
48663c56 | 2265 | path.res |
476ff2be | 2266 | } else { |
48663c56 | 2267 | Res::Err |
476ff2be | 2268 | }; |
48663c56 | 2269 | self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false) |
dfeec247 | 2270 | .map(|(ty, _, _)| ty) |
f035d41b | 2271 | .unwrap_or_else(|_| tcx.ty_error()) |
a7813a04 | 2272 | } |
3dfed10e XL |
2273 | hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => { |
2274 | let def_id = tcx.require_lang_item(lang_item, Some(span)); | |
cdc7bbd5 | 2275 | let (substs, _) = self.create_substs_for_ast_path( |
3dfed10e XL |
2276 | span, |
2277 | def_id, | |
2278 | &[], | |
5869c6ff | 2279 | &hir::PathSegment::invalid(), |
3dfed10e XL |
2280 | &GenericArgs::none(), |
2281 | true, | |
2282 | None, | |
2283 | ); | |
2284 | self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs)) | |
2285 | } | |
8faf50e0 | 2286 | hir::TyKind::Array(ref ty, ref length) => { |
f9f354fc | 2287 | let length_def_id = tcx.hir().local_def_id(length.hir_id); |
ba9703b0 | 2288 | let length = ty::Const::from_anon_const(tcx, length_def_id); |
b7449926 | 2289 | let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length)); |
ea8adc8c | 2290 | self.normalize_ty(ast_ty.span, array_ty) |
1a4d82fc | 2291 | } |
cdc7bbd5 | 2292 | hir::TyKind::Typeof(ref e) => { |
1b1a35ee | 2293 | tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span }); |
cdc7bbd5 | 2294 | tcx.type_of(tcx.hir().local_def_id(e.hir_id)) |
a7813a04 | 2295 | } |
8faf50e0 | 2296 | hir::TyKind::Infer => { |
b7449926 | 2297 | // Infer also appears as the type of arguments or return |
8faf50e0 | 2298 | // values in a ExprKind::Closure, or as |
a7813a04 XL |
2299 | // the type of local variables. Both of these cases are |
2300 | // handled specially and will not descend into this routine. | |
dc9dc135 | 2301 | self.ty_infer(None, ast_ty.span) |
cc61c64b | 2302 | } |
f035d41b | 2303 | hir::TyKind::Err => tcx.ty_error(), |
a7813a04 | 2304 | }; |
1a4d82fc | 2305 | |
cdc7bbd5 | 2306 | debug!(?result_ty); |
dc9dc135 | 2307 | |
ea8adc8c | 2308 | self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span); |
a7813a04 | 2309 | result_ty |
1a4d82fc | 2310 | } |
1a4d82fc | 2311 | |
cdc7bbd5 | 2312 | fn impl_trait_ty_to_ty( |
94b46f34 XL |
2313 | &self, |
2314 | def_id: DefId, | |
dfeec247 | 2315 | lifetimes: &[hir::GenericArg<'_>], |
f035d41b | 2316 | replace_parent_lifetimes: bool, |
94b46f34 | 2317 | ) -> Ty<'tcx> { |
ff7c6d11 XL |
2318 | debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes); |
2319 | let tcx = self.tcx(); | |
94b46f34 | 2320 | |
ff7c6d11 XL |
2321 | let generics = tcx.generics_of(def_id); |
2322 | ||
ff7c6d11 | 2323 | debug!("impl_trait_ty_to_ty: generics={:?}", generics); |
532ac7d7 | 2324 | let substs = InternalSubsts::for_item(tcx, def_id, |param, _| { |
94b46f34 XL |
2325 | if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) { |
2326 | // Our own parameters are the resolved lifetimes. | |
2327 | match param.kind { | |
2328 | GenericParamDefKind::Lifetime => { | |
8faf50e0 XL |
2329 | if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] { |
2330 | self.ast_region_to_region(lifetime, None).into() | |
2331 | } else { | |
2332 | bug!() | |
2333 | } | |
94b46f34 | 2334 | } |
dfeec247 | 2335 | _ => bug!(), |
94b46f34 XL |
2336 | } |
2337 | } else { | |
94b46f34 | 2338 | match param.kind { |
f035d41b XL |
2339 | // For RPIT (return position impl trait), only lifetimes |
2340 | // mentioned in the impl Trait predicate are captured by | |
2341 | // the opaque type, so the lifetime parameters from the | |
2342 | // parent item need to be replaced with `'static`. | |
2343 | // | |
2344 | // For `impl Trait` in the types of statics, constants, | |
2345 | // locals and type aliases. These capture all parent | |
2346 | // lifetimes, so they can use their identity subst. | |
2347 | GenericParamDefKind::Lifetime if replace_parent_lifetimes => { | |
2348 | tcx.lifetimes.re_static.into() | |
2349 | } | |
dfeec247 | 2350 | _ => tcx.mk_param_from_def(param), |
ff7c6d11 XL |
2351 | } |
2352 | } | |
94b46f34 | 2353 | }); |
dc9dc135 | 2354 | debug!("impl_trait_ty_to_ty: substs={:?}", substs); |
ff7c6d11 | 2355 | |
b7449926 | 2356 | let ty = tcx.mk_opaque(def_id, substs); |
94b46f34 XL |
2357 | debug!("impl_trait_ty_to_ty: {}", ty); |
2358 | ty | |
ff7c6d11 XL |
2359 | } |
2360 | ||
dfeec247 | 2361 | pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> { |
e74abb32 | 2362 | match ty.kind { |
8faf50e0 | 2363 | hir::TyKind::Infer if expected_ty.is_some() => { |
ea8adc8c XL |
2364 | self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span); |
2365 | expected_ty.unwrap() | |
2366 | } | |
32a655c1 | 2367 | _ => self.ast_ty_to_ty(ty), |
a7813a04 XL |
2368 | } |
2369 | } | |
1a4d82fc | 2370 | |
dfeec247 XL |
2371 | pub fn ty_of_fn( |
2372 | &self, | |
cdc7bbd5 | 2373 | hir_id: hir::HirId, |
dfeec247 XL |
2374 | unsafety: hir::Unsafety, |
2375 | abi: abi::Abi, | |
2376 | decl: &hir::FnDecl<'_>, | |
74b04a01 | 2377 | generics: &hir::Generics<'_>, |
dfeec247 | 2378 | ident_span: Option<Span>, |
6a06907d | 2379 | hir_ty: Option<&hir::Ty<'_>>, |
dfeec247 | 2380 | ) -> ty::PolyFnSig<'tcx> { |
32a655c1 | 2381 | debug!("ty_of_fn"); |
1a4d82fc | 2382 | |
ea8adc8c | 2383 | let tcx = self.tcx(); |
cdc7bbd5 XL |
2384 | let bound_vars = tcx.late_bound_vars(hir_id); |
2385 | debug!(?bound_vars); | |
1a4d82fc | 2386 | |
74b04a01 | 2387 | // We proactively collect all the inferred type params to emit a single error per fn def. |
dfeec247 XL |
2388 | let mut visitor = PlaceholderHirTyCollector::default(); |
2389 | for ty in decl.inputs { | |
2390 | visitor.visit_ty(ty); | |
2391 | } | |
74b04a01 XL |
2392 | walk_generics(&mut visitor, generics); |
2393 | ||
dfeec247 | 2394 | let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None)); |
a7813a04 | 2395 | let output_ty = match decl.output { |
74b04a01 | 2396 | hir::FnRetTy::Return(ref output) => { |
dfeec247 XL |
2397 | visitor.visit_ty(output); |
2398 | self.ast_ty_to_ty(output) | |
2399 | } | |
74b04a01 | 2400 | hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(), |
a7813a04 | 2401 | }; |
1a4d82fc | 2402 | |
32a655c1 | 2403 | debug!("ty_of_fn: output_ty={:?}", output_ty); |
9e0c209e | 2404 | |
cdc7bbd5 XL |
2405 | let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi); |
2406 | let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars); | |
dfeec247 | 2407 | |
3dfed10e | 2408 | if !self.allow_ty_infer() { |
dfeec247 XL |
2409 | // We always collect the spans for placeholder types when evaluating `fn`s, but we |
2410 | // only want to emit an error complaining about them if infer types (`_`) are not | |
ba9703b0 XL |
2411 | // allowed. `allow_ty_infer` gates this behavior. We check for the presence of |
2412 | // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`. | |
6a06907d | 2413 | |
dfeec247 XL |
2414 | crate::collect::placeholder_type_error( |
2415 | tcx, | |
3dfed10e | 2416 | ident_span.map(|sp| sp.shrink_to_hi()), |
6a06907d | 2417 | generics.params, |
dfeec247 | 2418 | visitor.0, |
ba9703b0 | 2419 | true, |
6a06907d | 2420 | hir_ty, |
dfeec247 XL |
2421 | ); |
2422 | } | |
ea8adc8c XL |
2423 | |
2424 | // Find any late-bound regions declared in return type that do | |
0bf4aa26 | 2425 | // not appear in the arguments. These are not well-formed. |
ea8adc8c XL |
2426 | // |
2427 | // Example: | |
2428 | // for<'a> fn() -> &'a str <-- 'a is bad | |
2429 | // for<'a> fn(&'a String) -> &'a str <-- 'a is ok | |
2430 | let inputs = bare_fn_ty.inputs(); | |
dfeec247 XL |
2431 | let late_bound_in_args = |
2432 | tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned())); | |
ea8adc8c XL |
2433 | let output = bare_fn_ty.output(); |
2434 | let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output); | |
3dfed10e XL |
2435 | |
2436 | self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| { | |
2437 | struct_span_err!( | |
dfeec247 XL |
2438 | tcx.sess, |
2439 | decl.output.span(), | |
2440 | E0581, | |
3dfed10e XL |
2441 | "return type references {}, which is not constrained by the fn input types", |
2442 | br_name | |
2443 | ) | |
2444 | }); | |
2445 | ||
2446 | bare_fn_ty | |
2447 | } | |
2448 | ||
2449 | fn validate_late_bound_regions( | |
2450 | &self, | |
fc512014 XL |
2451 | constrained_regions: FxHashSet<ty::BoundRegionKind>, |
2452 | referenced_regions: FxHashSet<ty::BoundRegionKind>, | |
3dfed10e XL |
2453 | generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>, |
2454 | ) { | |
2455 | for br in referenced_regions.difference(&constrained_regions) { | |
2456 | let br_name = match *br { | |
2457 | ty::BrNamed(_, name) => format!("lifetime `{}`", name), | |
2458 | ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(), | |
2459 | }; | |
2460 | ||
2461 | let mut err = generate_err(&br_name); | |
2462 | ||
2c00a5a8 XL |
2463 | if let ty::BrAnon(_) = *br { |
2464 | // The only way for an anonymous lifetime to wind up | |
2465 | // in the return type but **also** be unconstrained is | |
2466 | // if it only appears in "associated types" in the | |
3dfed10e | 2467 | // input. See #47511 and #62200 for examples. In this case, |
2c00a5a8 XL |
2468 | // though we can easily give a hint that ought to be |
2469 | // relevant. | |
dfeec247 | 2470 | err.note( |
74b04a01 | 2471 | "lifetimes appearing in an associated type are not considered constrained", |
dfeec247 | 2472 | ); |
2c00a5a8 | 2473 | } |
3dfed10e | 2474 | |
2c00a5a8 | 2475 | err.emit(); |
ea8adc8c | 2476 | } |
a7813a04 | 2477 | } |
1a4d82fc | 2478 | |
a7813a04 XL |
2479 | /// Given the bounds on an object, determines what single region bound (if any) we can |
2480 | /// use to summarize this type. The basic idea is that we will use the bound the user | |
2481 | /// provided, if they provided one, and otherwise search the supertypes of trait bounds | |
2482 | /// for region bounds. It may be that we can derive no bound at all, in which case | |
2483 | /// we return `None`. | |
dfeec247 XL |
2484 | fn compute_object_lifetime_bound( |
2485 | &self, | |
a7813a04 | 2486 | span: Span, |
cdc7bbd5 | 2487 | existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, |
dfeec247 | 2488 | ) -> Option<ty::Region<'tcx>> // if None, use the default |
a7813a04 XL |
2489 | { |
2490 | let tcx = self.tcx(); | |
85aaf69f | 2491 | |
dfeec247 | 2492 | debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates); |
1a4d82fc | 2493 | |
a7813a04 XL |
2494 | // No explicit region bound specified. Therefore, examine trait |
2495 | // bounds and see if we can derive region bounds from those. | |
dfeec247 | 2496 | let derived_region_bounds = object_region_bounds(tcx, existential_predicates); |
1a4d82fc | 2497 | |
a7813a04 XL |
2498 | // If there are no derived region bounds, then report back that we |
2499 | // can find no region bound. The caller will use the default. | |
2500 | if derived_region_bounds.is_empty() { | |
2501 | return None; | |
2502 | } | |
1a4d82fc | 2503 | |
a7813a04 XL |
2504 | // If any of the derived region bounds are 'static, that is always |
2505 | // the best choice. | |
9e0c209e | 2506 | if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) { |
48663c56 | 2507 | return Some(tcx.lifetimes.re_static); |
a7813a04 | 2508 | } |
1a4d82fc | 2509 | |
a7813a04 XL |
2510 | // Determine whether there is exactly one unique region in the set |
2511 | // of derived region bounds. If so, use that. Otherwise, report an | |
2512 | // error. | |
2513 | let r = derived_region_bounds[0]; | |
2514 | if derived_region_bounds[1..].iter().any(|r1| r != *r1) { | |
1b1a35ee | 2515 | tcx.sess.emit_err(AmbiguousLifetimeBound { span }); |
a7813a04 | 2516 | } |
ba9703b0 | 2517 | Some(r) |
1a4d82fc | 2518 | } |
1a4d82fc | 2519 | } |