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;
11 use rustc_hir::{def::CtorKind, def_id::DefId};
12 use rustc_middle::ty::TyCtxt;
13 use rustc_span::def_id::CRATE_DEF_INDEX;
16 use rustdoc_json_types::*;
18 use crate::clean::utils::print_const_expr;
19 use crate::clean::{self, ItemId};
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 .map(|clean::ItemLink { link, did, .. }| (link.clone(), from_item_id((*did).into())))
35 let docs = item.attrs.collapsed_doc_value();
40 .map(rustc_ast_pretty::pprust::attribute_to_string)
42 let span = item.span(self.tcx);
43 let clean::Item { name, attrs: _, kind: _, visibility, def_id, cfg: _ } = item;
44 let inner = match *item.kind {
45 clean::StrippedItem(_) => return None,
46 _ => from_clean_item(item, self.tcx),
49 id: from_item_id(def_id),
50 crate_id: def_id.krate().as_u32(),
51 name: name.map(|sym| sym.to_string()),
52 span: self.convert_span(span),
53 visibility: self.convert_visibility(visibility),
56 deprecation: deprecation.map(from_deprecation),
62 fn convert_span(&self, span: clean::Span) -> Option<Span> {
63 match span.filename(self.sess()) {
64 rustc_span::FileName::Real(name) => {
65 if let Some(local_path) = name.into_local_path() {
66 let hi = span.hi(self.sess());
67 let lo = span.lo(self.sess());
70 begin: (lo.line, lo.col.to_usize()),
71 end: (hi.line, hi.col.to_usize()),
81 fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
82 use clean::Visibility::*;
84 Public => Visibility::Public,
85 Inherited => Visibility::Default,
86 Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
87 Restricted(did) => Visibility::Restricted {
88 parent: from_item_id(did.into()),
89 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
95 crate trait FromWithTcx<T> {
96 fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
99 crate trait IntoWithTcx<T> {
100 fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
103 impl<T, U> IntoWithTcx<U> for T
107 fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
108 U::from_tcx(self, tcx)
112 crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
114 let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
115 Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
118 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
119 fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
120 use clean::GenericArgs::*;
122 AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
123 args: args.into_iter().map(|a| a.into_tcx(tcx)).collect(),
124 bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(),
126 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
127 inputs: inputs.into_iter().map(|a| a.into_tcx(tcx)).collect(),
128 output: output.map(|a| (*a).into_tcx(tcx)),
134 impl FromWithTcx<clean::GenericArg> for GenericArg {
135 fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
136 use clean::GenericArg::*;
138 Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
139 Type(t) => GenericArg::Type(t.into_tcx(tcx)),
140 Const(box c) => GenericArg::Const(c.into_tcx(tcx)),
141 Infer => GenericArg::Infer,
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_item_id(did: ItemId) -> Id {
174 struct DisplayDefId(DefId);
176 impl fmt::Display for DisplayDefId {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 write!(f, "{}:{}", self.0.krate.as_u32(), u32::from(self.0.index))
183 ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did))),
184 ItemId::Blanket { for_, impl_id } => {
185 Id(format!("b:{}-{}", DisplayDefId(impl_id), DisplayDefId(for_)))
187 ItemId::Auto { for_, trait_ } => {
188 Id(format!("a:{}-{}", DisplayDefId(trait_), DisplayDefId(for_)))
190 ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())),
194 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
195 use clean::ItemKind::*;
196 let name = item.name;
197 let is_crate = item.is_crate();
199 ModuleItem(m) => ItemEnum::Module(Module { is_crate, items: ids(m.items) }),
200 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
201 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
202 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
203 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
204 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
205 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
206 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
207 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
208 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
209 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
210 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
211 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
212 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
213 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
214 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
215 ForeignTypeItem => ItemEnum::ForeignType,
216 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
217 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
218 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
219 MacroItem(m) => ItemEnum::Macro(m.source),
220 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
221 AssocConstItem(t, s) => ItemEnum::AssocConst { type_: t.into_tcx(tcx), default: s },
222 AssocTypeItem(g, t) => ItemEnum::AssocType {
223 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
224 default: t.map(|x| x.into_tcx(tcx)),
226 // `convert_item` early returns `None` for striped items
227 StrippedItem(_) => unreachable!(),
228 PrimitiveItem(_) | KeywordItem(_) => {
229 panic!("{:?} is not supported for JSON output", item)
231 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
232 name: name.as_ref().unwrap().to_string(),
233 rename: src.map(|x| x.to_string()),
238 impl FromWithTcx<clean::Struct> for Struct {
239 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
240 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
242 struct_type: from_ctor_kind(struct_type),
243 generics: generics.into_tcx(tcx),
246 impls: Vec::new(), // Added in JsonRenderer::item
251 impl FromWithTcx<clean::Union> for Union {
252 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
253 let clean::Union { generics, fields, fields_stripped } = struct_;
255 generics: generics.into_tcx(tcx),
258 impls: Vec::new(), // Added in JsonRenderer::item
263 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
265 CtorKind::Fictive => StructType::Plain,
266 CtorKind::Fn => StructType::Tuple,
267 CtorKind::Const => StructType::Unit,
271 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
272 let mut v = HashSet::new();
274 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
275 v.insert(Qualifiers::Unsafe);
278 if let rustc_hir::IsAsync::Async = header.asyncness {
279 v.insert(Qualifiers::Async);
282 if let rustc_hir::Constness::Const = header.constness {
283 v.insert(Qualifiers::Const);
289 impl FromWithTcx<clean::Function> for Function {
290 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
291 let clean::Function { decl, generics, header } = function;
293 decl: decl.into_tcx(tcx),
294 generics: generics.into_tcx(tcx),
295 header: from_fn_header(&header),
296 abi: header.abi.to_string(),
301 impl FromWithTcx<clean::Generics> for Generics {
302 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
304 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
305 where_predicates: generics
308 .map(|x| x.into_tcx(tcx))
314 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
315 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
317 name: generic_param.name.to_string(),
318 kind: generic_param.kind.into_tcx(tcx),
323 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
324 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
325 use clean::GenericParamDefKind::*;
327 Lifetime { outlives } => GenericParamDefKind::Lifetime {
328 outlives: outlives.into_iter().map(|lt| lt.0.to_string()).collect(),
330 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
331 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
332 default: default.map(|x| x.into_tcx(tcx)),
334 Const { did: _, ty, default } => {
335 GenericParamDefKind::Const { ty: ty.into_tcx(tcx), default }
341 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
342 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
343 use clean::WherePredicate::*;
345 BoundPredicate { ty, bounds, .. } => WherePredicate::BoundPredicate {
346 ty: ty.into_tcx(tcx),
347 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
348 // FIXME: add `bound_params` to rustdoc-json-params?
350 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
351 lifetime: lifetime.0.to_string(),
352 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
354 EqPredicate { lhs, rhs } => {
355 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
361 impl FromWithTcx<clean::GenericBound> for GenericBound {
362 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
363 use clean::GenericBound::*;
365 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
366 GenericBound::TraitBound {
367 trait_: trait_.into_tcx(tcx),
368 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
369 modifier: from_trait_bound_modifier(modifier),
372 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
377 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
378 use rustc_hir::TraitBoundModifier::*;
380 None => TraitBoundModifier::None,
381 Maybe => TraitBoundModifier::Maybe,
382 MaybeConst => TraitBoundModifier::MaybeConst,
386 impl FromWithTcx<clean::Type> for Type {
387 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
390 ResolvedPath { path, did } => Type::ResolvedPath {
391 name: path.whole_name(),
392 id: from_item_id(did.into()),
393 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
394 param_names: Vec::new(),
396 DynTrait(mut bounds, lt) => {
397 let (path, id) = match bounds.remove(0).trait_ {
398 ResolvedPath { path, did, .. } => (path, did),
403 name: path.whole_name(),
404 id: from_item_id(id.into()),
408 .map(|args| Box::new(args.clone().args.into_tcx(tcx))),
412 clean::GenericBound::TraitBound(t, rustc_hir::TraitBoundModifier::None)
414 .chain(lt.into_iter().map(|lt| clean::GenericBound::Outlives(lt)))
415 .map(|bound| bound.into_tcx(tcx))
419 Generic(s) => Type::Generic(s.to_string()),
420 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
421 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
422 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
423 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
424 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
425 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
426 Never => Type::Never,
427 Infer => Type::Infer,
428 RawPointer(mutability, type_) => Type::RawPointer {
429 mutable: mutability == ast::Mutability::Mut,
430 type_: Box::new((*type_).into_tcx(tcx)),
432 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
433 lifetime: lifetime.map(|l| l.0.to_string()),
434 mutable: mutability == ast::Mutability::Mut,
435 type_: Box::new((*type_).into_tcx(tcx)),
437 QPath { name, self_type, trait_, .. } => Type::QualifiedPath {
438 name: name.to_string(),
439 self_type: Box::new((*self_type).into_tcx(tcx)),
440 trait_: Box::new((*trait_).into_tcx(tcx)),
446 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
447 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
448 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
450 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
451 let mut hs = HashSet::new();
452 hs.insert(Qualifiers::Unsafe);
457 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
458 decl: decl.into_tcx(tcx),
459 abi: abi.to_string(),
464 impl FromWithTcx<clean::FnDecl> for FnDecl {
465 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
466 let clean::FnDecl { inputs, output, c_variadic } = decl;
471 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
473 output: match output {
474 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
475 clean::FnRetTy::DefaultReturn => None,
482 impl FromWithTcx<clean::Trait> for Trait {
483 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
484 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
487 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
489 generics: generics.into_tcx(tcx),
490 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
491 implementors: Vec::new(), // Added in JsonRenderer::item
496 impl FromWithTcx<clean::Impl> for Impl {
497 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
498 let provided_trait_methods = impl_.provided_trait_methods(tcx);
511 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
512 generics: generics.into_tcx(tcx),
513 provided_trait_methods: provided_trait_methods
515 .map(|x| x.to_string())
517 trait_: trait_.map(|x| x.into_tcx(tcx)),
518 for_: for_.into_tcx(tcx),
520 negative: negative_polarity,
522 blanket_impl: blanket_impl.map(|x| (*x).into_tcx(tcx)),
527 crate fn from_function_method(
528 function: clean::Function,
532 let clean::Function { header, decl, generics } = function;
534 decl: decl.into_tcx(tcx),
535 generics: generics.into_tcx(tcx),
536 header: from_fn_header(&header),
537 abi: header.abi.to_string(),
542 impl FromWithTcx<clean::Enum> for Enum {
543 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
544 let clean::Enum { variants, generics, variants_stripped } = enum_;
546 generics: generics.into_tcx(tcx),
548 variants: ids(variants),
549 impls: Vec::new(), // Added in JsonRenderer::item
554 impl FromWithTcx<clean::VariantStruct> for Struct {
555 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
556 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
558 struct_type: from_ctor_kind(struct_type),
559 generics: Default::default(),
567 impl FromWithTcx<clean::Variant> for Variant {
568 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
569 use clean::Variant::*;
571 CLike => Variant::Plain,
572 Tuple(fields) => Variant::Tuple(
576 if let clean::StructFieldItem(ty) = *f.kind {
584 Struct(s) => Variant::Struct(ids(s.fields)),
589 impl FromWithTcx<clean::Import> for Import {
590 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
591 use clean::ImportKind::*;
593 Simple(s) => Import {
594 source: import.source.path.whole_name(),
596 id: import.source.did.map(ItemId::from).map(from_item_id),
600 source: import.source.path.whole_name(),
601 name: import.source.path.last_name().to_string(),
602 id: import.source.did.map(ItemId::from).map(from_item_id),
609 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
610 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
612 kind: from_macro_kind(mac.kind),
613 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
618 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
619 use rustc_span::hygiene::MacroKind::*;
621 Bang => MacroKind::Bang,
622 Attr => MacroKind::Attr,
623 Derive => MacroKind::Derive,
627 impl FromWithTcx<clean::Typedef> for Typedef {
628 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
629 let clean::Typedef { type_, generics, item_type: _ } = typedef;
630 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
634 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
635 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
637 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
638 generics: opaque.generics.into_tcx(tcx),
643 impl FromWithTcx<clean::Static> for Static {
644 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
646 type_: stat.type_.into_tcx(tcx),
647 mutable: stat.mutability == ast::Mutability::Mut,
648 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
653 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
654 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
656 generics: alias.generics.into_tcx(tcx),
657 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
662 impl FromWithTcx<ItemType> for ItemKind {
663 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
666 Module => ItemKind::Module,
667 ExternCrate => ItemKind::ExternCrate,
668 Import => ItemKind::Import,
669 Struct => ItemKind::Struct,
670 Union => ItemKind::Union,
671 Enum => ItemKind::Enum,
672 Function => ItemKind::Function,
673 Typedef => ItemKind::Typedef,
674 OpaqueTy => ItemKind::OpaqueTy,
675 Static => ItemKind::Static,
676 Constant => ItemKind::Constant,
677 Trait => ItemKind::Trait,
678 Impl => ItemKind::Impl,
679 TyMethod | Method => ItemKind::Method,
680 StructField => ItemKind::StructField,
681 Variant => ItemKind::Variant,
682 Macro => ItemKind::Macro,
683 Primitive => ItemKind::Primitive,
684 AssocConst => ItemKind::AssocConst,
685 AssocType => ItemKind::AssocType,
686 ForeignType => ItemKind::ForeignType,
687 Keyword => ItemKind::Keyword,
688 TraitAlias => ItemKind::TraitAlias,
689 ProcAttribute => ItemKind::ProcAttribute,
690 ProcDerive => ItemKind::ProcDerive,
695 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
696 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_item_id(i.def_id)).collect()