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