]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/conversions.rs
Migrate diagnostics in parser/expr to SessionDiagnostic
[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: span.and_then(|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 impl<I, T, U> FromWithTcx<I> for Vec<U>
123 where
124     I: IntoIterator<Item = T>,
125     U: FromWithTcx<T>,
126 {
127     fn from_tcx(f: I, tcx: TyCtxt<'_>) -> Vec<U> {
128         f.into_iter().map(|x| x.into_tcx(tcx)).collect()
129     }
130 }
131
132 pub(crate) fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
133     #[rustfmt::skip]
134     let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
135     Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
136 }
137
138 impl FromWithTcx<clean::GenericArgs> for GenericArgs {
139     fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self {
140         use clean::GenericArgs::*;
141         match args {
142             AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
143                 args: args.into_vec().into_tcx(tcx),
144                 bindings: bindings.into_tcx(tcx),
145             },
146             Parenthesized { inputs, output } => GenericArgs::Parenthesized {
147                 inputs: inputs.into_vec().into_tcx(tcx),
148                 output: output.map(|a| (*a).into_tcx(tcx)),
149             },
150         }
151     }
152 }
153
154 impl FromWithTcx<clean::GenericArg> for GenericArg {
155     fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self {
156         use clean::GenericArg::*;
157         match arg {
158             Lifetime(l) => GenericArg::Lifetime(convert_lifetime(l)),
159             Type(t) => GenericArg::Type(t.into_tcx(tcx)),
160             Const(box c) => GenericArg::Const(c.into_tcx(tcx)),
161             Infer => GenericArg::Infer,
162         }
163     }
164 }
165
166 impl FromWithTcx<clean::Constant> for Constant {
167     fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self {
168         let expr = constant.expr(tcx);
169         let value = constant.value(tcx);
170         let is_literal = constant.is_literal(tcx);
171         Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal }
172     }
173 }
174
175 impl FromWithTcx<clean::TypeBinding> for TypeBinding {
176     fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self {
177         TypeBinding {
178             name: binding.assoc.name.to_string(),
179             args: binding.assoc.args.into_tcx(tcx),
180             binding: binding.kind.into_tcx(tcx),
181         }
182     }
183 }
184
185 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
186     fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
187         use clean::TypeBindingKind::*;
188         match kind {
189             Equality { term } => TypeBindingKind::Equality(term.into_tcx(tcx)),
190             Constraint { bounds } => TypeBindingKind::Constraint(bounds.into_tcx(tcx)),
191         }
192     }
193 }
194
195 /// It generates an ID as follows:
196 ///
197 /// `CRATE_ID:ITEM_ID[:NAME_ID]` (if there is no name, NAME_ID is not generated).
198 pub(crate) fn from_item_id(item_id: ItemId, tcx: TyCtxt<'_>) -> Id {
199     from_item_id_with_name(item_id, tcx, None)
200 }
201
202 // FIXME: this function (and appending the name at the end of the ID) should be removed when
203 // reexports are not inlined anymore for json format. It should be done in #93518.
204 pub(crate) fn from_item_id_with_name(item_id: ItemId, tcx: TyCtxt<'_>, name: Option<Symbol>) -> Id {
205     struct DisplayDefId<'a>(DefId, TyCtxt<'a>, Option<Symbol>);
206
207     impl<'a> fmt::Display for DisplayDefId<'a> {
208         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209             let name = match self.2 {
210                 Some(name) => format!(":{}", name.as_u32()),
211                 None => self
212                     .1
213                     .opt_item_name(self.0)
214                     .map(|n| format!(":{}", n.as_u32()))
215                     .unwrap_or_default(),
216             };
217             write!(f, "{}:{}{}", self.0.krate.as_u32(), u32::from(self.0.index), name)
218         }
219     }
220
221     match item_id {
222         ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did, tcx, name))),
223         ItemId::Blanket { for_, impl_id } => {
224             Id(format!("b:{}-{}", DisplayDefId(impl_id, tcx, None), DisplayDefId(for_, tcx, name)))
225         }
226         ItemId::Auto { for_, trait_ } => {
227             Id(format!("a:{}-{}", DisplayDefId(trait_, tcx, None), DisplayDefId(for_, tcx, name)))
228         }
229         ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())),
230     }
231 }
232
233 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
234     use clean::ItemKind::*;
235     let name = item.name;
236     let is_crate = item.is_crate();
237     let header = item.fn_header(tcx);
238
239     match *item.kind {
240         ModuleItem(m) => {
241             ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false })
242         }
243         ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
244         StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
245         UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
246         StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
247         EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
248         VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
249         FunctionItem(f) => ItemEnum::Function(from_function(f, header.unwrap(), tcx)),
250         ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, header.unwrap(), tcx)),
251         TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
252         TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
253         MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, header.unwrap(), tcx)),
254         TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, header.unwrap(), tcx)),
255         ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)),
256         StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
257         ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
258         ForeignTypeItem => ItemEnum::ForeignType,
259         TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)),
260         OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
261         ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
262         MacroItem(m) => ItemEnum::Macro(m.source),
263         ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
264         PrimitiveItem(p) => ItemEnum::PrimitiveType(p.as_sym().to_string()),
265         TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None },
266         AssocConstItem(ty, default) => {
267             ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) }
268         }
269         TyAssocTypeItem(g, b) => ItemEnum::AssocType {
270             generics: (*g).into_tcx(tcx),
271             bounds: b.into_tcx(tcx),
272             default: None,
273         },
274         AssocTypeItem(t, b) => ItemEnum::AssocType {
275             generics: t.generics.into_tcx(tcx),
276             bounds: b.into_tcx(tcx),
277             default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)),
278         },
279         // `convert_item` early returns `None` for stripped items and keywords.
280         KeywordItem => unreachable!(),
281         StrippedItem(inner) => {
282             match *inner {
283                 ModuleItem(m) => ItemEnum::Module(Module {
284                     is_crate,
285                     items: ids(m.items, tcx),
286                     is_stripped: true,
287                 }),
288                 // `convert_item` early returns `None` for stripped items we're not including
289                 _ => unreachable!(),
290             }
291         }
292         ExternCrateItem { ref src } => ItemEnum::ExternCrate {
293             name: name.as_ref().unwrap().to_string(),
294             rename: src.map(|x| x.to_string()),
295         },
296     }
297 }
298
299 impl FromWithTcx<clean::Struct> for Struct {
300     fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
301         let fields_stripped = struct_.has_stripped_entries();
302         let clean::Struct { struct_type, generics, fields } = struct_;
303         Struct {
304             struct_type: from_ctor_kind(struct_type),
305             generics: generics.into_tcx(tcx),
306             fields_stripped,
307             fields: ids(fields, tcx),
308             impls: Vec::new(), // Added in JsonRenderer::item
309         }
310     }
311 }
312
313 impl FromWithTcx<clean::Union> for Union {
314     fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self {
315         let fields_stripped = union_.has_stripped_entries();
316         let clean::Union { generics, fields } = union_;
317         Union {
318             generics: generics.into_tcx(tcx),
319             fields_stripped,
320             fields: ids(fields, tcx),
321             impls: Vec::new(), // Added in JsonRenderer::item
322         }
323     }
324 }
325
326 pub(crate) fn from_ctor_kind(struct_type: CtorKind) -> StructType {
327     match struct_type {
328         CtorKind::Fictive => StructType::Plain,
329         CtorKind::Fn => StructType::Tuple,
330         CtorKind::Const => StructType::Unit,
331     }
332 }
333
334 pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header {
335     Header {
336         async_: header.is_async(),
337         const_: header.is_const(),
338         unsafe_: header.is_unsafe(),
339         abi: convert_abi(header.abi),
340     }
341 }
342
343 fn convert_abi(a: RustcAbi) -> Abi {
344     match a {
345         RustcAbi::Rust => Abi::Rust,
346         RustcAbi::C { unwind } => Abi::C { unwind },
347         RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
348         RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
349         RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
350         RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
351         RustcAbi::Win64 { unwind } => Abi::Win64 { unwind },
352         RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
353         RustcAbi::System { unwind } => Abi::System { unwind },
354         _ => Abi::Other(a.to_string()),
355     }
356 }
357
358 fn convert_lifetime(l: clean::Lifetime) -> String {
359     l.0.to_string()
360 }
361
362 impl FromWithTcx<clean::Generics> for Generics {
363     fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
364         Generics {
365             params: generics.params.into_tcx(tcx),
366             where_predicates: generics.where_predicates.into_tcx(tcx),
367         }
368     }
369 }
370
371 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
372     fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
373         GenericParamDef {
374             name: generic_param.name.to_string(),
375             kind: generic_param.kind.into_tcx(tcx),
376         }
377     }
378 }
379
380 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
381     fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
382         use clean::GenericParamDefKind::*;
383         match kind {
384             Lifetime { outlives } => GenericParamDefKind::Lifetime {
385                 outlives: outlives.into_iter().map(convert_lifetime).collect(),
386             },
387             Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type {
388                 bounds: bounds.into_tcx(tcx),
389                 default: default.map(|x| (*x).into_tcx(tcx)),
390                 synthetic,
391             },
392             Const { did: _, ty, default } => GenericParamDefKind::Const {
393                 type_: (*ty).into_tcx(tcx),
394                 default: default.map(|x| *x),
395             },
396         }
397     }
398 }
399
400 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
401     fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
402         use clean::WherePredicate::*;
403         match predicate {
404             BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
405                 type_: ty.into_tcx(tcx),
406                 bounds: bounds.into_tcx(tcx),
407                 generic_params: bound_params
408                     .into_iter()
409                     .map(|x| GenericParamDef {
410                         name: x.0.to_string(),
411                         kind: GenericParamDefKind::Lifetime { outlives: vec![] },
412                     })
413                     .collect(),
414             },
415             RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
416                 lifetime: convert_lifetime(lifetime),
417                 bounds: bounds.into_tcx(tcx),
418             },
419             EqPredicate { lhs, rhs } => {
420                 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
421             }
422         }
423     }
424 }
425
426 impl FromWithTcx<clean::GenericBound> for GenericBound {
427     fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
428         use clean::GenericBound::*;
429         match bound {
430             TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
431                 GenericBound::TraitBound {
432                     trait_: trait_.into_tcx(tcx),
433                     generic_params: generic_params.into_tcx(tcx),
434                     modifier: from_trait_bound_modifier(modifier),
435                 }
436             }
437             Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
438         }
439     }
440 }
441
442 pub(crate) fn from_trait_bound_modifier(
443     modifier: rustc_hir::TraitBoundModifier,
444 ) -> TraitBoundModifier {
445     use rustc_hir::TraitBoundModifier::*;
446     match modifier {
447         None => TraitBoundModifier::None,
448         Maybe => TraitBoundModifier::Maybe,
449         MaybeConst => TraitBoundModifier::MaybeConst,
450     }
451 }
452
453 impl FromWithTcx<clean::Type> for Type {
454     fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
455         use clean::Type::{
456             Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
457             RawPointer, Slice, Tuple,
458         };
459
460         match ty {
461             clean::Type::Path { path } => Type::ResolvedPath(path.into_tcx(tcx)),
462             clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
463                 lifetime: lt.map(convert_lifetime),
464                 traits: bounds.into_tcx(tcx),
465             }),
466             Generic(s) => Type::Generic(s.to_string()),
467             Primitive(p) => Type::Primitive(p.as_sym().to_string()),
468             BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
469             Tuple(t) => Type::Tuple(t.into_tcx(tcx)),
470             Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
471             Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
472             ImplTrait(g) => Type::ImplTrait(g.into_tcx(tcx)),
473             Infer => Type::Infer,
474             RawPointer(mutability, type_) => Type::RawPointer {
475                 mutable: mutability == ast::Mutability::Mut,
476                 type_: Box::new((*type_).into_tcx(tcx)),
477             },
478             BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
479                 lifetime: lifetime.map(convert_lifetime),
480                 mutable: mutability == ast::Mutability::Mut,
481                 type_: Box::new((*type_).into_tcx(tcx)),
482             },
483             QPath { assoc, self_type, trait_, .. } => Type::QualifiedPath {
484                 name: assoc.name.to_string(),
485                 args: Box::new(assoc.args.clone().into_tcx(tcx)),
486                 self_type: Box::new((*self_type).into_tcx(tcx)),
487                 trait_: trait_.into_tcx(tcx),
488             },
489         }
490     }
491 }
492
493 impl FromWithTcx<clean::Path> for Path {
494     fn from_tcx(path: clean::Path, tcx: TyCtxt<'_>) -> Path {
495         Path {
496             name: path.whole_name(),
497             id: from_item_id(path.def_id().into(), tcx),
498             args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
499         }
500     }
501 }
502
503 impl FromWithTcx<clean::Term> for Term {
504     fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
505         match term {
506             clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
507             clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
508         }
509     }
510 }
511
512 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
513     fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
514         let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
515         FunctionPointer {
516             header: Header {
517                 unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe),
518                 const_: false,
519                 async_: false,
520                 abi: convert_abi(abi),
521             },
522             generic_params: generic_params.into_tcx(tcx),
523             decl: decl.into_tcx(tcx),
524         }
525     }
526 }
527
528 impl FromWithTcx<clean::FnDecl> for FnDecl {
529     fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
530         let clean::FnDecl { inputs, output, c_variadic } = decl;
531         FnDecl {
532             inputs: inputs
533                 .values
534                 .into_iter()
535                 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
536                 .collect(),
537             output: match output {
538                 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
539                 clean::FnRetTy::DefaultReturn => None,
540             },
541             c_variadic,
542         }
543     }
544 }
545
546 impl FromWithTcx<clean::Trait> for Trait {
547     fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
548         let is_auto = trait_.is_auto(tcx);
549         let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe;
550         let clean::Trait { items, generics, bounds, .. } = trait_;
551         Trait {
552             is_auto,
553             is_unsafe,
554             items: ids(items, tcx),
555             generics: generics.into_tcx(tcx),
556             bounds: bounds.into_tcx(tcx),
557             implementations: Vec::new(), // Added in JsonRenderer::item
558         }
559     }
560 }
561
562 impl FromWithTcx<clean::PolyTrait> for PolyTrait {
563     fn from_tcx(
564         clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
565         tcx: TyCtxt<'_>,
566     ) -> Self {
567         PolyTrait { trait_: trait_.into_tcx(tcx), generic_params: generic_params.into_tcx(tcx) }
568     }
569 }
570
571 impl FromWithTcx<clean::Impl> for Impl {
572     fn from_tcx(impl_: 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: 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_: trait_.map(|path| path.into_tcx(tcx)),
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: Box<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: Box<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                     .filter_map(|f| match *f.kind {
666                         clean::StructFieldItem(ty) => Some(ty.into_tcx(tcx)),
667                         clean::StrippedItem(_) => None,
668                         _ => unreachable!(),
669                     })
670                     .collect(),
671             ),
672             Struct(s) => Variant::Struct(ids(s.fields, tcx)),
673         }
674     }
675 }
676
677 impl FromWithTcx<clean::Import> for Import {
678     fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
679         use clean::ImportKind::*;
680         let (name, glob) = match import.kind {
681             Simple(s) => (s.to_string(), false),
682             Glob => (
683                 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
684                 true,
685             ),
686         };
687         Import {
688             source: import.source.path.whole_name(),
689             name,
690             id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
691             glob,
692         }
693     }
694 }
695
696 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
697     fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
698         ProcMacro {
699             kind: from_macro_kind(mac.kind),
700             helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
701         }
702     }
703 }
704
705 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
706     use rustc_span::hygiene::MacroKind::*;
707     match kind {
708         Bang => MacroKind::Bang,
709         Attr => MacroKind::Attr,
710         Derive => MacroKind::Derive,
711     }
712 }
713
714 impl FromWithTcx<Box<clean::Typedef>> for Typedef {
715     fn from_tcx(typedef: Box<clean::Typedef>, tcx: TyCtxt<'_>) -> Self {
716         let clean::Typedef { type_, generics, item_type: _ } = *typedef;
717         Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
718     }
719 }
720
721 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
722     fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
723         OpaqueTy { bounds: opaque.bounds.into_tcx(tcx), generics: opaque.generics.into_tcx(tcx) }
724     }
725 }
726
727 impl FromWithTcx<clean::Static> for Static {
728     fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
729         Static {
730             type_: stat.type_.into_tcx(tcx),
731             mutable: stat.mutability == ast::Mutability::Mut,
732             expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
733         }
734     }
735 }
736
737 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
738     fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
739         TraitAlias { generics: alias.generics.into_tcx(tcx), params: alias.bounds.into_tcx(tcx) }
740     }
741 }
742
743 impl FromWithTcx<ItemType> for ItemKind {
744     fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
745         use ItemType::*;
746         match kind {
747             Module => ItemKind::Module,
748             ExternCrate => ItemKind::ExternCrate,
749             Import => ItemKind::Import,
750             Struct => ItemKind::Struct,
751             Union => ItemKind::Union,
752             Enum => ItemKind::Enum,
753             Function => ItemKind::Function,
754             Typedef => ItemKind::Typedef,
755             OpaqueTy => ItemKind::OpaqueTy,
756             Static => ItemKind::Static,
757             Constant => ItemKind::Constant,
758             Trait => ItemKind::Trait,
759             Impl => ItemKind::Impl,
760             TyMethod | Method => ItemKind::Method,
761             StructField => ItemKind::StructField,
762             Variant => ItemKind::Variant,
763             Macro => ItemKind::Macro,
764             Primitive => ItemKind::Primitive,
765             AssocConst => ItemKind::AssocConst,
766             AssocType => ItemKind::AssocType,
767             ForeignType => ItemKind::ForeignType,
768             Keyword => ItemKind::Keyword,
769             TraitAlias => ItemKind::TraitAlias,
770             ProcAttribute => ItemKind::ProcAttribute,
771             ProcDerive => ItemKind::ProcDerive,
772         }
773     }
774 }
775
776 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
777     items
778         .into_iter()
779         .filter(|x| !x.is_stripped() && !x.is_keyword())
780         .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
781         .collect()
782 }