Skip to main content

hir_ty/lower/
path.rs

1//! A wrapper around [`TyLoweringContext`] specifically for lowering paths.
2
3use either::Either;
4use hir_def::{
5    GenericDefId, GenericParamId, Lookup, TraitId, TypeParamId,
6    expr_store::{
7        ExpressionStore, HygieneId,
8        path::{
9            GenericArg as HirGenericArg, GenericArgs as HirGenericArgs, GenericArgsParentheses,
10            Path, PathSegment, PathSegments,
11        },
12    },
13    hir::generics::{
14        GenericParamDataRef, TypeOrConstParamData, TypeParamData, TypeParamProvenance,
15    },
16    resolver::{ResolveValueResult, TypeNs, ValueNs},
17    signatures::{TraitFlags, TraitSignature},
18    type_ref::{TypeRef, TypeRefId},
19};
20use rustc_type_ir::{
21    AliasTerm, AliasTy, AliasTyKind,
22    inherent::{GenericArgs as _, Region as _, Ty as _},
23};
24use smallvec::SmallVec;
25
26use crate::{
27    GenericArgsProhibitedReason, IncorrectGenericsLenKind, PathGenericsSource,
28    PathLoweringDiagnostic, Span, TyDefId, ValueTyDefId,
29    db::HirDatabase,
30    generics::{Generics, generics},
31    infer::unify::InferenceTable,
32    lower::{
33        AssocTypeShorthandResolution, ForbidParamsAfterReason, GenericPredicateSource,
34        LifetimeElisionKind, PathDiagnosticCallbackData, const_param_ty,
35    },
36    next_solver::{
37        AliasTermKind, Binder, Clause, Const, DbInterner, EarlyBinder, ErrorGuaranteed, GenericArg,
38        GenericArgs, Predicate, ProjectionPredicate, Region, TraitRef, Ty,
39    },
40};
41
42use super::{
43    ImplTraitLoweringMode, TyLoweringContext,
44    associated_type_by_name_including_super_traits_allow_ambiguity, ty_query,
45};
46
47type CallbackData<'a> =
48    Either<PathDiagnosticCallbackData, crate::infer::diagnostics::PathDiagnosticCallbackData<'a>>;
49
50// We cannot use `&mut dyn FnMut()` because of lifetime issues, and we don't want to use `Box<dyn FnMut()>`
51// because of the allocation, so we create a lifetime-less callback, tailored for our needs.
52pub(crate) struct PathDiagnosticCallback<'a, 'db> {
53    pub(crate) data: CallbackData<'a>,
54    pub(crate) callback:
55        fn(&CallbackData<'_>, &mut TyLoweringContext<'db, '_>, PathLoweringDiagnostic),
56}
57
58pub(crate) struct PathLoweringContext<'a, 'b, 'db> {
59    ctx: &'a mut TyLoweringContext<'db, 'b>,
60    on_diagnostic: PathDiagnosticCallback<'a, 'db>,
61    path: &'a Path,
62    segments: PathSegments<'a>,
63    current_segment_idx: usize,
64    /// Contains the previous segment if `current_segment_idx == segments.len()`
65    current_or_prev_segment: PathSegment<'a>,
66}
67
68impl<'a, 'b, 'db> PathLoweringContext<'a, 'b, 'db> {
69    #[inline]
70    pub(crate) fn new(
71        ctx: &'a mut TyLoweringContext<'db, 'b>,
72        on_diagnostic: PathDiagnosticCallback<'a, 'db>,
73        path: &'a Path,
74    ) -> Self {
75        let segments = path.segments();
76        let first_segment = segments.first().unwrap_or(PathSegment::MISSING);
77        Self {
78            ctx,
79            on_diagnostic,
80            path,
81            segments,
82            current_segment_idx: 0,
83            current_or_prev_segment: first_segment,
84        }
85    }
86
87    #[track_caller]
88    pub(crate) fn expect_table(&mut self) -> &mut InferenceTable<'db> {
89        self.ctx.expect_table()
90    }
91
92    #[inline]
93    #[cold]
94    fn on_diagnostic(&mut self, diag: PathLoweringDiagnostic) {
95        (self.on_diagnostic.callback)(&self.on_diagnostic.data, self.ctx, diag);
96    }
97
98    #[inline]
99    pub(crate) fn ty_ctx(&mut self) -> &mut TyLoweringContext<'db, 'b> {
100        self.ctx
101    }
102
103    #[inline]
104    fn current_segment_u32(&self) -> u32 {
105        self.current_segment_idx as u32
106    }
107
108    #[inline]
109    fn skip_resolved_segment(&mut self) {
110        if !matches!(self.path, Path::LangItem(..)) {
111            // In lang items, the resolved "segment" is not one of the segments. Perhaps we should've put it
112            // point at -1, but I don't feel this is clearer.
113            self.current_segment_idx += 1;
114        }
115        self.update_current_segment();
116    }
117
118    #[inline]
119    fn update_current_segment(&mut self) {
120        self.current_or_prev_segment =
121            self.segments.get(self.current_segment_idx).unwrap_or(self.current_or_prev_segment);
122    }
123
124    #[inline]
125    pub(crate) fn ignore_last_segment(&mut self) {
126        self.segments = self.segments.strip_last();
127    }
128
129    #[inline]
130    pub(crate) fn set_current_segment(&mut self, segment: usize) {
131        self.current_segment_idx = segment;
132        self.current_or_prev_segment = self
133            .segments
134            .get(segment)
135            .expect("invalid segment passed to PathLoweringContext::set_current_segment()");
136    }
137
138    #[inline]
139    fn with_lifetime_elision<T>(
140        &mut self,
141        lifetime_elision: LifetimeElisionKind<'db>,
142        f: impl FnOnce(&mut PathLoweringContext<'_, '_, 'db>) -> T,
143    ) -> T {
144        let old_lifetime_elision =
145            std::mem::replace(&mut self.ctx.lifetime_elision, lifetime_elision);
146        let result = f(self);
147        self.ctx.lifetime_elision = old_lifetime_elision;
148        result
149    }
150
151    pub(crate) fn lower_ty_relative_path(
152        &mut self,
153        ty: Ty<'db>,
154        // We need the original resolution to lower `Self::AssocTy` correctly
155        res: Option<TypeNs>,
156        infer_args: bool,
157        span: Span,
158    ) -> (Ty<'db>, Option<TypeNs>) {
159        let remaining_segments = self.segments.len() - self.current_segment_idx;
160        match remaining_segments {
161            0 => (ty, res),
162            1 => {
163                // resolve unselected assoc types
164                (self.select_associated_type(res, infer_args, span), None)
165            }
166            _ => {
167                // FIXME report error (ambiguous associated type)
168                (self.ctx.types.types.error, None)
169            }
170        }
171    }
172
173    // When calling this, the current segment is the resolved segment (we don't advance it yet).
174    pub(crate) fn lower_partly_resolved_path(
175        &mut self,
176        resolution: TypeNs,
177        infer_args: bool,
178        span: Span,
179    ) -> (Ty<'db>, Option<TypeNs>) {
180        let remaining_segments = self.segments.skip(self.current_segment_idx + 1);
181        tracing::debug!(?remaining_segments);
182        let rem_seg_len = remaining_segments.len();
183        tracing::debug!(?rem_seg_len);
184
185        let ty = match resolution {
186            TypeNs::TraitId(trait_) => {
187                let ty = match remaining_segments.len() {
188                    1 => {
189                        let trait_ref = self.lower_trait_ref_from_resolved_path(
190                            trait_,
191                            self.ctx.types.types.error,
192                            infer_args,
193                            span,
194                        );
195                        tracing::debug!(?trait_ref);
196                        self.skip_resolved_segment();
197                        let segment = self.current_or_prev_segment;
198                        let trait_id = trait_ref.def_id.0;
199                        let found =
200                            trait_id.trait_items(self.ctx.db).associated_type_by_name(segment.name);
201
202                        tracing::debug!(?found);
203                        match found {
204                            Some(associated_ty) => {
205                                // FIXME: `substs_from_path_segment()` pushes `TyKind::Error` for every parent
206                                // generic params. It's inefficient to splice the `Substitution`s, so we may want
207                                // that method to optionally take parent `Substitution` as we already know them at
208                                // this point (`trait_ref.substitution`).
209                                let substitution = self.substs_from_path_segment(
210                                    associated_ty.into(),
211                                    infer_args,
212                                    None,
213                                    true,
214                                    span,
215                                );
216                                let args = GenericArgs::new_from_iter(
217                                    self.ctx.interner,
218                                    trait_ref
219                                        .args
220                                        .iter()
221                                        .chain(substitution.iter().skip(trait_ref.args.len())),
222                                );
223                                Ty::new_alias(
224                                    self.ctx.interner,
225                                    AliasTy::new_from_args(
226                                        self.ctx.interner,
227                                        AliasTyKind::Projection { def_id: associated_ty.into() },
228                                        args,
229                                    ),
230                                )
231                            }
232                            None => {
233                                // FIXME: report error (associated type not found)
234                                self.ctx.types.types.error
235                            }
236                        }
237                    }
238                    0 => {
239                        // Trait object type without dyn; this should be handled in upstream. See
240                        // `lower_path()`.
241                        stdx::never!("unexpected fully resolved trait path");
242                        self.ctx.types.types.error
243                    }
244                    _ => {
245                        // FIXME report error (ambiguous associated type)
246                        self.ctx.types.types.error
247                    }
248                };
249                return (ty, None);
250            }
251            TypeNs::GenericParam(param_id) => {
252                let generics = self.ctx.generics();
253                let idx = generics.type_or_const_param_idx(param_id.into());
254                self.ctx.type_param(param_id, idx)
255            }
256            TypeNs::SelfType(impl_id) => self.ctx.db.impl_self_ty(impl_id).skip_binder(),
257            TypeNs::AdtSelfType(adt) => {
258                let args = GenericArgs::identity_for_item(self.ctx.interner, adt.into());
259                Ty::new_adt(self.ctx.interner, adt, args)
260            }
261
262            TypeNs::AdtId(it) => self.lower_path_inner(it.into(), infer_args, span),
263            TypeNs::BuiltinType(it) => self.lower_path_inner(it.into(), infer_args, span),
264            TypeNs::TypeAliasId(it) => self.lower_path_inner(it.into(), infer_args, span),
265            // FIXME: report error
266            TypeNs::EnumVariantId(_) | TypeNs::ModuleId(_) => {
267                return (self.ctx.types.types.error, None);
268            }
269        };
270
271        tracing::debug!(?ty);
272
273        self.skip_resolved_segment();
274        self.lower_ty_relative_path(ty, Some(resolution), infer_args, span)
275    }
276
277    /// This returns whether to keep the resolution (`true`) of throw it (`false`).
278    #[must_use]
279    fn handle_type_ns_resolution(&mut self, resolution: &TypeNs) -> bool {
280        let mut prohibit_generics_on_resolved = |reason| {
281            if self.current_or_prev_segment.args_and_bindings.is_some() {
282                let segment = self.current_segment_u32();
283                self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited {
284                    segment,
285                    reason,
286                });
287            }
288        };
289
290        match resolution {
291            TypeNs::SelfType(_) => {
292                prohibit_generics_on_resolved(GenericArgsProhibitedReason::SelfTy)
293            }
294            TypeNs::GenericParam(_) => {
295                prohibit_generics_on_resolved(GenericArgsProhibitedReason::TyParam)
296            }
297            TypeNs::AdtSelfType(_) => {
298                prohibit_generics_on_resolved(GenericArgsProhibitedReason::SelfTy);
299
300                if self.ctx.forbid_params_after.is_some()
301                    && self.ctx.forbid_params_after_reason
302                        == ForbidParamsAfterReason::LoweringParamDefault
303                {
304                    // FIXME: Handle other reasons.
305                    let segment = self.current_segment_u32();
306                    self.on_diagnostic(PathLoweringDiagnostic::GenericDefaultRefersToSelf {
307                        segment,
308                    });
309                    return false;
310                }
311            }
312            TypeNs::BuiltinType(_) => {
313                prohibit_generics_on_resolved(GenericArgsProhibitedReason::PrimitiveTy)
314            }
315            TypeNs::ModuleId(_) => {
316                prohibit_generics_on_resolved(GenericArgsProhibitedReason::Module)
317            }
318            TypeNs::AdtId(_)
319            | TypeNs::EnumVariantId(_)
320            | TypeNs::TypeAliasId(_)
321            | TypeNs::TraitId(_) => {}
322        }
323
324        true
325    }
326
327    pub(crate) fn resolve_path_in_type_ns_fully(&mut self) -> Option<TypeNs> {
328        let (res, unresolved) = self.resolve_path_in_type_ns()?;
329        if unresolved.is_some() {
330            return None;
331        }
332        Some(res)
333    }
334
335    #[tracing::instrument(skip(self), ret)]
336    pub(crate) fn resolve_path_in_type_ns(&mut self) -> Option<(TypeNs, Option<usize>)> {
337        let (resolution, remaining_index, _, prefix_info) =
338            self.ctx.resolver.resolve_path_in_type_ns_with_prefix_info(self.ctx.db, self.path)?;
339
340        let segments = self.segments;
341        if segments.is_empty() || matches!(self.path, Path::LangItem(..)) {
342            // `segments.is_empty()` can occur with `self`.
343            return Some((resolution, remaining_index));
344        }
345
346        let (module_segments, resolved_segment_idx, enum_segment) = match remaining_index {
347            None if prefix_info.enum_variant => {
348                (segments.strip_last_two(), segments.len() - 1, Some(segments.len() - 2))
349            }
350            None => (segments.strip_last(), segments.len() - 1, None),
351            Some(i) => (segments.take(i - 1), i - 1, None),
352        };
353
354        self.current_segment_idx = resolved_segment_idx;
355        self.current_or_prev_segment =
356            segments.get(resolved_segment_idx).expect("should have resolved segment");
357
358        for (i, mod_segment) in module_segments.iter().enumerate() {
359            if mod_segment.args_and_bindings.is_some() {
360                self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited {
361                    segment: i as u32,
362                    reason: GenericArgsProhibitedReason::Module,
363                });
364            }
365        }
366
367        if let Some(enum_segment) = enum_segment
368            && segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some())
369            && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some())
370        {
371            self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited {
372                segment: (enum_segment + 1) as u32,
373                reason: GenericArgsProhibitedReason::EnumVariant,
374            });
375        }
376
377        if !self.handle_type_ns_resolution(&resolution) {
378            return None;
379        }
380
381        Some((resolution, remaining_index))
382    }
383
384    pub(crate) fn resolve_path_in_value_ns(
385        &mut self,
386        hygiene_id: HygieneId,
387    ) -> Option<ResolveValueResult> {
388        let (res, prefix_info) = self.ctx.resolver.resolve_path_in_value_ns_with_prefix_info(
389            self.ctx.db,
390            self.path,
391            hygiene_id,
392        )?;
393
394        let segments = self.segments;
395        if segments.is_empty() || matches!(self.path, Path::LangItem(..)) {
396            // `segments.is_empty()` can occur with `self`.
397            return Some(res);
398        }
399
400        let (mod_segments, enum_segment, resolved_segment_idx) = match res {
401            ResolveValueResult::Partial(_, unresolved_segment) => {
402                (segments.take(unresolved_segment - 1), None, unresolved_segment - 1)
403            }
404            ResolveValueResult::ValueNs(ValueNs::EnumVariantId(_)) if prefix_info.enum_variant => {
405                (segments.strip_last_two(), segments.len().checked_sub(2), segments.len() - 1)
406            }
407            ResolveValueResult::ValueNs(..) => (segments.strip_last(), None, segments.len() - 1),
408        };
409
410        self.current_segment_idx = resolved_segment_idx;
411        self.current_or_prev_segment =
412            segments.get(resolved_segment_idx).expect("should have resolved segment");
413
414        for (i, mod_segment) in mod_segments.iter().enumerate() {
415            if mod_segment.args_and_bindings.is_some() {
416                self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited {
417                    segment: i as u32,
418                    reason: GenericArgsProhibitedReason::Module,
419                });
420            }
421        }
422
423        if let Some(enum_segment) = enum_segment
424            && segments.get(enum_segment).is_some_and(|it| it.args_and_bindings.is_some())
425            && segments.get(enum_segment + 1).is_some_and(|it| it.args_and_bindings.is_some())
426        {
427            self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited {
428                segment: (enum_segment + 1) as u32,
429                reason: GenericArgsProhibitedReason::EnumVariant,
430            });
431        }
432
433        match &res {
434            ResolveValueResult::ValueNs(resolution) => {
435                let resolved_segment_idx = self.current_segment_u32();
436                let resolved_segment = self.current_or_prev_segment;
437
438                let mut prohibit_generics_on_resolved = |reason| {
439                    if resolved_segment.args_and_bindings.is_some() {
440                        self.on_diagnostic(PathLoweringDiagnostic::GenericArgsProhibited {
441                            segment: resolved_segment_idx,
442                            reason,
443                        });
444                    }
445                };
446
447                match resolution {
448                    ValueNs::ImplSelf(_) => {
449                        prohibit_generics_on_resolved(GenericArgsProhibitedReason::SelfTy);
450                    }
451                    // FIXME: rustc generates E0107 (incorrect number of generic arguments) and not
452                    // E0109 (generic arguments provided for a type that doesn't accept them) for
453                    // consts and statics, presumably as a defense against future in which consts
454                    // and statics can be generic, or just because it was easier for rustc implementors.
455                    // That means we'll show the wrong error code. Because of us it's easier to do it
456                    // this way :)
457                    ValueNs::GenericParam(_) => {
458                        prohibit_generics_on_resolved(GenericArgsProhibitedReason::Const)
459                    }
460                    ValueNs::StaticId(_) => {
461                        prohibit_generics_on_resolved(GenericArgsProhibitedReason::Static)
462                    }
463                    ValueNs::LocalBinding(_) => {
464                        prohibit_generics_on_resolved(GenericArgsProhibitedReason::LocalVariable)
465                    }
466                    ValueNs::FunctionId(_)
467                    | ValueNs::StructId(_)
468                    | ValueNs::EnumVariantId(_)
469                    | ValueNs::ConstId(_) => {}
470                }
471            }
472            ResolveValueResult::Partial(resolution, _) => {
473                if !self.handle_type_ns_resolution(resolution) {
474                    return None;
475                }
476            }
477        };
478        Some(res)
479    }
480
481    #[tracing::instrument(skip(self), ret)]
482    fn select_associated_type(
483        &mut self,
484        res: Option<TypeNs>,
485        infer_args: bool,
486        span: Span,
487    ) -> Ty<'db> {
488        let interner = self.ctx.interner;
489        let db = self.ctx.db;
490        let def = self.ctx.generic_def;
491        let segment = self.current_or_prev_segment;
492        let assoc_name = segment.name;
493        let (assoc_type, trait_args) = match res {
494            Some(TypeNs::GenericParam(param)) => {
495                let AssocTypeShorthandResolution::Resolved(assoc_type) =
496                    super::resolve_type_param_assoc_type_shorthand(
497                        db,
498                        def,
499                        param,
500                        assoc_name.clone(),
501                    )
502                else {
503                    // FIXME: Emit an error.
504                    return self.ctx.types.types.error;
505                };
506                assoc_type
507                    .get_with(|(assoc_type, trait_args)| (*assoc_type, trait_args.as_ref()))
508                    .skip_binder()
509            }
510            Some(TypeNs::SelfType(impl_)) => {
511                let Some(impl_trait) = db.impl_trait(impl_) else {
512                    return self.ctx.types.types.error;
513                };
514                let impl_trait = impl_trait.instantiate_identity().skip_norm_wip();
515                // Searching for `Self::Assoc` in `impl Trait for Type` is like searching for `Self::Assoc` in `Trait`.
516                let AssocTypeShorthandResolution::Resolved(assoc_type) =
517                    super::resolve_type_param_assoc_type_shorthand(
518                        db,
519                        impl_trait.def_id.0.into(),
520                        TypeParamId::trait_self(impl_trait.def_id.0),
521                        assoc_name.clone(),
522                    )
523                else {
524                    // FIXME: Emit an error.
525                    return self.ctx.types.types.error;
526                };
527                let (assoc_type, trait_args) = assoc_type
528                    .get_with(|(assoc_type, trait_args)| (*assoc_type, trait_args.as_ref()))
529                    .skip_binder();
530                (
531                    assoc_type,
532                    EarlyBinder::bind(trait_args)
533                        .instantiate(interner, impl_trait.args)
534                        .skip_norm_wip(),
535                )
536            }
537            _ => return self.ctx.types.types.error,
538        };
539
540        // FIXME: `substs_from_path_segment()` pushes `TyKind::Error` for every parent
541        // generic params. It's inefficient to splice the `Substitution`s, so we may want
542        // that method to optionally take parent `Substitution` as we already know them at
543        // this point (`t.substitution`).
544        let substs = self.substs_from_path_segment(assoc_type.into(), infer_args, None, true, span);
545
546        let substs = GenericArgs::new_from_iter(
547            interner,
548            trait_args.iter().chain(substs.iter().skip(trait_args.len())),
549        );
550
551        Ty::new_projection_from_args(interner, assoc_type.into(), substs)
552    }
553
554    fn lower_path_inner(&mut self, typeable: TyDefId, infer_args: bool, span: Span) -> Ty<'db> {
555        let generic_def = match typeable {
556            TyDefId::BuiltinType(builtinty) => {
557                return Ty::from_builtin_type(self.ctx.interner, builtinty);
558            }
559            TyDefId::AdtId(it) => it.into(),
560            TyDefId::TypeAliasId(it) => it.into(),
561        };
562        let args = self.substs_from_path_segment(generic_def, infer_args, None, false, span);
563        let ty = ty_query(self.ctx.db, typeable);
564        ty.instantiate(self.ctx.interner, args).skip_norm_wip()
565    }
566
567    /// Collect generic arguments from a path into a `Substs`. See also
568    /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
569    pub(crate) fn substs_from_path(
570        &mut self,
571        // Note that we don't call `db.value_type(resolved)` here,
572        // `ValueTyDefId` is just a convenient way to pass generics and
573        // special-case enum variants
574        resolved: ValueTyDefId,
575        infer_args: bool,
576        lowering_assoc_type_generics: bool,
577        span: Span,
578    ) -> GenericArgs<'db> {
579        let interner = self.ctx.interner;
580        let prev_current_segment_idx = self.current_segment_idx;
581        let prev_current_segment = self.current_or_prev_segment;
582
583        let generic_def = match resolved {
584            ValueTyDefId::FunctionId(it) => it.into(),
585            ValueTyDefId::StructId(it) => it.into(),
586            ValueTyDefId::UnionId(it) => it.into(),
587            ValueTyDefId::ConstId(it) => it.into(),
588            ValueTyDefId::StaticId(_) => {
589                return GenericArgs::empty(interner);
590            }
591            ValueTyDefId::EnumVariantId(var) => {
592                // the generic args for an enum variant may be either specified
593                // on the segment referring to the enum, or on the segment
594                // referring to the variant. So `Option::<T>::None` and
595                // `Option::None::<T>` are both allowed (though the former is
596                // FIXME: This isn't strictly correct, enum variants may be used not through the enum
597                // (via `use Enum::Variant`). The resolver returns whether they were, but we don't have its result
598                // available here. The worst that can happen is that we will show some confusing diagnostics to the user,
599                // if generics exist on the module and they don't match with the variant.
600                // preferred). See also `def_ids_for_path_segments` in rustc.
601                //
602                // `wrapping_sub(1)` will return a number which `get` will return None for if current_segment_idx<2.
603                // This simplifies the code a bit.
604                let penultimate_idx = self.current_segment_idx.wrapping_sub(1);
605                let penultimate = self.segments.get(penultimate_idx);
606                if let Some(penultimate) = penultimate
607                    && self.current_or_prev_segment.args_and_bindings.is_none()
608                    && penultimate.args_and_bindings.is_some()
609                {
610                    self.current_segment_idx = penultimate_idx;
611                    self.current_or_prev_segment = penultimate;
612                }
613                var.lookup(self.ctx.db).parent.into()
614            }
615        };
616        let result = self.substs_from_path_segment(
617            generic_def,
618            infer_args,
619            None,
620            lowering_assoc_type_generics,
621            span,
622        );
623        self.current_segment_idx = prev_current_segment_idx;
624        self.current_or_prev_segment = prev_current_segment;
625        result
626    }
627
628    pub(crate) fn substs_from_path_segment(
629        &mut self,
630        def: GenericDefId,
631        infer_args: bool,
632        explicit_self_ty: Option<Ty<'db>>,
633        lowering_assoc_type_generics: bool,
634        span: Span,
635    ) -> GenericArgs<'db> {
636        let old_lifetime_elision = self.ctx.lifetime_elision;
637
638        if let Some(args) = self.current_or_prev_segment.args_and_bindings
639            && args.parenthesized != GenericArgsParentheses::No
640        {
641            let prohibit_parens = match def {
642                GenericDefId::TraitId(trait_) => {
643                    // RTN is prohibited anyways if we got here.
644                    let is_rtn = args.parenthesized == GenericArgsParentheses::ReturnTypeNotation;
645                    let is_fn_trait = TraitSignature::of(self.ctx.db, trait_)
646                        .flags
647                        .contains(TraitFlags::RUSTC_PAREN_SUGAR);
648                    is_rtn || !is_fn_trait
649                }
650                _ => true,
651            };
652
653            if prohibit_parens {
654                let segment = self.current_segment_u32();
655                self.on_diagnostic(
656                    PathLoweringDiagnostic::ParenthesizedGenericArgsWithoutFnTrait { segment },
657                );
658
659                return GenericArgs::error_for_item(self.ctx.interner, def.into());
660            }
661
662            // `Fn()`-style generics are treated like functions for the purpose of lifetime elision.
663            self.ctx.lifetime_elision =
664                LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false };
665        }
666
667        let result = self.substs_from_args_and_bindings(
668            self.current_or_prev_segment.args_and_bindings,
669            def,
670            infer_args,
671            explicit_self_ty,
672            PathGenericsSource::Segment(self.current_segment_u32()),
673            lowering_assoc_type_generics,
674            self.ctx.lifetime_elision,
675            span,
676        );
677        self.ctx.lifetime_elision = old_lifetime_elision;
678        result
679    }
680
681    pub(super) fn substs_from_args_and_bindings(
682        &mut self,
683        args_and_bindings: Option<&HirGenericArgs>,
684        def: GenericDefId,
685        infer_args: bool,
686        explicit_self_ty: Option<Ty<'db>>,
687        generics_source: PathGenericsSource,
688        lowering_assoc_type_generics: bool,
689        lifetime_elision: LifetimeElisionKind<'db>,
690        span: Span,
691    ) -> GenericArgs<'db> {
692        struct LowererCtx<'a, 'b, 'c, 'db> {
693            ctx: &'a mut PathLoweringContext<'b, 'c, 'db>,
694            generics_source: PathGenericsSource,
695            span: Span,
696        }
697
698        impl<'db> GenericArgsLowerer<'db> for LowererCtx<'_, '_, '_, 'db> {
699            fn report_len_mismatch(
700                &mut self,
701                def: GenericDefId,
702                provided_count: u32,
703                expected_count: u32,
704                kind: IncorrectGenericsLenKind,
705            ) {
706                self.ctx.on_diagnostic(PathLoweringDiagnostic::IncorrectGenericsLen {
707                    generics_source: self.generics_source,
708                    provided_count,
709                    expected_count,
710                    kind,
711                    def,
712                });
713            }
714
715            fn report_arg_mismatch(
716                &mut self,
717                param_id: GenericParamId,
718                arg_idx: u32,
719                has_self_arg: bool,
720            ) {
721                self.ctx.on_diagnostic(PathLoweringDiagnostic::IncorrectGenericsOrder {
722                    generics_source: self.generics_source,
723                    param_id,
724                    arg_idx,
725                    has_self_arg,
726                });
727            }
728
729            fn provided_kind(
730                &mut self,
731                param_id: GenericParamId,
732                param: GenericParamDataRef<'_>,
733                arg: &HirGenericArg,
734            ) -> GenericArg<'db> {
735                match (param, *arg) {
736                    (
737                        GenericParamDataRef::LifetimeParamData(_),
738                        HirGenericArg::Lifetime(lifetime),
739                    ) => self.ctx.ctx.lower_lifetime(lifetime).into(),
740                    (GenericParamDataRef::TypeParamData(_), HirGenericArg::Type(type_ref)) => {
741                        self.ctx.ctx.lower_ty(type_ref).into()
742                    }
743                    (GenericParamDataRef::ConstParamData(_), HirGenericArg::Const(konst)) => {
744                        let GenericParamId::ConstParamId(const_id) = param_id else {
745                            unreachable!("non-const param ID for const param");
746                        };
747                        self.ctx
748                            .ctx
749                            .lower_const(konst, const_param_ty(self.ctx.ctx.db, const_id))
750                            .into()
751                    }
752                    _ => unreachable!("unmatching param kinds were passed to `provided_kind()`"),
753                }
754            }
755
756            fn provided_type_like_const(
757                &mut self,
758                type_ref: TypeRefId,
759                const_ty: Ty<'db>,
760                arg: TypeLikeConst<'_>,
761            ) -> Const<'db> {
762                match arg {
763                    TypeLikeConst::Path(path) => self.ctx.ctx.lower_path_as_const(path, const_ty),
764                    TypeLikeConst::Infer => self.ctx.ctx.next_const_var(type_ref.into()),
765                }
766            }
767
768            fn inferred_kind(
769                &mut self,
770                def: GenericDefId,
771                param_id: GenericParamId,
772                param: GenericParamDataRef<'_>,
773                infer_args: bool,
774                preceding_args: &[GenericArg<'db>],
775                had_count_error: bool,
776            ) -> GenericArg<'db> {
777                let default = || {
778                    self.ctx.ctx.db.generic_defaults(def).get(preceding_args.len()).map(|default| {
779                        default.instantiate(self.ctx.ctx.interner, preceding_args).skip_norm_wip()
780                    })
781                };
782                // If `!infer_args`, we've already emitted an error, so put a dummy span.
783                let span = if !infer_args || had_count_error { Span::Dummy } else { self.span };
784                match param {
785                    GenericParamDataRef::LifetimeParamData(_) => {
786                        self.ctx.ctx.next_region_var(span).into()
787                    }
788                    GenericParamDataRef::TypeParamData(param) => {
789                        if !infer_args
790                            && param.default.is_some()
791                            && let Some(default) = default()
792                        {
793                            return default;
794                        }
795                        self.ctx.ctx.next_ty_var(span).into()
796                    }
797                    GenericParamDataRef::ConstParamData(param) => {
798                        if !infer_args
799                            && param.default.is_some()
800                            && let Some(default) = default()
801                        {
802                            return default;
803                        }
804                        let GenericParamId::ConstParamId(_) = param_id else {
805                            unreachable!("non-const param ID for const param");
806                        };
807                        self.ctx.ctx.next_const_var(span).into()
808                    }
809                }
810            }
811
812            fn parent_arg(&mut self, _param_idx: u32, param_id: GenericParamId) -> GenericArg<'db> {
813                match param_id {
814                    GenericParamId::TypeParamId(_) => {
815                        Ty::new_error(self.ctx.ctx.interner, ErrorGuaranteed).into()
816                    }
817                    GenericParamId::ConstParamId(_) => self.ctx.ctx.types.consts.error.into(),
818                    GenericParamId::LifetimeParamId(_) => self.ctx.ctx.types.regions.error.into(),
819                }
820            }
821
822            fn report_elided_lifetimes_in_path(
823                &mut self,
824                def: GenericDefId,
825                expected_count: u32,
826                hard_error: bool,
827            ) {
828                self.ctx.on_diagnostic(PathLoweringDiagnostic::ElidedLifetimesInPath {
829                    generics_source: self.generics_source,
830                    def,
831                    expected_count,
832                    hard_error,
833                });
834            }
835
836            fn report_elision_failure(&mut self, def: GenericDefId, expected_count: u32) {
837                self.ctx.on_diagnostic(PathLoweringDiagnostic::ElisionFailure {
838                    generics_source: self.generics_source,
839                    def,
840                    expected_count,
841                });
842            }
843
844            fn report_missing_lifetime(&mut self, def: GenericDefId, expected_count: u32) {
845                self.ctx.on_diagnostic(PathLoweringDiagnostic::MissingLifetime {
846                    generics_source: self.generics_source,
847                    def,
848                    expected_count,
849                });
850            }
851        }
852
853        substs_from_args_and_bindings(
854            self.ctx.db,
855            self.ctx.store,
856            args_and_bindings,
857            def,
858            infer_args,
859            lifetime_elision,
860            lowering_assoc_type_generics,
861            explicit_self_ty,
862            &mut LowererCtx { ctx: self, generics_source, span },
863        )
864    }
865
866    pub(crate) fn lower_trait_ref_from_resolved_path(
867        &mut self,
868        resolved: TraitId,
869        explicit_self_ty: Ty<'db>,
870        infer_args: bool,
871        span: Span,
872    ) -> TraitRef<'db> {
873        let args = self.trait_ref_substs_from_path(resolved, explicit_self_ty, infer_args, span);
874        TraitRef::new_from_args(self.ctx.interner, resolved.into(), args)
875    }
876
877    fn trait_ref_substs_from_path(
878        &mut self,
879        resolved: TraitId,
880        explicit_self_ty: Ty<'db>,
881        infer_args: bool,
882        span: Span,
883    ) -> GenericArgs<'db> {
884        self.substs_from_path_segment(
885            resolved.into(),
886            infer_args,
887            Some(explicit_self_ty),
888            false,
889            span,
890        )
891    }
892
893    pub(super) fn assoc_type_bindings_from_type_bound(
894        mut self,
895        trait_ref: TraitRef<'db>,
896        span: Span,
897    ) -> Option<impl Iterator<Item = (Clause<'db>, GenericPredicateSource)> + use<'a, 'b, 'db>>
898    {
899        let interner = self.ctx.interner;
900        self.current_or_prev_segment.args_and_bindings.map(|args_and_bindings| {
901            args_and_bindings.bindings.iter().enumerate().flat_map(move |(binding_idx, binding)| {
902                let found = associated_type_by_name_including_super_traits_allow_ambiguity(
903                    self.ctx.db,
904                    trait_ref,
905                    binding.name.clone(),
906                );
907                let (associated_ty, super_trait_args) = match found {
908                    None => return SmallVec::new(),
909                    Some(t) => t,
910                };
911                let args =
912                    self.with_lifetime_elision(LifetimeElisionKind::AnonymousReportError, |this| {
913                        // FIXME: `substs_from_path_segment()` pushes `TyKind::Error` for every parent
914                        // generic params. It's inefficient to splice the `Substitution`s, so we may want
915                        // that method to optionally take parent `Substitution` as we already know them at
916                        // this point (`super_trait_ref.substitution`).
917                        this.substs_from_args_and_bindings(
918                            binding.args.as_ref(),
919                            associated_ty.into(),
920                            false, // this is not relevant
921                            Some(super_trait_args.type_at(0)),
922                            PathGenericsSource::AssocType {
923                                segment: this.current_segment_u32(),
924                                assoc_type: binding_idx as u32,
925                            },
926                            false,
927                            this.ctx.lifetime_elision,
928                            span,
929                        )
930                    });
931                let args = GenericArgs::new_from_iter(
932                    interner,
933                    super_trait_args.iter().chain(args.iter().skip(super_trait_args.len())),
934                );
935                let projection_term = AliasTerm::new_from_args(
936                    interner,
937                    AliasTermKind::ProjectionTy { def_id: associated_ty.into() },
938                    args,
939                );
940                let mut predicates: SmallVec<[_; 1]> = SmallVec::with_capacity(
941                    binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
942                );
943                if let Some(type_ref) = binding.type_ref {
944                    let lifetime_elision =
945                        if args_and_bindings.parenthesized == GenericArgsParentheses::ParenSugar {
946                            // `Fn()`-style generics are elided like functions. This is `Output` (we lower to it in hir-def).
947                            LifetimeElisionKind::for_fn_ret(self.ctx.interner)
948                        } else {
949                            self.ctx.lifetime_elision
950                        };
951                    self.with_lifetime_elision(lifetime_elision, |this| {
952                        match (&this.ctx.store[type_ref], this.ctx.impl_trait_mode.mode) {
953                            (TypeRef::ImplTrait(_), ImplTraitLoweringMode::Disallowed) => (),
954                            (
955                                _,
956                                ImplTraitLoweringMode::Disallowed | ImplTraitLoweringMode::Opaque,
957                            ) => {
958                                let ty = this.ctx.lower_ty(type_ref);
959                                let bound_vars = this.ctx.peek_bound_vars();
960                                let pred = Clause(Predicate::new(
961                                    interner,
962                                    Binder::bind_with_vars(
963                                        rustc_type_ir::PredicateKind::Clause(
964                                            rustc_type_ir::ClauseKind::Projection(
965                                                ProjectionPredicate {
966                                                    projection_term,
967                                                    term: ty.into(),
968                                                },
969                                            ),
970                                        ),
971                                        bound_vars,
972                                    ),
973                                ));
974                                predicates.push((pred, GenericPredicateSource::SelfOnly));
975                            }
976                        }
977                    })
978                }
979                for bound in binding.bounds.iter() {
980                    predicates.extend(
981                        self.ctx
982                            .lower_type_bound(
983                                bound,
984                                Ty::new_alias(
985                                    self.ctx.interner,
986                                    AliasTy::new_from_args(
987                                        self.ctx.interner,
988                                        AliasTyKind::Projection { def_id: associated_ty.into() },
989                                        args,
990                                    ),
991                                ),
992                                false,
993                            )
994                            .map(|(pred, _)| (pred, GenericPredicateSource::AssocTyBound)),
995                    );
996                }
997                predicates
998            })
999        })
1000    }
1001
1002    pub(crate) fn interner(&self) -> DbInterner<'db> {
1003        self.ctx.interner
1004    }
1005}
1006
1007/// A const that were parsed like a type.
1008pub(crate) enum TypeLikeConst<'a> {
1009    Infer,
1010    Path(&'a Path),
1011}
1012
1013pub(crate) trait GenericArgsLowerer<'db> {
1014    fn report_elided_lifetimes_in_path(
1015        &mut self,
1016        def: GenericDefId,
1017        expected_count: u32,
1018        hard_error: bool,
1019    );
1020
1021    fn report_elision_failure(&mut self, def: GenericDefId, expected_count: u32);
1022
1023    fn report_missing_lifetime(&mut self, def: GenericDefId, expected_count: u32);
1024
1025    fn report_len_mismatch(
1026        &mut self,
1027        def: GenericDefId,
1028        provided_count: u32,
1029        expected_count: u32,
1030        kind: IncorrectGenericsLenKind,
1031    );
1032
1033    fn report_arg_mismatch(&mut self, param_id: GenericParamId, arg_idx: u32, has_self_arg: bool);
1034
1035    fn provided_kind(
1036        &mut self,
1037        param_id: GenericParamId,
1038        param: GenericParamDataRef<'_>,
1039        arg: &HirGenericArg,
1040    ) -> GenericArg<'db>;
1041
1042    fn provided_type_like_const(
1043        &mut self,
1044        type_ref: TypeRefId,
1045        const_ty: Ty<'db>,
1046        arg: TypeLikeConst<'_>,
1047    ) -> Const<'db>;
1048
1049    fn inferred_kind(
1050        &mut self,
1051        def: GenericDefId,
1052        param_id: GenericParamId,
1053        param: GenericParamDataRef<'_>,
1054        infer_args: bool,
1055        preceding_args: &[GenericArg<'db>],
1056        had_count_error: bool,
1057    ) -> GenericArg<'db>;
1058
1059    fn parent_arg(&mut self, param_idx: u32, param_id: GenericParamId) -> GenericArg<'db>;
1060}
1061
1062/// Returns true if there was an error.
1063fn check_generic_args_len<'db>(
1064    args_and_bindings: Option<&HirGenericArgs>,
1065    def: GenericDefId,
1066    def_generics: &Generics<'db>,
1067    infer_args: bool,
1068    lifetime_elision: &LifetimeElisionKind<'db>,
1069    lowering_assoc_type_generics: bool,
1070    ctx: &mut impl GenericArgsLowerer<'db>,
1071) -> bool {
1072    let mut had_error = false;
1073
1074    let (mut provided_lifetimes_count, mut provided_types_and_consts_count) = (0usize, 0usize);
1075    if let Some(args_and_bindings) = args_and_bindings {
1076        let args_no_self = &args_and_bindings.args[usize::from(args_and_bindings.has_self_type)..];
1077        for arg in args_no_self {
1078            match arg {
1079                HirGenericArg::Lifetime(_) => provided_lifetimes_count += 1,
1080                HirGenericArg::Type(_) | HirGenericArg::Const(_) => {
1081                    provided_types_and_consts_count += 1
1082                }
1083            }
1084        }
1085    }
1086
1087    let lifetime_args_len = def_generics.len_lifetimes_self();
1088    if provided_lifetimes_count == 0
1089        && lifetime_args_len > 0
1090        && (!lowering_assoc_type_generics || infer_args)
1091    {
1092        // In generic associated types, we never allow inferring the lifetimes, but only in type context, that is
1093        // when `infer_args == false`. In expression/pattern context we always allow inferring them, even for GATs.
1094        match lifetime_elision {
1095            &LifetimeElisionKind::AnonymousCreateParameter { report_in_path } => {
1096                ctx.report_elided_lifetimes_in_path(def, lifetime_args_len as u32, report_in_path);
1097                had_error |= report_in_path;
1098            }
1099            LifetimeElisionKind::AnonymousReportError => {
1100                ctx.report_missing_lifetime(def, lifetime_args_len as u32);
1101                had_error = true
1102            }
1103            LifetimeElisionKind::ElisionFailure => {
1104                ctx.report_elision_failure(def, lifetime_args_len as u32);
1105                had_error = true;
1106            }
1107            LifetimeElisionKind::StaticIfNoLifetimeInScope { only_lint: _ } => {
1108                // FIXME: Check there are other lifetimes in scope, and error/lint.
1109            }
1110            LifetimeElisionKind::Elided(_) => {
1111                ctx.report_elided_lifetimes_in_path(def, lifetime_args_len as u32, false);
1112            }
1113            LifetimeElisionKind::Infer => {
1114                // Allow eliding lifetimes.
1115            }
1116        }
1117    } else if lifetime_args_len != provided_lifetimes_count {
1118        ctx.report_len_mismatch(
1119            def,
1120            provided_lifetimes_count as u32,
1121            lifetime_args_len as u32,
1122            IncorrectGenericsLenKind::Lifetimes,
1123        );
1124        had_error = true;
1125    }
1126
1127    let defaults_count =
1128        def_generics.iter_self_type_or_consts().filter(|(_, param)| param.has_default()).count();
1129    let named_type_and_const_params_count = def_generics
1130        .iter_self_type_or_consts()
1131        .filter(|(_, param)| match param {
1132            TypeOrConstParamData::TypeParamData(param) => {
1133                param.provenance == TypeParamProvenance::TypeParamList
1134            }
1135            TypeOrConstParamData::ConstParamData(_) => true,
1136        })
1137        .count();
1138    let expected_max = named_type_and_const_params_count;
1139    let expected_min =
1140        if infer_args { 0 } else { named_type_and_const_params_count - defaults_count };
1141    if provided_types_and_consts_count < expected_min
1142        || expected_max < provided_types_and_consts_count
1143    {
1144        ctx.report_len_mismatch(
1145            def,
1146            provided_types_and_consts_count as u32,
1147            named_type_and_const_params_count as u32,
1148            IncorrectGenericsLenKind::TypesAndConsts,
1149        );
1150        had_error = true;
1151    }
1152
1153    had_error
1154}
1155
1156pub(crate) fn substs_from_args_and_bindings<'db>(
1157    db: &'db dyn HirDatabase,
1158    store: &ExpressionStore,
1159    args_and_bindings: Option<&HirGenericArgs>,
1160    def: GenericDefId,
1161    mut infer_args: bool,
1162    lifetime_elision: LifetimeElisionKind<'db>,
1163    lowering_assoc_type_generics: bool,
1164    explicit_self_ty: Option<Ty<'db>>,
1165    ctx: &mut impl GenericArgsLowerer<'db>,
1166) -> GenericArgs<'db> {
1167    let interner = DbInterner::new_no_crate(db);
1168
1169    tracing::debug!(?args_and_bindings);
1170
1171    // Order is
1172    // - Parent parameters
1173    // - Optional Self parameter
1174    // - Lifetime parameters
1175    // - Type or Const parameters
1176    let def_generics = generics(db, def);
1177    let args_slice = args_and_bindings.map(|it| &*it.args).unwrap_or_default();
1178
1179    // We do not allow inference if there are specified args, i.e. we do not allow partial inference.
1180    let has_non_lifetime_args =
1181        args_slice.iter().any(|arg| !matches!(arg, HirGenericArg::Lifetime(_)));
1182    infer_args &= !has_non_lifetime_args;
1183
1184    let had_count_error = check_generic_args_len(
1185        args_and_bindings,
1186        def,
1187        &def_generics,
1188        infer_args,
1189        &lifetime_elision,
1190        lowering_assoc_type_generics,
1191        ctx,
1192    );
1193
1194    let mut substs = Vec::with_capacity(def_generics.len(true));
1195
1196    substs.extend(
1197        def_generics.iter_parent_id().enumerate().map(|(idx, id)| ctx.parent_arg(idx as u32, id)),
1198    );
1199
1200    let mut args = args_slice.iter().enumerate().peekable();
1201    let mut params = def_generics.iter_self().peekable();
1202
1203    // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
1204    // If we later encounter a lifetime, we know that the arguments were provided in the
1205    // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
1206    // inferred, so we can use it for diagnostics later.
1207    let mut force_infer_lt = None;
1208
1209    let has_self_arg = args_and_bindings.is_some_and(|it| it.has_self_type);
1210    // First, handle `Self` parameter. Consume it from the args if provided, otherwise from `explicit_self_ty`,
1211    // and lastly infer it.
1212    if let Some(&(
1213        self_param_id,
1214        self_param @ GenericParamDataRef::TypeParamData(TypeParamData {
1215            provenance: TypeParamProvenance::TraitSelf,
1216            ..
1217        }),
1218    )) = params.peek()
1219    {
1220        let self_ty = if has_self_arg {
1221            let (_, self_ty) = args.next().expect("has_self_type=true, should have Self type");
1222            ctx.provided_kind(self_param_id, self_param, self_ty)
1223        } else {
1224            explicit_self_ty.map(|it| it.into()).unwrap_or_else(|| {
1225                ctx.inferred_kind(
1226                    def,
1227                    self_param_id,
1228                    self_param,
1229                    infer_args,
1230                    &substs,
1231                    had_count_error,
1232                )
1233            })
1234        };
1235        params.next();
1236        substs.push(self_ty);
1237    }
1238
1239    loop {
1240        // We're going to iterate through the generic arguments that the user
1241        // provided, matching them with the generic parameters we expect.
1242        // Mismatches can occur as a result of elided lifetimes, or for malformed
1243        // input. We try to handle both sensibly.
1244        match (args.peek(), params.peek()) {
1245            (Some(&(arg_idx, arg)), Some(&(param_id, param))) => match (arg, param) {
1246                (HirGenericArg::Type(_), GenericParamDataRef::TypeParamData(type_param))
1247                    if type_param.provenance == TypeParamProvenance::ArgumentImplTrait =>
1248                {
1249                    // Do not allow specifying `impl Trait` explicitly. We already err at that, but if we won't handle it here
1250                    // we will handle it as if it was specified, instead of inferring it.
1251                    substs.push(ctx.inferred_kind(
1252                        def,
1253                        param_id,
1254                        param,
1255                        infer_args,
1256                        &substs,
1257                        had_count_error,
1258                    ));
1259                    params.next();
1260                }
1261                (HirGenericArg::Lifetime(_), GenericParamDataRef::LifetimeParamData(_))
1262                | (HirGenericArg::Type(_), GenericParamDataRef::TypeParamData(_))
1263                | (HirGenericArg::Const(_), GenericParamDataRef::ConstParamData(_)) => {
1264                    substs.push(ctx.provided_kind(param_id, param, arg));
1265                    args.next();
1266                    params.next();
1267                }
1268                (
1269                    HirGenericArg::Type(_) | HirGenericArg::Const(_),
1270                    GenericParamDataRef::LifetimeParamData(_),
1271                ) => {
1272                    // We expected a lifetime argument, but got a type or const
1273                    // argument. That means we're inferring the lifetime.
1274                    substs.push(ctx.inferred_kind(
1275                        def,
1276                        param_id,
1277                        param,
1278                        infer_args,
1279                        &substs,
1280                        had_count_error,
1281                    ));
1282                    params.next();
1283                    force_infer_lt = Some((arg_idx as u32, param_id));
1284                }
1285                (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) => {
1286                    if let Some(konst) = type_looks_like_const(store, *type_ref) {
1287                        let GenericParamId::ConstParamId(param_id) = param_id else {
1288                            panic!("unmatching param kinds");
1289                        };
1290                        let const_ty = const_param_ty(db, param_id);
1291                        substs
1292                            .push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into());
1293                        args.next();
1294                        params.next();
1295                    } else {
1296                        // See the `_ => { ... }` branch.
1297                        if !had_count_error {
1298                            ctx.report_arg_mismatch(param_id, arg_idx as u32, has_self_arg);
1299                        }
1300                        while args.next().is_some() {}
1301                    }
1302                }
1303                _ => {
1304                    // We expected one kind of parameter, but the user provided
1305                    // another. This is an error. However, if we already know that
1306                    // the arguments don't match up with the parameters, we won't issue
1307                    // an additional error, as the user already knows what's wrong.
1308                    if !had_count_error {
1309                        ctx.report_arg_mismatch(param_id, arg_idx as u32, has_self_arg);
1310                    }
1311
1312                    // We've reported the error, but we want to make sure that this
1313                    // problem doesn't bubble down and create additional, irrelevant
1314                    // errors. In this case, we're simply going to ignore the argument
1315                    // and any following arguments. The rest of the parameters will be
1316                    // inferred.
1317                    while args.next().is_some() {}
1318                }
1319            },
1320
1321            (Some(&(_, arg)), None) => {
1322                // We should never be able to reach this point with well-formed input.
1323                // There are two situations in which we can encounter this issue.
1324                //
1325                //  1. The number of arguments is incorrect. In this case, an error
1326                //     will already have been emitted, and we can ignore it.
1327                //  2. We've inferred some lifetimes, which have been provided later (i.e.
1328                //     after a type or const). We want to throw an error in this case.
1329                if !had_count_error {
1330                    assert!(
1331                        matches!(arg, HirGenericArg::Lifetime(_)),
1332                        "the only possible situation here is incorrect lifetime order"
1333                    );
1334                    let (provided_arg_idx, param_id) =
1335                        force_infer_lt.expect("lifetimes ought to have been inferred");
1336                    ctx.report_arg_mismatch(param_id, provided_arg_idx, has_self_arg);
1337                }
1338
1339                break;
1340            }
1341
1342            (None, Some(&(param_id, param))) => {
1343                // If there are fewer arguments than parameters, it means we're inferring the remaining arguments.
1344                let param = if let GenericParamId::LifetimeParamId(_) = param_id {
1345                    match &lifetime_elision {
1346                        LifetimeElisionKind::ElisionFailure
1347                        | LifetimeElisionKind::AnonymousCreateParameter { report_in_path: true }
1348                        | LifetimeElisionKind::AnonymousReportError => {
1349                            assert!(had_count_error);
1350                            ctx.inferred_kind(
1351                                def,
1352                                param_id,
1353                                param,
1354                                infer_args,
1355                                &substs,
1356                                had_count_error,
1357                            )
1358                        }
1359                        LifetimeElisionKind::StaticIfNoLifetimeInScope { only_lint: _ } => {
1360                            Region::new_static(interner).into()
1361                        }
1362                        LifetimeElisionKind::Elided(lifetime) => (*lifetime).into(),
1363                        LifetimeElisionKind::AnonymousCreateParameter { report_in_path: false }
1364                        | LifetimeElisionKind::Infer => {
1365                            // FIXME: With `AnonymousCreateParameter`, we need to create a new lifetime parameter here
1366                            // (but this will probably be done in hir-def lowering instead).
1367                            ctx.inferred_kind(
1368                                def,
1369                                param_id,
1370                                param,
1371                                infer_args,
1372                                &substs,
1373                                had_count_error,
1374                            )
1375                        }
1376                    }
1377                } else {
1378                    ctx.inferred_kind(def, param_id, param, infer_args, &substs, had_count_error)
1379                };
1380                substs.push(param);
1381                params.next();
1382            }
1383
1384            (None, None) => break,
1385        }
1386    }
1387
1388    GenericArgs::new_from_slice(&substs)
1389}
1390
1391fn type_looks_like_const(
1392    store: &ExpressionStore,
1393    type_ref: TypeRefId,
1394) -> Option<TypeLikeConst<'_>> {
1395    // A path/`_` const will be parsed as a type, instead of a const, because when parsing/lowering
1396    // in hir-def we don't yet know the expected argument kind. rustc does this a bit differently,
1397    // when lowering to HIR it resolves the path, and if it doesn't resolve to the type namespace
1398    // it is lowered as a const. Our behavior could deviate from rustc when the value is resolvable
1399    // in both the type and value namespaces, but I believe we only allow more code.
1400    let type_ref = &store[type_ref];
1401    match type_ref {
1402        TypeRef::Path(path) => Some(TypeLikeConst::Path(path)),
1403        TypeRef::Placeholder => Some(TypeLikeConst::Infer),
1404        _ => None,
1405    }
1406}