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