]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/conversions.rs
Auto merge of #106916 - lukas-code:overlapping-substs, r=estebank
[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     }
256 }
257
258 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
259     use clean::ItemKind::*;
260     let name = item.name;
261     let is_crate = item.is_crate();
262     let header = item.fn_header(tcx);
263
264     match *item.kind {
265         ModuleItem(m) => {
266             ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false })
267         }
268         ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
269         StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
270         UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
271         StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
272         EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
273         VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
274         FunctionItem(f) => ItemEnum::Function(from_function(f, true, header.unwrap(), tcx)),
275         ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, false, header.unwrap(), tcx)),
276         TraitItem(t) => ItemEnum::Trait((*t).into_tcx(tcx)),
277         TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
278         MethodItem(m, _) => ItemEnum::Function(from_function(m, true, header.unwrap(), tcx)),
279         TyMethodItem(m) => ItemEnum::Function(from_function(m, false, header.unwrap(), tcx)),
280         ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)),
281         StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
282         ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
283         ForeignTypeItem => ItemEnum::ForeignType,
284         TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)),
285         OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
286         ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
287         MacroItem(m) => ItemEnum::Macro(m.source),
288         ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
289         PrimitiveItem(p) => {
290             ItemEnum::Primitive(Primitive {
291                 name: p.as_sym().to_string(),
292                 impls: Vec::new(), // Added in JsonRenderer::item
293             })
294         }
295         TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None },
296         AssocConstItem(ty, default) => {
297             ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) }
298         }
299         TyAssocTypeItem(g, b) => ItemEnum::AssocType {
300             generics: g.into_tcx(tcx),
301             bounds: b.into_tcx(tcx),
302             default: None,
303         },
304         AssocTypeItem(t, b) => ItemEnum::AssocType {
305             generics: t.generics.into_tcx(tcx),
306             bounds: b.into_tcx(tcx),
307             default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)),
308         },
309         // `convert_item` early returns `None` for stripped items and keywords.
310         KeywordItem => unreachable!(),
311         StrippedItem(inner) => {
312             match *inner {
313                 ModuleItem(m) => ItemEnum::Module(Module {
314                     is_crate,
315                     items: ids(m.items, tcx),
316                     is_stripped: true,
317                 }),
318                 // `convert_item` early returns `None` for stripped items we're not including
319                 _ => unreachable!(),
320             }
321         }
322         ExternCrateItem { ref src } => ItemEnum::ExternCrate {
323             name: name.as_ref().unwrap().to_string(),
324             rename: src.map(|x| x.to_string()),
325         },
326     }
327 }
328
329 impl FromWithTcx<clean::Struct> for Struct {
330     fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
331         let fields_stripped = struct_.has_stripped_entries();
332         let clean::Struct { ctor_kind, generics, fields } = struct_;
333
334         let kind = match ctor_kind {
335             Some(CtorKind::Fn) => StructKind::Tuple(ids_keeping_stripped(fields, tcx)),
336             Some(CtorKind::Const) => {
337                 assert!(fields.is_empty());
338                 StructKind::Unit
339             }
340             None => StructKind::Plain { fields: ids(fields, tcx), fields_stripped },
341         };
342
343         Struct {
344             kind,
345             generics: generics.into_tcx(tcx),
346             impls: Vec::new(), // Added in JsonRenderer::item
347         }
348     }
349 }
350
351 impl FromWithTcx<clean::Union> for Union {
352     fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self {
353         let fields_stripped = union_.has_stripped_entries();
354         let clean::Union { generics, fields } = union_;
355         Union {
356             generics: generics.into_tcx(tcx),
357             fields_stripped,
358             fields: ids(fields, tcx),
359             impls: Vec::new(), // Added in JsonRenderer::item
360         }
361     }
362 }
363
364 pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header {
365     Header {
366         async_: header.is_async(),
367         const_: header.is_const(),
368         unsafe_: header.is_unsafe(),
369         abi: convert_abi(header.abi),
370     }
371 }
372
373 fn convert_abi(a: RustcAbi) -> Abi {
374     match a {
375         RustcAbi::Rust => Abi::Rust,
376         RustcAbi::C { unwind } => Abi::C { unwind },
377         RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
378         RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
379         RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
380         RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
381         RustcAbi::Win64 { unwind } => Abi::Win64 { unwind },
382         RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
383         RustcAbi::System { unwind } => Abi::System { unwind },
384         _ => Abi::Other(a.to_string()),
385     }
386 }
387
388 fn convert_lifetime(l: clean::Lifetime) -> String {
389     l.0.to_string()
390 }
391
392 impl FromWithTcx<clean::Generics> for Generics {
393     fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
394         Generics {
395             params: generics.params.into_tcx(tcx),
396             where_predicates: generics.where_predicates.into_tcx(tcx),
397         }
398     }
399 }
400
401 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
402     fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
403         GenericParamDef {
404             name: generic_param.name.to_string(),
405             kind: generic_param.kind.into_tcx(tcx),
406         }
407     }
408 }
409
410 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
411     fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
412         use clean::GenericParamDefKind::*;
413         match kind {
414             Lifetime { outlives } => GenericParamDefKind::Lifetime {
415                 outlives: outlives.into_iter().map(convert_lifetime).collect(),
416             },
417             Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type {
418                 bounds: bounds.into_tcx(tcx),
419                 default: default.map(|x| (*x).into_tcx(tcx)),
420                 synthetic,
421             },
422             Const { did: _, ty, default } => GenericParamDefKind::Const {
423                 type_: (*ty).into_tcx(tcx),
424                 default: default.map(|x| *x),
425             },
426         }
427     }
428 }
429
430 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
431     fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
432         use clean::WherePredicate::*;
433         match predicate {
434             BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
435                 type_: ty.into_tcx(tcx),
436                 bounds: bounds.into_tcx(tcx),
437                 generic_params: bound_params
438                     .into_iter()
439                     .map(|x| GenericParamDef {
440                         name: x.0.to_string(),
441                         kind: GenericParamDefKind::Lifetime { outlives: vec![] },
442                     })
443                     .collect(),
444             },
445             RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
446                 lifetime: convert_lifetime(lifetime),
447                 bounds: bounds.into_tcx(tcx),
448             },
449             // FIXME(fmease): Convert bound parameters as well.
450             EqPredicate { lhs, rhs, bound_params: _ } => {
451                 WherePredicate::EqPredicate { lhs: (*lhs).into_tcx(tcx), rhs: (*rhs).into_tcx(tcx) }
452             }
453         }
454     }
455 }
456
457 impl FromWithTcx<clean::GenericBound> for GenericBound {
458     fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
459         use clean::GenericBound::*;
460         match bound {
461             TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
462                 GenericBound::TraitBound {
463                     trait_: trait_.into_tcx(tcx),
464                     generic_params: generic_params.into_tcx(tcx),
465                     modifier: from_trait_bound_modifier(modifier),
466                 }
467             }
468             Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
469         }
470     }
471 }
472
473 pub(crate) fn from_trait_bound_modifier(
474     modifier: rustc_hir::TraitBoundModifier,
475 ) -> TraitBoundModifier {
476     use rustc_hir::TraitBoundModifier::*;
477     match modifier {
478         None => TraitBoundModifier::None,
479         Maybe => TraitBoundModifier::Maybe,
480         MaybeConst => TraitBoundModifier::MaybeConst,
481     }
482 }
483
484 impl FromWithTcx<clean::Type> for Type {
485     fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
486         use clean::Type::{
487             Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
488             RawPointer, Slice, Tuple,
489         };
490
491         match ty {
492             clean::Type::Path { path } => Type::ResolvedPath(path.into_tcx(tcx)),
493             clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
494                 lifetime: lt.map(convert_lifetime),
495                 traits: bounds.into_tcx(tcx),
496             }),
497             Generic(s) => Type::Generic(s.to_string()),
498             Primitive(p) => Type::Primitive(p.as_sym().to_string()),
499             BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
500             Tuple(t) => Type::Tuple(t.into_tcx(tcx)),
501             Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
502             Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s.to_string() },
503             ImplTrait(g) => Type::ImplTrait(g.into_tcx(tcx)),
504             Infer => Type::Infer,
505             RawPointer(mutability, type_) => Type::RawPointer {
506                 mutable: mutability == ast::Mutability::Mut,
507                 type_: Box::new((*type_).into_tcx(tcx)),
508             },
509             BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
510                 lifetime: lifetime.map(convert_lifetime),
511                 mutable: mutability == ast::Mutability::Mut,
512                 type_: Box::new((*type_).into_tcx(tcx)),
513             },
514             QPath(box clean::QPathData { assoc, self_type, trait_, .. }) => Type::QualifiedPath {
515                 name: assoc.name.to_string(),
516                 args: Box::new(assoc.args.into_tcx(tcx)),
517                 self_type: Box::new(self_type.into_tcx(tcx)),
518                 trait_: trait_.into_tcx(tcx),
519             },
520         }
521     }
522 }
523
524 impl FromWithTcx<clean::Path> for Path {
525     fn from_tcx(path: clean::Path, tcx: TyCtxt<'_>) -> Path {
526         Path {
527             name: path.whole_name(),
528             id: from_item_id(path.def_id().into(), tcx),
529             args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
530         }
531     }
532 }
533
534 impl FromWithTcx<clean::Term> for Term {
535     fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
536         match term {
537             clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
538             clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
539         }
540     }
541 }
542
543 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
544     fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
545         let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
546         FunctionPointer {
547             header: Header {
548                 unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe),
549                 const_: false,
550                 async_: false,
551                 abi: convert_abi(abi),
552             },
553             generic_params: generic_params.into_tcx(tcx),
554             decl: decl.into_tcx(tcx),
555         }
556     }
557 }
558
559 impl FromWithTcx<clean::FnDecl> for FnDecl {
560     fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
561         let clean::FnDecl { inputs, output, c_variadic } = decl;
562         FnDecl {
563             inputs: inputs
564                 .values
565                 .into_iter()
566                 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
567                 .collect(),
568             output: match output {
569                 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
570                 clean::FnRetTy::DefaultReturn => None,
571             },
572             c_variadic,
573         }
574     }
575 }
576
577 impl FromWithTcx<clean::Trait> for Trait {
578     fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
579         let is_auto = trait_.is_auto(tcx);
580         let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe;
581         let clean::Trait { items, generics, bounds, .. } = trait_;
582         Trait {
583             is_auto,
584             is_unsafe,
585             items: ids(items, tcx),
586             generics: generics.into_tcx(tcx),
587             bounds: bounds.into_tcx(tcx),
588             implementations: Vec::new(), // Added in JsonRenderer::item
589         }
590     }
591 }
592
593 impl FromWithTcx<clean::PolyTrait> for PolyTrait {
594     fn from_tcx(
595         clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
596         tcx: TyCtxt<'_>,
597     ) -> Self {
598         PolyTrait { trait_: trait_.into_tcx(tcx), generic_params: generic_params.into_tcx(tcx) }
599     }
600 }
601
602 impl FromWithTcx<clean::Impl> for Impl {
603     fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
604         let provided_trait_methods = impl_.provided_trait_methods(tcx);
605         let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
606         // FIXME: use something like ImplKind in JSON?
607         let (synthetic, blanket_impl) = match kind {
608             clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None),
609             clean::ImplKind::Auto => (true, None),
610             clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
611         };
612         let negative_polarity = match polarity {
613             ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
614             ty::ImplPolarity::Negative => true,
615         };
616         Impl {
617             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
618             generics: generics.into_tcx(tcx),
619             provided_trait_methods: provided_trait_methods
620                 .into_iter()
621                 .map(|x| x.to_string())
622                 .collect(),
623             trait_: trait_.map(|path| path.into_tcx(tcx)),
624             for_: for_.into_tcx(tcx),
625             items: ids(items, tcx),
626             negative: negative_polarity,
627             synthetic,
628             blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
629         }
630     }
631 }
632
633 pub(crate) fn from_function(
634     function: Box<clean::Function>,
635     has_body: bool,
636     header: rustc_hir::FnHeader,
637     tcx: TyCtxt<'_>,
638 ) -> Function {
639     let clean::Function { decl, generics } = *function;
640     Function {
641         decl: decl.into_tcx(tcx),
642         generics: generics.into_tcx(tcx),
643         header: from_fn_header(&header),
644         has_body,
645     }
646 }
647
648 impl FromWithTcx<clean::Enum> for Enum {
649     fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
650         let variants_stripped = enum_.has_stripped_entries();
651         let clean::Enum { variants, generics } = enum_;
652         Enum {
653             generics: generics.into_tcx(tcx),
654             variants_stripped,
655             variants: ids(variants, tcx),
656             impls: Vec::new(), // Added in JsonRenderer::item
657         }
658     }
659 }
660
661 impl FromWithTcx<clean::Variant> for Variant {
662     fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
663         use clean::VariantKind::*;
664
665         let discriminant = variant.discriminant.map(|d| d.into_tcx(tcx));
666
667         let kind = match variant.kind {
668             CLike => VariantKind::Plain,
669             Tuple(fields) => VariantKind::Tuple(ids_keeping_stripped(fields, tcx)),
670             Struct(s) => VariantKind::Struct {
671                 fields_stripped: s.has_stripped_entries(),
672                 fields: ids(s.fields, tcx),
673             },
674         };
675
676         Variant { kind, discriminant }
677     }
678 }
679
680 impl FromWithTcx<clean::Discriminant> for Discriminant {
681     fn from_tcx(disr: clean::Discriminant, tcx: TyCtxt<'_>) -> Self {
682         Discriminant {
683             // expr is only none if going through the inlineing path, which gets
684             // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines
685             // the expr is always some.
686             expr: disr.expr(tcx).unwrap(),
687             value: disr.value(tcx),
688         }
689     }
690 }
691
692 impl FromWithTcx<clean::Import> for Import {
693     fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self {
694         use clean::ImportKind::*;
695         let (name, glob) = match import.kind {
696             Simple(s) => (s.to_string(), false),
697             Glob => (
698                 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
699                 true,
700             ),
701         };
702         Import {
703             source: import.source.path.whole_name(),
704             name,
705             id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)),
706             glob,
707         }
708     }
709 }
710
711 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
712     fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
713         ProcMacro {
714             kind: from_macro_kind(mac.kind),
715             helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
716         }
717     }
718 }
719
720 pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
721     use rustc_span::hygiene::MacroKind::*;
722     match kind {
723         Bang => MacroKind::Bang,
724         Attr => MacroKind::Attr,
725         Derive => MacroKind::Derive,
726     }
727 }
728
729 impl FromWithTcx<Box<clean::Typedef>> for Typedef {
730     fn from_tcx(typedef: Box<clean::Typedef>, tcx: TyCtxt<'_>) -> Self {
731         let clean::Typedef { type_, generics, item_type: _ } = *typedef;
732         Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
733     }
734 }
735
736 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
737     fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
738         OpaqueTy { bounds: opaque.bounds.into_tcx(tcx), generics: opaque.generics.into_tcx(tcx) }
739     }
740 }
741
742 impl FromWithTcx<clean::Static> for Static {
743     fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
744         Static {
745             type_: stat.type_.into_tcx(tcx),
746             mutable: stat.mutability == ast::Mutability::Mut,
747             expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
748         }
749     }
750 }
751
752 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
753     fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
754         TraitAlias { generics: alias.generics.into_tcx(tcx), params: alias.bounds.into_tcx(tcx) }
755     }
756 }
757
758 impl FromWithTcx<ItemType> for ItemKind {
759     fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
760         use ItemType::*;
761         match kind {
762             Module => ItemKind::Module,
763             ExternCrate => ItemKind::ExternCrate,
764             Import => ItemKind::Import,
765             Struct => ItemKind::Struct,
766             Union => ItemKind::Union,
767             Enum => ItemKind::Enum,
768             Function | TyMethod | Method => ItemKind::Function,
769             Typedef => ItemKind::Typedef,
770             OpaqueTy => ItemKind::OpaqueTy,
771             Static => ItemKind::Static,
772             Constant => ItemKind::Constant,
773             Trait => ItemKind::Trait,
774             Impl => ItemKind::Impl,
775             StructField => ItemKind::StructField,
776             Variant => ItemKind::Variant,
777             Macro => ItemKind::Macro,
778             Primitive => ItemKind::Primitive,
779             AssocConst => ItemKind::AssocConst,
780             AssocType => ItemKind::AssocType,
781             ForeignType => ItemKind::ForeignType,
782             Keyword => ItemKind::Keyword,
783             TraitAlias => ItemKind::TraitAlias,
784             ProcAttribute => ItemKind::ProcAttribute,
785             ProcDerive => ItemKind::ProcDerive,
786         }
787     }
788 }
789
790 fn ids(items: impl IntoIterator<Item = clean::Item>, tcx: TyCtxt<'_>) -> Vec<Id> {
791     items
792         .into_iter()
793         .filter(|x| !x.is_stripped() && !x.is_keyword())
794         .map(|i| from_item_id_with_name(i.item_id, tcx, i.name))
795         .collect()
796 }
797
798 fn ids_keeping_stripped(
799     items: impl IntoIterator<Item = clean::Item>,
800     tcx: TyCtxt<'_>,
801 ) -> Vec<Option<Id>> {
802     items
803         .into_iter()
804         .map(|i| {
805             if !i.is_stripped() && !i.is_keyword() {
806                 Some(from_item_id_with_name(i.item_id, tcx, i.name))
807             } else {
808                 None
809             }
810         })
811         .collect()
812 }