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;
10 use rustc_hir::def::CtorKind;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::def_id::CRATE_DEF_INDEX;
15 use rustdoc_json_types::*;
17 use crate::clean::utils::print_const_expr;
18 use crate::clean::{self, FakeDefId};
19 use crate::formats::item_type::ItemType;
20 use crate::json::JsonRenderer;
21 use std::collections::HashSet;
23 impl JsonRenderer<'_> {
24 pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
25 let deprecation = item.deprecation(self.tcx);
32 .filter_map(|clean::ItemLink { link, did, .. }| {
33 did.map(|did| (link.clone(), from_def_id(did.into())))
36 let docs = item.attrs.collapsed_doc_value();
41 .map(rustc_ast_pretty::pprust::attribute_to_string)
43 let span = item.span(self.tcx);
44 let clean::Item { name, attrs: _, kind: _, visibility, def_id, cfg: _ } = item;
45 let inner = match *item.kind {
46 clean::StrippedItem(_) => return None,
47 _ => from_clean_item(item, self.tcx),
50 id: from_def_id(def_id),
51 crate_id: def_id.krate().as_u32(),
52 name: name.map(|sym| sym.to_string()),
53 span: self.convert_span(span),
54 visibility: self.convert_visibility(visibility),
57 deprecation: deprecation.map(from_deprecation),
63 fn convert_span(&self, span: clean::Span) -> Option<Span> {
64 match span.filename(self.sess()) {
65 rustc_span::FileName::Real(name) => {
66 if let Some(local_path) = name.into_local_path() {
67 let hi = span.hi(self.sess());
68 let lo = span.lo(self.sess());
71 begin: (lo.line, lo.col.to_usize()),
72 end: (hi.line, hi.col.to_usize()),
82 fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
83 use clean::Visibility::*;
85 Public => Visibility::Public,
86 Inherited => Visibility::Default,
87 Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
88 Restricted(did) => Visibility::Restricted {
89 parent: from_def_id(did.into()),
90 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
96 crate trait FromWithTcx<T> {
97 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
100 crate trait IntoWithTcx<T> {
101 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
104 impl<T, U> IntoWithTcx<U> for T
108 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
109 U::from_tcx(self, tcx)
113 crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
115 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
116 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
119 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
120 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
121 use clean::GenericArgs::*;
123 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
124 args: args.into_iter().map(|a| a.into_tcx(tcx)).collect(),
125 bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(),
127 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
128 inputs: inputs.into_iter().map(|a| a.into_tcx(tcx)).collect(),
129 output: output.map(|a| a.into_tcx(tcx)),
135 impl FromWithTcx<clean::GenericArg> for GenericArg {
136 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
137 use clean::GenericArg::*;
139 Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
140 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
141 Const(c) => GenericArg::Const(c.into_tcx(tcx)),
146 impl FromWithTcx<clean::Constant> for Constant {
147 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
148 let expr = constant.expr(tcx);
149 let value = constant.value(tcx);
150 let is_literal = constant.is_literal(tcx);
151 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
155 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
156 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
157 TypeBinding { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
161 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
162 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
163 use clean::TypeBindingKind::*;
165 Equality { ty } => TypeBindingKind::Equality(ty.into_tcx(tcx)),
166 Constraint { bounds } => {
167 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
173 crate fn from_def_id(did: FakeDefId) -> Id {
175 FakeDefId::Real(did) => Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index))),
176 // We need to differentiate real and fake ids, because the indices might overlap for fake
177 // and real DefId's, which would cause two different Id's treated as they were the same.
178 FakeDefId::Fake(idx, krate) => Id(format!("F{}:{}", krate.as_u32(), u32::from(idx))),
182 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
183 use clean::ItemKind::*;
184 let name = item.name;
185 let is_crate = item.is_crate();
187 ModuleItem(m) => ItemEnum::Module(Module { is_crate, items: ids(m.items) }),
188 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
189 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
190 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
191 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
192 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
193 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
194 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
195 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
196 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
197 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
198 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
199 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
200 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
201 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
202 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
203 ForeignTypeItem => ItemEnum::ForeignType,
204 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
205 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
206 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
207 MacroItem(m) => ItemEnum::Macro(m.source),
208 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
209 AssocConstItem(t, s) => ItemEnum::AssocConst { type_: t.into_tcx(tcx), default: s },
210 AssocTypeItem(g, t) => ItemEnum::AssocType {
211 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
212 default: t.map(|x| x.into_tcx(tcx)),
214 // `convert_item` early returns `None` for striped items
215 StrippedItem(_) => unreachable!(),
216 PrimitiveItem(_) | KeywordItem(_) => {
217 panic!("{:?} is not supported for JSON output", item)
219 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
220 name: name.as_ref().unwrap().to_string(),
221 rename: src.map(|x| x.to_string()),
226 impl FromWithTcx<clean::Struct> for Struct {
227 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
228 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
230 struct_type: from_ctor_kind(struct_type),
231 generics: generics.into_tcx(tcx),
234 impls: Vec::new(), // Added in JsonRenderer::item
239 impl FromWithTcx<clean::Union> for Union {
240 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
241 let clean::Union { generics, fields, fields_stripped } = struct_;
243 generics: generics.into_tcx(tcx),
246 impls: Vec::new(), // Added in JsonRenderer::item
251 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
253 CtorKind::Fictive => StructType::Plain,
254 CtorKind::Fn => StructType::Tuple,
255 CtorKind::Const => StructType::Unit,
259 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
260 let mut v = HashSet::new();
262 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
263 v.insert(Qualifiers::Unsafe);
266 if let rustc_hir::IsAsync::Async = header.asyncness {
267 v.insert(Qualifiers::Async);
270 if let rustc_hir::Constness::Const = header.constness {
271 v.insert(Qualifiers::Const);
277 impl FromWithTcx<clean::Function> for Function {
278 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
279 let clean::Function { decl, generics, header } = function;
281 decl: decl.into_tcx(tcx),
282 generics: generics.into_tcx(tcx),
283 header: from_fn_header(&header),
284 abi: header.abi.to_string(),
289 impl FromWithTcx<clean::Generics> for Generics {
290 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
292 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
293 where_predicates: generics
296 .map(|x| x.into_tcx(tcx))
302 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
303 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
305 name: generic_param.name.to_string(),
306 kind: generic_param.kind.into_tcx(tcx),
311 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
312 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
313 use clean::GenericParamDefKind::*;
315 Lifetime => GenericParamDefKind::Lifetime,
316 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
317 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
318 default: default.map(|x| x.into_tcx(tcx)),
320 Const { did: _, ty, default } => {
321 GenericParamDefKind::Const { ty: ty.into_tcx(tcx), default }
327 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
328 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
329 use clean::WherePredicate::*;
331 BoundPredicate { ty, bounds, .. } => WherePredicate::BoundPredicate {
332 ty: ty.into_tcx(tcx),
333 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
334 // FIXME: add `bound_params` to rustdoc-json-params?
336 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
337 lifetime: lifetime.0.to_string(),
338 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
340 EqPredicate { lhs, rhs } => {
341 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
347 impl FromWithTcx<clean::GenericBound> for GenericBound {
348 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
349 use clean::GenericBound::*;
351 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
352 GenericBound::TraitBound {
353 trait_: trait_.into_tcx(tcx),
354 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
355 modifier: from_trait_bound_modifier(modifier),
358 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
363 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
364 use rustc_hir::TraitBoundModifier::*;
366 None => TraitBoundModifier::None,
367 Maybe => TraitBoundModifier::Maybe,
368 MaybeConst => TraitBoundModifier::MaybeConst,
372 impl FromWithTcx<clean::Type> for Type {
373 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
376 ResolvedPath { path, did, is_generic: _ } => Type::ResolvedPath {
377 name: path.whole_name(),
378 id: from_def_id(did.into()),
379 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
380 param_names: Vec::new(),
382 DynTrait(mut bounds, lt) => {
383 let (path, id) = match bounds.remove(0).trait_ {
384 ResolvedPath { path, did, .. } => (path, did),
389 name: path.whole_name(),
390 id: from_def_id(id.into()),
394 .map(|args| Box::new(args.clone().args.into_tcx(tcx))),
398 clean::GenericBound::TraitBound(t, rustc_hir::TraitBoundModifier::None)
400 .chain(lt.into_iter().map(|lt| clean::GenericBound::Outlives(lt)))
401 .map(|bound| bound.into_tcx(tcx))
405 Generic(s) => Type::Generic(s.to_string()),
406 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
407 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
408 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
409 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
410 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
411 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
412 Never => Type::Never,
413 Infer => Type::Infer,
414 RawPointer(mutability, type_) => Type::RawPointer {
415 mutable: mutability == ast::Mutability::Mut,
416 type_: Box::new((*type_).into_tcx(tcx)),
418 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
419 lifetime: lifetime.map(|l| l.0.to_string()),
420 mutable: mutability == ast::Mutability::Mut,
421 type_: Box::new((*type_).into_tcx(tcx)),
423 QPath { name, self_type, trait_, .. } => Type::QualifiedPath {
424 name: name.to_string(),
425 self_type: Box::new((*self_type).into_tcx(tcx)),
426 trait_: Box::new((*trait_).into_tcx(tcx)),
432 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
433 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
434 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
436 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
437 let mut hs = HashSet::new();
438 hs.insert(Qualifiers::Unsafe);
443 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
444 decl: decl.into_tcx(tcx),
445 abi: abi.to_string(),
450 impl FromWithTcx<clean::FnDecl> for FnDecl {
451 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
452 let clean::FnDecl { inputs, output, c_variadic } = decl;
457 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
459 output: match output {
460 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
461 clean::FnRetTy::DefaultReturn => None,
468 impl FromWithTcx<clean::Trait> for Trait {
469 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
470 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
473 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
475 generics: generics.into_tcx(tcx),
476 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
477 implementors: Vec::new(), // Added in JsonRenderer::item
482 impl FromWithTcx<clean::Impl> for Impl {
483 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
484 let provided_trait_methods = impl_.provided_trait_methods(tcx);
497 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
498 generics: generics.into_tcx(tcx),
499 provided_trait_methods: provided_trait_methods
501 .map(|x| x.to_string())
503 trait_: trait_.map(|x| x.into_tcx(tcx)),
504 for_: for_.into_tcx(tcx),
506 negative: negative_polarity,
508 blanket_impl: blanket_impl.map(|x| (*x).into_tcx(tcx)),
513 crate fn from_function_method(
514 function: clean::Function,
518 let clean::Function { header, decl, generics } = function;
520 decl: decl.into_tcx(tcx),
521 generics: generics.into_tcx(tcx),
522 header: from_fn_header(&header),
523 abi: header.abi.to_string(),
528 impl FromWithTcx<clean::Enum> for Enum {
529 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
530 let clean::Enum { variants, generics, variants_stripped } = enum_;
532 generics: generics.into_tcx(tcx),
534 variants: ids(variants),
535 impls: Vec::new(), // Added in JsonRenderer::item
540 impl FromWithTcx<clean::VariantStruct> for Struct {
541 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
542 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
544 struct_type: from_ctor_kind(struct_type),
545 generics: Default::default(),
553 impl FromWithTcx<clean::Variant> for Variant {
554 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
555 use clean::Variant::*;
557 CLike => Variant::Plain,
558 Tuple(t) => Variant::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
559 Struct(s) => Variant::Struct(ids(s.fields)),
564 impl FromWithTcx<clean::Import> for Import {
565 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
566 use clean::ImportKind::*;
568 Simple(s) => Import {
569 source: import.source.path.whole_name(),
571 id: import.source.did.map(FakeDefId::from).map(from_def_id),
575 source: import.source.path.whole_name(),
576 name: import.source.path.last_name().to_string(),
577 id: import.source.did.map(FakeDefId::from).map(from_def_id),
584 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
585 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
587 kind: from_macro_kind(mac.kind),
588 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
593 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
594 use rustc_span::hygiene::MacroKind::*;
596 Bang => MacroKind::Bang,
597 Attr => MacroKind::Attr,
598 Derive => MacroKind::Derive,
602 impl FromWithTcx<clean::Typedef> for Typedef {
603 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
604 let clean::Typedef { type_, generics, item_type: _ } = typedef;
605 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
609 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
610 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
612 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
613 generics: opaque.generics.into_tcx(tcx),
618 impl FromWithTcx<clean::Static> for Static {
619 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
621 type_: stat.type_.into_tcx(tcx),
622 mutable: stat.mutability == ast::Mutability::Mut,
623 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
628 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
629 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
631 generics: alias.generics.into_tcx(tcx),
632 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
637 impl FromWithTcx<ItemType> for ItemKind {
638 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
641 Module => ItemKind::Module,
642 ExternCrate => ItemKind::ExternCrate,
643 Import => ItemKind::Import,
644 Struct => ItemKind::Struct,
645 Union => ItemKind::Union,
646 Enum => ItemKind::Enum,
647 Function => ItemKind::Function,
648 Typedef => ItemKind::Typedef,
649 OpaqueTy => ItemKind::OpaqueTy,
650 Static => ItemKind::Static,
651 Constant => ItemKind::Constant,
652 Trait => ItemKind::Trait,
653 Impl => ItemKind::Impl,
654 TyMethod | Method => ItemKind::Method,
655 StructField => ItemKind::StructField,
656 Variant => ItemKind::Variant,
657 Macro => ItemKind::Macro,
658 Primitive => ItemKind::Primitive,
659 AssocConst => ItemKind::AssocConst,
660 AssocType => ItemKind::AssocType,
661 ForeignType => ItemKind::ForeignType,
662 Keyword => ItemKind::Keyword,
663 TraitAlias => ItemKind::TraitAlias,
664 ProcAttribute => ItemKind::ProcAttribute,
665 ProcDerive => ItemKind::ProcDerive,
670 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
671 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_def_id(i.def_id)).collect()