]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/path.rs
Rollup merge of #83219 - ehuss:update-cargo, r=ehuss
[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::Span;
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         let qself_position = qself.as_ref().map(|q| q.position);
28         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
29
30         let partial_res =
31             self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
32
33         let path_span_lo = p.span.shrink_to_lo();
34         let proj_start = p.segments.len() - partial_res.unresolved_segments();
35         let path = self.arena.alloc(hir::Path {
36             res: self.lower_res(partial_res.base_res()),
37             segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
38                 |(i, segment)| {
39                     let param_mode = match (qself_position, param_mode) {
40                         (Some(j), ParamMode::Optional) if i < j => {
41                             // This segment is part of the trait path in a
42                             // qualified path - one of `a`, `b` or `Trait`
43                             // in `<X as a::b::Trait>::T::U::method`.
44                             ParamMode::Explicit
45                         }
46                         _ => param_mode,
47                     };
48
49                     // Figure out if this is a type/trait segment,
50                     // which may need lifetime elision performed.
51                     let parent_def_id = |this: &mut Self, def_id: DefId| DefId {
52                         krate: def_id.krate,
53                         index: this.resolver.def_key(def_id).parent.expect("missing parent"),
54                     };
55                     let type_def_id = match partial_res.base_res() {
56                         Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
57                             Some(parent_def_id(self, def_id))
58                         }
59                         Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
60                             Some(parent_def_id(self, def_id))
61                         }
62                         Res::Def(DefKind::Struct, def_id)
63                         | Res::Def(DefKind::Union, def_id)
64                         | Res::Def(DefKind::Enum, def_id)
65                         | Res::Def(DefKind::TyAlias, def_id)
66                         | Res::Def(DefKind::Trait, def_id)
67                             if i + 1 == proj_start =>
68                         {
69                             Some(def_id)
70                         }
71                         _ => None,
72                     };
73                     let parenthesized_generic_args = match partial_res.base_res() {
74                         // `a::b::Trait(Args)`
75                         Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
76                             ParenthesizedGenericArgs::Ok
77                         }
78                         // `a::b::Trait(Args)::TraitItem`
79                         Res::Def(DefKind::AssocFn, _)
80                         | Res::Def(DefKind::AssocConst, _)
81                         | Res::Def(DefKind::AssocTy, _)
82                             if i + 2 == proj_start =>
83                         {
84                             ParenthesizedGenericArgs::Ok
85                         }
86                         // Avoid duplicated errors.
87                         Res::Err => ParenthesizedGenericArgs::Ok,
88                         // An error
89                         _ => ParenthesizedGenericArgs::Err,
90                     };
91
92                     let num_lifetimes = type_def_id.map_or(0, |def_id| {
93                         if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
94                             return n;
95                         }
96                         assert!(!def_id.is_local());
97                         let n = self.resolver.item_generics_num_lifetimes(def_id, self.sess);
98                         self.type_def_lifetime_params.insert(def_id, n);
99                         n
100                     });
101                     self.lower_path_segment(
102                         p.span,
103                         segment,
104                         param_mode,
105                         num_lifetimes,
106                         parenthesized_generic_args,
107                         itctx.reborrow(),
108                         None,
109                     )
110                 },
111             )),
112             span: p.segments[..proj_start]
113                 .last()
114                 .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
115         });
116
117         // Simple case, either no projections, or only fully-qualified.
118         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
119         if partial_res.unresolved_segments() == 0 {
120             return hir::QPath::Resolved(qself, path);
121         }
122
123         // Create the innermost type that we're projecting from.
124         let mut ty = if path.segments.is_empty() {
125             // If the base path is empty that means there exists a
126             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
127             qself.expect("missing QSelf for <T>::...")
128         } else {
129             // Otherwise, the base path is an implicit `Self` type path,
130             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
131             // `<I as Iterator>::Item::default`.
132             let new_id = self.next_id();
133             self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
134         };
135
136         // Anything after the base path are associated "extensions",
137         // out of which all but the last one are associated types,
138         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
139         // * base path is `std::vec::Vec<T>`
140         // * "extensions" are `IntoIter`, `Item` and `clone`
141         // * type nodes are:
142         //   1. `std::vec::Vec<T>` (created above)
143         //   2. `<std::vec::Vec<T>>::IntoIter`
144         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
145         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
146         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
147             let hir_segment = self.arena.alloc(self.lower_path_segment(
148                 p.span,
149                 segment,
150                 param_mode,
151                 0,
152                 ParenthesizedGenericArgs::Err,
153                 itctx.reborrow(),
154                 None,
155             ));
156             let qpath = hir::QPath::TypeRelative(ty, hir_segment);
157
158             // It's finished, return the extension of the right node type.
159             if i == p.segments.len() - 1 {
160                 return qpath;
161             }
162
163             // Wrap the associated extension in another type node.
164             let new_id = self.next_id();
165             ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
166         }
167
168         // We should've returned in the for loop above.
169
170         self.sess.diagnostic().span_bug(
171             p.span,
172             &format!(
173                 "lower_qpath: no final extension segment in {}..{}",
174                 proj_start,
175                 p.segments.len()
176             ),
177         );
178     }
179
180     crate fn lower_path_extra(
181         &mut self,
182         res: Res,
183         p: &Path,
184         param_mode: ParamMode,
185         explicit_owner: Option<NodeId>,
186     ) -> &'hir hir::Path<'hir> {
187         self.arena.alloc(hir::Path {
188             res,
189             segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
190                 self.lower_path_segment(
191                     p.span,
192                     segment,
193                     param_mode,
194                     0,
195                     ParenthesizedGenericArgs::Err,
196                     ImplTraitContext::disallowed(),
197                     explicit_owner,
198                 )
199             })),
200             span: p.span,
201         })
202     }
203
204     crate fn lower_path(
205         &mut self,
206         id: NodeId,
207         p: &Path,
208         param_mode: ParamMode,
209     ) -> &'hir hir::Path<'hir> {
210         let res = self.expect_full_res(id);
211         let res = self.lower_res(res);
212         self.lower_path_extra(res, p, param_mode, None)
213     }
214
215     crate fn lower_path_segment(
216         &mut self,
217         path_span: Span,
218         segment: &PathSegment,
219         param_mode: ParamMode,
220         expected_lifetimes: usize,
221         parenthesized_generic_args: ParenthesizedGenericArgs,
222         itctx: ImplTraitContext<'_, 'hir>,
223         explicit_owner: Option<NodeId>,
224     ) -> hir::PathSegment<'hir> {
225         let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
226             let msg = "parenthesized type parameters may only be used with a `Fn` trait";
227             match **generic_args {
228                 GenericArgs::AngleBracketed(ref data) => {
229                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
230                 }
231                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
232                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
233                     ParenthesizedGenericArgs::Err => {
234                         let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
235                         err.span_label(data.span, "only `Fn` traits may use parentheses");
236                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
237                             // Do not suggest going from `Trait()` to `Trait<>`
238                             if !data.inputs.is_empty() {
239                                 if let Some(split) = snippet.find('(') {
240                                     let trait_name = &snippet[0..split];
241                                     let args = &snippet[split + 1..snippet.len() - 1];
242                                     err.span_suggestion(
243                                         data.span,
244                                         "use angle brackets instead",
245                                         format!("{}<{}>", trait_name, args),
246                                         Applicability::MaybeIncorrect,
247                                     );
248                                 }
249                             }
250                         };
251                         err.emit();
252                         (
253                             self.lower_angle_bracketed_parameter_data(
254                                 &data.as_angle_bracketed_args(),
255                                 param_mode,
256                                 itctx,
257                             )
258                             .0,
259                             false,
260                         )
261                     }
262                 },
263             }
264         } else {
265             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
266         };
267
268         let has_lifetimes =
269             generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
270         let first_generic_span = generic_args
271             .args
272             .iter()
273             .map(|a| a.span())
274             .chain(generic_args.bindings.iter().map(|b| b.span))
275             .next();
276         if !generic_args.parenthesized && !has_lifetimes {
277             generic_args.args = self
278                 .elided_path_lifetimes(
279                     first_generic_span.map_or(segment.ident.span, |s| s.shrink_to_lo()),
280                     expected_lifetimes,
281                 )
282                 .map(GenericArg::Lifetime)
283                 .chain(generic_args.args.into_iter())
284                 .collect();
285             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
286                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
287                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
288                 let no_bindings = generic_args.bindings.is_empty();
289                 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
290                     // If there are no (non-implicit) generic args or associated type
291                     // bindings, our suggestion includes the angle brackets.
292                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
293                 } else {
294                     // Otherwise (sorry, this is kind of gross) we need to infer the
295                     // place to splice in the `'_, ` from the generics that do exist.
296                     let first_generic_span = first_generic_span
297                         .expect("already checked that non-lifetime args or bindings exist");
298                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
299                 };
300                 match self.anonymous_lifetime_mode {
301                     // In create-parameter mode we error here because we don't want to support
302                     // deprecated impl elision in new features like impl elision and `async fn`,
303                     // both of which work using the `CreateParameter` mode:
304                     //
305                     //     impl Foo for std::cell::Ref<u32> // note lack of '_
306                     //     async fn foo(_: std::cell::Ref<u32>) { ... }
307                     AnonymousLifetimeMode::CreateParameter => {
308                         let mut err = struct_span_err!(
309                             self.sess,
310                             path_span,
311                             E0726,
312                             "implicit elided lifetime not allowed here"
313                         );
314                         rustc_errors::add_elided_lifetime_in_path_suggestion(
315                             &self.sess.source_map(),
316                             &mut err,
317                             expected_lifetimes,
318                             path_span,
319                             incl_angl_brckt,
320                             insertion_sp,
321                             suggestion,
322                         );
323                         err.emit();
324                     }
325                     AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
326                         self.resolver.lint_buffer().buffer_lint_with_diagnostic(
327                             ELIDED_LIFETIMES_IN_PATHS,
328                             CRATE_NODE_ID,
329                             path_span,
330                             "hidden lifetime parameters in types are deprecated",
331                             BuiltinLintDiagnostics::ElidedLifetimesInPaths(
332                                 expected_lifetimes,
333                                 path_span,
334                                 incl_angl_brckt,
335                                 insertion_sp,
336                                 suggestion,
337                             ),
338                         );
339                     }
340                 }
341             }
342         }
343
344         let res = self.expect_full_res(segment.id);
345         let id = if let Some(owner) = explicit_owner {
346             self.lower_node_id_with_owner(segment.id, owner)
347         } else {
348             self.lower_node_id(segment.id)
349         };
350         debug!(
351             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
352             segment.ident, segment.id, id,
353         );
354
355         hir::PathSegment {
356             ident: segment.ident,
357             hir_id: Some(id),
358             res: Some(self.lower_res(res)),
359             infer_args,
360             args: if generic_args.is_empty() {
361                 None
362             } else {
363                 Some(self.arena.alloc(generic_args.into_generic_args(self.arena)))
364             },
365         }
366     }
367
368     pub(crate) fn lower_angle_bracketed_parameter_data(
369         &mut self,
370         data: &AngleBracketedArgs,
371         param_mode: ParamMode,
372         mut itctx: ImplTraitContext<'_, 'hir>,
373     ) -> (GenericArgsCtor<'hir>, bool) {
374         let has_non_lt_args = data.args.iter().any(|arg| match arg {
375             AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
376             | AngleBracketedArg::Constraint(_) => false,
377             AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
378         });
379         let args = data
380             .args
381             .iter()
382             .filter_map(|arg| match arg {
383                 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx.reborrow())),
384                 AngleBracketedArg::Constraint(_) => None,
385             })
386             .collect();
387         let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
388             AngleBracketedArg::Constraint(c) => {
389                 Some(self.lower_assoc_ty_constraint(c, itctx.reborrow()))
390             }
391             AngleBracketedArg::Arg(_) => None,
392         }));
393         let ctor = GenericArgsCtor { args, bindings, parenthesized: false };
394         (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
395     }
396
397     fn lower_parenthesized_parameter_data(
398         &mut self,
399         data: &ParenthesizedArgs,
400     ) -> (GenericArgsCtor<'hir>, bool) {
401         // Switch to `PassThrough` mode for anonymous lifetimes; this
402         // means that we permit things like `&Ref<T>`, where `Ref` has
403         // a hidden lifetime parameter. This is needed for backwards
404         // compatibility, even in contexts like an impl header where
405         // we generally don't permit such things (see #51008).
406         self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
407             let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
408             let inputs = this.arena.alloc_from_iter(
409                 inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())),
410             );
411             let output_ty = match output {
412                 FnRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
413                 FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(*span, &[])),
414             };
415             let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))];
416             let binding = this.output_ty_binding(output_ty.span, output_ty);
417             (
418                 GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true },
419                 false,
420             )
421         })
422     }
423
424     /// An associated type binding `Output = $ty`.
425     crate fn output_ty_binding(
426         &mut self,
427         span: Span,
428         ty: &'hir hir::Ty<'hir>,
429     ) -> hir::TypeBinding<'hir> {
430         let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
431         let kind = hir::TypeBindingKind::Equality { ty };
432         let args = arena_vec![self;];
433         let bindings = arena_vec![self;];
434         let gen_args = self.arena.alloc(hir::GenericArgs { args, bindings, parenthesized: false });
435         hir::TypeBinding { hir_id: self.next_id(), gen_args, span, ident, kind }
436     }
437 }