trustfall-rustdoc-adapter 60.0.0

Trustfall query adapter for rustdoc JSON data.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! Placeholder assignment for parameter-position `impl Trait`.
//!
//! Rustdoc splits each parameter-position `impl Trait` across two places: the
//! parameter type contains a `Type::ImplTrait` use site, while
//! `Function::generics.params` contains the corresponding synthetic generic
//! param and its bounds. Bounds and associated-item constraints are
//! semantically unordered, so equivalent source can appear in different rustdoc
//! orders.
//!
//! Canonical order is the deterministic order produced by sorting those
//! unordered pieces by normalized sort key. Formatter order is the order in
//! which `types.rs` encounters `Type::ImplTrait` nodes while rendering the raw
//! rustdoc type tree.
//!
//! This module uses both orders: a raw rustdoc-order walk pairs each use site
//! with the next synthetic generic param, while a canonical-order walk assigns
//! stable `IT<parameter>_<n>` placeholders. For example, in
//! `impl Trait<B = impl Copy, A = impl Clone>`, canonical order names `A`'s
//! `impl Clone` as `IT1_1` and `B`'s `impl Copy` as `IT1_2`, but the formatter
//! cursor yields `IT1_2` before `IT1_1` because it visits `B` before `A`.

use std::{borrow::Cow, collections::BTreeMap, num::NonZeroUsize};

use rustdoc_types::{
    AssocItemConstraint, AssocItemConstraintKind, GenericArg, GenericArgs, GenericBound,
    GenericParamDef, GenericParamDefKind, Generics, Path, Term, Type, WherePredicate,
};

use crate::PackageIndex;

use super::{
    names::{Names, is_synthetic_type_param, parameter_impl_trait_placeholder},
    sort_key,
};

#[derive(Clone, Copy, Debug)]
struct SyntheticTypeParam {
    index: usize,
}

/// The `impl Trait` uses inside a function's parameters.
///
/// Each item inside `by_parameter` describes the `impl Trait` uses in
/// the corresponding parameter, matched positionally (by index).
/// When formatting, each parameter's data is consumed via [`ParameterImplTraitCursor`].
#[derive(Clone, Debug)]
pub(super) struct FnParameterImplTraits {
    by_parameter: Vec<Vec<Cow<'static, str>>>,
}

/// Cursor over the synthetic type-param names for one function parameter.
///
/// A parameter may contain multiple `impl Trait` occurrences, such as
/// `(&impl Clone, Vec<impl Into<String>>)`. During parameter formatting, each
/// `Type::ImplTrait` consumes the next name from this cursor. Return-position
/// `impl Trait` formatting does not use this cursor, so it remains an opaque
/// `impl` type rather than becoming a synthetic generic placeholder.
#[derive(Clone, Copy)]
pub(super) struct ParameterImplTraitCursor {
    parameter_index: usize,
    next: usize,
}

impl FnParameterImplTraits {
    /// Returns a cursor over placeholders consumed while formatting `position`.
    ///
    /// The cursor order matches the formatter traversal order of `Type::ImplTrait`
    /// nodes in that parameter. Placeholder assignment itself may have used a
    /// canonical ordering first, so callers should not index into
    /// `by_parameter` directly.
    pub(super) fn cursor_for_parameter(&self, position: NonZeroUsize) -> ParameterImplTraitCursor {
        let parameter_index = position.get() - 1;
        self.by_parameter
            .get(parameter_index)
            .expect("function parameter position was out of bounds");
        ParameterImplTraitCursor {
            parameter_index,
            next: 0,
        }
    }
}

