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