]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/json/conversions.rs
New upstream version 1.60.0+dfsg1
[rustc.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
16 use rustdoc_json_types::*;
17
18 use crate::clean::utils::print_const_expr;
19 use crate::clean::{self, ItemId};
20 use crate::formats::item_type::ItemType;
21 use crate::json::JsonRenderer;
22 use std::collections::HashSet;
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 { name: binding.name.to_string(), binding: binding.kind.into_tcx(tcx) }
158 }
159 }
160
161 impl FromWithTcx<clean::TypeBindingKind> for TypeBindingKind {
162 fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self {
163 use clean::TypeBindingKind::*;
164 match kind {
165 Equality { term } => TypeBindingKind::Equality(term.into_tcx(tcx)),
166 Constraint { bounds } => {
167 TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect())
168 }
169 }
170 }
171 }
172
173 crate fn from_item_id(did: ItemId) -> Id {
174 struct DisplayDefId(DefId);
175
176 impl fmt::Display for DisplayDefId {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 write!(f, "{}:{}", self.0.krate.as_u32(), u32::from(self.0.index))
179 }
180 }
181
182 match did {
183 ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did))),
184 ItemId::Blanket { for_, impl_id } => {
185 Id(format!("b:{}-{}", DisplayDefId(impl_id), DisplayDefId(for_)))
186 }
187 ItemId::Auto { for_, trait_ } => {
188 Id(format!("a:{}-{}", DisplayDefId(trait_), DisplayDefId(for_)))
189 }
190 ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())),
191 }
192 }
193
194 fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum {
195 use clean::ItemKind::*;
196 let name = item.name;
197 let is_crate = item.is_crate();
198 match *item.kind {
199 ModuleItem(m) => ItemEnum::Module(Module { is_crate, items: ids(m.items) }),
200 ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)),
201 StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)),
202 UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)),
203 StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)),
204 EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)),
205 VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)),
206 FunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
207 ForeignFunctionItem(f) => ItemEnum::Function(f.into_tcx(tcx)),
208 TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)),
209 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)),
210 MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, tcx)),
211 TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, tcx)),
212 ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)),
213 StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
214 ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)),
215 ForeignTypeItem => ItemEnum::ForeignType,
216 TypedefItem(t, _) => ItemEnum::Typedef(t.into_tcx(tcx)),
217 OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)),
218 ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)),
219 MacroItem(m) => ItemEnum::Macro(m.source),
220 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)),
221 PrimitiveItem(p) => ItemEnum::PrimitiveType(p.as_sym().to_string()),
222 AssocConstItem(ty, default) => {
223 ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: default.map(|c| c.expr(tcx)) }
224 }
225 AssocTypeItem(g, t) => ItemEnum::AssocType {
226 bounds: g.into_iter().map(|x| x.into_tcx(tcx)).collect(),
227 default: t.map(|x| x.into_tcx(tcx)),
228 },
229 // `convert_item` early returns `None` for striped items
230 StrippedItem(_) => unreachable!(),
231 KeywordItem(_) => {
232 panic!("{:?} is not supported for JSON output", item)
233 }
234 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
235 name: name.as_ref().unwrap().to_string(),
236 rename: src.map(|x| x.to_string()),
237 },
238 }
239 }
240
241 impl FromWithTcx<clean::Struct> for Struct {
242 fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self {
243 let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
244 Struct {
245 struct_type: from_ctor_kind(struct_type),
246 generics: generics.into_tcx(tcx),
247 fields_stripped,
248 fields: ids(fields),
249 impls: Vec::new(), // Added in JsonRenderer::item
250 }
251 }
252 }
253
254 impl FromWithTcx<clean::Union> for Union {
255 fn from_tcx(struct_: clean::Union, tcx: TyCtxt<'_>) -> Self {
256 let clean::Union { generics, fields, fields_stripped } = struct_;
257 Union {
258 generics: generics.into_tcx(tcx),
259 fields_stripped,
260 fields: ids(fields),
261 impls: Vec::new(), // Added in JsonRenderer::item
262 }
263 }
264 }
265
266 crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
267 match struct_type {
268 CtorKind::Fictive => StructType::Plain,
269 CtorKind::Fn => StructType::Tuple,
270 CtorKind::Const => StructType::Unit,
271 }
272 }
273
274 crate fn from_fn_header(header: &rustc_hir::FnHeader) -> HashSet<Qualifiers> {
275 let mut v = HashSet::new();
276
277 if let rustc_hir::Unsafety::Unsafe = header.unsafety {
278 v.insert(Qualifiers::Unsafe);
279 }
280
281 if let rustc_hir::IsAsync::Async = header.asyncness {
282 v.insert(Qualifiers::Async);
283 }
284
285 if let rustc_hir::Constness::Const = header.constness {
286 v.insert(Qualifiers::Const);
287 }
288
289 v
290 }
291
292 impl FromWithTcx<clean::Function> for Function {
293 fn from_tcx(function: clean::Function, tcx: TyCtxt<'_>) -> Self {
294 let clean::Function { decl, generics, header } = function;
295 Function {
296 decl: decl.into_tcx(tcx),
297 generics: generics.into_tcx(tcx),
298 header: from_fn_header(&header),
299 abi: header.abi.to_string(),
300 }
301 }
302 }
303
304 impl FromWithTcx<clean::Generics> for Generics {
305 fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self {
306 Generics {
307 params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
308 where_predicates: generics
309 .where_predicates
310 .into_iter()
311 .map(|x| x.into_tcx(tcx))
312 .collect(),
313 }
314 }
315 }
316
317 impl FromWithTcx<clean::GenericParamDef> for GenericParamDef {
318 fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self {
319 GenericParamDef {
320 name: generic_param.name.to_string(),
321 kind: generic_param.kind.into_tcx(tcx),
322 }
323 }
324 }
325
326 impl FromWithTcx<clean::GenericParamDefKind> for GenericParamDefKind {
327 fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self {
328 use clean::GenericParamDefKind::*;
329 match kind {
330 Lifetime { outlives } => GenericParamDefKind::Lifetime {
331 outlives: outlives.into_iter().map(|lt| lt.0.to_string()).collect(),
332 },
333 Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
334 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
335 default: default.map(|x| (*x).into_tcx(tcx)),
336 },
337 Const { did: _, ty, default } => {
338 GenericParamDefKind::Const { ty: (*ty).into_tcx(tcx), default: default.map(|x| *x) }
339 }
340 }
341 }
342 }
343
344 impl FromWithTcx<clean::WherePredicate> for WherePredicate {
345 fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self {
346 use clean::WherePredicate::*;
347 match predicate {
348 BoundPredicate { ty, bounds, .. } => WherePredicate::BoundPredicate {
349 ty: ty.into_tcx(tcx),
350 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
351 // FIXME: add `bound_params` to rustdoc-json-params?
352 },
353 RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
354 lifetime: lifetime.0.to_string(),
355 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
356 },
357 EqPredicate { lhs, rhs } => {
358 WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) }
359 }
360 }
361 }
362 }
363
364 impl FromWithTcx<clean::GenericBound> for GenericBound {
365 fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self {
366 use clean::GenericBound::*;
367 match bound {
368 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
369 // FIXME: should `trait_` be a clean::Path equivalent in JSON?
370 let trait_ = clean::Type::Path { path: trait_ }.into_tcx(tcx);
371 GenericBound::TraitBound {
372 trait_,
373 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
374 modifier: from_trait_bound_modifier(modifier),
375 }
376 }
377 Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
378 }
379 }
380 }
381
382 crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
383 use rustc_hir::TraitBoundModifier::*;
384 match modifier {
385 None => TraitBoundModifier::None,
386 Maybe => TraitBoundModifier::Maybe,
387 MaybeConst => TraitBoundModifier::MaybeConst,
388 }
389 }
390
391 impl FromWithTcx<clean::Type> for Type {
392 fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self {
393 use clean::Type::{
394 Array, BareFunction, BorrowedRef, DynTrait, Generic, ImplTrait, Infer, Primitive,
395 QPath, RawPointer, Slice, Tuple,
396 };
397
398 match ty {
399 clean::Type::Path { path } => Type::ResolvedPath {
400 name: path.whole_name(),
401 id: from_item_id(path.def_id().into()),
402 args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))),
403 param_names: Vec::new(),
404 },
405 DynTrait(mut bounds, lt) => {
406 let first_trait = bounds.remove(0).trait_;
407
408 Type::ResolvedPath {
409 name: first_trait.whole_name(),
410 id: from_item_id(first_trait.def_id().into()),
411 args: first_trait
412 .segments
413 .last()
414 .map(|args| Box::new(args.clone().args.into_tcx(tcx))),
415 param_names: bounds
416 .into_iter()
417 .map(|t| {
418 clean::GenericBound::TraitBound(t, rustc_hir::TraitBoundModifier::None)
419 })
420 .chain(lt.map(clean::GenericBound::Outlives))
421 .map(|bound| bound.into_tcx(tcx))
422 .collect(),
423 }
424 }
425 Generic(s) => Type::Generic(s.to_string()),
426 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
427 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))),
428 Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()),
429 Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))),
430 Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s },
431 ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()),
432 Infer => Type::Infer,
433 RawPointer(mutability, type_) => Type::RawPointer {
434 mutable: mutability == ast::Mutability::Mut,
435 type_: Box::new((*type_).into_tcx(tcx)),
436 },
437 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
438 lifetime: lifetime.map(|l| l.0.to_string()),
439 mutable: mutability == ast::Mutability::Mut,
440 type_: Box::new((*type_).into_tcx(tcx)),
441 },
442 QPath { name, self_type, trait_, .. } => {
443 // FIXME: should `trait_` be a clean::Path equivalent in JSON?
444 let trait_ = clean::Type::Path { path: trait_ }.into_tcx(tcx);
445 Type::QualifiedPath {
446 name: name.to_string(),
447 self_type: Box::new((*self_type).into_tcx(tcx)),
448 trait_: Box::new(trait_),
449 }
450 }
451 }
452 }
453 }
454
455 impl FromWithTcx<clean::Term> for Term {
456 fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term {
457 match term {
458 clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)),
459 clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)),
460 }
461 }
462 }
463
464 impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
465 fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self {
466 let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
467 FunctionPointer {
468 header: if let rustc_hir::Unsafety::Unsafe = unsafety {
469 let mut hs = HashSet::new();
470 hs.insert(Qualifiers::Unsafe);
471 hs
472 } else {
473 HashSet::new()
474 },
475 generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(),
476 decl: decl.into_tcx(tcx),
477 abi: abi.to_string(),
478 }
479 }
480 }
481
482 impl FromWithTcx<clean::FnDecl> for FnDecl {
483 fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
484 let clean::FnDecl { inputs, output, c_variadic } = decl;
485 FnDecl {
486 inputs: inputs
487 .values
488 .into_iter()
489 .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx)))
490 .collect(),
491 output: match output {
492 clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)),
493 clean::FnRetTy::DefaultReturn => None,
494 },
495 c_variadic,
496 }
497 }
498 }
499
500 impl FromWithTcx<clean::Trait> for Trait {
501 fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
502 let clean::Trait { unsafety, items, generics, bounds, is_auto } = trait_;
503 Trait {
504 is_auto,
505 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
506 items: ids(items),
507 generics: generics.into_tcx(tcx),
508 bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
509 implementors: Vec::new(), // Added in JsonRenderer::item
510 }
511 }
512 }
513
514 impl FromWithTcx<clean::Impl> for Impl {
515 fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
516 let provided_trait_methods = impl_.provided_trait_methods(tcx);
517 let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
518 // FIXME: should `trait_` be a clean::Path equivalent in JSON?
519 let trait_ = trait_.map(|path| clean::Type::Path { path }.into_tcx(tcx));
520 // FIXME: use something like ImplKind in JSON?
521 let (synthetic, blanket_impl) = match kind {
522 clean::ImplKind::Normal => (false, None),
523 clean::ImplKind::Auto => (true, None),
524 clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
525 };
526 let negative_polarity = match polarity {
527 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
528 ty::ImplPolarity::Negative => true,
529 };
530 Impl {
531 is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
532 generics: generics.into_tcx(tcx),
533 provided_trait_methods: provided_trait_methods
534 .into_iter()
535 .map(|x| x.to_string())
536 .collect(),
537 trait_,
538 for_: for_.into_tcx(tcx),
539 items: ids(items),
540 negative: negative_polarity,
541 synthetic,
542 blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
543 }
544 }
545 }
546
547 crate fn from_function_method(
548 function: clean::Function,
549 has_body: bool,
550 tcx: TyCtxt<'_>,
551 ) -> Method {
552 let clean::Function { header, decl, generics } = function;
553 Method {
554 decl: decl.into_tcx(tcx),
555 generics: generics.into_tcx(tcx),
556 header: from_fn_header(&header),
557 abi: header.abi.to_string(),
558 has_body,
559 }
560 }
561
562 impl FromWithTcx<clean::Enum> for Enum {
563 fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self {
564 let clean::Enum { variants, generics, variants_stripped } = enum_;
565 Enum {
566 generics: generics.into_tcx(tcx),
567 variants_stripped,
568 variants: ids(variants),
569 impls: Vec::new(), // Added in JsonRenderer::item
570 }
571 }
572 }
573
574 impl FromWithTcx<clean::VariantStruct> for Struct {
575 fn from_tcx(struct_: clean::VariantStruct, _tcx: TyCtxt<'_>) -> Self {
576 let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
577 Struct {
578 struct_type: from_ctor_kind(struct_type),
579 generics: Default::default(),
580 fields_stripped,
581 fields: ids(fields),
582 impls: Vec::new(),
583 }
584 }
585 }
586
587 impl FromWithTcx<clean::Variant> for Variant {
588 fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self {
589 use clean::Variant::*;
590 match variant {
591 CLike => Variant::Plain,
592 Tuple(fields) => Variant::Tuple(
593 fields
594 .into_iter()
595 .map(|f| {
596 if let clean::StructFieldItem(ty) = *f.kind {
597 ty.into_tcx(tcx)
598 } else {
599 unreachable!()
600 }
601 })
602 .collect(),
603 ),
604 Struct(s) => Variant::Struct(ids(s.fields)),
605 }
606 }
607 }
608
609 impl FromWithTcx<clean::Import> for Import {
610 fn from_tcx(import: clean::Import, _tcx: TyCtxt<'_>) -> Self {
611 use clean::ImportKind::*;
612 match import.kind {
613 Simple(s) => Import {
614 source: import.source.path.whole_name(),
615 name: s.to_string(),
616 id: import.source.did.map(ItemId::from).map(from_item_id),
617 glob: false,
618 },
619 Glob => Import {
620 source: import.source.path.whole_name(),
621 name: import.source.path.last().to_string(),
622 id: import.source.did.map(ItemId::from).map(from_item_id),
623 glob: true,
624 },
625 }
626 }
627 }
628
629 impl FromWithTcx<clean::ProcMacro> for ProcMacro {
630 fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self {
631 ProcMacro {
632 kind: from_macro_kind(mac.kind),
633 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
634 }
635 }
636 }
637
638 crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
639 use rustc_span::hygiene::MacroKind::*;
640 match kind {
641 Bang => MacroKind::Bang,
642 Attr => MacroKind::Attr,
643 Derive => MacroKind::Derive,
644 }
645 }
646
647 impl FromWithTcx<clean::Typedef> for Typedef {
648 fn from_tcx(typedef: clean::Typedef, tcx: TyCtxt<'_>) -> Self {
649 let clean::Typedef { type_, generics, item_type: _ } = typedef;
650 Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) }
651 }
652 }
653
654 impl FromWithTcx<clean::OpaqueTy> for OpaqueTy {
655 fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self {
656 OpaqueTy {
657 bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
658 generics: opaque.generics.into_tcx(tcx),
659 }
660 }
661 }
662
663 impl FromWithTcx<clean::Static> for Static {
664 fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self {
665 Static {
666 type_: stat.type_.into_tcx(tcx),
667 mutable: stat.mutability == ast::Mutability::Mut,
668 expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(),
669 }
670 }
671 }
672
673 impl FromWithTcx<clean::TraitAlias> for TraitAlias {
674 fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self {
675 TraitAlias {
676 generics: alias.generics.into_tcx(tcx),
677 params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(),
678 }
679 }
680 }
681
682 impl FromWithTcx<ItemType> for ItemKind {
683 fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self {
684 use ItemType::*;
685 match kind {
686 Module => ItemKind::Module,
687 ExternCrate => ItemKind::ExternCrate,
688 Import => ItemKind::Import,
689 Struct => ItemKind::Struct,
690 Union => ItemKind::Union,
691 Enum => ItemKind::Enum,
692 Function => ItemKind::Function,
693 Typedef => ItemKind::Typedef,
694 OpaqueTy => ItemKind::OpaqueTy,
695 Static => ItemKind::Static,
696 Constant => ItemKind::Constant,
697 Trait => ItemKind::Trait,
698 Impl => ItemKind::Impl,
699 TyMethod | Method => ItemKind::Method,
700 StructField => ItemKind::StructField,
701 Variant => ItemKind::Variant,
702 Macro => ItemKind::Macro,
703 Primitive => ItemKind::Primitive,
704 AssocConst => ItemKind::AssocConst,
705 AssocType => ItemKind::AssocType,
706 ForeignType => ItemKind::ForeignType,
707 Keyword => ItemKind::Keyword,
708 TraitAlias => ItemKind::TraitAlias,
709 ProcAttribute => ItemKind::ProcAttribute,
710 ProcDerive => ItemKind::ProcDerive,
711 Generic => unreachable!(),
712 }
713 }
714 }
715
716 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
717 items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_item_id(i.def_id)).collect()
718 }