impl ParameterImplTraitCursor {
    pub(super) fn next<'a>(&mut self, impl_traits: &'a FnParameterImplTraits) -> &'a str {
        let names = impl_traits
            .by_parameter
            .get(self.parameter_index)
            .expect("parameter impl Trait cursor had an invalid parameter index");
        let name = names.get(self.next).unwrap_or_else(|| {
            unreachable!(
                "parameter-position impl Trait had no matching synthetic generic parameter: \
                next={}, names={:?}",
                self.next, names,
            )
        });
        self.next += 1;
        name.as_ref()
    }

    pub(super) fn next_index(&self) -> usize {
        self.next
    }

    pub(super) fn assert_finished(&self, impl_traits: &FnParameterImplTraits) {
        let names = impl_traits
            .by_parameter
            .get(self.parameter_index)
            .expect("parameter impl Trait cursor had an invalid parameter index");
        assert_eq!(
            self.next,
            names.len(),
            "not all parameter-position impl Trait synthetic generic parameters were used",
        );
    }
}

fn collect_type_impl_trait_params<'a>(
    crate_: &PackageIndex<'_>,
    names: &Names<'a>,
    type_: &'a Type,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    output: &mut Vec<SyntheticTypeParam>,
) {
    match type_ {
        Type::ResolvedPath(path) => {
            collect_path_impl_trait_params(crate_, names, path, synthetic_params, output);
        }
        Type::DynTrait(dyn_trait) => {
            let mut traits = Vec::new();
            for trait_ in &dyn_trait.traits {
                assert_supported_hrtb_generic_params(&trait_.generic_params);
                // TODO: If this cloning ends up being expensive,
                // we can look to replace it with an immutable hierarchical design instead.
                let mut scoped_names = names.clone();
                for param in &trait_.generic_params {
                    scoped_names.add_higher_ranked_param(param);
                }
                let mut params = Vec::new();
                collect_path_impl_trait_params(
                    crate_,
                    &scoped_names,
                    &trait_.trait_,
                    synthetic_params,
                    &mut params,
                );
                traits.push((
                    sort_key::parameter_poly_trait(crate_, names, trait_),
                    params,
                ));
            }
            traits.sort_unstable_by(|a, b| a.0.cmp(&b.0));
            for (_, params) in traits {
                output.extend(params);
            }
        }
        Type::Generic(_) | Type::Primitive(_) | Type::Infer | Type::Pat { .. } => {
            // No `impl Trait` uses here.
        }
        Type::FunctionPointer(pointer) => {
            assert_supported_hrtb_generic_params(&pointer.generic_params);
            // As of Rust 1.96, `impl Trait` nested in `fn` pointer signatures is
            // rejected, so there are no parameter-position synthetic params to
            // collect inside `pointer.sig`.
        }
        Type::Tuple(types) => {
            for type_ in types {
                collect_type_impl_trait_params(crate_, names, type_, synthetic_params, output);
            }
        }
        Type::Slice(type_) | Type::Array { type_, .. } => {
            collect_type_impl_trait_params(crate_, names, type_, synthetic_params, output);
        }
        Type::ImplTrait(bounds) => {
            collect_bounds_impl_trait_params(crate_, names, bounds, synthetic_params, output);
            output.push(synthetic_params.next().expect(
                "parameter-position impl Trait had no matching synthetic generic parameter",
            ));
        }
        Type::RawPointer { type_, .. } | Type::BorrowedRef { type_, .. } => {
            collect_type_impl_trait_params(crate_, names, type_, synthetic_params, output);
        }
        Type::QualifiedPath {
            args,
            self_type,
            trait_,
            ..
        } => {
            collect_type_impl_trait_params(crate_, names, self_type, synthetic_params, output);
            if let Some(trait_) = trait_ {
                collect_path_impl_trait_params(crate_, names, trait_, synthetic_params, output);
            }
            if let Some(args) = args.as_deref() {
                collect_generic_args_impl_trait_params(
                    crate_,
                    names,
                    args,
                    synthetic_params,
                    output,
                );
            }
        }
    }
}

