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