]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/path.rs
79262235cd9f250584e1556c7145a415eb2cf982
[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_span::symbol::Ident;
11 use rustc_span::{BytePos, Span, DUMMY_SP};
12
13 use smallvec::smallvec;
14 use tracing::debug;
15
16 impl<'a, 'hir> LoweringContext<'a, 'hir> {
17     crate fn lower_qpath(
18         &mut self,
19         id: NodeId,
20         qself: &Option<QSelf>,
21         p: &Path,
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()));
28
29         let partial_res =
30             self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
31
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(
37                 |(i, segment)| {
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`.
43                             ParamMode::Explicit
44                         }
45                         _ => param_mode,
46                     };
47
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 {
51                         krate: def_id.krate,
52                         index: this.resolver.def_key(def_id).parent.expect("missing parent"),
53                     };
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))
57                         }
58                         Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
59                             Some(parent_def_id(self, def_id))
60                         }
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 =>
67                         {
68                             Some(def_id)
69                         }
70                         _ => None,
71                     };
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
76                         }
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 =>
82                         {
83                             ParenthesizedGenericArgs::Ok
84                         }
85                         // Avoid duplicated errors.
86                         Res::Err => ParenthesizedGenericArgs::Ok,
87                         // An error
88                         _ => ParenthesizedGenericArgs::Err,
89                     };
90
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(
94                         p.span,
95                         segment,
96                         param_mode,
97                         num_lifetimes,
98                         parenthesized_generic_args,
99                         itctx.reborrow(),
100                     )
101                 },
102             )),
103             span: self.lower_span(
104                 p.segments[..proj_start]
105                     .last()
106                     .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
107             ),
108         });
109
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);
114         }
115
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>::...")
121         } else {
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)))
127         };
128
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`
134         // * type nodes are:
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(
141                 p.span,
142                 segment,
143                 param_mode,
144                 0,
145                 ParenthesizedGenericArgs::Err,
146                 itctx.reborrow(),
147             ));
148             let qpath = hir::QPath::TypeRelative(ty, hir_segment);
149
150             // It's finished, return the extension of the right node type.
151             if i == p.segments.len() - 1 {
152                 return qpath;
153             }
154
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));
158         }
159
160         // We should've returned in the for loop above.
161
162         self.sess.diagnostic().span_bug(
163             p.span,
164             &format!(
165                 "lower_qpath: no final extension segment in {}..{}",
166                 proj_start,
167                 p.segments.len()
168             ),
169         );
170     }
171
172     crate fn lower_path_extra(
173         &mut self,
174         res: Res,
175         p: &Path,
176         param_mode: ParamMode,
177     ) -> &'hir hir::Path<'hir> {
178         self.arena.alloc(hir::Path {
179             res,
180             segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
181                 self.lower_path_segment(
182                     p.span,
183                     segment,
184                     param_mode,
185                     0,
186                     ParenthesizedGenericArgs::Err,
187                     ImplTraitContext::disallowed(),
188                 )
189             })),
190             span: self.lower_span(p.span),
191         })
192     }
193
194     crate fn lower_path(
195         &mut self,
196         id: NodeId,
197         p: &Path,
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)
203     }
204
205     crate fn lower_path_segment(
206         &mut self,
207         path_span: Span,
208         segment: &PathSegment,
209         param_mode: ParamMode,
210         expected_lifetimes: usize,
211         parenthesized_generic_args: ParenthesizedGenericArgs,
212         itctx: ImplTraitContext<'_, 'hir>,
213     ) -> hir::PathSegment<'hir> {
214         debug!(
215             "path_span: {:?}, lower_path_segment(segment: {:?}, expected_lifetimes: {:?})",
216             path_span, segment, expected_lifetimes
217         );
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)
223                 }
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];
238                                         err.span_suggestion(
239                                             data.span,
240                                             "use angle brackets instead",
241                                             format!("{}<{}>", trait_name, args),
242                                             Applicability::MaybeIncorrect,
243                                         );
244                                     }
245                                 }
246                             }
247                         };
248                         err.emit();
249                         (
250                             self.lower_angle_bracketed_parameter_data(
251                                 &data.as_angle_bracketed_args(),
252                                 param_mode,
253                                 itctx,
254                             )
255                             .0,
256                             false,
257                         )
258                     }
259                 },
260             }
261         } else {
262             (
263                 GenericArgsCtor {
264                     args: Default::default(),
265                     bindings: &[],
266                     parenthesized: false,
267                     span: path_span.shrink_to_hi(),
268                 },
269                 param_mode == ParamMode::Optional,
270             )
271         };
272
273         let has_lifetimes =
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))
286             } else {
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()
289             };
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())
294                 .collect();
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:
298             //
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)
303             {
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))
310                 } else {
311                     // Otherwise we'll insert a `'_, ` right after the opening bracket.
312                     (false, format!("{}, ", anon_lt_suggestion))
313                 };
314                 let insertion_sp = elided_lifetime_span.shrink_to_hi();
315                 let mut err = struct_span_err!(
316                     self.sess,
317                     path_span,
318                     E0726,
319                     "implicit elided lifetime not allowed here"
320                 );
321                 rustc_errors::add_elided_lifetime_in_path_suggestion(
322                     &self.sess.source_map(),
323                     &mut err,
324                     expected_lifetimes,
325                     path_span,
326                     incl_angl_brckt,
327                     insertion_sp,
328                     suggestion,
329                 );
330                 err.note("assuming a `'static` lifetime...");
331                 err.emit();
332             }
333         }
334
335         let res = self.expect_full_res(segment.id);
336         let id = self.lower_node_id(segment.id);
337         debug!(
338             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
339             segment.ident, segment.id, id,
340         );
341
342         hir::PathSegment {
343             ident: self.lower_ident(segment.ident),
344             hir_id: Some(id),
345             res: Some(self.lower_res(res)),
346             infer_args,
347             args: if generic_args.is_empty() && generic_args.span.is_empty() {
348                 None
349             } else {
350                 Some(generic_args.into_generic_args(self))
351             },
352         }
353     }
354
355     pub(crate) fn lower_angle_bracketed_parameter_data(
356         &mut self,
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,
365         });
366         let args = data
367             .args
368             .iter()
369             .filter_map(|arg| match arg {
370                 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx.reborrow())),
371                 AngleBracketedArg::Constraint(_) => None,
372             })
373             .collect();
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()))
377             }
378             AngleBracketedArg::Arg(_) => None,
379         }));
380         let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
381         (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
382     }
383
384     fn lower_parenthesized_parameter_data(
385         &mut self,
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())),
397             );
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, &[])),
401             };
402             let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))];
403             let binding = this.output_ty_binding(output_ty.span, output_ty);
404             (
405                 GenericArgsCtor {
406                     args,
407                     bindings: arena_vec![this; binding],
408                     parenthesized: true,
409                     span: data.inputs_span,
410                 },
411                 false,
412             )
413         })
414     }
415
416     /// An associated type binding `Output = $ty`.
417     crate fn output_ty_binding(
418         &mut self,
419         span: Span,
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 {
427             args,
428             bindings,
429             parenthesized: false,
430             span_ext: DUMMY_SP,
431         });
432         hir::TypeBinding {
433             hir_id: self.next_id(),
434             gen_args,
435             span: self.lower_span(span),
436             ident,
437             kind,
438         }
439     }
440 }