fn assert_supported_hrtb_generic_params(params: &[GenericParamDef]) {
    for param in params {
        match &param.kind {
            GenericParamDefKind::Lifetime { .. } => {}
            GenericParamDefKind::Type { .. } => {
                // These generic params come from higher-ranked `for<...>`
                // binders on `fn` pointers or trait bounds. As of Rust 1.96,
                // hypothetical `for<T>` binders are rejected, so there are no
                // parameter-position synthetic params to collect here.
                unreachable!("found type generic param definition in HRTB position: {param:?}");
            }
            GenericParamDefKind::Const { .. } => {
                // These generic params come from higher-ranked `for<...>`
                // binders on `fn` pointers or trait bounds. As of Rust 1.96,
                // hypothetical `for<const N: usize>` binders are rejected, so
                // there are no parameter-position synthetic params to collect here.
                unreachable!("found const generic param definition in HRTB position: {param:?}");
            }
        }
    }
}

fn collect_path_impl_trait_params<'a>(
    crate_: &PackageIndex<'_>,
    names: &Names<'a>,
    path: &'a Path,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    output: &mut Vec<SyntheticTypeParam>,
) {
    if let Some(args) = path.args.as_deref() {
        collect_generic_args_impl_trait_params(crate_, names, args, synthetic_params, output);
    }
}

fn collect_generic_args_impl_trait_params<'a>(
    crate_: &PackageIndex<'_>,
    names: &Names<'a>,
    args: &'a GenericArgs,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    output: &mut Vec<SyntheticTypeParam>,
) {
    match args {
        GenericArgs::AngleBracketed { args, constraints } => {
            for arg in args {
                match arg {
                    GenericArg::Type(type_) => {
                        collect_type_impl_trait_params(
                            crate_,
                            names,
                            type_,
                            synthetic_params,
                            output,
                        );
                    }
                    GenericArg::Lifetime(_) | GenericArg::Const(_) | GenericArg::Infer => {}
                }
            }

            let mut constraint_params = Vec::new();
            for constraint in constraints {
                let mut params = Vec::new();
                collect_assoc_item_constraint_impl_trait_params_raw(
                    crate_,
                    names,
                    constraint,
                    synthetic_params,
                    &mut params,
                );
                constraint_params.push((
                    sort_key::parameter_assoc_item_constraint(crate_, names, constraint),
                    params,
                ));
            }
            constraint_params.sort_unstable_by(|a, b| a.0.cmp(&b.0));
            for (_, params) in constraint_params {
                output.extend(params);
            }
        }
        GenericArgs::Parenthesized { .. } => {
            // Parenthesized args represent `Fn`-trait signatures.
            // As of Rust 1.96, `impl Trait` nested in `Fn`-trait signatures is rejected,
            // so there are no parameter-position synthetic params to collect here.
        }
        GenericArgs::ReturnTypeNotation => {}
    }
}

fn collect_assoc_item_constraint_impl_trait_params_raw<'a>(
    crate_: &PackageIndex<'_>,
    names: &Names<'a>,
    constraint: &'a AssocItemConstraint,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    output: &mut Vec<SyntheticTypeParam>,
) {
    if let Some(args) = constraint.args.as_deref() {
        collect_generic_args_impl_trait_params(crate_, names, args, synthetic_params, output);
    }

    match &constraint.binding {
        AssocItemConstraintKind::Constraint(bounds) => {
            collect_bounds_impl_trait_params(crate_, names, bounds, synthetic_params, output);
        }
        AssocItemConstraintKind::Equality(term) => {
            collect_term_impl_trait_params(crate_, names, term, synthetic_params, output);
        }
    }
}

fn collect_bounds_impl_trait_params<'a>(
    crate_: &PackageIndex<'_>,
    names: &Names<'a>,
    bounds: &'a [GenericBound],
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    output: &mut Vec<SyntheticTypeParam>,
) {
    let mut bound_params = Vec::new();
    for bound in bounds {
        let mut params = Vec::new();
        match bound {
            GenericBound::TraitBound {
                trait_,
                generic_params,
                ..
            } => {
                assert_supported_hrtb_generic_params(generic_params);
                // TODO: If this cloning ends up being expensive,
                // we can look to replace it with an immutable hierarchical design instead.
                let mut scoped_names = names.clone();
                for param in generic_params {
                    scoped_names.add_higher_ranked_param(param);
                }
                collect_path_impl_trait_params(
                    crate_,
                    &scoped_names,
                    trait_,
                    synthetic_params,
                    &mut params,
                );
            }
            GenericBound::Outlives(_) | GenericBound::Use(_) => {}
        }
        bound_params.push((
            sort_key::parameter_generic_bound(crate_, names, bound),
            params,
        ));
    }

    bound_params.sort_unstable_by(|a, b| a.0.cmp(&b.0));
    for (_, params) in bound_params {
        output.extend(params);
    }
}

