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, param_names, 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: param_names
381 .map(|(v, _)| v.into_iter().map(|x| x.into_tcx(tcx)).collect())
382 .unwrap_or_default(),
384 Generic(s) => Type::Generic(s.to_string()),
385 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
386 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
387 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
388 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
389 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
390 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
391 Never => Type::Never,
392 Infer => Type::Infer,
393 RawPointer(mutability, type_) => Type::RawPointer {
394 mutable: mutability == ast::Mutability::Mut,
395 type_: Box::new((*type_).into_tcx(tcx)),
397 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
398 lifetime: lifetime.map(|l| l.0.to_string()),
399 mutable: mutability == ast::Mutability::Mut,
400 type_: Box::new((*type_).into_tcx(tcx)),
402 QPath { name, self_type, trait_, .. } => Type::QualifiedPath {
403 name: name.to_string(),
404 self_type: Box::new((*self_type).into_tcx(tcx)),
405 trait_: Box::new((*trait_).into_tcx(tcx)),
411 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
412 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
413 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
415 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
416 let mut hs = HashSet::new();
417 hs.insert(Qualifiers::Unsafe);
422 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
423 decl: decl.into_tcx(tcx),
424 abi: abi.to_string(),
429 impl FromWithTcx<clean::FnDecl> for FnDecl {
430 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
431 let clean::FnDecl { inputs, output, c_variadic } = decl;
436 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
438 output: match output {
439 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
440 clean::FnRetTy::DefaultReturn => None,
447 impl FromWithTcx<clean::Trait> for Trait {
448 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
449 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
452 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
454 generics: generics.into_tcx(tcx),
455 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
456 implementors: Vec::new(), // Added in JsonRenderer::item
461 impl FromWithTcx<clean::Impl> for Impl {
462 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
463 let provided_trait_methods = impl_.provided_trait_methods(tcx);
476 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
477 generics: generics.into_tcx(tcx),
478 provided_trait_methods: provided_trait_methods
480 .map(|x| x.to_string())
482 trait_: trait_.map(|x| x.into_tcx(tcx)),
483 for_: for_.into_tcx(tcx),
485 negative: negative_polarity,
487 blanket_impl: blanket_impl.map(|x| (*x).into_tcx(tcx)),
492 crate fn from_function_method(
493 function: clean::Function,
497 let clean::Function { header, decl, generics } = function;
499 decl: decl.into_tcx(tcx),
500 generics: generics.into_tcx(tcx),
501 header: from_fn_header(&header),
502 abi: header.abi.to_string(),
507 impl FromWithTcx<clean::Enum> for Enum {
508 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
509 let clean::Enum { variants, generics, variants_stripped } = enum_;
511 generics: generics.into_tcx(tcx),
513 variants: ids(variants),
514 impls: Vec::new(), // Added in JsonRenderer::item
519 impl FromWithTcx<clean::VariantStruct> for Struct {
520 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
521 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
523 struct_type: from_ctor_kind(struct_type),
524 generics: Default::default(),
532 impl FromWithTcx<clean::Variant> for Variant {
533 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
534 use clean::Variant::*;
536 CLike => Variant::Plain,
537 Tuple(t) => Variant::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
538 Struct(s) => Variant::Struct(ids(s.fields)),
543 impl FromWithTcx<clean::Import> for Import {
544 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
545 use clean::ImportKind::*;
547 Simple(s) => Import {
548 source: import.source.path.whole_name(),
550 id: import.source.did.map(FakeDefId::from).map(from_def_id),
554 source: import.source.path.whole_name(),
555 name: import.source.path.last_name().to_string(),
556 id: import.source.did.map(FakeDefId::from).map(from_def_id),
563 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
564 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
566 kind: from_macro_kind(mac.kind),
567 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
572 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
573 use rustc_span::hygiene::MacroKind::*;
575 Bang => MacroKind::Bang,
576 Attr => MacroKind::Attr,
577 Derive => MacroKind::Derive,
581 impl FromWithTcx<clean::Typedef> for Typedef {
582 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
583 let clean::Typedef { type_, generics, item_type: _ } = typedef;
584 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
588 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
589 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
591 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
592 generics: opaque.generics.into_tcx(tcx),
597 impl FromWithTcx<clean::Static> for Static {
598 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
600 type_: stat.type_.into_tcx(tcx),
601 mutable: stat.mutability == ast::Mutability::Mut,
602 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
607 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
608 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
610 generics: alias.generics.into_tcx(tcx),
611 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
616 impl FromWithTcx<ItemType> for ItemKind {
617 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
620 Module => ItemKind::Module,
621 ExternCrate => ItemKind::ExternCrate,
622 Import => ItemKind::Import,
623 Struct => ItemKind::Struct,
624 Union => ItemKind::Union,
625 Enum => ItemKind::Enum,
626 Function => ItemKind::Function,
627 Typedef => ItemKind::Typedef,
628 OpaqueTy => ItemKind::OpaqueTy,
629 Static => ItemKind::Static,
630 Constant => ItemKind::Constant,
631 Trait => ItemKind::Trait,
632 Impl => ItemKind::Impl,
633 TyMethod | Method => ItemKind::Method,
634 StructField => ItemKind::StructField,
635 Variant => ItemKind::Variant,
636 Macro => ItemKind::Macro,
637 Primitive => ItemKind::Primitive,
638 AssocConst => ItemKind::AssocConst,
639 AssocType => ItemKind::AssocType,
640 ForeignType => ItemKind::ForeignType,
641 Keyword => ItemKind::Keyword,
642 TraitAlias => ItemKind::TraitAlias,
643 ProcAttribute => ItemKind::ProcAttribute,
644 ProcDerive => ItemKind::ProcDerive,
649 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
650 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_def_id(i.def_id)).collect()