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