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: match name {
70 rustc_span::RealFileName::Named(path) => path,
71 rustc_span::RealFileName::Devirtualized { local_path, virtual_name: _ } => {
75 begin: (lo.line, lo.col.to_usize()),
76 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_def_id(did),
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(c) => GenericArg::Const(c.into_tcx(tcx)),
147 impl FromWithTcx<clean::Constant> for Constant {
148 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
149 let expr = constant.expr(tcx);
150 let value = constant.value(tcx);
151 let is_literal = constant.is_literal(tcx);
152 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
156 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
157 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
158 TypeBinding { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
162 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
163 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
164 use clean::TypeBindingKind::*;
166 Equality { ty } => TypeBindingKind::Equality(ty.into_tcx(tcx)),
167 Constraint { bounds } => {
168 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
174 crate fn from_def_id(did: DefId) -> Id {
175 Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
178 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
179 use clean::ItemKind::*;
180 let name = item.name;
181 let is_crate = item.is_crate();
183 ModuleItem(m) => ItemEnum::Module(Module { is_crate, items: ids(m.items) }),
184 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
185 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
186 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
187 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
188 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
189 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
190 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
191 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
192 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
193 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
194 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
195 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
196 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
197 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
198 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
199 ForeignTypeItem => ItemEnum::ForeignType,
200 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
201 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
202 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
203 MacroItem(m) => ItemEnum::Macro(m.source),
204 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
205 AssocConstItem(t, s) => ItemEnum::AssocConst { type_: t.into_tcx(tcx), default: s },
206 AssocTypeItem(g, t) => ItemEnum::AssocType {
207 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
208 default: t.map(|x| x.into_tcx(tcx)),
210 // `convert_item` early returns `None` for striped items
211 StrippedItem(_) => unreachable!(),
212 PrimitiveItem(_) | KeywordItem(_) => {
213 panic!("{:?} is not supported for JSON output", item)
215 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
216 name: name.as_ref().unwrap().to_string(),
217 rename: src.map(|x| x.to_string()),
222 impl FromWithTcx<clean::Struct> for Struct {
223 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
224 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
226 struct_type: from_ctor_kind(struct_type),
227 generics: generics.into_tcx(tcx),
230 impls: Vec::new(), // Added in JsonRenderer::item
235 impl FromWithTcx<clean::Union> for Union {
236 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
237 let clean::Union { generics, fields, fields_stripped } = struct_;
239 generics: generics.into_tcx(tcx),
242 impls: Vec::new(), // Added in JsonRenderer::item
247 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
249 CtorKind::Fictive => StructType::Plain,
250 CtorKind::Fn => StructType::Tuple,
251 CtorKind::Const => StructType::Unit,
255 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
256 let mut v = HashSet::new();
258 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
259 v.insert(Qualifiers::Unsafe);
262 if let rustc_hir::IsAsync::Async = header.asyncness {
263 v.insert(Qualifiers::Async);
266 if let rustc_hir::Constness::Const = header.constness {
267 v.insert(Qualifiers::Const);
273 impl FromWithTcx<clean::Function> for Function {
274 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
275 let clean::Function { decl, generics, header } = function;
277 decl: decl.into_tcx(tcx),
278 generics: generics.into_tcx(tcx),
279 header: from_fn_header(&header),
280 abi: header.abi.to_string(),
285 impl FromWithTcx<clean::Generics> for Generics {
286 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
288 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
289 where_predicates: generics
292 .map(|x| x.into_tcx(tcx))
298 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
299 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
301 name: generic_param.name.to_string(),
302 kind: generic_param.kind.into_tcx(tcx),
307 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
308 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
309 use clean::GenericParamDefKind::*;
311 Lifetime => GenericParamDefKind::Lifetime,
312 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
313 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
314 default: default.map(|x| x.into_tcx(tcx)),
316 Const { did: _, ty } => GenericParamDefKind::Const(ty.into_tcx(tcx)),
321 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
322 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
323 use clean::WherePredicate::*;
325 BoundPredicate { ty, bounds } => WherePredicate::BoundPredicate {
326 ty: ty.into_tcx(tcx),
327 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
329 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
330 lifetime: lifetime.0.to_string(),
331 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
333 EqPredicate { lhs, rhs } => {
334 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
340 impl FromWithTcx<clean::GenericBound> for GenericBound {
341 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
342 use clean::GenericBound::*;
344 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
345 GenericBound::TraitBound {
346 trait_: trait_.into_tcx(tcx),
347 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
348 modifier: from_trait_bound_modifier(modifier),
351 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
356 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
357 use rustc_hir::TraitBoundModifier::*;
359 None => TraitBoundModifier::None,
360 Maybe => TraitBoundModifier::Maybe,
361 MaybeConst => TraitBoundModifier::MaybeConst,
365 impl FromWithTcx<clean::Type> for Type {
366 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
369 ResolvedPath { path, param_names, did, is_generic: _ } => Type::ResolvedPath {
370 name: path.whole_name(),
371 id: from_def_id(did),
372 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
373 param_names: param_names
374 .map(|v| v.into_iter().map(|x| x.into_tcx(tcx)).collect())
375 .unwrap_or_default(),
377 Generic(s) => Type::Generic(s.to_string()),
378 Primitive(p) => Type::Primitive(p.as_str().to_string()),
379 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
380 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
381 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
382 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
383 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
384 Never => Type::Never,
385 Infer => Type::Infer,
386 RawPointer(mutability, type_) => Type::RawPointer {
387 mutable: mutability == ast::Mutability::Mut,
388 type_: Box::new((*type_).into_tcx(tcx)),
390 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
391 lifetime: lifetime.map(|l| l.0.to_string()),
392 mutable: mutability == ast::Mutability::Mut,
393 type_: Box::new((*type_).into_tcx(tcx)),
395 QPath { name, self_type, trait_ } => Type::QualifiedPath {
396 name: name.to_string(),
397 self_type: Box::new((*self_type).into_tcx(tcx)),
398 trait_: Box::new((*trait_).into_tcx(tcx)),
404 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
405 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
406 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
408 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
409 let mut hs = HashSet::new();
410 hs.insert(Qualifiers::Unsafe);
415 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
416 decl: decl.into_tcx(tcx),
417 abi: abi.to_string(),
422 impl FromWithTcx<clean::FnDecl> for FnDecl {
423 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
424 let clean::FnDecl { inputs, output, c_variadic } = decl;
429 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
431 output: match output {
432 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
433 clean::FnRetTy::DefaultReturn => None,
440 impl FromWithTcx<clean::Trait> for Trait {
441 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
442 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
445 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
447 generics: generics.into_tcx(tcx),
448 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
449 implementors: Vec::new(), // Added in JsonRenderer::item
454 impl FromWithTcx<clean::Impl> for Impl {
455 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
459 provided_trait_methods,
469 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
470 generics: generics.into_tcx(tcx),
471 provided_trait_methods: provided_trait_methods
473 .map(|x| x.to_string())
475 trait_: trait_.map(|x| x.into_tcx(tcx)),
476 for_: for_.into_tcx(tcx),
478 negative: negative_polarity,
480 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
485 crate fn from_function_method(
486 function: clean::Function,
490 let clean::Function { header, decl, generics } = function;
492 decl: decl.into_tcx(tcx),
493 generics: generics.into_tcx(tcx),
494 header: from_fn_header(&header),
495 abi: header.abi.to_string(),
500 impl FromWithTcx<clean::Enum> for Enum {
501 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
502 let clean::Enum { variants, generics, variants_stripped } = enum_;
504 generics: generics.into_tcx(tcx),
506 variants: ids(variants),
507 impls: Vec::new(), // Added in JsonRenderer::item
512 impl FromWithTcx<clean::VariantStruct> for Struct {
513 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
514 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
516 struct_type: from_ctor_kind(struct_type),
517 generics: Default::default(),
525 impl FromWithTcx<clean::Variant> for Variant {
526 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
527 use clean::Variant::*;
529 CLike => Variant::Plain,
530 Tuple(t) => Variant::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
531 Struct(s) => Variant::Struct(ids(s.fields)),
536 impl FromWithTcx<clean::Import> for Import {
537 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
538 use clean::ImportKind::*;
540 Simple(s) => Import {
541 source: import.source.path.whole_name(),
543 id: import.source.did.map(from_def_id),
547 source: import.source.path.whole_name(),
548 name: import.source.path.last_name().to_string(),
549 id: import.source.did.map(from_def_id),
556 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
557 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
559 kind: from_macro_kind(mac.kind),
560 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
565 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
566 use rustc_span::hygiene::MacroKind::*;
568 Bang => MacroKind::Bang,
569 Attr => MacroKind::Attr,
570 Derive => MacroKind::Derive,
574 impl FromWithTcx<clean::Typedef> for Typedef {
575 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
576 let clean::Typedef { type_, generics, item_type: _ } = typedef;
577 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
581 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
582 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
584 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
585 generics: opaque.generics.into_tcx(tcx),
590 impl FromWithTcx<clean::Static> for Static {
591 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
593 type_: stat.type_.into_tcx(tcx),
594 mutable: stat.mutability == ast::Mutability::Mut,
595 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
600 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
601 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
603 generics: alias.generics.into_tcx(tcx),
604 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
609 impl FromWithTcx<ItemType> for ItemKind {
610 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
613 Module => ItemKind::Module,
614 ExternCrate => ItemKind::ExternCrate,
615 Import => ItemKind::Import,
616 Struct => ItemKind::Struct,
617 Union => ItemKind::Union,
618 Enum => ItemKind::Enum,
619 Function => ItemKind::Function,
620 Typedef => ItemKind::Typedef,
621 OpaqueTy => ItemKind::OpaqueTy,
622 Static => ItemKind::Static,
623 Constant => ItemKind::Constant,
624 Trait => ItemKind::Trait,
625 Impl => ItemKind::Impl,
626 TyMethod | Method => ItemKind::Method,
627 StructField => ItemKind::StructField,
628 Variant => ItemKind::Variant,
629 Macro => ItemKind::Macro,
630 Primitive => ItemKind::Primitive,
631 AssocConst => ItemKind::AssocConst,
632 AssocType => ItemKind::AssocType,
633 ForeignType => ItemKind::ForeignType,
634 Keyword => ItemKind::Keyword,
635 TraitAlias => ItemKind::TraitAlias,
636 ProcAttribute => ItemKind::ProcAttribute,
637 ProcDerive => ItemKind::ProcDerive,
642 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
643 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_def_id(i.def_id)).collect()