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};
13 use rustc_span::symbol::Symbol;
16 use rustdoc_json_types::*;
19 use crate::clean::utils::print_const_expr;
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_def_id(did)))
37 let clean::Item { span, name, attrs, kind, visibility, def_id } = item;
38 let inner = match *kind {
39 clean::StrippedItem(_) => return None,
40 kind => from_clean_item_kind(kind, self.tcx, &name),
43 id: from_def_id(def_id),
44 crate_id: def_id.krate.as_u32(),
45 name: name.map(|sym| sym.to_string()),
46 span: self.convert_span(span),
47 visibility: self.convert_visibility(visibility),
48 docs: attrs.collapsed_doc_value(),
52 .map(rustc_ast_pretty::pprust::attribute_to_string)
54 deprecation: deprecation.map(from_deprecation),
60 fn convert_span(&self, span: clean::Span) -> Option<Span> {
61 match span.filename(self.sess()) {
62 rustc_span::FileName::Real(name) => {
63 let hi = span.hi(self.sess());
64 let lo = span.lo(self.sess());
66 filename: match name {
67 rustc_span::RealFileName::Named(path) => path,
68 rustc_span::RealFileName::Devirtualized { local_path, virtual_name: _ } => {
72 begin: (lo.line, lo.col.to_usize()),
73 end: (hi.line, hi.col.to_usize()),
80 fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
81 use clean::Visibility::*;
83 Public => Visibility::Public,
84 Inherited => Visibility::Default,
85 Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
86 Restricted(did) => Visibility::Restricted {
87 parent: from_def_id(did),
88 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
94 crate trait FromWithTcx<T> {
95 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
98 crate trait IntoWithTcx<T> {
99 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
102 impl<T, U> IntoWithTcx<U> for T
106 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
107 U::from_tcx(self, tcx)
111 crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
113 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
114 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
117 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
118 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
119 use clean::GenericArgs::*;
121 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
122 args: args.into_iter().map(|a| a.into_tcx(tcx)).collect(),
123 bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(),
125 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
126 inputs: inputs.into_iter().map(|a| a.into_tcx(tcx)).collect(),
127 output: output.map(|a| a.into_tcx(tcx)),
133 impl FromWithTcx<clean::GenericArg> for GenericArg {
134 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
135 use clean::GenericArg::*;
137 Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
138 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
139 Const(c) => GenericArg::Const(c.into_tcx(tcx)),
144 impl FromWithTcx<clean::Constant> for Constant {
145 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
146 let expr = constant.expr(tcx);
147 let value = constant.value(tcx);
148 let is_literal = constant.is_literal(tcx);
149 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
153 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
154 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
155 TypeBinding { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
159 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
160 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
161 use clean::TypeBindingKind::*;
163 Equality { ty } => TypeBindingKind::Equality(ty.into_tcx(tcx)),
164 Constraint { bounds } => {
165 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
171 crate fn from_def_id(did: DefId) -> Id {
172 Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
175 fn from_clean_item_kind(item: clean::ItemKind, tcx: TyCtxt<'_>, name: &Option<Symbol>) -> ItemEnum {
176 use clean::ItemKind::*;
178 ModuleItem(m) => ItemEnum::Module(m.into_tcx(tcx)),
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::Module> for Module {
218 fn from_tcx(module: clean::Module, _tcx: TyCtxt<'_>) -> Self {
219 Module { is_crate: module.is_crate, items: ids(module.items) }
223 impl FromWithTcx<clean::Struct> for Struct {
224 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
225 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
227 struct_type: from_ctor_kind(struct_type),
228 generics: generics.into_tcx(tcx),
231 impls: Vec::new(), // Added in JsonRenderer::item
236 impl FromWithTcx<clean::Union> for Union {
237 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
238 let clean::Union { generics, fields, fields_stripped } = struct_;
240 generics: generics.into_tcx(tcx),
243 impls: Vec::new(), // Added in JsonRenderer::item
248 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
250 CtorKind::Fictive => StructType::Plain,
251 CtorKind::Fn => StructType::Tuple,
252 CtorKind::Const => StructType::Unit,
256 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
257 let mut v = HashSet::new();
259 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
260 v.insert(Qualifiers::Unsafe);
263 if let rustc_hir::IsAsync::Async = header.asyncness {
264 v.insert(Qualifiers::Async);
267 if let rustc_hir::Constness::Const = header.constness {
268 v.insert(Qualifiers::Const);
274 impl FromWithTcx<clean::Function> for Function {
275 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
276 let clean::Function { decl, generics, header } = function;
278 decl: decl.into_tcx(tcx),
279 generics: generics.into_tcx(tcx),
280 header: from_fn_header(&header),
281 abi: header.abi.to_string(),
286 impl FromWithTcx<clean::Generics> for Generics {
287 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
289 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
290 where_predicates: generics
293 .map(|x| x.into_tcx(tcx))
299 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
300 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
302 name: generic_param.name.to_string(),
303 kind: generic_param.kind.into_tcx(tcx),
308 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
309 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
310 use clean::GenericParamDefKind::*;
312 Lifetime => GenericParamDefKind::Lifetime,
313 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
314 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
315 default: default.map(|x| x.into_tcx(tcx)),
317 Const { did: _, ty } => GenericParamDefKind::Const(ty.into_tcx(tcx)),
322 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
323 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
324 use clean::WherePredicate::*;
326 BoundPredicate { ty, bounds } => WherePredicate::BoundPredicate {
327 ty: ty.into_tcx(tcx),
328 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
330 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
331 lifetime: lifetime.0.to_string(),
332 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
334 EqPredicate { lhs, rhs } => {
335 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
341 impl FromWithTcx<clean::GenericBound> for GenericBound {
342 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
343 use clean::GenericBound::*;
345 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
346 GenericBound::TraitBound {
347 trait_: trait_.into_tcx(tcx),
348 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
349 modifier: from_trait_bound_modifier(modifier),
352 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
357 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
358 use rustc_hir::TraitBoundModifier::*;
360 None => TraitBoundModifier::None,
361 Maybe => TraitBoundModifier::Maybe,
362 MaybeConst => TraitBoundModifier::MaybeConst,
366 impl FromWithTcx<clean::Type> for Type {
367 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
370 ResolvedPath { path, param_names, did, is_generic: _ } => Type::ResolvedPath {
371 name: path.whole_name(),
372 id: from_def_id(did),
373 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
374 param_names: param_names
375 .map(|v| v.into_iter().map(|x| x.into_tcx(tcx)).collect())
376 .unwrap_or_default(),
378 Generic(s) => Type::Generic(s.to_string()),
379 Primitive(p) => Type::Primitive(p.as_str().to_string()),
380 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
381 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
382 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
383 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
384 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
385 Never => Type::Never,
386 Infer => Type::Infer,
387 RawPointer(mutability, type_) => Type::RawPointer {
388 mutable: mutability == ast::Mutability::Mut,
389 type_: Box::new((*type_).into_tcx(tcx)),
391 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
392 lifetime: lifetime.map(|l| l.0.to_string()),
393 mutable: mutability == ast::Mutability::Mut,
394 type_: Box::new((*type_).into_tcx(tcx)),
396 QPath { name, self_type, trait_ } => Type::QualifiedPath {
397 name: name.to_string(),
398 self_type: Box::new((*self_type).into_tcx(tcx)),
399 trait_: Box::new((*trait_).into_tcx(tcx)),
405 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
406 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
407 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
409 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
410 let mut hs = HashSet::new();
411 hs.insert(Qualifiers::Unsafe);
416 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
417 decl: decl.into_tcx(tcx),
418 abi: abi.to_string(),
423 impl FromWithTcx<clean::FnDecl> for FnDecl {
424 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
425 let clean::FnDecl { inputs, output, c_variadic, attrs: _ } = decl;
430 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
432 output: match output {
433 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
434 clean::FnRetTy::DefaultReturn => None,
441 impl FromWithTcx<clean::Trait> for Trait {
442 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
443 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
446 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
448 generics: generics.into_tcx(tcx),
449 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
450 implementors: Vec::new(), // Added in JsonRenderer::item
455 impl FromWithTcx<clean::Impl> for Impl {
456 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
460 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()