]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/path.rs
Auto merge of #2650 - RalfJung:rustup, r=RalfJung
[rust.git] / compiler / rustc_ast_lowering / src / path.rs
1 use crate::ImplTraitPosition;
2
3 use super::errors::{GenericTypeWithParentheses, UseAngleBrackets};
4 use super::ResolverAstLoweringExt;
5 use super::{GenericArgsCtor, LifetimeRes, ParenthesizedGenericArgs};
6 use super::{ImplTraitContext, LoweringContext, ParamMode};
7
8 use rustc_ast::{self as ast, *};
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, PartialRes, Res};
11 use rustc_hir::GenericArg;
12 use rustc_span::symbol::{kw, Ident};
13 use rustc_span::{BytePos, Span, DUMMY_SP};
14
15 use smallvec::smallvec;
16
17 impl<'a, 'hir> LoweringContext<'a, 'hir> {
18     #[instrument(level = "trace", skip(self))]
19     pub(crate) fn lower_qpath(
20         &mut self,
21         id: NodeId,
22         qself: &Option<QSelf>,
23         p: &Path,
24         param_mode: ParamMode,
25         itctx: &ImplTraitContext,
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));
29
30         let partial_res =
31             self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
32         let base_res = partial_res.base_res();
33         let unresolved_segments = partial_res.unresolved_segments();
34
35         let path_span_lo = p.span.shrink_to_lo();
36         let proj_start = p.segments.len() - unresolved_segments;
37         let path = self.arena.alloc(hir::Path {
38             res: self.lower_res(base_res),
39             segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
40                 |(i, segment)| {
41                     let param_mode = match (qself_position, param_mode) {
42                         (Some(j), ParamMode::Optional) if i < j => {
43                             // This segment is part of the trait path in a
44                             // qualified path - one of `a`, `b` or `Trait`
45                             // in `<X as a::b::Trait>::T::U::method`.
46                             ParamMode::Explicit
47                         }
48                         _ => param_mode,
49                     };
50
51                     let parenthesized_generic_args = match base_res {
52                         // `a::b::Trait(Args)`
53                         Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
54                             ParenthesizedGenericArgs::Ok
55                         }
56                         // `a::b::Trait(Args)::TraitItem`
57                         Res::Def(DefKind::AssocFn, _)
58                         | Res::Def(DefKind::AssocConst, _)
59                         | Res::Def(DefKind::AssocTy, _)
60                             if i + 2 == proj_start =>
61                         {
62                             ParenthesizedGenericArgs::Ok
63                         }
64                         // Avoid duplicated errors.
65                         Res::Err => ParenthesizedGenericArgs::Ok,
66                         // An error
67                         _ => ParenthesizedGenericArgs::Err,
68                     };
69
70                     self.lower_path_segment(
71                         p.span,
72                         segment,
73                         param_mode,
74                         parenthesized_generic_args,
75                         itctx,
76                     )
77                 },
78             )),
79             span: self.lower_span(
80                 p.segments[..proj_start]
81                     .last()
82                     .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
83             ),
84         });
85
86         // Simple case, either no projections, or only fully-qualified.
87         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
88         if unresolved_segments == 0 {
89             return hir::QPath::Resolved(qself, path);
90         }
91
92         // Create the innermost type that we're projecting from.
93         let mut ty = if path.segments.is_empty() {
94             // If the base path is empty that means there exists a
95             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
96             qself.expect("missing QSelf for <T>::...")
97         } else {
98             // Otherwise, the base path is an implicit `Self` type path,
99             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
100             // `<I as Iterator>::Item::default`.
101             let new_id = self.next_id();
102             self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
103         };
104
105         // Anything after the base path are associated "extensions",
106         // out of which all but the last one are associated types,
107         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
108         // * base path is `std::vec::Vec<T>`
109         // * "extensions" are `IntoIter`, `Item` and `clone`
110         // * type nodes are:
111         //   1. `std::vec::Vec<T>` (created above)
112         //   2. `<std::vec::Vec<T>>::IntoIter`
113         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
114         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
115         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
116             let hir_segment = self.arena.alloc(self.lower_path_segment(
117                 p.span,
118                 segment,
119                 param_mode,
120                 ParenthesizedGenericArgs::Err,
121                 itctx,
122             ));
123             let qpath = hir::QPath::TypeRelative(ty, hir_segment);
124
125             // It's finished, return the extension of the right node type.
126             if i == p.segments.len() - 1 {
127                 return qpath;
128             }
129
130             // Wrap the associated extension in another type node.
131             let new_id = self.next_id();
132             ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
133         }
134
135         // We should've returned in the for loop above.
136
137         self.diagnostic().span_bug(
138             p.span,
139             &format!(
140                 "lower_qpath: no final extension segment in {}..{}",
141                 proj_start,
142                 p.segments.len()
143             ),
144         );
145     }
146
147     pub(crate) fn lower_path_extra(
148         &mut self,
149         res: Res,
150         p: &Path,
151         param_mode: ParamMode,
152     ) -> &'hir hir::Path<'hir> {
153         self.arena.alloc(hir::Path {
154             res,
155             segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
156                 self.lower_path_segment(
157                     p.span,
158                     segment,
159                     param_mode,
160                     ParenthesizedGenericArgs::Err,
161                     &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
162                 )
163             })),
164             span: self.lower_span(p.span),
165         })
166     }
167
168     pub(crate) fn lower_path(
169         &mut self,
170         id: NodeId,
171         p: &Path,
172         param_mode: ParamMode,
173     ) -> &'hir hir::Path<'hir> {
174         let res = self.expect_full_res(id);
175         let res = self.lower_res(res);
176         self.lower_path_extra(res, p, param_mode)
177     }
178
179     pub(crate) fn lower_path_segment(
180         &mut self,
181         path_span: Span,
182         segment: &PathSegment,
183         param_mode: ParamMode,
184         parenthesized_generic_args: ParenthesizedGenericArgs,
185         itctx: &ImplTraitContext,
186     ) -> hir::PathSegment<'hir> {
187         debug!("path_span: {:?}, lower_path_segment(segment: {:?})", path_span, segment,);
188         let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
189             match **generic_args {
190                 GenericArgs::AngleBracketed(ref data) => {
191                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
192                 }
193                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
194                     ParenthesizedGenericArgs::Ok => {
195                         self.lower_parenthesized_parameter_data(data, itctx)
196                     }
197                     ParenthesizedGenericArgs::Err => {
198                         // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
199                         let sub = if !data.inputs.is_empty() {
200                             // Start of the span to the 1st character of 1st argument
201                             let open_param = data.inputs_span.shrink_to_lo().to(data
202                                 .inputs
203                                 .first()
204                                 .unwrap()
205                                 .span
206                                 .shrink_to_lo());
207                             // Last character position of last argument to the end of the span
208                             let close_param = data
209                                 .inputs
210                                 .last()
211                                 .unwrap()
212                                 .span
213                                 .shrink_to_hi()
214                                 .to(data.inputs_span.shrink_to_hi());
215
216                             Some(UseAngleBrackets { open_param, close_param })
217                         } else {
218                             None
219                         };
220                         self.tcx.sess.emit_err(GenericTypeWithParentheses { span: data.span, sub });
221                         (
222                             self.lower_angle_bracketed_parameter_data(
223                                 &data.as_angle_bracketed_args(),
224                                 param_mode,
225                                 itctx,
226                             )
227                             .0,
228                             false,
229                         )
230                     }
231                 },
232             }
233         } else {
234             (
235                 GenericArgsCtor {
236                     args: Default::default(),
237                     bindings: &[],
238                     parenthesized: false,
239                     span: path_span.shrink_to_hi(),
240                 },
241                 param_mode == ParamMode::Optional,
242             )
243         };
244
245         let has_lifetimes =
246             generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
247         if !generic_args.parenthesized && !has_lifetimes {
248             self.maybe_insert_elided_lifetimes_in_path(
249                 path_span,
250                 segment.id,
251                 segment.ident.span,
252                 &mut generic_args,
253             );
254         }
255
256         let res = self.expect_full_res(segment.id);
257         let hir_id = self.lower_node_id(segment.id);
258         debug!(
259             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
260             segment.ident, segment.id, hir_id,
261         );
262
263         hir::PathSegment {
264             ident: self.lower_ident(segment.ident),
265             hir_id,
266             res: self.lower_res(res),
267             infer_args,
268             args: if generic_args.is_empty() && generic_args.span.is_empty() {
269                 None
270             } else {
271                 Some(generic_args.into_generic_args(self))
272             },
273         }
274     }
275
276     fn maybe_insert_elided_lifetimes_in_path(
277         &mut self,
278         path_span: Span,
279         segment_id: NodeId,
280         segment_ident_span: Span,
281         generic_args: &mut GenericArgsCtor<'hir>,
282     ) {
283         let (start, end) = match self.resolver.get_lifetime_res(segment_id) {
284             Some(LifetimeRes::ElidedAnchor { start, end }) => (start, end),
285             None => return,
286             Some(_) => panic!(),
287         };
288         let expected_lifetimes = end.as_usize() - start.as_usize();
289         debug!(expected_lifetimes);
290
291         // Note: these spans are used for diagnostics when they can't be inferred.
292         // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
293         let elided_lifetime_span = if generic_args.span.is_empty() {
294             // If there are no brackets, use the identifier span.
295             // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
296             // originating from macros, since the segment's span might be from a macro arg.
297             segment_ident_span.find_ancestor_inside(path_span).unwrap_or(path_span)
298         } else if generic_args.is_empty() {
299             // If there are brackets, but not generic arguments, then use the opening bracket
300             generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
301         } else {
302             // Else use an empty span right after the opening bracket.
303             generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
304         };
305
306         generic_args.args.insert_many(
307             0,
308             (start.as_u32()..end.as_u32()).map(|i| {
309                 let id = NodeId::from_u32(i);
310                 let l = self.lower_lifetime(&Lifetime {
311                     id,
312                     ident: Ident::new(kw::UnderscoreLifetime, elided_lifetime_span),
313                 });
314                 GenericArg::Lifetime(l)
315             }),
316         );
317     }
318
319     pub(crate) fn lower_angle_bracketed_parameter_data(
320         &mut self,
321         data: &AngleBracketedArgs,
322         param_mode: ParamMode,
323         itctx: &ImplTraitContext,
324     ) -> (GenericArgsCtor<'hir>, bool) {
325         let has_non_lt_args = data.args.iter().any(|arg| match arg {
326             AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
327             | AngleBracketedArg::Constraint(_) => false,
328             AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
329         });
330         let args = data
331             .args
332             .iter()
333             .filter_map(|arg| match arg {
334                 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx)),
335                 AngleBracketedArg::Constraint(_) => None,
336             })
337             .collect();
338         let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
339             AngleBracketedArg::Constraint(c) => Some(self.lower_assoc_ty_constraint(c, itctx)),
340             AngleBracketedArg::Arg(_) => None,
341         }));
342         let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
343         (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
344     }
345
346     fn lower_parenthesized_parameter_data(
347         &mut self,
348         data: &ParenthesizedArgs,
349         itctx: &ImplTraitContext,
350     ) -> (GenericArgsCtor<'hir>, bool) {
351         // Switch to `PassThrough` mode for anonymous lifetimes; this
352         // means that we permit things like `&Ref<T>`, where `Ref` has
353         // a hidden lifetime parameter. This is needed for backwards
354         // compatibility, even in contexts like an impl header where
355         // we generally don't permit such things (see #51008).
356         let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
357         let inputs = self.arena.alloc_from_iter(inputs.iter().map(|ty| {
358             self.lower_ty_direct(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitParam))
359         }));
360         let output_ty = match output {
361             // Only allow `impl Trait` in return position. i.e.:
362             // ```rust
363             // fn f(_: impl Fn() -> impl Debug) -> impl Fn() -> impl Debug
364             // //      disallowed --^^^^^^^^^^        allowed --^^^^^^^^^^
365             // ```
366             FnRetTy::Ty(ty)
367                 if matches!(itctx, ImplTraitContext::ReturnPositionOpaqueTy { .. })
368                     && self.tcx.features().impl_trait_in_fn_trait_return =>
369             {
370                 self.lower_ty(&ty, itctx)
371             }
372             FnRetTy::Ty(ty) => {
373                 self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn))
374             }
375             FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])),
376         };
377         let args = smallvec![GenericArg::Type(self.arena.alloc(self.ty_tup(*inputs_span, inputs)))];
378         let binding = self.output_ty_binding(output_ty.span, output_ty);
379         (
380             GenericArgsCtor {
381                 args,
382                 bindings: arena_vec![self; binding],
383                 parenthesized: true,
384                 span: data.inputs_span,
385             },
386             false,
387         )
388     }
389
390     /// An associated type binding `Output = $ty`.
391     pub(crate) fn output_ty_binding(
392         &mut self,
393         span: Span,
394         ty: &'hir hir::Ty<'hir>,
395     ) -> hir::TypeBinding<'hir> {
396         let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
397         let kind = hir::TypeBindingKind::Equality { term: ty.into() };
398         let args = arena_vec![self;];
399         let bindings = arena_vec![self;];
400         let gen_args = self.arena.alloc(hir::GenericArgs {
401             args,
402             bindings,
403             parenthesized: false,
404             span_ext: DUMMY_SP,
405         });
406         hir::TypeBinding {
407             hir_id: self.next_id(),
408             gen_args,
409             span: self.lower_span(span),
410             ident,
411             kind,
412         }
413     }
414 }