fn collect_term_impl_trait_params<'a>(
    crate_: &PackageIndex<'_>,
    names: &Names<'a>,
    term: &'a Term,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    output: &mut Vec<SyntheticTypeParam>,
) {
    match term {
        Term::Type(type_) => {
            collect_type_impl_trait_params(crate_, names, type_, synthetic_params, output);
        }
        Term::Constant(constant) => {
            // As of Rust 1.96, associated const equality constraints such as
            // `T: Trait<N = 3>` are incomplete and rejected, so there are no
            // parameter-position synthetic params to collect here.
            unreachable!("found associated const equality constraint term: {constant:?}");
        }
    }
}

/// Computes the parameter-position `impl Trait` placeholders for one function.
///
/// Placeholder assignment is scoped to each containing function parameter:
/// `impl Trait` in the first parameter is named `IT1_1`, `IT1_2`, and so on,
/// while `impl Trait` in the second parameter is named `IT2_1`, `IT2_2`, and so
/// on. This keeps unrelated parameter positions from being renumbered when a
/// new `impl Trait` is added elsewhere in the same function signature.
pub(super) fn compute_for_function<'a>(
    crate_: &'a PackageIndex<'a>,
    names: &Names<'a>,
    function: &'a rustdoc_types::Function,
) -> FnParameterImplTraits {
    let synthetic_params = function
        .generics
        .params
        .iter()
        .enumerate()
        .filter(|(_, param)| is_synthetic_type_param(param))
        .map(|(index, _)| SyntheticTypeParam { index })
        .collect::<Vec<_>>();
    let mut synthetic_params = synthetic_params.iter().copied();
    let mut sink = Vec::new();

    collect_generics_impl_trait_names(
        &function.generics,
        &mut synthetic_params,
        None,
        &mut sink,
        false,
    );

    let mut output = Vec::with_capacity(function.sig.inputs.len());
    for (index, (_, type_)) in function.sig.inputs.iter().enumerate() {
        let parameter_position = index + 1;
        // Assign each parameter's suffixes in canonical order, but leave the
        // real cursor untouched. The formatter walks raw rustdoc nodes while
        // building strings that may later be sorted, so the cursor it receives
        // must remain in formatter traversal order.
        let mut canonical_synthetic_params = synthetic_params.clone();
        let mut canonical_params = Vec::new();
        collect_type_impl_trait_params(
            crate_,
            names,
            type_,
            &mut canonical_synthetic_params,
            &mut canonical_params,
        );

        let mut synthetic_names_by_index = BTreeMap::new();
        for (local_index, param) in canonical_params.iter().enumerate() {
            let existing = synthetic_names_by_index.insert(
                param.index,
                parameter_impl_trait_placeholder(parameter_position, local_index + 1),
            );
            assert!(
                existing.is_none(),
                "duplicate synthetic type parameter index `{}` in parameter {parameter_position}",
                param.index,
            );
        }

        let mut parameter_names = Vec::new();
        collect_type_impl_trait_names(
            type_,
            &mut synthetic_params,
            Some(&synthetic_names_by_index),
            &mut parameter_names,
            true,
        );
        output.push(parameter_names);
    }

    collect_where_predicates_impl_trait_names(
        &function.generics.where_predicates,
        &mut synthetic_params,
        None,
        &mut sink,
        false,
    );

    assert!(
        synthetic_params.next().is_none(),
        "rustdoc synthetic generics outnumbered parameter-position impl Trait occurrences",
    );
    FnParameterImplTraits {
        by_parameter: output,
    }
}

