]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/conversions.rs
Auto merge of #80014 - jyn514:box-item-kind, r=nnethercote
[rust.git] / src / librustdoc / json / conversions.rs
1 //! These from impls are used to create the JSON types which get serialized. They're very close to
2 //! the `clean` types but with some fields removed or stringified to simplify the output and not
3 //! expose unstable compiler internals.
4
5 use std::convert::From;
6
7 use rustc_ast::ast;
8 use rustc_span::def_id::{DefId, CRATE_DEF_INDEX};
9 use rustc_span::Pos;
10
11 use crate::clean;
12 use crate::doctree;
13 use crate::formats::item_type::ItemType;
14 use crate::json::types::*;
15 use crate::json::JsonRenderer;
16
17 impl JsonRenderer<'_> {
18     pub(super) fn convert_item(&self, item: clean::Item) -> Option<Item> {
19         let item_type = ItemType::from(&item);
20         let deprecation = item.deprecation(self.tcx);
21         let clean::Item { source, name, attrs, kind, visibility, def_id } = item;
22         match *kind {
23             clean::StrippedItem(_) => None,
24             kind => Some(Item {
25                 id: def_id.into(),
26                 crate_id: def_id.krate.as_u32(),
27                 name: name.map(|sym| sym.to_string()),
28                 source: self.convert_span(source),
29                 visibility: self.convert_visibility(visibility),
30                 docs: attrs.collapsed_doc_value().unwrap_or_default(),
31                 links: attrs
32                     .links
33                     .into_iter()
34                     .filter_map(|clean::ItemLink { link, did, .. }| {
35                         did.map(|did| (link, did.into()))
36                     })
37                     .collect(),
38                 attrs: attrs
39                     .other_attrs
40                     .iter()
41                     .map(rustc_ast_pretty::pprust::attribute_to_string)
42                     .collect(),
43                 deprecation: deprecation.map(Into::into),
44                 kind: item_type.into(),
45                 inner: kind.into(),
46             }),
47         }
48     }
49
50     fn convert_span(&self, span: clean::Span) -> Option<Span> {
51         match span.filename(self.sess()) {
52             rustc_span::FileName::Real(name) => {
53                 let hi = span.hi(self.sess());
54                 let lo = span.lo(self.sess());
55                 Some(Span {
56                     filename: match name {
57                         rustc_span::RealFileName::Named(path) => path,
58                         rustc_span::RealFileName::Devirtualized { local_path, virtual_name: _ } => {
59                             local_path
60                         }
61                     },
62                     begin: (lo.line, lo.col.to_usize()),
63                     end: (hi.line, hi.col.to_usize()),
64                 })
65             }
66             _ => None,
67         }
68     }
69
70     fn convert_visibility(&self, v: clean::Visibility) -> Visibility {
71         use clean::Visibility::*;
72         match v {
73             Public => Visibility::Public,
74             Inherited => Visibility::Default,
75             Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
76             Restricted(did) => Visibility::Restricted {
77                 parent: did.into(),
78                 path: self.tcx.def_path(did).to_string_no_crate_verbose(),
79             },
80         }
81     }
82 }
83
84 impl From<rustc_attr::Deprecation> for Deprecation {
85     fn from(deprecation: rustc_attr::Deprecation) -> Self {
86         #[rustfmt::skip]
87         let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
88         Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
89     }
90 }
91
92 impl From<clean::GenericArgs> for GenericArgs {
93     fn from(args: clean::GenericArgs) -> Self {
94         use clean::GenericArgs::*;
95         match args {
96             AngleBracketed { args, bindings } => GenericArgs::AngleBracketed {
97                 args: args.into_iter().map(Into::into).collect(),
98                 bindings: bindings.into_iter().map(Into::into).collect(),
99             },
100             Parenthesized { inputs, output } => GenericArgs::Parenthesized {
101                 inputs: inputs.into_iter().map(Into::into).collect(),
102                 output: output.map(Into::into),
103             },
104         }
105     }
106 }
107
108 impl From<clean::GenericArg> for GenericArg {
109     fn from(arg: clean::GenericArg) -> Self {
110         use clean::GenericArg::*;
111         match arg {
112             Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
113             Type(t) => GenericArg::Type(t.into()),
114             Const(c) => GenericArg::Const(c.into()),
115         }
116     }
117 }
118
119 impl From<clean::Constant> for Constant {
120     fn from(constant: clean::Constant) -> Self {
121         let clean::Constant { type_, expr, value, is_literal } = constant;
122         Constant { type_: type_.into(), expr, value, is_literal }
123     }
124 }
125
126 impl From<clean::TypeBinding> for TypeBinding {
127     fn from(binding: clean::TypeBinding) -> Self {
128         TypeBinding { name: binding.name.to_string(), binding: binding.kind.into() }
129     }
130 }
131
132 impl From<clean::TypeBindingKind> for TypeBindingKind {
133     fn from(kind: clean::TypeBindingKind) -> Self {
134         use clean::TypeBindingKind::*;
135         match kind {
136             Equality { ty } => TypeBindingKind::Equality(ty.into()),
137             Constraint { bounds } => {
138                 TypeBindingKind::Constraint(bounds.into_iter().map(Into::into).collect())
139             }
140         }
141     }
142 }
143
144 impl From<DefId> for Id {
145     fn from(did: DefId) -> Self {
146         Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
147     }
148 }
149
150 impl From<clean::ItemKind> for ItemEnum {
151     fn from(item: clean::ItemKind) -> Self {
152         use clean::ItemKind::*;
153         match item {
154             ModuleItem(m) => ItemEnum::ModuleItem(m.into()),
155             ExternCrateItem(c, a) => {
156                 ItemEnum::ExternCrateItem { name: c.to_string(), rename: a.map(|x| x.to_string()) }
157             }
158             ImportItem(i) => ItemEnum::ImportItem(i.into()),
159             StructItem(s) => ItemEnum::StructItem(s.into()),
160             UnionItem(u) => ItemEnum::StructItem(u.into()),
161             StructFieldItem(f) => ItemEnum::StructFieldItem(f.into()),
162             EnumItem(e) => ItemEnum::EnumItem(e.into()),
163             VariantItem(v) => ItemEnum::VariantItem(v.into()),
164             FunctionItem(f) => ItemEnum::FunctionItem(f.into()),
165             ForeignFunctionItem(f) => ItemEnum::FunctionItem(f.into()),
166             TraitItem(t) => ItemEnum::TraitItem(t.into()),
167             TraitAliasItem(t) => ItemEnum::TraitAliasItem(t.into()),
168             MethodItem(m, _) => ItemEnum::MethodItem(m.into()),
169             TyMethodItem(m) => ItemEnum::MethodItem(m.into()),
170             ImplItem(i) => ItemEnum::ImplItem(i.into()),
171             StaticItem(s) => ItemEnum::StaticItem(s.into()),
172             ForeignStaticItem(s) => ItemEnum::StaticItem(s.into()),
173             ForeignTypeItem => ItemEnum::ForeignTypeItem,
174             TypedefItem(t, _) => ItemEnum::TypedefItem(t.into()),
175             OpaqueTyItem(t) => ItemEnum::OpaqueTyItem(t.into()),
176             ConstantItem(c) => ItemEnum::ConstantItem(c.into()),
177             MacroItem(m) => ItemEnum::MacroItem(m.source),
178             ProcMacroItem(m) => ItemEnum::ProcMacroItem(m.into()),
179             AssocConstItem(t, s) => ItemEnum::AssocConstItem { type_: t.into(), default: s },
180             AssocTypeItem(g, t) => ItemEnum::AssocTypeItem {
181                 bounds: g.into_iter().map(Into::into).collect(),
182                 default: t.map(Into::into),
183             },
184             StrippedItem(inner) => (*inner).into(),
185             PrimitiveItem(_) | KeywordItem(_) => {
186                 panic!("{:?} is not supported for JSON output", item)
187             }
188         }
189     }
190 }
191
192 impl From<clean::Module> for Module {
193     fn from(module: clean::Module) -> Self {
194         Module { is_crate: module.is_crate, items: ids(module.items) }
195     }
196 }
197
198 impl From<clean::Struct> for Struct {
199     fn from(struct_: clean::Struct) -> Self {
200         let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
201         Struct {
202             struct_type: struct_type.into(),
203             generics: generics.into(),
204             fields_stripped,
205             fields: ids(fields),
206             impls: Vec::new(), // Added in JsonRenderer::item
207         }
208     }
209 }
210
211 impl From<clean::Union> for Struct {
212     fn from(struct_: clean::Union) -> Self {
213         let clean::Union { struct_type, generics, fields, fields_stripped } = struct_;
214         Struct {
215             struct_type: struct_type.into(),
216             generics: generics.into(),
217             fields_stripped,
218             fields: ids(fields),
219             impls: Vec::new(), // Added in JsonRenderer::item
220         }
221     }
222 }
223
224 impl From<doctree::StructType> for StructType {
225     fn from(struct_type: doctree::StructType) -> Self {
226         use doctree::StructType::*;
227         match struct_type {
228             Plain => StructType::Plain,
229             Tuple => StructType::Tuple,
230             Unit => StructType::Unit,
231         }
232     }
233 }
234
235 fn stringify_header(header: &rustc_hir::FnHeader) -> String {
236     let mut s = String::from(header.unsafety.prefix_str());
237     if header.asyncness == rustc_hir::IsAsync::Async {
238         s.push_str("async ")
239     }
240     if header.constness == rustc_hir::Constness::Const {
241         s.push_str("const ")
242     }
243     s
244 }
245
246 impl From<clean::Function> for Function {
247     fn from(function: clean::Function) -> Self {
248         let clean::Function { decl, generics, header, all_types: _, ret_types: _ } = function;
249         Function {
250             decl: decl.into(),
251             generics: generics.into(),
252             header: stringify_header(&header),
253             abi: header.abi.to_string(),
254         }
255     }
256 }
257
258 impl From<clean::Generics> for Generics {
259     fn from(generics: clean::Generics) -> Self {
260         Generics {
261             params: generics.params.into_iter().map(Into::into).collect(),
262             where_predicates: generics.where_predicates.into_iter().map(Into::into).collect(),
263         }
264     }
265 }
266
267 impl From<clean::GenericParamDef> for GenericParamDef {
268     fn from(generic_param: clean::GenericParamDef) -> Self {
269         GenericParamDef { name: generic_param.name.to_string(), kind: generic_param.kind.into() }
270     }
271 }
272
273 impl From<clean::GenericParamDefKind> for GenericParamDefKind {
274     fn from(kind: clean::GenericParamDefKind) -> Self {
275         use clean::GenericParamDefKind::*;
276         match kind {
277             Lifetime => GenericParamDefKind::Lifetime,
278             Type { did: _, bounds, default, synthetic: _ } => GenericParamDefKind::Type {
279                 bounds: bounds.into_iter().map(Into::into).collect(),
280                 default: default.map(Into::into),
281             },
282             Const { did: _, ty } => GenericParamDefKind::Const(ty.into()),
283         }
284     }
285 }
286
287 impl From<clean::WherePredicate> for WherePredicate {
288     fn from(predicate: clean::WherePredicate) -> Self {
289         use clean::WherePredicate::*;
290         match predicate {
291             BoundPredicate { ty, bounds } => WherePredicate::BoundPredicate {
292                 ty: ty.into(),
293                 bounds: bounds.into_iter().map(Into::into).collect(),
294             },
295             RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
296                 lifetime: lifetime.0.to_string(),
297                 bounds: bounds.into_iter().map(Into::into).collect(),
298             },
299             EqPredicate { lhs, rhs } => {
300                 WherePredicate::EqPredicate { lhs: lhs.into(), rhs: rhs.into() }
301             }
302         }
303     }
304 }
305
306 impl From<clean::GenericBound> for GenericBound {
307     fn from(bound: clean::GenericBound) -> Self {
308         use clean::GenericBound::*;
309         match bound {
310             TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => {
311                 GenericBound::TraitBound {
312                     trait_: trait_.into(),
313                     generic_params: generic_params.into_iter().map(Into::into).collect(),
314                     modifier: modifier.into(),
315                 }
316             }
317             Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
318         }
319     }
320 }
321
322 impl From<rustc_hir::TraitBoundModifier> for TraitBoundModifier {
323     fn from(modifier: rustc_hir::TraitBoundModifier) -> Self {
324         use rustc_hir::TraitBoundModifier::*;
325         match modifier {
326             None => TraitBoundModifier::None,
327             Maybe => TraitBoundModifier::Maybe,
328             MaybeConst => TraitBoundModifier::MaybeConst,
329         }
330     }
331 }
332
333 impl From<clean::Type> for Type {
334     fn from(ty: clean::Type) -> Self {
335         use clean::Type::*;
336         match ty {
337             ResolvedPath { path, param_names, did, is_generic: _ } => Type::ResolvedPath {
338                 name: path.whole_name(),
339                 id: did.into(),
340                 args: path.segments.last().map(|args| Box::new(args.clone().args.into())),
341                 param_names: param_names
342                     .map(|v| v.into_iter().map(Into::into).collect())
343                     .unwrap_or_default(),
344             },
345             Generic(s) => Type::Generic(s.to_string()),
346             Primitive(p) => Type::Primitive(p.as_str().to_string()),
347             BareFunction(f) => Type::FunctionPointer(Box::new((*f).into())),
348             Tuple(t) => Type::Tuple(t.into_iter().map(Into::into).collect()),
349             Slice(t) => Type::Slice(Box::new((*t).into())),
350             Array(t, s) => Type::Array { type_: Box::new((*t).into()), len: s },
351             ImplTrait(g) => Type::ImplTrait(g.into_iter().map(Into::into).collect()),
352             Never => Type::Never,
353             Infer => Type::Infer,
354             RawPointer(mutability, type_) => Type::RawPointer {
355                 mutable: mutability == ast::Mutability::Mut,
356                 type_: Box::new((*type_).into()),
357             },
358             BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
359                 lifetime: lifetime.map(|l| l.0.to_string()),
360                 mutable: mutability == ast::Mutability::Mut,
361                 type_: Box::new((*type_).into()),
362             },
363             QPath { name, self_type, trait_ } => Type::QualifiedPath {
364                 name: name.to_string(),
365                 self_type: Box::new((*self_type).into()),
366                 trait_: Box::new((*trait_).into()),
367             },
368         }
369     }
370 }
371
372 impl From<clean::BareFunctionDecl> for FunctionPointer {
373     fn from(bare_decl: clean::BareFunctionDecl) -> Self {
374         let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl;
375         FunctionPointer {
376             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
377             generic_params: generic_params.into_iter().map(Into::into).collect(),
378             decl: decl.into(),
379             abi: abi.to_string(),
380         }
381     }
382 }
383
384 impl From<clean::FnDecl> for FnDecl {
385     fn from(decl: clean::FnDecl) -> Self {
386         let clean::FnDecl { inputs, output, c_variadic, attrs: _ } = decl;
387         FnDecl {
388             inputs: inputs
389                 .values
390                 .into_iter()
391                 .map(|arg| (arg.name.to_string(), arg.type_.into()))
392                 .collect(),
393             output: match output {
394                 clean::FnRetTy::Return(t) => Some(t.into()),
395                 clean::FnRetTy::DefaultReturn => None,
396             },
397             c_variadic,
398         }
399     }
400 }
401
402 impl From<clean::Trait> for Trait {
403     fn from(trait_: clean::Trait) -> Self {
404         let clean::Trait { unsafety, items, generics, bounds, is_spotlight: _, is_auto } = trait_;
405         Trait {
406             is_auto,
407             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
408             items: ids(items),
409             generics: generics.into(),
410             bounds: bounds.into_iter().map(Into::into).collect(),
411             implementors: Vec::new(), // Added in JsonRenderer::item
412         }
413     }
414 }
415
416 impl From<clean::Impl> for Impl {
417     fn from(impl_: clean::Impl) -> Self {
418         let clean::Impl {
419             unsafety,
420             generics,
421             provided_trait_methods,
422             trait_,
423             for_,
424             items,
425             polarity,
426             synthetic,
427             blanket_impl,
428         } = impl_;
429         Impl {
430             is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
431             generics: generics.into(),
432             provided_trait_methods: provided_trait_methods
433                 .into_iter()
434                 .map(|x| x.to_string())
435                 .collect(),
436             trait_: trait_.map(Into::into),
437             for_: for_.into(),
438             items: ids(items),
439             negative: polarity == Some(clean::ImplPolarity::Negative),
440             synthetic,
441             blanket_impl: blanket_impl.map(Into::into),
442         }
443     }
444 }
445
446 impl From<clean::Function> for Method {
447     fn from(function: clean::Function) -> Self {
448         let clean::Function { header, decl, generics, all_types: _, ret_types: _ } = function;
449         Method {
450             decl: decl.into(),
451             generics: generics.into(),
452             header: stringify_header(&header),
453             has_body: true,
454         }
455     }
456 }
457
458 impl From<clean::Enum> for Enum {
459     fn from(enum_: clean::Enum) -> Self {
460         let clean::Enum { variants, generics, variants_stripped } = enum_;
461         Enum {
462             generics: generics.into(),
463             variants_stripped,
464             variants: ids(variants),
465             impls: Vec::new(), // Added in JsonRenderer::item
466         }
467     }
468 }
469
470 impl From<clean::VariantStruct> for Struct {
471     fn from(struct_: clean::VariantStruct) -> Self {
472         let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
473         Struct {
474             struct_type: struct_type.into(),
475             generics: Default::default(),
476             fields_stripped,
477             fields: ids(fields),
478             impls: Vec::new(),
479         }
480     }
481 }
482
483 impl From<clean::Variant> for Variant {
484     fn from(variant: clean::Variant) -> Self {
485         use clean::VariantKind::*;
486         match variant.kind {
487             CLike => Variant::Plain,
488             Tuple(t) => Variant::Tuple(t.into_iter().map(Into::into).collect()),
489             Struct(s) => Variant::Struct(ids(s.fields)),
490         }
491     }
492 }
493
494 impl From<clean::Import> for Import {
495     fn from(import: clean::Import) -> Self {
496         use clean::ImportKind::*;
497         match import.kind {
498             Simple(s) => Import {
499                 span: import.source.path.whole_name(),
500                 name: s.to_string(),
501                 id: import.source.did.map(Into::into),
502                 glob: false,
503             },
504             Glob => Import {
505                 span: import.source.path.whole_name(),
506                 name: import.source.path.last_name().to_string(),
507                 id: import.source.did.map(Into::into),
508                 glob: true,
509             },
510         }
511     }
512 }
513
514 impl From<clean::ProcMacro> for ProcMacro {
515     fn from(mac: clean::ProcMacro) -> Self {
516         ProcMacro {
517             kind: mac.kind.into(),
518             helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
519         }
520     }
521 }
522
523 impl From<rustc_span::hygiene::MacroKind> for MacroKind {
524     fn from(kind: rustc_span::hygiene::MacroKind) -> Self {
525         use rustc_span::hygiene::MacroKind::*;
526         match kind {
527             Bang => MacroKind::Bang,
528             Attr => MacroKind::Attr,
529             Derive => MacroKind::Derive,
530         }
531     }
532 }
533
534 impl From<clean::Typedef> for Typedef {
535     fn from(typedef: clean::Typedef) -> Self {
536         let clean::Typedef { type_, generics, item_type: _ } = typedef;
537         Typedef { type_: type_.into(), generics: generics.into() }
538     }
539 }
540
541 impl From<clean::OpaqueTy> for OpaqueTy {
542     fn from(opaque: clean::OpaqueTy) -> Self {
543         OpaqueTy {
544             bounds: opaque.bounds.into_iter().map(Into::into).collect(),
545             generics: opaque.generics.into(),
546         }
547     }
548 }
549
550 impl From<clean::Static> for Static {
551     fn from(stat: clean::Static) -> Self {
552         Static {
553             type_: stat.type_.into(),
554             mutable: stat.mutability == ast::Mutability::Mut,
555             expr: stat.expr,
556         }
557     }
558 }
559
560 impl From<clean::TraitAlias> for TraitAlias {
561     fn from(alias: clean::TraitAlias) -> Self {
562         TraitAlias {
563             generics: alias.generics.into(),
564             params: alias.bounds.into_iter().map(Into::into).collect(),
565         }
566     }
567 }
568
569 impl From<ItemType> for ItemKind {
570     fn from(kind: ItemType) -> Self {
571         use ItemType::*;
572         match kind {
573             Module => ItemKind::Module,
574             ExternCrate => ItemKind::ExternCrate,
575             Import => ItemKind::Import,
576             Struct => ItemKind::Struct,
577             Union => ItemKind::Union,
578             Enum => ItemKind::Enum,
579             Function => ItemKind::Function,
580             Typedef => ItemKind::Typedef,
581             OpaqueTy => ItemKind::OpaqueTy,
582             Static => ItemKind::Static,
583             Constant => ItemKind::Constant,
584             Trait => ItemKind::Trait,
585             Impl => ItemKind::Impl,
586             TyMethod | Method => ItemKind::Method,
587             StructField => ItemKind::StructField,
588             Variant => ItemKind::Variant,
589             Macro => ItemKind::Macro,
590             Primitive => ItemKind::Primitive,
591             AssocConst => ItemKind::AssocConst,
592             AssocType => ItemKind::AssocType,
593             ForeignType => ItemKind::ForeignType,
594             Keyword => ItemKind::Keyword,
595             TraitAlias => ItemKind::TraitAlias,
596             ProcAttribute => ItemKind::ProcAttribute,
597             ProcDerive => ItemKind::ProcDerive,
598         }
599     }
600 }
601
602 fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
603     items.into_iter().filter(|x| !x.is_stripped()).map(|i| i.def_id.into()).collect()
604 }