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