-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathlib.rs
More file actions
1757 lines (1670 loc) · 70 KB
/
lib.rs
File metadata and controls
1757 lines (1670 loc) · 70 KB
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Rustdoc's JSON output interface
//!
//! These types are the public API exposed through the `--output-format json` flag. The [`Crate`]
//! struct is the root of the JSON blob and all other items are contained within.
//!
//! # Feature Flags
//!
//! ## `rustc-hash`
//!
//! We expose a `rustc-hash` feature, disabled by default. This feature switches the
//! [`std::collections::HashMap`] for [`rustc_hash::FxHashMap`] to improve the performance of said
//! `HashMap` in specific situations.
//!
//! `cargo-semver-checks` for example, saw a [-3% improvement][1] when benchmarking using the
//! `aws_sdk_ec2` JSON output (~500MB of JSON). As always, we recommend measuring the impact before
//! turning this feature on, as [`FxHashMap`][2] only concerns itself with hash speed, and may
//! increase the number of collisions.
//!
//! ## `rkyv_0_8`
//!
//! We expose a `rkyv_0_8` feature, disabled by default. When enabled, it derives `rkyv`'s
//! [`Archive`][3], [`Serialize`][4] and [`Deserialize`][5] traits for all types in this crate.
//! Furthermore, it exposes the corresponding `Archived*` types (e.g. `ArchivedId` for [`Id`]).
//!
//! `rkyv` lets you works with JSON output without paying the deserialization cost _upfront_,
//! thanks to [zero-copy deserialization][6].
//! You can perform various types of analyses on the `Archived*` version of the relevant types,
//! incurring the full deserialization cost only for the subset of items you actually need.
//!
//! [1]: https://rust-lang.zulipchat.com/#narrow/channel/266220-t-rustdoc/topic/rustc-hash.20and.20performance.20of.20rustdoc-types/near/474855731
//! [2]: https://crates.io/crates/rustc-hash
//! [3]: https://docs.rs/rkyv/0.8.15/rkyv/trait.Archive.html
//! [4]: https://docs.rs/rkyv/0.8.15/rkyv/trait.Serialize.html
//! [5]: https://docs.rs/rkyv/0.8.15/rkyv/trait.Deserialize.html
//! [6]: https://rkyv.org/zero-copy-deserialization.html
// # On `rkyv` Derives
//
// In most cases, it's enough to add `#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]`
// on top of a type to derive the relevant `rkyv` traits.
//
// There are a few exceptions, though, where more complex macro options are required.
// The following sections break down the patterns that are showcased by `rkyv'`s
// [JSON schema example](https://github.com/rkyv/rkyv/blob/985b0230a0b9cb9fce4a4ee9facb6af148e27c8e/rkyv/examples/json_like_schema.rs).
//
// ## Recursive Types
//
// Let's look at the `Type` enum as an example. It stores a `Box<Type>` in its `Slice` variant.
// A "vanilla" `rkyv` annotation will cause an overflow in the compiler when
// building the crate, since the bounds generated by the macro will be self-referential and thus
// trap the compiler into a never-ending loop.
//
// To prevent this issue, `#[rkyv(omit_bounds)]` must be added to the relevant field.
//
// ## Co-Recursive Types
//
// The same problem occurs if a type is co-recursive—i.e. it doesn't _directly_ store a pointer
// to another instance of the same type, but one of its fields does, transitively.
//
// For example, let's look at `Path`:
//
// - `Path` has a field of type `Option<Box<GenericArgs>>`
// - One of the variants in `GenericArgs` has a field of type `Vec<GenericArg>`
// - One of the variants of `GenericArg` has a field of type `Type`
// - `Type::ResolvedPath` stores a `Path` instance
//
// The same logic of the recursive case applies here: we must use `#[rkyv(omit_bounds)]` to break the cycle.
//
// ## Additional Bounds
//
// Whenever `#[rkyv(omit_bounds)]` is added to a field or variant, `rkyv` omits _all_ traits bounds for that
// field in the generated impl. This may result in compilation errors due to insufficient bounds in the
// generated code.
//
// To add _some_ bounds back, `rkyv` exposes four knobs:
//
// - `#[rkyv(archive_bounds(..))]` to add predicates to all generated impls
// - `#[rkyv(serialize_bounds(..))]` to add predicates to just the `Serialize` impl
// - `#[rkyv(deserialize_bounds(..))]` to add predicates to just the `Deserialize` impl
// - `#[rkyv(bytecheck(bounds(..)))]` to add predicates to just the `CheckBytes` impl
//
// In particular, we use the following annotations in this crate:
//
// - `serialize_bounds(__S: rkyv::ser::Writer + rkyv::ser::Allocator, __S::Error: rkyv::rancor::Source)` for serializing
// variable-length types like `Vec<T>`. `rkyv`'s zero-copy format requires the serializer to be able
// to write bytes (`Writer`) and allocate scratch space (`Allocator`) for these types
// ([`rkyv`'s `Vec` impl bounds](https://docs.rs/rkyv/0.8.15/rkyv/trait.Serialize.html#impl-Serialize%3CS%3E-for-Vec%3CT%3E)).
// The `Error: Source` bound lets error types compose.
// - `deserialize_bounds(__D::Error: rkyv::rancor::Source)` so that errors from deserializing fields behind
// `omit_bounds` (e.g. `Box<T>`, `Vec<T>`) can compose via the `Source` trait.
// - `bytecheck(bounds(__C: rkyv::validation::ArchiveContext, __C::Error: rkyv::rancor::Source))` for validating
// archived data. Checking that bytes represent a valid archived value requires an `ArchiveContext` that tracks
// validation state (e.g. subtree ranges, to prevent overlapping/out-of-bounds archived data).
#[cfg(not(feature = "rustc-hash"))]
use std::collections::HashMap;
use std::path::PathBuf;
#[cfg(feature = "rustc-hash")]
use rustc_hash::FxHashMap as HashMap;
use serde_derive::{Deserialize, Serialize};
/// The version of JSON output that this crate represents.
///
/// This integer is incremented with every breaking change to the API,
/// and is returned along with the JSON blob as [`Crate::format_version`].
/// Consuming code should assert that this value matches the format version(s) that it supports.
//
// WARNING: When you update `FORMAT_VERSION`, please also update the "Latest feature" line with a
// description of the change. This minimizes the risk of two concurrent PRs changing
// `FORMAT_VERSION` from N to N+1 and git merging them without conflicts; the "Latest feature" line
// will instead cause conflicts. See #94591 for more. (This paragraph and the "Latest feature" line
// are deliberately not in a doc comment, because they need not be in public docs.)
//
// Latest feature: Add `ExternCrate::path`.
pub const FORMAT_VERSION: u32 = 57;
/// The root of the emitted JSON blob.
///
/// It contains all type/documentation information
/// about the language items in the local crate, as well as info about external items to allow
/// tools to find or link to them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Crate {
/// The id of the root [`Module`] item of the local crate.
pub root: Id,
/// The version string given to `--crate-version`, if any.
pub crate_version: Option<String>,
/// Whether or not the output includes private items.
pub includes_private: bool,
/// A collection of all items in the local crate as well as some external traits and their
/// items that are referenced locally.
pub index: HashMap<Id, Item>,
/// Maps IDs to fully qualified paths and other info helpful for generating links.
pub paths: HashMap<Id, ItemSummary>,
/// Maps `crate_id` of items to a crate name and html_root_url if it exists.
pub external_crates: HashMap<u32, ExternalCrate>,
/// Information about the target for which this documentation was generated
pub target: Target,
/// A single version number to be used in the future when making backwards incompatible changes
/// to the JSON output.
pub format_version: u32,
}
/// Information about a target
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Target {
/// The target triple for which this documentation was generated
pub triple: String,
/// A list of features valid for use in `#[target_feature]` attributes
/// for the target where this rustdoc JSON was generated.
pub target_features: Vec<TargetFeature>,
}
/// Information about a target feature.
///
/// Rust target features are used to influence code generation, especially around selecting
/// instructions which are not universally supported by the target architecture.
///
/// Target features are commonly enabled by the [`#[target_feature]` attribute][1] to influence code
/// generation for a particular function, and less commonly enabled by compiler options like
/// `-Ctarget-feature` or `-Ctarget-cpu`. Targets themselves automatically enable certain target
/// features by default, for example because the target's ABI specification requires saving specific
/// registers which only exist in an architectural extension.
///
/// Target features can imply other target features: for example, x86-64 `avx2` implies `avx`, and
/// aarch64 `sve2` implies `sve`, since both of these architectural extensions depend on their
/// predecessors.
///
/// Target features can be probed at compile time by [`#[cfg(target_feature)]`][2] or `cfg!(…)`
/// conditional compilation to determine whether a target feature is enabled in a particular
/// context.
///
/// [1]: https://doc.rust-lang.org/stable/reference/attributes/codegen.html#the-target_feature-attribute
/// [2]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct TargetFeature {
/// The name of this target feature.
pub name: String,
/// Other target features which are implied by this target feature, if any.
pub implies_features: Vec<String>,
/// If this target feature is unstable, the name of the associated language feature gate.
pub unstable_feature_gate: Option<String>,
/// Whether this feature is globally enabled for this compilation session.
///
/// Target features can be globally enabled implicitly as a result of the target's definition.
/// For example, x86-64 hardware floating point ABIs require saving x87 and SSE2 registers,
/// which in turn requires globally enabling the `x87` and `sse2` target features so that the
/// generated machine code conforms to the target's ABI.
///
/// Target features can also be globally enabled explicitly as a result of compiler flags like
/// [`-Ctarget-feature`][1] or [`-Ctarget-cpu`][2].
///
/// [1]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-feature
/// [2]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-cpu
pub globally_enabled: bool,
}
/// Metadata of a crate, either the same crate on which `rustdoc` was invoked, or its dependency.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct ExternalCrate {
/// The name of the crate.
///
/// Note: This is the [*crate* name][crate-name], which may not be the same as the
/// [*package* name][package-name]. For example, for <https://crates.io/crates/regex-syntax>,
/// this field will be `regex_syntax` (which uses an `_`, not a `-`).
///
/// [crate-name]: https://doc.rust-lang.org/stable/cargo/reference/cargo-targets.html#the-name-field
/// [package-name]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-name-field
pub name: String,
/// The root URL at which the crate's documentation lives.
pub html_root_url: Option<String>,
/// A path from where this crate was loaded.
///
/// This will typically be a `.rlib` or `.rmeta`. It can be used to determine which crate
/// this was in terms of whatever build-system invoked rustc.
#[cfg_attr(feature = "rkyv_0_8", rkyv(with = rkyv::with::AsString))]
pub path: PathBuf,
}
/// Information about an external (not defined in the local crate) [`Item`].
///
/// For external items, you don't get the same level of
/// information. This struct should contain enough to generate a link/reference to the item in
/// question, or can be used by a tool that takes the json output of multiple crates to find
/// the actual item definition with all the relevant info.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct ItemSummary {
/// Can be used to look up the name and html_root_url of the crate this item came from in the
/// `external_crates` map.
pub crate_id: u32,
/// The list of path components for the fully qualified path of this item (e.g.
/// `["std", "io", "lazy", "Lazy"]` for `std::io::lazy::Lazy`).
///
/// Note that items can appear in multiple paths, and the one chosen is implementation
/// defined. Currently, this is the full path to where the item was defined. Eg
/// [`String`] is currently `["alloc", "string", "String"]` and [`HashMap`][`std::collections::HashMap`]
/// is `["std", "collections", "hash", "map", "HashMap"]`, but this is subject to change.
pub path: Vec<String>,
/// Whether this item is a struct, trait, macro, etc.
pub kind: ItemKind,
}
/// Anything that can hold documentation - modules, structs, enums, functions, traits, etc.
///
/// The `Item` data type holds fields that can apply to any of these,
/// and leaves kind-specific details (like function args or enum variants) to the `inner` field.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Item {
/// The unique identifier of this item. Can be used to find this item in various mappings.
pub id: Id,
/// This can be used as a key to the `external_crates` map of [`Crate`] to see which crate
/// this item came from.
pub crate_id: u32,
/// Some items such as impls don't have names.
pub name: Option<String>,
/// The source location of this item (absent if it came from a macro expansion or inline
/// assembly).
pub span: Option<Span>,
/// By default all documented items are public, but you can tell rustdoc to output private items
/// so this field is needed to differentiate.
pub visibility: Visibility,
/// The full markdown docstring of this item. Absent if there is no documentation at all,
/// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
pub docs: Option<String>,
/// This mapping resolves [intra-doc links](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md) from the docstring to their IDs
pub links: HashMap<String, Id>,
/// Attributes on this item.
///
/// Does not include `#[deprecated]` attributes: see the [`Self::deprecation`] field instead.
///
/// Attributes appear in pretty-printed Rust form, regardless of their formatting
/// in the original source code. For example:
/// - `#[non_exhaustive]` and `#[must_use]` are represented as themselves.
/// - `#[no_mangle]` and `#[export_name]` are also represented as themselves.
/// - `#[repr(C)]` and other reprs also appear as themselves,
/// though potentially with a different order: e.g. `repr(i8, C)` may become `repr(C, i8)`.
/// Multiple repr attributes on the same item may be combined into an equivalent single attr.
pub attrs: Vec<Attribute>,
/// Information about the item’s deprecation, if present.
pub deprecation: Option<Deprecation>,
/// The type-specific fields describing this item.
pub inner: ItemEnum,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
/// An attribute, e.g. `#[repr(C)]`
///
/// This doesn't include:
/// - `#[doc = "Doc Comment"]` or `/// Doc comment`. These are in [`Item::docs`] instead.
/// - `#[deprecated]`. These are in [`Item::deprecation`] instead.
pub enum Attribute {
/// `#[non_exhaustive]`
NonExhaustive,
/// `#[must_use]`
MustUse { reason: Option<String> },
/// `#[macro_export]`
MacroExport,
/// `#[export_name = "name"]`
ExportName(String),
/// `#[link_section = "name"]`
LinkSection(String),
/// `#[automatically_derived]`
AutomaticallyDerived,
/// `#[repr]`
Repr(AttributeRepr),
/// `#[no_mangle]`
NoMangle,
/// #[target_feature(enable = "feature1", enable = "feature2")]
TargetFeature { enable: Vec<String> },
/// Something else.
///
/// Things here are explicitly *not* covered by the [`FORMAT_VERSION`]
/// constant, and may change without bumping the format version.
///
/// As an implementation detail, this is currently either:
/// 1. A HIR debug printing, like `"#[attr = Optimize(Speed)]"`
/// 2. The attribute as it appears in source form, like
/// `"#[optimize(speed)]"`.
Other(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
/// The contents of a `#[repr(...)]` attribute.
///
/// Used in [`Attribute::Repr`].
pub struct AttributeRepr {
/// The representation, e.g. `#[repr(C)]`, `#[repr(transparent)]`
pub kind: ReprKind,
/// Alignment in bytes, if explicitly specified by `#[repr(align(...)]`.
pub align: Option<u64>,
/// Alignment in bytes, if explicitly specified by `#[repr(packed(...)]]`.
pub packed: Option<u64>,
/// The integer type for an enum descriminant, if explicitly specified.
///
/// e.g. `"i32"`, for `#[repr(C, i32)]`
pub int: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
/// The kind of `#[repr]`.
///
/// See [AttributeRepr::kind]`.
pub enum ReprKind {
/// `#[repr(Rust)]`
///
/// Also the default.
Rust,
/// `#[repr(C)]`
C,
/// `#[repr(transparent)]
Transparent,
/// `#[repr(simd)]`
Simd,
}
/// A range of source code.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Span {
/// The path to the source file for this span relative to the path `rustdoc` was invoked with.
#[cfg_attr(feature = "rkyv_0_8", rkyv(with = rkyv::with::AsString))]
pub filename: PathBuf,
/// One indexed Line and Column of the first character of the `Span`.
pub begin: (usize, usize),
/// One indexed Line and Column of the last character of the `Span`.
pub end: (usize, usize),
}
/// Information about the deprecation of an [`Item`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Deprecation {
/// Usually a version number when this [`Item`] first became deprecated.
pub since: Option<String>,
/// The reason for deprecation and/or what alternatives to use.
pub note: Option<String>,
}
/// Visibility of an [`Item`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
pub enum Visibility {
/// Explicitly public visibility set with `pub`.
Public,
/// For the most part items are private by default. The exceptions are associated items of
/// public traits and variants of public enums.
Default,
/// Explicitly crate-wide visibility set with `pub(crate)`
Crate,
/// For `pub(in path)` visibility.
Restricted {
/// ID of the module to which this visibility restricts items.
parent: Id,
/// The path with which [`parent`] was referenced
/// (like `super::super` or `crate::foo::bar`).
///
/// [`parent`]: Visibility::Restricted::parent
path: String,
},
}
/// Dynamic trait object type (`dyn Trait`).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct DynTrait {
/// All the traits implemented. One of them is the vtable, and the rest must be auto traits.
pub traits: Vec<PolyTrait>,
/// The lifetime of the whole dyn object
/// ```text
/// dyn Debug + 'static
/// ^^^^^^^
/// |
/// this part
/// ```
pub lifetime: Option<String>,
}
/// A trait and potential HRTBs
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct PolyTrait {
/// The path to the trait.
#[serde(rename = "trait")]
pub trait_: Path,
/// Used for Higher-Rank Trait Bounds (HRTBs)
/// ```text
/// dyn for<'a> Fn() -> &'a i32"
/// ^^^^^^^
/// ```
pub generic_params: Vec<GenericParamDef>,
}
/// A set of generic arguments provided to a path segment, e.g.
///
/// ```text
/// std::option::Option<u32>
/// ^^^^^
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
__S: rkyv::ser::Writer + rkyv::ser::Allocator,
__S::Error: rkyv::rancor::Source,
)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
__D::Error: rkyv::rancor::Source,
)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
__C: rkyv::validation::ArchiveContext,
))))]
#[serde(rename_all = "snake_case")]
pub enum GenericArgs {
/// `<'a, 32, B: Copy, C = u32>`
AngleBracketed {
/// The list of each argument on this type.
/// ```text
/// <'a, 32, B: Copy, C = u32>
/// ^^^^^^
/// ```
args: Vec<GenericArg>,
/// Associated type or constant bindings (e.g. `Item=i32` or `Item: Clone`) for this type.
constraints: Vec<AssocItemConstraint>,
},
/// `Fn(A, B) -> C`
Parenthesized {
/// The input types, enclosed in parentheses.
#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
inputs: Vec<Type>,
/// The output type provided after the `->`, if present.
#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
output: Option<Type>,
},
/// `T::method(..)`
ReturnTypeNotation,
}
/// One argument in a list of generic arguments to a path segment.
///
/// Part of [`GenericArgs`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
pub enum GenericArg {
/// A lifetime argument.
/// ```text
/// std::borrow::Cow<'static, str>
/// ^^^^^^^
/// ```
Lifetime(String),
/// A type argument.
/// ```text
/// std::borrow::Cow<'static, str>
/// ^^^
/// ```
Type(Type),
/// A constant as a generic argument.
/// ```text
/// core::array::IntoIter<u32, { 640 * 1024 }>
/// ^^^^^^^^^^^^^^
/// ```
Const(Constant),
/// A generic argument that's explicitly set to be inferred.
/// ```text
/// std::vec::Vec::<_>
/// ^
/// ```
Infer,
}
/// A constant.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Constant {
/// The stringified expression of this constant. Note that its mapping to the original
/// source code is unstable and it's not guaranteed that it'll match the source code.
pub expr: String,
/// The value of the evaluated expression for this constant, which is only computed for numeric
/// types.
pub value: Option<String>,
/// Whether this constant is a bool, numeric, string, or char literal.
pub is_literal: bool,
}
/// Describes a bound applied to an associated type/constant.
///
/// Example:
/// ```text
/// IntoIterator<Item = u32, IntoIter: Clone>
/// ^^^^^^^^^^ ^^^^^^^^^^^^^^^
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
__S: rkyv::ser::Writer + rkyv::ser::Allocator,
__S::Error: rkyv::rancor::Source,
)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
__D::Error: rkyv::rancor::Source,
)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
__C: rkyv::validation::ArchiveContext,
<__C as rkyv::rancor::Fallible>::Error: rkyv::rancor::Source,
))))]
pub struct AssocItemConstraint {
/// The name of the associated type/constant.
pub name: String,
/// Arguments provided to the associated type/constant.
#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
pub args: Option<Box<GenericArgs>>,
/// The kind of bound applied to the associated type/constant.
pub binding: AssocItemConstraintKind,
}
/// The way in which an associate type/constant is bound.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
pub enum AssocItemConstraintKind {
/// The required value/type is specified exactly. e.g.
/// ```text
/// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
/// ^^^^^^^^^^
/// ```
Equality(Term),
/// The type is required to satisfy a set of bounds.
/// ```text
/// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// ```
Constraint(Vec<GenericBound>),
}
/// An opaque identifier for an item.
///
/// It can be used to lookup in [`Crate::index`] or [`Crate::paths`] to resolve it
/// to an [`Item`].
///
/// Id's are only valid within a single JSON blob. They cannot be used to
/// resolve references between the JSON output's for different crates.
///
/// Rustdoc makes no guarantees about the inner value of Id's. Applications
/// should treat them as opaque keys to lookup items, and avoid attempting
/// to parse them, or otherwise depend on any implementation details.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)))]
// FIXME(aDotInTheVoid): Consider making this non-public in rustdoc-types.
pub struct Id(pub u32);
/// The fundamental kind of an item. Unlike [`ItemEnum`], this does not carry any additional info.
///
/// Part of [`ItemSummary`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(compare(PartialEq)))]
#[serde(rename_all = "snake_case")]
pub enum ItemKind {
/// A module declaration, e.g. `mod foo;` or `mod foo {}`
Module,
/// A crate imported via the `extern crate` syntax.
ExternCrate,
/// An import of 1 or more items into scope, using the `use` keyword.
Use,
/// A `struct` declaration.
Struct,
/// A field of a struct.
StructField,
/// A `union` declaration.
Union,
/// An `enum` declaration.
Enum,
/// A variant of a enum.
Variant,
/// A function declaration, e.g. `fn f() {}`
Function,
/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
TypeAlias,
/// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
Constant,
/// A `trait` declaration.
Trait,
/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
///
/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
TraitAlias,
/// An `impl` block.
Impl,
/// A `static` declaration.
Static,
/// `type`s from an `extern` block.
///
/// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
ExternType,
/// A macro declaration.
///
/// Corresponds to either `ItemEnum::Macro(_)`
/// or `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Bang })`
Macro,
/// A procedural macro attribute.
///
/// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Attr })`
ProcAttribute,
/// A procedural macro usable in the `#[derive()]` attribute.
///
/// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Derive })`
ProcDerive,
/// An associated constant of a trait or a type.
AssocConst,
/// An associated type of a trait or a type.
AssocType,
/// A primitive type, e.g. `u32`.
///
/// [`Item`]s of this kind only come from the core library.
Primitive,
/// A keyword declaration.
///
/// [`Item`]s of this kind only come from the come library and exist solely
/// to carry documentation for the respective keywords.
Keyword,
/// An attribute declaration.
///
/// [`Item`]s of this kind only come from the core library and exist solely
/// to carry documentation for the respective builtin attributes.
Attribute,
}
/// Specific fields of an item.
///
/// Part of [`Item`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
pub enum ItemEnum {
/// A module declaration, e.g. `mod foo;` or `mod foo {}`
Module(Module),
/// A crate imported via the `extern crate` syntax.
ExternCrate {
/// The name of the imported crate.
name: String,
/// If the crate is renamed, this is its name in the crate.
rename: Option<String>,
},
/// An import of 1 or more items into scope, using the `use` keyword.
Use(Use),
/// A `union` declaration.
Union(Union),
/// A `struct` declaration.
Struct(Struct),
/// A field of a struct.
StructField(Type),
/// An `enum` declaration.
Enum(Enum),
/// A variant of a enum.
Variant(Variant),
/// A function declaration (including methods and other associated functions)
Function(Function),
/// A `trait` declaration.
Trait(Trait),
/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
///
/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
TraitAlias(TraitAlias),
/// An `impl` block.
Impl(Impl),
/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
TypeAlias(TypeAlias),
/// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
Constant {
/// The type of the constant.
#[serde(rename = "type")]
type_: Type,
/// The declared constant itself.
#[serde(rename = "const")]
const_: Constant,
},
/// A declaration of a `static`.
Static(Static),
/// `type`s from an `extern` block.
///
/// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
ExternType,
/// A macro_rules! declarative macro. Contains a single string with the source
/// representation of the macro with the patterns stripped.
Macro(String),
/// A procedural macro.
ProcMacro(ProcMacro),
/// A primitive type, e.g. `u32`.
///
/// [`Item`]s of this kind only come from the core library.
Primitive(Primitive),
/// An associated constant of a trait or a type.
AssocConst {
/// The type of the constant.
#[serde(rename = "type")]
type_: Type,
/// Inside a trait declaration, this is the default value for the associated constant,
/// if provided.
/// Inside an `impl` block, this is the value assigned to the associated constant,
/// and will always be present.
///
/// The representation is implementation-defined and not guaranteed to be representative of
/// either the resulting value or of the source code.
///
/// ```rust
/// const X: usize = 640 * 1024;
/// // ^^^^^^^^^^
/// ```
value: Option<String>,
},
/// An associated type of a trait or a type.
AssocType {
/// The generic parameters and where clauses on ahis associated type.
generics: Generics,
/// The bounds for this associated type. e.g.
/// ```rust
/// trait IntoIterator {
/// type Item;
/// type IntoIter: Iterator<Item = Self::Item>;
/// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// }
/// ```
bounds: Vec<GenericBound>,
/// Inside a trait declaration, this is the default for the associated type, if provided.
/// Inside an impl block, this is the type assigned to the associated type, and will always
/// be present.
///
/// ```rust
/// type X = usize;
/// // ^^^^^
/// ```
#[serde(rename = "type")]
type_: Option<Type>,
},
}
impl ItemEnum {
/// Get just the kind of this item, but with no further data.
///
/// ```rust
/// # use rustdoc_types::{ItemKind, ItemEnum};
/// let item = ItemEnum::ExternCrate { name: "libc".to_owned(), rename: None };
/// assert_eq!(item.item_kind(), ItemKind::ExternCrate);
/// ```
pub fn item_kind(&self) -> ItemKind {
match self {
ItemEnum::Module(_) => ItemKind::Module,
ItemEnum::ExternCrate { .. } => ItemKind::ExternCrate,
ItemEnum::Use(_) => ItemKind::Use,
ItemEnum::Union(_) => ItemKind::Union,
ItemEnum::Struct(_) => ItemKind::Struct,
ItemEnum::StructField(_) => ItemKind::StructField,
ItemEnum::Enum(_) => ItemKind::Enum,
ItemEnum::Variant(_) => ItemKind::Variant,
ItemEnum::Function(_) => ItemKind::Function,
ItemEnum::Trait(_) => ItemKind::Trait,
ItemEnum::TraitAlias(_) => ItemKind::TraitAlias,
ItemEnum::Impl(_) => ItemKind::Impl,
ItemEnum::TypeAlias(_) => ItemKind::TypeAlias,
ItemEnum::Constant { .. } => ItemKind::Constant,
ItemEnum::Static(_) => ItemKind::Static,
ItemEnum::ExternType => ItemKind::ExternType,
ItemEnum::Macro(_) => ItemKind::Macro,
ItemEnum::ProcMacro(pm) => match pm.kind {
MacroKind::Bang => ItemKind::Macro,
MacroKind::Attr => ItemKind::ProcAttribute,
MacroKind::Derive => ItemKind::ProcDerive,
},
ItemEnum::Primitive(_) => ItemKind::Primitive,
ItemEnum::AssocConst { .. } => ItemKind::AssocConst,
ItemEnum::AssocType { .. } => ItemKind::AssocType,
}
}
}
/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Module {
/// Whether this is the root item of a crate.
///
/// This item doesn't correspond to any construction in the source code and is generated by the
/// compiler.
pub is_crate: bool,
/// [`Item`]s declared inside this module.
pub items: Vec<Id>,
/// If `true`, this module is not part of the public API, but it contains
/// items that are re-exported as public API.
pub is_stripped: bool,
}
/// A `union`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Union {
/// The generic parameters and where clauses on this union.
pub generics: Generics,
/// Whether any fields have been removed from the result, due to being private or hidden.
pub has_stripped_fields: bool,
/// The list of fields in the union.
///
/// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
pub fields: Vec<Id>,
/// All impls (both of traits and inherent) for this union.
///
/// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
pub impls: Vec<Id>,
}
/// A `struct`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Struct {
/// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
/// i.e. fields.
pub kind: StructKind,
/// The generic parameters and where clauses on this struct.
pub generics: Generics,
/// All impls (both of traits and inherent) for this struct.
/// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
pub impls: Vec<Id>,
}
/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
pub enum StructKind {
/// A struct with no fields and no parentheses.
///
/// ```rust
/// pub struct Unit;
/// ```
Unit,
/// A struct with unnamed fields.
///
/// All [`Id`]'s will point to [`ItemEnum::StructField`].
/// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
/// instead of being omitted, because order matters.
///
/// ```rust
/// pub struct TupleStruct(i32);
/// pub struct EmptyTupleStruct();
/// ```
Tuple(Vec<Option<Id>>),
/// A struct with named fields.
///
/// ```rust
/// pub struct PlainStruct { x: i32 }
/// pub struct EmptyPlainStruct {}
/// ```
Plain {
/// The list of fields in the struct.
///
/// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
fields: Vec<Id>,
/// Whether any fields have been removed from the result, due to being private or hidden.
has_stripped_fields: bool,
},
}
/// An `enum`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Enum {
/// Information about the type parameters and `where` clauses of the enum.
pub generics: Generics,
/// Whether any variants have been removed from the result, due to being private or hidden.
pub has_stripped_variants: bool,
/// The list of variants in the enum.
///
/// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
pub variants: Vec<Id>,
/// `impl`s for the enum.
pub impls: Vec<Id>,
}
/// A variant of an enum.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
pub struct Variant {
/// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
pub kind: VariantKind,
/// The discriminant, if explicitly specified.
pub discriminant: Option<Discriminant>,
}
/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
#[serde(rename_all = "snake_case")]
pub enum VariantKind {
/// A variant with no parentheses
///
/// ```rust
/// enum Demo {
/// PlainVariant,
/// PlainWithDiscriminant = 1,