]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/conversions.rs
Auto merge of #100759 - fee1-dead-contrib:const_eval_select_real_intrinsic, r=oli...
[rust.git] / src / librustdoc / json / conversions.rs
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.
4
5 #![allow(rustc::default_hash_types)]
6
7 use std::convert::From;
8 use std::fmt;
9
10 use rustc_ast::ast;
11 use rustc_hir::{def::CtorKind, def_id::DefId};
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_span::{Pos, Symbol};
14 use rustc_target::spec::abi::Abi as RustcAbi;
15
16 use rustdoc_json_types::*;
17
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
23 impl JsonRenderer<'_> {
24     pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
25         let deprecation = item.deprecation(self.tcx);
26         let links = self
27             .cache
28             .intra_doc_links
29             .get(&item.item_id)
30             .into_iter()
31             .flatten()
32             .map(|clean::ItemLink { link, did, .. }| {
33                 (link.clone(), from_item_id((*did).into(), self.tcx))
34             })
35             .collect();
36         let docs = item.attrs.collapsed_doc_value();
37         let attrs = item
38             .attrs
39             .other_attrs
40             .iter()
41             .map(rustc_ast_pretty::pprust::attribute_to_string)
42             .collect();
43         let span = item.span(self.tcx);
44         let clean::Item { name, attrs: _, kind: _, visibility, item_id, cfg: _ } = item;
45         let inner = match *item.kind {
46             clean::KeywordItem => return None,
47             clean::StrippedItem(ref inner) => {
48                 match &**inner {
49                     // We document stripped modules as with `Module::is_stripped` set to
50                     // `true`, to prevent contained items from being orphaned for downstream users,
51                     // as JSON does no inlining.
52                     clean::ModuleItem(_)
53                         if self.imported_items.contains(&item_id.expect_def_id()) =>
54                     {
55                         from_clean_item(item, self.tcx)
56                     }
57                     _ => return None,
58                 }
59             }
60             _ => from_clean_item(item, self.tcx),
61         };
62         Some(Item {
63             id: from_item_id_with_name(item_id, self.tcx, name),
64             crate_id: item_id.krate().as_u32(),
65             name: name.map(|sym| sym.to_string()),
66             span: span.and_then(|span| self.convert_span(span)),
67             visibility: self.convert_visibility(visibility),
68             docs,
69             attrs,
70             deprecation: deprecation.map(from_deprecation),
71             inner,
72             links,
73         })
74     }
75
76     fn convert_span(&self, span: clean::Span) -> Option<Span> {
77         match span.filename(self.sess()) {
78             rustc_span::FileName::Real(name) => {
79                 if let Some(local_path) = name.into_local_path() {
80                     let hi = span.hi(self.sess());
81                     let lo = span.lo(self.sess());
82                     Some(Span {
83                         filename: local_path,
84                         begin: (lo.line, lo.col.to_usize()),
85                         end: (hi.line, hi.col.to_usize()),
86                     })
87                 } else {
88                     None
89                 }
90             }
91             _ => None,
92         }
93     }
94
95     fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
96         use clean::Visibility::*;
97         match v {
98             Public => Visibility::Public,
99             Inherited => Visibility::Default,
100             Restricted(did) if did.is_crate_root() => Visibility::Crate,
101             Restricted(did) => Visibility::Restricted {
102                 parent: from_item_id(did.into(), self.tcx),
103                 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
104             },
105         }
106     }
107 }
108
109 pub(crate) trait FromWithTcx<T> {
110     fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self;
111 }
112
113 pub(crate) trait IntoWithTcx<T> {
114     fn into_tcx(self, tcx: TyCtxt<'_>) -> T;
115 }
116
117 impl<T, U> IntoWithTcx<U> for T
118 where
119     U: FromWithTcx<T>,
120 {
121     fn into_tcx(self, tcx: TyCtxt<'_>) -> U {
122         U::from_tcx(self, tcx)
123     }
124 }
125
126 impl<I, T, U> FromWithTcx<I> for Vec<U>
127 where
128     I: IntoIterator<Item = T>,
129     U: FromWithTcx<T>,
130 {
131     fn from_tcx(f: I, tcx: TyCtxt<'_>) -> Vec<U> {
132         f.into_iter().map(|x| x.into_tcx(tcx)).collect()
133     }
134 }
135
136 pub(crate) fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
137     #[rustfmt::skip]
138     let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
139     Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
140 }
141
142 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
143     fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
144         use clean::GenericArgs::*;
145         match args {
146             AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
147                 args: args.into_vec().into_tcx(tcx),
148                 bindings: bindings.into_tcx(tcx),
149             },
150             Parenthesized { inputs, output } => GenericArgs::Parenthesized {
151                 inputs: inputs.into_vec().into_tcx(tcx),
152                 output: output.map(|a| (*a).into_tcx(tcx)),
153             },
154         }
155     }
156 }
157
158 impl FromWithTcx<clean::GenericArg> for GenericArg {
159     fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
160         use clean::GenericArg::*;
161         match arg {
162             Lifetime(l) => GenericArg::Lifetime(convert_lifetime(l)),
163             Type(t) => GenericArg::Type(t.into_tcx(tcx)),
164             Const(box c) => GenericArg::Const(c.into_tcx(tcx)),
165             Infer => GenericArg::Infer,
166         }
167     }
168 }
169
170 impl FromWithTcx<clean::Constant> for Constant {
171     fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
172         let expr = constant.expr(tcx);
173         let value = constant.value(tcx);
174         let is_literal = constant.is_literal(tcx);
175         Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
176     }
177 }
178
179 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
180     fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
181         TypeBinding {
182             name: binding.assoc.name.to_string(),
183             args: binding.assoc.args.into_tcx(tcx),
184             binding: binding.kind.into_tcx(tcx),
185         }
186     }
187 }
188
189 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
190     fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
191         use clean::TypeBindingKind::*;
192         match kind {
193             Equality { term } => TypeBindingKind::Equality(term.into_tcx(tcx)),
194             Constraint { bounds } => TypeBindingKind::Constraint(bounds.into_tcx(tcx)),
195         }
196     }
197 }
198
199 /// It generates an ID as follows:
200 ///
201 /// `CRATE_ID:ITEM_ID[:NAME_ID]` (if there is no name, NAME_ID is not generated).
202 pub(crate) fn from_item_id(item_id: ItemId, tcx: TyCtxt<'_>) -> Id {
203     from_item_id_with_name(item_id, tcx, None)
204 }
205
206 // FIXME: this function (and appending the name at the end of the ID) should be removed when
207 // reexports are not inlined anymore for json format. It should be done in #93518.
208 pub(crate) fn from_item_id_with_name(item_id: ItemId, tcx: TyCtxt<'_>, name: Option<Symbol>) -> Id {
209     struct DisplayDefId<'a>(DefId, TyCtxt<'a>, Option<Symbol>);
210
211     impl<'a> fmt::Display for DisplayDefId<'a> {
212         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213             let name = match self.2 {
214                 Some(name) => format!(":{}", name.as_u32()),
215                 None => self
216                     .1
217                     .opt_item_name(self.0)
218                     .map(|n| format!(":{}", n.as_u32()))
219                     .unwrap_or_default(),
220             };
221             write!(f, "{}:{}{}", self.0.krate.as_u32(), u32::from(self.0.index), name)
222         }
223     }
224
225     match item_id {
226         ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did, tcx, name))),
227         ItemId::Blanket { for_, impl_id } => {
228             Id(format!("b:{}-{}", DisplayDefId(impl_id, tcx, None), DisplayDefId(for_, tcx, name)))
229         }
230         ItemId::Auto { for_, trait_ } => {
231             Id(format!("a:{}-{}", DisplayDefId(trait_, tcx, None), DisplayDefId(for_, tcx, name)))
232         }
233         ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())),
234     }
235 }
236
237 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
238     use clean::ItemKind::*;
239     let name = item.name;
240     let is_crate = item.is_crate();
241     let header = item.fn_header(tcx);
242
243     match *item.kind {
244         ModuleItem(m) => {
245             ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false })
246         }
247         ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
248         StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
249         UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
250         StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
251         EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
252         VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
253         FunctionItem(f) => ItemEnum::Function(from_function(f, header.unwrap(), tcx)),
254         ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, header.unwrap(), tcx)),
255         TraitItem(t) => ItemEnum::Trait((*t).into_tcx(tcx)),
256         TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
257         MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, header.unwrap(), tcx)),
258         TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, header.unwrap(), tcx)),
259         ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)),
260         StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
261         ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
262         ForeignTypeItem => ItemEnum::ForeignType,
263         TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)),
264         OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
265         ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
266         MacroItem(m) => ItemEnum::Macro(m.source),
267         ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
268         PrimitiveItem(p) => ItemEnum::PrimitiveType(p.as_sym().to_string()),
269         TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None },
270         AssocConstItem(ty, default) => {
271             ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) }
272         }
273         TyAssocTypeItem(g, b) => ItemEnum::AssocType {
274             generics: (*g).into_tcx(tcx),
275             bounds: b.into_tcx(tcx),
276             default: None,
277         },
278         AssocTypeItem(t, b) => ItemEnum::AssocType {
279             generics: t.generics.into_tcx(tcx),
280             bounds: b.into_tcx(tcx),
281             default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)),
282         },
283         // `convert_item` early returns `None` for stripped items and keywords.
284         KeywordItem => unreachable!(),
285         StrippedItem(inner) => {
286             match *inner {
287                 ModuleItem(m) => ItemEnum::Module(Module {
288                     is_crate,
289                     items: ids(m.items, tcx),
290                     is_stripped: true,
291                 }),
292                 // `convert_item` early returns `None` for stripped items we're not including
293                 _ => unreachable!(),
294             }
295         }
296         ExternCrateItem { ref src } => ItemEnum::ExternCrate {
297             name: name.as_ref().unwrap().to_string(),
298             rename: src.map(|x| x.to_string()),
299         },
300     }
301 }
302
303 impl FromWithTcx<clean::Struct> for Struct {
304     fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
305         let fields_stripped = struct_.has_stripped_entries();
306         let clean::Struct { struct_type, generics, fields } = struct_;
307         Struct {
308             struct_type: from_ctor_kind(struct_type),
309             generics: generics.into_tcx(tcx),
310             fields_stripped,
311             fields: ids(fields, tcx),
312             impls: Vec::new(), // Added in JsonRenderer::item
313         }
314     }
315 }
316
317 impl FromWithTcx<clean::Union> for Union {
318     fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self {
319         let fields_stripped = union_.has_stripped_entries();
320         let clean::Union { generics, fields } = union_;
321         Union {
322             generics: generics.into_tcx(tcx),
323             fields_stripped,
324             fields: ids(fields, tcx),
325             impls: Vec::new(), // Added in JsonRenderer::item
326         }
327     }
328 }
329
330 pub(crate) fn from_ctor_kind(struct_type: CtorKind) -> StructType {
331     match struct_type {
332         CtorKind::Fictive => StructType::Plain,
333         CtorKind::Fn => StructType::Tuple,
334         CtorKind::Const => StructType::Unit,
335     }
336 }
337
338 pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header {
339     Header {
340         async_: header.is_async(),
341         const_: header.is_const(),
342         unsafe_: header.is_unsafe(),
343         abi: convert_abi(header.abi),
344     }
345 }
346
347 fn convert_abi(a: RustcAbi) -> Abi {
348     match a {
349         RustcAbi::Rust => Abi::Rust,
350         RustcAbi::C { unwind } => Abi::C { unwind },
351         RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
352         RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
353         RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
354         RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
355         RustcAbi::Win64 { unwind } => Abi::Win64 { unwind },
356         RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
357         RustcAbi::System { unwind } => Abi::System { unwind },
358         _ => Abi::Other(a.to_string()),
359     }
360 }
361
362 fn convert_lifetime(l: clean::Lifetime) -> String {
363     l.0.to_string()
364 }
365
366 impl FromWithTcx<clean::Generics> for Generics {
367     fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
368         Generics {
369             params: generics.params.into_tcx(tcx),
370             where_predicates: generics.where_predicates.into_tcx(tcx),
371         }
372     }
373 }
374
375 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
376     fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
377         GenericParamDef {
378             name: generic_param.name.to_string(),
379             kind: generic_param.kind.into_tcx(tcx),
380         }
381     }
382 }
383
384 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
385     fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
386         use clean::GenericParamDefKind::*;
387         match kind {
388             Lifetime { outlives } => GenericParamDefKind::Lifetime {
389                 outlives: outlives.into_iter().map(convert_lifetime).collect(),
390             },
391             Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type {
392                 bounds: bounds.into_tcx(tcx),
393                 default: default.map(|x| (*x).into_tcx(tcx)),
394                 synthetic,
395             },
396             Const { did: _, ty, default } => GenericParamDefKind::Const {
397                 type_: (*ty).into_tcx(tcx),
398                 default: default.map(|x| *x),
399             },
400         }
401     }
402 }
403
404 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
405     fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
406         use clean::WherePredicate::*;
407         match predicate {
408             BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
409                 type_: ty.into_tcx(tcx),
410                 bounds: bounds.into_tcx(tcx),
411                 generic_params: bound_params
412                     .into_iter()
413                     .map(|x| GenericParamDef {
414                         name: x.0.to_string(),
415                         kind: GenericParamDefKind::Lifetime { outlives: vec![] },
416                     })
417                     .collect(),
418             },
419             RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
420                 lifetime: convert_lifetime(lifetime),
421                 bounds: bounds.into_tcx(tcx),
422             },
423             EqPredicate { lhs, rhs } => {
424                 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
425             }
426         }
427     }
428 }
429
430 impl FromWithTcx<clean::GenericBound> for GenericBound {
431     fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
432         use clean::GenericBound::*;
433         match bound {
434             TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
435                 GenericBound::TraitBound {
436                     trait_: trait_.into_tcx(tcx),
437                     generic_params: generic_params.into_tcx(tcx),
438                     modifier: from_trait_bound_modifier(modifier),
439                 }
440             }
441             Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
442         }
443     }
444 }
445
446 pub(crate) fn from_trait_bound_modifier(
447     modifier: rustc_hir::TraitBoundModifier,
448 ) -> TraitBoundModifier {
449     use rustc_hir::TraitBoundModifier::*;
450     match modifier {
451         None => TraitBoundModifier::None,
452         Maybe => TraitBoundModifier::Maybe,
453         MaybeConst => TraitBoundModifier::MaybeConst,
454     }
455 }
456
457 impl FromWithTcx<clean::Type> for Type {
458     fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
459         use clean::Type::{
460             Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
461             RawPointer, Slice, Tuple,
462         };
463
464         match ty {
465             clean::Type::Path { path } => Type::ResolvedPath(path.into_tcx(tcx)),
466             clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
467                 lifetime: lt.map(convert_lifetime),
468                 traits: bounds.into_tcx(tcx),
469             }),
470             Generic(s) => Type::Generic(s.to_string()),
471             Primitive(p) => Type::Primitive(p.as_sym().to_string()),
472             BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
473             Tuple(t) => Type::Tuple(t.into_tcx(tcx)),
474             Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
475             Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
476             ImplTrait(g) => Type::ImplTrait(g.into_tcx(tcx)),
477             Infer => Type::Infer,
478             RawPointer(mutability, type_) => Type::RawPointer {
479                 mutable: mutability == ast::Mutability::Mut,
480                 type_: Box::new((*type_).into_tcx(tcx)),
481             },
482             BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
483                 lifetime: lifetime.map(convert_lifetime),
484                 mutable: mutability == ast::Mutability::Mut,
485                 type_: Box::new((*type_).into_tcx(tcx)),
486             },
487             QPath(box clean::QPathData { assoc, self_type, trait_, .. }) => Type::QualifiedPath {
488                 name: assoc.name.to_string(),
489                 args: Box::new(assoc.args.into_tcx(tcx)),
490                 self_type: Box::new(self_type.into_tcx(tcx)),
491                 trait_: trait_.into_tcx(tcx),
492             },
493         }
494     }
495 }
496
497 impl FromWithTcx<clean::Path> for Path {
498     fn from_tcx(path: clean::Path, tcx: TyCtxt<'_>) -> Path {
499         Path {
500             name: path.whole_name(),
501             id: from_item_id(path.def_id().into(), tcx),
502             args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
503         }
504     }
505 }
506
507 impl FromWithTcx<clean::Term> for Term {
508     fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
509         match term {
510             clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
511             clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
512         }
513     }
514 }
515
516 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
517     fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
518         let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
519         FunctionPointer {
520             header: Header {
521                 unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe),
522                 const_: false,
523                 async_: false,
524                 abi: convert_abi(abi),
525             },
526             generic_params: generic_params.into_tcx(tcx),
527             decl: decl.into_tcx(tcx),
528         }
529     }
530 }
531
532 impl FromWithTcx<clean::FnDecl> for FnDecl {
533     fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
534         let clean::FnDecl { inputs, output, c_variadic } = decl;
535         FnDecl {
536             inputs: inputs
537                 .values
538                 .into_iter()
539                 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
540                 .collect(),
541             output: match output {
542                 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
543                 clean::FnRetTy::DefaultReturn => None,
544             },
545             c_variadic,
546         }
547     }
548 }
549
550 impl FromWithTcx<clean::Trait> for Trait {
551     fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
552         let is_auto = trait_.is_auto(tcx);
553         let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe;
554         let clean::Trait { items, generics, bounds, .. } = trait_;
555         Trait {
556             is_auto,
557             is_unsafe,
558             items: ids(items, tcx),
559             generics: generics.into_tcx(tcx),
560             bounds: bounds.into_tcx(tcx),
561             implementations: Vec::new(), // Added in JsonRenderer::item
562         }
563     }
564 }
565
566 impl FromWithTcx<clean::PolyTrait> for PolyTrait {
567     fn from_tcx(
568         clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
569         tcx: TyCtxt<'_>,
570     ) -> Self {
571         PolyTrait { trait_: trait_.into_tcx(tcx), generic_params: generic_params.into_tcx(tcx) }
572     }
573 }
574
575 impl FromWithTcx<clean::Impl> for Impl {
576     fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
577         let provided_trait_methods = impl_.provided_trait_methods(tcx);
578         let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
579         // FIXME: use something like ImplKind in JSON?
580         let (synthetic, blanket_impl) = match kind {
581             clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
582             clean::ImplKind::Auto => (true, None),
583             clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
584         };
585         let negative_polarity = match polarity {
586             ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
587             ty::ImplPolarity::Negative => true,
588         };
589         Impl {
590             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
591             generics: generics.into_tcx(tcx),
592             provided_trait_methods: provided_trait_methods
593                 .into_iter()
594                 .map(|x| x.to_string())
595                 .collect(),
596             trait_: trait_.map(|path| path.into_tcx(tcx)),
597             for_: for_.into_tcx(tcx),
598             items: ids(items, tcx),
599             negative: negative_polarity,
600             synthetic,
601             blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
602         }
603     }
604 }
605
606 pub(crate) fn from_function(
607     function: Box<clean::Function>,
608     header: rustc_hir::FnHeader,
609     tcx: TyCtxt<'_>,
610 ) -> Function {
611     let clean::Function { decl, generics } = *function;
612     Function {
613         decl: decl.into_tcx(tcx),
614         generics: generics.into_tcx(tcx),
615         header: from_fn_header(&header),
616     }
617 }
618
619 pub(crate) fn from_function_method(
620     function: Box<clean::Function>,
621     has_body: bool,
622     header: rustc_hir::FnHeader,
623     tcx: TyCtxt<'_>,
624 ) -> Method {
625     let clean::Function { decl, generics } = *function;
626     Method {
627         decl: decl.into_tcx(tcx),
628         generics: generics.into_tcx(tcx),
629         header: from_fn_header(&header),
630         has_body,
631     }
632 }
633
634 impl FromWithTcx<clean::Enum> for Enum {
635     fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
636         let variants_stripped = enum_.has_stripped_entries();
637         let clean::Enum { variants, generics } = enum_;
638         Enum {
639             generics: generics.into_tcx(tcx),
640             variants_stripped,
641             variants: ids(variants, tcx),
642             impls: Vec::new(), // Added in JsonRenderer::item
643         }
644     }
645 }
646
647 impl FromWithTcx<clean::VariantStruct> for Struct {
648     fn from_tcx(struct_: clean::VariantStruct, tcx: TyCtxt<'_>) -> Self {
649         let fields_stripped = struct_.has_stripped_entries();
650         let clean::VariantStruct { struct_type, fields } = struct_;
651         Struct {
652             struct_type: from_ctor_kind(struct_type),
653             generics: Generics { params: vec![], where_predicates: vec![] },
654             fields_stripped,
655             fields: ids(fields, tcx),
656             impls: Vec::new(),
657         }
658     }
659 }
660
661 impl FromWithTcx<clean::Variant> for Variant {
662     fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
663         use clean::Variant::*;
664         match variant {
665             CLike => Variant::Plain,
666             Tuple(fields) => Variant::Tuple(
667                 fields
668                     .into_iter()
669                     .filter_map(|f| match *f.kind {
670                         clean::StructFieldItem(ty) => Some(ty.into_tcx(tcx)),
671                         clean::StrippedItem(_) => None,
672                         _ => unreachable!(),
673                     })
674                     .collect(),
675             ),
676             Struct(s) => Variant::Struct(ids(s.fields, tcx)),
677         }
678     }
679 }
680
681 impl FromWithTcx<clean::Import> for Import {
682     fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
683         use clean::ImportKind::*;
684         let (name, glob) = match import.kind {
685             Simple(s) => (s.to_string(), false),
686             Glob => (
687                 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
688                 true,
689             ),
690         };
691         Import {
692             source: import.source.path.whole_name(),
693             name,
694             id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
695             glob,
696         }
697     }
698 }
699
700 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
701     fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
702         ProcMacro {
703             kind: from_macro_kind(mac.kind),
704             helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
705         }
706     }
707 }
708
709 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
710     use rustc_span::hygiene::MacroKind::*;
711     match kind {
712         Bang => MacroKind::Bang,
713         Attr => MacroKind::Attr,
714         Derive => MacroKind::Derive,
715     }
716 }
717
718 impl FromWithTcx<Box<clean::Typedef>> for Typedef {
719     fn from_tcx(typedef: Box<clean::Typedef>, tcx: TyCtxt<'_>) -> Self {
720         let clean::Typedef { type_, generics, item_type: _ } = *typedef;
721         Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
722     }
723 }
724
725 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
726     fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
727         OpaqueTy { bounds: opaque.bounds.into_tcx(tcx), generics: opaque.generics.into_tcx(tcx) }
728     }
729 }
730
731 impl FromWithTcx<clean::Static> for Static {
732     fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
733         Static {
734             type_: stat.type_.into_tcx(tcx),
735             mutable: stat.mutability == ast::Mutability::Mut,
736             expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
737         }
738     }
739 }
740
741 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
742     fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
743         TraitAlias { generics: alias.generics.into_tcx(tcx), params: alias.bounds.into_tcx(tcx) }
744     }
745 }
746
747 impl FromWithTcx<ItemType> for ItemKind {
748     fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
749         use ItemType::*;
750         match kind {
751             Module => ItemKind::Module,
752             ExternCrate => ItemKind::ExternCrate,
753             Import => ItemKind::Import,
754             Struct => ItemKind::Struct,
755             Union => ItemKind::Union,
756             Enum => ItemKind::Enum,
757             Function => ItemKind::Function,
758             Typedef => ItemKind::Typedef,
759             OpaqueTy => ItemKind::OpaqueTy,
760             Static => ItemKind::Static,
761             Constant => ItemKind::Constant,
762             Trait => ItemKind::Trait,
763             Impl => ItemKind::Impl,
764             TyMethod | Method => ItemKind::Method,
765             StructField => ItemKind::StructField,
766             Variant => ItemKind::Variant,
767             Macro => ItemKind::Macro,
768             Primitive => ItemKind::Primitive,
769             AssocConst => ItemKind::AssocConst,
770             AssocType => ItemKind::AssocType,
771             ForeignType => ItemKind::ForeignType,
772             Keyword => ItemKind::Keyword,
773             TraitAlias => ItemKind::TraitAlias,
774             ProcAttribute => ItemKind::ProcAttribute,
775             ProcDerive => ItemKind::ProcDerive,
776         }
777     }
778 }
779
780 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
781     items
782         .into_iter()
783         .filter(|x| !x.is_stripped() && !x.is_keyword())
784         .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
785         .collect()
786 }