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);
27 let clean::Item { span, name, attrs, kind, visibility, def_id } = item;
28 let inner = match *kind {
29 clean::StrippedItem(_) => return None,
30 kind => from_clean_item_kind(kind, self.tcx, &name),
33 id: from_def_id(def_id),
34 crate_id: def_id.krate.as_u32(),
35 name: name.map(|sym| sym.to_string()),
36 span: self.convert_span(span),
37 visibility: self.convert_visibility(visibility),
38 docs: attrs.collapsed_doc_value(),
42 .filter_map(|clean::ItemLink { link, did, .. }| {
43 did.map(|did| (link, from_def_id(did)))
49 .map(rustc_ast_pretty::pprust::attribute_to_string)
51 deprecation: deprecation.map(from_deprecation),
56 fn convert_span(&self, span: clean::Span) -> Option<Span> {
57 match span.filename(self.sess()) {
58 rustc_span::FileName::Real(name) => {
59 let hi = span.hi(self.sess());
60 let lo = span.lo(self.sess());
62 filename: match name {
63 rustc_span::RealFileName::Named(path) => path,
64 rustc_span::RealFileName::Devirtualized { local_path, virtual_name: _ } => {
68 begin: (lo.line, lo.col.to_usize()),
69 end: (hi.line, hi.col.to_usize()),
76 fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
77 use clean::Visibility::*;
79 Public => Visibility::Public,
80 Inherited => Visibility::Default,
81 Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
82 Restricted(did) => Visibility::Restricted {
83 parent: from_def_id(did),
84 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
90 crate trait FromWithTcx<T> {
91 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
94 crate trait IntoWithTcx<T> {
95 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
98 impl<T, U> IntoWithTcx<U> for T
102 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
103 U::from_tcx(self, tcx)
107 crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
109 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
110 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
113 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
114 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
115 use clean::GenericArgs::*;
117 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
118 args: args.into_iter().map(|a| a.into_tcx(tcx)).collect(),
119 bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(),
121 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
122 inputs: inputs.into_iter().map(|a| a.into_tcx(tcx)).collect(),
123 output: output.map(|a| a.into_tcx(tcx)),
129 impl FromWithTcx<clean::GenericArg> for GenericArg {
130 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
131 use clean::GenericArg::*;
133 Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
134 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
135 Const(c) => GenericArg::Const(c.into_tcx(tcx)),
140 impl FromWithTcx<clean::Constant> for Constant {
141 fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
142 let expr = constant.expr(tcx);
143 let value = constant.value(tcx);
144 let is_literal = constant.is_literal(tcx);
145 Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
149 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
150 fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
151 TypeBinding { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
155 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
156 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
157 use clean::TypeBindingKind::*;
159 Equality { ty } => TypeBindingKind::Equality(ty.into_tcx(tcx)),
160 Constraint { bounds } => {
161 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
167 crate fn from_def_id(did: DefId) -> Id {
168 Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
171 fn from_clean_item_kind(item: clean::ItemKind, tcx: TyCtxt<'_>, name: &Option<Symbol>) -> ItemEnum {
172 use clean::ItemKind::*;
174 ModuleItem(m) => ItemEnum::Module(m.into_tcx(tcx)),
175 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
176 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
177 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
178 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
179 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
180 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
181 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
182 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
183 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
184 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
185 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
186 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
187 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
188 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
189 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
190 ForeignTypeItem => ItemEnum::ForeignType,
191 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
192 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
193 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
194 MacroItem(m) => ItemEnum::Macro(m.source),
195 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
196 AssocConstItem(t, s) => ItemEnum::AssocConst { type_: t.into_tcx(tcx), default: s },
197 AssocTypeItem(g, t) => ItemEnum::AssocType {
198 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
199 default: t.map(|x| x.into_tcx(tcx)),
201 // `convert_item` early returns `None` for striped items
202 StrippedItem(_) => unreachable!(),
203 PrimitiveItem(_) | KeywordItem(_) => {
204 panic!("{:?} is not supported for JSON output", item)
206 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
207 name: name.as_ref().unwrap().to_string(),
208 rename: src.map(|x| x.to_string()),
213 impl FromWithTcx<clean::Module> for Module {
214 fn from_tcx(module: clean::Module, _tcx: TyCtxt<'_>) -> Self {
215 Module { is_crate: module.is_crate, items: ids(module.items) }
219 impl FromWithTcx<clean::Struct> for Struct {
220 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
221 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
223 struct_type: from_ctor_kind(struct_type),
224 generics: generics.into_tcx(tcx),
227 impls: Vec::new(), // Added in JsonRenderer::item
232 impl FromWithTcx<clean::Union> for Union {
233 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
234 let clean::Union { generics, fields, fields_stripped } = struct_;
236 generics: generics.into_tcx(tcx),
239 impls: Vec::new(), // Added in JsonRenderer::item
244 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
246 CtorKind::Fictive => StructType::Plain,
247 CtorKind::Fn => StructType::Tuple,
248 CtorKind::Const => StructType::Unit,
252 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
253 let mut v = HashSet::new();
255 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
256 v.insert(Qualifiers::Unsafe);
259 if let rustc_hir::IsAsync::Async = header.asyncness {
260 v.insert(Qualifiers::Async);
263 if let rustc_hir::Constness::Const = header.constness {
264 v.insert(Qualifiers::Const);
270 impl FromWithTcx<clean::Function> for Function {
271 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
272 let clean::Function { decl, generics, header } = function;
274 decl: decl.into_tcx(tcx),
275 generics: generics.into_tcx(tcx),
276 header: from_fn_header(&header),
277 abi: header.abi.to_string(),
282 impl FromWithTcx<clean::Generics> for Generics {
283 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
285 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
286 where_predicates: generics
289 .map(|x| x.into_tcx(tcx))
295 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
296 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
298 name: generic_param.name.to_string(),
299 kind: generic_param.kind.into_tcx(tcx),
304 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
305 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
306 use clean::GenericParamDefKind::*;
308 Lifetime => GenericParamDefKind::Lifetime,
309 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
310 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
311 default: default.map(|x| x.into_tcx(tcx)),
313 Const { did: _, ty } => GenericParamDefKind::Const(ty.into_tcx(tcx)),
318 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
319 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
320 use clean::WherePredicate::*;
322 BoundPredicate { ty, bounds } => WherePredicate::BoundPredicate {
323 ty: ty.into_tcx(tcx),
324 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
326 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
327 lifetime: lifetime.0.to_string(),
328 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
330 EqPredicate { lhs, rhs } => {
331 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
337 impl FromWithTcx<clean::GenericBound> for GenericBound {
338 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
339 use clean::GenericBound::*;
341 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
342 GenericBound::TraitBound {
343 trait_: trait_.into_tcx(tcx),
344 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
345 modifier: from_trait_bound_modifier(modifier),
348 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
353 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
354 use rustc_hir::TraitBoundModifier::*;
356 None => TraitBoundModifier::None,
357 Maybe => TraitBoundModifier::Maybe,
358 MaybeConst => TraitBoundModifier::MaybeConst,
362 impl FromWithTcx<clean::Type> for Type {
363 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
366 ResolvedPath { path, param_names, did, is_generic: _ } => Type::ResolvedPath {
367 name: path.whole_name(),
368 id: from_def_id(did),
369 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
370 param_names: param_names
371 .map(|v| v.into_iter().map(|x| x.into_tcx(tcx)).collect())
372 .unwrap_or_default(),
374 Generic(s) => Type::Generic(s.to_string()),
375 Primitive(p) => Type::Primitive(p.as_str().to_string()),
376 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
377 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
378 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
379 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
380 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
381 Never => Type::Never,
382 Infer => Type::Infer,
383 RawPointer(mutability, type_) => Type::RawPointer {
384 mutable: mutability == ast::Mutability::Mut,
385 type_: Box::new((*type_).into_tcx(tcx)),
387 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
388 lifetime: lifetime.map(|l| l.0.to_string()),
389 mutable: mutability == ast::Mutability::Mut,
390 type_: Box::new((*type_).into_tcx(tcx)),
392 QPath { name, self_type, trait_ } => Type::QualifiedPath {
393 name: name.to_string(),
394 self_type: Box::new((*self_type).into_tcx(tcx)),
395 trait_: Box::new((*trait_).into_tcx(tcx)),
401 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
402 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
403 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
405 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
406 let mut hs = HashSet::new();
407 hs.insert(Qualifiers::Unsafe);
412 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
413 decl: decl.into_tcx(tcx),
414 abi: abi.to_string(),
419 impl FromWithTcx<clean::FnDecl> for FnDecl {
420 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
421 let clean::FnDecl { inputs, output, c_variadic, attrs: _ } = decl;
426 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
428 output: match output {
429 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
430 clean::FnRetTy::DefaultReturn => None,
437 impl FromWithTcx<clean::Trait> for Trait {
438 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
439 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
442 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
444 generics: generics.into_tcx(tcx),
445 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
446 implementors: Vec::new(), // Added in JsonRenderer::item
451 impl FromWithTcx<clean::Impl> for Impl {
452 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
456 provided_trait_methods,
465 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
466 generics: generics.into_tcx(tcx),
467 provided_trait_methods: provided_trait_methods
469 .map(|x| x.to_string())
471 trait_: trait_.map(|x| x.into_tcx(tcx)),
472 for_: for_.into_tcx(tcx),
474 negative: negative_polarity,
476 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
481 crate fn from_function_method(
482 function: clean::Function,
486 let clean::Function { header, decl, generics } = function;
488 decl: decl.into_tcx(tcx),
489 generics: generics.into_tcx(tcx),
490 header: from_fn_header(&header),
491 abi: header.abi.to_string(),
496 impl FromWithTcx<clean::Enum> for Enum {
497 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
498 let clean::Enum { variants, generics, variants_stripped } = enum_;
500 generics: generics.into_tcx(tcx),
502 variants: ids(variants),
503 impls: Vec::new(), // Added in JsonRenderer::item
508 impl FromWithTcx<clean::VariantStruct> for Struct {
509 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
510 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
512 struct_type: from_ctor_kind(struct_type),
513 generics: Default::default(),
521 impl FromWithTcx<clean::Variant> for Variant {
522 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
523 use clean::Variant::*;
525 CLike => Variant::Plain,
526 Tuple(t) => Variant::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
527 Struct(s) => Variant::Struct(ids(s.fields)),
532 impl FromWithTcx<clean::Import> for Import {
533 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
534 use clean::ImportKind::*;
536 Simple(s) => Import {
537 source: import.source.path.whole_name(),
539 id: import.source.did.map(from_def_id),
543 source: import.source.path.whole_name(),
544 name: import.source.path.last_name().to_string(),
545 id: import.source.did.map(from_def_id),
552 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
553 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
555 kind: from_macro_kind(mac.kind),
556 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
561 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
562 use rustc_span::hygiene::MacroKind::*;
564 Bang => MacroKind::Bang,
565 Attr => MacroKind::Attr,
566 Derive => MacroKind::Derive,
570 impl FromWithTcx<clean::Typedef> for Typedef {
571 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
572 let clean::Typedef { type_, generics, item_type: _ } = typedef;
573 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
577 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
578 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
580 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
581 generics: opaque.generics.into_tcx(tcx),
586 impl FromWithTcx<clean::Static> for Static {
587 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
589 type_: stat.type_.into_tcx(tcx),
590 mutable: stat.mutability == ast::Mutability::Mut,
591 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
596 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
597 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
599 generics: alias.generics.into_tcx(tcx),
600 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
605 impl FromWithTcx<ItemType> for ItemKind {
606 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
609 Module => ItemKind::Module,
610 ExternCrate => ItemKind::ExternCrate,
611 Import => ItemKind::Import,
612 Struct => ItemKind::Struct,
613 Union => ItemKind::Union,
614 Enum => ItemKind::Enum,
615 Function => ItemKind::Function,
616 Typedef => ItemKind::Typedef,
617 OpaqueTy => ItemKind::OpaqueTy,
618 Static => ItemKind::Static,
619 Constant => ItemKind::Constant,
620 Trait => ItemKind::Trait,
621 Impl => ItemKind::Impl,
622 TyMethod | Method => ItemKind::Method,
623 StructField => ItemKind::StructField,
624 Variant => ItemKind::Variant,
625 Macro => ItemKind::Macro,
626 Primitive => ItemKind::Primitive,
627 AssocConst => ItemKind::AssocConst,
628 AssocType => ItemKind::AssocType,
629 ForeignType => ItemKind::ForeignType,
630 Keyword => ItemKind::Keyword,
631 TraitAlias => ItemKind::TraitAlias,
632 ProcAttribute => ItemKind::ProcAttribute,
633 ProcDerive => ItemKind::ProcDerive,
638 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
639 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_def_id(i.def_id)).collect()