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