1 use super::{AnonymousLifetimeMode, ImplTraitContext, LoweringContext, ParamMode};
2 use super::{GenericArgsCtor, ParenthesizedGenericArgs};
4 use rustc_ast::{self as ast, *};
5 use rustc_errors::{struct_span_err, Applicability};
7 use rustc_hir::def::{DefKind, PartialRes, Res};
8 use rustc_hir::def_id::DefId;
9 use rustc_hir::GenericArg;
10 use rustc_span::symbol::Ident;
11 use rustc_span::{BytePos, Span, DUMMY_SP};
13 use smallvec::smallvec;
16 impl<'a, 'hir> LoweringContext<'a, 'hir> {
20 qself: &Option<QSelf>,
22 param_mode: ParamMode,
23 mut itctx: ImplTraitContext<'_, 'hir>,
24 ) -> hir::QPath<'hir> {
25 debug!("lower_qpath(id: {:?}, qself: {:?}, p: {:?})", id, qself, p);
26 let qself_position = qself.as_ref().map(|q| q.position);
27 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
30 self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
32 let path_span_lo = p.span.shrink_to_lo();
33 let proj_start = p.segments.len() - partial_res.unresolved_segments();
34 let path = self.arena.alloc(hir::Path {
35 res: self.lower_res(partial_res.base_res()),
36 segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
38 let param_mode = match (qself_position, param_mode) {
39 (Some(j), ParamMode::Optional) if i < j => {
40 // This segment is part of the trait path in a
41 // qualified path - one of `a`, `b` or `Trait`
42 // in `<X as a::b::Trait>::T::U::method`.
48 // Figure out if this is a type/trait segment,
49 // which may need lifetime elision performed.
50 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
52 index: this.resolver.def_key(def_id).parent.expect("missing parent"),
54 let type_def_id = match partial_res.base_res() {
55 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
56 Some(parent_def_id(self, def_id))
58 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
59 Some(parent_def_id(self, def_id))
61 Res::Def(DefKind::Struct, def_id)
62 | Res::Def(DefKind::Union, def_id)
63 | Res::Def(DefKind::Enum, def_id)
64 | Res::Def(DefKind::TyAlias, def_id)
65 | Res::Def(DefKind::Trait, def_id)
66 if i + 1 == proj_start =>
72 let parenthesized_generic_args = match partial_res.base_res() {
73 // `a::b::Trait(Args)`
74 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
75 ParenthesizedGenericArgs::Ok
77 // `a::b::Trait(Args)::TraitItem`
78 Res::Def(DefKind::AssocFn, _)
79 | Res::Def(DefKind::AssocConst, _)
80 | Res::Def(DefKind::AssocTy, _)
81 if i + 2 == proj_start =>
83 ParenthesizedGenericArgs::Ok
85 // Avoid duplicated errors.
86 Res::Err => ParenthesizedGenericArgs::Ok,
88 _ => ParenthesizedGenericArgs::Err,
91 let num_lifetimes = type_def_id
92 .map_or(0, |def_id| self.resolver.item_generics_num_lifetimes(def_id));
93 self.lower_path_segment(
98 parenthesized_generic_args,
103 span: self.lower_span(
104 p.segments[..proj_start]
106 .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
110 // Simple case, either no projections, or only fully-qualified.
111 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
112 if partial_res.unresolved_segments() == 0 {
113 return hir::QPath::Resolved(qself, path);
116 // Create the innermost type that we're projecting from.
117 let mut ty = if path.segments.is_empty() {
118 // If the base path is empty that means there exists a
119 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
120 qself.expect("missing QSelf for <T>::...")
122 // Otherwise, the base path is an implicit `Self` type path,
123 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
124 // `<I as Iterator>::Item::default`.
125 let new_id = self.next_id();
126 self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
129 // Anything after the base path are associated "extensions",
130 // out of which all but the last one are associated types,
131 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
132 // * base path is `std::vec::Vec<T>`
133 // * "extensions" are `IntoIter`, `Item` and `clone`
135 // 1. `std::vec::Vec<T>` (created above)
136 // 2. `<std::vec::Vec<T>>::IntoIter`
137 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
138 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
139 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
140 let hir_segment = self.arena.alloc(self.lower_path_segment(
145 ParenthesizedGenericArgs::Err,
148 let qpath = hir::QPath::TypeRelative(ty, hir_segment);
150 // It's finished, return the extension of the right node type.
151 if i == p.segments.len() - 1 {
155 // Wrap the associated extension in another type node.
156 let new_id = self.next_id();
157 ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
160 // We should've returned in the for loop above.
162 self.sess.diagnostic().span_bug(
165 "lower_qpath: no final extension segment in {}..{}",
172 crate fn lower_path_extra(
176 param_mode: ParamMode,
177 ) -> &'hir hir::Path<'hir> {
178 self.arena.alloc(hir::Path {
180 segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
181 self.lower_path_segment(
186 ParenthesizedGenericArgs::Err,
187 ImplTraitContext::disallowed(),
190 span: self.lower_span(p.span),
198 param_mode: ParamMode,
199 ) -> &'hir hir::Path<'hir> {
200 let res = self.expect_full_res(id);
201 let res = self.lower_res(res);
202 self.lower_path_extra(res, p, param_mode)
205 crate fn lower_path_segment(
208 segment: &PathSegment,
209 param_mode: ParamMode,
210 expected_lifetimes: usize,
211 parenthesized_generic_args: ParenthesizedGenericArgs,
212 itctx: ImplTraitContext<'_, 'hir>,
213 ) -> hir::PathSegment<'hir> {
215 "path_span: {:?}, lower_path_segment(segment: {:?}, expected_lifetimes: {:?})",
216 path_span, segment, expected_lifetimes
218 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
219 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
220 match **generic_args {
221 GenericArgs::AngleBracketed(ref data) => {
222 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
224 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
225 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
226 ParenthesizedGenericArgs::Err => {
227 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
228 err.span_label(data.span, "only `Fn` traits may use parentheses");
229 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
230 // Do not suggest going from `Trait()` to `Trait<>`
231 if !data.inputs.is_empty() {
232 // Suggest replacing `(` and `)` with `<` and `>`
233 // The snippet may be missing the closing `)`, skip that case
234 if snippet.ends_with(')') {
235 if let Some(split) = snippet.find('(') {
236 let trait_name = &snippet[0..split];
237 let args = &snippet[split + 1..snippet.len() - 1];
240 "use angle brackets instead",
241 format!("{}<{}>", trait_name, args),
242 Applicability::MaybeIncorrect,
250 self.lower_angle_bracketed_parameter_data(
251 &data.as_angle_bracketed_args(),
264 args: Default::default(),
266 parenthesized: false,
267 span: path_span.shrink_to_hi(),
269 param_mode == ParamMode::Optional,
274 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
275 if !generic_args.parenthesized && !has_lifetimes && expected_lifetimes > 0 {
276 // Note: these spans are used for diagnostics when they can't be inferred.
277 // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
278 let elided_lifetime_span = if generic_args.span.is_empty() {
279 // If there are no brackets, use the identifier span.
280 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
281 // originating from macros, since the segment's span might be from a macro arg.
282 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
283 } else if generic_args.is_empty() {
284 // If there are brackets, but not generic arguments, then use the opening bracket
285 generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
287 // Else use an empty span right after the opening bracket.
288 generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
290 generic_args.args = self
291 .elided_path_lifetimes(elided_lifetime_span, expected_lifetimes, param_mode)
292 .map(GenericArg::Lifetime)
293 .chain(generic_args.args.into_iter())
295 // In create-parameter mode we error here because we don't want to support
296 // deprecated impl elision in new features like impl elision and `async fn`,
297 // both of which work using the `CreateParameter` mode:
299 // impl Foo for std::cell::Ref<u32> // note lack of '_
300 // async fn foo(_: std::cell::Ref<u32>) { ... }
301 if let (ParamMode::Explicit, AnonymousLifetimeMode::CreateParameter) =
302 (param_mode, self.anonymous_lifetime_mode)
304 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
305 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
306 let no_bindings = generic_args.bindings.is_empty();
307 let (incl_angl_brckt, suggestion) = if no_non_lt_args && no_bindings {
308 // If there are no generic args, our suggestion can include the angle brackets.
309 (true, format!("<{}>", anon_lt_suggestion))
311 // Otherwise we'll insert a `'_, ` right after the opening bracket.
312 (false, format!("{}, ", anon_lt_suggestion))
314 let insertion_sp = elided_lifetime_span.shrink_to_hi();
315 let mut err = struct_span_err!(
319 "implicit elided lifetime not allowed here"
321 rustc_errors::add_elided_lifetime_in_path_suggestion(
322 &self.sess.source_map(),
330 err.note("assuming a `'static` lifetime...");
335 let res = self.expect_full_res(segment.id);
336 let id = self.lower_node_id(segment.id);
338 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
339 segment.ident, segment.id, id,
343 ident: self.lower_ident(segment.ident),
345 res: Some(self.lower_res(res)),
347 args: if generic_args.is_empty() && generic_args.span.is_empty() {
350 Some(generic_args.into_generic_args(self))
355 pub(crate) fn lower_angle_bracketed_parameter_data(
357 data: &AngleBracketedArgs,
358 param_mode: ParamMode,
359 mut itctx: ImplTraitContext<'_, 'hir>,
360 ) -> (GenericArgsCtor<'hir>, bool) {
361 let has_non_lt_args = data.args.iter().any(|arg| match arg {
362 AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
363 | AngleBracketedArg::Constraint(_) => false,
364 AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
369 .filter_map(|arg| match arg {
370 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx.reborrow())),
371 AngleBracketedArg::Constraint(_) => None,
374 let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
375 AngleBracketedArg::Constraint(c) => {
376 Some(self.lower_assoc_ty_constraint(c, itctx.reborrow()))
378 AngleBracketedArg::Arg(_) => None,
380 let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
381 (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
384 fn lower_parenthesized_parameter_data(
386 data: &ParenthesizedArgs,
387 ) -> (GenericArgsCtor<'hir>, bool) {
388 // Switch to `PassThrough` mode for anonymous lifetimes; this
389 // means that we permit things like `&Ref<T>`, where `Ref` has
390 // a hidden lifetime parameter. This is needed for backwards
391 // compatibility, even in contexts like an impl header where
392 // we generally don't permit such things (see #51008).
393 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
394 let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
395 let inputs = this.arena.alloc_from_iter(
396 inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())),
398 let output_ty = match output {
399 FnRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
400 FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(*span, &[])),
402 let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))];
403 let binding = this.output_ty_binding(output_ty.span, output_ty);
407 bindings: arena_vec![this; binding],
409 span: data.inputs_span,
416 /// An associated type binding `Output = $ty`.
417 crate fn output_ty_binding(
420 ty: &'hir hir::Ty<'hir>,
421 ) -> hir::TypeBinding<'hir> {
422 let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
423 let kind = hir::TypeBindingKind::Equality { term: ty.into() };
424 let args = arena_vec![self;];
425 let bindings = arena_vec![self;];
426 let gen_args = self.arena.alloc(hir::GenericArgs {
429 parenthesized: false,
433 hir_id: self.next_id(),
435 span: self.lower_span(span),