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