Skip to main content

rustdoc/json/
conversions.rs

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