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