Skip to main content

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