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