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::TyCtxt;
13 use rustc_span::def_id::CRATE_DEF_INDEX;
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 std::collections::HashSet;
24 impl JsonRenderer<'_> {
25 pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
26 let deprecation = item.deprecation(self.tcx);
33 .filter_map(|clean::ItemLink { link, did, .. }| {
34 did.map(|did| (link.clone(), from_item_id(did.into())))
37 let docs = item.attrs.collapsed_doc_value();
42 .map(rustc_ast_pretty::pprust::attribute_to_string)
44 let span = item.span(self.tcx);
45 let clean::Item { name, attrs: _, kind: _, visibility, def_id, cfg: _ } = item;
46 let inner = match *item.kind {
47 clean::StrippedItem(_) => return None,
48 _ => from_clean_item(item, self.tcx),
51 id: from_item_id(def_id),
52 crate_id: def_id.krate().as_u32(),
53 name: name.map(|sym| sym.to_string()),
54 span: self.convert_span(span),
55 visibility: self.convert_visibility(visibility),
58 deprecation: deprecation.map(from_deprecation),
64 fn convert_span(&self, span: clean::Span) -> Option<Span> {
65 match span.filename(self.sess()) {
66 rustc_span::FileName::Real(name) => {
67 if let Some(local_path) = name.into_local_path() {
68 let hi = span.hi(self.sess());
69 let lo = span.lo(self.sess());
72 begin: (lo.line, lo.col.to_usize()),
73 end: (hi.line, hi.col.to_usize()),
83 fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
84 use clean::Visibility::*;
86 Public => Visibility::Public,
87 Inherited => Visibility::Default,
88 Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
89 Restricted(did) => Visibility::Restricted {
90 parent: from_item_id(did.into()),
91 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
97 crate trait FromWithTcx<T> {
98 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
101 crate trait IntoWithTcx<T> {
102 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
105 impl<T, U> IntoWithTcx<U> for T
109 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
110 U::from_tcx(self, tcx)
114 crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
116 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
117 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
120 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
121 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
122 use clean::GenericArgs::*;
124 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
125 args: args.into_iter().map(|a| a.into_tcx(tcx)).collect(),
126 bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(),
128 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
129 inputs: inputs.into_iter().map(|a| a.into_tcx(tcx)).collect(),
130 output: output.map(|a| (*a).into_tcx(tcx)),
136 impl FromWithTcx<clean::GenericArg> for GenericArg {
137 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
138 use clean::GenericArg::*;
140 Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
141 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
142 Const(box c) => GenericArg::Const(c.into_tcx(tcx)),
143 Infer => GenericArg::Infer,
148 impl FromWithTcx<clean::Constant> for Constant {
149 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
150 let expr = constant.expr(tcx);
151 let value = constant.value(tcx);
152 let is_literal = constant.is_literal(tcx);
153 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
157 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
158 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
159 TypeBinding { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
163 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
164 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
165 use clean::TypeBindingKind::*;
167 Equality { ty } => TypeBindingKind::Equality(ty.into_tcx(tcx)),
168 Constraint { bounds } => {
169 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
175 crate fn from_item_id(did: ItemId) -> Id {
176 struct DisplayDefId(DefId);
178 impl fmt::Display for DisplayDefId {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 write!(f, "{}:{}", self.0.krate.as_u32(), u32::from(self.0.index))
185 ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did))),
186 ItemId::Blanket { for_, impl_id } => {
187 Id(format!("b:{}-{}", DisplayDefId(impl_id), DisplayDefId(for_)))
189 ItemId::Auto { for_, trait_ } => {
190 Id(format!("a:{}-{}", DisplayDefId(trait_), DisplayDefId(for_)))
192 ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())),
196 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
197 use clean::ItemKind::*;
198 let name = item.name;
199 let is_crate = item.is_crate();
201 ModuleItem(m) => ItemEnum::Module(Module { is_crate, items: ids(m.items) }),
202 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
203 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
204 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
205 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
206 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
207 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
208 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
209 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
210 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
211 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
212 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
213 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
214 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
215 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
216 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
217 ForeignTypeItem => ItemEnum::ForeignType,
218 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
219 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
220 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
221 MacroItem(m) => ItemEnum::Macro(m.source),
222 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
223 AssocConstItem(t, s) => ItemEnum::AssocConst { type_: t.into_tcx(tcx), default: s },
224 AssocTypeItem(g, t) => ItemEnum::AssocType {
225 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
226 default: t.map(|x| x.into_tcx(tcx)),
228 // `convert_item` early returns `None` for striped items
229 StrippedItem(_) => unreachable!(),
230 PrimitiveItem(_) | KeywordItem(_) => {
231 panic!("{:?} is not supported for JSON output", item)
233 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
234 name: name.as_ref().unwrap().to_string(),
235 rename: src.map(|x| x.to_string()),
240 impl FromWithTcx<clean::Struct> for Struct {
241 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
242 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
244 struct_type: from_ctor_kind(struct_type),
245 generics: generics.into_tcx(tcx),
248 impls: Vec::new(), // Added in JsonRenderer::item
253 impl FromWithTcx<clean::Union> for Union {
254 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
255 let clean::Union { generics, fields, fields_stripped } = struct_;
257 generics: generics.into_tcx(tcx),
260 impls: Vec::new(), // Added in JsonRenderer::item
265 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
267 CtorKind::Fictive => StructType::Plain,
268 CtorKind::Fn => StructType::Tuple,
269 CtorKind::Const => StructType::Unit,
273 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
274 let mut v = HashSet::new();
276 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
277 v.insert(Qualifiers::Unsafe);
280 if let rustc_hir::IsAsync::Async = header.asyncness {
281 v.insert(Qualifiers::Async);
284 if let rustc_hir::Constness::Const = header.constness {
285 v.insert(Qualifiers::Const);
291 impl FromWithTcx<clean::Function> for Function {
292 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
293 let clean::Function { decl, generics, header } = function;
295 decl: decl.into_tcx(tcx),
296 generics: generics.into_tcx(tcx),
297 header: from_fn_header(&header),
298 abi: header.abi.to_string(),
303 impl FromWithTcx<clean::Generics> for Generics {
304 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
306 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
307 where_predicates: generics
310 .map(|x| x.into_tcx(tcx))
316 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
317 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
319 name: generic_param.name.to_string(),
320 kind: generic_param.kind.into_tcx(tcx),
325 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
326 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
327 use clean::GenericParamDefKind::*;
329 Lifetime { outlives } => GenericParamDefKind::Lifetime {
330 outlives: outlives.into_iter().map(|lt| lt.0.to_string()).collect(),
332 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
333 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
334 default: default.map(|x| x.into_tcx(tcx)),
336 Const { did: _, ty, default } => {
337 GenericParamDefKind::Const { ty: ty.into_tcx(tcx), default }
343 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
344 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
345 use clean::WherePredicate::*;
347 BoundPredicate { ty, bounds, .. } => WherePredicate::BoundPredicate {
348 ty: ty.into_tcx(tcx),
349 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
350 // FIXME: add `bound_params` to rustdoc-json-params?
352 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
353 lifetime: lifetime.0.to_string(),
354 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
356 EqPredicate { lhs, rhs } => {
357 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
363 impl FromWithTcx<clean::GenericBound> for GenericBound {
364 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
365 use clean::GenericBound::*;
367 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
368 GenericBound::TraitBound {
369 trait_: trait_.into_tcx(tcx),
370 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
371 modifier: from_trait_bound_modifier(modifier),
374 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
379 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
380 use rustc_hir::TraitBoundModifier::*;
382 None => TraitBoundModifier::None,
383 Maybe => TraitBoundModifier::Maybe,
384 MaybeConst => TraitBoundModifier::MaybeConst,
388 impl FromWithTcx<clean::Type> for Type {
389 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
392 ResolvedPath { path, did, is_generic: _ } => Type::ResolvedPath {
393 name: path.whole_name(),
394 id: from_item_id(did.into()),
395 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
396 param_names: Vec::new(),
398 DynTrait(mut bounds, lt) => {
399 let (path, id) = match bounds.remove(0).trait_ {
400 ResolvedPath { path, did, .. } => (path, did),
405 name: path.whole_name(),
406 id: from_item_id(id.into()),
410 .map(|args| Box::new(args.clone().args.into_tcx(tcx))),
414 clean::GenericBound::TraitBound(t, rustc_hir::TraitBoundModifier::None)
416 .chain(lt.into_iter().map(|lt| clean::GenericBound::Outlives(lt)))
417 .map(|bound| bound.into_tcx(tcx))
421 Generic(s) => Type::Generic(s.to_string()),
422 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
423 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
424 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
425 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
426 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
427 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
428 Never => Type::Never,
429 Infer => Type::Infer,
430 RawPointer(mutability, type_) => Type::RawPointer {
431 mutable: mutability == ast::Mutability::Mut,
432 type_: Box::new((*type_).into_tcx(tcx)),
434 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
435 lifetime: lifetime.map(|l| l.0.to_string()),
436 mutable: mutability == ast::Mutability::Mut,
437 type_: Box::new((*type_).into_tcx(tcx)),
439 QPath { name, self_type, trait_, .. } => Type::QualifiedPath {
440 name: name.to_string(),
441 self_type: Box::new((*self_type).into_tcx(tcx)),
442 trait_: Box::new((*trait_).into_tcx(tcx)),
448 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
449 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
450 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
452 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
453 let mut hs = HashSet::new();
454 hs.insert(Qualifiers::Unsafe);
459 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
460 decl: decl.into_tcx(tcx),
461 abi: abi.to_string(),
466 impl FromWithTcx<clean::FnDecl> for FnDecl {
467 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
468 let clean::FnDecl { inputs, output, c_variadic } = decl;
473 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
475 output: match output {
476 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
477 clean::FnRetTy::DefaultReturn => None,
484 impl FromWithTcx<clean::Trait> for Trait {
485 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
486 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
489 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
491 generics: generics.into_tcx(tcx),
492 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
493 implementors: Vec::new(), // Added in JsonRenderer::item
498 impl FromWithTcx<clean::Impl> for Impl {
499 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
500 let provided_trait_methods = impl_.provided_trait_methods(tcx);
513 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
514 generics: generics.into_tcx(tcx),
515 provided_trait_methods: provided_trait_methods
517 .map(|x| x.to_string())
519 trait_: trait_.map(|x| x.into_tcx(tcx)),
520 for_: for_.into_tcx(tcx),
522 negative: negative_polarity,
524 blanket_impl: blanket_impl.map(|x| (*x).into_tcx(tcx)),
529 crate fn from_function_method(
530 function: clean::Function,
534 let clean::Function { header, decl, generics } = function;
536 decl: decl.into_tcx(tcx),
537 generics: generics.into_tcx(tcx),
538 header: from_fn_header(&header),
539 abi: header.abi.to_string(),
544 impl FromWithTcx<clean::Enum> for Enum {
545 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
546 let clean::Enum { variants, generics, variants_stripped } = enum_;
548 generics: generics.into_tcx(tcx),
550 variants: ids(variants),
551 impls: Vec::new(), // Added in JsonRenderer::item
556 impl FromWithTcx<clean::VariantStruct> for Struct {
557 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
558 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
560 struct_type: from_ctor_kind(struct_type),
561 generics: Default::default(),
569 impl FromWithTcx<clean::Variant> for Variant {
570 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
571 use clean::Variant::*;
573 CLike => Variant::Plain,
574 Tuple(fields) => Variant::Tuple(
578 if let clean::StructFieldItem(ty) = *f.kind {
586 Struct(s) => Variant::Struct(ids(s.fields)),
591 impl FromWithTcx<clean::Import> for Import {
592 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
593 use clean::ImportKind::*;
595 Simple(s) => Import {
596 source: import.source.path.whole_name(),
598 id: import.source.did.map(ItemId::from).map(from_item_id),
602 source: import.source.path.whole_name(),
603 name: import.source.path.last_name().to_string(),
604 id: import.source.did.map(ItemId::from).map(from_item_id),
611 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
612 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
614 kind: from_macro_kind(mac.kind),
615 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
620 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
621 use rustc_span::hygiene::MacroKind::*;
623 Bang => MacroKind::Bang,
624 Attr => MacroKind::Attr,
625 Derive => MacroKind::Derive,
629 impl FromWithTcx<clean::Typedef> for Typedef {
630 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
631 let clean::Typedef { type_, generics, item_type: _ } = typedef;
632 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
636 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
637 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
639 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
640 generics: opaque.generics.into_tcx(tcx),
645 impl FromWithTcx<clean::Static> for Static {
646 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
648 type_: stat.type_.into_tcx(tcx),
649 mutable: stat.mutability == ast::Mutability::Mut,
650 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
655 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
656 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
658 generics: alias.generics.into_tcx(tcx),
659 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
664 impl FromWithTcx<ItemType> for ItemKind {
665 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
668 Module => ItemKind::Module,
669 ExternCrate => ItemKind::ExternCrate,
670 Import => ItemKind::Import,
671 Struct => ItemKind::Struct,
672 Union => ItemKind::Union,
673 Enum => ItemKind::Enum,
674 Function => ItemKind::Function,
675 Typedef => ItemKind::Typedef,
676 OpaqueTy => ItemKind::OpaqueTy,
677 Static => ItemKind::Static,
678 Constant => ItemKind::Constant,
679 Trait => ItemKind::Trait,
680 Impl => ItemKind::Impl,
681 TyMethod | Method => ItemKind::Method,
682 StructField => ItemKind::StructField,
683 Variant => ItemKind::Variant,
684 Macro => ItemKind::Macro,
685 Primitive => ItemKind::Primitive,
686 AssocConst => ItemKind::AssocConst,
687 AssocType => ItemKind::AssocType,
688 ForeignType => ItemKind::ForeignType,
689 Keyword => ItemKind::Keyword,
690 TraitAlias => ItemKind::TraitAlias,
691 ProcAttribute => ItemKind::ProcAttribute,
692 ProcDerive => ItemKind::ProcDerive,
697 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
698 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_item_id(i.def_id)).collect()