Skip to main content

rustdoc/json/
conversions.rs

1//! These from impls are used to create the JSON types which get serialized. They're very close to
2//! the `clean` types but with some fields removed or stringified to simplify the output and not
3//! expose unstable compiler internals.
4
5use rustc_abi::ExternAbi;
6use rustc_ast::ast;
7use rustc_data_structures::fx::FxHashSet;
8use rustc_data_structures::thin_vec::ThinVec;
9use rustc_hir as hir;
10use rustc_hir::attrs::{
11    self, DeprecatedSince, DocAttribute, DocCfgHideShow, DocInline, HideOrShow, RustcVersion,
12};
13use rustc_hir::def::{CtorKind, DefKind};
14use rustc_hir::def_id::DefId;
15use rustc_hir::{HeaderSafety, Safety, find_attr, intravisit};
16use rustc_hir_pretty::PpAnn;
17use rustc_metadata::rendered_const;
18use rustc_middle::ty::TyCtxt;
19use rustc_middle::{bug, ty};
20use rustc_span::def_id::ModId;
21use rustc_span::{Pos, Symbol, kw, sym};
22use rustdoc_json_types::*;
23
24use crate::clean::{self, ItemId};
25use crate::formats::item_type::ItemType;
26use crate::json::JsonRenderer;
27use crate::passes::collect_intra_doc_links::UrlFragment;
28
29impl JsonRenderer<'_> {
30    pub(super) fn convert_item(&self, item: &clean::Item) -> Option<Item> {
31        let deprecation = item.deprecation(self.tcx);
32        let links = self
33            .cache
34            .intra_doc_links
35            .get(&item.item_id)
36            .into_iter()
37            .flatten()
38            .map(|clean::ItemLink { link, page_id, fragment, .. }| {
39                let id = match fragment {
40                    Some(UrlFragment::Item(frag_id)) => *frag_id,
41                    // FIXME: Pass the `UserWritten` segment to JSON consumer.
42                    Some(UrlFragment::UserWritten(_)) | None => *page_id,
43                };
44
45                (String::from(&**link), self.id_from_item_default(id.into()))
46            })
47            .collect();
48        let docs = item.opt_doc_value();
49        let attrs = item
50            .attrs
51            .other_attrs
52            .iter()
53            .flat_map(|a| maybe_from_hir_attr(a, item.item_id, self.tcx))
54            .collect();
55        let span = item.span(self.tcx);
56        let visibility = item.visibility(self.tcx);
57        let clean::ItemInner { name, item_id, .. } = *item.inner;
58        let id = self.id_from_item(item);
59        let inner = match item.kind {
60            clean::KeywordItem | clean::AttributeItem => return None,
61            clean::StrippedItem(ref inner) => {
62                match &**inner {
63                    // We document stripped modules as with `Module::is_stripped` set to
64                    // `true`, to prevent contained items from being orphaned for downstream users,
65                    // as JSON does no inlining.
66                    clean::ModuleItem(_)
67                        if self.imported_items.contains(&item_id.expect_def_id()) =>
68                    {
69                        from_clean_item(item, self)
70                    }
71                    _ => return None,
72                }
73            }
74            _ => from_clean_item(item, self),
75        };
76
77        // Rustdoc JSON keeps re-exports as `Use` items, so their stability describes
78        // the local `pub use` declaration. The imported target item's stability
79        // remains available through `inner.use.id`.
80        //
81        // We use raw stability attributes here instead of `clean::Item::stability()`,
82        // which is the effective stability rustdoc uses for rendering paths.
83        // For example, a stable `pub use` inside an unstable module is effectively unstable
84        // through that module path, but the `Use` declaration itself is still stable.
85        // In that example, `clean::Item::stability()` would return "unstable" as
86        // the effective stability, which is appropriate for HTML but makes JSON uses harder.
87        //
88        // JSON consumers already have to do path-based reasoning to reconstruct item reachability,
89        // names, and stability. Keeping component-wise stability allows them to easily reconstruct
90        // stability from the module, use item, and target item records.
91        let stability_def_id = if matches!(&item.kind, clean::ImportItem(_)) {
92            item.inline_stmt_id
93                .map(|def_id| def_id.to_def_id())
94                .or_else(|| item.item_id.as_def_id())
95        } else {
96            item.item_id.as_def_id()
97        };
98        let stability = stability_def_id.and_then(|def_id| self.tcx.lookup_stability(def_id));
99        let const_stability = item.item_id.as_def_id().and_then(|def_id| {
100            const_stability_for_def_id(self.tcx, def_id).map(|s| Box::new(s.into_json(self)))
101        });
102
103        Some(Item {
104            id,
105            crate_id: item_id.krate().as_u32(),
106            name: name.map(|sym| sym.to_string()),
107            span: span.and_then(|span| span.into_json(self)),
108            visibility: visibility.into_json(self),
109            stability: stability.map(|s| Box::new(s.into_json(self))),
110            const_stability,
111            docs,
112            attrs,
113            deprecation: deprecation.into_json(self),
114            inner,
115            links,
116        })
117    }
118
119    fn ids(&self, items: &[clean::Item]) -> Vec<Id> {
120        items
121            .iter()
122            .filter(|i| !i.is_stripped() && !i.is_keyword() && !i.is_attribute())
123            .map(|i| self.id_from_item(i))
124            .collect()
125    }
126
127    fn ids_keeping_stripped(&self, items: &[clean::Item]) -> Vec<Option<Id>> {
128        items
129            .iter()
130            .map(|i| {
131                (!i.is_stripped() && !i.is_keyword() && !i.is_attribute())
132                    .then(|| self.id_from_item(i))
133            })
134            .collect()
135    }
136}
137
138pub(crate) trait FromClean<T> {
139    fn from_clean(f: &T, renderer: &JsonRenderer<'_>) -> Self;
140}
141
142pub(crate) trait IntoJson<T> {
143    fn into_json(&self, renderer: &JsonRenderer<'_>) -> T;
144}
145
146impl<T, U> IntoJson<U> for T
147where
148    U: FromClean<T>,
149{
150    fn into_json(&self, renderer: &JsonRenderer<'_>) -> U {
151        U::from_clean(self, renderer)
152    }
153}
154
155impl<T, U> FromClean<Box<T>> for U
156where
157    U: FromClean<T>,
158{
159    fn from_clean(opt: &Box<T>, renderer: &JsonRenderer<'_>) -> Self {
160        opt.as_ref().into_json(renderer)
161    }
162}
163
164impl<T, U> FromClean<Option<T>> for Option<U>
165where
166    U: FromClean<T>,
167{
168    fn from_clean(opt: &Option<T>, renderer: &JsonRenderer<'_>) -> Self {
169        opt.as_ref().map(|x| x.into_json(renderer))
170    }
171}
172
173impl<T, U> FromClean<Vec<T>> for Vec<U>
174where
175    U: FromClean<T>,
176{
177    fn from_clean(items: &Vec<T>, renderer: &JsonRenderer<'_>) -> Self {
178        items.iter().map(|i| i.into_json(renderer)).collect()
179    }
180}
181
182impl<T, U> FromClean<ThinVec<T>> for Vec<U>
183where
184    U: FromClean<T>,
185{
186    fn from_clean(items: &ThinVec<T>, renderer: &JsonRenderer<'_>) -> Self {
187        items.iter().map(|i| i.into_json(renderer)).collect()
188    }
189}
190
191impl FromClean<clean::Span> for Option<Span> {
192    fn from_clean(span: &clean::Span, renderer: &JsonRenderer<'_>) -> Self {
193        match span.filename(renderer.sess()) {
194            rustc_span::FileName::Real(name) => {
195                if let Some(local_path) = name.into_local_path() {
196                    let hi = span.hi(renderer.sess());
197                    let lo = span.lo(renderer.sess());
198                    Some(Span {
199                        filename: local_path,
200                        begin: (lo.line, lo.col.to_usize() + 1),
201                        end: (hi.line, hi.col.to_usize() + 1),
202                    })
203                } else {
204                    None
205                }
206            }
207            _ => None,
208        }
209    }
210}
211
212impl FromClean<Option<ty::Visibility<ModId>>> for Visibility {
213    fn from_clean(v: &Option<ty::Visibility<ModId>>, renderer: &JsonRenderer<'_>) -> Self {
214        match *v {
215            None => Visibility::Default,
216            Some(ty::Visibility::Public) => Visibility::Public,
217            Some(ty::Visibility::Restricted(mod_id)) if mod_id.is_crate_root() => Visibility::Crate,
218            Some(ty::Visibility::Restricted(mod_id)) => Visibility::Restricted {
219                parent: renderer.id_from_item_default(ItemId::DefId(mod_id.to_def_id())),
220                path: renderer.tcx.def_path(mod_id.to_def_id()).to_string_no_crate_verbose(),
221            },
222        }
223    }
224}
225
226impl FromClean<attrs::Deprecation> for Deprecation {
227    fn from_clean(deprecation: &attrs::Deprecation, _renderer: &JsonRenderer<'_>) -> Self {
228        let attrs::Deprecation { since, note, suggestion: _ } = deprecation;
229        let since = match since {
230            DeprecatedSince::RustcVersion(version) => Some(version.to_string()),
231            DeprecatedSince::Future => Some("TBD".to_string()),
232            DeprecatedSince::NonStandard(since) => Some(since.to_string()),
233            DeprecatedSince::Unspecified | DeprecatedSince::Err => None,
234        };
235        Deprecation { since, note: note.map(|sym| sym.to_string()) }
236    }
237}
238
239impl FromClean<hir::Stability> for Stability {
240    fn from_clean(stab: &hir::Stability, _renderer: &JsonRenderer<'_>) -> Self {
241        let feature = stab.feature.to_string();
242        let level = match stab.level {
243            hir::StabilityLevel::Stable { since, .. } => StabilityLevel::Stable {
244                since: match since {
245                    hir::StableSince::Version(since) => Some(since.to_string()),
246                    hir::StableSince::Current => Some(RustcVersion::CURRENT.to_string()),
247                    // Match rustdoc HTML: malformed stable-since values are omitted.
248                    hir::StableSince::Err(_) => None,
249                },
250            },
251            hir::StabilityLevel::Unstable { .. } => StabilityLevel::Unstable,
252        };
253        Stability { feature, level }
254    }
255}
256
257impl FromClean<hir::ConstStability> for Stability {
258    fn from_clean(stab: &hir::ConstStability, _renderer: &JsonRenderer<'_>) -> Self {
259        let feature = stab.feature.to_string();
260        let level = match stab.level {
261            hir::StabilityLevel::Stable { since, .. } => StabilityLevel::Stable {
262                since: match since {
263                    hir::StableSince::Version(since) => Some(since.to_string()),
264                    hir::StableSince::Current => Some(RustcVersion::CURRENT.to_string()),
265                    // Match rustdoc HTML: malformed stable-since values are omitted.
266                    hir::StableSince::Err(_) => None,
267                },
268            },
269            hir::StabilityLevel::Unstable { .. } => StabilityLevel::Unstable,
270        };
271        Stability { feature, level }
272    }
273}
274
275impl FromClean<hir::DefaultBodyStability> for Box<ProvidedDefaultUnstable> {
276    fn from_clean(stab: &hir::DefaultBodyStability, _renderer: &JsonRenderer<'_>) -> Self {
277        let hir::StabilityLevel::Unstable { .. } = stab.level else {
278            bug!(
279                "unexpected stable default-body stability, \
280                 there's no stable equivalent of `#[rustc_default_body_unstable]`"
281            )
282        };
283        Box::new(ProvidedDefaultUnstable { feature: stab.feature.to_string() })
284    }
285}
286
287impl FromClean<clean::GenericArgs> for Option<Box<GenericArgs>> {
288    fn from_clean(generic_args: &clean::GenericArgs, renderer: &JsonRenderer<'_>) -> Self {
289        use clean::GenericArgs::*;
290        match generic_args {
291            AngleBracketed { args, constraints } => {
292                if generic_args.is_empty() {
293                    None
294                } else {
295                    Some(Box::new(GenericArgs::AngleBracketed {
296                        args: args.into_json(renderer),
297                        constraints: constraints.into_json(renderer),
298                    }))
299                }
300            }
301            Parenthesized { inputs, output } => Some(Box::new(GenericArgs::Parenthesized {
302                inputs: inputs.into_json(renderer),
303                output: output.into_json(renderer),
304            })),
305            ReturnTypeNotation => Some(Box::new(GenericArgs::ReturnTypeNotation)),
306        }
307    }
308}
309
310impl FromClean<clean::GenericArg> for GenericArg {
311    fn from_clean(arg: &clean::GenericArg, renderer: &JsonRenderer<'_>) -> Self {
312        use clean::GenericArg::*;
313        match arg {
314            Lifetime(l) => GenericArg::Lifetime(l.into_json(renderer)),
315            Type(t) => GenericArg::Type(t.into_json(renderer)),
316            Const(c) => GenericArg::Const(c.into_json(renderer)),
317            Infer => GenericArg::Infer,
318        }
319    }
320}
321
322impl FromClean<clean::ConstantKind> for Constant {
323    // FIXME(generic_const_items): Add support for generic const items.
324    fn from_clean(constant: &clean::ConstantKind, renderer: &JsonRenderer<'_>) -> Self {
325        let tcx = renderer.tcx;
326        let expr = constant.expr(tcx);
327        let value = constant.value(tcx);
328        let is_literal = constant.is_literal(tcx);
329        Constant { expr, value, is_literal }
330    }
331}
332
333impl FromClean<clean::AssocItemConstraint> for AssocItemConstraint {
334    fn from_clean(constraint: &clean::AssocItemConstraint, renderer: &JsonRenderer<'_>) -> Self {
335        AssocItemConstraint {
336            name: constraint.assoc.name.to_string(),
337            args: constraint.assoc.args.into_json(renderer),
338            binding: constraint.kind.into_json(renderer),
339        }
340    }
341}
342
343impl FromClean<clean::AssocItemConstraintKind> for AssocItemConstraintKind {
344    fn from_clean(kind: &clean::AssocItemConstraintKind, renderer: &JsonRenderer<'_>) -> Self {
345        use clean::AssocItemConstraintKind::*;
346        match kind {
347            Equality { term } => AssocItemConstraintKind::Equality(term.into_json(renderer)),
348            Bound { bounds } => AssocItemConstraintKind::Constraint(bounds.into_json(renderer)),
349        }
350    }
351}
352
353fn from_clean_item(item: &clean::Item, renderer: &JsonRenderer<'_>) -> ItemEnum {
354    use clean::ItemKind::*;
355    let name = item.name;
356    let is_crate = item.is_crate();
357    let header = item.fn_header(renderer.tcx);
358
359    match &item.inner.kind {
360        ModuleItem(m) => {
361            ItemEnum::Module(Module { is_crate, items: renderer.ids(&m.items), is_stripped: false })
362        }
363        ImportItem(i) => ItemEnum::Use(i.into_json(renderer)),
364        StructItem(s) => ItemEnum::Struct(s.into_json(renderer)),
365        UnionItem(u) => ItemEnum::Union(u.into_json(renderer)),
366        StructFieldItem(f) => ItemEnum::StructField(f.into_json(renderer)),
367        EnumItem(e) => ItemEnum::Enum(e.into_json(renderer)),
368        VariantItem(v) => ItemEnum::Variant(v.into_json(renderer)),
369        FunctionItem(f) => {
370            ItemEnum::Function(from_clean_function(f, true, None, header.unwrap(), renderer))
371        }
372        ForeignFunctionItem(f, _) => {
373            ItemEnum::Function(from_clean_function(f, false, None, header.unwrap(), renderer))
374        }
375        TraitItem(t) => ItemEnum::Trait(t.into_json(renderer)),
376        TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_json(renderer)),
377        MethodItem(m, _) => ItemEnum::Function(from_clean_function(
378            m,
379            true,
380            default_body_stability_for_def_id(renderer.tcx, item.item_id.expect_def_id())
381                .map(|stab| stab.into_json(renderer)),
382            header.unwrap(),
383            renderer,
384        )),
385        RequiredMethodItem(m, _) => {
386            ItemEnum::Function(from_clean_function(m, false, None, header.unwrap(), renderer))
387        }
388        ImplItem(i) => ItemEnum::Impl(i.into_json(renderer)),
389        StaticItem(s) => ItemEnum::Static(from_clean_static(s, rustc_hir::Safety::Safe, renderer)),
390        ForeignStaticItem(s, safety) => ItemEnum::Static(from_clean_static(s, *safety, renderer)),
391        ForeignTypeItem => ItemEnum::ExternType,
392        TypeAliasItem(t) => ItemEnum::TypeAlias(t.into_json(renderer)),
393        // FIXME(generic_const_items): Add support for generic free consts
394        ConstantItem(ci) => ItemEnum::Constant {
395            type_: ci.type_.into_json(renderer),
396            const_: ci.kind.into_json(renderer),
397        },
398        MacroItem(m, _) => ItemEnum::Macro(m.source.clone()),
399        ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_json(renderer)),
400        PrimitiveItem(p) => {
401            ItemEnum::Primitive(Primitive {
402                name: p.as_sym().to_string(),
403                impls: Vec::new(), // Added in JsonRenderer::item
404            })
405        }
406        // FIXME(generic_const_items): Add support for generic associated consts.
407        RequiredAssocConstItem(_generics, ty) => ItemEnum::AssocConst {
408            type_: ty.into_json(renderer),
409            value: None,
410            default_unstable: None,
411        },
412        // FIXME(generic_const_items): Add support for generic associated consts.
413        ProvidedAssocConstItem(ci) => ItemEnum::AssocConst {
414            type_: ci.type_.into_json(renderer),
415            value: Some(ci.kind.expr(renderer.tcx)),
416            default_unstable: default_body_stability_for_def_id(
417                renderer.tcx,
418                item.item_id.expect_def_id(),
419            )
420            .map(|stab| stab.into_json(renderer)),
421        },
422        ImplAssocConstItem(ci) => ItemEnum::AssocConst {
423            type_: ci.type_.into_json(renderer),
424            value: Some(ci.kind.expr(renderer.tcx)),
425            default_unstable: None,
426        },
427        RequiredAssocTypeItem(g, b) => ItemEnum::AssocType {
428            generics: g.into_json(renderer),
429            bounds: b.into_json(renderer),
430            type_: None,
431            default_unstable: None,
432        },
433        AssocTypeItem(t, b) => ItemEnum::AssocType {
434            generics: t.generics.into_json(renderer),
435            bounds: b.into_json(renderer),
436            type_: Some(t.item_type.as_ref().unwrap_or(&t.type_).into_json(renderer)),
437            default_unstable: default_body_stability_for_def_id(
438                renderer.tcx,
439                item.item_id.expect_def_id(),
440            )
441            .map(|stab| stab.into_json(renderer)),
442        },
443        // `convert_item` early returns `None` for stripped items, keywords, attributes and
444        // "special" macro rules.
445        KeywordItem | AttributeItem => unreachable!(),
446        StrippedItem(inner) => {
447            match inner.as_ref() {
448                ModuleItem(m) => ItemEnum::Module(Module {
449                    is_crate,
450                    items: renderer.ids(&m.items),
451                    is_stripped: true,
452                }),
453                // `convert_item` early returns `None` for stripped items we're not including
454                _ => unreachable!(),
455            }
456        }
457        ExternCrateItem { src } => ItemEnum::ExternCrate {
458            name: name.as_ref().unwrap().to_string(),
459            rename: src.map(|x| x.to_string()),
460        },
461        // All placeholder impl items should have been removed in the stripper passes.
462        PlaceholderImplItem => unreachable!(),
463    }
464}
465
466impl FromClean<clean::Struct> for Struct {
467    fn from_clean(struct_: &clean::Struct, renderer: &JsonRenderer<'_>) -> Self {
468        let has_stripped_fields = struct_.has_stripped_entries();
469        let clean::Struct { ctor_kind, generics, fields } = struct_;
470
471        let kind = match ctor_kind {
472            Some(CtorKind::Fn) => StructKind::Tuple(renderer.ids_keeping_stripped(fields)),
473            Some(CtorKind::Const) => {
474                assert!(fields.is_empty());
475                StructKind::Unit
476            }
477            None => StructKind::Plain { fields: renderer.ids(fields), has_stripped_fields },
478        };
479
480        Struct {
481            kind,
482            generics: generics.into_json(renderer),
483            impls: Vec::new(), // Added in JsonRenderer::item
484        }
485    }
486}
487
488impl FromClean<clean::Union> for Union {
489    fn from_clean(union_: &clean::Union, renderer: &JsonRenderer<'_>) -> Self {
490        let has_stripped_fields = union_.has_stripped_entries();
491        let clean::Union { generics, fields } = union_;
492        Union {
493            generics: generics.into_json(renderer),
494            has_stripped_fields,
495            fields: renderer.ids(fields),
496            impls: Vec::new(), // Added in JsonRenderer::item
497        }
498    }
499}
500
501impl FromClean<rustc_hir::FnHeader> for FunctionHeader {
502    fn from_clean(header: &rustc_hir::FnHeader, renderer: &JsonRenderer<'_>) -> Self {
503        let is_unsafe = match header.safety {
504            HeaderSafety::SafeTargetFeatures => {
505                // The type system's internal implementation details consider
506                // safe functions with the `#[target_feature]` attribute to be analogous
507                // to unsafe functions: `header.is_unsafe()` returns `true` for them.
508                // For rustdoc, this isn't the right decision, so we explicitly return `false`.
509                // Context: https://github.com/rust-lang/rust/issues/142655
510                false
511            }
512            HeaderSafety::Normal(Safety::Safe) => false,
513            HeaderSafety::Normal(Safety::Unsafe) => true,
514        };
515        FunctionHeader {
516            is_async: header.is_async(),
517            is_const: matches!(header.constness, rustc_hir::Constness::Const { .. }),
518            is_unsafe,
519            abi: header.abi.into_json(renderer),
520        }
521    }
522}
523
524impl FromClean<ExternAbi> for Abi {
525    fn from_clean(a: &ExternAbi, _renderer: &JsonRenderer<'_>) -> Self {
526        match *a {
527            ExternAbi::Rust => Abi::Rust,
528            ExternAbi::C { unwind } => Abi::C { unwind },
529            ExternAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
530            ExternAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
531            ExternAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
532            ExternAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
533            ExternAbi::Win64 { unwind } => Abi::Win64 { unwind },
534            ExternAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
535            ExternAbi::System { unwind } => Abi::System { unwind },
536            _ => Abi::Other(a.to_string()),
537        }
538    }
539}
540
541impl FromClean<clean::Lifetime> for String {
542    fn from_clean(l: &clean::Lifetime, _renderer: &JsonRenderer<'_>) -> String {
543        l.0.to_string()
544    }
545}
546
547impl FromClean<clean::Generics> for Generics {
548    fn from_clean(generics: &clean::Generics, renderer: &JsonRenderer<'_>) -> Self {
549        Generics {
550            params: generics.params.into_json(renderer),
551            where_predicates: generics.where_predicates.into_json(renderer),
552        }
553    }
554}
555
556impl FromClean<clean::GenericParamDef> for GenericParamDef {
557    fn from_clean(generic_param: &clean::GenericParamDef, renderer: &JsonRenderer<'_>) -> Self {
558        GenericParamDef {
559            name: generic_param.name.to_string(),
560            kind: generic_param.kind.into_json(renderer),
561        }
562    }
563}
564
565impl FromClean<clean::GenericParamDefKind> for GenericParamDefKind {
566    fn from_clean(kind: &clean::GenericParamDefKind, renderer: &JsonRenderer<'_>) -> Self {
567        use clean::GenericParamDefKind::*;
568        match kind {
569            Lifetime { outlives } => {
570                GenericParamDefKind::Lifetime { outlives: outlives.into_json(renderer) }
571            }
572            Type { bounds, default, synthetic } => GenericParamDefKind::Type {
573                bounds: bounds.into_json(renderer),
574                default: default.into_json(renderer),
575                is_synthetic: *synthetic,
576            },
577            Const { ty, default } => GenericParamDefKind::Const {
578                type_: ty.into_json(renderer),
579                default: default.as_ref().map(|x| x.as_ref().clone()),
580            },
581        }
582    }
583}
584
585impl FromClean<clean::WherePredicate> for WherePredicate {
586    fn from_clean(predicate: &clean::WherePredicate, renderer: &JsonRenderer<'_>) -> Self {
587        use clean::WherePredicate::*;
588        match predicate {
589            BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
590                type_: ty.into_json(renderer),
591                bounds: bounds.into_json(renderer),
592                generic_params: bound_params.into_json(renderer),
593            },
594            RegionPredicate { lifetime, bounds } => WherePredicate::LifetimePredicate {
595                lifetime: lifetime.into_json(renderer),
596                outlives: bounds
597                    .iter()
598                    .map(|bound| match bound {
599                        clean::GenericBound::Outlives(lt) => lt.into_json(renderer),
600                        _ => bug!("found non-outlives-bound on lifetime predicate"),
601                    })
602                    .collect(),
603            },
604            ProjectionPredicate { lhs, rhs } => WherePredicate::EqPredicate {
605                // The LHS currently has type `Type` but it should be a `QualifiedPath` since it may
606                // refer to an associated const. However, `EqPredicate` shouldn't exist in the first
607                // place: <https://github.com/rust-lang/rust/141368>.
608                lhs: lhs.into_json(renderer),
609                rhs: rhs.into_json(renderer),
610            },
611        }
612    }
613}
614
615impl FromClean<clean::GenericBound> for GenericBound {
616    fn from_clean(bound: &clean::GenericBound, renderer: &JsonRenderer<'_>) -> Self {
617        use clean::GenericBound::*;
618        match bound {
619            TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
620                GenericBound::TraitBound {
621                    trait_: trait_.into_json(renderer),
622                    generic_params: generic_params.into_json(renderer),
623                    modifier: modifier.into_json(renderer),
624                }
625            }
626            Outlives(lifetime) => GenericBound::Outlives(lifetime.into_json(renderer)),
627            Use(args) => GenericBound::Use(
628                args.iter()
629                    .map(|arg| match arg {
630                        clean::PreciseCapturingArg::Lifetime(lt) => {
631                            PreciseCapturingArg::Lifetime(lt.into_json(renderer))
632                        }
633                        clean::PreciseCapturingArg::Param(param) => {
634                            PreciseCapturingArg::Param(param.to_string())
635                        }
636                    })
637                    .collect(),
638            ),
639        }
640    }
641}
642
643impl FromClean<rustc_hir::TraitBoundModifiers> for TraitBoundModifier {
644    fn from_clean(
645        modifiers: &rustc_hir::TraitBoundModifiers,
646        _renderer: &JsonRenderer<'_>,
647    ) -> Self {
648        use rustc_hir as hir;
649        let hir::TraitBoundModifiers { constness, polarity } = modifiers;
650        match (constness, polarity) {
651            (hir::BoundConstness::Never, hir::BoundPolarity::Positive) => TraitBoundModifier::None,
652            (hir::BoundConstness::Never, hir::BoundPolarity::Maybe(_)) => TraitBoundModifier::Maybe,
653            (hir::BoundConstness::Maybe(_), hir::BoundPolarity::Positive) => {
654                TraitBoundModifier::MaybeConst
655            }
656            // FIXME: Fill out the rest of this matrix.
657            _ => TraitBoundModifier::None,
658        }
659    }
660}
661
662impl FromClean<clean::Type> for Type {
663    fn from_clean(ty: &clean::Type, renderer: &JsonRenderer<'_>) -> Self {
664        use clean::Type::{
665            Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
666            RawPointer, SelfTy, Slice, Tuple, UnsafeBinder,
667        };
668
669        match ty {
670            clean::Type::Path { path } => Type::ResolvedPath(path.into_json(renderer)),
671            clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
672                lifetime: lt.into_json(renderer),
673                traits: bounds.into_json(renderer),
674            }),
675            Generic(s) => Type::Generic(s.to_string()),
676            // FIXME: add dedicated variant to json Type?
677            SelfTy => Type::Generic("Self".to_owned()),
678            Primitive(p) => Type::Primitive(p.as_sym().to_string()),
679            BareFunction(f) => Type::FunctionPointer(Box::new(f.into_json(renderer))),
680            Tuple(t) => Type::Tuple(t.into_json(renderer)),
681            Slice(t) => Type::Slice(Box::new(t.into_json(renderer))),
682            Array(t, s) => {
683                Type::Array { type_: Box::new(t.into_json(renderer)), len: s.to_string() }
684            }
685            clean::Type::Pat(t, p) => Type::Pat {
686                type_: Box::new(t.into_json(renderer)),
687                __pat_unstable_do_not_use: p.to_string(),
688            },
689            // FIXME(FRTs): implement
690            clean::Type::FieldOf(..) => unimplemented!(),
691            ImplTrait(g) => Type::ImplTrait(g.into_json(renderer)),
692            Infer => Type::Infer,
693            RawPointer(mutability, type_) => Type::RawPointer {
694                is_mutable: *mutability == ast::Mutability::Mut,
695                type_: Box::new(type_.into_json(renderer)),
696            },
697            BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
698                lifetime: lifetime.into_json(renderer),
699                is_mutable: *mutability == ast::Mutability::Mut,
700                type_: Box::new(type_.into_json(renderer)),
701            },
702            QPath(qpath) => qpath.into_json(renderer),
703            // FIXME(unsafe_binder): Implement rustdoc-json.
704            UnsafeBinder(_) => unimplemented!(),
705        }
706    }
707}
708
709impl FromClean<clean::Path> for Path {
710    fn from_clean(path: &clean::Path, renderer: &JsonRenderer<'_>) -> Self {
711        Path {
712            path: path.whole_name(),
713            id: renderer.id_from_item_default(path.def_id().into()),
714            args: {
715                if let Some((final_seg, rest_segs)) = path.segments.split_last() {
716                    // In general, `clean::Path` can hold things like
717                    // `std::vec::Vec::<u32>::new`, where generic args appear
718                    // in a middle segment. But for the places where `Path` is
719                    // used by rustdoc-json-types, generic args can only be
720                    // used in the final segment, e.g. `std::vec::Vec<u32>`. So
721                    // check that the non-final segments have no generic args.
722                    assert!(rest_segs.iter().all(|seg| seg.args.is_empty()));
723                    final_seg.args.into_json(renderer)
724                } else {
725                    None // no generics on any segments because there are no segments
726                }
727            },
728        }
729    }
730}
731
732impl FromClean<clean::QPathData> for Type {
733    fn from_clean(qpath: &clean::QPathData, renderer: &JsonRenderer<'_>) -> Self {
734        let clean::QPathData { assoc, self_type, should_fully_qualify: _, trait_ } = qpath;
735
736        Self::QualifiedPath {
737            name: assoc.name.to_string(),
738            args: assoc.args.into_json(renderer),
739            self_type: Box::new(self_type.into_json(renderer)),
740            trait_: trait_.into_json(renderer),
741        }
742    }
743}
744
745impl FromClean<clean::Term> for Term {
746    fn from_clean(term: &clean::Term, renderer: &JsonRenderer<'_>) -> Self {
747        match term {
748            clean::Term::Type(ty) => Term::Type(ty.into_json(renderer)),
749            clean::Term::Constant(c) => Term::Constant(c.into_json(renderer)),
750        }
751    }
752}
753
754impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
755    fn from_clean(bare_decl: &clean::BareFunctionDecl, renderer: &JsonRenderer<'_>) -> Self {
756        let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
757        FunctionPointer {
758            header: FunctionHeader {
759                is_unsafe: safety.is_unsafe(),
760                is_const: false,
761                is_async: false,
762                abi: abi.into_json(renderer),
763            },
764            generic_params: generic_params.into_json(renderer),
765            sig: decl.into_json(renderer),
766        }
767    }
768}
769
770impl FromClean<clean::FnDecl> for FunctionSignature {
771    fn from_clean(decl: &clean::FnDecl, renderer: &JsonRenderer<'_>) -> Self {
772        let clean::FnDecl { inputs, output, c_variadic } = decl;
773        FunctionSignature {
774            inputs: inputs
775                .iter()
776                .map(|param| {
777                    // `_` is the most sensible name for missing param names.
778                    let name = param.name.unwrap_or(kw::Underscore).to_string();
779                    let type_ = param.type_.into_json(renderer);
780                    (name, type_)
781                })
782                .collect(),
783            output: if output.is_unit() { None } else { Some(output.into_json(renderer)) },
784            is_c_variadic: *c_variadic,
785        }
786    }
787}
788
789impl FromClean<clean::Trait> for Trait {
790    fn from_clean(trait_: &clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
791        let tcx = renderer.tcx;
792        let is_auto = trait_.is_auto(tcx);
793        let is_unsafe = trait_.safety(tcx).is_unsafe();
794        let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
795        let clean::Trait { items, generics, bounds, .. } = trait_;
796        Trait {
797            is_auto,
798            is_unsafe,
799            is_dyn_compatible,
800            items: renderer.ids(items),
801            generics: generics.into_json(renderer),
802            bounds: bounds.into_json(renderer),
803            implementations: Vec::new(), // Added in JsonRenderer::item
804        }
805    }
806}
807
808impl FromClean<clean::PolyTrait> for PolyTrait {
809    fn from_clean(
810        clean::PolyTrait { trait_, generic_params }: &clean::PolyTrait,
811        renderer: &JsonRenderer<'_>,
812    ) -> Self {
813        PolyTrait {
814            trait_: trait_.into_json(renderer),
815            generic_params: generic_params.into_json(renderer),
816        }
817    }
818}
819
820impl FromClean<clean::Impl> for Impl {
821    fn from_clean(impl_: &clean::Impl, renderer: &JsonRenderer<'_>) -> Self {
822        let provided_trait_methods = impl_.provided_trait_methods(renderer.tcx);
823        let clean::Impl { safety, generics, trait_, for_, items, polarity, kind, is_deprecated: _ } =
824            impl_;
825        // FIXME: use something like ImplKind in JSON?
826        let (is_synthetic, blanket_impl) = match kind {
827            clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
828            clean::ImplKind::Auto => (true, None),
829            clean::ImplKind::Blanket(ty) => (false, Some(ty)),
830        };
831        let is_negative = match polarity {
832            ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
833            ty::ImplPolarity::Negative => true,
834        };
835        Impl {
836            is_unsafe: safety.is_unsafe(),
837            generics: generics.into_json(renderer),
838            provided_trait_methods: provided_trait_methods
839                .into_iter()
840                .map(|x| x.to_string())
841                .collect(),
842            trait_: trait_.into_json(renderer),
843            for_: for_.into_json(renderer),
844            items: renderer.ids(items),
845            is_negative,
846            is_synthetic,
847            blanket_impl: blanket_impl.map(|x| x.into_json(renderer)),
848        }
849    }
850}
851
852pub(crate) fn from_clean_function(
853    clean::Function { decl, generics }: &clean::Function,
854    has_body: bool,
855    default_unstable: Option<Box<ProvidedDefaultUnstable>>,
856    header: rustc_hir::FnHeader,
857    renderer: &JsonRenderer<'_>,
858) -> Function {
859    Function {
860        sig: decl.into_json(renderer),
861        generics: generics.into_json(renderer),
862        header: header.into_json(renderer),
863        has_body,
864        default_unstable,
865    }
866}
867
868impl FromClean<clean::Enum> for Enum {
869    fn from_clean(enum_: &clean::Enum, renderer: &JsonRenderer<'_>) -> Self {
870        let has_stripped_variants = enum_.has_stripped_entries();
871        let clean::Enum { variants, generics } = enum_;
872        Enum {
873            generics: generics.into_json(renderer),
874            has_stripped_variants,
875            variants: renderer.ids(&variants.as_slice().raw),
876            impls: Vec::new(), // Added in JsonRenderer::item
877        }
878    }
879}
880
881impl FromClean<clean::Variant> for Variant {
882    fn from_clean(variant: &clean::Variant, renderer: &JsonRenderer<'_>) -> Self {
883        use clean::VariantKind::*;
884
885        let discriminant = variant.discriminant.into_json(renderer);
886
887        let kind = match &variant.kind {
888            CLike => VariantKind::Plain,
889            Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)),
890            Struct(s) => VariantKind::Struct {
891                has_stripped_fields: s.has_stripped_entries(),
892                fields: renderer.ids(&s.fields),
893            },
894        };
895
896        Variant { kind, discriminant }
897    }
898}
899
900impl FromClean<clean::Discriminant> for Discriminant {
901    fn from_clean(disr: &clean::Discriminant, renderer: &JsonRenderer<'_>) -> Self {
902        let tcx = renderer.tcx;
903        Discriminant {
904            // expr is only none if going through the inlining path, which gets
905            // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
906            // the expr is always some.
907            expr: disr.expr(tcx).unwrap(),
908            value: disr.value(tcx, false),
909        }
910    }
911}
912
913impl FromClean<clean::Import> for Use {
914    fn from_clean(import: &clean::Import, renderer: &JsonRenderer<'_>) -> Self {
915        use clean::ImportKind::*;
916        let (name, is_glob) = match import.kind {
917            Simple(s) => (s.to_string(), false),
918            Glob => (import.source.path.last_opt().unwrap_or(sym::asterisk).to_string(), true),
919        };
920        Use {
921            source: import.source.path.whole_name(),
922            name,
923            id: import.source.did.map(ItemId::from).map(|i| renderer.id_from_item_default(i)),
924            is_glob,
925        }
926    }
927}
928
929impl FromClean<clean::ProcMacro> for ProcMacro {
930    fn from_clean(mac: &clean::ProcMacro, renderer: &JsonRenderer<'_>) -> Self {
931        ProcMacro {
932            kind: mac.kind.into_json(renderer),
933            helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
934        }
935    }
936}
937
938impl FromClean<rustc_span::hygiene::MacroKind> for MacroKind {
939    fn from_clean(kind: &rustc_span::hygiene::MacroKind, _renderer: &JsonRenderer<'_>) -> Self {
940        use rustc_span::hygiene::MacroKind::*;
941        match kind {
942            Bang => MacroKind::Bang,
943            Attr => MacroKind::Attr,
944            Derive => MacroKind::Derive,
945        }
946    }
947}
948
949impl FromClean<clean::TypeAlias> for TypeAlias {
950    fn from_clean(type_alias: &clean::TypeAlias, renderer: &JsonRenderer<'_>) -> Self {
951        let clean::TypeAlias { type_, generics, item_type: _, inner_type: _ } = type_alias;
952        TypeAlias { type_: type_.into_json(renderer), generics: generics.into_json(renderer) }
953    }
954}
955
956fn from_clean_static(
957    stat: &clean::Static,
958    safety: rustc_hir::Safety,
959    renderer: &JsonRenderer<'_>,
960) -> Static {
961    let tcx = renderer.tcx;
962    Static {
963        type_: stat.type_.as_ref().into_json(renderer),
964        is_mutable: stat.mutability == ast::Mutability::Mut,
965        is_unsafe: safety.is_unsafe(),
966        expr: stat
967            .expr
968            .map(|e| rendered_const(tcx, tcx.hir_body(e), tcx.hir_body_owner_def_id(e)))
969            .unwrap_or_default(),
970    }
971}
972
973impl FromClean<clean::TraitAlias> for TraitAlias {
974    fn from_clean(alias: &clean::TraitAlias, renderer: &JsonRenderer<'_>) -> Self {
975        TraitAlias {
976            generics: alias.generics.into_json(renderer),
977            params: alias.bounds.into_json(renderer),
978        }
979    }
980}
981
982impl FromClean<ItemType> for ItemKind {
983    fn from_clean(kind: &ItemType, _renderer: &JsonRenderer<'_>) -> Self {
984        use ItemType::*;
985        match kind {
986            Module => ItemKind::Module,
987            ExternCrate => ItemKind::ExternCrate,
988            Import => ItemKind::Use,
989            Struct => ItemKind::Struct,
990            Union => ItemKind::Union,
991            Enum => ItemKind::Enum,
992            Function | TyMethod | Method => ItemKind::Function,
993            TypeAlias => ItemKind::TypeAlias,
994            Static => ItemKind::Static,
995            Constant => ItemKind::Constant,
996            Trait => ItemKind::Trait,
997            Impl => ItemKind::Impl,
998            StructField => ItemKind::StructField,
999            Variant => ItemKind::Variant,
1000            Macro => ItemKind::Macro,
1001            Primitive => ItemKind::Primitive,
1002            AssocConst => ItemKind::AssocConst,
1003            AssocType => ItemKind::AssocType,
1004            ForeignType => ItemKind::ExternType,
1005            Keyword => ItemKind::Keyword,
1006            Attribute => ItemKind::Attribute,
1007            TraitAlias => ItemKind::TraitAlias,
1008            ProcAttribute | DeclMacroAttribute => ItemKind::ProcAttribute,
1009            ProcDerive | DeclMacroDerive => ItemKind::ProcDerive,
1010        }
1011    }
1012}
1013
1014fn default_body_stability_for_def_id(
1015    tcx: TyCtxt<'_>,
1016    def_id: DefId,
1017) -> Option<hir::DefaultBodyStability> {
1018    let stability = tcx.lookup_default_body_stability(def_id)?;
1019    match stability.level {
1020        hir::StabilityLevel::Unstable { .. } => Some(stability),
1021        hir::StabilityLevel::Stable { .. } => None,
1022    }
1023}
1024
1025fn const_stability_for_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::ConstStability> {
1026    if !tcx.is_conditionally_const(def_id) {
1027        // The item cannot be conditionally-const. No const stability here.
1028        //
1029        // This includes associated consts, which are an interesting exception
1030        // to the general rule that items inside `const impl` and `const trait` carry
1031        // the const-stability of that block. Associated consts are already const, always.
1032        return None;
1033    }
1034
1035    let const_stability = tcx.lookup_const_stability(def_id)?;
1036    if find_attr!(tcx, def_id, RustcConstStability { .. }) {
1037        // Direct const-stability attribute on the item itself. Return it directly.
1038        return Some(const_stability);
1039    }
1040
1041    if const_stability.is_const_stable() {
1042        // Items that are const-stable without an explicit attribute on their own item
1043        // must be associated items inside `const trait` or `const impl`.
1044        // We don't want to duplicate their parent item's const-stability attribute.
1045        return None;
1046    }
1047
1048    // We're dealing with an item that is const-unstable,
1049    // but doesn't have an explicit const-stability attribute on it.
1050    //
1051    // Today, this means one of two cases:
1052    // - The item is enclosed within a `#[rustc_const_unstable]` block,
1053    //   like a `const trait` or `const impl`, in which case our query propagated the parent's
1054    //   const-instability info. This const-instability is desirable to place into JSON
1055    //   because *only some* associated items inside such a block are const-unstable.
1056    //   Associated consts are the exception, and were handled earlier.
1057    // - The item is `#[unstable]` which implies it's const-unstable under the same feature,
1058    //   in which case we don't want to duplicate the existing stability attribute
1059    //   which would already appear in an adjacent field in the JSON anyway.
1060    if let Some(parent_def_id) = tcx.opt_parent(def_id)
1061        && matches!(tcx.def_kind(parent_def_id), DefKind::Trait | DefKind::Impl { .. })
1062        && tcx.lookup_const_stability(parent_def_id) == Some(const_stability)
1063    {
1064        Some(const_stability)
1065    } else {
1066        std::debug_assert_matches!(
1067            tcx.lookup_stability(def_id).map(|s| s.level),
1068            Some(hir::StabilityLevel::Unstable { .. })
1069        );
1070        None
1071    }
1072}
1073
1074/// Maybe convert a attribute from hir to json.
1075///
1076/// Returns `None` if the attribute shouldn't be in the output.
1077fn maybe_from_hir_attr(attr: &hir::Attribute, item_id: ItemId, tcx: TyCtxt<'_>) -> Vec<Attribute> {
1078    use attrs::AttributeKind as AK;
1079
1080    let kind = match attr {
1081        hir::Attribute::Parsed(kind) => kind,
1082
1083        hir::Attribute::Unparsed(_) => {
1084            // FIXME: We should handle `#[doc(hidden)]`.
1085            return vec![other_attr(tcx, attr)];
1086        }
1087    };
1088
1089    vec![match kind {
1090        AK::Deprecated { .. } => return Vec::new(), // Handled separately into Item::deprecation.
1091        AK::Stability { .. } => return Vec::new(),  // Handled separately into Item::stability
1092        AK::RustcConstStability { .. } => return Vec::new(), // Handled separately into Item::const_stability.
1093        AK::RustcBodyStability { .. } => return Vec::new(), // Handled separately by `default_unstable`.
1094
1095        AK::DocComment { .. } => unreachable!("doc comments stripped out earlier"),
1096
1097        AK::MacroExport { .. } => Attribute::MacroExport,
1098        AK::MustUse { reason, span: _ } => {
1099            Attribute::MustUse { reason: reason.map(|s| s.to_string()) }
1100        }
1101        AK::Repr { .. } => repr_attr(
1102            tcx,
1103            item_id.as_def_id().expect("all items that could have #[repr] have a DefId"),
1104        ),
1105        AK::ExportName { name, span: _ } => Attribute::ExportName(name.to_string()),
1106        AK::LinkSection { name } => Attribute::LinkSection(name.to_string()),
1107        AK::TargetFeature { features, .. } => Attribute::TargetFeature {
1108            enable: features.iter().map(|(feat, _span)| feat.to_string()).collect(),
1109        },
1110
1111        AK::NoMangle(_) => Attribute::NoMangle,
1112        AK::NonExhaustive(_) => Attribute::NonExhaustive,
1113        AK::AutomaticallyDerived => Attribute::AutomaticallyDerived,
1114        AK::Doc(d) => {
1115            fn toggle_attr(ret: &mut Vec<Attribute>, name: &str, v: &Option<rustc_span::Span>) {
1116                if v.is_some() {
1117                    ret.push(Attribute::Other(format!("#[doc({name})]")));
1118                }
1119            }
1120
1121            fn name_value_attr(
1122                ret: &mut Vec<Attribute>,
1123                name: &str,
1124                v: &Option<(Symbol, rustc_span::Span)>,
1125            ) {
1126                if let Some((v, _)) = v {
1127                    // We use `as_str` and debug display to have characters escaped and `"`
1128                    // characters surrounding the string.
1129                    ret.push(Attribute::Other(format!("#[doc({name} = {:?})]", v.as_str())));
1130                }
1131            }
1132
1133            let DocAttribute {
1134                first_span: _,
1135                aliases,
1136                hidden,
1137                inline,
1138                cfg,
1139                auto_cfg,
1140                auto_cfg_change,
1141                fake_variadic,
1142                keyword,
1143                attribute,
1144                masked,
1145                notable_trait,
1146                search_unbox,
1147                html_favicon_url,
1148                html_logo_url,
1149                html_playground_url,
1150                html_root_url,
1151                html_no_source,
1152                issue_tracker_base_url,
1153                rust_logo,
1154                test_attrs,
1155                no_crate_inject,
1156            } = &**d;
1157
1158            let mut ret = Vec::new();
1159
1160            for (alias, _) in aliases {
1161                // We use `as_str` and debug display to have characters escaped and `"` characters
1162                // surrounding the string.
1163                ret.push(Attribute::Other(format!("#[doc(alias = {:?})]", alias.as_str())));
1164            }
1165            toggle_attr(&mut ret, "hidden", hidden);
1166            if let Some(inline) = inline.first() {
1167                ret.push(Attribute::Other(format!(
1168                    "#[doc({})]",
1169                    match inline.0 {
1170                        DocInline::Inline => "inline",
1171                        DocInline::NoInline => "no_inline",
1172                    }
1173                )));
1174            }
1175            for sub_cfg in cfg {
1176                ret.push(Attribute::Other(format!("#[doc(cfg({sub_cfg}))]")));
1177            }
1178            if !auto_cfg.is_empty() {
1179                let mut out = format!("#[doc(auto_cfg(");
1180                for (index, (auto_cfg, _)) in auto_cfg.iter().enumerate() {
1181                    let kind = match auto_cfg.kind {
1182                        HideOrShow::Hide => "hide",
1183                        HideOrShow::Show => "show",
1184                    };
1185                    if index > 0 {
1186                        out.push_str(", ");
1187                    }
1188                    out.push_str(&format!("{kind}("));
1189                    for (name, cfgs) in &auto_cfg.values {
1190                        out.push_str(&format!("{name}, values("));
1191                        match cfgs {
1192                            DocCfgHideShow::Any(_) => {
1193                                out.push_str("any()");
1194                            }
1195                            DocCfgHideShow::List(values) => {
1196                                for (pos, value) in values.iter().enumerate() {
1197                                    let separator = if pos > 0 { ", " } else { "" };
1198                                    if let Some(value) = &value.value {
1199                                        // We use `as_str` and debug display to have characters escaped
1200                                        // and `"` characters surrounding the string.
1201                                        out.push_str(&format!("{separator}{:?}", value.as_str()));
1202                                    } else {
1203                                        out.push_str(&format!("{separator}none()"));
1204                                    }
1205                                }
1206                            }
1207                        }
1208                        out.push_str(")");
1209                    }
1210                    out.push(')');
1211                }
1212                out.push_str("))]");
1213                ret.push(Attribute::Other(out));
1214            }
1215            for (change, _) in auto_cfg_change {
1216                ret.push(Attribute::Other(format!("#[doc(auto_cfg = {change})]")));
1217            }
1218            toggle_attr(&mut ret, "fake_variadic", fake_variadic);
1219            name_value_attr(&mut ret, "keyword", keyword);
1220            name_value_attr(&mut ret, "attribute", attribute);
1221            toggle_attr(&mut ret, "masked", masked);
1222            toggle_attr(&mut ret, "notable_trait", notable_trait);
1223            toggle_attr(&mut ret, "search_unbox", search_unbox);
1224            name_value_attr(&mut ret, "html_favicon_url", html_favicon_url);
1225            name_value_attr(&mut ret, "html_logo_url", html_logo_url);
1226            name_value_attr(&mut ret, "html_playground_url", html_playground_url);
1227            name_value_attr(&mut ret, "html_root_url", html_root_url);
1228            toggle_attr(&mut ret, "html_no_source", html_no_source);
1229            name_value_attr(&mut ret, "issue_tracker_base_url", issue_tracker_base_url);
1230            toggle_attr(&mut ret, "rust_logo", rust_logo);
1231            let source_map = tcx.sess.source_map();
1232            for attr_span in test_attrs {
1233                // FIXME: This is ugly, remove when `test_attrs` has been ported to new attribute API.
1234                if let Ok(snippet) = source_map.span_to_snippet(*attr_span) {
1235                    ret.push(Attribute::Other(format!("#[doc(test(attr({snippet})))]")));
1236                }
1237            }
1238            toggle_attr(&mut ret, "test(no_crate_inject)", no_crate_inject);
1239            return ret;
1240        }
1241
1242        _ => other_attr(tcx, attr),
1243    }]
1244}
1245
1246fn other_attr(tcx: TyCtxt<'_>, attr: &hir::Attribute) -> Attribute {
1247    let mut s = rustc_hir_pretty::attribute_to_string(
1248        &(&tcx as &dyn intravisit::HirTyCtxt<'_>) as &dyn PpAnn,
1249        attr,
1250    );
1251    assert_eq!(s.pop(), Some('\n'));
1252    Attribute::Other(s)
1253}
1254
1255fn repr_attr(tcx: TyCtxt<'_>, def_id: DefId) -> Attribute {
1256    let repr = tcx.adt_def(def_id).repr();
1257
1258    let kind = if repr.c() {
1259        ReprKind::C
1260    } else if repr.transparent() {
1261        ReprKind::Transparent
1262    } else if repr.simd() {
1263        ReprKind::Simd
1264    } else {
1265        ReprKind::Rust
1266    };
1267
1268    let align = repr.align.map(|a| a.bytes());
1269    let packed = repr.pack.map(|p| p.bytes());
1270    let int = repr.int.map(format_integer_type);
1271
1272    Attribute::Repr(AttributeRepr { kind, align, packed, int })
1273}
1274
1275fn format_integer_type(it: rustc_abi::IntegerType) -> String {
1276    use rustc_abi::Integer::*;
1277    use rustc_abi::IntegerType::*;
1278    match it {
1279        Pointer(true) => "isize",
1280        Pointer(false) => "usize",
1281        Fixed(I8, true) => "i8",
1282        Fixed(I8, false) => "u8",
1283        Fixed(I16, true) => "i16",
1284        Fixed(I16, false) => "u16",
1285        Fixed(I32, true) => "i32",
1286        Fixed(I32, false) => "u32",
1287        Fixed(I64, true) => "i64",
1288        Fixed(I64, false) => "u64",
1289        Fixed(I128, true) => "i128",
1290        Fixed(I128, false) => "u128",
1291    }
1292    .to_owned()
1293}
1294
1295pub(super) fn target(sess: &rustc_session::Session) -> Target {
1296    // Build a set of which features are enabled on this target
1297    let globally_enabled_features: FxHashSet<&str> =
1298        sess.internal_target_features.iter().map(|name| name.as_str()).collect();
1299
1300    // Build a map of target feature stability by feature name
1301    use rustc_target::target_features::Stability;
1302    let feature_stability: FxHashMap<&str, Stability> = sess
1303        .target
1304        .rust_target_features()
1305        .iter()
1306        .copied()
1307        .map(|(name, stability, _)| (name, stability))
1308        .collect();
1309
1310    Target {
1311        triple: sess.opts.target_triple.tuple().into(),
1312        target_features: sess
1313            .target
1314            .rust_target_features()
1315            .iter()
1316            .copied()
1317            .filter(|(_, stability, _)| {
1318                // Describe only target features which the user can toggle
1319                stability.toggle_allowed().is_ok()
1320            })
1321            .map(|(name, stability, implied_features)| {
1322                TargetFeature {
1323                    name: name.into(),
1324                    unstable_feature_gate: match stability {
1325                        Stability::Unstable(feature_gate) => Some(feature_gate.as_str().into()),
1326                        _ => None,
1327                    },
1328                    implies_features: implied_features
1329                        .iter()
1330                        .copied()
1331                        .filter(|name| {
1332                            // Imply only target features which the user can toggle
1333                            feature_stability
1334                                .get(name)
1335                                .map(|stability| stability.toggle_allowed().is_ok())
1336                                .unwrap_or(false)
1337                        })
1338                        .map(String::from)
1339                        .collect(),
1340                    globally_enabled: globally_enabled_features.contains(name),
1341                }
1342            })
1343            .collect(),
1344    }
1345}