1 use crate::ImplTraitPosition;
3 use super::errors::{GenericTypeWithParentheses, UseAngleBrackets};
4 use super::ResolverAstLoweringExt;
5 use super::{GenericArgsCtor, LifetimeRes, ParenthesizedGenericArgs};
6 use super::{ImplTraitContext, LoweringContext, ParamMode};
8 use rustc_ast::{self as ast, *};
10 use rustc_hir::def::{DefKind, PartialRes, Res};
11 use rustc_hir::GenericArg;
12 use rustc_span::symbol::{kw, sym, Ident};
13 use rustc_span::{BytePos, Span, DUMMY_SP};
15 use smallvec::{smallvec, SmallVec};
17 impl<'a, 'hir> LoweringContext<'a, 'hir> {
18 #[instrument(level = "trace", skip(self))]
19 pub(crate) fn lower_qpath(
22 qself: &Option<ptr::P<QSelf>>,
24 param_mode: ParamMode,
25 itctx: &ImplTraitContext,
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));
31 self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
32 let base_res = partial_res.base_res();
33 let unresolved_segments = partial_res.unresolved_segments();
35 let path_span_lo = p.span.shrink_to_lo();
36 let proj_start = p.segments.len() - unresolved_segments;
37 let path = self.arena.alloc(hir::Path {
38 res: self.lower_res(base_res),
39 segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
41 let param_mode = match (qself_position, param_mode) {
42 (Some(j), ParamMode::Optional) if i < j => {
43 // This segment is part of the trait path in a
44 // qualified path - one of `a`, `b` or `Trait`
45 // in `<X as a::b::Trait>::T::U::method`.
51 let parenthesized_generic_args = match base_res {
52 // `a::b::Trait(Args)`
53 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
54 ParenthesizedGenericArgs::Ok
56 // `a::b::Trait(Args)::TraitItem`
57 Res::Def(DefKind::AssocFn, _)
58 | Res::Def(DefKind::AssocConst, _)
59 | Res::Def(DefKind::AssocTy, _)
60 if i + 2 == proj_start =>
62 ParenthesizedGenericArgs::Ok
64 // Avoid duplicated errors.
65 Res::Err => ParenthesizedGenericArgs::Ok,
67 _ => ParenthesizedGenericArgs::Err,
70 self.lower_path_segment(
74 parenthesized_generic_args,
79 span: self.lower_span(
80 p.segments[..proj_start]
82 .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
86 // Simple case, either no projections, or only fully-qualified.
87 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
88 if unresolved_segments == 0 {
89 return hir::QPath::Resolved(qself, path);
92 // Create the innermost type that we're projecting from.
93 let mut ty = if path.segments.is_empty() {
94 // If the base path is empty that means there exists a
95 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
96 qself.expect("missing QSelf for <T>::...")
98 // Otherwise, the base path is an implicit `Self` type path,
99 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
100 // `<I as Iterator>::Item::default`.
101 let new_id = self.next_id();
102 self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
105 // Anything after the base path are associated "extensions",
106 // out of which all but the last one are associated types,
107 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
108 // * base path is `std::vec::Vec<T>`
109 // * "extensions" are `IntoIter`, `Item` and `clone`
111 // 1. `std::vec::Vec<T>` (created above)
112 // 2. `<std::vec::Vec<T>>::IntoIter`
113 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
114 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
115 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
116 let hir_segment = self.arena.alloc(self.lower_path_segment(
120 ParenthesizedGenericArgs::Err,
123 let qpath = hir::QPath::TypeRelative(ty, hir_segment);
125 // It's finished, return the extension of the right node type.
126 if i == p.segments.len() - 1 {
130 // Wrap the associated extension in another type node.
131 let new_id = self.next_id();
132 ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
135 // We should've returned in the for loop above.
137 self.diagnostic().span_bug(
140 "lower_qpath: no final extension segment in {}..{}",
147 pub(crate) fn lower_use_path(
149 res: SmallVec<[Res; 3]>,
151 param_mode: ParamMode,
152 ) -> &'hir hir::UsePath<'hir> {
153 self.arena.alloc(hir::UsePath {
155 segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
156 self.lower_path_segment(
160 ParenthesizedGenericArgs::Err,
161 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
164 span: self.lower_span(p.span),
168 pub(crate) fn lower_path_segment(
171 segment: &PathSegment,
172 param_mode: ParamMode,
173 parenthesized_generic_args: ParenthesizedGenericArgs,
174 itctx: &ImplTraitContext,
175 ) -> hir::PathSegment<'hir> {
176 debug!("path_span: {:?}, lower_path_segment(segment: {:?})", path_span, segment,);
177 let (mut generic_args, infer_args) = if let Some(generic_args) = segment.args.as_deref() {
179 GenericArgs::AngleBracketed(data) => {
180 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
182 GenericArgs::Parenthesized(data) => match parenthesized_generic_args {
183 ParenthesizedGenericArgs::Ok => {
184 self.lower_parenthesized_parameter_data(data, itctx)
186 ParenthesizedGenericArgs::Err => {
187 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
188 let sub = if !data.inputs.is_empty() {
189 // Start of the span to the 1st character of 1st argument
190 let open_param = data.inputs_span.shrink_to_lo().to(data
196 // Last character position of last argument to the end of the span
197 let close_param = data
203 .to(data.inputs_span.shrink_to_hi());
205 Some(UseAngleBrackets { open_param, close_param })
209 self.tcx.sess.emit_err(GenericTypeWithParentheses { span: data.span, sub });
211 self.lower_angle_bracketed_parameter_data(
212 &data.as_angle_bracketed_args(),
225 args: Default::default(),
227 parenthesized: false,
228 span: path_span.shrink_to_hi(),
230 param_mode == ParamMode::Optional,
235 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
236 if !generic_args.parenthesized && !has_lifetimes {
237 self.maybe_insert_elided_lifetimes_in_path(
245 let res = self.expect_full_res(segment.id);
246 let hir_id = self.lower_node_id(segment.id);
248 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
249 segment.ident, segment.id, hir_id,
253 ident: self.lower_ident(segment.ident),
255 res: self.lower_res(res),
257 args: if generic_args.is_empty() && generic_args.span.is_empty() {
260 Some(generic_args.into_generic_args(self))
265 fn maybe_insert_elided_lifetimes_in_path(
269 segment_ident_span: Span,
270 generic_args: &mut GenericArgsCtor<'hir>,
272 let (start, end) = match self.resolver.get_lifetime_res(segment_id) {
273 Some(LifetimeRes::ElidedAnchor { start, end }) => (start, end),
277 let expected_lifetimes = end.as_usize() - start.as_usize();
278 debug!(expected_lifetimes);
280 // Note: these spans are used for diagnostics when they can't be inferred.
281 // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
282 let elided_lifetime_span = if generic_args.span.is_empty() {
283 // If there are no brackets, use the identifier span.
284 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
285 // originating from macros, since the segment's span might be from a macro arg.
286 segment_ident_span.find_ancestor_inside(path_span).unwrap_or(path_span)
287 } else if generic_args.is_empty() {
288 // If there are brackets, but not generic arguments, then use the opening bracket
289 generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
291 // Else use an empty span right after the opening bracket.
292 generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
295 generic_args.args.insert_many(
297 (start.as_u32()..end.as_u32()).map(|i| {
298 let id = NodeId::from_u32(i);
299 let l = self.lower_lifetime(&Lifetime {
301 ident: Ident::new(kw::Empty, elided_lifetime_span),
303 GenericArg::Lifetime(l)
308 pub(crate) fn lower_angle_bracketed_parameter_data(
310 data: &AngleBracketedArgs,
311 param_mode: ParamMode,
312 itctx: &ImplTraitContext,
313 ) -> (GenericArgsCtor<'hir>, bool) {
314 let has_non_lt_args = data.args.iter().any(|arg| match arg {
315 AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
316 | AngleBracketedArg::Constraint(_) => false,
317 AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
322 .filter_map(|arg| match arg {
323 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx)),
324 AngleBracketedArg::Constraint(_) => None,
327 let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
328 AngleBracketedArg::Constraint(c) => Some(self.lower_assoc_ty_constraint(c, itctx)),
329 AngleBracketedArg::Arg(_) => None,
331 let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
332 (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
335 fn lower_parenthesized_parameter_data(
337 data: &ParenthesizedArgs,
338 itctx: &ImplTraitContext,
339 ) -> (GenericArgsCtor<'hir>, bool) {
340 // Switch to `PassThrough` mode for anonymous lifetimes; this
341 // means that we permit things like `&Ref<T>`, where `Ref` has
342 // a hidden lifetime parameter. This is needed for backwards
343 // compatibility, even in contexts like an impl header where
344 // we generally don't permit such things (see #51008).
345 let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
346 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|ty| {
347 self.lower_ty_direct(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitParam))
349 let output_ty = match output {
350 // Only allow `impl Trait` in return position. i.e.:
352 // fn f(_: impl Fn() -> impl Debug) -> impl Fn() -> impl Debug
353 // // disallowed --^^^^^^^^^^ allowed --^^^^^^^^^^
355 FnRetTy::Ty(ty) if matches!(itctx, ImplTraitContext::ReturnPositionOpaqueTy { .. }) => {
356 if self.tcx.features().impl_trait_in_fn_trait_return {
357 self.lower_ty(&ty, itctx)
361 &ImplTraitContext::FeatureGated(
362 ImplTraitPosition::FnTraitReturn,
363 sym::impl_trait_in_fn_trait_return,
369 self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn))
371 FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])),
373 let args = smallvec![GenericArg::Type(self.arena.alloc(self.ty_tup(*inputs_span, inputs)))];
374 let binding = self.output_ty_binding(output_ty.span, output_ty);
378 bindings: arena_vec![self; binding],
380 span: data.inputs_span,
386 /// An associated type binding `Output = $ty`.
387 pub(crate) fn output_ty_binding(
390 ty: &'hir hir::Ty<'hir>,
391 ) -> hir::TypeBinding<'hir> {
392 let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
393 let kind = hir::TypeBindingKind::Equality { term: ty.into() };
394 let args = arena_vec![self;];
395 let bindings = arena_vec![self;];
396 let gen_args = self.arena.alloc(hir::GenericArgs {
399 parenthesized: false,
403 hir_id: self.next_id(),
405 span: self.lower_span(span),