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_id::DefId};
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_span::{Pos, Symbol};
14 use rustc_target::spec::abi::Abi as RustcAbi;
16 use rustdoc_json_types::*;
18 use crate::clean::utils::print_const_expr;
19 use crate::clean::{self, ItemId};
20 use crate::formats::item_type::ItemType;
21 use crate::json::JsonRenderer;
22 use crate::passes::collect_intra_doc_links::UrlFragment;
24 impl JsonRenderer<'_> {
25 pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
26 let deprecation = item.deprecation(self.tcx);
33 .map(|clean::ItemLink { link, page_id, fragment, .. }| {
34 let id = match fragment {
35 Some(UrlFragment::Item(frag_id)) => *frag_id,
36 // FIXME: Pass the `UserWritten` segment to JSON consumer.
37 Some(UrlFragment::UserWritten(_)) | None => *page_id,
40 (link.clone(), from_item_id(id.into(), self.tcx))
43 let docs = item.attrs.collapsed_doc_value();
48 .map(rustc_ast_pretty::pprust::attribute_to_string)
50 let span = item.span(self.tcx);
51 let visibility = item.visibility(self.tcx);
52 let clean::Item { name, attrs: _, kind: _, item_id, cfg: _, .. } = item;
53 let inner = match *item.kind {
54 clean::KeywordItem => return None,
55 clean::StrippedItem(ref inner) => {
57 // We document stripped modules as with `Module::is_stripped` set to
58 // `true`, to prevent contained items from being orphaned for downstream users,
59 // as JSON does no inlining.
61 if self.imported_items.contains(&item_id.expect_def_id()) =>
63 from_clean_item(item, self.tcx)
68 _ => from_clean_item(item, self.tcx),
71 id: from_item_id_with_name(item_id, self.tcx, name),
72 crate_id: item_id.krate().as_u32(),
73 name: name.map(|sym| sym.to_string()),
74 span: span.and_then(|span| self.convert_span(span)),
75 visibility: self.convert_visibility(visibility),
78 deprecation: deprecation.map(from_deprecation),
84 fn convert_span(&self, span: clean::Span) -> Option<Span> {
85 match span.filename(self.sess()) {
86 rustc_span::FileName::Real(name) => {
87 if let Some(local_path) = name.into_local_path() {
88 let hi = span.hi(self.sess());
89 let lo = span.lo(self.sess());
92 begin: (lo.line, lo.col.to_usize()),
93 end: (hi.line, hi.col.to_usize()),
103 fn convert_visibility(&self, v: Option<ty::Visibility<DefId>>) -> Visibility {
105 None => Visibility::Default,
106 Some(ty::Visibility::Public) => Visibility::Public,
107 Some(ty::Visibility::Restricted(did)) if did.is_crate_root() => Visibility::Crate,
108 Some(ty::Visibility::Restricted(did)) => Visibility::Restricted {
109 parent: from_item_id(did.into(), self.tcx),
110 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
116 pub(crate) trait FromWithTcx<T> {
117 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
120 pub(crate) trait IntoWithTcx<T> {
121 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
124 impl<T, U> IntoWithTcx<U> for T
128 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
129 U::from_tcx(self, tcx)
133 impl<I, T, U> FromWithTcx<I> for Vec<U>
135 I: IntoIterator<Item = T>,
138 fn from_tcx(f: I, tcx: TyCtxt<'_>) -> Vec<U> {
139 f.into_iter().map(|x| x.into_tcx(tcx)).collect()
143 pub(crate) fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
145 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
146 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
149 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
150 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
151 use clean::GenericArgs::*;
153 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
154 args: args.into_vec().into_tcx(tcx),
155 bindings: bindings.into_tcx(tcx),
157 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
158 inputs: inputs.into_vec().into_tcx(tcx),
159 output: output.map(|a| (*a).into_tcx(tcx)),
165 impl FromWithTcx<clean::GenericArg> for GenericArg {
166 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
167 use clean::GenericArg::*;
169 Lifetime(l) => GenericArg::Lifetime(convert_lifetime(l)),
170 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
171 Const(box c) => GenericArg::Const(c.into_tcx(tcx)),
172 Infer => GenericArg::Infer,
177 impl FromWithTcx<clean::Constant> for Constant {
178 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
179 let expr = constant.expr(tcx);
180 let value = constant.value(tcx);
181 let is_literal = constant.is_literal(tcx);
182 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
186 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
187 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
189 name: binding.assoc.name.to_string(),
190 args: binding.assoc.args.into_tcx(tcx),
191 binding: binding.kind.into_tcx(tcx),
196 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
197 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
198 use clean::TypeBindingKind::*;
200 Equality { term } => TypeBindingKind::Equality(term.into_tcx(tcx)),
201 Constraint { bounds } => TypeBindingKind::Constraint(bounds.into_tcx(tcx)),
206 /// It generates an ID as follows:
208 /// `CRATE_ID:ITEM_ID[:NAME_ID]` (if there is no name, NAME_ID is not generated).
209 pub(crate) fn from_item_id(item_id: ItemId, tcx: TyCtxt<'_>) -> Id {
210 from_item_id_with_name(item_id, tcx, None)
213 // FIXME: this function (and appending the name at the end of the ID) should be removed when
214 // reexports are not inlined anymore for json format. It should be done in #93518.
215 pub(crate) fn from_item_id_with_name(item_id: ItemId, tcx: TyCtxt<'_>, name: Option<Symbol>) -> Id {
216 struct DisplayDefId<'a>(DefId, TyCtxt<'a>, Option<Symbol>);
218 impl<'a> fmt::Display for DisplayDefId<'a> {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 let name = match self.2 {
221 Some(name) => format!(":{}", name.as_u32()),
224 .opt_item_name(self.0)
225 .map(|n| format!(":{}", n.as_u32()))
226 .unwrap_or_default(),
228 write!(f, "{}:{}{}", self.0.krate.as_u32(), u32::from(self.0.index), name)
233 ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did, tcx, name))),
234 ItemId::Blanket { for_, impl_id } => {
235 Id(format!("b:{}-{}", DisplayDefId(impl_id, tcx, None), DisplayDefId(for_, tcx, name)))
237 ItemId::Auto { for_, trait_ } => {
238 Id(format!("a:{}-{}", DisplayDefId(trait_, tcx, None), DisplayDefId(for_, tcx, name)))
240 ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())),
244 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
245 use clean::ItemKind::*;
246 let name = item.name;
247 let is_crate = item.is_crate();
248 let header = item.fn_header(tcx);
252 ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false })
254 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
255 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
256 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
257 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
258 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
259 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
260 FunctionItem(f) => ItemEnum::Function(from_function(f, true, header.unwrap(), tcx)),
261 ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, false, header.unwrap(), tcx)),
262 TraitItem(t) => ItemEnum::Trait((*t).into_tcx(tcx)),
263 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
264 MethodItem(m, _) => ItemEnum::Function(from_function(m, true, header.unwrap(), tcx)),
265 TyMethodItem(m) => ItemEnum::Function(from_function(m, false, header.unwrap(), tcx)),
266 ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)),
267 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
268 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
269 ForeignTypeItem => ItemEnum::ForeignType,
270 TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)),
271 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
272 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
273 MacroItem(m) => ItemEnum::Macro(m.source),
274 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
275 PrimitiveItem(p) => {
276 ItemEnum::Primitive(Primitive {
277 name: p.as_sym().to_string(),
278 impls: Vec::new(), // Added in JsonRenderer::item
281 TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None },
282 AssocConstItem(ty, default) => {
283 ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) }
285 TyAssocTypeItem(g, b) => ItemEnum::AssocType {
286 generics: g.into_tcx(tcx),
287 bounds: b.into_tcx(tcx),
290 AssocTypeItem(t, b) => ItemEnum::AssocType {
291 generics: t.generics.into_tcx(tcx),
292 bounds: b.into_tcx(tcx),
293 default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)),
295 // `convert_item` early returns `None` for stripped items and keywords.
296 KeywordItem => unreachable!(),
297 StrippedItem(inner) => {
299 ModuleItem(m) => ItemEnum::Module(Module {
301 items: ids(m.items, tcx),
304 // `convert_item` early returns `None` for stripped items we're not including
308 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
309 name: name.as_ref().unwrap().to_string(),
310 rename: src.map(|x| x.to_string()),
315 impl FromWithTcx<clean::Struct> for Struct {
316 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
317 let fields_stripped = struct_.has_stripped_entries();
318 let clean::Struct { ctor_kind, generics, fields } = struct_;
320 let kind = match ctor_kind {
321 Some(CtorKind::Fn) => StructKind::Tuple(ids_keeping_stripped(fields, tcx)),
322 Some(CtorKind::Const) => {
323 assert!(fields.is_empty());
326 None => StructKind::Plain { fields: ids(fields, tcx), fields_stripped },
331 generics: generics.into_tcx(tcx),
332 impls: Vec::new(), // Added in JsonRenderer::item
337 impl FromWithTcx<clean::Union> for Union {
338 fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self {
339 let fields_stripped = union_.has_stripped_entries();
340 let clean::Union { generics, fields } = union_;
342 generics: generics.into_tcx(tcx),
344 fields: ids(fields, tcx),
345 impls: Vec::new(), // Added in JsonRenderer::item
350 pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header {
352 async_: header.is_async(),
353 const_: header.is_const(),
354 unsafe_: header.is_unsafe(),
355 abi: convert_abi(header.abi),
359 fn convert_abi(a: RustcAbi) -> Abi {
361 RustcAbi::Rust => Abi::Rust,
362 RustcAbi::C { unwind } => Abi::C { unwind },
363 RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
364 RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
365 RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
366 RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
367 RustcAbi::Win64 { unwind } => Abi::Win64 { unwind },
368 RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
369 RustcAbi::System { unwind } => Abi::System { unwind },
370 _ => Abi::Other(a.to_string()),
374 fn convert_lifetime(l: clean::Lifetime) -> String {
378 impl FromWithTcx<clean::Generics> for Generics {
379 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
381 params: generics.params.into_tcx(tcx),
382 where_predicates: generics.where_predicates.into_tcx(tcx),
387 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
388 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
390 name: generic_param.name.to_string(),
391 kind: generic_param.kind.into_tcx(tcx),
396 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
397 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
398 use clean::GenericParamDefKind::*;
400 Lifetime { outlives } => GenericParamDefKind::Lifetime {
401 outlives: outlives.into_iter().map(convert_lifetime).collect(),
403 Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type {
404 bounds: bounds.into_tcx(tcx),
405 default: default.map(|x| (*x).into_tcx(tcx)),
408 Const { did: _, ty, default } => GenericParamDefKind::Const {
409 type_: (*ty).into_tcx(tcx),
410 default: default.map(|x| *x),
416 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
417 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
418 use clean::WherePredicate::*;
420 BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
421 type_: ty.into_tcx(tcx),
422 bounds: bounds.into_tcx(tcx),
423 generic_params: bound_params
425 .map(|x| GenericParamDef {
426 name: x.0.to_string(),
427 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
431 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
432 lifetime: convert_lifetime(lifetime),
433 bounds: bounds.into_tcx(tcx),
435 // FIXME(fmease): Convert bound parameters as well.
436 EqPredicate { lhs, rhs, bound_params: _ } => {
437 WherePredicate::EqPredicate { lhs: (*lhs).into_tcx(tcx), rhs: (*rhs).into_tcx(tcx) }
443 impl FromWithTcx<clean::GenericBound> for GenericBound {
444 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
445 use clean::GenericBound::*;
447 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
448 GenericBound::TraitBound {
449 trait_: trait_.into_tcx(tcx),
450 generic_params: generic_params.into_tcx(tcx),
451 modifier: from_trait_bound_modifier(modifier),
454 Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
459 pub(crate) fn from_trait_bound_modifier(
460 modifier: rustc_hir::TraitBoundModifier,
461 ) -> TraitBoundModifier {
462 use rustc_hir::TraitBoundModifier::*;
464 None => TraitBoundModifier::None,
465 Maybe => TraitBoundModifier::Maybe,
466 MaybeConst => TraitBoundModifier::MaybeConst,
470 impl FromWithTcx<clean::Type> for Type {
471 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
473 Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
474 RawPointer, Slice, Tuple,
478 clean::Type::Path { path } => Type::ResolvedPath(path.into_tcx(tcx)),
479 clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
480 lifetime: lt.map(convert_lifetime),
481 traits: bounds.into_tcx(tcx),
483 Generic(s) => Type::Generic(s.to_string()),
484 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
485 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
486 Tuple(t) => Type::Tuple(t.into_tcx(tcx)),
487 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
488 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s.to_string() },
489 ImplTrait(g) => Type::ImplTrait(g.into_tcx(tcx)),
490 Infer => Type::Infer,
491 RawPointer(mutability, type_) => Type::RawPointer {
492 mutable: mutability == ast::Mutability::Mut,
493 type_: Box::new((*type_).into_tcx(tcx)),
495 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
496 lifetime: lifetime.map(convert_lifetime),
497 mutable: mutability == ast::Mutability::Mut,
498 type_: Box::new((*type_).into_tcx(tcx)),
500 QPath(box clean::QPathData { assoc, self_type, trait_, .. }) => Type::QualifiedPath {
501 name: assoc.name.to_string(),
502 args: Box::new(assoc.args.into_tcx(tcx)),
503 self_type: Box::new(self_type.into_tcx(tcx)),
504 trait_: trait_.into_tcx(tcx),
510 impl FromWithTcx<clean::Path> for Path {
511 fn from_tcx(path: clean::Path, tcx: TyCtxt<'_>) -> Path {
513 name: path.whole_name(),
514 id: from_item_id(path.def_id().into(), tcx),
515 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
520 impl FromWithTcx<clean::Term> for Term {
521 fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
523 clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
524 clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
529 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
530 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
531 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
534 unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe),
537 abi: convert_abi(abi),
539 generic_params: generic_params.into_tcx(tcx),
540 decl: decl.into_tcx(tcx),
545 impl FromWithTcx<clean::FnDecl> for FnDecl {
546 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
547 let clean::FnDecl { inputs, output, c_variadic } = decl;
552 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
554 output: match output {
555 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
556 clean::FnRetTy::DefaultReturn => None,
563 impl FromWithTcx<clean::Trait> for Trait {
564 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
565 let is_auto = trait_.is_auto(tcx);
566 let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe;
567 let clean::Trait { items, generics, bounds, .. } = trait_;
571 items: ids(items, tcx),
572 generics: generics.into_tcx(tcx),
573 bounds: bounds.into_tcx(tcx),
574 implementations: Vec::new(), // Added in JsonRenderer::item
579 impl FromWithTcx<clean::PolyTrait> for PolyTrait {
581 clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
584 PolyTrait { trait_: trait_.into_tcx(tcx), generic_params: generic_params.into_tcx(tcx) }
588 impl FromWithTcx<clean::Impl> for Impl {
589 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
590 let provided_trait_methods = impl_.provided_trait_methods(tcx);
591 let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
592 // FIXME: use something like ImplKind in JSON?
593 let (synthetic, blanket_impl) = match kind {
594 clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
595 clean::ImplKind::Auto => (true, None),
596 clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
598 let negative_polarity = match polarity {
599 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
600 ty::ImplPolarity::Negative => true,
603 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
604 generics: generics.into_tcx(tcx),
605 provided_trait_methods: provided_trait_methods
607 .map(|x| x.to_string())
609 trait_: trait_.map(|path| path.into_tcx(tcx)),
610 for_: for_.into_tcx(tcx),
611 items: ids(items, tcx),
612 negative: negative_polarity,
614 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
619 pub(crate) fn from_function(
620 function: Box<clean::Function>,
622 header: rustc_hir::FnHeader,
625 let clean::Function { decl, generics } = *function;
627 decl: decl.into_tcx(tcx),
628 generics: generics.into_tcx(tcx),
629 header: from_fn_header(&header),
634 impl FromWithTcx<clean::Enum> for Enum {
635 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
636 let variants_stripped = enum_.has_stripped_entries();
637 let clean::Enum { variants, generics } = enum_;
639 generics: generics.into_tcx(tcx),
641 variants: ids(variants, tcx),
642 impls: Vec::new(), // Added in JsonRenderer::item
647 impl FromWithTcx<clean::Variant> for Variant {
648 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
649 use clean::Variant::*;
651 CLike(disr) => Variant::Plain(disr.map(|disr| disr.into_tcx(tcx))),
652 Tuple(fields) => Variant::Tuple(ids_keeping_stripped(fields, tcx)),
653 Struct(s) => Variant::Struct {
654 fields_stripped: s.has_stripped_entries(),
655 fields: ids(s.fields, tcx),
661 impl FromWithTcx<clean::Discriminant> for Discriminant {
662 fn from_tcx(disr: clean::Discriminant, tcx: TyCtxt<'_>) -> Self {
664 // expr is only none if going through the inlineing path, which gets
665 // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
666 // the expr is always some.
667 expr: disr.expr(tcx).unwrap(),
668 value: disr.value(tcx),
673 impl FromWithTcx<clean::Import> for Import {
674 fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
675 use clean::ImportKind::*;
676 let (name, glob) = match import.kind {
677 Simple(s) => (s.to_string(), false),
679 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
684 source: import.source.path.whole_name(),
686 id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
692 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
693 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
695 kind: from_macro_kind(mac.kind),
696 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
701 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
702 use rustc_span::hygiene::MacroKind::*;
704 Bang => MacroKind::Bang,
705 Attr => MacroKind::Attr,
706 Derive => MacroKind::Derive,
710 impl FromWithTcx<Box<clean::Typedef>> for Typedef {
711 fn from_tcx(typedef: Box<clean::Typedef>, tcx: TyCtxt<'_>) -> Self {
712 let clean::Typedef { type_, generics, item_type: _ } = *typedef;
713 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
717 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
718 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
719 OpaqueTy { bounds: opaque.bounds.into_tcx(tcx), generics: opaque.generics.into_tcx(tcx) }
723 impl FromWithTcx<clean::Static> for Static {
724 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
726 type_: stat.type_.into_tcx(tcx),
727 mutable: stat.mutability == ast::Mutability::Mut,
728 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
733 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
734 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
735 TraitAlias { generics: alias.generics.into_tcx(tcx), params: alias.bounds.into_tcx(tcx) }
739 impl FromWithTcx<ItemType> for ItemKind {
740 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
743 Module => ItemKind::Module,
744 ExternCrate => ItemKind::ExternCrate,
745 Import => ItemKind::Import,
746 Struct => ItemKind::Struct,
747 Union => ItemKind::Union,
748 Enum => ItemKind::Enum,
749 Function | TyMethod | Method => ItemKind::Function,
750 Typedef => ItemKind::Typedef,
751 OpaqueTy => ItemKind::OpaqueTy,
752 Static => ItemKind::Static,
753 Constant => ItemKind::Constant,
754 Trait => ItemKind::Trait,
755 Impl => ItemKind::Impl,
756 StructField => ItemKind::StructField,
757 Variant => ItemKind::Variant,
758 Macro => ItemKind::Macro,
759 Primitive => ItemKind::Primitive,
760 AssocConst => ItemKind::AssocConst,
761 AssocType => ItemKind::AssocType,
762 ForeignType => ItemKind::ForeignType,
763 Keyword => ItemKind::Keyword,
764 TraitAlias => ItemKind::TraitAlias,
765 ProcAttribute => ItemKind::ProcAttribute,
766 ProcDerive => ItemKind::ProcDerive,
771 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
774 .filter(|x| !x.is_stripped() && !x.is_keyword())
775 .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
779 fn ids_keeping_stripped(
780 items: impl IntoIterator<Item = clean::Item>,
782 ) -> Vec<Option<Id>> {
786 if !i.is_stripped() && !i.is_keyword() {
787 Some(from_item_id_with_name(i.item_id, tcx, i.name))