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
use std::{
    borrow::Borrow,
    fmt::{Display, Result},
    sync::Arc,
};

use crate::rust_ir::*;
use chalk_ir::{interner::Interner, *};
use itertools::Itertools;

use crate::{logging_db::RecordedItemId, split::Split, RustIrDatabase};

#[macro_use]
mod utils;

mod bounds;
mod identifiers;
mod items;
mod render_trait;
mod state;
mod stub;
mod ty;

use self::render_trait::*;
pub use self::state::*;
pub use self::utils::sanitize_debug_name;

use self::utils::as_display;

fn write_item<F, I, T>(f: &mut F, ws: &InternalWriterState<'_, I>, v: &T) -> Result
where
    F: std::fmt::Write + ?Sized,
    I: Interner,
    T: RenderAsRust<I>,
{
    writeln!(f, "{}", v.display(ws))
}

/// Writes stubs for items which were referenced by name, but for which we
/// didn't directly access. For instance, traits mentioned in where bounds which
/// are only usually checked during well-formedness, when we weren't recording
/// well-formedness.
///
/// The "stub" nature of this means it writes output with the right names and
/// the right number of generics, but nothing else. Where clauses, bounds, and
/// fields are skipped. Associated types are ???? skipped.
///
/// `RecordedItemId::Impl` is not supported.
pub fn write_stub_items<F, I, DB, P, T>(f: &mut F, ws: &WriterState<I, DB, P>, ids: T) -> Result
where
    F: std::fmt::Write + ?Sized,
    I: Interner,
    DB: RustIrDatabase<I>,
    P: Borrow<DB>,
    T: IntoIterator<Item = RecordedItemId<I>>,
{
    let wrapped_db = &ws.wrap_db_ref(|db| stub::StubWrapper::new(db.borrow()));

    write_items(f, wrapped_db, ids)
}

/// Writes out each item recorded by a [`LoggingRustIrDatabase`].
///
/// [`LoggingRustIrDatabase`]: crate::logging_db::LoggingRustIrDatabase
pub fn write_items<F, I, DB, P, T>(f: &mut F, ws: &WriterState<I, DB, P>, ids: T) -> Result
where
    F: std::fmt::Write + ?Sized,
    I: Interner,
    DB: RustIrDatabase<I>,
    P: Borrow<DB>,
    T: IntoIterator<Item = RecordedItemId<I>>,
{
    for id in ids {
        match id {
            RecordedItemId::Impl(id) => {
                let v = ws.db().impl_datum(id);
                write_item(f, &InternalWriterState::new(ws), &*v)?;
            }
            RecordedItemId::Adt(id) => {
                let v = ws.db().adt_datum(id);
                write_item(f, &InternalWriterState::new(ws), &*v)?;
            }
            RecordedItemId::Trait(id) => {
                let v = ws.db().trait_datum(id);
                write_item(f, &InternalWriterState::new(ws), &*v)?;
            }
            RecordedItemId::OpaqueTy(id) => {
                let v = ws.db().opaque_ty_data(id);
                write_item(f, &InternalWriterState::new(ws), &*v)?;
            }
            RecordedItemId::FnDef(id) => {
                let v = ws.db().fn_def_datum(id);
                write_item(f, &InternalWriterState::new(ws), &*v)?;
            }
            RecordedItemId::Coroutine(id) => {
                let coroutine = ws.db().coroutine_datum(id);
                let witness = ws.db().coroutine_witness_datum(id);
                write_item(f, &InternalWriterState::new(ws), &(&*coroutine, &*witness))?;
            }
        }
    }
    Ok(())
}

/// Displays a set of bounds, all targeting `Self`, as just the trait names,
/// separated by `+`.
///
/// For example, a list of quantified where clauses which would normally be
/// displayed as:
///
/// ```notrust
/// Self: A, Self: B, Self: C
/// ```
///
/// Is instead displayed by this function as:
///
/// ```notrust
/// A + B + C
/// ```
///
/// Shared between the `Trait` in `dyn Trait` and [`OpaqueTyDatum`] bounds.
fn display_self_where_clauses_as_bounds<'a, I: Interner>(
    s: &'a InternalWriterState<'a, I>,
    bounds: &'a [QuantifiedWhereClause<I>],
) -> impl Display + 'a {
    as_display(move |f| {
        let interner = s.db().interner();
        write!(
            f,
            "{}",
            bounds
                .iter()
                .map(|bound| {
                    as_display(|f| {
                        // each individual trait can have a forall
                        let s = &s.add_debrujin_index(None);
                        if !bound.binders.is_empty(interner) {
                            write!(
                                f,
                                "forall<{}> ",
                                s.binder_var_display(&bound.binders)
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            )?;
                        }
                        match &bound.skip_binders() {
                            WhereClause::Implemented(trait_ref) => display_type_with_generics(
                                s,
                                trait_ref.trait_id,
                                &trait_ref.substitution.as_slice(interner)[1..],
                            )
                            .fmt(f),
                            WhereClause::AliasEq(alias_eq) => match &alias_eq.alias {
                                AliasTy::Projection(projection_ty) => {
                                    let (assoc_ty_datum, trait_params, assoc_type_params) =
                                        s.db().split_projection(projection_ty);
                                    display_trait_with_assoc_ty_value(
                                        s,
                                        assoc_ty_datum,
                                        &trait_params[1..],
                                        assoc_type_params,
                                        &alias_eq.ty,
                                    )
                                    .fmt(f)
                                }
                                AliasTy::Opaque(opaque) => opaque.display(s).fmt(f),
                            },
                            WhereClause::LifetimeOutlives(lifetime) => lifetime.display(s).fmt(f),
                            WhereClause::TypeOutlives(ty) => ty.display(s).fmt(f),
                        }
                    })
                    .to_string()
                })
                .format(" + ")
        )
    })
}

