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