]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_ast_lowering/src/path.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / compiler / rustc_ast_lowering / src / path.rs
1 use crate::ImplTraitPosition;
2
3 use super::errors::{GenericTypeWithParentheses, UseAngleBrackets};
4 use super::ResolverAstLoweringExt;
5 use super::{GenericArgsCtor, LifetimeRes, ParenthesizedGenericArgs};
6 use super::{ImplTraitContext, LoweringContext, ParamMode};
7
8 use rustc_ast::{self as ast, *};
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, PartialRes, Res};
11 use rustc_hir::GenericArg;
12 use rustc_span::symbol::{kw, Ident};
13 use rustc_span::{BytePos, Span, DUMMY_SP};
14
15 use smallvec::smallvec;
16
17 impl<'a, 'hir> LoweringContext<'a, 'hir> {
18 #[instrument(level = "trace", skip(self))]
19 pub(crate) fn lower_qpath(
20 &mut self,
21 id: NodeId,
22 qself: &Option<QSelf>,
23 p: &Path,
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));
29
30 let partial_res =
31 self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
32
33 let path_span_lo = p.span.shrink_to_lo();
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 let parenthesized_generic_args = match partial_res.base_res() {
50 // `a::b::Trait(Args)`
51 Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
52 ParenthesizedGenericArgs::Ok
53 }
54 // `a::b::Trait(Args)::TraitItem`
55 Res::Def(DefKind::AssocFn, _)
56 | Res::Def(DefKind::AssocConst, _)
57 | Res::Def(DefKind::AssocTy, _)
58 if i + 2 == proj_start =>
59 {
60 ParenthesizedGenericArgs::Ok
61 }
62 // Avoid duplicated errors.
63 Res::Err => ParenthesizedGenericArgs::Ok,
64 // An error
65 _ => ParenthesizedGenericArgs::Err,
66 };
67
68 self.lower_path_segment(
69 p.span,
70 segment,
71 param_mode,
72 parenthesized_generic_args,
73 itctx,
74 )
75 },
76 )),
77 span: self.lower_span(
78 p.segments[..proj_start]
79 .last()
80 .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
81 ),
82 });
83
84 // Simple case, either no projections, or only fully-qualified.
85 // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
86 if partial_res.unresolved_segments() == 0 {
87 return hir::QPath::Resolved(qself, path);
88 }
89
90 // Create the innermost type that we're projecting from.
91 let mut ty = if path.segments.is_empty() {
92 // If the base path is empty that means there exists a
93 // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
94 qself.expect("missing QSelf for <T>::...")
95 } else {
96 // Otherwise, the base path is an implicit `Self` type path,
97 // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
98 // `<I as Iterator>::Item::default`.
99 let new_id = self.next_id();
100 self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
101 };
102
103 // Anything after the base path are associated "extensions",
104 // out of which all but the last one are associated types,
105 // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
106 // * base path is `std::vec::Vec<T>`
107 // * "extensions" are `IntoIter`, `Item` and `clone`
108 // * type nodes are:
109 // 1. `std::vec::Vec<T>` (created above)
110 // 2. `<std::vec::Vec<T>>::IntoIter`
111 // 3. `<<std::vec::Vec<T>>::IntoIter>::Item`
112 // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
113 for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
114 let hir_segment = self.arena.alloc(self.lower_path_segment(
115 p.span,
116 segment,
117 param_mode,
118 ParenthesizedGenericArgs::Err,
119 itctx,
120 ));
121 let qpath = hir::QPath::TypeRelative(ty, hir_segment);
122
123 // It's finished, return the extension of the right node type.
124 if i == p.segments.len() - 1 {
125 return qpath;
126 }
127
128 // Wrap the associated extension in another type node.
129 let new_id = self.next_id();
130 ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
131 }
132
133 // We should've returned in the for loop above.
134
135 self.diagnostic().span_bug(
136 p.span,
137 &format!(
138 "lower_qpath: no final extension segment in {}..{}",
139 proj_start,
140 p.segments.len()
141 ),
142 );
143 }
144
145 pub(crate) fn lower_path_extra(
146 &mut self,
147 res: Res,
148 p: &Path,
149 param_mode: ParamMode,
150 ) -> &'hir hir::Path<'hir> {
151 self.arena.alloc(hir::Path {
152 res,
153 segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
154 self.lower_path_segment(
155 p.span,
156 segment,
157 param_mode,
158 ParenthesizedGenericArgs::Err,
159 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
160 )
161 })),
162 span: self.lower_span(p.span),
163 })
164 }
165
166 pub(crate) fn lower_path(
167 &mut self,
168 id: NodeId,
169 p: &Path,
170 param_mode: ParamMode,
171 ) -> &'hir hir::Path<'hir> {
172 let res = self.expect_full_res(id);
173 let res = self.lower_res(res);
174 self.lower_path_extra(res, p, param_mode)
175 }
176
177 pub(crate) fn lower_path_segment(
178 &mut self,
179 path_span: Span,
180 segment: &PathSegment,
181 param_mode: ParamMode,
182 parenthesized_generic_args: ParenthesizedGenericArgs,
183 itctx: &ImplTraitContext,
184 ) -> hir::PathSegment<'hir> {
185 debug!("path_span: {:?}, lower_path_segment(segment: {:?})", path_span, segment,);
186 let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args {
187 match **generic_args {
188 GenericArgs::AngleBracketed(ref data) => {
189 self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
190 }
191 GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
192 ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
193 ParenthesizedGenericArgs::Err => {
194 // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
195 let sub = if !data.inputs.is_empty() {
196 // Start of the span to the 1st character of 1st argument
197 let open_param = data.inputs_span.shrink_to_lo().to(data
198 .inputs
199 .first()
200 .unwrap()
201 .span
202 .shrink_to_lo());
203 // Last character position of last argument to the end of the span
204 let close_param = data
205 .inputs
206 .last()
207 .unwrap()
208 .span
209 .shrink_to_hi()
210 .to(data.inputs_span.shrink_to_hi());
211
212 Some(UseAngleBrackets { open_param, close_param })
213 } else {
214 None
215 };
216 self.tcx.sess.emit_err(GenericTypeWithParentheses { span: data.span, sub });
217 (
218 self.lower_angle_bracketed_parameter_data(
219 &data.as_angle_bracketed_args(),
220 param_mode,
221 itctx,
222 )
223 .0,
224 false,
225 )
226 }
227 },
228 }
229 } else {
230 (
231 GenericArgsCtor {
232 args: Default::default(),
233 bindings: &[],
234 parenthesized: false,
235 span: path_span.shrink_to_hi(),
236 },
237 param_mode == ParamMode::Optional,
238 )
239 };
240
241 let has_lifetimes =
242 generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
243 if !generic_args.parenthesized && !has_lifetimes {
244 self.maybe_insert_elided_lifetimes_in_path(
245 path_span,
246 segment.id,
247 segment.ident.span,
248 &mut generic_args,
249 );
250 }
251
252 let res = self.expect_full_res(segment.id);
253 let hir_id = self.lower_node_id(segment.id);
254 debug!(
255 "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
256 segment.ident, segment.id, hir_id,
257 );
258
259 hir::PathSegment {
260 ident: self.lower_ident(segment.ident),
261 hir_id,
262 res: self.lower_res(res),
263 infer_args,
264 args: if generic_args.is_empty() && generic_args.span.is_empty() {
265 None
266 } else {
267 Some(generic_args.into_generic_args(self))
268 },
269 }
270 }
271
272 fn maybe_insert_elided_lifetimes_in_path(
273 &mut self,
274 path_span: Span,
275 segment_id: NodeId,
276 segment_ident_span: Span,
277 generic_args: &mut GenericArgsCtor<'hir>,
278 ) {
279 let (start, end) = match self.resolver.get_lifetime_res(segment_id) {
280 Some(LifetimeRes::ElidedAnchor { start, end }) => (start, end),
281 None => return,
282 Some(_) => panic!(),
283 };
284 let expected_lifetimes = end.as_usize() - start.as_usize();
285 debug!(expected_lifetimes);
286
287 // Note: these spans are used for diagnostics when they can't be inferred.
288 // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
289 let elided_lifetime_span = if generic_args.span.is_empty() {
290 // If there are no brackets, use the identifier span.
291 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
292 // originating from macros, since the segment's span might be from a macro arg.
293 segment_ident_span.find_ancestor_inside(path_span).unwrap_or(path_span)
294 } else if generic_args.is_empty() {
295 // If there are brackets, but not generic arguments, then use the opening bracket
296 generic_args.span.with_hi(generic_args.span.lo() + BytePos(1))
297 } else {
298 // Else use an empty span right after the opening bracket.
299 generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo()
300 };
301
302 generic_args.args.insert_many(
303 0,
304 (start.as_u32()..end.as_u32()).map(|i| {
305 let id = NodeId::from_u32(i);
306 let l = self.lower_lifetime(&Lifetime {
307 id,
308 ident: Ident::new(kw::UnderscoreLifetime, elided_lifetime_span),
309 });
310 GenericArg::Lifetime(l)
311 }),
312 );
313 }
314
315 pub(crate) fn lower_angle_bracketed_parameter_data(
316 &mut self,
317 data: &AngleBracketedArgs,
318 param_mode: ParamMode,
319 itctx: &ImplTraitContext,
320 ) -> (GenericArgsCtor<'hir>, bool) {
321 let has_non_lt_args = data.args.iter().any(|arg| match arg {
322 AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
323 | AngleBracketedArg::Constraint(_) => false,
324 AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
325 });
326 let args = data
327 .args
328 .iter()
329 .filter_map(|arg| match arg {
330 AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx)),
331 AngleBracketedArg::Constraint(_) => None,
332 })
333 .collect();
334 let bindings = self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
335 AngleBracketedArg::Constraint(c) => Some(self.lower_assoc_ty_constraint(c, itctx)),
336 AngleBracketedArg::Arg(_) => None,
337 }));
338 let ctor = GenericArgsCtor { args, bindings, parenthesized: false, span: data.span };
339 (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
340 }
341
342 fn lower_parenthesized_parameter_data(
343 &mut self,
344 data: &ParenthesizedArgs,
345 ) -> (GenericArgsCtor<'hir>, bool) {
346 // Switch to `PassThrough` mode for anonymous lifetimes; this
347 // means that we permit things like `&Ref<T>`, where `Ref` has
348 // a hidden lifetime parameter. This is needed for backwards
349 // compatibility, even in contexts like an impl header where
350 // we generally don't permit such things (see #51008).
351 let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
352 let inputs = self.arena.alloc_from_iter(inputs.iter().map(|ty| {
353 self.lower_ty_direct(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitParam))
354 }));
355 let output_ty = match output {
356 FnRetTy::Ty(ty) => {
357 self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn))
358 }
359 FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])),
360 };
361 let args = smallvec![GenericArg::Type(self.arena.alloc(self.ty_tup(*inputs_span, inputs)))];
362 let binding = self.output_ty_binding(output_ty.span, output_ty);
363 (
364 GenericArgsCtor {
365 args,
366 bindings: arena_vec![self; binding],
367 parenthesized: true,
368 span: data.inputs_span,
369 },
370 false,
371 )
372 }
373
374 /// An associated type binding `Output = $ty`.
375 pub(crate) fn output_ty_binding(
376 &mut self,
377 span: Span,
378 ty: &'hir hir::Ty<'hir>,
379 ) -> hir::TypeBinding<'hir> {
380 let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
381 let kind = hir::TypeBindingKind::Equality { term: ty.into() };
382 let args = arena_vec![self;];
383 let bindings = arena_vec![self;];
384 let gen_args = self.arena.alloc(hir::GenericArgs {
385 args,
386 bindings,
387 parenthesized: false,
388 span_ext: DUMMY_SP,
389 });
390 hir::TypeBinding {
391 hir_id: self.next_id(),
392 gen_args,
393 span: self.lower_span(span),
394 ident,
395 kind,
396 }
397 }
398 }