]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/path.rs
Auto merge of #103071 - wesleywiser:fix_inlined_line_numbers, r=davidtwco
[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 => self.lower_parenthesized_parameter_data(data),
195                     ParenthesizedGenericArgs::Err => {
196                         // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
197                         let sub = if !data.inputs.is_empty() {
198                             // Start of the span to the 1st character of 1st argument
199                             let open_param = data.inputs_span.shrink_to_lo().to(data
200                                 .inputs
201                                 .first()
202                                 .unwrap()
203                                 .span
204                                 .shrink_to_lo());
205                             // Last character position of last argument to the end of the span
206                             let close_param = data
207                                 .inputs
208                                 .last()
209                                 .unwrap()
210                                 .span
211                                 .shrink_to_hi()
212                                 .to(data.inputs_span.shrink_to_hi());
213
214                             Some(UseAngleBrackets { open_param, close_param })
215                         } else {
216                             None
217                         };
218                         self.tcx.sess.emit_err(GenericTypeWithParentheses { span: data.span, sub });
219                         (
220                             self.lower_angle_bracketed_parameter_data(
221                                 &data.as_angle_bracketed_args(),
222                                 param_mode,
223                                 itctx,
224                             )
225                             .0,
226                             false,
227                         )
228                     }
229                 },
230             }
231         } else {
232             (
233                 GenericArgsCtor {
234                     args: Default::default(),
235                     bindings: &[],
236                     parenthesized: false,
237                     span: path_span.shrink_to_hi(),
238                 },
239                 param_mode == ParamMode::Optional,
240             )
241         };
242
243         let has_lifetimes =
244             generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
245         if !generic_args.parenthesized && !has_lifetimes {
246             self.maybe_insert_elided_lifetimes_in_path(
247                 path_span,
248                 segment.id,
249                 segment.ident.span,
250                 &mut generic_args,
251             );
252         }
253
254         let res = self.expect_full_res(segment.id);
255         let hir_id = self.lower_node_id(segment.id);
256         debug!(
257             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
258             segment.ident, segment.id, hir_id,
259         );
260
261         hir::PathSegment {
262             ident: self.lower_ident(segment.ident),
263             hir_id,
264             res: self.lower_res(res),
265             infer_args,
266             args: if generic_args.is_empty() && generic_args.span.is_empty() {
267                 None
268             } else {
269                 Some(generic_args.into_generic_args(self))
270             },
271         }
272     }
273
274     fn maybe_insert_elided_lifetimes_in_path(
275         &mut self,
276         path_span: Span,
277         segment_id: NodeId,
278         segment_ident_span: Span,
279         generic_args: &mut GenericArgsCtor<'hir>,
280     ) {
281         let (start, end) = match self.resolver.get_lifetime_res(segment_id) {
282             Some(LifetimeRes::ElidedAnchor { start, end }) => (start, end),
283             None => return,
284             Some(_) => panic!(),
285         };
286         let expected_lifetimes = end.as_usize() - start.as_usize();
287         debug!(expected_lifetimes);
288
289         // Note: these spans are used for diagnostics when they can't be inferred.
290         // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
291         let elided_lifetime_span = if generic_args.span.is_empty() {
292             // If there are no brackets, use the identifier span.
293             // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
294             // originating from macros, since the segment's span might be from a macro arg.
295             segment_ident_span.find_ancestor_inside(path_span).unwrap_or(path_span)
296         } else if generic_args.is_empty() {
297             // If there are brackets, but not generic arguments, then use the opening bracket
298             generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
299         } else {
300             // Else use an empty span right after the opening bracket.
301             generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
302         };
303
304         generic_args.args.insert_many(
305             0,
306             (start.as_u32()..end.as_u32()).map(|i| {
307                 let id = NodeId::from_u32(i);
308                 let l = self.lower_lifetime(&Lifetime {
309                     id,
310                     ident: Ident::new(kw::UnderscoreLifetime, elided_lifetime_span),
311                 });
312                 GenericArg::Lifetime(l)
313             }),
314         );
315     }
316
317     pub(crate) fn lower_angle_bracketed_parameter_data(
318         &mut self,
319         data: &AngleBracketedArgs,
320         param_mode: ParamMode,
321         itctx: &ImplTraitContext,
322     ) -> (GenericArgsCtor<'hir>, bool) {
323         let has_non_lt_args = data.args.iter().any(|arg| match arg {
324             AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
325             | AngleBracketedArg::Constraint(_) => false,
326             AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
327         });
328         let args = data
329             .args
330             .iter()
331             .filter_map(|arg| match arg {
332                 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx)),
333                 AngleBracketedArg::Constraint(_) => None,
334             })
335             .collect();
336         let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
337             AngleBracketedArg::Constraint(c) => Some(self.lower_assoc_ty_constraint(c, itctx)),
338             AngleBracketedArg::Arg(_) => None,
339         }));
340         let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
341         (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
342     }
343
344     fn lower_parenthesized_parameter_data(
345         &mut self,
346         data: &ParenthesizedArgs,
347     ) -> (GenericArgsCtor<'hir>, bool) {
348         // Switch to `PassThrough` mode for anonymous lifetimes; this
349         // means that we permit things like `&Ref<T>`, where `Ref` has
350         // a hidden lifetime parameter. This is needed for backwards
351         // compatibility, even in contexts like an impl header where
352         // we generally don't permit such things (see #51008).
353         let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
354         let inputs = self.arena.alloc_from_iter(inputs.iter().map(|ty| {
355             self.lower_ty_direct(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitParam))
356         }));
357         let output_ty = match output {
358             FnRetTy::Ty(ty) => {
359                 self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn))
360             }
361             FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])),
362         };
363         let args = smallvec![GenericArg::Type(self.arena.alloc(self.ty_tup(*inputs_span, inputs)))];
364         let binding = self.output_ty_binding(output_ty.span, output_ty);
365         (
366             GenericArgsCtor {
367                 args,
368                 bindings: arena_vec![self; binding],
369                 parenthesized: true,
370                 span: data.inputs_span,
371             },
372             false,
373         )
374     }
375
376     /// An associated type binding `Output = $ty`.
377     pub(crate) fn output_ty_binding(
378         &mut self,
379         span: Span,
380         ty: &'hir hir::Ty<'hir>,
381     ) -> hir::TypeBinding<'hir> {
382         let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
383         let kind = hir::TypeBindingKind::Equality { term: ty.into() };
384         let args = arena_vec![self;];
385         let bindings = arena_vec![self;];
386         let gen_args = self.arena.alloc(hir::GenericArgs {
387             args,
388             bindings,
389             parenthesized: false,
390             span_ext: DUMMY_SP,
391         });
392         hir::TypeBinding {
393             hir_id: self.next_id(),
394             gen_args,
395             span: self.lower_span(span),
396             ident,
397             kind,
398         }
399     }
400 }