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)))
255 ItemId::Primitive(_, _) => unreachable!(),
259 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
260 use clean::ItemKind::*;
261 let name = item.name;
262 let is_crate = item.is_crate();
263 let header = item.fn_header(tcx);
267 ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false })
269 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
270 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
271 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
272 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
273 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
274 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
275 FunctionItem(f) => ItemEnum::Function(from_function(f, true, header.unwrap(), tcx)),
276 ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, false, header.unwrap(), tcx)),
277 TraitItem(t) => ItemEnum::Trait((*t).into_tcx(tcx)),
278 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
279 MethodItem(m, _) => ItemEnum::Function(from_function(m, true, header.unwrap(), tcx)),
280 TyMethodItem(m) => ItemEnum::Function(from_function(m, false, header.unwrap(), tcx)),
281 ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)),
282 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
283 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
284 ForeignTypeItem => ItemEnum::ForeignType,
285 TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)),
286 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
287 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
288 MacroItem(m) => ItemEnum::Macro(m.source),
289 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
290 PrimitiveItem(p) => {
291 ItemEnum::Primitive(Primitive {
292 name: p.as_sym().to_string(),
293 impls: Vec::new(), // Added in JsonRenderer::item
296 TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None },
297 AssocConstItem(ty, default) => {
298 ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) }
300 TyAssocTypeItem(g, b) => ItemEnum::AssocType {
301 generics: g.into_tcx(tcx),
302 bounds: b.into_tcx(tcx),
305 AssocTypeItem(t, b) => ItemEnum::AssocType {
306 generics: t.generics.into_tcx(tcx),
307 bounds: b.into_tcx(tcx),
308 default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)),
310 // `convert_item` early returns `None` for stripped items and keywords.
311 KeywordItem => unreachable!(),
312 StrippedItem(inner) => {
314 ModuleItem(m) => ItemEnum::Module(Module {
316 items: ids(m.items, tcx),
319 // `convert_item` early returns `None` for stripped items we're not including
323 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
324 name: name.as_ref().unwrap().to_string(),
325 rename: src.map(|x| x.to_string()),
330 impl FromWithTcx<clean::Struct> for Struct {
331 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
332 let fields_stripped = struct_.has_stripped_entries();
333 let clean::Struct { ctor_kind, generics, fields } = struct_;
335 let kind = match ctor_kind {
336 Some(CtorKind::Fn) => StructKind::Tuple(ids_keeping_stripped(fields, tcx)),
337 Some(CtorKind::Const) => {
338 assert!(fields.is_empty());
341 None => StructKind::Plain { fields: ids(fields, tcx), fields_stripped },
346 generics: generics.into_tcx(tcx),
347 impls: Vec::new(), // Added in JsonRenderer::item
352 impl FromWithTcx<clean::Union> for Union {
353 fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self {
354 let fields_stripped = union_.has_stripped_entries();
355 let clean::Union { generics, fields } = union_;
357 generics: generics.into_tcx(tcx),
359 fields: ids(fields, tcx),
360 impls: Vec::new(), // Added in JsonRenderer::item
365 pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header {
367 async_: header.is_async(),
368 const_: header.is_const(),
369 unsafe_: header.is_unsafe(),
370 abi: convert_abi(header.abi),
374 fn convert_abi(a: RustcAbi) -> Abi {
376 RustcAbi::Rust => Abi::Rust,
377 RustcAbi::C { unwind } => Abi::C { unwind },
378 RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
379 RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
380 RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
381 RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
382 RustcAbi::Win64 { unwind } => Abi::Win64 { unwind },
383 RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
384 RustcAbi::System { unwind } => Abi::System { unwind },
385 _ => Abi::Other(a.to_string()),
389 fn convert_lifetime(l: clean::Lifetime) -> String {
393 impl FromWithTcx<clean::Generics> for Generics {
394 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
396 params: generics.params.into_tcx(tcx),
397 where_predicates: generics.where_predicates.into_tcx(tcx),
402 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
403 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
405 name: generic_param.name.to_string(),
406 kind: generic_param.kind.into_tcx(tcx),
411 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
412 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
413 use clean::GenericParamDefKind::*;
415 Lifetime { outlives } => GenericParamDefKind::Lifetime {
416 outlives: outlives.into_iter().map(convert_lifetime).collect(),
418 Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type {
419 bounds: bounds.into_tcx(tcx),
420 default: default.map(|x| (*x).into_tcx(tcx)),
423 Const { did: _, ty, default } => GenericParamDefKind::Const {
424 type_: (*ty).into_tcx(tcx),
425 default: default.map(|x| *x),
431 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
432 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
433 use clean::WherePredicate::*;
435 BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
436 type_: ty.into_tcx(tcx),
437 bounds: bounds.into_tcx(tcx),
438 generic_params: bound_params
440 .map(|x| GenericParamDef {
441 name: x.0.to_string(),
442 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
446 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
447 lifetime: convert_lifetime(lifetime),
448 bounds: bounds.into_tcx(tcx),
450 // FIXME(fmease): Convert bound parameters as well.
451 EqPredicate { lhs, rhs, bound_params: _ } => {
452 WherePredicate::EqPredicate { lhs: (*lhs).into_tcx(tcx), rhs: (*rhs).into_tcx(tcx) }
458 impl FromWithTcx<clean::GenericBound> for GenericBound {
459 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
460 use clean::GenericBound::*;
462 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
463 GenericBound::TraitBound {
464 trait_: trait_.into_tcx(tcx),
465 generic_params: generic_params.into_tcx(tcx),
466 modifier: from_trait_bound_modifier(modifier),
469 Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
474 pub(crate) fn from_trait_bound_modifier(
475 modifier: rustc_hir::TraitBoundModifier,
476 ) -> TraitBoundModifier {
477 use rustc_hir::TraitBoundModifier::*;
479 None => TraitBoundModifier::None,
480 Maybe => TraitBoundModifier::Maybe,
481 MaybeConst => TraitBoundModifier::MaybeConst,
485 impl FromWithTcx<clean::Type> for Type {
486 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
488 Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
489 RawPointer, Slice, Tuple,
493 clean::Type::Path { path } => Type::ResolvedPath(path.into_tcx(tcx)),
494 clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
495 lifetime: lt.map(convert_lifetime),
496 traits: bounds.into_tcx(tcx),
498 Generic(s) => Type::Generic(s.to_string()),
499 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
500 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
501 Tuple(t) => Type::Tuple(t.into_tcx(tcx)),
502 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
503 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s.to_string() },
504 ImplTrait(g) => Type::ImplTrait(g.into_tcx(tcx)),
505 Infer => Type::Infer,
506 RawPointer(mutability, type_) => Type::RawPointer {
507 mutable: mutability == ast::Mutability::Mut,
508 type_: Box::new((*type_).into_tcx(tcx)),
510 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
511 lifetime: lifetime.map(convert_lifetime),
512 mutable: mutability == ast::Mutability::Mut,
513 type_: Box::new((*type_).into_tcx(tcx)),
515 QPath(box clean::QPathData { assoc, self_type, trait_, .. }) => Type::QualifiedPath {
516 name: assoc.name.to_string(),
517 args: Box::new(assoc.args.into_tcx(tcx)),
518 self_type: Box::new(self_type.into_tcx(tcx)),
519 trait_: trait_.into_tcx(tcx),
525 impl FromWithTcx<clean::Path> for Path {
526 fn from_tcx(path: clean::Path, tcx: TyCtxt<'_>) -> Path {
528 name: path.whole_name(),
529 id: from_item_id(path.def_id().into(), tcx),
530 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
535 impl FromWithTcx<clean::Term> for Term {
536 fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
538 clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
539 clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
544 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
545 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
546 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
549 unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe),
552 abi: convert_abi(abi),
554 generic_params: generic_params.into_tcx(tcx),
555 decl: decl.into_tcx(tcx),
560 impl FromWithTcx<clean::FnDecl> for FnDecl {
561 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
562 let clean::FnDecl { inputs, output, c_variadic } = decl;
567 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
569 output: match output {
570 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
571 clean::FnRetTy::DefaultReturn => None,
578 impl FromWithTcx<clean::Trait> for Trait {
579 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
580 let is_auto = trait_.is_auto(tcx);
581 let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe;
582 let clean::Trait { items, generics, bounds, .. } = trait_;
586 items: ids(items, tcx),
587 generics: generics.into_tcx(tcx),
588 bounds: bounds.into_tcx(tcx),
589 implementations: Vec::new(), // Added in JsonRenderer::item
594 impl FromWithTcx<clean::PolyTrait> for PolyTrait {
596 clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
599 PolyTrait { trait_: trait_.into_tcx(tcx), generic_params: generic_params.into_tcx(tcx) }
603 impl FromWithTcx<clean::Impl> for Impl {
604 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
605 let provided_trait_methods = impl_.provided_trait_methods(tcx);
606 let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
607 // FIXME: use something like ImplKind in JSON?
608 let (synthetic, blanket_impl) = match kind {
609 clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
610 clean::ImplKind::Auto => (true, None),
611 clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
613 let negative_polarity = match polarity {
614 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
615 ty::ImplPolarity::Negative => true,
618 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
619 generics: generics.into_tcx(tcx),
620 provided_trait_methods: provided_trait_methods
622 .map(|x| x.to_string())
624 trait_: trait_.map(|path| path.into_tcx(tcx)),
625 for_: for_.into_tcx(tcx),
626 items: ids(items, tcx),
627 negative: negative_polarity,
629 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
634 pub(crate) fn from_function(
635 function: Box<clean::Function>,
637 header: rustc_hir::FnHeader,
640 let clean::Function { decl, generics } = *function;
642 decl: decl.into_tcx(tcx),
643 generics: generics.into_tcx(tcx),
644 header: from_fn_header(&header),
649 impl FromWithTcx<clean::Enum> for Enum {
650 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
651 let variants_stripped = enum_.has_stripped_entries();
652 let clean::Enum { variants, generics } = enum_;
654 generics: generics.into_tcx(tcx),
656 variants: ids(variants, tcx),
657 impls: Vec::new(), // Added in JsonRenderer::item
662 impl FromWithTcx<clean::Variant> for Variant {
663 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
664 use clean::VariantKind::*;
666 let discriminant = variant.discriminant.map(|d| d.into_tcx(tcx));
668 let kind = match variant.kind {
669 CLike => VariantKind::Plain,
670 Tuple(fields) => VariantKind::Tuple(ids_keeping_stripped(fields, tcx)),
671 Struct(s) => VariantKind::Struct {
672 fields_stripped: s.has_stripped_entries(),
673 fields: ids(s.fields, tcx),
677 Variant { kind, discriminant }
681 impl FromWithTcx<clean::Discriminant> for Discriminant {
682 fn from_tcx(disr: clean::Discriminant, tcx: TyCtxt<'_>) -> Self {
684 // expr is only none if going through the inlineing path, which gets
685 // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
686 // the expr is always some.
687 expr: disr.expr(tcx).unwrap(),
688 value: disr.value(tcx),
693 impl FromWithTcx<clean::Import> for Import {
694 fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
695 use clean::ImportKind::*;
696 let (name, glob) = match import.kind {
697 Simple(s) => (s.to_string(), false),
699 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
704 source: import.source.path.whole_name(),
706 id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
712 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
713 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
715 kind: from_macro_kind(mac.kind),
716 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
721 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
722 use rustc_span::hygiene::MacroKind::*;
724 Bang => MacroKind::Bang,
725 Attr => MacroKind::Attr,
726 Derive => MacroKind::Derive,
730 impl FromWithTcx<Box<clean::Typedef>> for Typedef {
731 fn from_tcx(typedef: Box<clean::Typedef>, tcx: TyCtxt<'_>) -> Self {
732 let clean::Typedef { type_, generics, item_type: _ } = *typedef;
733 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
737 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
738 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
739 OpaqueTy { bounds: opaque.bounds.into_tcx(tcx), generics: opaque.generics.into_tcx(tcx) }
743 impl FromWithTcx<clean::Static> for Static {
744 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
746 type_: stat.type_.into_tcx(tcx),
747 mutable: stat.mutability == ast::Mutability::Mut,
748 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
753 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
754 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
755 TraitAlias { generics: alias.generics.into_tcx(tcx), params: alias.bounds.into_tcx(tcx) }
759 impl FromWithTcx<ItemType> for ItemKind {
760 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
763 Module => ItemKind::Module,
764 ExternCrate => ItemKind::ExternCrate,
765 Import => ItemKind::Import,
766 Struct => ItemKind::Struct,
767 Union => ItemKind::Union,
768 Enum => ItemKind::Enum,
769 Function | TyMethod | Method => ItemKind::Function,
770 Typedef => ItemKind::Typedef,
771 OpaqueTy => ItemKind::OpaqueTy,
772 Static => ItemKind::Static,
773 Constant => ItemKind::Constant,
774 Trait => ItemKind::Trait,
775 Impl => ItemKind::Impl,
776 StructField => ItemKind::StructField,
777 Variant => ItemKind::Variant,
778 Macro => ItemKind::Macro,
779 Primitive => ItemKind::Primitive,
780 AssocConst => ItemKind::AssocConst,
781 AssocType => ItemKind::AssocType,
782 ForeignType => ItemKind::ForeignType,
783 Keyword => ItemKind::Keyword,
784 TraitAlias => ItemKind::TraitAlias,
785 ProcAttribute => ItemKind::ProcAttribute,
786 ProcDerive => ItemKind::ProcDerive,
791 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
794 .filter(|x| !x.is_stripped() && !x.is_keyword())
795 .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
799 fn ids_keeping_stripped(
800 items: impl IntoIterator<Item = clean::Item>,
802 ) -> Vec<Option<Id>> {
806 if !i.is_stripped() && !i.is_keyword() {
807 Some(from_item_id_with_name(i.item_id, tcx, i.name))