1#![allow(rustc::default_hash_types)]
6
7use rustc_abi::ExternAbi;
8use rustc_ast::ast;
9use rustc_attr_parsing::DeprecatedSince;
10use rustc_hir::def::CtorKind;
11use rustc_hir::def_id::DefId;
12use rustc_metadata::rendered_const;
13use rustc_middle::{bug, ty};
14use rustc_span::{Pos, Symbol};
15use rustdoc_json_types::*;
16
17use crate::clean::{self, ItemId};
18use crate::formats::FormatRenderer;
19use crate::formats::item_type::ItemType;
20use crate::json::JsonRenderer;
21use crate::passes::collect_intra_doc_links::UrlFragment;
22
23impl JsonRenderer<'_> {
24 pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
25 let deprecation = item.deprecation(self.tcx);
26 let links = self
27 .cache
28 .intra_doc_links
29 .get(&item.item_id)
30 .into_iter()
31 .flatten()
32 .map(|clean::ItemLink { link, page_id, fragment, .. }| {
33 let id = match fragment {
34 Some(UrlFragment::Item(frag_id)) => *frag_id,
35 Some(UrlFragment::UserWritten(_)) | None => *page_id,
37 };
38
39 (String::from(&**link), self.id_from_item_default(id.into()))
40 })
41 .collect();
42 let docs = item.opt_doc_value();
43 let attrs = item.attributes(self.tcx, self.cache(), true);
44 let span = item.span(self.tcx);
45 let visibility = item.visibility(self.tcx);
46 let clean::Item { name, item_id, .. } = item;
47 let id = self.id_from_item(&item);
48 let inner = match item.kind {
49 clean::KeywordItem => return None,
50 clean::StrippedItem(ref inner) => {
51 match &**inner {
52 clean::ModuleItem(_)
56 if self.imported_items.contains(&item_id.expect_def_id()) =>
57 {
58 from_clean_item(item, self)
59 }
60 _ => return None,
61 }
62 }
63 _ => from_clean_item(item, self),
64 };
65 Some(Item {
66 id,
67 crate_id: item_id.krate().as_u32(),
68 name: name.map(|sym| sym.to_string()),
69 span: span.and_then(|span| self.convert_span(span)),
70 visibility: self.convert_visibility(visibility),
71 docs,
72 attrs,
73 deprecation: deprecation.map(from_deprecation),
74 inner,
75 links,
76 })
77 }
78
79 fn convert_span(&self, span: clean::Span) -> Option<Span> {
80 match span.filename(self.sess()) {
81 rustc_span::FileName::Real(name) => {
82 if let Some(local_path) = name.into_local_path() {
83 let hi = span.hi(self.sess());
84 let lo = span.lo(self.sess());
85 Some(Span {
86 filename: local_path,
87 begin: (lo.line, lo.col.to_usize()),
88 end: (hi.line, hi.col.to_usize()),
89 })
90 } else {
91 None
92 }
93 }
94 _ => None,
95 }
96 }
97
98 fn convert_visibility(&self, v: Option<ty::Visibility<DefId>>) -> Visibility {
99 match v {
100 None => Visibility::Default,
101 Some(ty::Visibility::Public) => Visibility::Public,
102 Some(ty::Visibility::Restricted(did)) if did.is_crate_root() => Visibility::Crate,
103 Some(ty::Visibility::Restricted(did)) => Visibility::Restricted {
104 parent: self.id_from_item_default(did.into()),
105 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
106 },
107 }
108 }
109
110 fn ids(&self, items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
111 items
112 .into_iter()
113 .filter(|x| !x.is_stripped() && !x.is_keyword())
114 .map(|i| self.id_from_item(&i))
115 .collect()
116 }
117
118 fn ids_keeping_stripped(
119 &self,
120 items: impl IntoIterator<Item = clean::Item>,
121 ) -> Vec<Option<Id>> {
122 items
123 .into_iter()
124 .map(|i| (!i.is_stripped() && !i.is_keyword()).then(|| self.id_from_item(&i)))
125 .collect()
126 }
127}
128
129pub(crate) trait FromClean<T> {
130 fn from_clean(f: T, renderer: &JsonRenderer<'_>) -> Self;
131}
132
133pub(crate) trait IntoJson<T> {
134 fn into_json(self, renderer: &JsonRenderer<'_>) -> T;
135}
136
137impl<T, U> IntoJson<U> for T
138where
139 U: FromClean<T>,
140{
141 fn into_json(self, renderer: &JsonRenderer<'_>) -> U {
142 U::from_clean(self, renderer)
143 }
144}
145
146impl<I, T, U> FromClean<I> for Vec<U>
147where
148 I: IntoIterator<Item = T>,
149 U: FromClean<T>,
150{
151 fn from_clean(f: I, renderer: &JsonRenderer<'_>) -> Vec<U> {
152 f.into_iter().map(|x| x.into_json(renderer)).collect()
153 }
154}
155
156pub(crate) fn from_deprecation(deprecation: rustc_attr_parsing::Deprecation) -> Deprecation {
157 let rustc_attr_parsing::Deprecation { since, note, suggestion: _ } = deprecation;
158 let since = match since {
159 DeprecatedSince::RustcVersion(version) => Some(version.to_string()),
160 DeprecatedSince::Future => Some("TBD".to_owned()),
161 DeprecatedSince::NonStandard(since) => Some(since.to_string()),
162 DeprecatedSince::Unspecified | DeprecatedSince::Err => None,
163 };
164 Deprecation { since, note: note.map(|s| s.to_string()) }
165}
166
167impl FromClean<clean::GenericArgs> for GenericArgs {
168 fn from_clean(args: clean::GenericArgs, renderer: &JsonRenderer<'_>) -> Self {
169 use clean::GenericArgs::*;
170 match args {
171 AngleBracketed { args, constraints } => GenericArgs::AngleBracketed {
172 args: args.into_json(renderer),
173 constraints: constraints.into_json(renderer),
174 },
175 Parenthesized { inputs, output } => GenericArgs::Parenthesized {
176 inputs: inputs.into_json(renderer),
177 output: output.map(|a| (*a).into_json(renderer)),
178 },
179 ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
180 }
181 }
182}
183
184impl FromClean<clean::GenericArg> for GenericArg {
185 fn from_clean(arg: clean::GenericArg, renderer: &JsonRenderer<'_>) -> Self {
186 use clean::GenericArg::*;
187 match arg {
188 Lifetime(l) => GenericArg::Lifetime(convert_lifetime(l)),
189 Type(t) => GenericArg::Type(t.into_json(renderer)),
190 Const(box c) => GenericArg::Const(c.into_json(renderer)),
191 Infer => GenericArg::Infer,
192 }
193 }
194}
195
196impl FromClean<clean::Constant> for Constant {
197 fn from_clean(constant: clean::Constant, renderer: &JsonRenderer<'_>) -> Self {
199 let tcx = renderer.tcx;
200 let expr = constant.expr(tcx);
201 let value = constant.value(tcx);
202 let is_literal = constant.is_literal(tcx);
203 Constant { expr, value, is_literal }
204 }
205}
206
207impl FromClean<clean::ConstantKind> for Constant {
208 fn from_clean(constant: clean::ConstantKind, renderer: &JsonRenderer<'_>) -> Self {
210 let tcx = renderer.tcx;
211 let expr = constant.expr(tcx);
212 let value = constant.value(tcx);
213 let is_literal = constant.is_literal(tcx);
214 Constant { expr, value, is_literal }
215 }
216}
217
218impl FromClean<clean::AssocItemConstraint> for AssocItemConstraint {
219 fn from_clean(constraint: clean::AssocItemConstraint, renderer: &JsonRenderer<'_>) -> Self {
220 AssocItemConstraint {
221 name: constraint.assoc.name.to_string(),
222 args: constraint.assoc.args.into_json(renderer),
223 binding: constraint.kind.into_json(renderer),
224 }
225 }
226}
227
228impl FromClean<clean::AssocItemConstraintKind> for AssocItemConstraintKind {
229 fn from_clean(kind: clean::AssocItemConstraintKind, renderer: &JsonRenderer<'_>) -> Self {
230 use clean::AssocItemConstraintKind::*;
231 match kind {
232 Equality { term } => AssocItemConstraintKind::Equality(term.into_json(renderer)),
233 Bound { bounds } => AssocItemConstraintKind::Constraint(bounds.into_json(renderer)),
234 }
235 }
236}
237
238fn from_clean_item(item: clean::Item, renderer: &JsonRenderer<'_>) -> ItemEnum {
239 use clean::ItemKind::*;
240 let name = item.name;
241 let is_crate = item.is_crate();
242 let header = item.fn_header(renderer.tcx);
243
244 match item.inner.kind {
245 ModuleItem(m) => {
246 ItemEnum::Module(Module { is_crate, items: renderer.ids(m.items), is_stripped: false })
247 }
248 ImportItem(i) => ItemEnum::Use(i.into_json(renderer)),
249 StructItem(s) => ItemEnum::Struct(s.into_json(renderer)),
250 UnionItem(u) => ItemEnum::Union(u.into_json(renderer)),
251 StructFieldItem(f) => ItemEnum::StructField(f.into_json(renderer)),
252 EnumItem(e) => ItemEnum::Enum(e.into_json(renderer)),
253 VariantItem(v) => ItemEnum::Variant(v.into_json(renderer)),
254 FunctionItem(f) => ItemEnum::Function(from_function(*f, true, header.unwrap(), renderer)),
255 ForeignFunctionItem(f, _) => {
256 ItemEnum::Function(from_function(*f, false, header.unwrap(), renderer))
257 }
258 TraitItem(t) => ItemEnum::Trait((*t).into_json(renderer)),
259 TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_json(renderer)),
260 MethodItem(m, _) => ItemEnum::Function(from_function(*m, true, header.unwrap(), renderer)),
261 RequiredMethodItem(m) => {
262 ItemEnum::Function(from_function(*m, false, header.unwrap(), renderer))
263 }
264 ImplItem(i) => ItemEnum::Impl((*i).into_json(renderer)),
265 StaticItem(s) => ItemEnum::Static(convert_static(s, rustc_hir::Safety::Safe, renderer)),
266 ForeignStaticItem(s, safety) => ItemEnum::Static(convert_static(s, safety, renderer)),
267 ForeignTypeItem => ItemEnum::ExternType,
268 TypeAliasItem(t) => ItemEnum::TypeAlias(t.into_json(renderer)),
269 ConstantItem(ci) => ItemEnum::Constant {
271 type_: ci.type_.into_json(renderer),
272 const_: ci.kind.into_json(renderer),
273 },
274 MacroItem(m) => ItemEnum::Macro(m.source),
275 ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_json(renderer)),
276 PrimitiveItem(p) => {
277 ItemEnum::Primitive(Primitive {
278 name: p.as_sym().to_string(),
279 impls: Vec::new(), })
281 }
282 RequiredAssocConstItem(_generics, ty) => {
284 ItemEnum::AssocConst { type_: (*ty).into_json(renderer), value: None }
285 }
286 ProvidedAssocConstItem(ci) | ImplAssocConstItem(ci) => ItemEnum::AssocConst {
288 type_: ci.type_.into_json(renderer),
289 value: Some(ci.kind.expr(renderer.tcx)),
290 },
291 RequiredAssocTypeItem(g, b) => ItemEnum::AssocType {
292 generics: g.into_json(renderer),
293 bounds: b.into_json(renderer),
294 type_: None,
295 },
296 AssocTypeItem(t, b) => ItemEnum::AssocType {
297 generics: t.generics.into_json(renderer),
298 bounds: b.into_json(renderer),
299 type_: Some(t.item_type.unwrap_or(t.type_).into_json(renderer)),
300 },
301 KeywordItem => unreachable!(),
303 StrippedItem(inner) => {
304 match *inner {
305 ModuleItem(m) => ItemEnum::Module(Module {
306 is_crate,
307 items: renderer.ids(m.items),
308 is_stripped: true,
309 }),
310 _ => unreachable!(),
312 }
313 }
314 ExternCrateItem { ref src } => ItemEnum::ExternCrate {
315 name: name.as_ref().unwrap().to_string(),
316 rename: src.map(|x| x.to_string()),
317 },
318 }
319}
320
321impl FromClean<clean::Struct> for Struct {
322 fn from_clean(struct_: clean::Struct, renderer: &JsonRenderer<'_>) -> Self {
323 let has_stripped_fields = struct_.has_stripped_entries();
324 let clean::Struct { ctor_kind, generics, fields } = struct_;
325
326 let kind = match ctor_kind {
327 Some(CtorKind::Fn) => StructKind::Tuple(renderer.ids_keeping_stripped(fields)),
328 Some(CtorKind::Const) => {
329 assert!(fields.is_empty());
330 StructKind::Unit
331 }
332 None => StructKind::Plain { fields: renderer.ids(fields), has_stripped_fields },
333 };
334
335 Struct {
336 kind,
337 generics: generics.into_json(renderer),
338 impls: Vec::new(), }
340 }
341}
342
343impl FromClean<clean::Union> for Union {
344 fn from_clean(union_: clean::Union, renderer: &JsonRenderer<'_>) -> Self {
345 let has_stripped_fields = union_.has_stripped_entries();
346 let clean::Union { generics, fields } = union_;
347 Union {
348 generics: generics.into_json(renderer),
349 has_stripped_fields,
350 fields: renderer.ids(fields),
351 impls: Vec::new(), }
353 }
354}
355
356pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> FunctionHeader {
357 FunctionHeader {
358 is_async: header.is_async(),
359 is_const: header.is_const(),
360 is_unsafe: header.is_unsafe(),
361 abi: convert_abi(header.abi),
362 }
363}
364
365fn convert_abi(a: ExternAbi) -> Abi {
366 match a {
367 ExternAbi::Rust => Abi::Rust,
368 ExternAbi::C { unwind } => Abi::C { unwind },
369 ExternAbi::Cdecl { unwind } => Abi::Cdecl { unwind },
370 ExternAbi::Stdcall { unwind } => Abi::Stdcall { unwind },
371 ExternAbi::Fastcall { unwind } => Abi::Fastcall { unwind },
372 ExternAbi::Aapcs { unwind } => Abi::Aapcs { unwind },
373 ExternAbi::Win64 { unwind } => Abi::Win64 { unwind },
374 ExternAbi::SysV64 { unwind } => Abi::SysV64 { unwind },
375 ExternAbi::System { unwind } => Abi::System { unwind },
376 _ => Abi::Other(a.to_string()),
377 }
378}
379
380fn convert_lifetime(l: clean::Lifetime) -> String {
381 l.0.to_string()
382}
383
384impl FromClean<clean::Generics> for Generics {
385 fn from_clean(generics: clean::Generics, renderer: &JsonRenderer<'_>) -> Self {
386 Generics {
387 params: generics.params.into_json(renderer),
388 where_predicates: generics.where_predicates.into_json(renderer),
389 }
390 }
391}
392
393impl FromClean<clean::GenericParamDef> for GenericParamDef {
394 fn from_clean(generic_param: clean::GenericParamDef, renderer: &JsonRenderer<'_>) -> Self {
395 GenericParamDef {
396 name: generic_param.name.to_string(),
397 kind: generic_param.kind.into_json(renderer),
398 }
399 }
400}
401
402impl FromClean<clean::GenericParamDefKind> for GenericParamDefKind {
403 fn from_clean(kind: clean::GenericParamDefKind, renderer: &JsonRenderer<'_>) -> Self {
404 use clean::GenericParamDefKind::*;
405 match kind {
406 Lifetime { outlives } => GenericParamDefKind::Lifetime {
407 outlives: outlives.into_iter().map(convert_lifetime).collect(),
408 },
409 Type { bounds, default, synthetic } => GenericParamDefKind::Type {
410 bounds: bounds.into_json(renderer),
411 default: default.map(|x| (*x).into_json(renderer)),
412 is_synthetic: synthetic,
413 },
414 Const { ty, default, synthetic: _ } => GenericParamDefKind::Const {
415 type_: (*ty).into_json(renderer),
416 default: default.map(|x| *x),
417 },
418 }
419 }
420}
421
422impl FromClean<clean::WherePredicate> for WherePredicate {
423 fn from_clean(predicate: clean::WherePredicate, renderer: &JsonRenderer<'_>) -> Self {
424 use clean::WherePredicate::*;
425 match predicate {
426 BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate {
427 type_: ty.into_json(renderer),
428 bounds: bounds.into_json(renderer),
429 generic_params: bound_params
430 .into_iter()
431 .map(|x| {
432 let name = x.name.to_string();
433 let kind = match x.kind {
434 clean::GenericParamDefKind::Lifetime { outlives } => {
435 GenericParamDefKind::Lifetime {
436 outlives: outlives.iter().map(|lt| lt.0.to_string()).collect(),
437 }
438 }
439 clean::GenericParamDefKind::Type { bounds, default, synthetic } => {
440 GenericParamDefKind::Type {
441 bounds: bounds
442 .into_iter()
443 .map(|bound| bound.into_json(renderer))
444 .collect(),
445 default: default.map(|ty| (*ty).into_json(renderer)),
446 is_synthetic: synthetic,
447 }
448 }
449 clean::GenericParamDefKind::Const { ty, default, synthetic: _ } => {
450 GenericParamDefKind::Const {
451 type_: (*ty).into_json(renderer),
452 default: default.map(|d| *d),
453 }
454 }
455 };
456 GenericParamDef { name, kind }
457 })
458 .collect(),
459 },
460 RegionPredicate { lifetime, bounds } => WherePredicate::LifetimePredicate {
461 lifetime: convert_lifetime(lifetime),
462 outlives: bounds
463 .iter()
464 .map(|bound| match bound {
465 clean::GenericBound::Outlives(lt) => convert_lifetime(*lt),
466 _ => bug!("found non-outlives-bound on lifetime predicate"),
467 })
468 .collect(),
469 },
470 EqPredicate { lhs, rhs } => WherePredicate::EqPredicate {
471 lhs: lhs.into_json(renderer),
472 rhs: rhs.into_json(renderer),
473 },
474 }
475 }
476}
477
478impl FromClean<clean::GenericBound> for GenericBound {
479 fn from_clean(bound: clean::GenericBound, renderer: &JsonRenderer<'_>) -> Self {
480 use clean::GenericBound::*;
481 match bound {
482 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
483 GenericBound::TraitBound {
484 trait_: trait_.into_json(renderer),
485 generic_params: generic_params.into_json(renderer),
486 modifier: from_trait_bound_modifier(modifier),
487 }
488 }
489 Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
490 Use(args) => GenericBound::Use(
491 args.iter()
492 .map(|arg| match arg {
493 clean::PreciseCapturingArg::Lifetime(lt) => {
494 PreciseCapturingArg::Lifetime(convert_lifetime(*lt))
495 }
496 clean::PreciseCapturingArg::Param(param) => {
497 PreciseCapturingArg::Param(param.to_string())
498 }
499 })
500 .collect(),
501 ),
502 }
503 }
504}
505
506pub(crate) fn from_trait_bound_modifier(
507 modifiers: rustc_hir::TraitBoundModifiers,
508) -> TraitBoundModifier {
509 use rustc_hir as hir;
510 let hir::TraitBoundModifiers { constness, polarity } = modifiers;
511 match (constness, polarity) {
512 (hir::BoundConstness::Never, hir::BoundPolarity::Positive) => TraitBoundModifier::None,
513 (hir::BoundConstness::Never, hir::BoundPolarity::Maybe(_)) => TraitBoundModifier::Maybe,
514 (hir::BoundConstness::Maybe(_), hir::BoundPolarity::Positive) => {
515 TraitBoundModifier::MaybeConst
516 }
517 _ => TraitBoundModifier::None,
519 }
520}
521
522impl FromClean<clean::Type> for Type {
523 fn from_clean(ty: clean::Type, renderer: &JsonRenderer<'_>) -> Self {
524 use clean::Type::{
525 Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
526 RawPointer, SelfTy, Slice, Tuple, UnsafeBinder,
527 };
528
529 match ty {
530 clean::Type::Path { path } => Type::ResolvedPath(path.into_json(renderer)),
531 clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
532 lifetime: lt.map(convert_lifetime),
533 traits: bounds.into_json(renderer),
534 }),
535 Generic(s) => Type::Generic(s.to_string()),
536 SelfTy => Type::Generic("Self".to_owned()),
538 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
539 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_json(renderer))),
540 Tuple(t) => Type::Tuple(t.into_json(renderer)),
541 Slice(t) => Type::Slice(Box::new((*t).into_json(renderer))),
542 Array(t, s) => {
543 Type::Array { type_: Box::new((*t).into_json(renderer)), len: s.to_string() }
544 }
545 clean::Type::Pat(t, p) => Type::Pat {
546 type_: Box::new((*t).into_json(renderer)),
547 __pat_unstable_do_not_use: p.to_string(),
548 },
549 ImplTrait(g) => Type::ImplTrait(g.into_json(renderer)),
550 Infer => Type::Infer,
551 RawPointer(mutability, type_) => Type::RawPointer {
552 is_mutable: mutability == ast::Mutability::Mut,
553 type_: Box::new((*type_).into_json(renderer)),
554 },
555 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
556 lifetime: lifetime.map(convert_lifetime),
557 is_mutable: mutability == ast::Mutability::Mut,
558 type_: Box::new((*type_).into_json(renderer)),
559 },
560 QPath(box clean::QPathData { assoc, self_type, trait_, .. }) => Type::QualifiedPath {
561 name: assoc.name.to_string(),
562 args: Box::new(assoc.args.into_json(renderer)),
563 self_type: Box::new(self_type.into_json(renderer)),
564 trait_: trait_.map(|trait_| trait_.into_json(renderer)),
565 },
566 UnsafeBinder(_) => todo!(),
568 }
569 }
570}
571
572impl FromClean<clean::Path> for Path {
573 fn from_clean(path: clean::Path, renderer: &JsonRenderer<'_>) -> Path {
574 Path {
575 path: path.whole_name(),
576 id: renderer.id_from_item_default(path.def_id().into()),
577 args: path.segments.last().map(|args| Box::new(args.clone().args.into_json(renderer))),
578 }
579 }
580}
581
582impl FromClean<clean::Term> for Term {
583 fn from_clean(term: clean::Term, renderer: &JsonRenderer<'_>) -> Term {
584 match term {
585 clean::Term::Type(ty) => Term::Type(ty.into_json(renderer)),
586 clean::Term::Constant(c) => Term::Constant(c.into_json(renderer)),
587 }
588 }
589}
590
591impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
592 fn from_clean(bare_decl: clean::BareFunctionDecl, renderer: &JsonRenderer<'_>) -> Self {
593 let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
594 FunctionPointer {
595 header: FunctionHeader {
596 is_unsafe: safety.is_unsafe(),
597 is_const: false,
598 is_async: false,
599 abi: convert_abi(abi),
600 },
601 generic_params: generic_params.into_json(renderer),
602 sig: decl.into_json(renderer),
603 }
604 }
605}
606
607impl FromClean<clean::FnDecl> for FunctionSignature {
608 fn from_clean(decl: clean::FnDecl, renderer: &JsonRenderer<'_>) -> Self {
609 let clean::FnDecl { inputs, output, c_variadic } = decl;
610 FunctionSignature {
611 inputs: inputs
612 .values
613 .into_iter()
614 .map(|arg| (arg.name.to_string(), arg.type_.into_json(renderer)))
615 .collect(),
616 output: if output.is_unit() { None } else { Some(output.into_json(renderer)) },
617 is_c_variadic: c_variadic,
618 }
619 }
620}
621
622impl FromClean<clean::Trait> for Trait {
623 fn from_clean(trait_: clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
624 let tcx = renderer.tcx;
625 let is_auto = trait_.is_auto(tcx);
626 let is_unsafe = trait_.safety(tcx).is_unsafe();
627 let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
628 let clean::Trait { items, generics, bounds, .. } = trait_;
629 Trait {
630 is_auto,
631 is_unsafe,
632 is_dyn_compatible,
633 items: renderer.ids(items),
634 generics: generics.into_json(renderer),
635 bounds: bounds.into_json(renderer),
636 implementations: Vec::new(), }
638 }
639}
640
641impl FromClean<clean::PolyTrait> for PolyTrait {
642 fn from_clean(
643 clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
644 renderer: &JsonRenderer<'_>,
645 ) -> Self {
646 PolyTrait {
647 trait_: trait_.into_json(renderer),
648 generic_params: generic_params.into_json(renderer),
649 }
650 }
651}
652
653impl FromClean<clean::Impl> for Impl {
654 fn from_clean(impl_: clean::Impl, renderer: &JsonRenderer<'_>) -> Self {
655 let provided_trait_methods = impl_.provided_trait_methods(renderer.tcx);
656 let clean::Impl { safety, generics, trait_, for_, items, polarity, kind } = impl_;
657 let (is_synthetic, blanket_impl) = match kind {
659 clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
660 clean::ImplKind::Auto => (true, None),
661 clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
662 };
663 let is_negative = match polarity {
664 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
665 ty::ImplPolarity::Negative => true,
666 };
667 Impl {
668 is_unsafe: safety.is_unsafe(),
669 generics: generics.into_json(renderer),
670 provided_trait_methods: provided_trait_methods
671 .into_iter()
672 .map(|x| x.to_string())
673 .collect(),
674 trait_: trait_.map(|path| path.into_json(renderer)),
675 for_: for_.into_json(renderer),
676 items: renderer.ids(items),
677 is_negative,
678 is_synthetic,
679 blanket_impl: blanket_impl.map(|x| x.into_json(renderer)),
680 }
681 }
682}
683
684pub(crate) fn from_function(
685 clean::Function { decl, generics }: clean::Function,
686 has_body: bool,
687 header: rustc_hir::FnHeader,
688 renderer: &JsonRenderer<'_>,
689) -> Function {
690 Function {
691 sig: decl.into_json(renderer),
692 generics: generics.into_json(renderer),
693 header: from_fn_header(&header),
694 has_body,
695 }
696}
697
698impl FromClean<clean::Enum> for Enum {
699 fn from_clean(enum_: clean::Enum, renderer: &JsonRenderer<'_>) -> Self {
700 let has_stripped_variants = enum_.has_stripped_entries();
701 let clean::Enum { variants, generics } = enum_;
702 Enum {
703 generics: generics.into_json(renderer),
704 has_stripped_variants,
705 variants: renderer.ids(variants),
706 impls: Vec::new(), }
708 }
709}
710
711impl FromClean<clean::Variant> for Variant {
712 fn from_clean(variant: clean::Variant, renderer: &JsonRenderer<'_>) -> Self {
713 use clean::VariantKind::*;
714
715 let discriminant = variant.discriminant.map(|d| d.into_json(renderer));
716
717 let kind = match variant.kind {
718 CLike => VariantKind::Plain,
719 Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)),
720 Struct(s) => VariantKind::Struct {
721 has_stripped_fields: s.has_stripped_entries(),
722 fields: renderer.ids(s.fields),
723 },
724 };
725
726 Variant { kind, discriminant }
727 }
728}
729
730impl FromClean<clean::Discriminant> for Discriminant {
731 fn from_clean(disr: clean::Discriminant, renderer: &JsonRenderer<'_>) -> Self {
732 let tcx = renderer.tcx;
733 Discriminant {
734 expr: disr.expr(tcx).unwrap(),
738 value: disr.value(tcx, false),
739 }
740 }
741}
742
743impl FromClean<clean::Import> for Use {
744 fn from_clean(import: clean::Import, renderer: &JsonRenderer<'_>) -> Self {
745 use clean::ImportKind::*;
746 let (name, is_glob) = match import.kind {
747 Simple(s) => (s.to_string(), false),
748 Glob => (
749 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
750 true,
751 ),
752 };
753 Use {
754 source: import.source.path.whole_name(),
755 name,
756 id: import.source.did.map(ItemId::from).map(|i| renderer.id_from_item_default(i)),
757 is_glob,
758 }
759 }
760}
761
762impl FromClean<clean::ProcMacro> for ProcMacro {
763 fn from_clean(mac: clean::ProcMacro, _renderer: &JsonRenderer<'_>) -> Self {
764 ProcMacro {
765 kind: from_macro_kind(mac.kind),
766 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
767 }
768 }
769}
770
771pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
772 use rustc_span::hygiene::MacroKind::*;
773 match kind {
774 Bang => MacroKind::Bang,
775 Attr => MacroKind::Attr,
776 Derive => MacroKind::Derive,
777 }
778}
779
780impl FromClean<Box<clean::TypeAlias>> for TypeAlias {
781 fn from_clean(type_alias: Box<clean::TypeAlias>, renderer: &JsonRenderer<'_>) -> Self {
782 let clean::TypeAlias { type_, generics, item_type: _, inner_type: _ } = *type_alias;
783 TypeAlias { type_: type_.into_json(renderer), generics: generics.into_json(renderer) }
784 }
785}
786
787fn convert_static(
788 stat: clean::Static,
789 safety: rustc_hir::Safety,
790 renderer: &JsonRenderer<'_>,
791) -> Static {
792 let tcx = renderer.tcx;
793 Static {
794 type_: (*stat.type_).into_json(renderer),
795 is_mutable: stat.mutability == ast::Mutability::Mut,
796 is_unsafe: safety.is_unsafe(),
797 expr: stat
798 .expr
799 .map(|e| rendered_const(tcx, tcx.hir_body(e), tcx.hir_body_owner_def_id(e)))
800 .unwrap_or_default(),
801 }
802}
803
804impl FromClean<clean::TraitAlias> for TraitAlias {
805 fn from_clean(alias: clean::TraitAlias, renderer: &JsonRenderer<'_>) -> Self {
806 TraitAlias {
807 generics: alias.generics.into_json(renderer),
808 params: alias.bounds.into_json(renderer),
809 }
810 }
811}
812
813impl FromClean<ItemType> for ItemKind {
814 fn from_clean(kind: ItemType, _renderer: &JsonRenderer<'_>) -> Self {
815 use ItemType::*;
816 match kind {
817 Module => ItemKind::Module,
818 ExternCrate => ItemKind::ExternCrate,
819 Import => ItemKind::Use,
820 Struct => ItemKind::Struct,
821 Union => ItemKind::Union,
822 Enum => ItemKind::Enum,
823 Function | TyMethod | Method => ItemKind::Function,
824 TypeAlias => ItemKind::TypeAlias,
825 Static => ItemKind::Static,
826 Constant => ItemKind::Constant,
827 Trait => ItemKind::Trait,
828 Impl => ItemKind::Impl,
829 StructField => ItemKind::StructField,
830 Variant => ItemKind::Variant,
831 Macro => ItemKind::Macro,
832 Primitive => ItemKind::Primitive,
833 AssocConst => ItemKind::AssocConst,
834 AssocType => ItemKind::AssocType,
835 ForeignType => ItemKind::ExternType,
836 Keyword => ItemKind::Keyword,
837 TraitAlias => ItemKind::TraitAlias,
838 ProcAttribute => ItemKind::ProcAttribute,
839 ProcDerive => ItemKind::ProcDerive,
840 }
841 }
842}