]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/path.rs
Rollup merge of #89473 - FabianWolff:issue-89469, r=joshtriplett
[rust.git] / compiler / rustc_ast_lowering / src / path.rs
1 use super::{AnonymousLifetimeMode, ImplTraitContext, LoweringContext, ParamMode};
2 use super::{GenericArgsCtor, ParenthesizedGenericArgs};
3
4 use rustc_ast::{self as ast, *};
5 use rustc_errors::{struct_span_err, Applicability};
6 use rustc_hir as hir;
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};
14
15 use smallvec::smallvec;
16 use tracing::debug;
17
18 impl<'a, 'hir> LoweringContext<'a, 'hir> {
19     crate fn lower_qpath(
20         &mut self,
21         id: NodeId,
22         qself: &Option<QSelf>,
23         p: &Path,
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()));
30
31         let partial_res =
32             self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
33
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(
39                 |(i, segment)| {
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`.
45                             ParamMode::Explicit
46                         }
47                         _ => param_mode,
48                     };
49
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 {
53                         krate: def_id.krate,
54                         index: this.resolver.def_key(def_id).parent.expect("missing parent"),
55                     };
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))
59                         }
60                         Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
61                             Some(parent_def_id(self, def_id))
62                         }
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 =>
69                         {
70                             Some(def_id)
71                         }
72                         _ => None,
73                     };
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
78                         }
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 =>
84                         {
85                             ParenthesizedGenericArgs::Ok
86                         }
87                         // Avoid duplicated errors.
88                         Res::Err => ParenthesizedGenericArgs::Ok,
89                         // An error
90                         _ => ParenthesizedGenericArgs::Err,
91                     };
92
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(
96                         p.span,
97                         segment,
98                         param_mode,
99                         num_lifetimes,
100                         parenthesized_generic_args,
101                         itctx.reborrow(),
102                     )
103                 },
104             )),
105             span: self.lower_span(
106                 p.segments[..proj_start]
107                     .last()
108                     .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
109             ),
110         });
111
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);
116         }
117
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>::...")
123         } else {
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)))
129         };
130
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`
136         // * type nodes are:
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(
143                 p.span,
144                 segment,
145                 param_mode,
146                 0,
147                 ParenthesizedGenericArgs::Err,
148                 itctx.reborrow(),
149             ));
150             let qpath = hir::QPath::TypeRelative(ty, hir_segment);
151
152             // It's finished, return the extension of the right node type.
153             if i == p.segments.len() - 1 {
154                 return qpath;
155             }
156
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));
160         }
161
162         // We should've returned in the for loop above.
163
164         self.sess.diagnostic().span_bug(
165             p.span,
166             &format!(
167                 "lower_qpath: no final extension segment in {}..{}",
168                 proj_start,
169                 p.segments.len()
170             ),
171         );
172     }
173
174     crate fn lower_path_extra(
175         &mut self,
176         res: Res,
177         p: &Path,
178         param_mode: ParamMode,
179     ) -> &'hir hir::Path<'hir> {
180         self.arena.alloc(hir::Path {
181             res,
182             segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
183                 self.lower_path_segment(
184                     p.span,
185                     segment,
186                     param_mode,
187                     0,
188                     ParenthesizedGenericArgs::Err,
189                     ImplTraitContext::disallowed(),
190                 )
191             })),
192             span: self.lower_span(p.span),
193         })
194     }
195
196     crate fn lower_path(
197         &mut self,
198         id: NodeId,
199         p: &Path,
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)
205     }
206
207     crate fn lower_path_segment(
208         &mut self,
209         path_span: Span,
210         segment: &PathSegment,
211         param_mode: ParamMode,
212         expected_lifetimes: usize,
213         parenthesized_generic_args: ParenthesizedGenericArgs,
214         itctx: ImplTraitContext<'_, 'hir>,
215     ) -> hir::PathSegment<'hir> {
216         debug!(
217             "path_span: {:?}, lower_path_segment(segment: {:?}, expected_lifetimes: {:?})",
218             path_span, segment, expected_lifetimes
219         );
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)
225                 }
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];
237                                     err.span_suggestion(
238                                         data.span,
239                                         "use angle brackets instead",
240                                         format!("{}<{}>", trait_name, args),
241                                         Applicability::MaybeIncorrect,
242                                     );
243                                 }
244                             }
245                         };
246                         err.emit();
247                         (
248                             self.lower_angle_bracketed_parameter_data(
249                                 &data.as_angle_bracketed_args(),
250                                 param_mode,
251                                 itctx,
252                             )
253                             .0,
254                             false,
255                         )
256                     }
257                 },
258             }
259         } else {
260             (
261                 GenericArgsCtor {
262                     args: Default::default(),
263                     bindings: &[],
264                     parenthesized: false,
265                     span: path_span.shrink_to_hi(),
266                 },
267                 param_mode == ParamMode::Optional,
268             )
269         };
270
271         let has_lifetimes =
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.
278                 segment.ident.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))
282             } else {
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()
285             };
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())
290                 .collect();
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))
298                 } else {
299                     // Otherwise we'll insert a `'_, ` right after the opening bracket.
300                     let span = generic_args
301                         .span
302                         .with_lo(generic_args.span.lo() + BytePos(1))
303                         .shrink_to_lo();
304                     (false, span, format!("{}, ", anon_lt_suggestion))
305                 };
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:
310                     //
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!(
315                             self.sess,
316                             path_span,
317                             E0726,
318                             "implicit elided lifetime not allowed here"
319                         );
320                         rustc_errors::add_elided_lifetime_in_path_suggestion(
321                             &self.sess.source_map(),
322                             &mut err,
323                             expected_lifetimes,
324                             path_span,
325                             incl_angl_brckt,
326                             insertion_sp,
327                             suggestion,
328                         );
329                         err.note("assuming a `'static` lifetime...");
330                         err.emit();
331                     }
332                     AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
333                         self.resolver.lint_buffer().buffer_lint_with_diagnostic(
334                             ELIDED_LIFETIMES_IN_PATHS,
335                             CRATE_NODE_ID,
336                             path_span,
337                             "hidden lifetime parameters in types are deprecated",
338                             BuiltinLintDiagnostics::ElidedLifetimesInPaths(
339                                 expected_lifetimes,
340                                 path_span,
341                                 incl_angl_brckt,
342                                 insertion_sp,
343                                 suggestion,
344                             ),
345                         );
346                     }
347                 }
348             }
349         }
350
351         let res = self.expect_full_res(segment.id);
352         let id = self.lower_node_id(segment.id);
353         debug!(
354             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
355             segment.ident, segment.id, id,
356         );
357
358         hir::PathSegment {
359             ident: self.lower_ident(segment.ident),
360             hir_id: Some(id),
361             res: Some(self.lower_res(res)),
362             infer_args,
363             args: if generic_args.is_empty() && generic_args.span.is_empty() {
364                 None
365             } else {
366                 Some(generic_args.into_generic_args(self))
367             },
368         }
369     }
370
371     pub(crate) fn lower_angle_bracketed_parameter_data(
372         &mut self,
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,
381         });
382         let args = data
383             .args
384             .iter()
385             .filter_map(|arg| match arg {
386                 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx.reborrow())),
387                 AngleBracketedArg::Constraint(_) => None,
388             })
389             .collect();
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()))
393             }
394             AngleBracketedArg::Arg(_) => None,
395         }));
396         let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
397         (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
398     }
399
400     fn lower_parenthesized_parameter_data(
401         &mut self,
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())),
413             );
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, &[])),
417             };
418             let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))];
419             let binding = this.output_ty_binding(output_ty.span, output_ty);
420             (
421                 GenericArgsCtor {
422                     args,
423                     bindings: arena_vec![this; binding],
424                     parenthesized: true,
425                     span: data.inputs_span,
426                 },
427                 false,
428             )
429         })
430     }
431
432     /// An associated type binding `Output = $ty`.
433     crate fn output_ty_binding(
434         &mut self,
435         span: Span,
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 {
443             args,
444             bindings,
445             parenthesized: false,
446             span_ext: DUMMY_SP,
447         });
448         hir::TypeBinding {
449             hir_id: self.next_id(),
450             gen_args,
451             span: self.lower_span(span),
452             ident,
453             kind,
454         }
455     }
456 }