]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast_lowering/path.rs
refactor 'Output = $ty' & reduce rustc dep
[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::{self, 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_span::Span;
13 use syntax::ast::{self, *};
14
15 use log::debug;
16 use smallvec::smallvec;
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         let qself_position = qself.as_ref().map(|q| q.position);
28         let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow()));
29
30         let partial_res =
31             self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
32
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.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::Method, _)
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.map_or(0, |def_id| {
92                         if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
93                             return n;
94                         }
95                         assert!(!def_id.is_local());
96                         let item_generics = self
97                             .resolver
98                             .cstore()
99                             .item_generics_cloned_untracked(def_id, self.sess);
100                         let n = item_generics.own_counts().lifetimes;
101                         self.type_def_lifetime_params.insert(def_id, n);
102                         n
103                     });
104                     self.lower_path_segment(
105                         p.span,
106                         segment,
107                         param_mode,
108                         num_lifetimes,
109                         parenthesized_generic_args,
110                         itctx.reborrow(),
111                         None,
112                     )
113                 },
114             )),
115             span: p.span,
116         });
117
118         // Simple case, either no projections, or only fully-qualified.
119         // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
120         if partial_res.unresolved_segments() == 0 {
121             return hir::QPath::Resolved(qself, path);
122         }
123
124         // Create the innermost type that we're projecting from.
125         let mut ty = if path.segments.is_empty() {
126             // If the base path is empty that means there exists a
127             // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
128             qself.expect("missing QSelf for <T>::...")
129         } else {
130             // Otherwise, the base path is an implicit `Self` type path,
131             // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
132             // `<I as Iterator>::Item::default`.
133             let new_id = self.next_id();
134             self.arena.alloc(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path)))
135         };
136
137         // Anything after the base path are associated "extensions",
138         // out of which all but the last one are associated types,
139         // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
140         // * base path is `std::vec::Vec<T>`
141         // * "extensions" are `IntoIter`, `Item` and `clone`
142         // * type nodes are:
143         //   1. `std::vec::Vec<T>` (created above)
144         //   2. `<std::vec::Vec<T>>::IntoIter`
145         //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
146         // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
147         for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
148             let segment = self.arena.alloc(self.lower_path_segment(
149                 p.span,
150                 segment,
151                 param_mode,
152                 0,
153                 ParenthesizedGenericArgs::Err,
154                 itctx.reborrow(),
155                 None,
156             ));
157             let qpath = hir::QPath::TypeRelative(ty, segment);
158
159             // It's finished, return the extension of the right node type.
160             if i == p.segments.len() - 1 {
161                 return qpath;
162             }
163
164             // Wrap the associated extension in another type node.
165             let new_id = self.next_id();
166             ty = self.arena.alloc(self.ty_path(new_id, p.span, qpath));
167         }
168
169         // We should've returned in the for loop above.
170         span_bug!(
171             p.span,
172             "lower_qpath: no final extension segment in {}..{}",
173             proj_start,
174             p.segments.len()
175         )
176     }
177
178     crate fn lower_path_extra(
179         &mut self,
180         res: Res,
181         p: &Path,
182         param_mode: ParamMode,
183         explicit_owner: Option<NodeId>,
184     ) -> &'hir hir::Path<'hir> {
185         self.arena.alloc(hir::Path {
186             res,
187             segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
188                 self.lower_path_segment(
189                     p.span,
190                     segment,
191                     param_mode,
192                     0,
193                     ParenthesizedGenericArgs::Err,
194                     ImplTraitContext::disallowed(),
195                     explicit_owner,
196                 )
197             })),
198             span: p.span,
199         })
200     }
201
202     crate fn lower_path(
203         &mut self,
204         id: NodeId,
205         p: &Path,
206         param_mode: ParamMode,
207     ) -> &'hir hir::Path<'hir> {
208         let res = self.expect_full_res(id);
209         let res = self.lower_res(res);
210         self.lower_path_extra(res, p, param_mode, None)
211     }
212
213     crate fn lower_path_segment(
214         &mut self,
215         path_span: Span,
216         segment: &PathSegment,
217         param_mode: ParamMode,
218         expected_lifetimes: usize,
219         parenthesized_generic_args: ParenthesizedGenericArgs,
220         itctx: ImplTraitContext<'_, 'hir>,
221         explicit_owner: Option<NodeId>,
222     ) -> hir::PathSegment<'hir> {
223         let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
224             let msg = "parenthesized type parameters may only be used with a `Fn` trait";
225             match **generic_args {
226                 GenericArgs::AngleBracketed(ref data) => {
227                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
228                 }
229                 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
230                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
231                     ParenthesizedGenericArgs::Err => {
232                         let mut err = struct_span_err!(self.sess, data.span, E0214, "{}", msg);
233                         err.span_label(data.span, "only `Fn` traits may use parentheses");
234                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(data.span) {
235                             // Do not suggest going from `Trait()` to `Trait<>`
236                             if data.inputs.len() > 0 {
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                         err.emit();
250                         (
251                             self.lower_angle_bracketed_parameter_data(
252                                 &data.as_angle_bracketed_args(),
253                                 param_mode,
254                                 itctx,
255                             )
256                             .0,
257                             false,
258                         )
259                     }
260                 },
261             }
262         } else {
263             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
264         };
265
266         let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
267             GenericArg::Lifetime(_) => true,
268             _ => false,
269         });
270         let first_generic_span = generic_args
271             .args
272             .iter()
273             .map(|a| a.span())
274             .chain(generic_args.bindings.iter().map(|b| b.span))
275             .next();
276         if !generic_args.parenthesized && !has_lifetimes {
277             generic_args.args = self
278                 .elided_path_lifetimes(path_span, expected_lifetimes)
279                 .map(|lt| GenericArg::Lifetime(lt))
280                 .chain(generic_args.args.into_iter())
281                 .collect();
282             if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {
283                 let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", ");
284                 let no_non_lt_args = generic_args.args.len() == expected_lifetimes;
285                 let no_bindings = generic_args.bindings.is_empty();
286                 let (incl_angl_brckt, insertion_sp, suggestion) = if no_non_lt_args && no_bindings {
287                     // If there are no (non-implicit) generic args or associated type
288                     // bindings, our suggestion includes the angle brackets.
289                     (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion))
290                 } else {
291                     // Otherwise (sorry, this is kind of gross) we need to infer the
292                     // place to splice in the `'_, ` from the generics that do exist.
293                     let first_generic_span = first_generic_span
294                         .expect("already checked that non-lifetime args or bindings exist");
295                     (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion))
296                 };
297                 match self.anonymous_lifetime_mode {
298                     // In create-parameter mode we error here because we don't want to support
299                     // deprecated impl elision in new features like impl elision and `async fn`,
300                     // both of which work using the `CreateParameter` mode:
301                     //
302                     //     impl Foo for std::cell::Ref<u32> // note lack of '_
303                     //     async fn foo(_: std::cell::Ref<u32>) { ... }
304                     AnonymousLifetimeMode::CreateParameter => {
305                         let mut err = struct_span_err!(
306                             self.sess,
307                             path_span,
308                             E0726,
309                             "implicit elided lifetime not allowed here"
310                         );
311                         crate::lint::builtin::add_elided_lifetime_in_path_suggestion(
312                             &self.sess,
313                             &mut err,
314                             expected_lifetimes,
315                             path_span,
316                             incl_angl_brckt,
317                             insertion_sp,
318                             suggestion,
319                         );
320                         err.emit();
321                     }
322                     AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
323                         self.resolver.lint_buffer().buffer_lint_with_diagnostic(
324                             ELIDED_LIFETIMES_IN_PATHS,
325                             CRATE_NODE_ID,
326                             path_span,
327                             "hidden lifetime parameters in types are deprecated",
328                             builtin::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
329                                 expected_lifetimes,
330                                 path_span,
331                                 incl_angl_brckt,
332                                 insertion_sp,
333                                 suggestion,
334                             ),
335                         );
336                     }
337                 }
338             }
339         }
340
341         let res = self.expect_full_res(segment.id);
342         let id = if let Some(owner) = explicit_owner {
343             self.lower_node_id_with_owner(segment.id, owner)
344         } else {
345             self.lower_node_id(segment.id)
346         };
347         debug!(
348             "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
349             segment.ident, segment.id, id,
350         );
351
352         hir::PathSegment {
353             ident: segment.ident,
354             hir_id: Some(id),
355             res: Some(self.lower_res(res)),
356             infer_args,
357             args: if generic_args.is_empty() {
358                 None
359             } else {
360                 Some(self.arena.alloc(generic_args.into_generic_args(self.arena)))
361             },
362         }
363     }
364
365     fn lower_angle_bracketed_parameter_data(
366         &mut self,
367         data: &AngleBracketedArgs,
368         param_mode: ParamMode,
369         mut itctx: ImplTraitContext<'_, 'hir>,
370     ) -> (GenericArgsCtor<'hir>, bool) {
371         let &AngleBracketedArgs { ref args, ref constraints, .. } = data;
372         let has_non_lt_args = args.iter().any(|arg| match arg {
373             ast::GenericArg::Lifetime(_) => false,
374             ast::GenericArg::Type(_) => true,
375             ast::GenericArg::Const(_) => true,
376         });
377         (
378             GenericArgsCtor {
379                 args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(),
380                 bindings: self.arena.alloc_from_iter(
381                     constraints.iter().map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow())),
382                 ),
383                 parenthesized: false,
384             },
385             !has_non_lt_args && param_mode == ParamMode::Optional,
386         )
387     }
388
389     fn lower_parenthesized_parameter_data(
390         &mut self,
391         data: &ParenthesizedArgs,
392     ) -> (GenericArgsCtor<'hir>, bool) {
393         // Switch to `PassThrough` mode for anonymous lifetimes; this
394         // means that we permit things like `&Ref<T>`, where `Ref` has
395         // a hidden lifetime parameter. This is needed for backwards
396         // compatibility, even in contexts like an impl header where
397         // we generally don't permit such things (see #51008).
398         self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| {
399             let &ParenthesizedArgs { ref inputs, ref output, span } = data;
400             let inputs = this.arena.alloc_from_iter(
401                 inputs.iter().map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())),
402             );
403             let output_ty = match output {
404                 FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()),
405                 FunctionRetTy::Default(_) => this.arena.alloc(this.ty_tup(span, &[])),
406             };
407             let args = smallvec![GenericArg::Type(this.ty_tup(span, inputs))];
408             let binding = this.output_ty_binding(output_ty.span, output_ty);
409             (
410                 GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true },
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 { ty };
424         hir::TypeBinding { hir_id: self.next_id(), span, ident, kind }
425     }
426 }