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