]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/path.rs
Rollup merge of #93827 - eholk:stabilize-const_fn-features, r=wesleywiser
[rust.git] / compiler / rustc_ast_lowering / src / path.rs
1 use crate::ImplTraitPosition;
2
3 use super::{AnonymousLifetimeMode, ImplTraitContext, LoweringContext, ParamMode};
4 use super::{GenericArgsCtor, ParenthesizedGenericArgs};
5
6 use rustc_ast::{self as ast, *};
7 use rustc_errors::{struct_span_err, Applicability};
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, PartialRes, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::GenericArg;
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(ImplTraitPosition::Path),
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                                 // Suggest replacing `(` and `)` with `<` and `>`
235                                 // The snippet may be missing the closing `)`, skip that case
236                                 if snippet.ends_with(')') {
237                                     if let Some(split) = snippet.find('(') {
238                                         let trait_name = &snippet[0..split];
239                                         let args = &snippet[split + 1..snippet.len() - 1];
240                                         err.span_suggestion(
241                                             data.span,
242                                             "use angle brackets instead",
243                                             format!("{}<{}>", trait_name, args),
244                                             Applicability::MaybeIncorrect,
245                                         );
246                                     }
247                                 }
248                             }
249                         };
250                         err.emit();
251                         (
252                             self.lower_angle_bracketed_parameter_data(
253                                 &data.as_angle_bracketed_args(),
254                                 param_mode,
255                                 itctx,
256                             )
257                             .0,
258                             false,
259                         )
260                     }
261                 },
262             }
263         } else {
264             (
265                 GenericArgsCtor {
266                     args: Default::default(),
267                     bindings: &[],
268                     parenthesized: false,
269                     span: path_span.shrink_to_hi(),
270                 },
271                 param_mode == ParamMode::Optional,
272             )
273         };
274
275         let has_lifetimes =
276             generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
277         if !generic_args.parenthesized && !has_lifetimes && expected_lifetimes > 0 {
278             // Note: these spans are used for diagnostics when they can't be inferred.
279             // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
280             let elided_lifetime_span = if generic_args.span.is_empty() {
281                 // If there are no brackets, use the identifier span.
282                 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
283                 // originating from macros, since the segment's span might be from a macro arg.
284                 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
285             } else if generic_args.is_empty() {
286                 // If there are brackets, but not generic arguments, then use the opening bracket
287                 generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
288             } else {
289                 // Else use an empty span right after the opening bracket.
290                 generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
291             };
292             generic_args.args = self
293                 .elided_path_lifetimes(elided_lifetime_span, expected_lifetimes, param_mode)
294                 .map(GenericArg::Lifetime)
295                 .chain(generic_args.args.into_iter())
296                 .collect();
297             // In create-parameter mode we error here because we don't want to support
298             // deprecated impl elision in new features like impl elision and `async fn`,
299             // both of which work using the `CreateParameter` mode:
300             //
301             //     impl Foo for std::cell::Ref<u32> // note lack of '_
302             //     async fn foo(_: std::cell::Ref<u32>) { ... }
303             if let (ParamMode::Explicit, AnonymousLifetimeMode::CreateParameter) =
304                 (param_mode, self.anonymous_lifetime_mode)
305             {
306                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
307                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
308                 let no_bindings = generic_args.bindings.is_empty();
309                 let (incl_angl_brckt, suggestion) = if no_non_lt_args && no_bindings {
310                     // If there are no generic args, our suggestion can include the angle brackets.
311                     (true, format!("<{}>", anon_lt_suggestion))
312                 } else {
313                     // Otherwise we'll insert a `'_, ` right after the opening bracket.
314                     (false, format!("{}, ", anon_lt_suggestion))
315                 };
316                 let insertion_sp = elided_lifetime_span.shrink_to_hi();
317                 let mut err = struct_span_err!(
318                     self.sess,
319                     path_span,
320                     E0726,
321                     "implicit elided lifetime not allowed here"
322                 );
323                 rustc_errors::add_elided_lifetime_in_path_suggestion(
324                     &self.sess.source_map(),
325                     &mut err,
326                     expected_lifetimes,
327                     path_span,
328                     incl_angl_brckt,
329                     insertion_sp,
330                     suggestion,
331                 );
332                 err.note("assuming a `'static` lifetime...");
333                 err.emit();
334             }
335         }
336
337         let res = self.expect_full_res(segment.id);
338         let id = self.lower_node_id(segment.id);
339         debug!(
340             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
341             segment.ident, segment.id, id,
342         );
343
344         hir::PathSegment {
345             ident: self.lower_ident(segment.ident),
346             hir_id: Some(id),
347             res: Some(self.lower_res(res)),
348             infer_args,
349             args: if generic_args.is_empty() && generic_args.span.is_empty() {
350                 None
351             } else {
352                 Some(generic_args.into_generic_args(self))
353             },
354         }
355     }
356
357     pub(crate) fn lower_angle_bracketed_parameter_data(
358         &mut self,
359         data: &AngleBracketedArgs,
360         param_mode: ParamMode,
361         mut itctx: ImplTraitContext<'_, 'hir>,
362     ) -> (GenericArgsCtor<'hir>, bool) {
363         let has_non_lt_args = data.args.iter().any(|arg| match arg {
364             AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
365             | AngleBracketedArg::Constraint(_) => false,
366             AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
367         });
368         let args = data
369             .args
370             .iter()
371             .filter_map(|arg| match arg {
372                 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx.reborrow())),
373                 AngleBracketedArg::Constraint(_) => None,
374             })
375             .collect();
376         let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
377             AngleBracketedArg::Constraint(c) => {
378                 Some(self.lower_assoc_ty_constraint(c, itctx.reborrow()))
379             }
380             AngleBracketedArg::Arg(_) => None,
381         }));
382         let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
383         (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
384     }
385
386     fn lower_parenthesized_parameter_data(
387         &mut self,
388         data: &ParenthesizedArgs,
389     ) -> (GenericArgsCtor<'hir>, bool) {
390         // Switch to `PassThrough` mode for anonymous lifetimes; this
391         // means that we permit things like `&Ref<T>`, where `Ref` has
392         // a hidden lifetime parameter. This is needed for backwards
393         // compatibility, even in contexts like an impl header where
394         // we generally don't permit such things (see #51008).
395         self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
396             let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
397             let inputs = this.arena.alloc_from_iter(inputs.iter().map(|ty| {
398                 this.lower_ty_direct(
399                     ty,
400                     ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitParam),
401                 )
402             }));
403             let output_ty = match output {
404                 FnRetTy::Ty(ty) => this
405                     .lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn)),
406                 FnRetTy::Default(_) => this.arena.alloc(this.ty_tup(*span, &[])),
407             };
408             let args = smallvec![GenericArg::Type(this.ty_tup(*inputs_span, inputs))];
409             let binding = this.output_ty_binding(output_ty.span, output_ty);
410             (
411                 GenericArgsCtor {
412                     args,
413                     bindings: arena_vec![this; binding],
414                     parenthesized: true,
415                     span: data.inputs_span,
416                 },
417                 false,
418             )
419         })
420     }
421
422     /// An associated type binding `Output = $ty`.
423     crate fn output_ty_binding(
424         &mut self,
425         span: Span,
426         ty: &'hir hir::Ty<'hir>,
427     ) -> hir::TypeBinding<'hir> {
428         let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
429         let kind = hir::TypeBindingKind::Equality { term: ty.into() };
430         let args = arena_vec![self;];
431         let bindings = arena_vec![self;];
432         let gen_args = self.arena.alloc(hir::GenericArgs {
433             args,
434             bindings,
435             parenthesized: false,
436             span_ext: DUMMY_SP,
437         });
438         hir::TypeBinding {
439             hir_id: self.next_id(),
440             gen_args,
441             span: self.lower_span(span),
442             ident,
443             kind,
444         }
445     }
446 }