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            // FIXME(FRTs): implement
583            clean::Type::FieldOf(..) => todo!(),
584            ImplTrait(g) => Type::ImplTrait(g.into_json(renderer)),
585            Infer => Type::Infer,
586            RawPointer(mutability, type_) => Type::RawPointer {
587                is_mutable: *mutability == ast::Mutability::Mut,
588                type_: Box::new(type_.into_json(renderer)),
589            },
590            BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
591                lifetime: lifetime.into_json(renderer),
592                is_mutable: *mutability == ast::Mutability::Mut,
593                type_: Box::new(type_.into_json(renderer)),
594            },
595            QPath(qpath) => qpath.into_json(renderer),
596            // FIXME(unsafe_binder): Implement rustdoc-json.
597            UnsafeBinder(_) => todo!(),
598        }
599    }
600}
601
602impl FromClean<clean::Path> for Path {
603    fn from_clean(path: &clean::Path, renderer: &JsonRenderer<'_>) -> Self {
604        Path {
605            path: path.whole_name(),
606            id: renderer.id_from_item_default(path.def_id().into()),
607            args: {
608                if let Some((final_seg, rest_segs)) = path.segments.split_last() {
609                    // In general, `clean::Path` can hold things like
610                    // `std::vec::Vec::<u32>::new`, where generic args appear
611                    // in a middle segment. But for the places where `Path` is
612                    // used by rustdoc-json-types, generic args can only be
613                    // used in the final segment, e.g. `std::vec::Vec<u32>`. So
614                    // check that the non-final segments have no generic args.
615                    assert!(rest_segs.iter().all(|seg| seg.args.is_empty()));
616                    final_seg.args.into_json(renderer)
617                } else {
618                    None // no generics on any segments because there are no segments
619                }
620            },
621        }
622    }
623}
624
625impl FromClean<clean::QPathData> for Type {
626    fn from_clean(qpath: &clean::QPathData, renderer: &JsonRenderer<'_>) -> Self {
627        let clean::QPathData { assoc, self_type, should_fully_qualify: _, trait_ } = qpath;
628
629        Self::QualifiedPath {
630            name: assoc.name.to_string(),
631            args: assoc.args.into_json(renderer),
632            self_type: Box::new(self_type.into_json(renderer)),
633            trait_: trait_.into_json(renderer),
634        }
635    }
636}
637
638impl FromClean<clean::Term> for Term {
639    fn from_clean(term: &clean::Term, renderer: &JsonRenderer<'_>) -> Self {
640        match term {
641            clean::Term::Type(ty) => Term::Type(ty.into_json(renderer)),
642            clean::Term::Constant(c) => Term::Constant(c.into_json(renderer)),
643        }
644    }
645}
646
647impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
648    fn from_clean(bare_decl: &clean::BareFunctionDecl, renderer: &JsonRenderer<'_>) -> Self {
649        let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
650        FunctionPointer {
651            header: FunctionHeader {
652                is_unsafe: safety.is_unsafe(),
653                is_const: false,
654                is_async: false,
655                abi: abi.into_json(renderer),
656            },
657            generic_params: generic_params.into_json(renderer),
658            sig: decl.into_json(renderer),
659        }
660    }
661}
662
663impl FromClean<clean::FnDecl> for FunctionSignature {
664    fn from_clean(decl: &clean::FnDecl, renderer: &JsonRenderer<'_>) -> Self {
665        let clean::FnDecl { inputs, output, c_variadic } = decl;
666        FunctionSignature {
667            inputs: inputs
668                .iter()
669                .map(|param| {
670                    // `_` is the most sensible name for missing param names.
671                    let name = param.name.unwrap_or(kw::Underscore).to_string();
672                    let type_ = param.type_.into_json(renderer);
673                    (name, type_)
674                })
675                .collect(),
676            output: if output.is_unit() { None } else { Some(output.into_json(renderer)) },
677            is_c_variadic: *c_variadic,
678        }
679    }
680}
681
682impl FromClean<clean::Trait> for Trait {
683    fn from_clean(trait_: &clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
684        let tcx = renderer.tcx;
685        let is_auto = trait_.is_auto(tcx);
686        let is_unsafe = trait_.safety(tcx).is_unsafe();
687        let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
688        let clean::Trait { items, generics, bounds, .. } = trait_;
689        Trait {
690            is_auto,
691            is_unsafe,
692            is_dyn_compatible,
693            items: renderer.ids(items),
694            generics: generics.into_json(renderer),
695            bounds: bounds.into_json(renderer),
696            implementations: Vec::new(), // Added in JsonRenderer::item
697        }
698    }
699}
700
701impl FromClean<clean::PolyTrait> for PolyTrait {
702    fn from_clean(
703        clean::PolyTrait { trait_, generic_params }: &clean::PolyTrait,
704        renderer: &JsonRenderer<'_>,
705    ) -> Self {
706        PolyTrait {
707            trait_: trait_.into_json(renderer),
708            generic_params: generic_params.into_json(renderer),
709        }
710    }
711}
712
713impl FromClean<clean::Impl> for Impl {
714    fn from_clean(impl_: &clean::Impl, renderer: &JsonRenderer<'_>) -> Self {
715        let provided_trait_methods = impl_.provided_trait_methods(renderer.tcx);
716        let clean::Impl { safety, generics, trait_, for_, items, polarity, kind, is_deprecated: _ } =
717            impl_;
718        // FIXME: use something like ImplKind in JSON?
719        let (is_synthetic, blanket_impl) = match kind {
720            clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
721            clean::ImplKind::Auto => (true, None),
722            clean::ImplKind::Blanket(ty) => (false, Some(ty)),
723        };
724        let is_negative = match polarity {
725            ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
726            ty::ImplPolarity::Negative => true,
727        };
728        Impl {
729            is_unsafe: safety.is_unsafe(),
730            generics: generics.into_json(renderer),
731            provided_trait_methods: provided_trait_methods
732                .into_iter()
733                .map(|x| x.to_string())
734                .collect(),
735            trait_: trait_.into_json(renderer),
736            for_: for_.into_json(renderer),
737            items: renderer.ids(items),
738            is_negative,
739            is_synthetic,
740            blanket_impl: blanket_impl.map(|x| x.into_json(renderer)),
741        }
742    }
743}
744
745pub(crate) fn from_clean_function(
746    clean::Function { decl, generics }: &clean::Function,
747    has_body: bool,
748    header: rustc_hir::FnHeader,
749    renderer: &JsonRenderer<'_>,
750) -> Function {
751    Function {
752        sig: decl.into_json(renderer),
753        generics: generics.into_json(renderer),
754        header: header.into_json(renderer),
755        has_body,
756    }
757}
758
759impl FromClean<clean::Enum> for Enum {
760    fn from_clean(enum_: &clean::Enum, renderer: &JsonRenderer<'_>) -> Self {
761        let has_stripped_variants = enum_.has_stripped_entries();
762        let clean::Enum { variants, generics } = enum_;
763        Enum {
764            generics: generics.into_json(renderer),
765            has_stripped_variants,
766            variants: renderer.ids(&variants.as_slice().raw),
767            impls: Vec::new(), // Added in JsonRenderer::item
768        }
769    }
770}
771
772impl FromClean<clean::Variant> for Variant {
773    fn from_clean(variant: &clean::Variant, renderer: &JsonRenderer<'_>) -> Self {
774        use clean::VariantKind::*;
775
776        let discriminant = variant.discriminant.into_json(renderer);
777
778        let kind = match &variant.kind {
779            CLike => VariantKind::Plain,
780            Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)),
781            Struct(s) => VariantKind::Struct {
782                has_stripped_fields: s.has_stripped_entries(),
783                fields: renderer.ids(&s.fields),
784            },
785        };
786
787        Variant { kind, discriminant }
788    }
789}
790
791impl FromClean<clean::Discriminant> for Discriminant {
792    fn from_clean(disr: &clean::Discriminant, renderer: &JsonRenderer<'_>) -> Self {
793        let tcx = renderer.tcx;
794        Discriminant {
795            // expr is only none if going through the inlining path, which gets
796            // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
797            // the expr is always some.
798            expr: disr.expr(tcx).unwrap(),
799            value: disr.value(tcx, false),
800        }
801    }
802}
803
804impl FromClean<clean::Import> for Use {
805    fn from_clean(import: &clean::Import, renderer: &JsonRenderer<'_>) -> Self {
806        use clean::ImportKind::*;
807        let (name, is_glob) = match import.kind {
808            Simple(s) => (s.to_string(), false),
809            Glob => (import.source.path.last_opt().unwrap_or(sym::asterisk).to_string(), true),
810        };
811        Use {
812            source: import.source.path.whole_name(),
813            name,
814            id: import.source.did.map(ItemId::from).map(|i| renderer.id_from_item_default(i)),
815            is_glob,
816        }
817    }
818}
819
820impl FromClean<clean::ProcMacro> for ProcMacro {
821    fn from_clean(mac: &clean::ProcMacro, renderer: &JsonRenderer<'_>) -> Self {
822        ProcMacro {
823            kind: mac.kind.into_json(renderer),
824            helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
825        }
826    }
827}
828
829impl FromClean<rustc_span::hygiene::MacroKind> for MacroKind {
830    fn from_clean(kind: &rustc_span::hygiene::MacroKind, _renderer: &JsonRenderer<'_>) -> Self {
831        use rustc_span::hygiene::MacroKind::*;
832        match kind {
833            Bang => MacroKind::Bang,
834            Attr => MacroKind::Attr,
835            Derive => MacroKind::Derive,
836        }
837    }
838}
839
840impl FromClean<clean::TypeAlias> for TypeAlias {
841    fn from_clean(type_alias: &clean::TypeAlias, renderer: &JsonRenderer<'_>) -> Self {
842        let clean::TypeAlias { type_, generics, item_type: _, inner_type: _ } = type_alias;
843        TypeAlias { type_: type_.into_json(renderer), generics: generics.into_json(renderer) }
844    }
845}
846
847fn from_clean_static(
848    stat: &clean::Static,
849    safety: rustc_hir::Safety,
850    renderer: &JsonRenderer<'_>,
851) -> Static {
852    let tcx = renderer.tcx;
853    Static {
854        type_: stat.type_.as_ref().into_json(renderer),
855        is_mutable: stat.mutability == ast::Mutability::Mut,
856        is_unsafe: safety.is_unsafe(),
857        expr: stat
858            .expr
859            .map(|e| rendered_const(tcx, tcx.hir_body(e), tcx.hir_body_owner_def_id(e)))
860            .unwrap_or_default(),
861    }
862}
863
864impl FromClean<clean::TraitAlias> for TraitAlias {
865    fn from_clean(alias: &clean::TraitAlias, renderer: &JsonRenderer<'_>) -> Self {
866        TraitAlias {
867            generics: alias.generics.into_json(renderer),
868            params: alias.bounds.into_json(renderer),
869        }
870    }
871}
872
873impl FromClean<ItemType> for ItemKind {
874    fn from_clean(kind: &ItemType, _renderer: &JsonRenderer<'_>) -> Self {
875        use ItemType::*;
876        match kind {
877            Module => ItemKind::Module,
878            ExternCrate => ItemKind::ExternCrate,
879            Import => ItemKind::Use,
880            Struct => ItemKind::Struct,
881            Union => ItemKind::Union,
882            Enum => ItemKind::Enum,
883            Function | TyMethod | Method => ItemKind::Function,
884            TypeAlias => ItemKind::TypeAlias,
885            Static => ItemKind::Static,
886            Constant => ItemKind::Constant,
887            Trait => ItemKind::Trait,
888            Impl => ItemKind::Impl,
889            StructField => ItemKind::StructField,
890            Variant => ItemKind::Variant,
891            Macro => ItemKind::Macro,
892            Primitive => ItemKind::Primitive,
893            AssocConst => ItemKind::AssocConst,
894            AssocType => ItemKind::AssocType,
895            ForeignType => ItemKind::ExternType,
896            Keyword => ItemKind::Keyword,
897            Attribute => ItemKind::Attribute,
898            TraitAlias => ItemKind::TraitAlias,
899            ProcAttribute => ItemKind::ProcAttribute,
900            ProcDerive => ItemKind::ProcDerive,
901        }
902    }
903}
904
905/// Maybe convert a attribute from hir to json.
906///
907/// Returns `None` if the attribute shouldn't be in the output.
908fn maybe_from_hir_attr(attr: &hir::Attribute, item_id: ItemId, tcx: TyCtxt<'_>) -> Vec<Attribute> {
909    use attrs::AttributeKind as AK;
910
911    let kind = match attr {
912        hir::Attribute::Parsed(kind) => kind,
913
914        hir::Attribute::Unparsed(_) => {
915            // FIXME: We should handle `#[doc(hidden)]`.
916            return vec![other_attr(tcx, attr)];
917        }
918    };
919
920    vec![match kind {
921        AK::Deprecated { .. } => return Vec::new(), // Handled separately into Item::deprecation.
922        AK::DocComment { .. } => unreachable!("doc comments stripped out earlier"),
923
924        AK::MacroExport { .. } => Attribute::MacroExport,
925        AK::MustUse { reason, span: _ } => {
926            Attribute::MustUse { reason: reason.map(|s| s.to_string()) }
927        }
928        AK::Repr { .. } => repr_attr(
929            tcx,
930            item_id.as_def_id().expect("all items that could have #[repr] have a DefId"),
931        ),
932        AK::ExportName { name, span: _ } => Attribute::ExportName(name.to_string()),
933        AK::LinkSection { name, span: _ } => Attribute::LinkSection(name.to_string()),
934        AK::TargetFeature { features, .. } => Attribute::TargetFeature {
935            enable: features.iter().map(|(feat, _span)| feat.to_string()).collect(),
936        },
937
938        AK::NoMangle(_) => Attribute::NoMangle,
939        AK::NonExhaustive(_) => Attribute::NonExhaustive,
940        AK::AutomaticallyDerived(_) => Attribute::AutomaticallyDerived,
941        AK::Doc(d) => {
942            fn toggle_attr(ret: &mut Vec<Attribute>, name: &str, v: &Option<rustc_span::Span>) {
943                if v.is_some() {
944                    ret.push(Attribute::Other(format!("#[doc({name})]")));
945                }
946            }
947
948            fn name_value_attr(
949                ret: &mut Vec<Attribute>,
950                name: &str,
951                v: &Option<(Symbol, rustc_span::Span)>,
952            ) {
953                if let Some((v, _)) = v {
954                    // We use `as_str` and debug display to have characters escaped and `"`
955                    // characters surrounding the string.
956                    ret.push(Attribute::Other(format!("#[doc({name} = {:?})]", v.as_str())));
957                }
958            }
959
960            let DocAttribute {
961                aliases,
962                hidden,
963                inline,
964                cfg,
965                auto_cfg,
966                auto_cfg_change,
967                fake_variadic,
968                keyword,
969                attribute,
970                masked,
971                notable_trait,
972                search_unbox,
973                html_favicon_url,
974                html_logo_url,
975                html_playground_url,
976                html_root_url,
977                html_no_source,
978                issue_tracker_base_url,
979                rust_logo,
980                test_attrs,
981                no_crate_inject,
982            } = &**d;
983
984            let mut ret = Vec::new();
985
986            for (alias, _) in aliases {
987                // We use `as_str` and debug display to have characters escaped and `"` characters
988                // surrounding the string.
989                ret.push(Attribute::Other(format!("#[doc(alias = {:?})]", alias.as_str())));
990            }
991            toggle_attr(&mut ret, "hidden", hidden);
992            if let Some(inline) = inline.first() {
993                ret.push(Attribute::Other(format!(
994                    "#[doc({})]",
995                    match inline.0 {
996                        DocInline::Inline => "inline",
997                        DocInline::NoInline => "no_inline",
998                    }
999                )));
1000            }
1001            for sub_cfg in cfg {
1002                ret.push(Attribute::Other(format!("#[doc(cfg({sub_cfg}))]")));
1003            }
1004            for (auto_cfg, _) in auto_cfg {
1005                let kind = match auto_cfg.kind {
1006                    HideOrShow::Hide => "hide",
1007                    HideOrShow::Show => "show",
1008                };
1009                let mut out = format!("#[doc(auto_cfg({kind}(");
1010                for (pos, value) in auto_cfg.values.iter().enumerate() {
1011                    if pos > 0 {
1012                        out.push_str(", ");
1013                    }
1014                    out.push_str(value.name.as_str());
1015                    if let Some((value, _)) = value.value {
1016                        // We use `as_str` and debug display to have characters escaped and `"`
1017                        // characters surrounding the string.
1018                        out.push_str(&format!(" = {:?}", value.as_str()));
1019                    }
1020                }
1021                out.push_str(")))]");
1022                ret.push(Attribute::Other(out));
1023            }
1024            for (change, _) in auto_cfg_change {
1025                ret.push(Attribute::Other(format!("#[doc(auto_cfg = {change})]")));
1026            }
1027            toggle_attr(&mut ret, "fake_variadic", fake_variadic);
1028            name_value_attr(&mut ret, "keyword", keyword);
1029            name_value_attr(&mut ret, "attribute", attribute);
1030            toggle_attr(&mut ret, "masked", masked);
1031            toggle_attr(&mut ret, "notable_trait", notable_trait);
1032            toggle_attr(&mut ret, "search_unbox", search_unbox);
1033            name_value_attr(&mut ret, "html_favicon_url", html_favicon_url);
1034            name_value_attr(&mut ret, "html_logo_url", html_logo_url);
1035            name_value_attr(&mut ret, "html_playground_url", html_playground_url);
1036            name_value_attr(&mut ret, "html_root_url", html_root_url);
1037            toggle_attr(&mut ret, "html_no_source", html_no_source);
1038            name_value_attr(&mut ret, "issue_tracker_base_url", issue_tracker_base_url);
1039            toggle_attr(&mut ret, "rust_logo", rust_logo);
1040            let source_map = tcx.sess.source_map();
1041            for attr_span in test_attrs {
1042                // FIXME: This is ugly, remove when `test_attrs` has been ported to new attribute API.
1043                if let Ok(snippet) = source_map.span_to_snippet(*attr_span) {
1044                    ret.push(Attribute::Other(format!("#[doc(test(attr({snippet})))]")));
1045                }
1046            }
1047            toggle_attr(&mut ret, "test(no_crate_inject)", no_crate_inject);
1048            return ret;
1049        }
1050
1051        _ => other_attr(tcx, attr),
1052    }]
1053}
1054
1055fn other_attr(tcx: TyCtxt<'_>, attr: &hir::Attribute) -> Attribute {
1056    let mut s = rustc_hir_pretty::attribute_to_string(&tcx, attr);
1057    assert_eq!(s.pop(), Some('\n'));
1058    Attribute::Other(s)
1059}
1060
1061fn repr_attr(tcx: TyCtxt<'_>, def_id: DefId) -> Attribute {
1062    let repr = tcx.adt_def(def_id).repr();
1063
1064    let kind = if repr.c() {
1065        ReprKind::C
1066    } else if repr.transparent() {
1067        ReprKind::Transparent
1068    } else if repr.simd() {
1069        ReprKind::Simd
1070    } else {
1071        ReprKind::Rust
1072    };
1073
1074    let align = repr.align.map(|a| a.bytes());
1075    let packed = repr.pack.map(|p| p.bytes());
1076    let int = repr.int.map(format_integer_type);
1077
1078    Attribute::Repr(AttributeRepr { kind, align, packed, int })
1079}
1080
1081fn format_integer_type(it: rustc_abi::IntegerType) -> String {
1082    use rustc_abi::Integer::*;
1083    use rustc_abi::IntegerType::*;
1084    match it {
1085        Pointer(true) => "isize",
1086        Pointer(false) => "usize",
1087        Fixed(I8, true) => "i8",
1088        Fixed(I8, false) => "u8",
1089        Fixed(I16, true) => "i16",
1090        Fixed(I16, false) => "u16",
1091        Fixed(I32, true) => "i32",
1092        Fixed(I32, false) => "u32",
1093        Fixed(I64, true) => "i64",
1094        Fixed(I64, false) => "u64",
1095        Fixed(I128, true) => "i128",
1096        Fixed(I128, false) => "u128",
1097    }
1098    .to_owned()
1099}
1100
1101pub(super) fn target(sess: &rustc_session::Session) -> Target {
1102    // Build a set of which features are enabled on this target
1103    let globally_enabled_features: FxHashSet<&str> =
1104        sess.unstable_target_features.iter().map(|name| name.as_str()).collect();
1105
1106    // Build a map of target feature stability by feature name
1107    use rustc_target::target_features::Stability;
1108    let feature_stability: FxHashMap<&str, Stability> = sess
1109        .target
1110        .rust_target_features()
1111        .iter()
1112        .copied()
1113        .map(|(name, stability, _)| (name, stability))
1114        .collect();
1115
1116    Target {
1117        triple: sess.opts.target_triple.tuple().into(),
1118        target_features: sess
1119            .target
1120            .rust_target_features()
1121            .iter()
1122            .copied()
1123            .filter(|(_, stability, _)| {
1124                // Describe only target features which the user can toggle
1125                stability.toggle_allowed().is_ok()
1126            })
1127            .map(|(name, stability, implied_features)| {
1128                TargetFeature {
1129                    name: name.into(),
1130                    unstable_feature_gate: match stability {
1131                        Stability::Unstable(feature_gate) => Some(feature_gate.as_str().into()),
1132                        _ => None,
1133                    },
1134                    implies_features: implied_features
1135                        .iter()
1136                        .copied()
1137                        .filter(|name| {
1138                            // Imply only target features which the user can toggle
1139                            feature_stability
1140                                .get(name)
1141                                .map(|stability| stability.toggle_allowed().is_ok())
1142                                .unwrap_or(false)
1143                        })
1144                        .map(String::from)
1145                        .collect(),
1146                    globally_enabled: globally_enabled_features.contains(name),
1147                }
1148            })
1149            .collect(),
1150    }
1151}