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.
5 #![allow(rustc::default_hash_types)]
7 use std::convert::From;
11 use rustc_hir::{def::CtorKind, def::DefKind, def_id::DefId};
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_span::symbol::sym;
14 use rustc_span::{Pos, Symbol};
15 use rustc_target::spec::abi::Abi as RustcAbi;
17 use rustdoc_json_types::*;
19 use crate::clean::utils::print_const_expr;
20 use crate::clean::{self, ItemId};
21 use crate::formats::item_type::ItemType;
22 use crate::json::JsonRenderer;
23 use crate::passes::collect_intra_doc_links::UrlFragment;
25 impl JsonRenderer<'_> {
26 pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
27 let deprecation = item.deprecation(self.tcx);
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,
41 (link.clone(), from_item_id(id.into(), self.tcx))
44 let docs = item.attrs.collapsed_doc_value();
49 .map(rustc_ast_pretty::pprust::attribute_to_string)
51 let span = item.span(self.tcx);
52 let visibility = item.visibility(self.tcx);
53 let clean::Item { name, attrs: _, kind: _, item_id, cfg: _, .. } = item;
54 let inner = match *item.kind {
55 clean::KeywordItem => return None,
56 clean::StrippedItem(ref inner) => {
58 // We document stripped modules as with `Module::is_stripped` set to
59 // `true`, to prevent contained items from being orphaned for downstream users,
60 // as JSON does no inlining.
62 if self.imported_items.contains(&item_id.expect_def_id()) =>
64 from_clean_item(item, self.tcx)
69 _ => from_clean_item(item, self.tcx),
72 id: from_item_id_with_name(item_id, self.tcx, name),
73 crate_id: item_id.krate().as_u32(),
74 name: name.map(|sym| sym.to_string()),
75 span: span.and_then(|span| self.convert_span(span)),
76 visibility: self.convert_visibility(visibility),
79 deprecation: deprecation.map(from_deprecation),
85 fn convert_span(&self, span: clean::Span) -> Option<Span> {
86 match span.filename(self.sess()) {
87 rustc_span::FileName::Real(name) => {
88 if let Some(local_path) = name.into_local_path() {
89 let hi = span.hi(self.sess());
90 let lo = span.lo(self.sess());
93 begin: (lo.line, lo.col.to_usize()),
94 end: (hi.line, hi.col.to_usize()),
104 fn convert_visibility(&self, v: Option<ty::Visibility<DefId>>) -> Visibility {
106 None => Visibility::Default,
107 Some(ty::Visibility::Public) => Visibility::Public,
108 Some(ty::Visibility::Restricted(did)) if did.is_crate_root() => Visibility::Crate,
109 Some(ty::Visibility::Restricted(did)) => Visibility::Restricted {
110 parent: from_item_id(did.into(), self.tcx),
111 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
117 pub(crate) trait FromWithTcx<T> {
118 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
121 pub(crate) trait IntoWithTcx<T> {
122 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
125 impl<T, U> IntoWithTcx<U> for T
129 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
130 U::from_tcx(self, tcx)
134 impl<I, T, U> FromWithTcx<I> for Vec<U>
136 I: IntoIterator<Item = T>,
139 fn from_tcx(f: I, tcx: TyCtxt<'_>) -> Vec<U> {
140 f.into_iter().map(|x| x.into_tcx(tcx)).collect()
144 pub(crate) fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
146 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
147 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
150 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
151 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
152 use clean::GenericArgs::*;
154 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
155 args: args.into_vec().into_tcx(tcx),
156 bindings: bindings.into_tcx(tcx),
158 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
159 inputs: inputs.into_vec().into_tcx(tcx),
160 output: output.map(|a| (*a).into_tcx(tcx)),
166 impl FromWithTcx<clean::GenericArg> for GenericArg {
167 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
168 use clean::GenericArg::*;
170 Lifetime(l) => GenericArg::Lifetime(convert_lifetime(l)),
171 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
172 Const(box c) => GenericArg::Const(c.into_tcx(tcx)),
173 Infer => GenericArg::Infer,
178 impl FromWithTcx<clean::Constant> for Constant {
179 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
180 let expr = constant.expr(tcx);
181 let value = constant.value(tcx);
182 let is_literal = constant.is_literal(tcx);
183 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
187 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
188 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
190 name: binding.assoc.name.to_string(),
191 args: binding.assoc.args.into_tcx(tcx),
192 binding: binding.kind.into_tcx(tcx),
197 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
198 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
199 use clean::TypeBindingKind::*;
201 Equality { term } => TypeBindingKind::Equality(term.into_tcx(tcx)),
202 Constraint { bounds } => TypeBindingKind::Constraint(bounds.into_tcx(tcx)),
207 /// It generates an ID as follows:
209 /// `CRATE_ID:ITEM_ID[:NAME_ID]` (if there is no name, NAME_ID is not generated).
210 pub(crate) fn from_item_id(item_id: ItemId, tcx: TyCtxt<'_>) -> Id {
211 from_item_id_with_name(item_id, tcx, None)
214 // FIXME: this function (and appending the name at the end of the ID) should be removed when
215 // reexports are not inlined anymore for json format. It should be done in #93518.
216 pub(crate) fn from_item_id_with_name(item_id: ItemId, tcx: TyCtxt<'_>, name: Option<Symbol>) -> Id {
217 struct DisplayDefId<'a>(DefId, TyCtxt<'a>, Option<Symbol>);
219 impl<'a> fmt::Display for DisplayDefId<'a> {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 let DisplayDefId(def_id, tcx, name) = self;
222 let name = match name {
223 Some(name) => format!(":{}", name.as_u32()),
225 // We need this workaround because primitive types' DefId actually refers to
226 // their parent module, which isn't present in the output JSON items. So
227 // instead, we directly get the primitive symbol and convert it to u32 to
229 if matches!(tcx.def_kind(def_id), DefKind::Mod) &&
230 let Some(prim) = tcx.get_attrs(*def_id, sym::doc)
231 .flat_map(|attr| attr.meta_item_list().unwrap_or_default())
232 .filter(|attr| attr.has_name(sym::primitive))
233 .find_map(|attr| attr.value_str()) {
234 format!(":{}", prim.as_u32())
237 .opt_item_name(*def_id)
238 .map(|n| format!(":{}", n.as_u32()))
243 write!(f, "{}:{}{}", self.0.krate.as_u32(), u32::from(self.0.index), name)
248 ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did, tcx, name))),
249 ItemId::Blanket { for_, impl_id } => {
250 Id(format!("b:{}-{}", DisplayDefId(impl_id, tcx, None), DisplayDefId(for_, tcx, name)))
252 ItemId::Auto { for_, trait_ } => {
253 Id(format!("a:{}-{}", DisplayDefId(trait_, tcx, None), DisplayDefId(for_, tcx, name)))
258 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
259 use clean::ItemKind::*;
260 let name = item.name;
261 let is_crate = item.is_crate();
262 let header = item.fn_header(tcx);
266 ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false })
268 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
269 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
270 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
271 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
272 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
273 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
274 FunctionItem(f) => ItemEnum::Function(from_function(f, true, header.unwrap(), tcx)),
275 ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, false, header.unwrap(), tcx)),
276 TraitItem(t) => ItemEnum::Trait((*t).into_tcx(tcx)),
277 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
278 MethodItem(m, _) => ItemEnum::Function(from_function(m, true, header.unwrap(), tcx)),
279 TyMethodItem(m) => ItemEnum::Function(from_function(m, false, header.unwrap(), tcx)),
280 ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)),
281 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
282 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
283 ForeignTypeItem => ItemEnum::ForeignType,
284 TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)),
285 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
286 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
287 MacroItem(m) => ItemEnum::Macro(m.source),
288 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
289 PrimitiveItem(p) => {
290 ItemEnum::Primitive(Primitive {
291 name: p.as_sym().to_string(),
292 impls: Vec::new(), // Added in JsonRenderer::item
295 TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None },
296 AssocConstItem(ty, default) => {
297 ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) }
299 TyAssocTypeItem(g, b) => ItemEnum::AssocType {
300 generics: g.into_tcx(tcx),
301 bounds: b.into_tcx(tcx),
304 AssocTypeItem(t, b) => ItemEnum::AssocType {
305 generics: t.generics.into_tcx(tcx),
306 bounds: b.into_tcx(tcx),
307 default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)),
309 // `convert_item` early returns `None` for stripped items and keywords.
310 KeywordItem => unreachable!(),
311 StrippedItem(inner) => {
313 ModuleItem(m) => ItemEnum::Module(Module {
315 items: ids(m.items, tcx),
318 // `convert_item` early returns `None` for stripped items we're not including
322 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
323 name: name.as_ref().unwrap().to_string(),
324 rename: src.map(|x| x.to_string()),
329 impl FromWithTcx<clean::Struct> for Struct {
330 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
331 let fields_stripped = struct_.has_stripped_entries();
332 let clean::Struct { ctor_kind, generics, fields } = struct_;
334 let kind = match ctor_kind {
335 Some(CtorKind::Fn) => StructKind::Tuple(ids_keeping_stripped(fields, tcx)),
336 Some(CtorKind::Const) => {
337 assert!(fields.is_empty());
340 None => StructKind::Plain { fields: ids(fields, tcx), fields_stripped },
345 generics: generics.into_tcx(tcx),
346 impls: Vec::new(), // Added in JsonRenderer::item
351 impl FromWithTcx<clean::Union> for Union {
352 fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self {
353 let fields_stripped = union_.has_stripped_entries();
354 let clean::Union { generics, fields } = union_;
356 generics: generics.into_tcx(tcx),
358 fields: ids(fields, tcx),
359 impls: Vec::new(), // Added in JsonRenderer::item
364 pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header {
366 async_: header.is_async(),
367 const_: header.is_const(),
368 unsafe_: header.is_unsafe(),
369 abi: convert_abi(header.abi),
373 fn convert_abi(a: RustcAbi) -> Abi {
375 RustcAbi::Rust => Abi::Rust,
376 RustcAbi::C { unwind } => Abi::C { unwind },
377 RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
378 RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
379 RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
380 RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
381 RustcAbi::Win64 { unwind } => Abi::Win64 { unwind },
382 RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
383 RustcAbi::System { unwind } => Abi::System { unwind },
384 _ => Abi::Other(a.to_string()),
388 fn convert_lifetime(l: clean::Lifetime) -> String {
392 impl FromWithTcx<clean::Generics> for Generics {
393 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
395 params: generics.params.into_tcx(tcx),
396 where_predicates: generics.where_predicates.into_tcx(tcx),
401 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
402 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
404 name: generic_param.name.to_string(),
405 kind: generic_param.kind.into_tcx(tcx),
410 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
411 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
412 use clean::GenericParamDefKind::*;
414 Lifetime { outlives } => GenericParamDefKind::Lifetime {
415 outlives: outlives.into_iter().map(convert_lifetime).collect(),
417 Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type {
418 bounds: bounds.into_tcx(tcx),
419 default: default.map(|x| (*x).into_tcx(tcx)),
422 Const { did: _, ty, default } => GenericParamDefKind::Const {
423 type_: (*ty).into_tcx(tcx),
424 default: default.map(|x| *x),
430 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
431 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
432 use clean::WherePredicate::*;
434 BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
435 type_: ty.into_tcx(tcx),
436 bounds: bounds.into_tcx(tcx),
437 generic_params: bound_params
439 .map(|x| GenericParamDef {
440 name: x.0.to_string(),
441 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
445 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
446 lifetime: convert_lifetime(lifetime),
447 bounds: bounds.into_tcx(tcx),
449 // FIXME(fmease): Convert bound parameters as well.
450 EqPredicate { lhs, rhs, bound_params: _ } => {
451 WherePredicate::EqPredicate { lhs: (*lhs).into_tcx(tcx), rhs: (*rhs).into_tcx(tcx) }
457 impl FromWithTcx<clean::GenericBound> for GenericBound {
458 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
459 use clean::GenericBound::*;
461 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
462 GenericBound::TraitBound {
463 trait_: trait_.into_tcx(tcx),
464 generic_params: generic_params.into_tcx(tcx),
465 modifier: from_trait_bound_modifier(modifier),
468 Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
473 pub(crate) fn from_trait_bound_modifier(
474 modifier: rustc_hir::TraitBoundModifier,
475 ) -> TraitBoundModifier {
476 use rustc_hir::TraitBoundModifier::*;
478 None => TraitBoundModifier::None,
479 Maybe => TraitBoundModifier::Maybe,
480 MaybeConst => TraitBoundModifier::MaybeConst,
484 impl FromWithTcx<clean::Type> for Type {
485 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
487 Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
488 RawPointer, Slice, Tuple,
492 clean::Type::Path { path } => Type::ResolvedPath(path.into_tcx(tcx)),
493 clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
494 lifetime: lt.map(convert_lifetime),
495 traits: bounds.into_tcx(tcx),
497 Generic(s) => Type::Generic(s.to_string()),
498 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
499 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
500 Tuple(t) => Type::Tuple(t.into_tcx(tcx)),
501 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
502 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s.to_string() },
503 ImplTrait(g) => Type::ImplTrait(g.into_tcx(tcx)),
504 Infer => Type::Infer,
505 RawPointer(mutability, type_) => Type::RawPointer {
506 mutable: mutability == ast::Mutability::Mut,
507 type_: Box::new((*type_).into_tcx(tcx)),
509 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
510 lifetime: lifetime.map(convert_lifetime),
511 mutable: mutability == ast::Mutability::Mut,
512 type_: Box::new((*type_).into_tcx(tcx)),
514 QPath(box clean::QPathData { assoc, self_type, trait_, .. }) => Type::QualifiedPath {
515 name: assoc.name.to_string(),
516 args: Box::new(assoc.args.into_tcx(tcx)),
517 self_type: Box::new(self_type.into_tcx(tcx)),
518 trait_: trait_.into_tcx(tcx),
524 impl FromWithTcx<clean::Path> for Path {
525 fn from_tcx(path: clean::Path, tcx: TyCtxt<'_>) -> Path {
527 name: path.whole_name(),
528 id: from_item_id(path.def_id().into(), tcx),
529 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
534 impl FromWithTcx<clean::Term> for Term {
535 fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
537 clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
538 clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
543 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
544 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
545 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
548 unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe),
551 abi: convert_abi(abi),
553 generic_params: generic_params.into_tcx(tcx),
554 decl: decl.into_tcx(tcx),
559 impl FromWithTcx<clean::FnDecl> for FnDecl {
560 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
561 let clean::FnDecl { inputs, output, c_variadic } = decl;
566 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
568 output: match output {
569 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
570 clean::FnRetTy::DefaultReturn => None,
577 impl FromWithTcx<clean::Trait> for Trait {
578 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
579 let is_auto = trait_.is_auto(tcx);
580 let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe;
581 let clean::Trait { items, generics, bounds, .. } = trait_;
585 items: ids(items, tcx),
586 generics: generics.into_tcx(tcx),
587 bounds: bounds.into_tcx(tcx),
588 implementations: Vec::new(), // Added in JsonRenderer::item
593 impl FromWithTcx<clean::PolyTrait> for PolyTrait {
595 clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
598 PolyTrait { trait_: trait_.into_tcx(tcx), generic_params: generic_params.into_tcx(tcx) }
602 impl FromWithTcx<clean::Impl> for Impl {
603 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
604 let provided_trait_methods = impl_.provided_trait_methods(tcx);
605 let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
606 // FIXME: use something like ImplKind in JSON?
607 let (synthetic, blanket_impl) = match kind {
608 clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
609 clean::ImplKind::Auto => (true, None),
610 clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
612 let negative_polarity = match polarity {
613 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
614 ty::ImplPolarity::Negative => true,
617 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
618 generics: generics.into_tcx(tcx),
619 provided_trait_methods: provided_trait_methods
621 .map(|x| x.to_string())
623 trait_: trait_.map(|path| path.into_tcx(tcx)),
624 for_: for_.into_tcx(tcx),
625 items: ids(items, tcx),
626 negative: negative_polarity,
628 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
633 pub(crate) fn from_function(
634 function: Box<clean::Function>,
636 header: rustc_hir::FnHeader,
639 let clean::Function { decl, generics } = *function;
641 decl: decl.into_tcx(tcx),
642 generics: generics.into_tcx(tcx),
643 header: from_fn_header(&header),
648 impl FromWithTcx<clean::Enum> for Enum {
649 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
650 let variants_stripped = enum_.has_stripped_entries();
651 let clean::Enum { variants, generics } = enum_;
653 generics: generics.into_tcx(tcx),
655 variants: ids(variants, tcx),
656 impls: Vec::new(), // Added in JsonRenderer::item
661 impl FromWithTcx<clean::Variant> for Variant {
662 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
663 use clean::VariantKind::*;
665 let discriminant = variant.discriminant.map(|d| d.into_tcx(tcx));
667 let kind = match variant.kind {
668 CLike => VariantKind::Plain,
669 Tuple(fields) => VariantKind::Tuple(ids_keeping_stripped(fields, tcx)),
670 Struct(s) => VariantKind::Struct {
671 fields_stripped: s.has_stripped_entries(),
672 fields: ids(s.fields, tcx),
676 Variant { kind, discriminant }
680 impl FromWithTcx<clean::Discriminant> for Discriminant {
681 fn from_tcx(disr: clean::Discriminant, tcx: TyCtxt<'_>) -> Self {
683 // expr is only none if going through the inlineing path, which gets
684 // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
685 // the expr is always some.
686 expr: disr.expr(tcx).unwrap(),
687 value: disr.value(tcx),
692 impl FromWithTcx<clean::Import> for Import {
693 fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
694 use clean::ImportKind::*;
695 let (name, glob) = match import.kind {
696 Simple(s) => (s.to_string(), false),
698 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
703 source: import.source.path.whole_name(),
705 id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
711 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
712 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
714 kind: from_macro_kind(mac.kind),
715 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
720 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
721 use rustc_span::hygiene::MacroKind::*;
723 Bang => MacroKind::Bang,
724 Attr => MacroKind::Attr,
725 Derive => MacroKind::Derive,
729 impl FromWithTcx<Box<clean::Typedef>> for Typedef {
730 fn from_tcx(typedef: Box<clean::Typedef>, tcx: TyCtxt<'_>) -> Self {
731 let clean::Typedef { type_, generics, item_type: _ } = *typedef;
732 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
736 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
737 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
738 OpaqueTy { bounds: opaque.bounds.into_tcx(tcx), generics: opaque.generics.into_tcx(tcx) }
742 impl FromWithTcx<clean::Static> for Static {
743 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
745 type_: stat.type_.into_tcx(tcx),
746 mutable: stat.mutability == ast::Mutability::Mut,
747 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
752 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
753 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
754 TraitAlias { generics: alias.generics.into_tcx(tcx), params: alias.bounds.into_tcx(tcx) }
758 impl FromWithTcx<ItemType> for ItemKind {
759 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
762 Module => ItemKind::Module,
763 ExternCrate => ItemKind::ExternCrate,
764 Import => ItemKind::Import,
765 Struct => ItemKind::Struct,
766 Union => ItemKind::Union,
767 Enum => ItemKind::Enum,
768 Function | TyMethod | Method => ItemKind::Function,
769 Typedef => ItemKind::Typedef,
770 OpaqueTy => ItemKind::OpaqueTy,
771 Static => ItemKind::Static,
772 Constant => ItemKind::Constant,
773 Trait => ItemKind::Trait,
774 Impl => ItemKind::Impl,
775 StructField => ItemKind::StructField,
776 Variant => ItemKind::Variant,
777 Macro => ItemKind::Macro,
778 Primitive => ItemKind::Primitive,
779 AssocConst => ItemKind::AssocConst,
780 AssocType => ItemKind::AssocType,
781 ForeignType => ItemKind::ForeignType,
782 Keyword => ItemKind::Keyword,
783 TraitAlias => ItemKind::TraitAlias,
784 ProcAttribute => ItemKind::ProcAttribute,
785 ProcDerive => ItemKind::ProcDerive,
790 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
793 .filter(|x| !x.is_stripped() && !x.is_keyword())
794 .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
798 fn ids_keeping_stripped(
799 items: impl IntoIterator<Item = clean::Item>,
801 ) -> Vec<Option<Id>> {
805 if !i.is_stripped() && !i.is_keyword() {
806 Some(from_item_id_with_name(i.item_id, tcx, i.name))