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