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        // All placeholder impl items should have been removed in the stripper passes.
357        PlaceholderImplItem => unreachable!(),
358    }
359}
360
361impl FromClean<clean::Struct> for Struct {
362    fn from_clean(struct_: &clean::Struct, renderer: &JsonRenderer<'_>) -> Self {
363        let has_stripped_fields = struct_.has_stripped_entries();
364        let clean::Struct { ctor_kind, generics, fields } = struct_;
365
366        let kind = match ctor_kind {
367            Some(CtorKind::Fn) => StructKind::Tuple(renderer.ids_keeping_stripped(fields)),
368            Some(CtorKind::Const) => {
369                assert!(fields.is_empty());
370                StructKind::Unit
371            }
372            None => StructKind::Plain { fields: renderer.ids(fields), has_stripped_fields },
373        };
374
375        Struct {
376            kind,
377            generics: generics.into_json(renderer),
378            impls: Vec::new(), // Added in JsonRenderer::item
379        }
380    }
381}
382
383impl FromClean<clean::Union> for Union {
384    fn from_clean(union_: &clean::Union, renderer: &JsonRenderer<'_>) -> Self {
385        let has_stripped_fields = union_.has_stripped_entries();
386        let clean::Union { generics, fields } = union_;
387        Union {
388            generics: generics.into_json(renderer),
389            has_stripped_fields,
390            fields: renderer.ids(fields),
391            impls: Vec::new(), // Added in JsonRenderer::item
392        }
393    }
394}
395
396impl FromClean<rustc_hir::FnHeader> for FunctionHeader {
397    fn from_clean(header: &rustc_hir::FnHeader, renderer: &JsonRenderer<'_>) -> Self {
398        let is_unsafe = match header.safety {
399            HeaderSafety::SafeTargetFeatures => {
400                // The type system's internal implementation details consider
401                // safe functions with the `#[target_feature]` attribute to be analogous
402                // to unsafe functions: `header.is_unsafe()` returns `true` for them.
403                // For rustdoc, this isn't the right decision, so we explicitly return `false`.
404                // Context: https://github.com/rust-lang/rust/issues/142655
405                false
406            }
407            HeaderSafety::Normal(Safety::Safe) => false,
408            HeaderSafety::Normal(Safety::Unsafe) => true,
409        };
410        FunctionHeader {
411            is_async: header.is_async(),
412            is_const: header.is_const(),
413            is_unsafe,
414            abi: header.abi.into_json(renderer),
415        }
416    }
417}
418
419impl FromClean<ExternAbi> for Abi {
420    fn from_clean(a: &ExternAbi, _renderer: &JsonRenderer<'_>) -> Self {
421        match *a {
422            ExternAbi::Rust => Abi::Rust,
423            ExternAbi::C { unwind } => Abi::C { unwind },
424            ExternAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
425            ExternAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
426            ExternAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
427            ExternAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
428            ExternAbi::Win64 { unwind } => Abi::Win64 { unwind },
429            ExternAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
430            ExternAbi::System { unwind } => Abi::System { unwind },
431            _ => Abi::Other(a.to_string()),
432        }
433    }
434}
435
436impl FromClean<clean::Lifetime> for String {
437    fn from_clean(l: &clean::Lifetime, _renderer: &JsonRenderer<'_>) -> String {
438        l.0.to_string()
439    }
440}
441
442impl FromClean<clean::Generics> for Generics {
443    fn from_clean(generics: &clean::Generics, renderer: &JsonRenderer<'_>) -> Self {
444        Generics {
445            params: generics.params.into_json(renderer),
446            where_predicates: generics.where_predicates.into_json(renderer),
447        }
448    }
449}
450
451impl FromClean<clean::GenericParamDef> for GenericParamDef {
452    fn from_clean(generic_param: &clean::GenericParamDef, renderer: &JsonRenderer<'_>) -> Self {
453        GenericParamDef {
454            name: generic_param.name.to_string(),
455            kind: generic_param.kind.into_json(renderer),
456        }
457    }
458}
459
460impl FromClean<clean::GenericParamDefKind> for GenericParamDefKind {
461    fn from_clean(kind: &clean::GenericParamDefKind, renderer: &JsonRenderer<'_>) -> Self {
462        use clean::GenericParamDefKind::*;
463        match kind {
464            Lifetime { outlives } => {
465                GenericParamDefKind::Lifetime { outlives: outlives.into_json(renderer) }
466            }
467            Type { bounds, default, synthetic } => GenericParamDefKind::Type {
468                bounds: bounds.into_json(renderer),
469                default: default.into_json(renderer),
470                is_synthetic: *synthetic,
471            },
472            Const { ty, default } => GenericParamDefKind::Const {
473                type_: ty.into_json(renderer),
474                default: default.as_ref().map(|x| x.as_ref().clone()),
475            },
476        }
477    }
478}
479
480impl FromClean<clean::WherePredicate> for WherePredicate {
481    fn from_clean(predicate: &clean::WherePredicate, renderer: &JsonRenderer<'_>) -> Self {
482        use clean::WherePredicate::*;
483        match predicate {
484            BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
485                type_: ty.into_json(renderer),
486                bounds: bounds.into_json(renderer),
487                generic_params: bound_params.into_json(renderer),
488            },
489            RegionPredicate { lifetime, bounds } => WherePredicate::LifetimePredicate {
490                lifetime: lifetime.into_json(renderer),
491                outlives: bounds
492                    .iter()
493                    .map(|bound| match bound {
494                        clean::GenericBound::Outlives(lt) => lt.into_json(renderer),
495                        _ => bug!("found non-outlives-bound on lifetime predicate"),
496                    })
497                    .collect(),
498            },
499            EqPredicate { lhs, rhs } => WherePredicate::EqPredicate {
500                // The LHS currently has type `Type` but it should be a `QualifiedPath` since it may
501                // refer to an associated const. However, `EqPredicate` shouldn't exist in the first
502                // place: <https://github.com/rust-lang/rust/141368>.
503                lhs: lhs.into_json(renderer),
504                rhs: rhs.into_json(renderer),
505            },
506        }
507    }
508}
509
510impl FromClean<clean::GenericBound> for GenericBound {
511    fn from_clean(bound: &clean::GenericBound, renderer: &JsonRenderer<'_>) -> Self {
512        use clean::GenericBound::*;
513        match bound {
514            TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
515                GenericBound::TraitBound {
516                    trait_: trait_.into_json(renderer),
517                    generic_params: generic_params.into_json(renderer),
518                    modifier: modifier.into_json(renderer),
519                }
520            }
521            Outlives(lifetime) => GenericBound::Outlives(lifetime.into_json(renderer)),
522            Use(args) => GenericBound::Use(
523                args.iter()
524                    .map(|arg| match arg {
525                        clean::PreciseCapturingArg::Lifetime(lt) => {
526                            PreciseCapturingArg::Lifetime(lt.into_json(renderer))
527                        }
528                        clean::PreciseCapturingArg::Param(param) => {
529                            PreciseCapturingArg::Param(param.to_string())
530                        }
531                    })
532                    .collect(),
533            ),
534        }
535    }
536}
537
538impl FromClean<rustc_hir::TraitBoundModifiers> for TraitBoundModifier {
539    fn from_clean(
540        modifiers: &rustc_hir::TraitBoundModifiers,
541        _renderer: &JsonRenderer<'_>,
542    ) -> Self {
543        use rustc_hir as hir;
544        let hir::TraitBoundModifiers { constness, polarity } = modifiers;
545        match (constness, polarity) {
546            (hir::BoundConstness::Never, hir::BoundPolarity::Positive) => TraitBoundModifier::None,
547            (hir::BoundConstness::Never, hir::BoundPolarity::Maybe(_)) => TraitBoundModifier::Maybe,
548            (hir::BoundConstness::Maybe(_), hir::BoundPolarity::Positive) => {
549                TraitBoundModifier::MaybeConst
550            }
551            // FIXME: Fill out the rest of this matrix.
552            _ => TraitBoundModifier::None,
553        }
554    }
555}
556
557impl FromClean<clean::Type> for Type {
558    fn from_clean(ty: &clean::Type, renderer: &JsonRenderer<'_>) -> Self {
559        use clean::Type::{
560            Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
561            RawPointer, SelfTy, Slice, Tuple, UnsafeBinder,
562        };
563
564        match ty {
565            clean::Type::Path { path } => Type::ResolvedPath(path.into_json(renderer)),
566            clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
567                lifetime: lt.into_json(renderer),
568                traits: bounds.into_json(renderer),
569            }),
570            Generic(s) => Type::Generic(s.to_string()),
571            // FIXME: add dedicated variant to json Type?
572            SelfTy => Type::Generic("Self".to_owned()),
573            Primitive(p) => Type::Primitive(p.as_sym().to_string()),
574            BareFunction(f) => Type::FunctionPointer(Box::new(f.into_json(renderer))),
575            Tuple(t) => Type::Tuple(t.into_json(renderer)),
576            Slice(t) => Type::Slice(Box::new(t.into_json(renderer))),
577            Array(t, s) => {
578                Type::Array { type_: Box::new(t.into_json(renderer)), len: s.to_string() }
579            }
580            clean::Type::Pat(t, p) => Type::Pat {
581                type_: Box::new(t.into_json(renderer)),
582                __pat_unstable_do_not_use: p.to_string(),
583            },
584            // FIXME(FRTs): implement
585            clean::Type::FieldOf(..) => todo!(),
586            ImplTrait(g) => Type::ImplTrait(g.into_json(renderer)),
587            Infer => Type::Infer,
588            RawPointer(mutability, type_) => Type::RawPointer {
589                is_mutable: *mutability == ast::Mutability::Mut,
590                type_: Box::new(type_.into_json(renderer)),
591            },
592            BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
593                lifetime: lifetime.into_json(renderer),
594                is_mutable: *mutability == ast::Mutability::Mut,
595                type_: Box::new(type_.into_json(renderer)),
596            },
597            QPath(qpath) => qpath.into_json(renderer),
598            // FIXME(unsafe_binder): Implement rustdoc-json.
599            UnsafeBinder(_) => todo!(),
600        }
601    }
602}
603
604impl FromClean<clean::Path> for Path {
605    fn from_clean(path: &clean::Path, renderer: &JsonRenderer<'_>) -> Self {
606        Path {
607            path: path.whole_name(),
608            id: renderer.id_from_item_default(path.def_id().into()),
609            args: {
610                if let Some((final_seg, rest_segs)) = path.segments.split_last() {
611                    // In general, `clean::Path` can hold things like
612                    // `std::vec::Vec::<u32>::new`, where generic args appear
613                    // in a middle segment. But for the places where `Path` is
614                    // used by rustdoc-json-types, generic args can only be
615                    // used in the final segment, e.g. `std::vec::Vec<u32>`. So
616                    // check that the non-final segments have no generic args.
617                    assert!(rest_segs.iter().all(|seg| seg.args.is_empty()));
618                    final_seg.args.into_json(renderer)
619                } else {
620                    None // no generics on any segments because there are no segments
621                }
622            },
623        }
624    }
625}
626
627impl FromClean<clean::QPathData> for Type {
628    fn from_clean(qpath: &clean::QPathData, renderer: &JsonRenderer<'_>) -> Self {
629        let clean::QPathData { assoc, self_type, should_fully_qualify: _, trait_ } = qpath;
630
631        Self::QualifiedPath {
632            name: assoc.name.to_string(),
633            args: assoc.args.into_json(renderer),
634            self_type: Box::new(self_type.into_json(renderer)),
635            trait_: trait_.into_json(renderer),
636        }
637    }
638}
639
640impl FromClean<clean::Term> for Term {
641    fn from_clean(term: &clean::Term, renderer: &JsonRenderer<'_>) -> Self {
642        match term {
643            clean::Term::Type(ty) => Term::Type(ty.into_json(renderer)),
644            clean::Term::Constant(c) => Term::Constant(c.into_json(renderer)),
645        }
646    }
647}
648
649impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
650    fn from_clean(bare_decl: &clean::BareFunctionDecl, renderer: &JsonRenderer<'_>) -> Self {
651        let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
652        FunctionPointer {
653            header: FunctionHeader {
654                is_unsafe: safety.is_unsafe(),
655                is_const: false,
656                is_async: false,
657                abi: abi.into_json(renderer),
658            },
659            generic_params: generic_params.into_json(renderer),
660            sig: decl.into_json(renderer),
661        }
662    }
663}
664
665impl FromClean<clean::FnDecl> for FunctionSignature {
666    fn from_clean(decl: &clean::FnDecl, renderer: &JsonRenderer<'_>) -> Self {
667        let clean::FnDecl { inputs, output, c_variadic } = decl;
668        FunctionSignature {
669            inputs: inputs
670                .iter()
671                .map(|param| {
672                    // `_` is the most sensible name for missing param names.
673                    let name = param.name.unwrap_or(kw::Underscore).to_string();
674                    let type_ = param.type_.into_json(renderer);
675                    (name, type_)
676                })
677                .collect(),
678            output: if output.is_unit() { None } else { Some(output.into_json(renderer)) },
679            is_c_variadic: *c_variadic,
680        }
681    }
682}
683
684impl FromClean<clean::Trait> for Trait {
685    fn from_clean(trait_: &clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
686        let tcx = renderer.tcx;
687        let is_auto = trait_.is_auto(tcx);
688        let is_unsafe = trait_.safety(tcx).is_unsafe();
689        let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
690        let clean::Trait { items, generics, bounds, .. } = trait_;
691        Trait {
692            is_auto,
693            is_unsafe,
694            is_dyn_compatible,
695            items: renderer.ids(items),
696            generics: generics.into_json(renderer),
697            bounds: bounds.into_json(renderer),
698            implementations: Vec::new(), // Added in JsonRenderer::item
699        }
700    }
701}
702
703impl FromClean<clean::PolyTrait> for PolyTrait {
704    fn from_clean(
705        clean::PolyTrait { trait_, generic_params }: &clean::PolyTrait,
706        renderer: &JsonRenderer<'_>,
707    ) -> Self {
708        PolyTrait {
709            trait_: trait_.into_json(renderer),
710            generic_params: generic_params.into_json(renderer),
711        }
712    }
713}
714
715impl FromClean<clean::Impl> for Impl {
716    fn from_clean(impl_: &clean::Impl, renderer: &JsonRenderer<'_>) -> Self {
717        let provided_trait_methods = impl_.provided_trait_methods(renderer.tcx);
718        let clean::Impl { safety, generics, trait_, for_, items, polarity, kind, is_deprecated: _ } =
719            impl_;
720        // FIXME: use something like ImplKind in JSON?
721        let (is_synthetic, blanket_impl) = match kind {
722            clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
723            clean::ImplKind::Auto => (true, None),
724            clean::ImplKind::Blanket(ty) => (false, Some(ty)),
725        };
726        let is_negative = match polarity {
727            ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
728            ty::ImplPolarity::Negative => true,
729        };
730        Impl {
731            is_unsafe: safety.is_unsafe(),
732            generics: generics.into_json(renderer),
733            provided_trait_methods: provided_trait_methods
734                .into_iter()
735                .map(|x| x.to_string())
736                .collect(),
737            trait_: trait_.into_json(renderer),
738            for_: for_.into_json(renderer),
739            items: renderer.ids(items),
740            is_negative,
741            is_synthetic,
742            blanket_impl: blanket_impl.map(|x| x.into_json(renderer)),
743        }
744    }
745}
746
747pub(crate) fn from_clean_function(
748    clean::Function { decl, generics }: &clean::Function,
749    has_body: bool,
750    header: rustc_hir::FnHeader,
751    renderer: &JsonRenderer<'_>,
752) -> Function {
753    Function {
754        sig: decl.into_json(renderer),
755        generics: generics.into_json(renderer),
756        header: header.into_json(renderer),
757        has_body,
758    }
759}
760
761impl FromClean<clean::Enum> for Enum {
762    fn from_clean(enum_: &clean::Enum, renderer: &JsonRenderer<'_>) -> Self {
763        let has_stripped_variants = enum_.has_stripped_entries();
764        let clean::Enum { variants, generics } = enum_;
765        Enum {
766            generics: generics.into_json(renderer),
767            has_stripped_variants,
768            variants: renderer.ids(&variants.as_slice().raw),
769            impls: Vec::new(), // Added in JsonRenderer::item
770        }
771    }
772}
773
774impl FromClean<clean::Variant> for Variant {
775    fn from_clean(variant: &clean::Variant, renderer: &JsonRenderer<'_>) -> Self {
776        use clean::VariantKind::*;
777
778        let discriminant = variant.discriminant.into_json(renderer);
779
780        let kind = match &variant.kind {
781            CLike => VariantKind::Plain,
782            Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)),
783            Struct(s) => VariantKind::Struct {
784                has_stripped_fields: s.has_stripped_entries(),
785                fields: renderer.ids(&s.fields),
786            },
787        };
788
789        Variant { kind, discriminant }
790    }
791}
792
793impl FromClean<clean::Discriminant> for Discriminant {
794    fn from_clean(disr: &clean::Discriminant, renderer: &JsonRenderer<'_>) -> Self {
795        let tcx = renderer.tcx;
796        Discriminant {
797            // expr is only none if going through the inlining path, which gets
798            // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
799            // the expr is always some.
800            expr: disr.expr(tcx).unwrap(),
801            value: disr.value(tcx, false),
802        }
803    }
804}
805
806impl FromClean<clean::Import> for Use {
807    fn from_clean(import: &clean::Import, renderer: &JsonRenderer<'_>) -> Self {
808        use clean::ImportKind::*;
809        let (name, is_glob) = match import.kind {
810            Simple(s) => (s.to_string(), false),
811            Glob => (import.source.path.last_opt().unwrap_or(sym::asterisk).to_string(), true),
812        };
813        Use {
814            source: import.source.path.whole_name(),
815            name,
816            id: import.source.did.map(ItemId::from).map(|i| renderer.id_from_item_default(i)),
817            is_glob,
818        }
819    }
820}
821
822impl FromClean<clean::ProcMacro> for ProcMacro {
823    fn from_clean(mac: &clean::ProcMacro, renderer: &JsonRenderer<'_>) -> Self {
824        ProcMacro {
825            kind: mac.kind.into_json(renderer),
826            helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
827        }
828    }
829}
830
831impl FromClean<rustc_span::hygiene::MacroKind> for MacroKind {
832    fn from_clean(kind: &rustc_span::hygiene::MacroKind, _renderer: &JsonRenderer<'_>) -> Self {
833        use rustc_span::hygiene::MacroKind::*;
834        match kind {
835            Bang => MacroKind::Bang,
836            Attr => MacroKind::Attr,
837            Derive => MacroKind::Derive,
838        }
839    }
840}
841
842impl FromClean<clean::TypeAlias> for TypeAlias {
843    fn from_clean(type_alias: &clean::TypeAlias, renderer: &JsonRenderer<'_>) -> Self {
844        let clean::TypeAlias { type_, generics, item_type: _, inner_type: _ } = type_alias;
845        TypeAlias { type_: type_.into_json(renderer), generics: generics.into_json(renderer) }
846    }
847}
848
849fn from_clean_static(
850    stat: &clean::Static,
851    safety: rustc_hir::Safety,
852    renderer: &JsonRenderer<'_>,
853) -> Static {
854    let tcx = renderer.tcx;
855    Static {
856        type_: stat.type_.as_ref().into_json(renderer),
857        is_mutable: stat.mutability == ast::Mutability::Mut,
858        is_unsafe: safety.is_unsafe(),
859        expr: stat
860            .expr
861            .map(|e| rendered_const(tcx, tcx.hir_body(e), tcx.hir_body_owner_def_id(e)))
862            .unwrap_or_default(),
863    }
864}
865
866impl FromClean<clean::TraitAlias> for TraitAlias {
867    fn from_clean(alias: &clean::TraitAlias, renderer: &JsonRenderer<'_>) -> Self {
868        TraitAlias {
869            generics: alias.generics.into_json(renderer),
870            params: alias.bounds.into_json(renderer),
871        }
872    }
873}
874
875impl FromClean<ItemType> for ItemKind {
876    fn from_clean(kind: &ItemType, _renderer: &JsonRenderer<'_>) -> Self {
877        use ItemType::*;
878        match kind {
879            Module => ItemKind::Module,
880            ExternCrate => ItemKind::ExternCrate,
881            Import => ItemKind::Use,
882            Struct => ItemKind::Struct,
883            Union => ItemKind::Union,
884            Enum => ItemKind::Enum,
885            Function | TyMethod | Method => ItemKind::Function,
886            TypeAlias => ItemKind::TypeAlias,
887            Static => ItemKind::Static,
888            Constant => ItemKind::Constant,
889            Trait => ItemKind::Trait,
890            Impl => ItemKind::Impl,
891            StructField => ItemKind::StructField,
892            Variant => ItemKind::Variant,
893            Macro => ItemKind::Macro,
894            Primitive => ItemKind::Primitive,
895            AssocConst => ItemKind::AssocConst,
896            AssocType => ItemKind::AssocType,
897            ForeignType => ItemKind::ExternType,
898            Keyword => ItemKind::Keyword,
899            Attribute => ItemKind::Attribute,
900            TraitAlias => ItemKind::TraitAlias,
901            ProcAttribute => ItemKind::ProcAttribute,
902            ProcDerive => ItemKind::ProcDerive,
903        }
904    }
905}
906
907/// Maybe convert a attribute from hir to json.
908///
909/// Returns `None` if the attribute shouldn't be in the output.
910fn maybe_from_hir_attr(attr: &hir::Attribute, item_id: ItemId, tcx: TyCtxt<'_>) -> Vec<Attribute> {
911    use attrs::AttributeKind as AK;
912
913    let kind = match attr {
914        hir::Attribute::Parsed(kind) => kind,
915
916        hir::Attribute::Unparsed(_) => {
917            // FIXME: We should handle `#[doc(hidden)]`.
918            return vec![other_attr(tcx, attr)];
919        }
920    };
921
922    vec![match kind {
923        AK::Deprecated { .. } => return Vec::new(), // Handled separately into Item::deprecation.
924        AK::DocComment { .. } => unreachable!("doc comments stripped out earlier"),
925
926        AK::MacroExport { .. } => Attribute::MacroExport,
927        AK::MustUse { reason, span: _ } => {
928            Attribute::MustUse { reason: reason.map(|s| s.to_string()) }
929        }
930        AK::Repr { .. } => repr_attr(
931            tcx,
932            item_id.as_def_id().expect("all items that could have #[repr] have a DefId"),
933        ),
934        AK::ExportName { name, span: _ } => Attribute::ExportName(name.to_string()),
935        AK::LinkSection { name, span: _ } => Attribute::LinkSection(name.to_string()),
936        AK::TargetFeature { features, .. } => Attribute::TargetFeature {
937            enable: features.iter().map(|(feat, _span)| feat.to_string()).collect(),
938        },
939
940        AK::NoMangle(_) => Attribute::NoMangle,
941        AK::NonExhaustive(_) => Attribute::NonExhaustive,
942        AK::AutomaticallyDerived(_) => Attribute::AutomaticallyDerived,
943        AK::Doc(d) => {
944            fn toggle_attr(ret: &mut Vec<Attribute>, name: &str, v: &Option<rustc_span::Span>) {
945                if v.is_some() {
946                    ret.push(Attribute::Other(format!("#[doc({name})]")));
947                }
948            }
949
950            fn name_value_attr(
951                ret: &mut Vec<Attribute>,
952                name: &str,
953                v: &Option<(Symbol, rustc_span::Span)>,
954            ) {
955                if let Some((v, _)) = v {
956                    // We use `as_str` and debug display to have characters escaped and `"`
957                    // characters surrounding the string.
958                    ret.push(Attribute::Other(format!("#[doc({name} = {:?})]", v.as_str())));
959                }
960            }
961
962            let DocAttribute {
963                aliases,
964                hidden,
965                inline,
966                cfg,
967                auto_cfg,
968                auto_cfg_change,
969                fake_variadic,
970                keyword,
971                attribute,
972                masked,
973                notable_trait,
974                search_unbox,
975                html_favicon_url,
976                html_logo_url,
977                html_playground_url,
978                html_root_url,
979                html_no_source,
980                issue_tracker_base_url,
981                rust_logo,
982                test_attrs,
983                no_crate_inject,
984            } = &**d;
985
986            let mut ret = Vec::new();
987
988            for (alias, _) in aliases {
989                // We use `as_str` and debug display to have characters escaped and `"` characters
990                // surrounding the string.
991                ret.push(Attribute::Other(format!("#[doc(alias = {:?})]", alias.as_str())));
992            }
993            toggle_attr(&mut ret, "hidden", hidden);
994            if let Some(inline) = inline.first() {
995                ret.push(Attribute::Other(format!(
996                    "#[doc({})]",
997                    match inline.0 {
998                        DocInline::Inline => "inline",
999                        DocInline::NoInline => "no_inline",
1000                    }
1001                )));
1002            }
1003            for sub_cfg in cfg {
1004                ret.push(Attribute::Other(format!("#[doc(cfg({sub_cfg}))]")));
1005            }
1006            for (auto_cfg, _) in auto_cfg {
1007                let kind = match auto_cfg.kind {
1008                    HideOrShow::Hide => "hide",
1009                    HideOrShow::Show => "show",
1010                };
1011                let mut out = format!("#[doc(auto_cfg({kind}(");
1012                for (pos, value) in auto_cfg.values.iter().enumerate() {
1013                    if pos > 0 {
1014                        out.push_str(", ");
1015                    }
1016                    out.push_str(value.name.as_str());
1017                    if let Some((value, _)) = value.value {
1018                        // We use `as_str` and debug display to have characters escaped and `"`
1019                        // characters surrounding the string.
1020                        out.push_str(&format!(" = {:?}", value.as_str()));
1021                    }
1022                }
1023                out.push_str(")))]");
1024                ret.push(Attribute::Other(out));
1025            }
1026            for (change, _) in auto_cfg_change {
1027                ret.push(Attribute::Other(format!("#[doc(auto_cfg = {change})]")));
1028            }
1029            toggle_attr(&mut ret, "fake_variadic", fake_variadic);
1030            name_value_attr(&mut ret, "keyword", keyword);
1031            name_value_attr(&mut ret, "attribute", attribute);
1032            toggle_attr(&mut ret, "masked", masked);
1033            toggle_attr(&mut ret, "notable_trait", notable_trait);
1034            toggle_attr(&mut ret, "search_unbox", search_unbox);
1035            name_value_attr(&mut ret, "html_favicon_url", html_favicon_url);
1036            name_value_attr(&mut ret, "html_logo_url", html_logo_url);
1037            name_value_attr(&mut ret, "html_playground_url", html_playground_url);
1038            name_value_attr(&mut ret, "html_root_url", html_root_url);
1039            toggle_attr(&mut ret, "html_no_source", html_no_source);
1040            name_value_attr(&mut ret, "issue_tracker_base_url", issue_tracker_base_url);
1041            toggle_attr(&mut ret, "rust_logo", rust_logo);
1042            let source_map = tcx.sess.source_map();
1043            for attr_span in test_attrs {
1044                // FIXME: This is ugly, remove when `test_attrs` has been ported to new attribute API.
1045                if let Ok(snippet) = source_map.span_to_snippet(*attr_span) {
1046                    ret.push(Attribute::Other(format!("#[doc(test(attr({snippet})))]")));
1047                }
1048            }
1049            toggle_attr(&mut ret, "test(no_crate_inject)", no_crate_inject);
1050            return ret;
1051        }
1052
1053        _ => other_attr(tcx, attr),
1054    }]
1055}
1056
1057fn other_attr(tcx: TyCtxt<'_>, attr: &hir::Attribute) -> Attribute {
1058    let mut s = rustc_hir_pretty::attribute_to_string(&tcx, attr);
1059    assert_eq!(s.pop(), Some('\n'));
1060    Attribute::Other(s)
1061}
1062
1063fn repr_attr(tcx: TyCtxt<'_>, def_id: DefId) -> Attribute {
1064    let repr = tcx.adt_def(def_id).repr();
1065
1066    let kind = if repr.c() {
1067        ReprKind::C
1068    } else if repr.transparent() {
1069        ReprKind::Transparent
1070    } else if repr.simd() {
1071        ReprKind::Simd
1072    } else {
1073        ReprKind::Rust
1074    };
1075
1076    let align = repr.align.map(|a| a.bytes());
1077    let packed = repr.pack.map(|p| p.bytes());
1078    let int = repr.int.map(format_integer_type);
1079
1080    Attribute::Repr(AttributeRepr { kind, align, packed, int })
1081}
1082
1083fn format_integer_type(it: rustc_abi::IntegerType) -> String {
1084    use rustc_abi::Integer::*;
1085    use rustc_abi::IntegerType::*;
1086    match it {
1087        Pointer(true) => "isize",
1088        Pointer(false) => "usize",
1089        Fixed(I8, true) => "i8",
1090        Fixed(I8, false) => "u8",
1091        Fixed(I16, true) => "i16",
1092        Fixed(I16, false) => "u16",
1093        Fixed(I32, true) => "i32",
1094        Fixed(I32, false) => "u32",
1095        Fixed(I64, true) => "i64",
1096        Fixed(I64, false) => "u64",
1097        Fixed(I128, true) => "i128",
1098        Fixed(I128, false) => "u128",
1099    }
1100    .to_owned()
1101}
1102
1103pub(super) fn target(sess: &rustc_session::Session) -> Target {
1104    // Build a set of which features are enabled on this target
1105    let globally_enabled_features: FxHashSet<&str> =
1106        sess.unstable_target_features.iter().map(|name| name.as_str()).collect();
1107
1108    // Build a map of target feature stability by feature name
1109    use rustc_target::target_features::Stability;
1110    let feature_stability: FxHashMap<&str, Stability> = sess
1111        .target
1112        .rust_target_features()
1113        .iter()
1114        .copied()
1115        .map(|(name, stability, _)| (name, stability))
1116        .collect();
1117
1118    Target {
1119        triple: sess.opts.target_triple.tuple().into(),
1120        target_features: sess
1121            .target
1122            .rust_target_features()
1123            .iter()
1124            .copied()
1125            .filter(|(_, stability, _)| {
1126                // Describe only target features which the user can toggle
1127                stability.toggle_allowed().is_ok()
1128            })
1129            .map(|(name, stability, implied_features)| {
1130                TargetFeature {
1131                    name: name.into(),
1132                    unstable_feature_gate: match stability {
1133                        Stability::Unstable(feature_gate) => Some(feature_gate.as_str().into()),
1134                        _ => None,
1135                    },
1136                    implies_features: implied_features
1137                        .iter()
1138                        .copied()
1139                        .filter(|name| {
1140                            // Imply only target features which the user can toggle
1141                            feature_stability
1142                                .get(name)
1143                                .map(|stability| stability.toggle_allowed().is_ok())
1144                                .unwrap_or(false)
1145                        })
1146                        .map(String::from)
1147                        .collect(),
1148                    globally_enabled: globally_enabled_features.contains(name),
1149                }
1150            })
1151            .collect(),
1152    }
1153}