]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast_lowering/path.rs
Rollup merge of #68123 - crlf0710:linked_list_cursor, r=Amanieu
[rust.git] / src / librustc_ast_lowering / path.rs
1 use super::{AnonymousLifetimeMode, ImplTraitContext, LoweringContext, ParamMode};
2 use super::{GenericArgsCtor, ParenthesizedGenericArgs};
3
4 use rustc::lint::builtin::ELIDED_LIFETIMES_IN_PATHS;
5 use rustc::span_bug;
6 use rustc_error_codes::*;
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_session::lint::BuiltinLintDiagnostics;
13 use rustc_span::Span;
14 use syntax::ast::{self, *};
15
16 use log::debug;
17 use smallvec::smallvec;
18
19 impl<'a, 'hir> LoweringContext<'a, 'hir> {
20     crate fn lower_qpath(
21         &mut self,
22         id: NodeId,
23         qself: &Option<QSelf>,
24         p: &Path,
25         param_mode: ParamMode,
26         mut itctx: ImplTraitContext<'_, 'hir>,
27     ) -> hir::QPath<'hir> {
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 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::Method, _)
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.span,
113         });
114
115         // Simple case, either no projections, or only fully-qualified.
116         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
117         if partial_res.unresolved_segments() == 0 {
118             return hir::QPath::Resolved(qself, path);
119         }
120
121         // Create the innermost type that we're projecting from.
122         let mut ty = if path.segments.is_empty() {
123             // If the base path is empty that means there exists a
124             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
125             qself.expect("missing QSelf for <T>::...")
126         } else {
127             // Otherwise, the base path is an implicit `Self` type path,
128             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
129             // `<I as Iterator>::Item::default`.
130             let new_id = self.next_id();
131             self.arena.alloc(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
132         };
133
134         // Anything after the base path are associated "extensions",
135         // out of which all but the last one are associated types,
136         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
137         // * base path is `std::vec::Vec<T>`
138         // * "extensions" are `IntoIter`, `Item` and `clone`
139         // * type nodes are:
140         //   1. `std::vec::Vec<T>` (created above)
141         //   2. `<std::vec::Vec<T>>::IntoIter`
142         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
143         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
144         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
145             let segment = self.arena.alloc(self.lower_path_segment(
146                 p.span,
147                 segment,
148                 param_mode,
149                 0,
150                 ParenthesizedGenericArgs::Err,
151                 itctx.reborrow(),
152                 None,
153             ));
154             let qpath = hir::QPath::TypeRelative(ty, segment);
155
156             // It's finished, return the extension of the right node type.
157             if i == p.segments.len() - 1 {
158                 return qpath;
159             }
160
161             // Wrap the associated extension in another type node.
162             let new_id = self.next_id();
163             ty = self.arena.alloc(self.ty_path(new_id, p.span, qpath));
164         }
165
166         // We should've returned in the for loop above.
167         span_bug!(
168             p.span,
169             "lower_qpath: no final extension segment in {}..{}",
170             proj_start,
171             p.segments.len()
172         )
173     }
174
175     crate fn lower_path_extra(
176         &mut self,
177         res: Res,
178         p: &Path,
179         param_mode: ParamMode,
180         explicit_owner: Option<NodeId>,
181     ) -> &'hir hir::Path<'hir> {
182         self.arena.alloc(hir::Path {
183             res,
184             segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
185                 self.lower_path_segment(
186                     p.span,
187                     segment,
188                     param_mode,
189                     0,
190                     ParenthesizedGenericArgs::Err,
191                     ImplTraitContext::disallowed(),
192                     explicit_owner,
193                 )
194             })),
195             span: p.span,
196         })
197     }
198
199     crate fn lower_path(
200         &mut self,
201         id: NodeId,
202         p: &Path,
203         param_mode: ParamMode,
204     ) -> &'hir hir::Path<'hir> {
205         let res = self.expect_full_res(id);
206         let res = self.lower_res(res);
207         self.lower_path_extra(res, p, param_mode, None)
208     }
209
210     crate fn lower_path_segment(
211         &mut self,
212         path_span: Span,
213         segment: &PathSegment,
214         param_mode: ParamMode,
215         expected_lifetimes: usize,
216         parenthesized_generic_args: ParenthesizedGenericArgs,
217         itctx: ImplTraitContext<'_, 'hir>,
218         explicit_owner: Option<NodeId>,
219     ) -> hir::PathSegment<'hir> {
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.len() > 0 {
234                                 if let Some(split) = snippet.find('(') {
235                                     let trait_name = &snippet[0..split];
236                                     let args = &snippet[split + 1..snippet.len() - 1];
237                                     err.span_suggestion(
238                                         data.span,
239                                         "use angle brackets instead",
240                                         format!("{}<{}>", trait_name, args),
241                                         Applicability::MaybeIncorrect,
242                                     );
243                                 }
244                             }
245                         };
246                         err.emit();
247                         (
248                             self.lower_angle_bracketed_parameter_data(
249                                 &data.as_angle_bracketed_args(),
250                                 param_mode,
251                                 itctx,
252                             )
253                             .0,
254                             false,
255                         )
256                     }
257                 },
258             }
259         } else {
260             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
261         };
262
263         let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
264             GenericArg::Lifetime(_) => true,
265             _ => false,
266         });
267         let first_generic_span = generic_args
268             .args
269             .iter()
270             .map(|a| a.span())
271             .chain(generic_args.bindings.iter().map(|b| b.span))
272             .next();
273         if !generic_args.parenthesized && !has_lifetimes {
274             generic_args.args = self
275                 .elided_path_lifetimes(path_span, expected_lifetimes)
276                 .map(|lt| GenericArg::Lifetime(lt))
277                 .chain(generic_args.args.into_iter())
278                 .collect();
279             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
280                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
281                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
282                 let no_bindings = generic_args.bindings.is_empty();
283                 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
284                     // If there are no (non-implicit) generic args or associated type
285                     // bindings, our suggestion includes the angle brackets.
286                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
287                 } else {
288                     // Otherwise (sorry, this is kind of gross) we need to infer the
289                     // place to splice in the `'_, ` from the generics that do exist.
290                     let first_generic_span = first_generic_span
291                         .expect("already checked that non-lifetime args or bindings exist");
292                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
293                 };
294                 match self.anonymous_lifetime_mode {
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                     AnonymousLifetimeMode::CreateParameter => {
302                         let mut err = struct_span_err!(
303                             self.sess,
304                             path_span,
305                             E0726,
306                             "implicit elided lifetime not allowed here"
307                         );
308                         rustc::lint::add_elided_lifetime_in_path_suggestion(
309                             &self.sess,
310                             &mut err,
311                             expected_lifetimes,
312                             path_span,
313                             incl_angl_brckt,
314                             insertion_sp,
315                             suggestion,
316                         );
317                         err.emit();
318                     }
319                     AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
320                         self.resolver.lint_buffer().buffer_lint_with_diagnostic(
321                             ELIDED_LIFETIMES_IN_PATHS,
322                             CRATE_NODE_ID,
323                             path_span,
324                             "hidden lifetime parameters in types are deprecated",
325                             BuiltinLintDiagnostics::ElidedLifetimesInPaths(
326                                 expected_lifetimes,
327                                 path_span,
328                                 incl_angl_brckt,
329                                 insertion_sp,
330                                 suggestion,
331                             ),
332                         );
333                     }
334                 }
335             }
336         }
337
338         let res = self.expect_full_res(segment.id);
339         let id = if let Some(owner) = explicit_owner {
340             self.lower_node_id_with_owner(segment.id, owner)
341         } else {
342             self.lower_node_id(segment.id)
343         };
344         debug!(
345             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
346             segment.ident, segment.id, id,
347         );
348
349         hir::PathSegment {
350             ident: segment.ident,
351             hir_id: Some(id),
352             res: Some(self.lower_res(res)),
353             infer_args,
354             args: if generic_args.is_empty() {
355                 None
356             } else {
357                 Some(self.arena.alloc(generic_args.into_generic_args(self.arena)))
358             },
359         }
360     }
361
362     fn lower_angle_bracketed_parameter_data(
363         &mut self,
364         data: &AngleBracketedArgs,
365         param_mode: ParamMode,
366         mut itctx: ImplTraitContext<'_, 'hir>,
367     ) -> (GenericArgsCtor<'hir>, bool) {
368         let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
369         let has_non_lt_args = args.iter().any(|arg| match arg {
370             ast::GenericArg::Lifetime(_) => false,
371             ast::GenericArg::Type(_) => true,
372             ast::GenericArg::Const(_) => true,
373         });
374         (
375             GenericArgsCtor {
376                 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
377                 bindings: self.arena.alloc_from_iter(
378                     constraints.iter().map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow())),
379                 ),
380                 parenthesized: false,
381             },
382             !has_non_lt_args && param_mode == ParamMode::Optional,
383         )
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 { ref inputs, ref output, span } = data;
397             let inputs = this.arena.alloc_from_iter(
398                 inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())),
399             );
400             let output_ty = match output {
401                 FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
402                 FunctionRetTy::Default(_) => this.arena.alloc(this.ty_tup(span, &[])),
403             };
404             let args = smallvec![GenericArg::Type(this.ty_tup(span, inputs))];
405             let binding = this.output_ty_binding(output_ty.span, output_ty);
406             (
407                 GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true },
408                 false,
409             )
410         })
411     }
412
413     /// An associated type binding `Output = $ty`.
414     crate fn output_ty_binding(
415         &mut self,
416         span: Span,
417         ty: &'hir hir::Ty<'hir>,
418     ) -> hir::TypeBinding<'hir> {
419         let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
420         let kind = hir::TypeBindingKind::Equality { ty };
421         hir::TypeBinding { hir_id: self.next_id(), span, ident, kind }
422     }
423 }