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