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