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_session::lint::builtin::ELIDED_LIFETIMES_IN_PATHS;
11 use rustc_session::lint::BuiltinLintDiagnostics;
12 use rustc_span::symbol::Ident;
13 use rustc_span::{BytePos, Span, DUMMY_SP};
15 use smallvec::smallvec;
18 impl<'a, 'hir> LoweringContext<'a, 'hir> {
22 qself: &Option<QSelf>,
24 param_mode: ParamMode,
25 mut itctx: ImplTraitContext<'_, 'hir>,
26 ) -> hir::QPath<'hir> {
27 debug!("lower_qpath(id: {:?}, qself: {:?}, p: {:?})", id, qself, p);
28 let qself_position = qself.as_ref().map(|q| q.position);
29 let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
32 self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
34 let path_span_lo = p.span.shrink_to_lo();
35 let proj_start = p.segments.len() - partial_res.unresolved_segments();
36 let path = self.arena.alloc(hir::Path {
37 res: self.lower_res(partial_res.base_res()),
38 segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
40 let param_mode = match (qself_position, param_mode) {
41 (Some(j), ParamMode::Optional) if i < j => {
42 // This segment is part of the trait path in a
43 // qualified path - one of `a`, `b` or `Trait`
44 // in `<X as a::b::Trait>::T::U::method`.
50 // Figure out if this is a type/trait segment,
51 // which may need lifetime elision performed.
52 let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
54 index: this.resolver.def_key(def_id).parent.expect("missing parent"),
56 let type_def_id = match partial_res.base_res() {
57 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
58 Some(parent_def_id(self, def_id))
60 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
61 Some(parent_def_id(self, def_id))
63 Res::Def(DefKind::Struct, def_id)
64 | Res::Def(DefKind::Union, def_id)
65 | Res::Def(DefKind::Enum, def_id)
66 | Res::Def(DefKind::TyAlias, def_id)
67 | Res::Def(DefKind::Trait, def_id)
68 if i + 1 == proj_start =>
74 let parenthesized_generic_args = match partial_res.base_res() {
75 // `a::b::Trait(Args)`
76 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
77 ParenthesizedGenericArgs::Ok
79 // `a::b::Trait(Args)::TraitItem`
80 Res::Def(DefKind::AssocFn, _)
81 | Res::Def(DefKind::AssocConst, _)
82 | Res::Def(DefKind::AssocTy, _)
83 if i + 2 == proj_start =>
85 ParenthesizedGenericArgs::Ok
87 // Avoid duplicated errors.
88 Res::Err => ParenthesizedGenericArgs::Ok,
90 _ => ParenthesizedGenericArgs::Err,
93 let num_lifetimes = type_def_id
94 .map_or(0, |def_id| self.resolver.item_generics_num_lifetimes(def_id));
95 self.lower_path_segment(
100 parenthesized_generic_args,
105 span: self.lower_span(
106 p.segments[..proj_start]
108 .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
112 // Simple case, either no projections, or only fully-qualified.
113 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
114 if partial_res.unresolved_segments() == 0 {
115 return hir::QPath::Resolved(qself, path);
118 // Create the innermost type that we're projecting from.
119 let mut ty = if path.segments.is_empty() {
120 // If the base path is empty that means there exists a
121 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
122 qself.expect("missing QSelf for <T>::...")
124 // Otherwise, the base path is an implicit `Self` type path,
125 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
126 // `<I as Iterator>::Item::default`.
127 let new_id = self.next_id();
128 self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
131 // Anything after the base path are associated "extensions",
132 // out of which all but the last one are associated types,
133 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
134 // * base path is `std::vec::Vec<T>`
135 // * "extensions" are `IntoIter`, `Item` and `clone`
137 // 1. `std::vec::Vec<T>` (created above)
138 // 2. `<std::vec::Vec<T>>::IntoIter`
139 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
140 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
141 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
142 let hir_segment = self.arena.alloc(self.lower_path_segment(
147 ParenthesizedGenericArgs::Err,
150 let qpath = hir::QPath::TypeRelative(ty, hir_segment);
152 // It's finished, return the extension of the right node type.
153 if i == p.segments.len() - 1 {
157 // Wrap the associated extension in another type node.
158 let new_id = self.next_id();
159 ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
162 // We should've returned in the for loop above.
164 self.sess.diagnostic().span_bug(
167 "lower_qpath: no final extension segment in {}..{}",
174 crate fn lower_path_extra(
178 param_mode: ParamMode,
179 ) -> &'hir hir::Path<'hir> {
180 self.arena.alloc(hir::Path {
182 segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
183 self.lower_path_segment(
188 ParenthesizedGenericArgs::Err,
189 ImplTraitContext::disallowed(),
192 span: self.lower_span(p.span),
200 param_mode: ParamMode,
201 ) -> &'hir hir::Path<'hir> {
202 let res = self.expect_full_res(id);
203 let res = self.lower_res(res);
204 self.lower_path_extra(res, p, param_mode)
207 crate fn lower_path_segment(
210 segment: &PathSegment,
211 param_mode: ParamMode,
212 expected_lifetimes: usize,
213 parenthesized_generic_args: ParenthesizedGenericArgs,
214 itctx: ImplTraitContext<'_, 'hir>,
215 ) -> hir::PathSegment<'hir> {
217 "path_span: {:?}, lower_path_segment(segment: {:?}, expected_lifetimes: {:?})",
218 path_span, segment, expected_lifetimes
220 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
221 let msg = "parenthesized type parameters may only be used with a `Fn` trait";
222 match **generic_args {
223 GenericArgs::AngleBracketed(ref data) => {
224 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
226 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
227 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
228 ParenthesizedGenericArgs::Err => {
229 let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
230 err.span_label(data.span, "only `Fn` traits may use parentheses");
231 if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
232 // Do not suggest going from `Trait()` to `Trait<>`
233 if !data.inputs.is_empty() {
234 if let Some(split) = snippet.find('(') {
235 let trait_name = &snippet[0..split];
236 let args = &snippet[split + 1..snippet.len() - 1];
239 "use angle brackets instead",
240 format!("{}<{}>", trait_name, args),
241 Applicability::MaybeIncorrect,
248 self.lower_angle_bracketed_parameter_data(
249 &data.as_angle_bracketed_args(),
262 args: Default::default(),
264 parenthesized: false,
265 span: path_span.shrink_to_hi(),
267 param_mode == ParamMode::Optional,
272 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
273 if !generic_args.parenthesized && !has_lifetimes {
274 // Note: these spans are used for diagnostics when they can't be inferred.
275 // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
276 let elided_lifetime_span = if generic_args.span.is_empty() {
277 // If there are no brackets, use the identifier span.
279 } else if generic_args.is_empty() {
280 // If there are brackets, but not generic arguments, then use the opening bracket
281 generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
283 // Else use an empty span right after the opening bracket.
284 generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
286 generic_args.args = self
287 .elided_path_lifetimes(elided_lifetime_span, expected_lifetimes)
288 .map(GenericArg::Lifetime)
289 .chain(generic_args.args.into_iter())
291 if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
292 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
293 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
294 let no_bindings = generic_args.bindings.is_empty();
295 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
296 // If there are no generic args, our suggestion can include the angle brackets.
297 (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
299 // Otherwise we'll insert a `'_, ` right after the opening bracket.
300 let span = generic_args
302 .with_lo(generic_args.span.lo() + BytePos(1))
304 (false, span, format!("{}, ", anon_lt_suggestion))
306 match self.anonymous_lifetime_mode {
307 // In create-parameter mode we error here because we don't want to support
308 // deprecated impl elision in new features like impl elision and `async fn`,
309 // both of which work using the `CreateParameter` mode:
311 // impl Foo for std::cell::Ref<u32> // note lack of '_
312 // async fn foo(_: std::cell::Ref<u32>) { ... }
313 AnonymousLifetimeMode::CreateParameter => {
314 let mut err = struct_span_err!(
318 "implicit elided lifetime not allowed here"
320 rustc_errors::add_elided_lifetime_in_path_suggestion(
321 &self.sess.source_map(),
329 err.note("assuming a `'static` lifetime...");
332 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
333 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
334 ELIDED_LIFETIMES_IN_PATHS,
337 "hidden lifetime parameters in types are deprecated",
338 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
351 let res = self.expect_full_res(segment.id);
352 let id = self.lower_node_id(segment.id);
354 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
355 segment.ident, segment.id, id,
359 ident: self.lower_ident(segment.ident),
361 res: Some(self.lower_res(res)),
363 args: if generic_args.is_empty() && generic_args.span.is_empty() {
366 Some(generic_args.into_generic_args(self))
371 pub(crate) fn lower_angle_bracketed_parameter_data(
373 data: &AngleBracketedArgs,
374 param_mode: ParamMode,
375 mut itctx: ImplTraitContext<'_, 'hir>,
376 ) -> (GenericArgsCtor<'hir>, bool) {
377 let has_non_lt_args = data.args.iter().any(|arg| match arg {
378 AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
379 | AngleBracketedArg::Constraint(_) => false,
380 AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
385 .filter_map(|arg| match arg {
386 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx.reborrow())),
387 AngleBracketedArg::Constraint(_) => None,
390 let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
391 AngleBracketedArg::Constraint(c) => {
392 Some(self.lower_assoc_ty_constraint(c, itctx.reborrow()))
394 AngleBracketedArg::Arg(_) => None,
396 let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
397 (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
400 fn lower_parenthesized_parameter_data(
402 data: &ParenthesizedArgs,
403 ) -> (GenericArgsCtor<'hir>, bool) {
404 // Switch to `PassThrough` mode for anonymous lifetimes; this
405 // means that we permit things like `&Ref<T>`, where `Ref` has
406 // a hidden lifetime parameter. This is needed for backwards
407 // compatibility, even in contexts like an impl header where
408 // we generally don't permit such things (see #51008).
409 self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
410 let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
411 let inputs = this.arena.alloc_from_iter(
412 inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())),
414 let output_ty = match output {
415 FnRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
416 FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(*span, &[])),
418 let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))];
419 let binding = this.output_ty_binding(output_ty.span, output_ty);
423 bindings: arena_vec![this; binding],
425 span: data.inputs_span,
432 /// An associated type binding `Output = $ty`.
433 crate fn output_ty_binding(
436 ty: &'hir hir::Ty<'hir>,
437 ) -> hir::TypeBinding<'hir> {
438 let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
439 let kind = hir::TypeBindingKind::Equality { ty };
440 let args = arena_vec![self;];
441 let bindings = arena_vec![self;];
442 let gen_args = self.arena.alloc(hir::GenericArgs {
445 parenthesized: false,
449 hir_id: self.next_id(),
451 span: self.lower_span(span),