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