]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/conversions.rs
Rollup merge of #99480 - miam-miam100:arg-format, r=oli-obk
[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 clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
558         Trait {
559             is_auto,
560             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
561             items: ids(items, tcx),
562             generics: generics.into_tcx(tcx),
563             bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
564             implementations: Vec::new(), // Added in JsonRenderer::item
565         }
566     }
567 }
568
569 impl FromWithTcx<clean::Impl> for Impl {
570     fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
571         let provided_trait_methods = impl_.provided_trait_methods(tcx);
572         let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
573         // FIXME: should `trait_` be a clean::Path equivalent in JSON?
574         let trait_ = trait_.map(|path| clean::Type::Path { path }.into_tcx(tcx));
575         // FIXME: use something like ImplKind in JSON?
576         let (synthetic, blanket_impl) = match kind {
577             clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
578             clean::ImplKind::Auto => (true, None),
579             clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
580         };
581         let negative_polarity = match polarity {
582             ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
583             ty::ImplPolarity::Negative => true,
584         };
585         Impl {
586             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
587             generics: generics.into_tcx(tcx),
588             provided_trait_methods: provided_trait_methods
589                 .into_iter()
590                 .map(|x| x.to_string())
591                 .collect(),
592             trait_,
593             for_: for_.into_tcx(tcx),
594             items: ids(items, tcx),
595             negative: negative_polarity,
596             synthetic,
597             blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
598         }
599     }
600 }
601
602 pub(crate) fn from_function(
603     function: clean::Function,
604     header: rustc_hir::FnHeader,
605     tcx: TyCtxt<'_>,
606 ) -> Function {
607     let clean::Function { decl, generics } = function;
608     Function {
609         decl: decl.into_tcx(tcx),
610         generics: generics.into_tcx(tcx),
611         header: from_fn_header(&header),
612     }
613 }
614
615 pub(crate) fn from_function_method(
616     function: clean::Function,
617     has_body: bool,
618     header: rustc_hir::FnHeader,
619     tcx: TyCtxt<'_>,
620 ) -> Method {
621     let clean::Function { decl, generics } = function;
622     Method {
623         decl: decl.into_tcx(tcx),
624         generics: generics.into_tcx(tcx),
625         header: from_fn_header(&header),
626         has_body,
627     }
628 }
629
630 impl FromWithTcx<clean::Enum> for Enum {
631     fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
632         let variants_stripped = enum_.has_stripped_entries();
633         let clean::Enum { variants, generics } = enum_;
634         Enum {
635             generics: generics.into_tcx(tcx),
636             variants_stripped,
637             variants: ids(variants, tcx),
638             impls: Vec::new(), // Added in JsonRenderer::item
639         }
640     }
641 }
642
643 impl FromWithTcx<clean::VariantStruct> for Struct {
644     fn from_tcx(struct_: clean::VariantStruct, tcx: TyCtxt<'_>) -> Self {
645         let fields_stripped = struct_.has_stripped_entries();
646         let clean::VariantStruct { struct_type, fields } = struct_;
647         Struct {
648             struct_type: from_ctor_kind(struct_type),
649             generics: Generics { params: vec![], where_predicates: vec![] },
650             fields_stripped,
651             fields: ids(fields, tcx),
652             impls: Vec::new(),
653         }
654     }
655 }
656
657 impl FromWithTcx<clean::Variant> for Variant {
658     fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
659         use clean::Variant::*;
660         match variant {
661             CLike => Variant::Plain,
662             Tuple(fields) => Variant::Tuple(
663                 fields
664                     .into_iter()
665                     .map(|f| {
666                         if let clean::StructFieldItem(ty) = *f.kind {
667                             ty.into_tcx(tcx)
668                         } else {
669                             unreachable!()
670                         }
671                     })
672                     .collect(),
673             ),
674             Struct(s) => Variant::Struct(ids(s.fields, tcx)),
675         }
676     }
677 }
678
679 impl FromWithTcx<clean::Import> for Import {
680     fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
681         use clean::ImportKind::*;
682         match import.kind {
683             Simple(s) => Import {
684                 source: import.source.path.whole_name(),
685                 name: s.to_string(),
686                 id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
687                 glob: false,
688             },
689             Glob => Import {
690                 source: import.source.path.whole_name(),
691                 name: import
692                     .source
693                     .path
694                     .last_opt()
695                     .unwrap_or_else(|| Symbol::intern("*"))
696                     .to_string(),
697                 id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
698                 glob: true,
699             },
700         }
701     }
702 }
703
704 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
705     fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
706         ProcMacro {
707             kind: from_macro_kind(mac.kind),
708             helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
709         }
710     }
711 }
712
713 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
714     use rustc_span::hygiene::MacroKind::*;
715     match kind {
716         Bang => MacroKind::Bang,
717         Attr => MacroKind::Attr,
718         Derive => MacroKind::Derive,
719     }
720 }
721
722 impl FromWithTcx<clean::Typedef> for Typedef {
723     fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
724         let clean::Typedef { type_, generics, item_type: _ } = typedef;
725         Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
726     }
727 }
728
729 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
730     fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
731         OpaqueTy {
732             bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
733             generics: opaque.generics.into_tcx(tcx),
734         }
735     }
736 }
737
738 impl FromWithTcx<clean::Static> for Static {
739     fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
740         Static {
741             type_: stat.type_.into_tcx(tcx),
742             mutable: stat.mutability == ast::Mutability::Mut,
743             expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
744         }
745     }
746 }
747
748 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
749     fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
750         TraitAlias {
751             generics: alias.generics.into_tcx(tcx),
752             params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
753         }
754     }
755 }
756
757 impl FromWithTcx<ItemType> for ItemKind {
758     fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
759         use ItemType::*;
760         match kind {
761             Module => ItemKind::Module,
762             ExternCrate => ItemKind::ExternCrate,
763             Import => ItemKind::Import,
764             Struct => ItemKind::Struct,
765             Union => ItemKind::Union,
766             Enum => ItemKind::Enum,
767             Function => ItemKind::Function,
768             Typedef => ItemKind::Typedef,
769             OpaqueTy => ItemKind::OpaqueTy,
770             Static => ItemKind::Static,
771             Constant => ItemKind::Constant,
772             Trait => ItemKind::Trait,
773             Impl => ItemKind::Impl,
774             TyMethod | Method => ItemKind::Method,
775             StructField => ItemKind::StructField,
776             Variant => ItemKind::Variant,
777             Macro => ItemKind::Macro,
778             Primitive => ItemKind::Primitive,
779             AssocConst => ItemKind::AssocConst,
780             AssocType => ItemKind::AssocType,
781             ForeignType => ItemKind::ForeignType,
782             Keyword => ItemKind::Keyword,
783             TraitAlias => ItemKind::TraitAlias,
784             ProcAttribute => ItemKind::ProcAttribute,
785             ProcDerive => ItemKind::ProcDerive,
786         }
787     }
788 }
789
790 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
791     items
792         .into_iter()
793         .filter(|x| !x.is_stripped() && !x.is_keyword())
794         .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
795         .collect()
796 }