rustdoc_types/
lib.rs

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