/// Displays a type with its parameters - something like `AsRef<T>`,
/// OpaqueTyName<U>, or `AdtName<Value>`.
///
/// This is shared between where bounds, OpaqueTy, & dyn Trait.
fn display_type_with_generics<'a, I: Interner>(
    s: &'a InternalWriterState<'a, I>,
    trait_name: impl RenderAsRust<I> + 'a,
    trait_params: impl IntoIterator<Item = &'a GenericArg<I>> + 'a,
) -> impl Display + 'a {
    use std::fmt::Write;
    let trait_params = trait_params.into_iter().map(|param| param.display(s));
    let mut trait_params_str = String::new();
    write_joined_non_empty_list!(trait_params_str, "<{}>", trait_params, ", ").unwrap();
    as_display(move |f| write!(f, "{}{}", trait_name.display(s), trait_params_str))
}

/// Displays a trait with its parameters and a single associated type -
/// something like `IntoIterator<Item=T>`.
///
/// This is shared between where bounds & dyn Trait.
fn display_trait_with_assoc_ty_value<'a, I: Interner>(
    s: &'a InternalWriterState<'a, I>,
    assoc_ty_datum: Arc<AssociatedTyDatum<I>>,
    trait_params: &'a [GenericArg<I>],
    assoc_ty_params: &'a [GenericArg<I>],
    assoc_ty_value: &'a Ty<I>,
) -> impl Display + 'a {
    as_display(move |f| {
        write!(f, "{}<", assoc_ty_datum.trait_id.display(s))?;
        write_joined_non_empty_list!(
            f,
            "{}, ",
            trait_params.iter().map(|param| param.display(s)),
            ", "
        )?;
        write!(f, "{}", assoc_ty_datum.id.display(s))?;
        write_joined_non_empty_list!(
            f,
            "<{}>",
            assoc_ty_params.iter().map(|param| param.display(s)),
            ", "
        )?;
        write!(f, "={}>", assoc_ty_value.display(s))?;
        Ok(())
    })
}