fn collect_generics_impl_trait_names(
    generics: &Generics,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    for param in &generics.params {
        match &param.kind {
            GenericParamDefKind::Type {
                bounds,
                default,
                is_synthetic: false,
            } => {
                collect_bounds_impl_trait_names(
                    bounds,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
                if let Some(default) = default {
                    collect_type_impl_trait_names(
                        default,
                        synthetic_params,
                        synthetic_names_by_index,
                        output,
                        emit,
                    );
                }
            }
            GenericParamDefKind::Type {
                is_synthetic: true, ..
            }
            | GenericParamDefKind::Lifetime { .. } => {}
            GenericParamDefKind::Const { type_, .. } => {
                collect_type_impl_trait_names(
                    type_,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
        }
    }
}

fn collect_type_impl_trait_names(
    type_: &Type,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    match type_ {
        Type::ResolvedPath(path) => {
            collect_path_impl_trait_names(
                path,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
        }
        Type::DynTrait(dyn_trait) => {
            for trait_ in &dyn_trait.traits {
                assert_supported_hrtb_generic_params(&trait_.generic_params);
                collect_path_impl_trait_names(
                    &trait_.trait_,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
        }
        Type::Generic(_) | Type::Primitive(_) | Type::Infer | Type::Pat { .. } => {}
        Type::FunctionPointer(pointer) => {
            assert_supported_hrtb_generic_params(&pointer.generic_params);
            // As of Rust 1.96, `impl Trait` nested in `fn` pointer signatures is
            // rejected, so there are no parameter-position synthetic params to
            // collect inside `pointer.sig`.
        }
        Type::Tuple(types) => {
            for type_ in types {
                collect_type_impl_trait_names(
                    type_,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
        }
        Type::Slice(type_) | Type::Array { type_, .. } => {
            collect_type_impl_trait_names(
                type_,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
        }
        Type::ImplTrait(bounds) => {
            collect_bounds_impl_trait_names(
                bounds,
                synthetic_params,
                synthetic_names_by_index,
                output,
                false,
            );
            let param = synthetic_params.next().expect(
                "parameter-position impl Trait had no matching synthetic generic parameter",
            );
            if emit {
                let names = synthetic_names_by_index.expect(
                    "parameter-position impl Trait name emission requires precomputed names",
                );
                output.push(names.get(&param.index).cloned().unwrap_or_else(|| {
                    unreachable!(
                        "missing normalized name for synthetic type parameter index `{}`",
                        param.index,
                    )
                }));
            }
        }
        Type::RawPointer { type_, .. } | Type::BorrowedRef { type_, .. } => {
            collect_type_impl_trait_names(
                type_,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
        }
        Type::QualifiedPath {
            args,
            self_type,
            trait_,
            ..
        } => {
            collect_type_impl_trait_names(
                self_type,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
            if let Some(trait_) = trait_ {
                collect_path_impl_trait_names(
                    trait_,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
            if let Some(args) = args.as_deref() {
                collect_generic_args_impl_trait_names(
                    args,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
        }
    }
}

fn collect_path_impl_trait_names(
    path: &Path,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    if let Some(args) = path.args.as_deref() {
        collect_generic_args_impl_trait_names(
            args,
            synthetic_params,
            synthetic_names_by_index,
            output,
            emit,
        );
    }
}

fn collect_generic_args_impl_trait_names(
    args: &GenericArgs,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    match args {
        GenericArgs::AngleBracketed { args, constraints } => {
            for arg in args {
                match arg {
                    GenericArg::Type(type_) => {
                        collect_type_impl_trait_names(
                            type_,
                            synthetic_params,
                            synthetic_names_by_index,
                            output,
                            emit,
                        );
                    }
                    GenericArg::Lifetime(_) | GenericArg::Const(_) | GenericArg::Infer => {}
                }
            }
            for constraint in constraints {
                collect_assoc_item_constraint_impl_trait_names(
                    constraint,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
        }
        GenericArgs::Parenthesized { .. } => {
            // Parenthesized args represent `Fn`-trait signatures.
            // As of Rust 1.96, `impl Trait` nested in those input or output
            // types is rejected, so there are no parameter-position synthetic
            // params to collect here.
        }
        GenericArgs::ReturnTypeNotation => {}
    }
}

fn collect_assoc_item_constraint_impl_trait_names(
    constraint: &AssocItemConstraint,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    if let Some(args) = constraint.args.as_deref() {
        collect_generic_args_impl_trait_names(
            args,
            synthetic_params,
            synthetic_names_by_index,
            output,
            emit,
        );
    }

    match &constraint.binding {
        AssocItemConstraintKind::Constraint(bounds) => {
            collect_bounds_impl_trait_names(
                bounds,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
        }
        AssocItemConstraintKind::Equality(term) => {
            collect_term_impl_trait_names(
                term,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
        }
    }
}

fn collect_bounds_impl_trait_names(
    bounds: &[GenericBound],
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    for bound in bounds {
        match bound {
            GenericBound::TraitBound {
                trait_,
                generic_params,
                ..
            } => {
                assert_supported_hrtb_generic_params(generic_params);
                collect_path_impl_trait_names(
                    trait_,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
            GenericBound::Outlives(_) | GenericBound::Use(_) => {}
        }
    }
}

fn collect_term_impl_trait_names(
    term: &Term,
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    match term {
        Term::Type(type_) => {
            collect_type_impl_trait_names(
                type_,
                synthetic_params,
                synthetic_names_by_index,
                output,
                emit,
            );
        }
        Term::Constant(constant) => {
            // As of Rust 1.96, associated const equality constraints such as
            // `T: Trait<N = 3>` are incomplete and rejected, so there are no
            // parameter-position synthetic params to collect here.
            unreachable!("found associated const equality constraint term: {constant:?}");
        }
    }
}

fn collect_where_predicates_impl_trait_names(
    predicates: &[WherePredicate],
    synthetic_params: &mut impl Iterator<Item = SyntheticTypeParam>,
    synthetic_names_by_index: Option<&BTreeMap<usize, Cow<'static, str>>>,
    output: &mut Vec<Cow<'static, str>>,
    emit: bool,
) {
    for predicate in predicates {
        match predicate {
            WherePredicate::BoundPredicate {
                type_,
                bounds,
                generic_params,
            } => {
                assert_supported_hrtb_generic_params(generic_params);
                collect_type_impl_trait_names(
                    type_,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
                collect_bounds_impl_trait_names(
                    bounds,
                    synthetic_params,
                    synthetic_names_by_index,
                    output,
                    emit,
                );
            }
            WherePredicate::LifetimePredicate { .. } => {}
            WherePredicate::EqPredicate { .. } => {
                // As of Rust 1.96, general equality constraints such as
                // `where T::Assoc = U` are rejected. Associated-item
                // constraints such as `where T: Trait<Assoc = U>` are represented
                // as `BoundPredicate` instead, so there are no
                // parameter-position synthetic params to collect here.
                unreachable!(
                    "found general equality predicate in function generics: {predicate:?}"
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use crate::adapter::normalize::names::parameter_impl_trait_placeholder;

    #[test]
    fn first_impl_trait_names_use_requested_static_prefix() {
        assert!(matches!(
            parameter_impl_trait_placeholder(1, 1),
            Cow::Borrowed("IT1_1")
        ));
        assert!(matches!(
            parameter_impl_trait_placeholder(8, 1),
            Cow::Borrowed("IT8_1")
        ));
        assert!(
            matches!(parameter_impl_trait_placeholder(9, 1), Cow::Owned(value) if value == "IT9_1")
        );
        assert!(
            matches!(parameter_impl_trait_placeholder(1, 2), Cow::Owned(value) if value == "IT1_2")
        );
    }
}