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::{DefId, CRATE_DEF_INDEX};
15 use rustdoc_json_types::*;
18 use crate::clean::utils::print_const_expr;
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)))
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 let hi = span.hi(self.sess());
67 let lo = span.lo(self.sess());
69 filename: name.into_local_path(),
70 begin: (lo.line, lo.col.to_usize()),
71 end: (hi.line, hi.col.to_usize()),
78 fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
79 use clean::Visibility::*;
81 Public => Visibility::Public,
82 Inherited => Visibility::Default,
83 Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
84 Restricted(did) => Visibility::Restricted {
85 parent: from_def_id(did),
86 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
92 crate trait FromWithTcx<T> {
93 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
96 crate trait IntoWithTcx<T> {
97 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
100 impl<T, U> IntoWithTcx<U> for T
104 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
105 U::from_tcx(self, tcx)
109 crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
111 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
112 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
115 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
116 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
117 use clean::GenericArgs::*;
119 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
120 args: args.into_iter().map(|a| a.into_tcx(tcx)).collect(),
121 bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(),
123 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
124 inputs: inputs.into_iter().map(|a| a.into_tcx(tcx)).collect(),
125 output: output.map(|a| a.into_tcx(tcx)),
131 impl FromWithTcx<clean::GenericArg> for GenericArg {
132 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
133 use clean::GenericArg::*;
135 Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
136 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
137 Const(c) => GenericArg::Const(c.into_tcx(tcx)),
142 impl FromWithTcx<clean::Constant> for Constant {
143 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
144 let expr = constant.expr(tcx);
145 let value = constant.value(tcx);
146 let is_literal = constant.is_literal(tcx);
147 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
151 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
152 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
153 TypeBinding { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
157 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
158 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
159 use clean::TypeBindingKind::*;
161 Equality { ty } => TypeBindingKind::Equality(ty.into_tcx(tcx)),
162 Constraint { bounds } => {
163 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
169 crate fn from_def_id(did: DefId) -> Id {
170 Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
173 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
174 use clean::ItemKind::*;
175 let name = item.name;
176 let is_crate = item.is_crate();
178 ModuleItem(m) => ItemEnum::Module(Module { is_crate, items: ids(m.items) }),
179 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
180 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
181 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
182 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
183 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
184 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
185 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
186 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
187 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
188 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
189 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
190 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
191 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
192 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
193 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
194 ForeignTypeItem => ItemEnum::ForeignType,
195 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
196 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
197 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
198 MacroItem(m) => ItemEnum::Macro(m.source),
199 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
200 AssocConstItem(t, s) => ItemEnum::AssocConst { type_: t.into_tcx(tcx), default: s },
201 AssocTypeItem(g, t) => ItemEnum::AssocType {
202 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
203 default: t.map(|x| x.into_tcx(tcx)),
205 // `convert_item` early returns `None` for striped items
206 StrippedItem(_) => unreachable!(),
207 PrimitiveItem(_) | KeywordItem(_) => {
208 panic!("{:?} is not supported for JSON output", item)
210 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
211 name: name.as_ref().unwrap().to_string(),
212 rename: src.map(|x| x.to_string()),
217 impl FromWithTcx<clean::Struct> for Struct {
218 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
219 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
221 struct_type: from_ctor_kind(struct_type),
222 generics: generics.into_tcx(tcx),
225 impls: Vec::new(), // Added in JsonRenderer::item
230 impl FromWithTcx<clean::Union> for Union {
231 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
232 let clean::Union { generics, fields, fields_stripped } = struct_;
234 generics: generics.into_tcx(tcx),
237 impls: Vec::new(), // Added in JsonRenderer::item
242 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
244 CtorKind::Fictive => StructType::Plain,
245 CtorKind::Fn => StructType::Tuple,
246 CtorKind::Const => StructType::Unit,
250 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
251 let mut v = HashSet::new();
253 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
254 v.insert(Qualifiers::Unsafe);
257 if let rustc_hir::IsAsync::Async = header.asyncness {
258 v.insert(Qualifiers::Async);
261 if let rustc_hir::Constness::Const = header.constness {
262 v.insert(Qualifiers::Const);
268 impl FromWithTcx<clean::Function> for Function {
269 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
270 let clean::Function { decl, generics, header } = function;
272 decl: decl.into_tcx(tcx),
273 generics: generics.into_tcx(tcx),
274 header: from_fn_header(&header),
275 abi: header.abi.to_string(),
280 impl FromWithTcx<clean::Generics> for Generics {
281 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
283 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
284 where_predicates: generics
287 .map(|x| x.into_tcx(tcx))
293 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
294 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
296 name: generic_param.name.to_string(),
297 kind: generic_param.kind.into_tcx(tcx),
302 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
303 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
304 use clean::GenericParamDefKind::*;
306 Lifetime => GenericParamDefKind::Lifetime,
307 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
308 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
309 default: default.map(|x| x.into_tcx(tcx)),
311 Const { did: _, ty } => GenericParamDefKind::Const(ty.into_tcx(tcx)),
316 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
317 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
318 use clean::WherePredicate::*;
320 BoundPredicate { ty, bounds } => WherePredicate::BoundPredicate {
321 ty: ty.into_tcx(tcx),
322 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
324 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
325 lifetime: lifetime.0.to_string(),
326 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
328 EqPredicate { lhs, rhs } => {
329 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
335 impl FromWithTcx<clean::GenericBound> for GenericBound {
336 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
337 use clean::GenericBound::*;
339 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
340 GenericBound::TraitBound {
341 trait_: trait_.into_tcx(tcx),
342 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
343 modifier: from_trait_bound_modifier(modifier),
346 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
351 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
352 use rustc_hir::TraitBoundModifier::*;
354 None => TraitBoundModifier::None,
355 Maybe => TraitBoundModifier::Maybe,
356 MaybeConst => TraitBoundModifier::MaybeConst,
360 impl FromWithTcx<clean::Type> for Type {
361 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
364 ResolvedPath { path, param_names, did, is_generic: _ } => Type::ResolvedPath {
365 name: path.whole_name(),
366 id: from_def_id(did),
367 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
368 param_names: param_names
369 .map(|v| v.into_iter().map(|x| x.into_tcx(tcx)).collect())
370 .unwrap_or_default(),
372 Generic(s) => Type::Generic(s.to_string()),
373 Primitive(p) => Type::Primitive(p.as_str().to_string()),
374 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
375 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
376 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
377 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
378 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
379 Never => Type::Never,
380 Infer => Type::Infer,
381 RawPointer(mutability, type_) => Type::RawPointer {
382 mutable: mutability == ast::Mutability::Mut,
383 type_: Box::new((*type_).into_tcx(tcx)),
385 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
386 lifetime: lifetime.map(|l| l.0.to_string()),
387 mutable: mutability == ast::Mutability::Mut,
388 type_: Box::new((*type_).into_tcx(tcx)),
390 QPath { name, self_type, trait_ } => Type::QualifiedPath {
391 name: name.to_string(),
392 self_type: Box::new((*self_type).into_tcx(tcx)),
393 trait_: Box::new((*trait_).into_tcx(tcx)),
399 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
400 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
401 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
403 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
404 let mut hs = HashSet::new();
405 hs.insert(Qualifiers::Unsafe);
410 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
411 decl: decl.into_tcx(tcx),
412 abi: abi.to_string(),
417 impl FromWithTcx<clean::FnDecl> for FnDecl {
418 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
419 let clean::FnDecl { inputs, output, c_variadic } = decl;
424 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
426 output: match output {
427 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
428 clean::FnRetTy::DefaultReturn => None,
435 impl FromWithTcx<clean::Trait> for Trait {
436 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
437 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
440 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
442 generics: generics.into_tcx(tcx),
443 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
444 implementors: Vec::new(), // Added in JsonRenderer::item
449 impl FromWithTcx<clean::Impl> for Impl {
450 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
451 let provided_trait_methods = impl_.provided_trait_methods(tcx);
464 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
465 generics: generics.into_tcx(tcx),
466 provided_trait_methods: provided_trait_methods
468 .map(|x| x.to_string())
470 trait_: trait_.map(|x| x.into_tcx(tcx)),
471 for_: for_.into_tcx(tcx),
473 negative: negative_polarity,
475 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
480 crate fn from_function_method(
481 function: clean::Function,
485 let clean::Function { header, decl, generics } = function;
487 decl: decl.into_tcx(tcx),
488 generics: generics.into_tcx(tcx),
489 header: from_fn_header(&header),
490 abi: header.abi.to_string(),
495 impl FromWithTcx<clean::Enum> for Enum {
496 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
497 let clean::Enum { variants, generics, variants_stripped } = enum_;
499 generics: generics.into_tcx(tcx),
501 variants: ids(variants),
502 impls: Vec::new(), // Added in JsonRenderer::item
507 impl FromWithTcx<clean::VariantStruct> for Struct {
508 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
509 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
511 struct_type: from_ctor_kind(struct_type),
512 generics: Default::default(),
520 impl FromWithTcx<clean::Variant> for Variant {
521 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
522 use clean::Variant::*;
524 CLike => Variant::Plain,
525 Tuple(t) => Variant::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
526 Struct(s) => Variant::Struct(ids(s.fields)),
531 impl FromWithTcx<clean::Import> for Import {
532 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
533 use clean::ImportKind::*;
535 Simple(s) => Import {
536 source: import.source.path.whole_name(),
538 id: import.source.did.map(from_def_id),
542 source: import.source.path.whole_name(),
543 name: import.source.path.last_name().to_string(),
544 id: import.source.did.map(from_def_id),
551 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
552 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
554 kind: from_macro_kind(mac.kind),
555 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
560 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
561 use rustc_span::hygiene::MacroKind::*;
563 Bang => MacroKind::Bang,
564 Attr => MacroKind::Attr,
565 Derive => MacroKind::Derive,
569 impl FromWithTcx<clean::Typedef> for Typedef {
570 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
571 let clean::Typedef { type_, generics, item_type: _ } = typedef;
572 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
576 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
577 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
579 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
580 generics: opaque.generics.into_tcx(tcx),
585 impl FromWithTcx<clean::Static> for Static {
586 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
588 type_: stat.type_.into_tcx(tcx),
589 mutable: stat.mutability == ast::Mutability::Mut,
590 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
595 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
596 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
598 generics: alias.generics.into_tcx(tcx),
599 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
604 impl FromWithTcx<ItemType> for ItemKind {
605 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
608 Module => ItemKind::Module,
609 ExternCrate => ItemKind::ExternCrate,
610 Import => ItemKind::Import,
611 Struct => ItemKind::Struct,
612 Union => ItemKind::Union,
613 Enum => ItemKind::Enum,
614 Function => ItemKind::Function,
615 Typedef => ItemKind::Typedef,
616 OpaqueTy => ItemKind::OpaqueTy,
617 Static => ItemKind::Static,
618 Constant => ItemKind::Constant,
619 Trait => ItemKind::Trait,
620 Impl => ItemKind::Impl,
621 TyMethod | Method => ItemKind::Method,
622 StructField => ItemKind::StructField,
623 Variant => ItemKind::Variant,
624 Macro => ItemKind::Macro,
625 Primitive => ItemKind::Primitive,
626 AssocConst => ItemKind::AssocConst,
627 AssocType => ItemKind::AssocType,
628 ForeignType => ItemKind::ForeignType,
629 Keyword => ItemKind::Keyword,
630 TraitAlias => ItemKind::TraitAlias,
631 ProcAttribute => ItemKind::ProcAttribute,
632 ProcDerive => ItemKind::ProcDerive,
637 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
638 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_def_id(i.def_id)).collect()