1 use super::{AnonymousLifetimeMode, ImplTraitContext, LoweringContext, ParamMode};
2 use super::{GenericArgsCtor, ParenthesizedGenericArgs};
4 use rustc::lint::builtin::ELIDED_LIFETIMES_IN_PATHS;
6 use rustc_error_codes::*;
7 use rustc_errors::{struct_span_err, Applicability};
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;
14 use syntax::ast::{self, *};
17 use smallvec::smallvec;
19 impl<'a, 'hir> LoweringContext<'a, 'hir> {
23 qself: &Option<QSelf>,
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()));
32 self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
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(
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`.
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 {
53 index: this.resolver.def_key(def_id).parent.expect("missing parent"),
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))
59 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
60 Some(parent_def_id(self, def_id))
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 =>
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
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 =>
84 ParenthesizedGenericArgs::Ok
86 // Avoid duplicated errors.
87 Res::Err => ParenthesizedGenericArgs::Ok,
89 _ => ParenthesizedGenericArgs::Err,
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) {
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);
101 self.lower_path_segment(
106 parenthesized_generic_args,
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);
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>::...")
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)))
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`
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(
150 ParenthesizedGenericArgs::Err,
154 let qpath = hir::QPath::TypeRelative(ty, segment);
156 // It's finished, return the extension of the right node type.
157 if i == p.segments.len() - 1 {
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));
166 // We should've returned in the for loop above.
169 "lower_qpath: no final extension segment in {}..{}",
175 crate fn lower_path_extra(
179 param_mode: ParamMode,
180 explicit_owner: Option<NodeId>,
181 ) -> &'hir hir::Path<'hir> {
182 self.arena.alloc(hir::Path {
184 segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
185 self.lower_path_segment(
190 ParenthesizedGenericArgs::Err,
191 ImplTraitContext::disallowed(),
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)
210 crate fn lower_path_segment(
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)
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];
239 "use angle brackets instead",
240 format!("{}<{}>", trait_name, args),
241 Applicability::MaybeIncorrect,
248 self.lower_angle_bracketed_parameter_data(
249 &data.as_angle_bracketed_args(),
260 self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
263 let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
264 GenericArg::Lifetime(_) => true,
267 let first_generic_span = generic_args
271 .chain(generic_args.bindings.iter().map(|b| b.span))
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())
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))
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))
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:
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!(
306 "implicit elided lifetime not allowed here"
308 rustc::lint::add_elided_lifetime_in_path_suggestion(
319 AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => {
320 self.resolver.lint_buffer().buffer_lint_with_diagnostic(
321 ELIDED_LIFETIMES_IN_PATHS,
324 "hidden lifetime parameters in types are deprecated",
325 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
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)
342 self.lower_node_id(segment.id)
345 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
346 segment.ident, segment.id, id,
350 ident: segment.ident,
352 res: Some(self.lower_res(res)),
354 args: if generic_args.is_empty() {
357 Some(self.arena.alloc(generic_args.into_generic_args(self.arena)))
362 fn lower_angle_bracketed_parameter_data(
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,
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())),
380 parenthesized: false,
382 !has_non_lt_args && param_mode == ParamMode::Optional,
386 fn lower_parenthesized_parameter_data(
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())),
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, &[])),
404 let args = smallvec![GenericArg::Type(this.ty_tup(span, inputs))];
405 let binding = this.output_ty_binding(output_ty.span, output_ty);
407 GenericArgsCtor { args, bindings: arena_vec![this; binding], parenthesized: true },
413 /// An associated type binding `Output = $ty`.
414 crate fn output_ty_binding(
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 }