Skip to main content

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: Make `Stability` work with non-self-describing formats
117pub const FORMAT_VERSION: u32 = 61;
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    /// - `#[rustc_default_body_unstable]` attributes: instead see `default_unstable` fields on
291    ///   item kinds that can have unstable default values, such as [`Function::default_unstable`],
292    ///   [`ItemEnum::AssocConst::default_unstable`], and [`ItemEnum::AssocType::default_unstable`].
293    ///
294    /// Attributes appear in pretty-printed Rust form, regardless of their formatting
295    /// in the original source code. For example:
296    /// - `#[non_exhaustive]` and `#[must_use]` are represented as themselves.
297    /// - `#[no_mangle]` and `#[export_name]` are also represented as themselves.
298    /// - `#[repr(C)]` and other reprs also appear as themselves,
299    ///   though potentially with a different order: e.g. `repr(i8, C)` may become `repr(C, i8)`.
300    ///   Multiple repr attributes on the same item may be combined into an equivalent single attr.
301    pub attrs: Vec<Attribute>,
302    /// Information about the item’s deprecation, if present.
303    pub deprecation: Option<Deprecation>,
304
305    /// Stability information for this item, if any.
306    ///
307    /// This describes whether the item itself is stable or unstable, as noted by a `#[stable]` or
308    /// `#[unstable]` attribute. It does not capture const stability, default-body stability, etc.
309    ///
310    /// Whether a path to an item is stable depends on the stability of containing modules
311    /// or re-exports along that path. For example, a stable item can be reachable through both an
312    /// unstable module and a stable re-export.
313    ///
314    /// For items whose inner kind is [`ItemEnum::Use`], this is the stability of the import itself,
315    /// not the item being imported. This allows users to determine the stability of paths
316    /// that involve re-exports.
317    ///
318    /// Associated items can inherit instability from their enclosing unstable trait or impl.
319    /// Unannotated associated items in stable traits or impls may have no separate stability value.
320    ///
321    /// Currently, Rust's `#[stable]` and `#[unstable]` attributes are themselves not stable.
322    /// As a result, this field is primarily populated for standard-library items;
323    /// most ordinary third-party crates usually have no data here.
324    pub stability: Option<Box<Stability>>,
325
326    /// Stability information for using this item in const contexts, if any.
327    ///
328    /// This is separate from [`Self::stability`]. An item can be stable as regular API while its
329    /// const use is unstable. An unstable item may have no separate const-stability value here.
330    ///
331    /// This field is only populated for item kinds whose const behavior can have separate
332    /// stability information, such as const functions, const traits, const trait impls,
333    /// and associated items whose const behavior is controlled by a const trait or const impl.
334    pub const_stability: Option<Box<Stability>>,
335
336    /// The type-specific fields describing this item.
337    pub inner: ItemEnum,
338}
339
340/// Stability information for an item.
341///
342/// In [`Item::stability`], this refers to regular item stability: whether the item is
343/// stable or unstable as represented by the `#[stable]` or `#[unstable]` attributes.
344/// In [`Item::const_stability`], this refers to using the item in const contexts,
345/// as represented by `#[rustc_const_stable]` or `#[rustc_const_unstable]`.
346#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
347#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
348#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
349pub struct Stability {
350    /// The feature associated with this stability record.
351    ///
352    /// For unstable items, this is the feature gate associated with the item.
353    /// For stable items, this is the historical label recorded when the item was stabilized.
354    pub feature: String,
355
356    pub level: StabilityLevel,
357}
358
359#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
360#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
361#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
362#[serde(rename_all = "snake_case")]
363pub enum StabilityLevel {
364    Stable {
365        /// The Rust version in which this item became stable, if available.
366        since: Option<String>,
367    },
368    Unstable,
369}
370
371/// Information about an unstable default provided by a trait item.
372///
373/// Example unstable defaults include:
374/// - a stable trait function or method whose body is not stable
375/// - a stable trait associated type or const whose default value is not stable
376#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
377#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
378#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
379pub struct ProvidedDefaultUnstable {
380    /// The feature that must be enabled to use the provided default.
381    pub feature: String,
382}
383
384#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
385#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
386#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
387#[serde(rename_all = "snake_case")]
388/// An attribute, e.g. `#[repr(C)]`
389///
390/// This doesn't include:
391/// - `#[doc = "Doc Comment"]` or `/// Doc comment`. These are in [`Item::docs`] instead.
392/// - `#[deprecated]`. These are in [`Item::deprecation`] instead.
393/// - `#[stable]` and `#[unstable]`. These are in [`Item::stability`] instead.
394/// - `#[rustc_const_stable]` and `#[rustc_const_unstable]`. These are in
395///   [`Item::const_stability`] instead.
396/// - `#[rustc_default_body_unstable]`. These are in the `default_unstable` field on the appropriate
397///   item kinds: [`Function::default_unstable`], [`ItemEnum::AssocConst::default_unstable`],
398///   and [`ItemEnum::AssocType::default_unstable`].
399pub enum Attribute {
400    /// `#[non_exhaustive]`
401    NonExhaustive,
402
403    /// `#[must_use]`
404    MustUse { reason: Option<String> },
405
406    /// `#[macro_export]`
407    MacroExport,
408
409    /// `#[export_name = "name"]`
410    ExportName(String),
411
412    /// `#[link_section = "name"]`
413    LinkSection(String),
414
415    /// `#[automatically_derived]`
416    AutomaticallyDerived,
417
418    /// `#[repr]`
419    Repr(AttributeRepr),
420
421    /// `#[no_mangle]`
422    NoMangle,
423
424    /// #[target_feature(enable = "feature1", enable = "feature2")]
425    TargetFeature { enable: Vec<String> },
426
427    /// Something else.
428    ///
429    /// Things here are explicitly *not* covered by the [`FORMAT_VERSION`]
430    /// constant, and may change without bumping the format version.
431    ///
432    /// As an implementation detail, this is currently either:
433    /// 1. A HIR debug printing, like `"#[attr = Optimize(Speed)]"`
434    /// 2. The attribute as it appears in source form, like
435    ///    `"#[optimize(speed)]"`.
436    Other(String),
437}
438
439#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
440#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
441#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
442/// The contents of a `#[repr(...)]` attribute.
443///
444/// Used in [`Attribute::Repr`].
445pub struct AttributeRepr {
446    /// The representation, e.g. `#[repr(C)]`, `#[repr(transparent)]`
447    pub kind: ReprKind,
448
449    /// Alignment in bytes, if explicitly specified by `#[repr(align(...)]`.
450    pub align: Option<u64>,
451    /// Alignment in bytes, if explicitly specified by `#[repr(packed(...)]]`.
452    pub packed: Option<u64>,
453
454    /// The integer type for an enum descriminant, if explicitly specified.
455    ///
456    /// e.g. `"i32"`, for `#[repr(C, i32)]`
457    pub int: Option<String>,
458}
459
460#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
461#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
462#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
463#[serde(rename_all = "snake_case")]
464/// The kind of `#[repr]`.
465///
466/// See [AttributeRepr::kind]`.
467pub enum ReprKind {
468    /// `#[repr(Rust)]`
469    ///
470    /// Also the default.
471    Rust,
472    /// `#[repr(C)]`
473    C,
474    /// `#[repr(transparent)]
475    Transparent,
476    /// `#[repr(simd)]`
477    Simd,
478}
479
480/// A range of source code.
481#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
482#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
483#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
484pub struct Span {
485    /// The path to the source file for this span relative to the path `rustdoc` was invoked with.
486    #[cfg_attr(feature = "rkyv_0_8", rkyv(with = rkyv::with::AsString))]
487    pub filename: PathBuf,
488    /// One indexed Line and Column of the first character of the `Span`.
489    pub begin: (usize, usize),
490    /// One indexed Line and Column of the last character of the `Span`.
491    pub end: (usize, usize),
492}
493
494/// Information about the deprecation of an [`Item`].
495#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
496#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
497#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
498pub struct Deprecation {
499    /// Usually a version number when this [`Item`] first became deprecated.
500    pub since: Option<String>,
501    /// The reason for deprecation and/or what alternatives to use.
502    pub note: Option<String>,
503}
504
505/// Visibility of an [`Item`].
506#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
507#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
508#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
509#[serde(rename_all = "snake_case")]
510pub enum Visibility {
511    /// Explicitly public visibility set with `pub`.
512    Public,
513    /// For the most part items are private by default. The exceptions are associated items of
514    /// public traits and variants of public enums.
515    Default,
516    /// Explicitly crate-wide visibility set with `pub(crate)`
517    Crate,
518    /// For `pub(in path)` visibility.
519    Restricted {
520        /// ID of the module to which this visibility restricts items.
521        parent: Id,
522        /// The path with which [`parent`] was referenced
523        /// (like `super::super` or `crate::foo::bar`).
524        ///
525        /// [`parent`]: Visibility::Restricted::parent
526        path: String,
527    },
528}
529
530/// Dynamic trait object type (`dyn Trait`).
531#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
532#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
533#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
534pub struct DynTrait {
535    /// All the traits implemented. One of them is the vtable, and the rest must be auto traits.
536    pub traits: Vec<PolyTrait>,
537    /// The lifetime of the whole dyn object
538    /// ```text
539    /// dyn Debug + 'static
540    ///             ^^^^^^^
541    ///             |
542    ///             this part
543    /// ```
544    pub lifetime: Option<String>,
545}
546
547/// A trait and potential HRTBs
548#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
549#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
550#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
551pub struct PolyTrait {
552    /// The path to the trait.
553    #[serde(rename = "trait")]
554    pub trait_: Path,
555    /// Used for Higher-Rank Trait Bounds (HRTBs)
556    /// ```text
557    /// dyn for<'a> Fn() -> &'a i32"
558    ///     ^^^^^^^
559    /// ```
560    pub generic_params: Vec<GenericParamDef>,
561}
562
563/// A set of generic arguments provided to a path segment, e.g.
564///
565/// ```text
566/// std::option::Option<u32>
567///                    ^^^^^
568/// ```
569#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
570#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
571#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
572#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
573    __S: rkyv::ser::Writer + rkyv::ser::Allocator,
574    __S::Error: rkyv::rancor::Source,
575)))]
576#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
577    __D::Error: rkyv::rancor::Source,
578)))]
579#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
580    __C: rkyv::validation::ArchiveContext,
581))))]
582#[serde(rename_all = "snake_case")]
583pub enum GenericArgs {
584    /// `<'a, 32, B: Copy, C = u32>`
585    AngleBracketed {
586        /// The list of each argument on this type.
587        /// ```text
588        /// <'a, 32, B: Copy, C = u32>
589        ///  ^^^^^^
590        /// ```
591        args: Vec<GenericArg>,
592        /// Associated type or constant bindings (e.g. `Item=i32` or `Item: Clone`) for this type.
593        constraints: Vec<AssocItemConstraint>,
594    },
595    /// `Fn(A, B) -> C`
596    Parenthesized {
597        /// The input types, enclosed in parentheses.
598        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
599        inputs: Vec<Type>,
600        /// The output type provided after the `->`, if present.
601        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
602        output: Option<Type>,
603    },
604    /// `T::method(..)`
605    ReturnTypeNotation,
606}
607
608/// One argument in a list of generic arguments to a path segment.
609///
610/// Part of [`GenericArgs`].
611#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
612#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
613#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
614#[serde(rename_all = "snake_case")]
615pub enum GenericArg {
616    /// A lifetime argument.
617    /// ```text
618    /// std::borrow::Cow<'static, str>
619    ///                  ^^^^^^^
620    /// ```
621    Lifetime(String),
622    /// A type argument.
623    /// ```text
624    /// std::borrow::Cow<'static, str>
625    ///                           ^^^
626    /// ```
627    Type(Type),
628    /// A constant as a generic argument.
629    /// ```text
630    /// core::array::IntoIter<u32, { 640 * 1024 }>
631    ///                            ^^^^^^^^^^^^^^
632    /// ```
633    Const(Constant),
634    /// A generic argument that's explicitly set to be inferred.
635    /// ```text
636    /// std::vec::Vec::<_>
637    ///                 ^
638    /// ```
639    Infer,
640}
641
642/// A constant.
643#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
644#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
645#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
646pub struct Constant {
647    /// The stringified expression of this constant. Note that its mapping to the original
648    /// source code is unstable and it's not guaranteed that it'll match the source code.
649    pub expr: String,
650    /// The value of the evaluated expression for this constant, which is only computed for numeric
651    /// types.
652    pub value: Option<String>,
653    /// Whether this constant is a bool, numeric, string, or char literal.
654    pub is_literal: bool,
655}
656
657/// Describes a bound applied to an associated type/constant.
658///
659/// Example:
660/// ```text
661/// IntoIterator<Item = u32, IntoIter: Clone>
662///              ^^^^^^^^^^  ^^^^^^^^^^^^^^^
663/// ```
664#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
665#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
666#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
667#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
668    __S: rkyv::ser::Writer + rkyv::ser::Allocator,
669    __S::Error: rkyv::rancor::Source,
670)))]
671#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
672    __D::Error: rkyv::rancor::Source,
673)))]
674#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
675    __C: rkyv::validation::ArchiveContext,
676    <__C as rkyv::rancor::Fallible>::Error: rkyv::rancor::Source,
677))))]
678pub struct AssocItemConstraint {
679    /// The name of the associated type/constant.
680    pub name: String,
681    /// Arguments provided to the associated type/constant.
682    #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
683    pub args: Option<Box<GenericArgs>>,
684    /// The kind of bound applied to the associated type/constant.
685    pub binding: AssocItemConstraintKind,
686}
687
688/// The way in which an associate type/constant is bound.
689#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
690#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
691#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
692#[serde(rename_all = "snake_case")]
693pub enum AssocItemConstraintKind {
694    /// The required value/type is specified exactly. e.g.
695    /// ```text
696    /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
697    ///          ^^^^^^^^^^
698    /// ```
699    Equality(Term),
700    /// The type is required to satisfy a set of bounds.
701    /// ```text
702    /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
703    ///                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
704    /// ```
705    Constraint(Vec<GenericBound>),
706}
707
708/// An opaque identifier for an item.
709///
710/// It can be used to lookup in [`Crate::index`] or [`Crate::paths`] to resolve it
711/// to an [`Item`].
712///
713/// Id's are only valid within a single JSON blob. They cannot be used to
714/// resolve references between the JSON output's for different crates.
715///
716/// Rustdoc makes no guarantees about the inner value of Id's. Applications
717/// should treat them as opaque keys to lookup items, and avoid attempting
718/// to parse them, or otherwise depend on any implementation details.
719#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
720#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
721#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)))]
722// FIXME(aDotInTheVoid): Consider making this non-public in rustdoc-types.
723pub struct Id(pub u32);
724
725/// The fundamental kind of an item. Unlike [`ItemEnum`], this does not carry any additional info.
726///
727/// Part of [`ItemSummary`].
728#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
729#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
730#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
731#[cfg_attr(feature = "rkyv_0_8", rkyv(compare(PartialEq)))]
732#[serde(rename_all = "snake_case")]
733pub enum ItemKind {
734    /// A module declaration, e.g. `mod foo;` or `mod foo {}`
735    Module,
736    /// A crate imported via the `extern crate` syntax.
737    ExternCrate,
738    /// An import of 1 or more items into scope, using the `use` keyword.
739    Use,
740    /// A `struct` declaration.
741    Struct,
742    /// A field of a struct.
743    StructField,
744    /// A `union` declaration.
745    Union,
746    /// An `enum` declaration.
747    Enum,
748    /// A variant of a enum.
749    Variant,
750    /// A function declaration, e.g. `fn f() {}`
751    Function,
752    /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
753    TypeAlias,
754    /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
755    Constant,
756    /// A `trait` declaration.
757    Trait,
758    /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
759    ///
760    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
761    TraitAlias,
762    /// An `impl` block.
763    Impl,
764    /// A `static` declaration.
765    Static,
766    /// `type`s from an `extern` block.
767    ///
768    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
769    ExternType,
770    /// A macro declaration.
771    ///
772    /// Corresponds to either `ItemEnum::Macro(_)`
773    /// or `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Bang })`
774    Macro,
775    /// A procedural macro attribute.
776    ///
777    /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Attr })`
778    ProcAttribute,
779    /// A procedural macro usable in the `#[derive()]` attribute.
780    ///
781    /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Derive })`
782    ProcDerive,
783    /// An associated constant of a trait or a type.
784    AssocConst,
785    /// An associated type of a trait or a type.
786    AssocType,
787    /// A primitive type, e.g. `u32`.
788    ///
789    /// [`Item`]s of this kind only come from the core library.
790    Primitive,
791    /// A keyword declaration.
792    ///
793    /// [`Item`]s of this kind only come from the come library and exist solely
794    /// to carry documentation for the respective keywords.
795    Keyword,
796    /// An attribute declaration.
797    ///
798    /// [`Item`]s of this kind only come from the core library and exist solely
799    /// to carry documentation for the respective builtin attributes.
800    Attribute,
801}
802
803/// Specific fields of an item.
804///
805/// Part of [`Item`].
806#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
807#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
808#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
809#[serde(rename_all = "snake_case")]
810pub enum ItemEnum {
811    /// A module declaration, e.g. `mod foo;` or `mod foo {}`
812    Module(Module),
813    /// A crate imported via the `extern crate` syntax.
814    ExternCrate {
815        /// The name of the imported crate.
816        name: String,
817        /// If the crate is renamed, this is its name in the crate.
818        rename: Option<String>,
819    },
820    /// An import of 1 or more items into scope, using the `use` keyword.
821    Use(Use),
822
823    /// A `union` declaration.
824    Union(Union),
825    /// A `struct` declaration.
826    Struct(Struct),
827    /// A field of a struct.
828    StructField(Type),
829    /// An `enum` declaration.
830    Enum(Enum),
831    /// A variant of a enum.
832    Variant(Variant),
833
834    /// A function declaration (including methods and other associated functions)
835    Function(Function),
836
837    /// A `trait` declaration.
838    Trait(Trait),
839    /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
840    ///
841    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
842    TraitAlias(TraitAlias),
843    /// An `impl` block.
844    Impl(Impl),
845
846    /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
847    TypeAlias(TypeAlias),
848    /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
849    Constant {
850        /// The type of the constant.
851        #[serde(rename = "type")]
852        type_: Type,
853        /// The declared constant itself.
854        #[serde(rename = "const")]
855        const_: Constant,
856    },
857
858    /// A declaration of a `static`.
859    Static(Static),
860
861    /// `type`s from an `extern` block.
862    ///
863    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
864    ExternType,
865
866    /// A macro_rules! declarative macro. Contains a single string with the source
867    /// representation of the macro with the patterns stripped.
868    Macro(String),
869    /// A procedural macro.
870    ProcMacro(ProcMacro),
871
872    /// A primitive type, e.g. `u32`.
873    ///
874    /// [`Item`]s of this kind only come from the core library.
875    Primitive(Primitive),
876
877    /// An associated constant of a trait or a type.
878    AssocConst {
879        /// The type of the constant.
880        #[serde(rename = "type")]
881        type_: Type,
882        /// Inside a trait declaration, this is the default value for the associated constant,
883        /// if provided.
884        /// Inside an `impl` block, this is the value assigned to the associated constant,
885        /// and will always be present.
886        ///
887        /// The representation is implementation-defined and not guaranteed to be representative of
888        /// either the resulting value or of the source code.
889        ///
890        /// ```rust
891        /// const X: usize = 640 * 1024;
892        /// //               ^^^^^^^^^^
893        /// ```
894        value: Option<String>,
895        /// Metadata about an unstable default value provided for the associated constant, if any.
896        ///
897        /// Empty if the associated constant has no default (see [`ItemEnum::AssocConst::value`]),
898        /// or if the default value is stable.
899        default_unstable: Option<Box<ProvidedDefaultUnstable>>,
900    },
901    /// An associated type of a trait or a type.
902    AssocType {
903        /// The generic parameters and where clauses on ahis associated type.
904        generics: Generics,
905        /// The bounds for this associated type. e.g.
906        /// ```rust
907        /// trait IntoIterator {
908        ///     type Item;
909        ///     type IntoIter: Iterator<Item = Self::Item>;
910        /// //                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
911        /// }
912        /// ```
913        bounds: Vec<GenericBound>,
914        /// Inside a trait declaration, this is the default for the associated type, if provided.
915        /// Inside an impl block, this is the type assigned to the associated type, and will always
916        /// be present.
917        ///
918        /// ```rust
919        /// type X = usize;
920        /// //       ^^^^^
921        /// ```
922        #[serde(rename = "type")]
923        type_: Option<Type>,
924        /// Metadata about an unstable default value provided for the associated type, if any.
925        ///
926        /// Empty if the associated type has no default (see [`ItemEnum::AssocType::type_`]),
927        /// or if the default value is stable.
928        default_unstable: Option<Box<ProvidedDefaultUnstable>>,
929    },
930}
931
932impl ItemEnum {
933    /// Get just the kind of this item, but with no further data.
934    ///
935    /// ```rust
936    /// # use rustdoc_types::{ItemKind, ItemEnum};
937    /// let item = ItemEnum::ExternCrate { name: "libc".to_owned(), rename: None };
938    /// assert_eq!(item.item_kind(), ItemKind::ExternCrate);
939    /// ```
940    pub fn item_kind(&self) -> ItemKind {
941        match self {
942            ItemEnum::Module(_) => ItemKind::Module,
943            ItemEnum::ExternCrate { .. } => ItemKind::ExternCrate,
944            ItemEnum::Use(_) => ItemKind::Use,
945            ItemEnum::Union(_) => ItemKind::Union,
946            ItemEnum::Struct(_) => ItemKind::Struct,
947            ItemEnum::StructField(_) => ItemKind::StructField,
948            ItemEnum::Enum(_) => ItemKind::Enum,
949            ItemEnum::Variant(_) => ItemKind::Variant,
950            ItemEnum::Function(_) => ItemKind::Function,
951            ItemEnum::Trait(_) => ItemKind::Trait,
952            ItemEnum::TraitAlias(_) => ItemKind::TraitAlias,
953            ItemEnum::Impl(_) => ItemKind::Impl,
954            ItemEnum::TypeAlias(_) => ItemKind::TypeAlias,
955            ItemEnum::Constant { .. } => ItemKind::Constant,
956            ItemEnum::Static(_) => ItemKind::Static,
957            ItemEnum::ExternType => ItemKind::ExternType,
958            ItemEnum::Macro(_) => ItemKind::Macro,
959            ItemEnum::ProcMacro(pm) => match pm.kind {
960                MacroKind::Bang => ItemKind::Macro,
961                MacroKind::Attr => ItemKind::ProcAttribute,
962                MacroKind::Derive => ItemKind::ProcDerive,
963            },
964            ItemEnum::Primitive(_) => ItemKind::Primitive,
965            ItemEnum::AssocConst { .. } => ItemKind::AssocConst,
966            ItemEnum::AssocType { .. } => ItemKind::AssocType,
967        }
968    }
969}
970
971/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
972#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
973#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
974#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
975pub struct Module {
976    /// Whether this is the root item of a crate.
977    ///
978    /// This item doesn't correspond to any construction in the source code and is generated by the
979    /// compiler.
980    pub is_crate: bool,
981    /// [`Item`]s declared inside this module.
982    pub items: Vec<Id>,
983    /// If `true`, this module is not part of the public API, but it contains
984    /// items that are re-exported as public API.
985    pub is_stripped: bool,
986}
987
988/// A `union`.
989#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
990#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
991#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
992pub struct Union {
993    /// The generic parameters and where clauses on this union.
994    pub generics: Generics,
995    /// Whether any fields have been removed from the result, due to being private or hidden.
996    pub has_stripped_fields: bool,
997    /// The list of fields in the union.
998    ///
999    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
1000    pub fields: Vec<Id>,
1001    /// All impls (both of traits and inherent) for this union.
1002    ///
1003    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
1004    pub impls: Vec<Id>,
1005}
1006
1007/// A `struct`.
1008#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1009#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1010#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1011pub struct Struct {
1012    /// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
1013    /// i.e. fields.
1014    pub kind: StructKind,
1015    /// The generic parameters and where clauses on this struct.
1016    pub generics: Generics,
1017    /// All impls (both of traits and inherent) for this struct.
1018    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
1019    pub impls: Vec<Id>,
1020}
1021
1022/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
1023#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1024#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1025#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1026#[serde(rename_all = "snake_case")]
1027pub enum StructKind {
1028    /// A struct with no fields and no parentheses.
1029    ///
1030    /// ```rust
1031    /// pub struct Unit;
1032    /// ```
1033    Unit,
1034    /// A struct with unnamed fields.
1035    ///
1036    /// All [`Id`]'s will point to [`ItemEnum::StructField`].
1037    /// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
1038    /// instead of being omitted, because order matters.
1039    ///
1040    /// ```rust
1041    /// pub struct TupleStruct(i32);
1042    /// pub struct EmptyTupleStruct();
1043    /// ```
1044    Tuple(Vec<Option<Id>>),
1045    /// A struct with named fields.
1046    ///
1047    /// ```rust
1048    /// pub struct PlainStruct { x: i32 }
1049    /// pub struct EmptyPlainStruct {}
1050    /// ```
1051    Plain {
1052        /// The list of fields in the struct.
1053        ///
1054        /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
1055        fields: Vec<Id>,
1056        /// Whether any fields have been removed from the result, due to being private or hidden.
1057        has_stripped_fields: bool,
1058    },
1059}
1060
1061/// An `enum`.
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)))]
1065pub struct Enum {
1066    /// Information about the type parameters and `where` clauses of the enum.
1067    pub generics: Generics,
1068    /// Whether any variants have been removed from the result, due to being private or hidden.
1069    pub has_stripped_variants: bool,
1070    /// The list of variants in the enum.
1071    ///
1072    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
1073    pub variants: Vec<Id>,
1074    /// `impl`s for the enum.
1075    pub impls: Vec<Id>,
1076}
1077
1078/// A variant of an enum.
1079#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1080#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1081#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1082pub struct Variant {
1083    /// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
1084    pub kind: VariantKind,
1085    /// The discriminant, if explicitly specified.
1086    pub discriminant: Option<Discriminant>,
1087}
1088
1089/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
1090#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1091#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1092#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1093#[serde(rename_all = "snake_case")]
1094pub enum VariantKind {
1095    /// A variant with no parentheses
1096    ///
1097    /// ```rust
1098    /// enum Demo {
1099    ///     PlainVariant,
1100    ///     PlainWithDiscriminant = 1,
1101    /// }
1102    /// ```
1103    Plain,
1104    /// A variant with unnamed fields.
1105    ///
1106    /// All [`Id`]'s will point to [`ItemEnum::StructField`].
1107    /// Unlike most of JSON, `#[doc(hidden)]` fields will be given as `None`
1108    /// instead of being omitted, because order matters.
1109    ///
1110    /// ```rust
1111    /// enum Demo {
1112    ///     TupleVariant(i32),
1113    ///     EmptyTupleVariant(),
1114    /// }
1115    /// ```
1116    Tuple(Vec<Option<Id>>),
1117    /// A variant with named fields.
1118    ///
1119    /// ```rust
1120    /// enum Demo {
1121    ///     StructVariant { x: i32 },
1122    ///     EmptyStructVariant {},
1123    /// }
1124    /// ```
1125    Struct {
1126        /// The list of named fields in the variant.
1127        /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
1128        fields: Vec<Id>,
1129        /// Whether any fields have been removed from the result, due to being private or hidden.
1130        has_stripped_fields: bool,
1131    },
1132}
1133
1134/// The value that distinguishes a variant in an [`Enum`] from other variants.
1135#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1136#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1137#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1138pub struct Discriminant {
1139    /// The expression that produced the discriminant.
1140    ///
1141    /// Unlike `value`, this preserves the original formatting (eg suffixes,
1142    /// hexadecimal, and underscores), making it unsuitable to be machine
1143    /// interpreted.
1144    ///
1145    /// In some cases, when the value is too complex, this may be `"{ _ }"`.
1146    /// When this occurs is unstable, and may change without notice.
1147    pub expr: String,
1148    /// The numerical value of the discriminant. Stored as a string due to
1149    /// JSON's poor support for large integers, and the fact that it would need
1150    /// to store from [`i128::MIN`] to [`u128::MAX`].
1151    pub value: String,
1152}
1153
1154/// A set of fundamental properties of a function.
1155#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1156#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1157#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1158pub struct FunctionHeader {
1159    /// Is this function marked as `const`?
1160    pub is_const: bool,
1161    /// Is this function unsafe?
1162    pub is_unsafe: bool,
1163    /// Is this function async?
1164    pub is_async: bool,
1165    /// The ABI used by the function.
1166    pub abi: Abi,
1167}
1168
1169/// The ABI (Application Binary Interface) used by a function.
1170///
1171/// If a variant has an `unwind` field, this means the ABI that it represents can be specified in 2
1172/// ways: `extern "_"` and `extern "_-unwind"`, and a value of `true` for that field signifies the
1173/// latter variant.
1174///
1175/// See the [Rustonomicon section](https://doc.rust-lang.org/nightly/nomicon/ffi.html#ffi-and-unwinding)
1176/// on unwinding for more info.
1177#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1178#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1179#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1180pub enum Abi {
1181    // We only have a concrete listing here for stable ABI's because there are so many
1182    // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
1183    /// The default ABI, but that can also be written explicitly with `extern "Rust"`.
1184    Rust,
1185    /// Can be specified as `extern "C"` or, as a shorthand, just `extern`.
1186    C { unwind: bool },
1187    /// Can be specified as `extern "cdecl"`.
1188    Cdecl { unwind: bool },
1189    /// Can be specified as `extern "stdcall"`.
1190    Stdcall { unwind: bool },
1191    /// Can be specified as `extern "fastcall"`.
1192    Fastcall { unwind: bool },
1193    /// Can be specified as `extern "aapcs"`.
1194    Aapcs { unwind: bool },
1195    /// Can be specified as `extern "win64"`.
1196    Win64 { unwind: bool },
1197    /// Can be specified as `extern "sysv64"`.
1198    SysV64 { unwind: bool },
1199    /// Can be specified as `extern "system"`.
1200    System { unwind: bool },
1201    /// Any other ABI, including unstable ones.
1202    Other(String),
1203}
1204
1205/// A function declaration (including methods and other associated functions).
1206#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1207#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1208#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1209pub struct Function {
1210    /// Information about the function signature, or declaration.
1211    pub sig: FunctionSignature,
1212    /// Information about the function’s type parameters and `where` clauses.
1213    pub generics: Generics,
1214    /// Information about core properties of the function, e.g. whether it's `const`, its ABI, etc.
1215    pub header: FunctionHeader,
1216    /// Whether the function has a body, i.e. an implementation.
1217    pub has_body: bool,
1218    /// Metadata about a possible unstable provided default implementation for trait methods.
1219    ///
1220    /// Only populated for function items inside traits. Empty if the trait method
1221    /// does not have a default implementation (see [`Function::has_body`]),
1222    /// or if its default implementation is stable.
1223    pub default_unstable: Option<Box<ProvidedDefaultUnstable>>,
1224}
1225
1226/// Generic parameters accepted by an item and `where` clauses imposed on it and the parameters.
1227#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1228#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1229#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1230pub struct Generics {
1231    /// A list of generic parameter definitions (e.g. `<T: Clone + Hash, U: Copy>`).
1232    pub params: Vec<GenericParamDef>,
1233    /// A list of where predicates (e.g. `where T: Iterator, T::Item: Copy`).
1234    pub where_predicates: Vec<WherePredicate>,
1235}
1236
1237/// One generic parameter accepted by an item.
1238#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1239#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1240#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1241pub struct GenericParamDef {
1242    /// Name of the parameter.
1243    /// ```rust
1244    /// fn f<'resource, Resource>(x: &'resource Resource) {}
1245    /// //    ^^^^^^^^  ^^^^^^^^
1246    /// ```
1247    pub name: String,
1248    /// The kind of the parameter and data specific to a particular parameter kind, e.g. type
1249    /// bounds.
1250    pub kind: GenericParamDefKind,
1251}
1252
1253/// The kind of a [`GenericParamDef`].
1254#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1255#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1256#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1257#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
1258    __S: rkyv::ser::Writer + rkyv::ser::Allocator,
1259    __S::Error: rkyv::rancor::Source,
1260)))]
1261#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
1262    __D::Error: rkyv::rancor::Source,
1263)))]
1264#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
1265    __C: rkyv::validation::ArchiveContext,
1266))))]
1267#[serde(rename_all = "snake_case")]
1268pub enum GenericParamDefKind {
1269    /// Denotes a lifetime parameter.
1270    Lifetime {
1271        /// Lifetimes that this lifetime parameter is required to outlive.
1272        ///
1273        /// ```rust
1274        /// fn f<'a, 'b, 'resource: 'a + 'b>(a: &'a str, b: &'b str, res: &'resource str) {}
1275        /// //                      ^^^^^^^
1276        /// ```
1277        outlives: Vec<String>,
1278    },
1279
1280    /// Denotes a type parameter.
1281    Type {
1282        /// Bounds applied directly to the type. Note that the bounds from `where` clauses
1283        /// that constrain this parameter won't appear here.
1284        ///
1285        /// ```rust
1286        /// fn default2<T: Default>() -> [T; 2] where T: Clone { todo!() }
1287        /// //             ^^^^^^^
1288        /// ```
1289        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1290        bounds: Vec<GenericBound>,
1291        /// The default type for this parameter, if provided, e.g.
1292        ///
1293        /// ```rust
1294        /// trait PartialEq<Rhs = Self> {}
1295        /// //                    ^^^^
1296        /// ```
1297        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1298        default: Option<Type>,
1299        /// This is normally `false`, which means that this generic parameter is
1300        /// declared in the Rust source text.
1301        ///
1302        /// If it is `true`, this generic parameter has been introduced by the
1303        /// compiler behind the scenes.
1304        ///
1305        /// # Example
1306        ///
1307        /// Consider
1308        ///
1309        /// ```ignore (pseudo-rust)
1310        /// pub fn f(_: impl Trait) {}
1311        /// ```
1312        ///
1313        /// The compiler will transform this behind the scenes to
1314        ///
1315        /// ```ignore (pseudo-rust)
1316        /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
1317        /// ```
1318        ///
1319        /// In this example, the generic parameter named `impl Trait` (and which
1320        /// is bound by `Trait`) is synthetic, because it was not originally in
1321        /// the Rust source text.
1322        is_synthetic: bool,
1323    },
1324
1325    /// Denotes a constant parameter.
1326    Const {
1327        /// The type of the constant as declared.
1328        #[serde(rename = "type")]
1329        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1330        type_: Type,
1331        /// The stringified expression for the default value, if provided. It's not guaranteed that
1332        /// it'll match the actual source code for the default value.
1333        default: Option<String>,
1334    },
1335}
1336
1337/// One `where` clause.
1338/// ```rust
1339/// fn default<T>() -> T where T: Default { T::default() }
1340/// //                         ^^^^^^^^^^
1341/// ```
1342#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1343#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1344#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1345#[serde(rename_all = "snake_case")]
1346pub enum WherePredicate {
1347    /// A type is expected to comply with a set of bounds
1348    BoundPredicate {
1349        /// The type that's being constrained.
1350        ///
1351        /// ```rust
1352        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1353        /// //                              ^
1354        /// ```
1355        #[serde(rename = "type")]
1356        type_: Type,
1357        /// The set of bounds that constrain the type.
1358        ///
1359        /// ```rust
1360        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1361        /// //                                 ^^^^^^^^
1362        /// ```
1363        bounds: Vec<GenericBound>,
1364        /// Used for Higher-Rank Trait Bounds (HRTBs)
1365        /// ```rust
1366        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1367        /// //                  ^^^^^^^
1368        /// ```
1369        generic_params: Vec<GenericParamDef>,
1370    },
1371
1372    /// A lifetime is expected to outlive other lifetimes.
1373    LifetimePredicate {
1374        /// The name of the lifetime.
1375        lifetime: String,
1376        /// The lifetimes that must be encompassed by the lifetime.
1377        outlives: Vec<String>,
1378    },
1379
1380    /// A type must exactly equal another type.
1381    EqPredicate {
1382        /// The left side of the equation.
1383        lhs: Type,
1384        /// The right side of the equation.
1385        rhs: Term,
1386    },
1387}
1388
1389/// Either a trait bound or a lifetime bound.
1390#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1391#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1392#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1393#[serde(rename_all = "snake_case")]
1394pub enum GenericBound {
1395    /// A trait bound.
1396    TraitBound {
1397        /// The full path to the trait.
1398        #[serde(rename = "trait")]
1399        trait_: Path,
1400        /// Used for Higher-Rank Trait Bounds (HRTBs)
1401        /// ```text
1402        /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
1403        ///          ^^^^^^^^^^^
1404        ///          |
1405        ///          this part
1406        /// ```
1407        generic_params: Vec<GenericParamDef>,
1408        /// The context for which a trait is supposed to be used, e.g. `const
1409        modifier: TraitBoundModifier,
1410    },
1411    /// A lifetime bound, e.g.
1412    /// ```rust
1413    /// fn f<'a, T>(x: &'a str, y: &T) where T: 'a {}
1414    /// //                                     ^^^
1415    /// ```
1416    Outlives(String),
1417    /// `use<'a, T>` precise-capturing bound syntax
1418    Use(Vec<PreciseCapturingArg>),
1419}
1420
1421/// A set of modifiers applied to a trait.
1422#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1423#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1424#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1425#[serde(rename_all = "snake_case")]
1426pub enum TraitBoundModifier {
1427    /// Marks the absence of a modifier.
1428    None,
1429    /// Indicates that the trait bound relaxes a trait bound applied to a parameter by default,
1430    /// e.g. `T: Sized?`, the `Sized` trait is required for all generic type parameters by default
1431    /// unless specified otherwise with this modifier.
1432    Maybe,
1433    /// Indicates that the trait bound must be applicable in both a run-time and a compile-time
1434    /// context.
1435    MaybeConst,
1436}
1437
1438/// One precise capturing argument. See [the rust reference](https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing).
1439#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1440#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1441#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1442#[serde(rename_all = "snake_case")]
1443pub enum PreciseCapturingArg {
1444    /// A lifetime.
1445    /// ```rust
1446    /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1447    /// //                                                        ^^
1448    Lifetime(String),
1449    /// A type or constant parameter.
1450    /// ```rust
1451    /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1452    /// //                                                            ^  ^
1453    Param(String),
1454}
1455
1456/// Either a type or a constant, usually stored as the right-hand side of an equation in places like
1457/// [`AssocItemConstraint`]
1458#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1459#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1460#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1461#[serde(rename_all = "snake_case")]
1462pub enum Term {
1463    /// A type.
1464    ///
1465    /// ```rust
1466    /// fn f(x: impl IntoIterator<Item = u32>) {}
1467    /// //                               ^^^
1468    /// ```
1469    Type(Type),
1470    /// A constant.
1471    ///
1472    /// ```ignore (incomplete feature in the snippet)
1473    /// trait Foo {
1474    ///     const BAR: usize;
1475    /// }
1476    ///
1477    /// fn f(x: impl Foo<BAR = 42>) {}
1478    /// //                     ^^
1479    /// ```
1480    Constant(Constant),
1481}
1482
1483/// A type.
1484#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1485#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1486#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1487#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
1488    __S: rkyv::ser::Writer + rkyv::ser::Allocator,
1489    __S::Error: rkyv::rancor::Source,
1490)))]
1491#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
1492    __D::Error: rkyv::rancor::Source,
1493)))]
1494#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
1495    __C: rkyv::validation::ArchiveContext,
1496))))]
1497#[serde(rename_all = "snake_case")]
1498pub enum Type {
1499    /// Structs, enums, unions and type aliases, e.g. `std::option::Option<u32>`
1500    ResolvedPath(Path),
1501    /// Dynamic trait object type (`dyn Trait`).
1502    DynTrait(DynTrait),
1503    /// Parameterized types. The contained string is the name of the parameter.
1504    Generic(String),
1505    /// Built-in numeric types (e.g. `u32`, `f32`), `bool`, `char`.
1506    Primitive(String),
1507    /// A function pointer type, e.g. `fn(u32) -> u32`, `extern "C" fn() -> *const u8`
1508    FunctionPointer(#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))] Box<FunctionPointer>),
1509    /// A tuple type, e.g. `(String, u32, Box<usize>)`
1510    Tuple(#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))] Vec<Type>),
1511    /// An unsized slice type, e.g. `[u32]`.
1512    Slice(#[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))] Box<Type>),
1513    /// An array type, e.g. `[u32; 15]`
1514    Array {
1515        /// The type of the contained element.
1516        #[serde(rename = "type")]
1517        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1518        type_: Box<Type>,
1519        /// The stringified expression that is the length of the array.
1520        ///
1521        /// Keep in mind that it's not guaranteed to match the actual source code of the expression.
1522        len: String,
1523    },
1524    /// A pattern type, e.g. `u32 is 1..`
1525    ///
1526    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/123646)
1527    Pat {
1528        /// The base type, e.g. the `u32` in `u32 is 1..`
1529        #[serde(rename = "type")]
1530        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1531        type_: Box<Type>,
1532        #[doc(hidden)]
1533        __pat_unstable_do_not_use: String,
1534    },
1535    /// An opaque type that satisfies a set of bounds, `impl TraitA + TraitB + ...`
1536    ImplTrait(Vec<GenericBound>),
1537    /// A type that's left to be inferred, `_`
1538    Infer,
1539    /// A raw pointer type, e.g. `*mut u32`, `*const u8`, etc.
1540    RawPointer {
1541        /// This is `true` for `*mut _` and `false` for `*const _`.
1542        is_mutable: bool,
1543        /// The type of the pointee.
1544        #[serde(rename = "type")]
1545        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1546        type_: Box<Type>,
1547    },
1548    /// `&'a mut String`, `&str`, etc.
1549    BorrowedRef {
1550        /// The name of the lifetime of the reference, if provided.
1551        lifetime: Option<String>,
1552        /// This is `true` for `&mut i32` and `false` for `&i32`
1553        is_mutable: bool,
1554        /// The type of the pointee, e.g. the `i32` in `&'a mut i32`
1555        #[serde(rename = "type")]
1556        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1557        type_: Box<Type>,
1558    },
1559    /// Associated types like `<Type as Trait>::Name` and `T::Item` where
1560    /// `T: Iterator` or inherent associated types like `Struct::Name`.
1561    QualifiedPath {
1562        /// The name of the associated type in the parent type.
1563        ///
1564        /// ```ignore (incomplete expression)
1565        /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1566        /// //                                            ^^^^
1567        /// ```
1568        name: String,
1569        /// The generic arguments provided to the associated type.
1570        ///
1571        /// ```ignore (incomplete expression)
1572        /// <core::slice::IterMut<'static, u32> as BetterIterator>::Item<'static>
1573        /// //                                                          ^^^^^^^^^
1574        /// ```
1575        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1576        args: Option<Box<GenericArgs>>,
1577        /// The type with which this type is associated.
1578        ///
1579        /// ```ignore (incomplete expression)
1580        /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1581        /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1582        /// ```
1583        #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1584        self_type: Box<Type>,
1585        /// `None` iff this is an *inherent* associated type.
1586        #[serde(rename = "trait")]
1587        trait_: Option<Path>,
1588    },
1589}
1590
1591/// A type that has a simple path to it. This is the kind of type of structs, unions, enums, etc.
1592#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1593#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1594#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1595#[cfg_attr(feature = "rkyv_0_8", rkyv(serialize_bounds(
1596    __S: rkyv::ser::Writer + rkyv::ser::Allocator,
1597    __S::Error: rkyv::rancor::Source,
1598)))]
1599#[cfg_attr(feature = "rkyv_0_8", rkyv(deserialize_bounds(
1600    __D::Error: rkyv::rancor::Source,
1601)))]
1602#[cfg_attr(feature = "rkyv_0_8", rkyv(bytecheck(bounds(
1603    __C: rkyv::validation::ArchiveContext,
1604    <__C as rkyv::rancor::Fallible>::Error: rkyv::rancor::Source,
1605))))]
1606pub struct Path {
1607    /// The path of the type.
1608    ///
1609    /// This will be the path that is *used* (not where it is defined), so
1610    /// multiple `Path`s may have different values for this field even if
1611    /// they all refer to the same item. e.g.
1612    ///
1613    /// ```rust
1614    /// pub type Vec1 = std::vec::Vec<i32>; // path: "std::vec::Vec"
1615    /// pub type Vec2 = Vec<i32>; // path: "Vec"
1616    /// pub type Vec3 = std::prelude::v1::Vec<i32>; // path: "std::prelude::v1::Vec"
1617    /// ```
1618    //
1619    // Example tested in ./tests/rustdoc-json/path_name.rs
1620    pub path: String,
1621    /// The ID of the type.
1622    pub id: Id,
1623    /// Generic arguments to the type.
1624    ///
1625    /// ```ignore (incomplete expression)
1626    /// std::borrow::Cow<'static, str>
1627    /// //              ^^^^^^^^^^^^^^
1628    /// ```
1629    #[cfg_attr(feature = "rkyv_0_8", rkyv(omit_bounds))]
1630    pub args: Option<Box<GenericArgs>>,
1631}
1632
1633/// A type that is a function pointer.
1634#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1635#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1636#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1637pub struct FunctionPointer {
1638    /// The signature of the function.
1639    pub sig: FunctionSignature,
1640    /// Used for Higher-Rank Trait Bounds (HRTBs)
1641    ///
1642    /// ```ignore (incomplete expression)
1643    ///    for<'c> fn(val: &'c i32) -> i32
1644    /// // ^^^^^^^
1645    /// ```
1646    pub generic_params: Vec<GenericParamDef>,
1647    /// The core properties of the function, such as the ABI it conforms to, whether it's unsafe, etc.
1648    pub header: FunctionHeader,
1649}
1650
1651/// The signature of a function.
1652#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1653#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1654#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1655pub struct FunctionSignature {
1656    /// List of argument names and their type.
1657    ///
1658    /// Note that not all names will be valid identifiers, as some of
1659    /// them may be patterns.
1660    pub inputs: Vec<(String, Type)>,
1661    /// The output type, if specified.
1662    pub output: Option<Type>,
1663    /// Whether the function accepts an arbitrary amount of trailing arguments the C way.
1664    ///
1665    /// ```ignore (incomplete code)
1666    /// fn printf(fmt: &str, ...);
1667    /// ```
1668    pub is_c_variadic: bool,
1669}
1670
1671/// A `trait` declaration.
1672#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1673#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1674#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1675pub struct Trait {
1676    /// Whether the trait is marked `auto` and is thus implemented automatically
1677    /// for all applicable types.
1678    pub is_auto: bool,
1679    /// Whether the trait is marked as `unsafe`.
1680    pub is_unsafe: bool,
1681    /// Whether the trait is [dyn compatible](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility)[^1].
1682    ///
1683    /// [^1]: Formerly known as "object safe".
1684    pub is_dyn_compatible: bool,
1685    /// Associated [`Item`]s that can/must be implemented by the `impl` blocks.
1686    pub items: Vec<Id>,
1687    /// Information about the type parameters and `where` clauses of the trait.
1688    pub generics: Generics,
1689    /// Constraints that must be met by the implementor of the trait.
1690    pub bounds: Vec<GenericBound>,
1691    /// The implementations of the trait.
1692    pub implementations: Vec<Id>,
1693}
1694
1695/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
1696///
1697/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
1698#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1699#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1700#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1701pub struct TraitAlias {
1702    /// Information about the type parameters and `where` clauses of the alias.
1703    pub generics: Generics,
1704    /// The bounds that are associated with the alias.
1705    pub params: Vec<GenericBound>,
1706}
1707
1708/// An `impl` block.
1709#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1710#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1711#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1712pub struct Impl {
1713    /// Whether this impl is for an unsafe trait.
1714    pub is_unsafe: bool,
1715    /// Information about the impl’s type parameters and `where` clauses.
1716    pub generics: Generics,
1717    /// The list of the names of all the trait methods that weren't mentioned in this impl but
1718    /// were provided by the trait itself.
1719    ///
1720    /// For example, for this impl of the [`PartialEq`] trait:
1721    /// ```rust
1722    /// struct Foo;
1723    ///
1724    /// impl PartialEq for Foo {
1725    ///     fn eq(&self, other: &Self) -> bool { todo!() }
1726    /// }
1727    /// ```
1728    /// This field will be `["ne"]`, as it has a default implementation defined for it.
1729    pub provided_trait_methods: Vec<String>,
1730    /// The trait being implemented or `None` if the impl is inherent, which means
1731    /// `impl Struct {}` as opposed to `impl Trait for Struct {}`.
1732    #[serde(rename = "trait")]
1733    pub trait_: Option<Path>,
1734    /// The type that the impl block is for.
1735    #[serde(rename = "for")]
1736    pub for_: Type,
1737    /// The list of associated items contained in this impl block.
1738    pub items: Vec<Id>,
1739    /// Whether this is a negative impl (e.g. `!Sized` or `!Send`).
1740    pub is_negative: bool,
1741    /// Whether this is an impl that’s implied by the compiler
1742    /// (for autotraits, e.g. `Send` or `Sync`).
1743    pub is_synthetic: bool,
1744    // FIXME: document this
1745    pub blanket_impl: Option<Type>,
1746}
1747
1748/// A `use` statement.
1749#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1750#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1751#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1752#[serde(rename_all = "snake_case")]
1753pub struct Use {
1754    /// The full path being imported.
1755    pub source: String,
1756    /// May be different from the last segment of `source` when renaming imports:
1757    /// `use source as name;`
1758    pub name: String,
1759    /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
1760    /// ```rust
1761    /// pub use i32 as my_i32;
1762    /// ```
1763    pub id: Option<Id>,
1764    /// Whether this statement is a wildcard `use`, e.g. `use source::*;`
1765    pub is_glob: bool,
1766}
1767
1768/// A procedural macro.
1769#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1770#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1771#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1772pub struct ProcMacro {
1773    /// How this macro is supposed to be called: `foo!()`, `#[foo]` or `#[derive(foo)]`
1774    pub kind: MacroKind,
1775    /// Helper attributes defined by a macro to be used inside it.
1776    ///
1777    /// Defined only for derive macros.
1778    ///
1779    /// E.g. the [`Default`] derive macro defines a `#[default]` helper attribute so that one can
1780    /// do:
1781    ///
1782    /// ```rust
1783    /// #[derive(Default)]
1784    /// enum Option<T> {
1785    ///     #[default]
1786    ///     None,
1787    ///     Some(T),
1788    /// }
1789    /// ```
1790    pub helpers: Vec<String>,
1791}
1792
1793/// The way a [`ProcMacro`] is declared to be used.
1794#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1795#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1796#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1797#[serde(rename_all = "snake_case")]
1798pub enum MacroKind {
1799    /// A bang macro `foo!()`.
1800    Bang,
1801    /// An attribute macro `#[foo]`.
1802    Attr,
1803    /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
1804    Derive,
1805}
1806
1807/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
1808#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1809#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1810#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1811pub struct TypeAlias {
1812    /// The type referred to by this alias.
1813    #[serde(rename = "type")]
1814    pub type_: Type,
1815    /// Information about the type parameters and `where` clauses of the alias.
1816    pub generics: Generics,
1817}
1818
1819/// A `static` declaration.
1820#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1821#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1822#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1823pub struct Static {
1824    /// The type of the static.
1825    #[serde(rename = "type")]
1826    pub type_: Type,
1827    /// This is `true` for mutable statics, declared as `static mut X: T = f();`
1828    pub is_mutable: bool,
1829    /// The stringified expression for the initial value.
1830    ///
1831    /// It's not guaranteed that it'll match the actual source code for the initial value.
1832    pub expr: String,
1833
1834    /// Is the static `unsafe`?
1835    ///
1836    /// This is only true if it's in an `extern` block, and not explicitly marked
1837    /// as `safe`.
1838    ///
1839    /// ```rust
1840    /// unsafe extern {
1841    ///     static A: i32;      // unsafe
1842    ///     safe static B: i32; // safe
1843    /// }
1844    ///
1845    /// static C: i32 = 0;     // safe
1846    /// static mut D: i32 = 0; // safe
1847    /// ```
1848    pub is_unsafe: bool,
1849}
1850
1851/// A primitive type declaration. Declarations of this kind can only come from the core library.
1852#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1853#[cfg_attr(feature = "rkyv_0_8", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
1854#[cfg_attr(feature = "rkyv_0_8", rkyv(derive(Debug)))]
1855pub struct Primitive {
1856    /// The name of the type.
1857    pub name: String,
1858    /// The implementations, inherent and of traits, on the primitive type.
1859    pub impls: Vec<Id>,
1860}
1861
1862#[cfg(test)]
1863mod tests;