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,
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        }
695    }
696}
697
698impl FromClean<clean::Path> for Path {
699    fn from_clean(path: &clean::Path, renderer: &JsonRenderer<'_>) -> Self {
700        Path {
701            path: path.whole_name(),
702            id: renderer.id_from_item_default(path.def_id().into()),
703            args: {
704                if let Some((final_seg, rest_segs)) = path.segments.split_last() {
705                    // In general, `clean::Path` can hold things like
706                    // `std::vec::Vec::<u32>::new`, where generic args appear
707                    // in a middle segment. But for the places where `Path` is
708                    // used by rustdoc-json-types, generic args can only be
709                    // used in the final segment, e.g. `std::vec::Vec<u32>`. So
710                    // check that the non-final segments have no generic args.
711                    assert!(rest_segs.iter().all(|seg| seg.args.is_empty()));
712                    final_seg.args.into_json(renderer)
713                } else {
714                    None // no generics on any segments because there are no segments
715                }
716            },
717        }
718    }
719}
720
721impl FromClean<clean::QPathData> for Type {
722    fn from_clean(qpath: &clean::QPathData, renderer: &JsonRenderer<'_>) -> Self {
723        let clean::QPathData { assoc, self_type, should_fully_qualify: _, trait_ } = qpath;
724
725        Self::QualifiedPath {
726            name: assoc.name.to_string(),
727            args: assoc.args.into_json(renderer),
728            self_type: Box::new(self_type.into_json(renderer)),
729            trait_: trait_.into_json(renderer),
730        }
731    }
732}
733
734impl FromClean<clean::Term> for Term {
735    fn from_clean(term: &clean::Term, renderer: &JsonRenderer<'_>) -> Self {
736        match term {
737            clean::Term::Type(ty) => Term::Type(ty.into_json(renderer)),
738            clean::Term::Constant(c) => Term::Constant(c.into_json(renderer)),
739        }
740    }
741}
742
743impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
744    fn from_clean(bare_decl: &clean::BareFunctionDecl, renderer: &JsonRenderer<'_>) -> Self {
745        let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
746        FunctionPointer {
747            header: FunctionHeader {
748                is_unsafe: safety.is_unsafe(),
749                is_const: false,
750                is_async: false,
751                abi: abi.into_json(renderer),
752            },
753            generic_params: generic_params.into_json(renderer),
754            sig: decl.into_json(renderer),
755        }
756    }
757}
758
759impl FromClean<clean::FnDecl> for FunctionSignature {
760    fn from_clean(decl: &clean::FnDecl, renderer: &JsonRenderer<'_>) -> Self {
761        let clean::FnDecl { inputs, output, c_variadic } = decl;
762        FunctionSignature {
763            inputs: inputs
764                .iter()
765                .map(|param| {
766                    // `_` is the most sensible name for missing param names.
767                    let name = param.name.unwrap_or(kw::Underscore).to_string();
768                    let type_ = param.type_.into_json(renderer);
769                    (name, type_)
770                })
771                .collect(),
772            output: if output.is_unit() { None } else { Some(output.into_json(renderer)) },
773            is_c_variadic: *c_variadic,
774        }
775    }
776}
777
778impl FromClean<clean::Trait> for Trait {
779    fn from_clean(trait_: &clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
780        let tcx = renderer.tcx;
781        let is_auto = trait_.is_auto(tcx);
782        let is_unsafe = trait_.safety(tcx).is_unsafe();
783        let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
784        let clean::Trait { items, generics, bounds, .. } = trait_;
785        Trait {
786            is_auto,
787            is_unsafe,
788            is_dyn_compatible,
789            items: renderer.ids(items),
790            generics: generics.into_json(renderer),
791            bounds: bounds.into_json(renderer),
792            implementations: Vec::new(), // Added in JsonRenderer::item
793        }
794    }
795}
796
797impl FromClean<clean::PolyTrait> for PolyTrait {
798    fn from_clean(
799        clean::PolyTrait { trait_, generic_params }: &clean::PolyTrait,
800        renderer: &JsonRenderer<'_>,
801    ) -> Self {
802        PolyTrait {
803            trait_: trait_.into_json(renderer),
804            generic_params: generic_params.into_json(renderer),
805        }
806    }
807}
808
809impl FromClean<clean::Impl> for Impl {
810    fn from_clean(impl_: &clean::Impl, renderer: &JsonRenderer<'_>) -> Self {
811        let provided_trait_methods = impl_.provided_trait_methods(renderer.tcx);
812        let clean::Impl { safety, generics, trait_, for_, items, polarity, kind, is_deprecated: _ } =
813            impl_;
814        // FIXME: use something like ImplKind in JSON?
815        let (is_synthetic, blanket_impl) = match kind {
816            clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
817            clean::ImplKind::Auto => (true, None),
818            clean::ImplKind::Blanket(ty) => (false, Some(ty)),
819        };
820        let is_negative = match polarity {
821            ty::ImplPolarity::Positive => false,
822            ty::ImplPolarity::Negative => true,
823        };
824        Impl {
825            is_unsafe: safety.is_unsafe(),
826            generics: generics.into_json(renderer),
827            provided_trait_methods: provided_trait_methods
828                .into_iter()
829                .map(|x| x.to_string())
830                .collect(),
831            trait_: trait_.into_json(renderer),
832            for_: for_.into_json(renderer),
833            items: renderer.ids(items),
834            is_negative,
835            is_synthetic,
836            blanket_impl: blanket_impl.map(|x| x.into_json(renderer)),
837        }
838    }
839}
840
841impl FromClean<clean::Enum> for Enum {
842    fn from_clean(enum_: &clean::Enum, renderer: &JsonRenderer<'_>) -> Self {
843        let has_stripped_variants = enum_.has_stripped_entries();
844        let clean::Enum { variants, generics } = enum_;
845        Enum {
846            generics: generics.into_json(renderer),
847            has_stripped_variants,
848            variants: renderer.ids(&variants.as_slice().raw),
849            impls: Vec::new(), // Added in JsonRenderer::item
850        }
851    }
852}
853
854impl FromClean<clean::Variant> for Variant {
855    fn from_clean(variant: &clean::Variant, renderer: &JsonRenderer<'_>) -> Self {
856        use clean::VariantKind::*;
857
858        let discriminant = variant.discriminant.into_json(renderer);
859
860        let kind = match &variant.kind {
861            CLike => VariantKind::Plain,
862            Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)),
863            Struct(s) => VariantKind::Struct {
864                has_stripped_fields: s.has_stripped_entries(),
865                fields: renderer.ids(&s.fields),
866            },
867        };
868
869        Variant { kind, discriminant }
870    }
871}
872
873impl FromClean<clean::Discriminant> for Discriminant {
874    fn from_clean(disr: &clean::Discriminant, renderer: &JsonRenderer<'_>) -> Self {
875        let tcx = renderer.tcx;
876        Discriminant {
877            // expr is only none if going through the inlining path, which gets
878            // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
879            // the expr is always some.
880            expr: disr.expr(tcx).unwrap(),
881            value: disr.value(tcx, false),
882        }
883    }
884}
885
886impl FromClean<clean::Import> for Use {
887    fn from_clean(import: &clean::Import, renderer: &JsonRenderer<'_>) -> Self {
888        use clean::ImportKind::*;
889        let (name, is_glob) = match import.kind {
890            Simple(s) => (s.to_string(), false),
891            Glob => (import.source.path.last_opt().unwrap_or(sym::asterisk).to_string(), true),
892        };
893        Use {
894            source: import.source.path.whole_name(),
895            name,
896            id: import.source.did.map(ItemId::from).map(|i| renderer.id_from_item_default(i)),
897            is_glob,
898        }
899    }
900}
901
902impl FromClean<clean::ProcMacro> for ProcMacro {
903    fn from_clean(mac: &clean::ProcMacro, renderer: &JsonRenderer<'_>) -> Self {
904        ProcMacro {
905            kind: mac.kind.into_json(renderer),
906            helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
907        }
908    }
909}
910
911impl FromClean<rustc_span::hygiene::MacroKind> for MacroKind {
912    fn from_clean(kind: &rustc_span::hygiene::MacroKind, _renderer: &JsonRenderer<'_>) -> Self {
913        use rustc_span::hygiene::MacroKind::*;
914        match kind {
915            Bang => MacroKind::Bang,
916            Attr => MacroKind::Attr,
917            Derive => MacroKind::Derive,
918        }
919    }
920}
921
922impl FromClean<clean::TypeAlias> for TypeAlias {
923    fn from_clean(type_alias: &clean::TypeAlias, renderer: &JsonRenderer<'_>) -> Self {
924        let clean::TypeAlias { type_, generics, inner_type: _ } = type_alias;
925        TypeAlias { type_: type_.into_json(renderer), generics: generics.into_json(renderer) }
926    }
927}
928
929fn from_clean_static(
930    stat: &clean::Static,
931    safety: rustc_hir::Safety,
932    renderer: &JsonRenderer<'_>,
933) -> Static {
934    let tcx = renderer.tcx;
935    Static {
936        type_: stat.type_.as_ref().into_json(renderer),
937        is_mutable: stat.mutability == ast::Mutability::Mut,
938        is_unsafe: safety.is_unsafe(),
939        expr: stat
940            .expr
941            .map(|e| rendered_const(tcx, tcx.hir_body(e), tcx.hir_body_owner_def_id(e)))
942            .unwrap_or_default(),
943    }
944}
945
946impl FromClean<clean::TraitAlias> for TraitAlias {
947    fn from_clean(alias: &clean::TraitAlias, renderer: &JsonRenderer<'_>) -> Self {
948        TraitAlias {
949            generics: alias.generics.into_json(renderer),
950            params: alias.bounds.into_json(renderer),
951        }
952    }
953}
954
955impl FromClean<ItemType> for ItemKind {
956    fn from_clean(kind: &ItemType, _renderer: &JsonRenderer<'_>) -> Self {
957        use ItemType::*;
958        match kind {
959            Module => ItemKind::Module,
960            ExternCrate => ItemKind::ExternCrate,
961            Import => ItemKind::Use,
962            Struct => ItemKind::Struct,
963            Union => ItemKind::Union,
964            Enum => ItemKind::Enum,
965            Function | AssocFnWithoutBody | AssocFnWithBody => ItemKind::Function,
966            TypeAlias => ItemKind::TypeAlias,
967            Static => ItemKind::Static,
968            Constant => ItemKind::Constant,
969            Trait => ItemKind::Trait,
970            Impl => ItemKind::Impl,
971            StructField => ItemKind::StructField,
972            Variant => ItemKind::Variant,
973            Macro => ItemKind::Macro,
974            Primitive => ItemKind::Primitive,
975            AssocConst => ItemKind::AssocConst,
976            AssocType => ItemKind::AssocType,
977            ForeignType => ItemKind::ExternType,
978            Keyword => ItemKind::Keyword,
979            Attribute => ItemKind::Attribute,
980            TraitAlias => ItemKind::TraitAlias,
981            ProcAttribute | DeclMacroAttribute => ItemKind::ProcAttribute,
982            ProcDerive | DeclMacroDerive => ItemKind::ProcDerive,
983        }
984    }
985}
986
987fn default_body_stability_for_def_id(
988    tcx: TyCtxt<'_>,
989    def_id: DefId,
990) -> Option<rustc_attr_ir::DefaultBodyStability> {
991    let stability = tcx.lookup_default_body_stability(def_id)?;
992    match stability.level {
993        rustc_attr_ir::StabilityLevel::Unstable { .. } => Some(stability),
994        rustc_attr_ir::StabilityLevel::Stable { .. } => None,
995    }
996}
997
998fn const_stability_for_def_id(
999    tcx: TyCtxt<'_>,
1000    def_id: DefId,
1001) -> Option<rustc_attr_ir::ConstStability> {
1002    if !tcx.is_conditionally_const(def_id) {
1003        // The item cannot be conditionally-const. No const stability here.
1004        //
1005        // This includes associated consts, which are an interesting exception
1006        // to the general rule that items inside `const impl` and `const trait` carry
1007        // the const-stability of that block. Associated consts are already const, always.
1008        return None;
1009    }
1010
1011    let const_stability = tcx.lookup_const_stability(def_id)?;
1012    if find_attr!(tcx, def_id, RustcConstStability { .. }) {
1013        // Direct const-stability attribute on the item itself. Return it directly.
1014        return Some(const_stability);
1015    }
1016
1017    if const_stability.is_const_stable() {
1018        // Items that are const-stable without an explicit attribute on their own item
1019        // must be associated items inside `const trait` or `const impl`.
1020        // We don't want to duplicate their parent item's const-stability attribute.
1021        return None;
1022    }
1023
1024    // We're dealing with an item that is const-unstable,
1025    // but doesn't have an explicit const-stability attribute on it.
1026    //
1027    // Today, this means one of two cases:
1028    // - The item is enclosed within a `#[rustc_const_unstable]` block,
1029    //   like a `const trait` or `const impl`, in which case our query propagated the parent's
1030    //   const-instability info. This const-instability is desirable to place into JSON
1031    //   because *only some* associated items inside such a block are const-unstable.
1032    //   Associated consts are the exception, and were handled earlier.
1033    // - The item is `#[unstable]` which implies it's const-unstable under the same feature,
1034    //   in which case we don't want to duplicate the existing stability attribute
1035    //   which would already appear in an adjacent field in the JSON anyway.
1036    if let Some(parent_def_id) = tcx.opt_parent(def_id)
1037        && matches!(tcx.def_kind(parent_def_id), DefKind::Trait | DefKind::Impl { .. })
1038        && tcx.lookup_const_stability(parent_def_id) == Some(const_stability)
1039    {
1040        Some(const_stability)
1041    } else {
1042        std::debug_assert_matches!(
1043            tcx.lookup_stability(def_id).map(|s| s.level),
1044            Some(rustc_attr_ir::StabilityLevel::Unstable { .. })
1045        );
1046        None
1047    }
1048}
1049
1050/// Maybe convert a attribute from hir to json.
1051///
1052/// Returns `None` if the attribute shouldn't be in the output.
1053fn maybe_from_hir_attr(
1054    attr: &rustc_attr_ir::Attribute,
1055    item_id: ItemId,
1056    tcx: TyCtxt<'_>,
1057) -> Vec<Attribute> {
1058    use rustc_attr_ir::AttributeKind as AK;
1059
1060    let kind = match attr {
1061        rustc_attr_ir::Attribute::Parsed(kind) => kind,
1062
1063        rustc_attr_ir::Attribute::Tool(_) | rustc_attr_ir::Attribute::DeriveHelper(_) => {
1064            // FIXME: We should handle `#[doc(hidden)]`.
1065            return vec![other_attr(tcx, attr)];
1066        }
1067    };
1068
1069    vec![match kind {
1070        AK::Deprecated { .. } => return Vec::new(), // Handled separately into Item::deprecation.
1071        AK::Stability { .. } => return Vec::new(),  // Handled separately into Item::stability
1072        AK::RustcConstStability { .. } => return Vec::new(), // Handled separately into Item::const_stability.
1073        AK::RustcBodyStability { .. } => return Vec::new(), // Handled separately by `default_unstable`.
1074
1075        AK::DocComment { .. } => unreachable!("doc comments stripped out earlier"),
1076
1077        AK::MacroExport { .. } => Attribute::MacroExport,
1078        AK::MustUse { reason, span: _ } => {
1079            Attribute::MustUse { reason: reason.map(|s| s.to_string()) }
1080        }
1081        AK::Repr { .. } => repr_attr(
1082            tcx,
1083            item_id.as_def_id().expect("all items that could have #[repr] have a DefId"),
1084        ),
1085        AK::ExportName { name, span: _ } => Attribute::ExportName(name.to_string()),
1086        AK::LinkSection { name } => Attribute::LinkSection(name.to_string()),
1087        AK::TargetFeature { features, .. } => Attribute::TargetFeature {
1088            enable: features.iter().map(|(feat, _span)| feat.to_string()).collect(),
1089        },
1090
1091        AK::NoMangle(_) => Attribute::NoMangle,
1092        AK::NonExhaustive(_) => Attribute::NonExhaustive,
1093        AK::AutomaticallyDerived => Attribute::AutomaticallyDerived,
1094        AK::Doc(d) => {
1095            fn toggle_attr(ret: &mut Vec<Attribute>, name: &str, v: &Option<rustc_span::Span>) {
1096                if v.is_some() {
1097                    ret.push(Attribute::Other(format!("#[doc({name})]")));
1098                }
1099            }
1100
1101            fn name_value_attr(
1102                ret: &mut Vec<Attribute>,
1103                name: &str,
1104                v: &Option<(Symbol, rustc_span::Span)>,
1105            ) {
1106                if let Some((v, _)) = v {
1107                    // We use `as_str` and debug display to have characters escaped and `"`
1108                    // characters surrounding the string.
1109                    ret.push(Attribute::Other(format!("#[doc({name} = {:?})]", v.as_str())));
1110                }
1111            }
1112
1113            let DocAttribute {
1114                first_span: _,
1115                aliases,
1116                hidden,
1117                inline,
1118                cfg,
1119                auto_cfg,
1120                auto_cfg_change,
1121                fake_variadic,
1122                keyword,
1123                attribute,
1124                masked,
1125                notable_trait,
1126                search_unbox,
1127                html_favicon_url,
1128                html_logo_url,
1129                html_playground_url,
1130                html_root_url,
1131                html_no_source,
1132                issue_tracker_base_url,
1133                rust_logo,
1134                test_attrs,
1135                no_crate_inject,
1136            } = &**d;
1137
1138            let mut ret = Vec::new();
1139
1140            for (alias, _) in aliases {
1141                // We use `as_str` and debug display to have characters escaped and `"` characters
1142                // surrounding the string.
1143                ret.push(Attribute::Other(format!("#[doc(alias = {:?})]", alias.as_str())));
1144            }
1145            toggle_attr(&mut ret, "hidden", hidden);
1146            if let Some(inline) = inline {
1147                ret.push(Attribute::Other(format!(
1148                    "#[doc({})]",
1149                    match inline.0 {
1150                        DocInline::Inline => "inline",
1151                        DocInline::NoInline => "no_inline",
1152                    }
1153                )));
1154            }
1155            for sub_cfg in cfg {
1156                ret.push(Attribute::Other(format!("#[doc(cfg({sub_cfg}))]")));
1157            }
1158            if !auto_cfg.is_empty() {
1159                let mut out = format!("#[doc(auto_cfg(");
1160                for (index, (auto_cfg, _)) in auto_cfg.iter().enumerate() {
1161                    let kind = match auto_cfg.kind {
1162                        HideOrShow::Hide => "hide",
1163                        HideOrShow::Show => "show",
1164                    };
1165                    if index > 0 {
1166                        out.push_str(", ");
1167                    }
1168                    out.push_str(&format!("{kind}("));
1169                    for (name, cfgs) in &auto_cfg.values {
1170                        out.push_str(&format!("{name}, values("));
1171                        match cfgs {
1172                            DocCfgHideShow::Any(_) => {
1173                                out.push_str("any()");
1174                            }
1175                            DocCfgHideShow::List(values) => {
1176                                for (pos, value) in values.iter().enumerate() {
1177                                    let separator = if pos > 0 { ", " } else { "" };
1178                                    if let Some(value) = &value.value {
1179                                        // We use `as_str` and debug display to have characters escaped
1180                                        // and `"` characters surrounding the string.
1181                                        out.push_str(&format!("{separator}{:?}", value.as_str()));
1182                                    } else {
1183                                        out.push_str(&format!("{separator}none()"));
1184                                    }
1185                                }
1186                            }
1187                        }
1188                        out.push_str(")");
1189                    }
1190                    out.push(')');
1191                }
1192                out.push_str("))]");
1193                ret.push(Attribute::Other(out));
1194            }
1195            for (change, _) in auto_cfg_change {
1196                ret.push(Attribute::Other(format!("#[doc(auto_cfg = {change})]")));
1197            }
1198            toggle_attr(&mut ret, "fake_variadic", fake_variadic);
1199            name_value_attr(&mut ret, "keyword", keyword);
1200            name_value_attr(&mut ret, "attribute", attribute);
1201            toggle_attr(&mut ret, "masked", masked);
1202            if let Some((notable_trait, _span)) = notable_trait {
1203                if let Some((color, _span)) = notable_trait {
1204                    ret.push(Attribute::Other(format!("#[doc(notable_trait = \"{color}\")]")));
1205                } else {
1206                    ret.push(Attribute::Other(format!("#[doc(notable_trait)]")));
1207                }
1208            }
1209            toggle_attr(&mut ret, "search_unbox", search_unbox);
1210            name_value_attr(&mut ret, "html_favicon_url", html_favicon_url);
1211            name_value_attr(&mut ret, "html_logo_url", html_logo_url);
1212            name_value_attr(&mut ret, "html_playground_url", html_playground_url);
1213            name_value_attr(&mut ret, "html_root_url", html_root_url);
1214            toggle_attr(&mut ret, "html_no_source", html_no_source);
1215            name_value_attr(&mut ret, "issue_tracker_base_url", issue_tracker_base_url);
1216            toggle_attr(&mut ret, "rust_logo", rust_logo);
1217            let source_map = tcx.sess.source_map();
1218            for attr_span in test_attrs {
1219                // FIXME: This is ugly, remove when `test_attrs` has been ported to new attribute API.
1220                if let Ok(snippet) = source_map.span_to_snippet(*attr_span) {
1221                    ret.push(Attribute::Other(format!("#[doc(test(attr({snippet})))]")));
1222                }
1223            }
1224            toggle_attr(&mut ret, "test(no_crate_inject)", no_crate_inject);
1225            return ret;
1226        }
1227
1228        _ => other_attr(tcx, attr),
1229    }]
1230}
1231
1232fn other_attr(tcx: TyCtxt<'_>, attr: &rustc_attr_ir::Attribute) -> Attribute {
1233    let mut s = rustc_hir_pretty::attribute_to_string(
1234        &(&tcx as &dyn intravisit::HirTyCtxt<'_>) as &dyn PpAnn,
1235        attr,
1236    );
1237    assert_eq!(s.pop(), Some('\n'));
1238    Attribute::Other(s)
1239}
1240
1241fn repr_attr(tcx: TyCtxt<'_>, def_id: DefId) -> Attribute {
1242    let repr = tcx.adt_def(def_id).repr();
1243
1244    let kind = if repr.c() {
1245        ReprKind::C
1246    } else if repr.transparent() {
1247        ReprKind::Transparent
1248    } else if repr.simd() {
1249        ReprKind::Simd
1250    } else {
1251        ReprKind::Rust
1252    };
1253
1254    let align = repr.align.map(|a| a.bytes());
1255    let packed = repr.pack.map(|p| p.bytes());
1256    let int = repr.int.map(format_integer_type);
1257
1258    Attribute::Repr(AttributeRepr { kind, align, packed, int })
1259}
1260
1261fn format_integer_type(it: rustc_abi::IntegerType) -> String {
1262    use rustc_abi::Integer::*;
1263    use rustc_abi::IntegerType::*;
1264    match it {
1265        Pointer(true) => "isize",
1266        Pointer(false) => "usize",
1267        Fixed(I8, true) => "i8",
1268        Fixed(I8, false) => "u8",
1269        Fixed(I16, true) => "i16",
1270        Fixed(I16, false) => "u16",
1271        Fixed(I32, true) => "i32",
1272        Fixed(I32, false) => "u32",
1273        Fixed(I64, true) => "i64",
1274        Fixed(I64, false) => "u64",
1275        Fixed(I128, true) => "i128",
1276        Fixed(I128, false) => "u128",
1277    }
1278    .to_owned()
1279}
1280
1281pub(super) fn target(sess: &rustc_session::Session) -> Target {
1282    // Build a set of which features are enabled on this target
1283    let globally_enabled_features: FxHashSet<&str> =
1284        sess.internal_target_features.iter().map(|name| name.as_str()).collect();
1285
1286    // Build a map of target feature stability by feature name
1287    use rustc_target::target_features::Stability;
1288    let feature_stability: FxHashMap<&str, Stability> = sess
1289        .target
1290        .rust_target_features()
1291        .iter()
1292        .copied()
1293        .map(|(name, stability, _)| (name, stability))
1294        .collect();
1295
1296    Target {
1297        triple: sess.opts.target_triple.tuple().into(),
1298        target_features: sess
1299            .target
1300            .rust_target_features()
1301            .iter()
1302            .copied()
1303            .filter(|(_, stability, _)| {
1304                // Describe only target features which the user can toggle
1305                stability.toggle_allowed().is_ok()
1306            })
1307            .map(|(name, stability, implied_features)| {
1308                TargetFeature {
1309                    name: name.into(),
1310                    unstable_feature_gate: match stability {
1311                        Stability::Unstable(feature_gate) => Some(feature_gate.as_str().into()),
1312                        _ => None,
1313                    },
1314                    implies_features: implied_features
1315                        .iter()
1316                        .copied()
1317                        .filter(|name| {
1318                            // Imply only target features which the user can toggle
1319                            feature_stability
1320                                .get(name)
1321                                .map(|stability| stability.toggle_allowed().is_ok())
1322                                .unwrap_or(false)
1323                        })
1324                        .map(String::from)
1325                        .collect(),
1326                    globally_enabled: globally_enabled_features.contains(name),
1327                }
1328            })
1329            .collect(),
1330    }
1331}