rustdoc_types/lib.rs
1//! Rustdoc's JSON output interface
2//!
3//! These types are the public API exposed through the `--output-format json` flag. The [`Crate`]
4//! struct is the root of the JSON blob and all other items are contained within.
5//!
6//! # Feature Flags
7//!
8//! ## `rustc-hash`
9//!
10//! We expose a `rustc-hash` feature, disabled by default. This feature switches the
11//! [`std::collections::HashMap`] for [`rustc_hash::FxHashMap`] to improve the performance of said
12//! `HashMap` in specific situations.
13//!
14//! `cargo-semver-checks` for example, saw a [-3% improvement][1] when benchmarking using the
15//! `aws_sdk_ec2` JSON output (~500MB of JSON). As always, we recommend measuring the impact before
16//! turning this feature on, as [`FxHashMap`][2] only concerns itself with hash speed, and may
17//! increase the number of collisions.
18//!
19//! ## `rkyv_0_8`
20//!
21//! We expose a `rkyv_0_8` feature, disabled by default. When enabled, it derives `rkyv`'s
22//! [`Archive`][3], [`Serialize`][4] and [`Deserialize`][5] traits for all types in this crate.
23//! Furthermore, it exposes the corresponding `Archived*` types (e.g. `ArchivedId` for [`Id`]).
24//!
25//! `rkyv` lets you works with JSON output without paying the deserialization cost _upfront_,
26//! thanks to [zero-copy deserialization][6].
27//! You can perform various types of analyses on the `Archived*` version of the relevant types,
28//! incurring the full deserialization cost only for the subset of items you actually need.
29//!
30//! [1]: https://rust-lang.zulipchat.com/#narrow/channel/266220-t-rustdoc/topic/rustc-hash.20and.20performance.20of.20rustdoc-types/near/474855731
31//! [2]: https://crates.io/crates/rustc-hash
32//! [3]: https://docs.rs/rkyv/0.8.15/rkyv/trait.Archive.html
33//! [4]: https://docs.rs/rkyv/0.8.15/rkyv/trait.Serialize.html
34//! [5]: https://docs.rs/rkyv/0.8.15/rkyv/trait.Deserialize.html
35//! [6]: https://rkyv.org/zero-copy-deserialization.html
36
37// # On `rkyv` Derives
38//
39// In most cases, it's enough to add `#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]`
40// on top of a type to derive the relevant `rkyv` traits.
41//
42// There are a few exceptions, though, where more complex macro options are required.
43// The following sections break down the patterns that are showcased by `rkyv'`s
44// [JSON schema example](https://github.com/rkyv/rkyv/blob/985b0230a0b9cb9fce4a4ee9facb6af148e27c8e/rkyv/examples/json_like_schema.rs).
45//
46// ## Recursive Types
47//
48// Let's look at the `Type` enum as an example. It stores a `Box<Type>` in its `Slice` variant.
49// A "vanilla" `rkyv` annotation will cause an overflow in the compiler when
50// building the crate, since the bounds generated by the macro will be self-referential and thus
51// trap the compiler into a never-ending loop.
52//
53// To prevent this issue, `#[rkyv(omit_bounds)]` must be added to the relevant field.
54//
55// ## Co-Recursive Types
56//
57// The same problem occurs if a type is co-recursive—i.e. it doesn't _directly_ store a pointer
58// to another instance of the same type, but one of its fields does, transitively.
59//
60// For example, let's look at `Path`:
61//
62// - `Path` has a field of type `Option<Box<GenericArgs>>`
63// - One of the variants in `GenericArgs` has a field of type `Vec<GenericArg>`
64// - One of the variants of `GenericArg` has a field of type `Type`
65// - `Type::ResolvedPath` stores a `Path` instance
66//
67// The same logic of the recursive case applies here: we must use `#[rkyv(omit_bounds)]` to break the cycle.
68//
69// ## Additional Bounds
70//
71// Whenever `#[rkyv(omit_bounds)]` is added to a field or variant, `rkyv` omits _all_ traits bounds for that
72// field in the generated impl. This may result in compilation errors due to insufficient bounds in the
73// generated code.
74//
75// To add _some_ bounds back, `rkyv` exposes four knobs:
76//
77// - `#[rkyv(archive_bounds(..))]` to add predicates to all generated impls
78// - `#[rkyv(serialize_bounds(..))]` to add predicates to just the `Serialize` impl
79// - `#[rkyv(deserialize_bounds(..))]` to add predicates to just the `Deserialize` impl
80// - `#[rkyv(bytecheck(bounds(..)))]` to add predicates to just the `CheckBytes` impl
81//
82// In particular, we use the following annotations in this crate:
83//
84// - `serialize_bounds(__S: rkyv::ser::Writer + rkyv::ser::Allocator, __S::Error: rkyv::rancor::Source)` for serializing
85// variable-length types like `Vec<T>`. `rkyv`'s zero-copy format requires the serializer to be able
86// to write bytes (`Writer`) and allocate scratch space (`Allocator`) for these types
87// ([`rkyv`'s `Vec` impl bounds](https://docs.rs/rkyv/0.8.15/rkyv/trait.Serialize.html#impl-Serialize%3CS%3E-for-Vec%3CT%3E)).
88// The `Error: Source` bound lets error types compose.
89// - `deserialize_bounds(__D::Error: rkyv::rancor::Source)` so that errors from deserializing fields behind
90// `omit_bounds` (e.g. `Box<T>`, `Vec<T>`) can compose via the `Source` trait.
91// - `bytecheck(bounds(__C: rkyv::validation::ArchiveContext, __C::Error: rkyv::rancor::Source))` for validating
92// archived data. Checking that bytes represent a valid archived value requires an `ArchiveContext` that tracks
93// validation state (e.g. subtree ranges, to prevent overlapping/out-of-bounds archived data).
94
95#[cfg(not(feature = "rustc-hash"))]
96use std::collections::HashMap;
97use std::path::PathBuf;
98
99#[cfg(feature = "rustc-hash")]
100use rustc_hash::FxHashMap as HashMap;
101use serde_derive::{Deserialize, Serialize};
102
103
104/// The version of JSON output that this crate represents.
105///
106/// This integer is incremented with every breaking change to the API,
107/// and is returned along with the JSON blob as [`Crate::format_version`].
108/// Consuming code should assert that this value matches the format version(s) that it supports.
109//
110// WARNING: When you update `FORMAT_VERSION`, please also update the "Latest feature" line with a
111// description of the change. This minimizes the risk of two concurrent PRs changing
112// `FORMAT_VERSION` from N to N+1 and git merging them without conflicts; the "Latest feature" line
113// will instead cause conflicts. See #94591 for more. (This paragraph and the "Latest feature" line
114// are deliberately not in a doc comment, because they need not be in public docs.)
115//
116// Latest feature: Add `Item::const_stability`.
117pub const FORMAT_VERSION: u32 = 59;
118
119/// The root of the emitted JSON blob.
120///
121/// It contains all type/documentation information
122/// about the language items in the local crate, as well as info about external items to allow
123/// tools to find or link to them.
124#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
125#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
126#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
127pub struct Crate {
128 /// The id of the root [`Module`] item of the local crate.
129 pub root: Id,
130 /// The version string given to `--crate-version`, if any.
131 pub crate_version: Option<String>,
132 /// Whether or not the output includes private items.
133 pub includes_private: bool,
134 /// A collection of all items in the local crate as well as some external traits and their
135 /// items that are referenced locally.
136 pub index: HashMap<Id, Item>,
137 /// Maps IDs to fully qualified paths and other info helpful for generating links.
138 pub paths: HashMap<Id, ItemSummary>,
139 /// Maps `crate_id` of items to a crate name and html_root_url if it exists.
140 pub external_crates: HashMap<u32, ExternalCrate>,
141 /// Information about the target for which this documentation was generated
142 pub target: Target,
143 /// A single version number to be used in the future when making backwards incompatible changes
144 /// to the JSON output.
145 pub format_version: u32,
146}
147
148/// Information about a target
149#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
150#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
151#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
152pub struct Target {
153 /// The target triple for which this documentation was generated
154 pub triple: String,
155 /// A list of features valid for use in `#[target_feature]` attributes
156 /// for the target where this rustdoc JSON was generated.
157 pub target_features: Vec<TargetFeature>,
158}
159
160/// Information about a target feature.
161///
162/// Rust target features are used to influence code generation, especially around selecting
163/// instructions which are not universally supported by the target architecture.
164///
165/// Target features are commonly enabled by the [`#[target_feature]` attribute][1] to influence code
166/// generation for a particular function, and less commonly enabled by compiler options like
167/// `-Ctarget-feature` or `-Ctarget-cpu`. Targets themselves automatically enable certain target
168/// features by default, for example because the target's ABI specification requires saving specific
169/// registers which only exist in an architectural extension.
170///
171/// Target features can imply other target features: for example, x86-64 `avx2` implies `avx`, and
172/// aarch64 `sve2` implies `sve`, since both of these architectural extensions depend on their
173/// predecessors.
174///
175/// Target features can be probed at compile time by [`#[cfg(target_feature)]`][2] or `cfg!(…)`
176/// conditional compilation to determine whether a target feature is enabled in a particular
177/// context.
178///
179/// [1]: https://doc.rust-lang.org/stable/reference/attributes/codegen.html#the-target_feature-attribute
180/// [2]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature
181#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
182#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
183#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
184pub struct TargetFeature {
185 /// The name of this target feature.
186 pub name: String,
187 /// Other target features which are implied by this target feature, if any.
188 pub implies_features: Vec<String>,
189 /// If this target feature is unstable, the name of the associated language feature gate.
190 pub unstable_feature_gate: Option<String>,
191 /// Whether this feature is globally enabled for this compilation session.
192 ///
193 /// Target features can be globally enabled implicitly as a result of the target's definition.
194 /// For example, x86-64 hardware floating point ABIs require saving x87 and SSE2 registers,
195 /// which in turn requires globally enabling the `x87` and `sse2` target features so that the
196 /// generated machine code conforms to the target's ABI.
197 ///
198 /// Target features can also be globally enabled explicitly as a result of compiler flags like
199 /// [`-Ctarget-feature`][1] or [`-Ctarget-cpu`][2].
200 ///
201 /// [1]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-feature
202 /// [2]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-cpu
203 pub globally_enabled: bool,
204}
205
206/// Metadata of a crate, either the same crate on which `rustdoc` was invoked, or its dependency.
207#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
208#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
209#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
210pub struct ExternalCrate {
211 /// The name of the crate.
212 ///
213 /// Note: This is the [*crate* name][crate-name], which may not be the same as the
214 /// [*package* name][package-name]. For example, for <https://crates.io/crates/regex-syntax>,
215 /// this field will be `regex_syntax` (which uses an `_`, not a `-`).
216 ///
217 /// [crate-name]: https://doc.rust-lang.org/stable/cargo/reference/cargo-targets.html#the-name-field
218 /// [package-name]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-name-field
219 pub name: String,
220 /// The root URL at which the crate's documentation lives.
221 pub html_root_url: Option<String>,
222
223 /// A path from where this crate was loaded.
224 ///
225 /// This will typically be a `.rlib` or `.rmeta`. It can be used to determine which crate
226 /// this was in terms of whatever build-system invoked rustc.
227 #[cfg_attr(feature = "rkyv_0_8", rkyv(with = rkyv::with::AsString))]
228 pub path: PathBuf,
229}
230
231/// Information about an external (not defined in the local crate) [`Item`].
232///
233/// For external items, you don't get the same level of
234/// information. This struct should contain enough to generate a link/reference to the item in
235/// question, or can be used by a tool that takes the json output of multiple crates to find
236/// the actual item definition with all the relevant info.
237#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
238#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
239#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
240pub struct ItemSummary {
241 /// Can be used to look up the name and html_root_url of the crate this item came from in the
242 /// `external_crates` map.
243 pub crate_id: u32,
244 /// The list of path components for the fully qualified path of this item (e.g.
245 /// `["std", "io", "lazy", "Lazy"]` for `std::io::lazy::Lazy`).
246 ///
247 /// Note that items can appear in multiple paths, and the one chosen is implementation
248 /// defined. Currently, this is the full path to where the item was defined. Eg
249 /// [`String`] is currently `["alloc", "string", "String"]` and [`HashMap`][`std::collections::HashMap`]
250 /// is `["std", "collections", "hash", "map", "HashMap"]`, but this is subject to change.
251 pub path: Vec<String>,
252 /// Whether this item is a struct, trait, macro, etc.
253 pub kind: ItemKind,
254}
255
256/// Anything that can hold documentation - modules, structs, enums, functions, traits, etc.
257///
258/// The `Item` data type holds fields that can apply to any of these,
259/// and leaves kind-specific details (like function args or enum variants) to the `inner` field.
260#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
261#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
262#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
263pub struct Item {
264 /// The unique identifier of this item. Can be used to find this item in various mappings.
265 pub id: Id,
266 /// This can be used as a key to the `external_crates` map of [`Crate`] to see which crate
267 /// this item came from.
268 pub crate_id: u32,
269 /// Some items such as impls don't have names.
270 pub name: Option<String>,
271 /// The source location of this item (absent if it came from a macro expansion or inline
272 /// assembly).
273 pub span: Option<Span>,
274 /// By default all documented items are public, but you can tell rustdoc to output private items
275 /// so this field is needed to differentiate.
276 pub visibility: Visibility,
277 /// The full markdown docstring of this item. Absent if there is no documentation at all,
278 /// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
279 pub docs: Option<String>,
280 /// 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
281 pub links: HashMap<String, Id>,
282 /// Attributes on this item.
283 ///
284 /// Does not include:
285 /// - `#[doc = "Doc Comment"]` or `/// Doc comment`: see [`Self::docs`] instead.
286 /// - `#[deprecated]` attributes: see the [`Self::deprecation`] field instead.
287 /// - `#[stable]` and `#[unstable]` attributes: see the [`Self::stability`] field instead.
288 /// - `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes:
289 /// see the [`Self::const_stability`] field instead.
290 ///
291 /// Attributes appear in pretty-printed Rust form, regardless of their formatting
292 /// in the original source code. For example:
293 /// - `#[non_exhaustive]` and `#[must_use]` are represented as themselves.
294 /// - `#[no_mangle]` and `#[export_name]` are also represented as themselves.
295 /// - `#[repr(C)]` and other reprs also appear as themselves,
296 /// though potentially with a different order: e.g. `repr(i8, C)` may become `repr(C, i8)`.
297 /// Multiple repr attributes on the same item may be combined into an equivalent single attr.
298 pub attrs: Vec<Attribute>,
299 /// Information about the item’s deprecation, if present.
300 pub deprecation: Option<Deprecation>,
301
302 /// Stability information for this item, if any.
303 ///
304 /// This describes whether the item itself is stable or unstable, as noted by a `#[stable]` or
305 /// `#[unstable]` attribute. It does not capture const stability, default-body stability, etc.
306 ///
307 /// Whether a path to an item is stable depends on the stability of containing modules
308 /// or re-exports along that path. For example, a stable item can be reachable through both an
309 /// unstable module and a stable re-export.
310 ///
311 /// For items whose inner kind is [`ItemEnum::Use`], this is the stability of the import itself,
312 /// not the item being imported. This allows users to determine the stability of paths
313 /// that involve re-exports.
314 ///
315 /// Associated items can inherit instability from their enclosing unstable trait or impl.
316 /// Unannotated associated items in stable traits or impls may have no separate stability value.
317 ///
318 /// Currently, Rust's `#[stable]` and `#[unstable]` attributes are themselves not stable.
319 /// As a result, this field is primarily populated for standard-library items;
320 /// most ordinary third-party crates usually have no data here.
321 pub stability: Option<Box<Stability>>,
322
323 /// Stability information for using this item in const contexts, if any.
324 ///
325 /// This is separate from [`Self::stability`]. An item can be stable as regular API while its
326 /// const use is unstable. An unstable item may have no separate const-stability value here.
327 ///
328 /// This field is only populated for item kinds whose const behavior can have separate
329 /// stability information, such as const functions, const traits, const trait impls,
330 /// and associated items whose const behavior is controlled by a const trait or const impl.
331 pub const_stability: Option<Box<Stability>>,
332
333 /// The type-specific fields describing this item.
334 pub inner: ItemEnum,
335}
336
337/// Stability information for an item.
338///
339/// In [`Item::stability`], this refers to regular item stability: whether the item is
340/// stable or unstable as represented by the `#[stable]` or `#[unstable]` attributes.
341/// In [`Item::const_stability`], this refers to using the item in const contexts,
342/// as represented by `#[rustc_const_stable]` or `#[rustc_const_unstable]`.
343#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
344#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
345#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
346pub struct Stability {
347 /// The feature associated with this stability record.
348 ///
349 /// For unstable items, this is the feature gate associated with the item.
350 /// For stable items, this is the historical label recorded when the item was stabilized.
351 pub feature: String,
352
353 #[serde(flatten)]
354 pub level: StabilityLevel,
355}
356
357#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
358#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
359#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
360#[serde(tag = "level", rename_all = "snake_case")]
361pub enum StabilityLevel {
362 Stable {
363 /// The Rust version in which this item became stable, if available.
364 since: Option<String>,
365 },
366 Unstable,
367}
368
369#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
370#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
371#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
372#[serde(rename_all = "snake_case")]
373/// An attribute, e.g. `#[repr(C)]`
374///
375/// This doesn't include:
376/// - `#[doc = "Doc Comment"]` or `/// Doc comment`. These are in [`Item::docs`] instead.
377/// - `#[deprecated]`. These are in [`Item::deprecation`] instead.
378/// - `#[stable]` and `#[unstable]`. These are in [`Item::stability`] instead.
379/// - `#[rustc_const_stable]` and `#[rustc_const_unstable]`. These are in
380/// [`Item::const_stability`] instead.
381pub enum Attribute {
382 /// `#[non_exhaustive]`
383 NonExhaustive,
384
385 /// `#[must_use]`
386 MustUse { reason: Option<String> },
387
388 /// `#[macro_export]`
389 MacroExport,
390
391 /// `#[export_name = "name"]`
392 ExportName(String),
393
394 /// `#[link_section = "name"]`
395 LinkSection(String),
396
397 /// `#[automatically_derived]`
398 AutomaticallyDerived,
399
400 /// `#[repr]`
401 Repr(AttributeRepr),
402
403 /// `#[no_mangle]`
404 NoMangle,
405
406 /// #[target_feature(enable = "feature1", enable = "feature2")]
407 TargetFeature { enable: Vec<String> },
408
409 /// Something else.
410 ///
411 /// Things here are explicitly *not* covered by the [`FORMAT_VERSION`]
412 /// constant, and may change without bumping the format version.
413 ///
414 /// As an implementation detail, this is currently either:
415 /// 1. A HIR debug printing, like `"#[attr = Optimize(Speed)]"`
416 /// 2. The attribute as it appears in source form, like
417 /// `"#[optimize(speed)]"`.
418 Other(String),
419}
420
421#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
422#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
423#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
424/// The contents of a `#[repr(...)]` attribute.
425///
426/// Used in [`Attribute::Repr`].
427pub struct AttributeRepr {
428 /// The representation, e.g. `#[repr(C)]`, `#[repr(transparent)]`
429 pub kind: ReprKind,
430
431 /// Alignment in bytes, if explicitly specified by `#[repr(align(...)]`.
432 pub align: Option<u64>,
433 /// Alignment in bytes, if explicitly specified by `#[repr(packed(...)]]`.
434 pub packed: Option<u64>,
435
436 /// The integer type for an enum descriminant, if explicitly specified.
437 ///
438 /// e.g. `"i32"`, for `#[repr(C, i32)]`
439 pub int: Option<String>,
440}
441
442#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
443#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
444#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
445#[serde(rename_all = "snake_case")]
446/// The kind of `#[repr]`.
447///
448/// See [AttributeRepr::kind]`.
449pub enum ReprKind {
450 /// `#[repr(Rust)]`
451 ///
452 /// Also the default.
453 Rust,
454 /// `#[repr(C)]`
455 C,
456 /// `#[repr(transparent)]
457 Transparent,
458 /// `#[repr(simd)]`
459 Simd,
460}
461
462/// A range of source code.
463#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
464#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
465#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
466pub struct Span {
467 /// The path to the source file for this span relative to the path `rustdoc` was invoked with.
468 #[cfg_attr(feature = "rkyv_0_8", rkyv(with = rkyv::with::AsString))]
469 pub filename: PathBuf,
470 /// One indexed Line and Column of the first character of the `Span`.
471 pub begin: (usize, usize),
472 /// One indexed Line and Column of the last character of the `Span`.
473 pub end: (usize, usize),
474}
475
476/// Information about the deprecation of an [`Item`].
477#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
478#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
479#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
480pub struct Deprecation {
481 /// Usually a version number when this [`Item`] first became deprecated.
482 pub since: Option<String>,
483 /// The reason for deprecation and/or what alternatives to use.
484 pub note: Option<String>,
485}
486
487/// Visibility of an [`Item`].
488#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
489#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
490#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
491#[serde(rename_all = "snake_case")]
492pub enum Visibility {
493 /// Explicitly public visibility set with `pub`.
494 Public,
495 /// For the most part items are private by default. The exceptions are associated items of
496 /// public traits and variants of public enums.
497 Default,
498 /// Explicitly crate-wide visibility set with `pub(crate)`
499 Crate,
500 /// For `pub(in path)` visibility.
501 Restricted {
502 /// ID of the module to which this visibility restricts items.
503 parent: Id,
504 /// The path with which [`parent`] was referenced
505 /// (like `super::super` or `crate::foo::bar`).
506 ///
507 /// [`parent`]: Visibility::Restricted::parent
508 path: String,
509 },
510}
511
512/// Dynamic trait object type (`dyn Trait`).
513#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
514#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
515#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
516pub struct DynTrait {
517 /// All the traits implemented. One of them is the vtable, and the rest must be auto traits.
518 pub traits: Vec<PolyTrait>,
519 /// The lifetime of the whole dyn object
520 /// ```text
521 /// dyn Debug + 'static
522 /// ^^^^^^^
523 /// |
524 /// this part
525 /// ```
526 pub lifetime: Option<String>,
527}
528
529/// A trait and potential HRTBs
530#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
531#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
532#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
533pub struct PolyTrait {
534 /// The path to the trait.
535 #[serde(rename = "trait")]
536 pub trait_: Path,
537 /// Used for Higher-Rank Trait Bounds (HRTBs)
538 /// ```text
539 /// dyn for<'a> Fn() -> &'a i32"
540 /// ^^^^^^^
541 /// ```
542 pub generic_params: Vec<GenericParamDef>,
543}
544
545/// A set of generic arguments provided to a path segment, e.g.
546///
547/// ```text
548/// std::option::Option<u32>
549/// ^^^^^
550/// ```
551#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
552#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
553#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
554#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
555 __S: rkyv::ser::Writer + rkyv::ser::Allocator,
556 __S::Error: rkyv::rancor::Source,
557)))]
558#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
559 __D::Error: rkyv::rancor::Source,
560)))]
561#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
562 __C: rkyv::validation::ArchiveContext,
563))))]
564#[serde(rename_all = "snake_case")]
565pub enum GenericArgs {
566 /// `<'a, 32, B: Copy, C = u32>`
567 AngleBracketed {
568 /// The list of each argument on this type.
569 /// ```text
570 /// <'a, 32, B: Copy, C = u32>
571 /// ^^^^^^
572 /// ```
573 args: Vec<GenericArg>,
574 /// Associated type or constant bindings (e.g. `Item=i32` or `Item: Clone`) for this type.
575 constraints: Vec<AssocItemConstraint>,
576 },
577 /// `Fn(A, B) -> C`
578 Parenthesized {
579 /// The input types, enclosed in parentheses.
580 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
581 inputs: Vec<Type>,
582 /// The output type provided after the `->`, if present.
583 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
584 output: Option<Type>,
585 },
586 /// `T::method(..)`
587 ReturnTypeNotation,
588}
589
590/// One argument in a list of generic arguments to a path segment.
591///
592/// Part of [`GenericArgs`].
593#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
594#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
595#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
596#[serde(rename_all = "snake_case")]
597pub enum GenericArg {
598 /// A lifetime argument.
599 /// ```text
600 /// std::borrow::Cow<'static, str>
601 /// ^^^^^^^
602 /// ```
603 Lifetime(String),
604 /// A type argument.
605 /// ```text
606 /// std::borrow::Cow<'static, str>
607 /// ^^^
608 /// ```
609 Type(Type),
610 /// A constant as a generic argument.
611 /// ```text
612 /// core::array::IntoIter<u32, { 640 * 1024 }>
613 /// ^^^^^^^^^^^^^^
614 /// ```
615 Const(Constant),
616 /// A generic argument that's explicitly set to be inferred.
617 /// ```text
618 /// std::vec::Vec::<_>
619 /// ^
620 /// ```
621 Infer,
622}
623
624/// A constant.
625#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
626#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
627#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
628pub struct Constant {
629 /// The stringified expression of this constant. Note that its mapping to the original
630 /// source code is unstable and it's not guaranteed that it'll match the source code.
631 pub expr: String,
632 /// The value of the evaluated expression for this constant, which is only computed for numeric
633 /// types.
634 pub value: Option<String>,
635 /// Whether this constant is a bool, numeric, string, or char literal.
636 pub is_literal: bool,
637}
638
639/// Describes a bound applied to an associated type/constant.
640///
641/// Example:
642/// ```text
643/// IntoIterator<Item = u32, IntoIter: Clone>
644/// ^^^^^^^^^^ ^^^^^^^^^^^^^^^
645/// ```
646#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
647#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
648#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
649#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
650 __S: rkyv::ser::Writer + rkyv::ser::Allocator,
651 __S::Error: rkyv::rancor::Source,
652)))]
653#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
654 __D::Error: rkyv::rancor::Source,
655)))]
656#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
657 __C: rkyv::validation::ArchiveContext,
658 <__C as rkyv::rancor::Fallible>::Error: rkyv::rancor::Source,
659))))]
660pub struct AssocItemConstraint {
661 /// The name of the associated type/constant.
662 pub name: String,
663 /// Arguments provided to the associated type/constant.
664 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
665 pub args: Option<Box<GenericArgs>>,
666 /// The kind of bound applied to the associated type/constant.
667 pub binding: AssocItemConstraintKind,
668}
669
670/// The way in which an associate type/constant is bound.
671#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
672#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
673#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
674#[serde(rename_all = "snake_case")]
675pub enum AssocItemConstraintKind {
676 /// The required value/type is specified exactly. e.g.
677 /// ```text
678 /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
679 /// ^^^^^^^^^^
680 /// ```
681 Equality(Term),
682 /// The type is required to satisfy a set of bounds.
683 /// ```text
684 /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
685 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
686 /// ```
687 Constraint(Vec<GenericBound>),
688}
689
690/// An opaque identifier for an item.
691///
692/// It can be used to lookup in [`Crate::index`] or [`Crate::paths`] to resolve it
693/// to an [`Item`].
694///
695/// Id's are only valid within a single JSON blob. They cannot be used to
696/// resolve references between the JSON output's for different crates.
697///
698/// Rustdoc makes no guarantees about the inner value of Id's. Applications
699/// should treat them as opaque keys to lookup items, and avoid attempting
700/// to parse them, or otherwise depend on any implementation details.
701#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
702#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
703#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)))]
704// FIXME(aDotInTheVoid): Consider making this non-public in rustdoc-types.
705pub struct Id(pub u32);
706
707/// The fundamental kind of an item. Unlike [`ItemEnum`], this does not carry any additional info.
708///
709/// Part of [`ItemSummary`].
710#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
711#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
712#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
713#[cfg_attr(feature = "rkyv_0_8", rkyv(compare(PartialEq)))]
714#[serde(rename_all = "snake_case")]
715pub enum ItemKind {
716 /// A module declaration, e.g. `mod foo;` or `mod foo {}`
717 Module,
718 /// A crate imported via the `extern crate` syntax.
719 ExternCrate,
720 /// An import of 1 or more items into scope, using the `use` keyword.
721 Use,
722 /// A `struct` declaration.
723 Struct,
724 /// A field of a struct.
725 StructField,
726 /// A `union` declaration.
727 Union,
728 /// An `enum` declaration.
729 Enum,
730 /// A variant of a enum.
731 Variant,
732 /// A function declaration, e.g. `fn f() {}`
733 Function,
734 /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
735 TypeAlias,
736 /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
737 Constant,
738 /// A `trait` declaration.
739 Trait,
740 /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
741 ///
742 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
743 TraitAlias,
744 /// An `impl` block.
745 Impl,
746 /// A `static` declaration.
747 Static,
748 /// `type`s from an `extern` block.
749 ///
750 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
751 ExternType,
752 /// A macro declaration.
753 ///
754 /// Corresponds to either `ItemEnum::Macro(_)`
755 /// or `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Bang })`
756 Macro,
757 /// A procedural macro attribute.
758 ///
759 /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Attr })`
760 ProcAttribute,
761 /// A procedural macro usable in the `#[derive()]` attribute.
762 ///
763 /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Derive })`
764 ProcDerive,
765 /// An associated constant of a trait or a type.
766 AssocConst,
767 /// An associated type of a trait or a type.
768 AssocType,
769 /// A primitive type, e.g. `u32`.
770 ///
771 /// [`Item`]s of this kind only come from the core library.
772 Primitive,
773 /// A keyword declaration.
774 ///
775 /// [`Item`]s of this kind only come from the come library and exist solely
776 /// to carry documentation for the respective keywords.
777 Keyword,
778 /// An attribute declaration.
779 ///
780 /// [`Item`]s of this kind only come from the core library and exist solely
781 /// to carry documentation for the respective builtin attributes.
782 Attribute,
783}
784
785/// Specific fields of an item.
786///
787/// Part of [`Item`].
788#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
789#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
790#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
791#[serde(rename_all = "snake_case")]
792pub enum ItemEnum {
793 /// A module declaration, e.g. `mod foo;` or `mod foo {}`
794 Module(Module),
795 /// A crate imported via the `extern crate` syntax.
796 ExternCrate {
797 /// The name of the imported crate.
798 name: String,
799 /// If the crate is renamed, this is its name in the crate.
800 rename: Option<String>,
801 },
802 /// An import of 1 or more items into scope, using the `use` keyword.
803 Use(Use),
804
805 /// A `union` declaration.
806 Union(Union),
807 /// A `struct` declaration.
808 Struct(Struct),
809 /// A field of a struct.
810 StructField(Type),
811 /// An `enum` declaration.
812 Enum(Enum),
813 /// A variant of a enum.
814 Variant(Variant),
815
816 /// A function declaration (including methods and other associated functions)
817 Function(Function),
818
819 /// A `trait` declaration.
820 Trait(Trait),
821 /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
822 ///
823 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
824 TraitAlias(TraitAlias),
825 /// An `impl` block.
826 Impl(Impl),
827
828 /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
829 TypeAlias(TypeAlias),
830 /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
831 Constant {
832 /// The type of the constant.
833 #[serde(rename = "type")]
834 type_: Type,
835 /// The declared constant itself.
836 #[serde(rename = "const")]
837 const_: Constant,
838 },
839
840 /// A declaration of a `static`.
841 Static(Static),
842
843 /// `type`s from an `extern` block.
844 ///
845 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
846 ExternType,
847
848 /// A macro_rules! declarative macro. Contains a single string with the source
849 /// representation of the macro with the patterns stripped.
850 Macro(String),
851 /// A procedural macro.
852 ProcMacro(ProcMacro),
853
854 /// A primitive type, e.g. `u32`.
855 ///
856 /// [`Item`]s of this kind only come from the core library.
857 Primitive(Primitive),
858
859 /// An associated constant of a trait or a type.
860 AssocConst {
861 /// The type of the constant.
862 #[serde(rename = "type")]
863 type_: Type,
864 /// Inside a trait declaration, this is the default value for the associated constant,
865 /// if provided.
866 /// Inside an `impl` block, this is the value assigned to the associated constant,
867 /// and will always be present.
868 ///
869 /// The representation is implementation-defined and not guaranteed to be representative of
870 /// either the resulting value or of the source code.
871 ///
872 /// ```rust
873 /// const X: usize = 640 * 1024;
874 /// // ^^^^^^^^^^
875 /// ```
876 value: Option<String>,
877 },
878 /// An associated type of a trait or a type.
879 AssocType {
880 /// The generic parameters and where clauses on ahis associated type.
881 generics: Generics,
882 /// The bounds for this associated type. e.g.
883 /// ```rust
884 /// trait IntoIterator {
885 /// type Item;
886 /// type IntoIter: Iterator<Item = Self::Item>;
887 /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
888 /// }
889 /// ```
890 bounds: Vec<GenericBound>,
891 /// Inside a trait declaration, this is the default for the associated type, if provided.
892 /// Inside an impl block, this is the type assigned to the associated type, and will always
893 /// be present.
894 ///
895 /// ```rust
896 /// type X = usize;
897 /// // ^^^^^
898 /// ```
899 #[serde(rename = "type")]
900 type_: Option<Type>,
901 },
902}
903
904impl ItemEnum {
905 /// Get just the kind of this item, but with no further data.
906 ///
907 /// ```rust
908 /// # use rustdoc_types::{ItemKind, ItemEnum};
909 /// let item = ItemEnum::ExternCrate { name: "libc".to_owned(), rename: None };
910 /// assert_eq!(item.item_kind(), ItemKind::ExternCrate);
911 /// ```
912 pub fn item_kind(&self) -> ItemKind {
913 match self {
914 ItemEnum::Module(_) => ItemKind::Module,
915 ItemEnum::ExternCrate { .. } => ItemKind::ExternCrate,
916 ItemEnum::Use(_) => ItemKind::Use,
917 ItemEnum::Union(_) => ItemKind::Union,
918 ItemEnum::Struct(_) => ItemKind::Struct,
919 ItemEnum::StructField(_) => ItemKind::StructField,
920 ItemEnum::Enum(_) => ItemKind::Enum,
921 ItemEnum::Variant(_) => ItemKind::Variant,
922 ItemEnum::Function(_) => ItemKind::Function,
923 ItemEnum::Trait(_) => ItemKind::Trait,
924 ItemEnum::TraitAlias(_) => ItemKind::TraitAlias,
925 ItemEnum::Impl(_) => ItemKind::Impl,
926 ItemEnum::TypeAlias(_) => ItemKind::TypeAlias,
927 ItemEnum::Constant { .. } => ItemKind::Constant,
928 ItemEnum::Static(_) => ItemKind::Static,
929 ItemEnum::ExternType => ItemKind::ExternType,
930 ItemEnum::Macro(_) => ItemKind::Macro,
931 ItemEnum::ProcMacro(pm) => match pm.kind {
932 MacroKind::Bang => ItemKind::Macro,
933 MacroKind::Attr => ItemKind::ProcAttribute,
934 MacroKind::Derive => ItemKind::ProcDerive,
935 },
936 ItemEnum::Primitive(_) => ItemKind::Primitive,
937 ItemEnum::AssocConst { .. } => ItemKind::AssocConst,
938 ItemEnum::AssocType { .. } => ItemKind::AssocType,
939 }
940 }
941}
942
943/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
944#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
945#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
946#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
947pub struct Module {
948 /// Whether this is the root item of a crate.
949 ///
950 /// This item doesn't correspond to any construction in the source code and is generated by the
951 /// compiler.
952 pub is_crate: bool,
953 /// [`Item`]s declared inside this module.
954 pub items: Vec<Id>,
955 /// If `true`, this module is not part of the public API, but it contains
956 /// items that are re-exported as public API.
957 pub is_stripped: bool,
958}
959
960/// A `union`.
961#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
962#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
963#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
964pub struct Union {
965 /// The generic parameters and where clauses on this union.
966 pub generics: Generics,
967 /// Whether any fields have been removed from the result, due to being private or hidden.
968 pub has_stripped_fields: bool,
969 /// The list of fields in the union.
970 ///
971 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
972 pub fields: Vec<Id>,
973 /// All impls (both of traits and inherent) for this union.
974 ///
975 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
976 pub impls: Vec<Id>,
977}
978
979/// A `struct`.
980#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
981#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
982#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
983pub struct Struct {
984 /// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
985 /// i.e. fields.
986 pub kind: StructKind,
987 /// The generic parameters and where clauses on this struct.
988 pub generics: Generics,
989 /// All impls (both of traits and inherent) for this struct.
990 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
991 pub impls: Vec<Id>,
992}
993
994/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
995#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
996#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
997#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
998#[serde(rename_all = "snake_case")]
999pub enum StructKind {
1000 /// A struct with no fields and no parentheses.
1001 ///
1002 /// ```rust
1003 /// pub struct Unit;
1004 /// ```
1005 Unit,
1006 /// A struct with unnamed fields.
1007 ///
1008 /// All [`Id`]'s will point to [`ItemEnum::StructField`].
1009 /// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
1010 /// instead of being omitted, because order matters.
1011 ///
1012 /// ```rust
1013 /// pub struct TupleStruct(i32);
1014 /// pub struct EmptyTupleStruct();
1015 /// ```
1016 Tuple(Vec<Option<Id>>),
1017 /// A struct with named fields.
1018 ///
1019 /// ```rust
1020 /// pub struct PlainStruct { x: i32 }
1021 /// pub struct EmptyPlainStruct {}
1022 /// ```
1023 Plain {
1024 /// The list of fields in the struct.
1025 ///
1026 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
1027 fields: Vec<Id>,
1028 /// Whether any fields have been removed from the result, due to being private or hidden.
1029 has_stripped_fields: bool,
1030 },
1031}
1032
1033/// An `enum`.
1034#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1035#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1036#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1037pub struct Enum {
1038 /// Information about the type parameters and `where` clauses of the enum.
1039 pub generics: Generics,
1040 /// Whether any variants have been removed from the result, due to being private or hidden.
1041 pub has_stripped_variants: bool,
1042 /// The list of variants in the enum.
1043 ///
1044 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
1045 pub variants: Vec<Id>,
1046 /// `impl`s for the enum.
1047 pub impls: Vec<Id>,
1048}
1049
1050/// A variant of an enum.
1051#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1052#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1053#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1054pub struct Variant {
1055 /// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
1056 pub kind: VariantKind,
1057 /// The discriminant, if explicitly specified.
1058 pub discriminant: Option<Discriminant>,
1059}
1060
1061/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
1062#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1063#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1064#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1065#[serde(rename_all = "snake_case")]
1066pub enum VariantKind {
1067 /// A variant with no parentheses
1068 ///
1069 /// ```rust
1070 /// enum Demo {
1071 /// PlainVariant,
1072 /// PlainWithDiscriminant = 1,
1073 /// }
1074 /// ```
1075 Plain,
1076 /// A variant with unnamed fields.
1077 ///
1078 /// All [`Id`]'s will point to [`ItemEnum::StructField`].
1079 /// Unlike most of JSON, `#[doc(hidden)]` fields will be given as `None`
1080 /// instead of being omitted, because order matters.
1081 ///
1082 /// ```rust
1083 /// enum Demo {
1084 /// TupleVariant(i32),
1085 /// EmptyTupleVariant(),
1086 /// }
1087 /// ```
1088 Tuple(Vec<Option<Id>>),
1089 /// A variant with named fields.
1090 ///
1091 /// ```rust
1092 /// enum Demo {
1093 /// StructVariant { x: i32 },
1094 /// EmptyStructVariant {},
1095 /// }
1096 /// ```
1097 Struct {
1098 /// The list of named fields in the variant.
1099 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
1100 fields: Vec<Id>,
1101 /// Whether any fields have been removed from the result, due to being private or hidden.
1102 has_stripped_fields: bool,
1103 },
1104}
1105
1106/// The value that distinguishes a variant in an [`Enum`] from other variants.
1107#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1108#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1109#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1110pub struct Discriminant {
1111 /// The expression that produced the discriminant.
1112 ///
1113 /// Unlike `value`, this preserves the original formatting (eg suffixes,
1114 /// hexadecimal, and underscores), making it unsuitable to be machine
1115 /// interpreted.
1116 ///
1117 /// In some cases, when the value is too complex, this may be `"{ _ }"`.
1118 /// When this occurs is unstable, and may change without notice.
1119 pub expr: String,
1120 /// The numerical value of the discriminant. Stored as a string due to
1121 /// JSON's poor support for large integers, and the fact that it would need
1122 /// to store from [`i128::MIN`] to [`u128::MAX`].
1123 pub value: String,
1124}
1125
1126/// A set of fundamental properties of a function.
1127#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1128#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1129#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1130pub struct FunctionHeader {
1131 /// Is this function marked as `const`?
1132 pub is_const: bool,
1133 /// Is this function unsafe?
1134 pub is_unsafe: bool,
1135 /// Is this function async?
1136 pub is_async: bool,
1137 /// The ABI used by the function.
1138 pub abi: Abi,
1139}
1140
1141/// The ABI (Application Binary Interface) used by a function.
1142///
1143/// If a variant has an `unwind` field, this means the ABI that it represents can be specified in 2
1144/// ways: `extern "_"` and `extern "_-unwind"`, and a value of `true` for that field signifies the
1145/// latter variant.
1146///
1147/// See the [Rustonomicon section](https://doc.rust-lang.org/nightly/nomicon/ffi.html#ffi-and-unwinding)
1148/// on unwinding for more info.
1149#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1150#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1151#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1152pub enum Abi {
1153 // We only have a concrete listing here for stable ABI's because there are so many
1154 // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
1155 /// The default ABI, but that can also be written explicitly with `extern "Rust"`.
1156 Rust,
1157 /// Can be specified as `extern "C"` or, as a shorthand, just `extern`.
1158 C { unwind: bool },
1159 /// Can be specified as `extern "cdecl"`.
1160 Cdecl { unwind: bool },
1161 /// Can be specified as `extern "stdcall"`.
1162 Stdcall { unwind: bool },
1163 /// Can be specified as `extern "fastcall"`.
1164 Fastcall { unwind: bool },
1165 /// Can be specified as `extern "aapcs"`.
1166 Aapcs { unwind: bool },
1167 /// Can be specified as `extern "win64"`.
1168 Win64 { unwind: bool },
1169 /// Can be specified as `extern "sysv64"`.
1170 SysV64 { unwind: bool },
1171 /// Can be specified as `extern "system"`.
1172 System { unwind: bool },
1173 /// Any other ABI, including unstable ones.
1174 Other(String),
1175}
1176
1177/// A function declaration (including methods and other associated functions).
1178#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1179#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1180#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1181pub struct Function {
1182 /// Information about the function signature, or declaration.
1183 pub sig: FunctionSignature,
1184 /// Information about the function’s type parameters and `where` clauses.
1185 pub generics: Generics,
1186 /// Information about core properties of the function, e.g. whether it's `const`, its ABI, etc.
1187 pub header: FunctionHeader,
1188 /// Whether the function has a body, i.e. an implementation.
1189 pub has_body: bool,
1190}
1191
1192/// Generic parameters accepted by an item and `where` clauses imposed on it and the parameters.
1193#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1194#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1195#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1196pub struct Generics {
1197 /// A list of generic parameter definitions (e.g. `<T: Clone + Hash, U: Copy>`).
1198 pub params: Vec<GenericParamDef>,
1199 /// A list of where predicates (e.g. `where T: Iterator, T::Item: Copy`).
1200 pub where_predicates: Vec<WherePredicate>,
1201}
1202
1203/// One generic parameter accepted by an item.
1204#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1205#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1206#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1207pub struct GenericParamDef {
1208 /// Name of the parameter.
1209 /// ```rust
1210 /// fn f<'resource, Resource>(x: &'resource Resource) {}
1211 /// // ^^^^^^^^ ^^^^^^^^
1212 /// ```
1213 pub name: String,
1214 /// The kind of the parameter and data specific to a particular parameter kind, e.g. type
1215 /// bounds.
1216 pub kind: GenericParamDefKind,
1217}
1218
1219/// The kind of a [`GenericParamDef`].
1220#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1221#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1222#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1223#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
1224 __S: rkyv::ser::Writer + rkyv::ser::Allocator,
1225 __S::Error: rkyv::rancor::Source,
1226)))]
1227#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
1228 __D::Error: rkyv::rancor::Source,
1229)))]
1230#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
1231 __C: rkyv::validation::ArchiveContext,
1232))))]
1233#[serde(rename_all = "snake_case")]
1234pub enum GenericParamDefKind {
1235 /// Denotes a lifetime parameter.
1236 Lifetime {
1237 /// Lifetimes that this lifetime parameter is required to outlive.
1238 ///
1239 /// ```rust
1240 /// fn f<'a, 'b, 'resource: 'a + 'b>(a: &'a str, b: &'b str, res: &'resource str) {}
1241 /// // ^^^^^^^
1242 /// ```
1243 outlives: Vec<String>,
1244 },
1245
1246 /// Denotes a type parameter.
1247 Type {
1248 /// Bounds applied directly to the type. Note that the bounds from `where` clauses
1249 /// that constrain this parameter won't appear here.
1250 ///
1251 /// ```rust
1252 /// fn default2<T: Default>() -> [T; 2] where T: Clone { todo!() }
1253 /// // ^^^^^^^
1254 /// ```
1255 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1256 bounds: Vec<GenericBound>,
1257 /// The default type for this parameter, if provided, e.g.
1258 ///
1259 /// ```rust
1260 /// trait PartialEq<Rhs = Self> {}
1261 /// // ^^^^
1262 /// ```
1263 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1264 default: Option<Type>,
1265 /// This is normally `false`, which means that this generic parameter is
1266 /// declared in the Rust source text.
1267 ///
1268 /// If it is `true`, this generic parameter has been introduced by the
1269 /// compiler behind the scenes.
1270 ///
1271 /// # Example
1272 ///
1273 /// Consider
1274 ///
1275 /// ```ignore (pseudo-rust)
1276 /// pub fn f(_: impl Trait) {}
1277 /// ```
1278 ///
1279 /// The compiler will transform this behind the scenes to
1280 ///
1281 /// ```ignore (pseudo-rust)
1282 /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
1283 /// ```
1284 ///
1285 /// In this example, the generic parameter named `impl Trait` (and which
1286 /// is bound by `Trait`) is synthetic, because it was not originally in
1287 /// the Rust source text.
1288 is_synthetic: bool,
1289 },
1290
1291 /// Denotes a constant parameter.
1292 Const {
1293 /// The type of the constant as declared.
1294 #[serde(rename = "type")]
1295 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1296 type_: Type,
1297 /// The stringified expression for the default value, if provided. It's not guaranteed that
1298 /// it'll match the actual source code for the default value.
1299 default: Option<String>,
1300 },
1301}
1302
1303/// One `where` clause.
1304/// ```rust
1305/// fn default<T>() -> T where T: Default { T::default() }
1306/// // ^^^^^^^^^^
1307/// ```
1308#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1309#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1310#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1311#[serde(rename_all = "snake_case")]
1312pub enum WherePredicate {
1313 /// A type is expected to comply with a set of bounds
1314 BoundPredicate {
1315 /// The type that's being constrained.
1316 ///
1317 /// ```rust
1318 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1319 /// // ^
1320 /// ```
1321 #[serde(rename = "type")]
1322 type_: Type,
1323 /// The set of bounds that constrain the type.
1324 ///
1325 /// ```rust
1326 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1327 /// // ^^^^^^^^
1328 /// ```
1329 bounds: Vec<GenericBound>,
1330 /// Used for Higher-Rank Trait Bounds (HRTBs)
1331 /// ```rust
1332 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1333 /// // ^^^^^^^
1334 /// ```
1335 generic_params: Vec<GenericParamDef>,
1336 },
1337
1338 /// A lifetime is expected to outlive other lifetimes.
1339 LifetimePredicate {
1340 /// The name of the lifetime.
1341 lifetime: String,
1342 /// The lifetimes that must be encompassed by the lifetime.
1343 outlives: Vec<String>,
1344 },
1345
1346 /// A type must exactly equal another type.
1347 EqPredicate {
1348 /// The left side of the equation.
1349 lhs: Type,
1350 /// The right side of the equation.
1351 rhs: Term,
1352 },
1353}
1354
1355/// Either a trait bound or a lifetime bound.
1356#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1357#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1358#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1359#[serde(rename_all = "snake_case")]
1360pub enum GenericBound {
1361 /// A trait bound.
1362 TraitBound {
1363 /// The full path to the trait.
1364 #[serde(rename = "trait")]
1365 trait_: Path,
1366 /// Used for Higher-Rank Trait Bounds (HRTBs)
1367 /// ```text
1368 /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
1369 /// ^^^^^^^^^^^
1370 /// |
1371 /// this part
1372 /// ```
1373 generic_params: Vec<GenericParamDef>,
1374 /// The context for which a trait is supposed to be used, e.g. `const
1375 modifier: TraitBoundModifier,
1376 },
1377 /// A lifetime bound, e.g.
1378 /// ```rust
1379 /// fn f<'a, T>(x: &'a str, y: &T) where T: 'a {}
1380 /// // ^^^
1381 /// ```
1382 Outlives(String),
1383 /// `use<'a, T>` precise-capturing bound syntax
1384 Use(Vec<PreciseCapturingArg>),
1385}
1386
1387/// A set of modifiers applied to a trait.
1388#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1389#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1390#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1391#[serde(rename_all = "snake_case")]
1392pub enum TraitBoundModifier {
1393 /// Marks the absence of a modifier.
1394 None,
1395 /// Indicates that the trait bound relaxes a trait bound applied to a parameter by default,
1396 /// e.g. `T: Sized?`, the `Sized` trait is required for all generic type parameters by default
1397 /// unless specified otherwise with this modifier.
1398 Maybe,
1399 /// Indicates that the trait bound must be applicable in both a run-time and a compile-time
1400 /// context.
1401 MaybeConst,
1402}
1403
1404/// One precise capturing argument. See [the rust reference](https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing).
1405#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1406#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1407#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1408#[serde(rename_all = "snake_case")]
1409pub enum PreciseCapturingArg {
1410 /// A lifetime.
1411 /// ```rust
1412 /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1413 /// // ^^
1414 Lifetime(String),
1415 /// A type or constant parameter.
1416 /// ```rust
1417 /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1418 /// // ^ ^
1419 Param(String),
1420}
1421
1422/// Either a type or a constant, usually stored as the right-hand side of an equation in places like
1423/// [`AssocItemConstraint`]
1424#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1425#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1426#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1427#[serde(rename_all = "snake_case")]
1428pub enum Term {
1429 /// A type.
1430 ///
1431 /// ```rust
1432 /// fn f(x: impl IntoIterator<Item = u32>) {}
1433 /// // ^^^
1434 /// ```
1435 Type(Type),
1436 /// A constant.
1437 ///
1438 /// ```ignore (incomplete feature in the snippet)
1439 /// trait Foo {
1440 /// const BAR: usize;
1441 /// }
1442 ///
1443 /// fn f(x: impl Foo<BAR = 42>) {}
1444 /// // ^^
1445 /// ```
1446 Constant(Constant),
1447}
1448
1449/// A type.
1450#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1451#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1452#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1453#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
1454 __S: rkyv::ser::Writer + rkyv::ser::Allocator,
1455 __S::Error: rkyv::rancor::Source,
1456)))]
1457#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
1458 __D::Error: rkyv::rancor::Source,
1459)))]
1460#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
1461 __C: rkyv::validation::ArchiveContext,
1462))))]
1463#[serde(rename_all = "snake_case")]
1464pub enum Type {
1465 /// Structs, enums, unions and type aliases, e.g. `std::option::Option<u32>`
1466 ResolvedPath(Path),
1467 /// Dynamic trait object type (`dyn Trait`).
1468 DynTrait(DynTrait),
1469 /// Parameterized types. The contained string is the name of the parameter.
1470 Generic(String),
1471 /// Built-in numeric types (e.g. `u32`, `f32`), `bool`, `char`.
1472 Primitive(String),
1473 /// A function pointer type, e.g. `fn(u32) -> u32`, `extern "C" fn() -> *const u8`
1474 FunctionPointer(#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))] Box<FunctionPointer>),
1475 /// A tuple type, e.g. `(String, u32, Box<usize>)`
1476 Tuple(#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))] Vec<Type>),
1477 /// An unsized slice type, e.g. `[u32]`.
1478 Slice(#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))] Box<Type>),
1479 /// An array type, e.g. `[u32; 15]`
1480 Array {
1481 /// The type of the contained element.
1482 #[serde(rename = "type")]
1483 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1484 type_: Box<Type>,
1485 /// The stringified expression that is the length of the array.
1486 ///
1487 /// Keep in mind that it's not guaranteed to match the actual source code of the expression.
1488 len: String,
1489 },
1490 /// A pattern type, e.g. `u32 is 1..`
1491 ///
1492 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/123646)
1493 Pat {
1494 /// The base type, e.g. the `u32` in `u32 is 1..`
1495 #[serde(rename = "type")]
1496 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1497 type_: Box<Type>,
1498 #[doc(hidden)]
1499 __pat_unstable_do_not_use: String,
1500 },
1501 /// An opaque type that satisfies a set of bounds, `impl TraitA + TraitB + ...`
1502 ImplTrait(Vec<GenericBound>),
1503 /// A type that's left to be inferred, `_`
1504 Infer,
1505 /// A raw pointer type, e.g. `*mut u32`, `*const u8`, etc.
1506 RawPointer {
1507 /// This is `true` for `*mut _` and `false` for `*const _`.
1508 is_mutable: bool,
1509 /// The type of the pointee.
1510 #[serde(rename = "type")]
1511 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1512 type_: Box<Type>,
1513 },
1514 /// `&'a mut String`, `&str`, etc.
1515 BorrowedRef {
1516 /// The name of the lifetime of the reference, if provided.
1517 lifetime: Option<String>,
1518 /// This is `true` for `&mut i32` and `false` for `&i32`
1519 is_mutable: bool,
1520 /// The type of the pointee, e.g. the `i32` in `&'a mut i32`
1521 #[serde(rename = "type")]
1522 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1523 type_: Box<Type>,
1524 },
1525 /// Associated types like `<Type as Trait>::Name` and `T::Item` where
1526 /// `T: Iterator` or inherent associated types like `Struct::Name`.
1527 QualifiedPath {
1528 /// The name of the associated type in the parent type.
1529 ///
1530 /// ```ignore (incomplete expression)
1531 /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1532 /// // ^^^^
1533 /// ```
1534 name: String,
1535 /// The generic arguments provided to the associated type.
1536 ///
1537 /// ```ignore (incomplete expression)
1538 /// <core::slice::IterMut<'static, u32> as BetterIterator>::Item<'static>
1539 /// // ^^^^^^^^^
1540 /// ```
1541 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1542 args: Option<Box<GenericArgs>>,
1543 /// The type with which this type is associated.
1544 ///
1545 /// ```ignore (incomplete expression)
1546 /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1547 /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1548 /// ```
1549 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1550 self_type: Box<Type>,
1551 /// `None` iff this is an *inherent* associated type.
1552 #[serde(rename = "trait")]
1553 trait_: Option<Path>,
1554 },
1555}
1556
1557/// A type that has a simple path to it. This is the kind of type of structs, unions, enums, etc.
1558#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1559#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1560#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1561#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
1562 __S: rkyv::ser::Writer + rkyv::ser::Allocator,
1563 __S::Error: rkyv::rancor::Source,
1564)))]
1565#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
1566 __D::Error: rkyv::rancor::Source,
1567)))]
1568#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
1569 __C: rkyv::validation::ArchiveContext,
1570 <__C as rkyv::rancor::Fallible>::Error: rkyv::rancor::Source,
1571))))]
1572pub struct Path {
1573 /// The path of the type.
1574 ///
1575 /// This will be the path that is *used* (not where it is defined), so
1576 /// multiple `Path`s may have different values for this field even if
1577 /// they all refer to the same item. e.g.
1578 ///
1579 /// ```rust
1580 /// pub type Vec1 = std::vec::Vec<i32>; // path: "std::vec::Vec"
1581 /// pub type Vec2 = Vec<i32>; // path: "Vec"
1582 /// pub type Vec3 = std::prelude::v1::Vec<i32>; // path: "std::prelude::v1::Vec"
1583 /// ```
1584 //
1585 // Example tested in ./tests/rustdoc-json/path_name.rs
1586 pub path: String,
1587 /// The ID of the type.
1588 pub id: Id,
1589 /// Generic arguments to the type.
1590 ///
1591 /// ```ignore (incomplete expression)
1592 /// std::borrow::Cow<'static, str>
1593 /// // ^^^^^^^^^^^^^^
1594 /// ```
1595 #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1596 pub args: Option<Box<GenericArgs>>,
1597}
1598
1599/// A type that is a function pointer.
1600#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1601#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1602#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1603pub struct FunctionPointer {
1604 /// The signature of the function.
1605 pub sig: FunctionSignature,
1606 /// Used for Higher-Rank Trait Bounds (HRTBs)
1607 ///
1608 /// ```ignore (incomplete expression)
1609 /// for<'c> fn(val: &'c i32) -> i32
1610 /// // ^^^^^^^
1611 /// ```
1612 pub generic_params: Vec<GenericParamDef>,
1613 /// The core properties of the function, such as the ABI it conforms to, whether it's unsafe, etc.
1614 pub header: FunctionHeader,
1615}
1616
1617/// The signature of a function.
1618#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1619#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1620#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1621pub struct FunctionSignature {
1622 /// List of argument names and their type.
1623 ///
1624 /// Note that not all names will be valid identifiers, as some of
1625 /// them may be patterns.
1626 pub inputs: Vec<(String, Type)>,
1627 /// The output type, if specified.
1628 pub output: Option<Type>,
1629 /// Whether the function accepts an arbitrary amount of trailing arguments the C way.
1630 ///
1631 /// ```ignore (incomplete code)
1632 /// fn printf(fmt: &str, ...);
1633 /// ```
1634 pub is_c_variadic: bool,
1635}
1636
1637/// A `trait` declaration.
1638#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1639#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1640#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1641pub struct Trait {
1642 /// Whether the trait is marked `auto` and is thus implemented automatically
1643 /// for all applicable types.
1644 pub is_auto: bool,
1645 /// Whether the trait is marked as `unsafe`.
1646 pub is_unsafe: bool,
1647 /// Whether the trait is [dyn compatible](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility)[^1].
1648 ///
1649 /// [^1]: Formerly known as "object safe".
1650 pub is_dyn_compatible: bool,
1651 /// Associated [`Item`]s that can/must be implemented by the `impl` blocks.
1652 pub items: Vec<Id>,
1653 /// Information about the type parameters and `where` clauses of the trait.
1654 pub generics: Generics,
1655 /// Constraints that must be met by the implementor of the trait.
1656 pub bounds: Vec<GenericBound>,
1657 /// The implementations of the trait.
1658 pub implementations: Vec<Id>,
1659}
1660
1661/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
1662///
1663/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
1664#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1665#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1666#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1667pub struct TraitAlias {
1668 /// Information about the type parameters and `where` clauses of the alias.
1669 pub generics: Generics,
1670 /// The bounds that are associated with the alias.
1671 pub params: Vec<GenericBound>,
1672}
1673
1674/// An `impl` block.
1675#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1676#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1677#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1678pub struct Impl {
1679 /// Whether this impl is for an unsafe trait.
1680 pub is_unsafe: bool,
1681 /// Information about the impl’s type parameters and `where` clauses.
1682 pub generics: Generics,
1683 /// The list of the names of all the trait methods that weren't mentioned in this impl but
1684 /// were provided by the trait itself.
1685 ///
1686 /// For example, for this impl of the [`PartialEq`] trait:
1687 /// ```rust
1688 /// struct Foo;
1689 ///
1690 /// impl PartialEq for Foo {
1691 /// fn eq(&self, other: &Self) -> bool { todo!() }
1692 /// }
1693 /// ```
1694 /// This field will be `["ne"]`, as it has a default implementation defined for it.
1695 pub provided_trait_methods: Vec<String>,
1696 /// The trait being implemented or `None` if the impl is inherent, which means
1697 /// `impl Struct {}` as opposed to `impl Trait for Struct {}`.
1698 #[serde(rename = "trait")]
1699 pub trait_: Option<Path>,
1700 /// The type that the impl block is for.
1701 #[serde(rename = "for")]
1702 pub for_: Type,
1703 /// The list of associated items contained in this impl block.
1704 pub items: Vec<Id>,
1705 /// Whether this is a negative impl (e.g. `!Sized` or `!Send`).
1706 pub is_negative: bool,
1707 /// Whether this is an impl that’s implied by the compiler
1708 /// (for autotraits, e.g. `Send` or `Sync`).
1709 pub is_synthetic: bool,
1710 // FIXME: document this
1711 pub blanket_impl: Option<Type>,
1712}
1713
1714/// A `use` statement.
1715#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1716#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1717#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1718#[serde(rename_all = "snake_case")]
1719pub struct Use {
1720 /// The full path being imported.
1721 pub source: String,
1722 /// May be different from the last segment of `source` when renaming imports:
1723 /// `use source as name;`
1724 pub name: String,
1725 /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
1726 /// ```rust
1727 /// pub use i32 as my_i32;
1728 /// ```
1729 pub id: Option<Id>,
1730 /// Whether this statement is a wildcard `use`, e.g. `use source::*;`
1731 pub is_glob: bool,
1732}
1733
1734/// A procedural macro.
1735#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1736#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1737#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1738pub struct ProcMacro {
1739 /// How this macro is supposed to be called: `foo!()`, `#[foo]` or `#[derive(foo)]`
1740 pub kind: MacroKind,
1741 /// Helper attributes defined by a macro to be used inside it.
1742 ///
1743 /// Defined only for derive macros.
1744 ///
1745 /// E.g. the [`Default`] derive macro defines a `#[default]` helper attribute so that one can
1746 /// do:
1747 ///
1748 /// ```rust
1749 /// #[derive(Default)]
1750 /// enum Option<T> {
1751 /// #[default]
1752 /// None,
1753 /// Some(T),
1754 /// }
1755 /// ```
1756 pub helpers: Vec<String>,
1757}
1758
1759/// The way a [`ProcMacro`] is declared to be used.
1760#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1761#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1762#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1763#[serde(rename_all = "snake_case")]
1764pub enum MacroKind {
1765 /// A bang macro `foo!()`.
1766 Bang,
1767 /// An attribute macro `#[foo]`.
1768 Attr,
1769 /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
1770 Derive,
1771}
1772
1773/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
1774#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1775#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1776#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1777pub struct TypeAlias {
1778 /// The type referred to by this alias.
1779 #[serde(rename = "type")]
1780 pub type_: Type,
1781 /// Information about the type parameters and `where` clauses of the alias.
1782 pub generics: Generics,
1783}
1784
1785/// A `static` declaration.
1786#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1787#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1788#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1789pub struct Static {
1790 /// The type of the static.
1791 #[serde(rename = "type")]
1792 pub type_: Type,
1793 /// This is `true` for mutable statics, declared as `static mut X: T = f();`
1794 pub is_mutable: bool,
1795 /// The stringified expression for the initial value.
1796 ///
1797 /// It's not guaranteed that it'll match the actual source code for the initial value.
1798 pub expr: String,
1799
1800 /// Is the static `unsafe`?
1801 ///
1802 /// This is only true if it's in an `extern` block, and not explicitly marked
1803 /// as `safe`.
1804 ///
1805 /// ```rust
1806 /// unsafe extern {
1807 /// static A: i32; // unsafe
1808 /// safe static B: i32; // safe
1809 /// }
1810 ///
1811 /// static C: i32 = 0; // safe
1812 /// static mut D: i32 = 0; // safe
1813 /// ```
1814 pub is_unsafe: bool,
1815}
1816
1817/// A primitive type declaration. Declarations of this kind can only come from the core library.
1818#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1819#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1820#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1821pub struct Primitive {
1822 /// The name of the type.
1823 pub name: String,
1824 /// The implementations, inherent and of traits, on the primitive type.
1825 pub impls: Vec<Id>,
1826}
1827
1828#[cfg(test)]
1829mod tests;