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