1#![allow(rustc::default_hash_types)]
6
7use rustc_abi::ExternAbi;
8use rustc_ast::ast;
9use rustc_attr_data_structures::{self as attrs, 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, kw};
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_and_repr(self.tcx, self.cache(), true);
44 let span = item.span(self.tcx);
45 let visibility = item.visibility(self.tcx);
46 let clean::ItemInner { name, item_id, .. } = *item.inner;
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() + 1),
88 end: (hi.line, hi.col.to_usize() + 1),
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: attrs::Deprecation) -> Deprecation {
157 let attrs::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),
475 rhs: rhs.into_json(renderer),
476 },
477 }
478 }
479}
480
481impl FromClean<clean::GenericBound> for GenericBound {
482 fn from_clean(bound: clean::GenericBound, renderer: &JsonRenderer<'_>) -> Self {
483 use clean::GenericBound::*;
484 match bound {
485 TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
486 GenericBound::TraitBound {
487 trait_: trait_.into_json(renderer),
488 generic_params: generic_params.into_json(renderer),
489 modifier: from_trait_bound_modifier(modifier),
490 }
491 }
492 Outlives(lifetime) => GenericBound::Outlives(convert_lifetime(lifetime)),
493 Use(args) => GenericBound::Use(
494 args.iter()
495 .map(|arg| match arg {
496 clean::PreciseCapturingArg::Lifetime(lt) => {
497 PreciseCapturingArg::Lifetime(convert_lifetime(*lt))
498 }
499 clean::PreciseCapturingArg::Param(param) => {
500 PreciseCapturingArg::Param(param.to_string())
501 }
502 })
503 .collect(),
504 ),
505 }
506 }
507}
508
509pub(crate) fn from_trait_bound_modifier(
510 modifiers: rustc_hir::TraitBoundModifiers,
511) -> TraitBoundModifier {
512 use rustc_hir as hir;
513 let hir::TraitBoundModifiers { constness, polarity } = modifiers;
514 match (constness, polarity) {
515 (hir::BoundConstness::Never, hir::BoundPolarity::Positive) => TraitBoundModifier::None,
516 (hir::BoundConstness::Never, hir::BoundPolarity::Maybe(_)) => TraitBoundModifier::Maybe,
517 (hir::BoundConstness::Maybe(_), hir::BoundPolarity::Positive) => {
518 TraitBoundModifier::MaybeConst
519 }
520 _ => TraitBoundModifier::None,
522 }
523}
524
525impl FromClean<clean::Type> for Type {
526 fn from_clean(ty: clean::Type, renderer: &JsonRenderer<'_>) -> Self {
527 use clean::Type::{
528 Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath,
529 RawPointer, SelfTy, Slice, Tuple, UnsafeBinder,
530 };
531
532 match ty {
533 clean::Type::Path { path } => Type::ResolvedPath(path.into_json(renderer)),
534 clean::Type::DynTrait(bounds, lt) => Type::DynTrait(DynTrait {
535 lifetime: lt.map(convert_lifetime),
536 traits: bounds.into_json(renderer),
537 }),
538 Generic(s) => Type::Generic(s.to_string()),
539 SelfTy => Type::Generic("Self".to_owned()),
541 Primitive(p) => Type::Primitive(p.as_sym().to_string()),
542 BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_json(renderer))),
543 Tuple(t) => Type::Tuple(t.into_json(renderer)),
544 Slice(t) => Type::Slice(Box::new((*t).into_json(renderer))),
545 Array(t, s) => {
546 Type::Array { type_: Box::new((*t).into_json(renderer)), len: s.to_string() }
547 }
548 clean::Type::Pat(t, p) => Type::Pat {
549 type_: Box::new((*t).into_json(renderer)),
550 __pat_unstable_do_not_use: p.to_string(),
551 },
552 ImplTrait(g) => Type::ImplTrait(g.into_json(renderer)),
553 Infer => Type::Infer,
554 RawPointer(mutability, type_) => Type::RawPointer {
555 is_mutable: mutability == ast::Mutability::Mut,
556 type_: Box::new((*type_).into_json(renderer)),
557 },
558 BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
559 lifetime: lifetime.map(convert_lifetime),
560 is_mutable: mutability == ast::Mutability::Mut,
561 type_: Box::new((*type_).into_json(renderer)),
562 },
563 QPath(qpath) => (*qpath).into_json(renderer),
564 UnsafeBinder(_) => todo!(),
566 }
567 }
568}
569
570impl FromClean<clean::Path> for Path {
571 fn from_clean(path: clean::Path, renderer: &JsonRenderer<'_>) -> Path {
572 Path {
573 path: path.whole_name(),
574 id: renderer.id_from_item_default(path.def_id().into()),
575 args: path.segments.last().map(|args| Box::new(args.clone().args.into_json(renderer))),
576 }
577 }
578}
579
580impl FromClean<clean::QPathData> for Type {
581 fn from_clean(qpath: clean::QPathData, renderer: &JsonRenderer<'_>) -> Self {
582 let clean::QPathData { assoc, self_type, should_fully_qualify: _, trait_ } = qpath;
583
584 Self::QualifiedPath {
585 name: assoc.name.to_string(),
586 args: Box::new(assoc.args.into_json(renderer)),
587 self_type: Box::new(self_type.into_json(renderer)),
588 trait_: trait_.map(|trait_| trait_.into_json(renderer)),
589 }
590 }
591}
592
593impl FromClean<clean::Term> for Term {
594 fn from_clean(term: clean::Term, renderer: &JsonRenderer<'_>) -> Term {
595 match term {
596 clean::Term::Type(ty) => Term::Type(ty.into_json(renderer)),
597 clean::Term::Constant(c) => Term::Constant(c.into_json(renderer)),
598 }
599 }
600}
601
602impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
603 fn from_clean(bare_decl: clean::BareFunctionDecl, renderer: &JsonRenderer<'_>) -> Self {
604 let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
605 FunctionPointer {
606 header: FunctionHeader {
607 is_unsafe: safety.is_unsafe(),
608 is_const: false,
609 is_async: false,
610 abi: convert_abi(abi),
611 },
612 generic_params: generic_params.into_json(renderer),
613 sig: decl.into_json(renderer),
614 }
615 }
616}
617
618impl FromClean<clean::FnDecl> for FunctionSignature {
619 fn from_clean(decl: clean::FnDecl, renderer: &JsonRenderer<'_>) -> Self {
620 let clean::FnDecl { inputs, output, c_variadic } = decl;
621 FunctionSignature {
622 inputs: inputs
623 .into_iter()
624 .map(|param| {
625 let name = param.name.unwrap_or(kw::Underscore).to_string();
627 let type_ = param.type_.into_json(renderer);
628 (name, type_)
629 })
630 .collect(),
631 output: if output.is_unit() { None } else { Some(output.into_json(renderer)) },
632 is_c_variadic: c_variadic,
633 }
634 }
635}
636
637impl FromClean<clean::Trait> for Trait {
638 fn from_clean(trait_: clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
639 let tcx = renderer.tcx;
640 let is_auto = trait_.is_auto(tcx);
641 let is_unsafe = trait_.safety(tcx).is_unsafe();
642 let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
643 let clean::Trait { items, generics, bounds, .. } = trait_;
644 Trait {
645 is_auto,
646 is_unsafe,
647 is_dyn_compatible,
648 items: renderer.ids(items),
649 generics: generics.into_json(renderer),
650 bounds: bounds.into_json(renderer),
651 implementations: Vec::new(), }
653 }
654}
655
656impl FromClean<clean::PolyTrait> for PolyTrait {
657 fn from_clean(
658 clean::PolyTrait { trait_, generic_params }: clean::PolyTrait,
659 renderer: &JsonRenderer<'_>,
660 ) -> Self {
661 PolyTrait {
662 trait_: trait_.into_json(renderer),
663 generic_params: generic_params.into_json(renderer),
664 }
665 }
666}
667
668impl FromClean<clean::Impl> for Impl {
669 fn from_clean(impl_: clean::Impl, renderer: &JsonRenderer<'_>) -> Self {
670 let provided_trait_methods = impl_.provided_trait_methods(renderer.tcx);
671 let clean::Impl { safety, generics, trait_, for_, items, polarity, kind } = impl_;
672 let (is_synthetic, blanket_impl) = match kind {
674 clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
675 clean::ImplKind::Auto => (true, None),
676 clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
677 };
678 let is_negative = match polarity {
679 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
680 ty::ImplPolarity::Negative => true,
681 };
682 Impl {
683 is_unsafe: safety.is_unsafe(),
684 generics: generics.into_json(renderer),
685 provided_trait_methods: provided_trait_methods
686 .into_iter()
687 .map(|x| x.to_string())
688 .collect(),
689 trait_: trait_.map(|path| path.into_json(renderer)),
690 for_: for_.into_json(renderer),
691 items: renderer.ids(items),
692 is_negative,
693 is_synthetic,
694 blanket_impl: blanket_impl.map(|x| x.into_json(renderer)),
695 }
696 }
697}
698
699pub(crate) fn from_function(
700 clean::Function { decl, generics }: clean::Function,
701 has_body: bool,
702 header: rustc_hir::FnHeader,
703 renderer: &JsonRenderer<'_>,
704) -> Function {
705 Function {
706 sig: decl.into_json(renderer),
707 generics: generics.into_json(renderer),
708 header: from_fn_header(&header),
709 has_body,
710 }
711}
712
713impl FromClean<clean::Enum> for Enum {
714 fn from_clean(enum_: clean::Enum, renderer: &JsonRenderer<'_>) -> Self {
715 let has_stripped_variants = enum_.has_stripped_entries();
716 let clean::Enum { variants, generics } = enum_;
717 Enum {
718 generics: generics.into_json(renderer),
719 has_stripped_variants,
720 variants: renderer.ids(variants),
721 impls: Vec::new(), }
723 }
724}
725
726impl FromClean<clean::Variant> for Variant {
727 fn from_clean(variant: clean::Variant, renderer: &JsonRenderer<'_>) -> Self {
728 use clean::VariantKind::*;
729
730 let discriminant = variant.discriminant.map(|d| d.into_json(renderer));
731
732 let kind = match variant.kind {
733 CLike => VariantKind::Plain,
734 Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)),
735 Struct(s) => VariantKind::Struct {
736 has_stripped_fields: s.has_stripped_entries(),
737 fields: renderer.ids(s.fields),
738 },
739 };
740
741 Variant { kind, discriminant }
742 }
743}
744
745impl FromClean<clean::Discriminant> for Discriminant {
746 fn from_clean(disr: clean::Discriminant, renderer: &JsonRenderer<'_>) -> Self {
747 let tcx = renderer.tcx;
748 Discriminant {
749 expr: disr.expr(tcx).unwrap(),
753 value: disr.value(tcx, false),
754 }
755 }
756}
757
758impl FromClean<clean::Import> for Use {
759 fn from_clean(import: clean::Import, renderer: &JsonRenderer<'_>) -> Self {
760 use clean::ImportKind::*;
761 let (name, is_glob) = match import.kind {
762 Simple(s) => (s.to_string(), false),
763 Glob => (
764 import.source.path.last_opt().unwrap_or_else(|| Symbol::intern("*")).to_string(),
765 true,
766 ),
767 };
768 Use {
769 source: import.source.path.whole_name(),
770 name,
771 id: import.source.did.map(ItemId::from).map(|i| renderer.id_from_item_default(i)),
772 is_glob,
773 }
774 }
775}
776
777impl FromClean<clean::ProcMacro> for ProcMacro {
778 fn from_clean(mac: clean::ProcMacro, _renderer: &JsonRenderer<'_>) -> Self {
779 ProcMacro {
780 kind: from_macro_kind(mac.kind),
781 helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
782 }
783 }
784}
785
786pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
787 use rustc_span::hygiene::MacroKind::*;
788 match kind {
789 Bang => MacroKind::Bang,
790 Attr => MacroKind::Attr,
791 Derive => MacroKind::Derive,
792 }
793}
794
795impl FromClean<Box<clean::TypeAlias>> for TypeAlias {
796 fn from_clean(type_alias: Box<clean::TypeAlias>, renderer: &JsonRenderer<'_>) -> Self {
797 let clean::TypeAlias { type_, generics, item_type: _, inner_type: _ } = *type_alias;
798 TypeAlias { type_: type_.into_json(renderer), generics: generics.into_json(renderer) }
799 }
800}
801
802fn convert_static(
803 stat: clean::Static,
804 safety: rustc_hir::Safety,
805 renderer: &JsonRenderer<'_>,
806) -> Static {
807 let tcx = renderer.tcx;
808 Static {
809 type_: (*stat.type_).into_json(renderer),
810 is_mutable: stat.mutability == ast::Mutability::Mut,
811 is_unsafe: safety.is_unsafe(),
812 expr: stat
813 .expr
814 .map(|e| rendered_const(tcx, tcx.hir_body(e), tcx.hir_body_owner_def_id(e)))
815 .unwrap_or_default(),
816 }
817}
818
819impl FromClean<clean::TraitAlias> for TraitAlias {
820 fn from_clean(alias: clean::TraitAlias, renderer: &JsonRenderer<'_>) -> Self {
821 TraitAlias {
822 generics: alias.generics.into_json(renderer),
823 params: alias.bounds.into_json(renderer),
824 }
825 }
826}
827
828impl FromClean<ItemType> for ItemKind {
829 fn from_clean(kind: ItemType, _renderer: &JsonRenderer<'_>) -> Self {
830 use ItemType::*;
831 match kind {
832 Module => ItemKind::Module,
833 ExternCrate => ItemKind::ExternCrate,
834 Import => ItemKind::Use,
835 Struct => ItemKind::Struct,
836 Union => ItemKind::Union,
837 Enum => ItemKind::Enum,
838 Function | TyMethod | Method => ItemKind::Function,
839 TypeAlias => ItemKind::TypeAlias,
840 Static => ItemKind::Static,
841 Constant => ItemKind::Constant,
842 Trait => ItemKind::Trait,
843 Impl => ItemKind::Impl,
844 StructField => ItemKind::StructField,
845 Variant => ItemKind::Variant,
846 Macro => ItemKind::Macro,
847 Primitive => ItemKind::Primitive,
848 AssocConst => ItemKind::AssocConst,
849 AssocType => ItemKind::AssocType,
850 ForeignType => ItemKind::ExternType,
851 Keyword => ItemKind::Keyword,
852 TraitAlias => ItemKind::TraitAlias,
853 ProcAttribute => ItemKind::ProcAttribute,
854 ProcDerive => ItemKind::ProcDerive,
855 }
856 }
857}