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