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 `ItemKind::Attribute`.
40pub const FORMAT_VERSION: u32 = 56;
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    /// An attribute declaration.
555    ///
556    /// [`Item`]s of this kind only come from the core library and exist solely
557    /// to carry documentation for the respective builtin attributes.
558    Attribute,
559}
560
561/// Specific fields of an item.
562///
563/// Part of [`Item`].
564#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
565#[serde(rename_all = "snake_case")]
566pub enum ItemEnum {
567    /// A module declaration, e.g. `mod foo;` or `mod foo {}`
568    Module(Module),
569    /// A crate imported via the `extern crate` syntax.
570    ExternCrate {
571        /// The name of the imported crate.
572        name: String,
573        /// If the crate is renamed, this is its name in the crate.
574        rename: Option<String>,
575    },
576    /// An import of 1 or more items into scope, using the `use` keyword.
577    Use(Use),
578
579    /// A `union` declaration.
580    Union(Union),
581    /// A `struct` declaration.
582    Struct(Struct),
583    /// A field of a struct.
584    StructField(Type),
585    /// An `enum` declaration.
586    Enum(Enum),
587    /// A variant of a enum.
588    Variant(Variant),
589
590    /// A function declaration (including methods and other associated functions)
591    Function(Function),
592
593    /// A `trait` declaration.
594    Trait(Trait),
595    /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
596    ///
597    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
598    TraitAlias(TraitAlias),
599    /// An `impl` block.
600    Impl(Impl),
601
602    /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
603    TypeAlias(TypeAlias),
604    /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
605    Constant {
606        /// The type of the constant.
607        #[serde(rename = "type")]
608        type_: Type,
609        /// The declared constant itself.
610        #[serde(rename = "const")]
611        const_: Constant,
612    },
613
614    /// A declaration of a `static`.
615    Static(Static),
616
617    /// `type`s from an `extern` block.
618    ///
619    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
620    ExternType,
621
622    /// A macro_rules! declarative macro. Contains a single string with the source
623    /// representation of the macro with the patterns stripped.
624    Macro(String),
625    /// A procedural macro.
626    ProcMacro(ProcMacro),
627
628    /// A primitive type, e.g. `u32`.
629    ///
630    /// [`Item`]s of this kind only come from the core library.
631    Primitive(Primitive),
632
633    /// An associated constant of a trait or a type.
634    AssocConst {
635        /// The type of the constant.
636        #[serde(rename = "type")]
637        type_: Type,
638        /// Inside a trait declaration, this is the default value for the associated constant,
639        /// if provided.
640        /// Inside an `impl` block, this is the value assigned to the associated constant,
641        /// and will always be present.
642        ///
643        /// The representation is implementation-defined and not guaranteed to be representative of
644        /// either the resulting value or of the source code.
645        ///
646        /// ```rust
647        /// const X: usize = 640 * 1024;
648        /// //               ^^^^^^^^^^
649        /// ```
650        value: Option<String>,
651    },
652    /// An associated type of a trait or a type.
653    AssocType {
654        /// The generic parameters and where clauses on ahis associated type.
655        generics: Generics,
656        /// The bounds for this associated type. e.g.
657        /// ```rust
658        /// trait IntoIterator {
659        ///     type Item;
660        ///     type IntoIter: Iterator<Item = Self::Item>;
661        /// //                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
662        /// }
663        /// ```
664        bounds: Vec<GenericBound>,
665        /// Inside a trait declaration, this is the default for the associated type, if provided.
666        /// Inside an impl block, this is the type assigned to the associated type, and will always
667        /// be present.
668        ///
669        /// ```rust
670        /// type X = usize;
671        /// //       ^^^^^
672        /// ```
673        #[serde(rename = "type")]
674        type_: Option<Type>,
675    },
676}
677
678/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
679#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
680pub struct Module {
681    /// Whether this is the root item of a crate.
682    ///
683    /// This item doesn't correspond to any construction in the source code and is generated by the
684    /// compiler.
685    pub is_crate: bool,
686    /// [`Item`]s declared inside this module.
687    pub items: Vec<Id>,
688    /// If `true`, this module is not part of the public API, but it contains
689    /// items that are re-exported as public API.
690    pub is_stripped: bool,
691}
692
693/// A `union`.
694#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
695pub struct Union {
696    /// The generic parameters and where clauses on this union.
697    pub generics: Generics,
698    /// Whether any fields have been removed from the result, due to being private or hidden.
699    pub has_stripped_fields: bool,
700    /// The list of fields in the union.
701    ///
702    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
703    pub fields: Vec<Id>,
704    /// All impls (both of traits and inherent) for this union.
705    ///
706    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
707    pub impls: Vec<Id>,
708}
709
710/// A `struct`.
711#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
712pub struct Struct {
713    /// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
714    /// i.e. fields.
715    pub kind: StructKind,
716    /// The generic parameters and where clauses on this struct.
717    pub generics: Generics,
718    /// All impls (both of traits and inherent) for this struct.
719    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
720    pub impls: Vec<Id>,
721}
722
723/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
724#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
725#[serde(rename_all = "snake_case")]
726pub enum StructKind {
727    /// A struct with no fields and no parentheses.
728    ///
729    /// ```rust
730    /// pub struct Unit;
731    /// ```
732    Unit,
733    /// A struct with unnamed fields.
734    ///
735    /// All [`Id`]'s will point to [`ItemEnum::StructField`].
736    /// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
737    /// instead of being omitted, because order matters.
738    ///
739    /// ```rust
740    /// pub struct TupleStruct(i32);
741    /// pub struct EmptyTupleStruct();
742    /// ```
743    Tuple(Vec<Option<Id>>),
744    /// A struct with named fields.
745    ///
746    /// ```rust
747    /// pub struct PlainStruct { x: i32 }
748    /// pub struct EmptyPlainStruct {}
749    /// ```
750    Plain {
751        /// The list of fields in the struct.
752        ///
753        /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
754        fields: Vec<Id>,
755        /// Whether any fields have been removed from the result, due to being private or hidden.
756        has_stripped_fields: bool,
757    },
758}
759
760/// An `enum`.
761#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
762pub struct Enum {
763    /// Information about the type parameters and `where` clauses of the enum.
764    pub generics: Generics,
765    /// Whether any variants have been removed from the result, due to being private or hidden.
766    pub has_stripped_variants: bool,
767    /// The list of variants in the enum.
768    ///
769    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
770    pub variants: Vec<Id>,
771    /// `impl`s for the enum.
772    pub impls: Vec<Id>,
773}
774
775/// A variant of an enum.
776#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
777pub struct Variant {
778    /// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
779    pub kind: VariantKind,
780    /// The discriminant, if explicitly specified.
781    pub discriminant: Option<Discriminant>,
782}
783
784/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
785#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
786#[serde(rename_all = "snake_case")]
787pub enum VariantKind {
788    /// A variant with no parentheses
789    ///
790    /// ```rust
791    /// enum Demo {
792    ///     PlainVariant,
793    ///     PlainWithDiscriminant = 1,
794    /// }
795    /// ```
796    Plain,
797    /// A variant with unnamed fields.
798    ///
799    /// All [`Id`]'s will point to [`ItemEnum::StructField`].
800    /// Unlike most of JSON, `#[doc(hidden)]` fields will be given as `None`
801    /// instead of being omitted, because order matters.
802    ///
803    /// ```rust
804    /// enum Demo {
805    ///     TupleVariant(i32),
806    ///     EmptyTupleVariant(),
807    /// }
808    /// ```
809    Tuple(Vec<Option<Id>>),
810    /// A variant with named fields.
811    ///
812    /// ```rust
813    /// enum Demo {
814    ///     StructVariant { x: i32 },
815    ///     EmptyStructVariant {},
816    /// }
817    /// ```
818    Struct {
819        /// The list of variants in the enum.
820        /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`].
821        fields: Vec<Id>,
822        /// Whether any variants have been removed from the result, due to being private or hidden.
823        has_stripped_fields: bool,
824    },
825}
826
827/// The value that distinguishes a variant in an [`Enum`] from other variants.
828#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
829pub struct Discriminant {
830    /// The expression that produced the discriminant.
831    ///
832    /// Unlike `value`, this preserves the original formatting (eg suffixes,
833    /// hexadecimal, and underscores), making it unsuitable to be machine
834    /// interpreted.
835    ///
836    /// In some cases, when the value is too complex, this may be `"{ _ }"`.
837    /// When this occurs is unstable, and may change without notice.
838    pub expr: String,
839    /// The numerical value of the discriminant. Stored as a string due to
840    /// JSON's poor support for large integers, and the fact that it would need
841    /// to store from [`i128::MIN`] to [`u128::MAX`].
842    pub value: String,
843}
844
845/// A set of fundamental properties of a function.
846#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
847pub struct FunctionHeader {
848    /// Is this function marked as `const`?
849    pub is_const: bool,
850    /// Is this function unsafe?
851    pub is_unsafe: bool,
852    /// Is this function async?
853    pub is_async: bool,
854    /// The ABI used by the function.
855    pub abi: Abi,
856}
857
858/// The ABI (Application Binary Interface) used by a function.
859///
860/// If a variant has an `unwind` field, this means the ABI that it represents can be specified in 2
861/// ways: `extern "_"` and `extern "_-unwind"`, and a value of `true` for that field signifies the
862/// latter variant.
863///
864/// See the [Rustonomicon section](https://doc.rust-lang.org/nightly/nomicon/ffi.html#ffi-and-unwinding)
865/// on unwinding for more info.
866#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
867pub enum Abi {
868    // We only have a concrete listing here for stable ABI's because there are so many
869    // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
870    /// The default ABI, but that can also be written explicitly with `extern "Rust"`.
871    Rust,
872    /// Can be specified as `extern "C"` or, as a shorthand, just `extern`.
873    C { unwind: bool },
874    /// Can be specified as `extern "cdecl"`.
875    Cdecl { unwind: bool },
876    /// Can be specified as `extern "stdcall"`.
877    Stdcall { unwind: bool },
878    /// Can be specified as `extern "fastcall"`.
879    Fastcall { unwind: bool },
880    /// Can be specified as `extern "aapcs"`.
881    Aapcs { unwind: bool },
882    /// Can be specified as `extern "win64"`.
883    Win64 { unwind: bool },
884    /// Can be specified as `extern "sysv64"`.
885    SysV64 { unwind: bool },
886    /// Can be specified as `extern "system"`.
887    System { unwind: bool },
888    /// Any other ABI, including unstable ones.
889    Other(String),
890}
891
892/// A function declaration (including methods and other associated functions).
893#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
894pub struct Function {
895    /// Information about the function signature, or declaration.
896    pub sig: FunctionSignature,
897    /// Information about the function’s type parameters and `where` clauses.
898    pub generics: Generics,
899    /// Information about core properties of the function, e.g. whether it's `const`, its ABI, etc.
900    pub header: FunctionHeader,
901    /// Whether the function has a body, i.e. an implementation.
902    pub has_body: bool,
903}
904
905/// Generic parameters accepted by an item and `where` clauses imposed on it and the parameters.
906#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
907pub struct Generics {
908    /// A list of generic parameter definitions (e.g. `<T: Clone + Hash, U: Copy>`).
909    pub params: Vec<GenericParamDef>,
910    /// A list of where predicates (e.g. `where T: Iterator, T::Item: Copy`).
911    pub where_predicates: Vec<WherePredicate>,
912}
913
914/// One generic parameter accepted by an item.
915#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
916pub struct GenericParamDef {
917    /// Name of the parameter.
918    /// ```rust
919    /// fn f<'resource, Resource>(x: &'resource Resource) {}
920    /// //    ^^^^^^^^  ^^^^^^^^
921    /// ```
922    pub name: String,
923    /// The kind of the parameter and data specific to a particular parameter kind, e.g. type
924    /// bounds.
925    pub kind: GenericParamDefKind,
926}
927
928/// The kind of a [`GenericParamDef`].
929#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
930#[serde(rename_all = "snake_case")]
931pub enum GenericParamDefKind {
932    /// Denotes a lifetime parameter.
933    Lifetime {
934        /// Lifetimes that this lifetime parameter is required to outlive.
935        ///
936        /// ```rust
937        /// fn f<'a, 'b, 'resource: 'a + 'b>(a: &'a str, b: &'b str, res: &'resource str) {}
938        /// //                      ^^^^^^^
939        /// ```
940        outlives: Vec<String>,
941    },
942
943    /// Denotes a type parameter.
944    Type {
945        /// Bounds applied directly to the type. Note that the bounds from `where` clauses
946        /// that constrain this parameter won't appear here.
947        ///
948        /// ```rust
949        /// fn default2<T: Default>() -> [T; 2] where T: Clone { todo!() }
950        /// //             ^^^^^^^
951        /// ```
952        bounds: Vec<GenericBound>,
953        /// The default type for this parameter, if provided, e.g.
954        ///
955        /// ```rust
956        /// trait PartialEq<Rhs = Self> {}
957        /// //                    ^^^^
958        /// ```
959        default: Option<Type>,
960        /// This is normally `false`, which means that this generic parameter is
961        /// declared in the Rust source text.
962        ///
963        /// If it is `true`, this generic parameter has been introduced by the
964        /// compiler behind the scenes.
965        ///
966        /// # Example
967        ///
968        /// Consider
969        ///
970        /// ```ignore (pseudo-rust)
971        /// pub fn f(_: impl Trait) {}
972        /// ```
973        ///
974        /// The compiler will transform this behind the scenes to
975        ///
976        /// ```ignore (pseudo-rust)
977        /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
978        /// ```
979        ///
980        /// In this example, the generic parameter named `impl Trait` (and which
981        /// is bound by `Trait`) is synthetic, because it was not originally in
982        /// the Rust source text.
983        is_synthetic: bool,
984    },
985
986    /// Denotes a constant parameter.
987    Const {
988        /// The type of the constant as declared.
989        #[serde(rename = "type")]
990        type_: Type,
991        /// The stringified expression for the default value, if provided. It's not guaranteed that
992        /// it'll match the actual source code for the default value.
993        default: Option<String>,
994    },
995}
996
997/// One `where` clause.
998/// ```rust
999/// fn default<T>() -> T where T: Default { T::default() }
1000/// //                         ^^^^^^^^^^
1001/// ```
1002#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1003#[serde(rename_all = "snake_case")]
1004pub enum WherePredicate {
1005    /// A type is expected to comply with a set of bounds
1006    BoundPredicate {
1007        /// The type that's being constrained.
1008        ///
1009        /// ```rust
1010        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1011        /// //                              ^
1012        /// ```
1013        #[serde(rename = "type")]
1014        type_: Type,
1015        /// The set of bounds that constrain the type.
1016        ///
1017        /// ```rust
1018        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1019        /// //                                 ^^^^^^^^
1020        /// ```
1021        bounds: Vec<GenericBound>,
1022        /// Used for Higher-Rank Trait Bounds (HRTBs)
1023        /// ```rust
1024        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1025        /// //                  ^^^^^^^
1026        /// ```
1027        generic_params: Vec<GenericParamDef>,
1028    },
1029
1030    /// A lifetime is expected to outlive other lifetimes.
1031    LifetimePredicate {
1032        /// The name of the lifetime.
1033        lifetime: String,
1034        /// The lifetimes that must be encompassed by the lifetime.
1035        outlives: Vec<String>,
1036    },
1037
1038    /// A type must exactly equal another type.
1039    EqPredicate {
1040        /// The left side of the equation.
1041        lhs: Type,
1042        /// The right side of the equation.
1043        rhs: Term,
1044    },
1045}
1046
1047/// Either a trait bound or a lifetime bound.
1048#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1049#[serde(rename_all = "snake_case")]
1050pub enum GenericBound {
1051    /// A trait bound.
1052    TraitBound {
1053        /// The full path to the trait.
1054        #[serde(rename = "trait")]
1055        trait_: Path,
1056        /// Used for Higher-Rank Trait Bounds (HRTBs)
1057        /// ```text
1058        /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
1059        ///          ^^^^^^^^^^^
1060        ///          |
1061        ///          this part
1062        /// ```
1063        generic_params: Vec<GenericParamDef>,
1064        /// The context for which a trait is supposed to be used, e.g. `const
1065        modifier: TraitBoundModifier,
1066    },
1067    /// A lifetime bound, e.g.
1068    /// ```rust
1069    /// fn f<'a, T>(x: &'a str, y: &T) where T: 'a {}
1070    /// //                                     ^^^
1071    /// ```
1072    Outlives(String),
1073    /// `use<'a, T>` precise-capturing bound syntax
1074    Use(Vec<PreciseCapturingArg>),
1075}
1076
1077/// A set of modifiers applied to a trait.
1078#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1079#[serde(rename_all = "snake_case")]
1080pub enum TraitBoundModifier {
1081    /// Marks the absence of a modifier.
1082    None,
1083    /// Indicates that the trait bound relaxes a trait bound applied to a parameter by default,
1084    /// e.g. `T: Sized?`, the `Sized` trait is required for all generic type parameters by default
1085    /// unless specified otherwise with this modifier.
1086    Maybe,
1087    /// Indicates that the trait bound must be applicable in both a run-time and a compile-time
1088    /// context.
1089    MaybeConst,
1090}
1091
1092/// One precise capturing argument. See [the rust reference](https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing).
1093#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1094#[serde(rename_all = "snake_case")]
1095pub enum PreciseCapturingArg {
1096    /// A lifetime.
1097    /// ```rust
1098    /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1099    /// //                                                        ^^
1100    Lifetime(String),
1101    /// A type or constant parameter.
1102    /// ```rust
1103    /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1104    /// //                                                            ^  ^
1105    Param(String),
1106}
1107
1108/// Either a type or a constant, usually stored as the right-hand side of an equation in places like
1109/// [`AssocItemConstraint`]
1110#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1111#[serde(rename_all = "snake_case")]
1112pub enum Term {
1113    /// A type.
1114    ///
1115    /// ```rust
1116    /// fn f(x: impl IntoIterator<Item = u32>) {}
1117    /// //                               ^^^
1118    /// ```
1119    Type(Type),
1120    /// A constant.
1121    ///
1122    /// ```ignore (incomplete feature in the snippet)
1123    /// trait Foo {
1124    ///     const BAR: usize;
1125    /// }
1126    ///
1127    /// fn f(x: impl Foo<BAR = 42>) {}
1128    /// //                     ^^
1129    /// ```
1130    Constant(Constant),
1131}
1132
1133/// A type.
1134#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1135#[serde(rename_all = "snake_case")]
1136pub enum Type {
1137    /// Structs, enums, unions and type aliases, e.g. `std::option::Option<u32>`
1138    ResolvedPath(Path),
1139    /// Dynamic trait object type (`dyn Trait`).
1140    DynTrait(DynTrait),
1141    /// Parameterized types. The contained string is the name of the parameter.
1142    Generic(String),
1143    /// Built-in numeric types (e.g. `u32`, `f32`), `bool`, `char`.
1144    Primitive(String),
1145    /// A function pointer type, e.g. `fn(u32) -> u32`, `extern "C" fn() -> *const u8`
1146    FunctionPointer(Box<FunctionPointer>),
1147    /// A tuple type, e.g. `(String, u32, Box<usize>)`
1148    Tuple(Vec<Type>),
1149    /// An unsized slice type, e.g. `[u32]`.
1150    Slice(Box<Type>),
1151    /// An array type, e.g. `[u32; 15]`
1152    Array {
1153        /// The type of the contained element.
1154        #[serde(rename = "type")]
1155        type_: Box<Type>,
1156        /// The stringified expression that is the length of the array.
1157        ///
1158        /// Keep in mind that it's not guaranteed to match the actual source code of the expression.
1159        len: String,
1160    },
1161    /// A pattern type, e.g. `u32 is 1..`
1162    ///
1163    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/123646)
1164    Pat {
1165        /// The base type, e.g. the `u32` in `u32 is 1..`
1166        #[serde(rename = "type")]
1167        type_: Box<Type>,
1168        #[doc(hidden)]
1169        __pat_unstable_do_not_use: String,
1170    },
1171    /// An opaque type that satisfies a set of bounds, `impl TraitA + TraitB + ...`
1172    ImplTrait(Vec<GenericBound>),
1173    /// A type that's left to be inferred, `_`
1174    Infer,
1175    /// A raw pointer type, e.g. `*mut u32`, `*const u8`, etc.
1176    RawPointer {
1177        /// This is `true` for `*mut _` and `false` for `*const _`.
1178        is_mutable: bool,
1179        /// The type of the pointee.
1180        #[serde(rename = "type")]
1181        type_: Box<Type>,
1182    },
1183    /// `&'a mut String`, `&str`, etc.
1184    BorrowedRef {
1185        /// The name of the lifetime of the reference, if provided.
1186        lifetime: Option<String>,
1187        /// This is `true` for `&mut i32` and `false` for `&i32`
1188        is_mutable: bool,
1189        /// The type of the pointee, e.g. the `i32` in `&'a mut i32`
1190        #[serde(rename = "type")]
1191        type_: Box<Type>,
1192    },
1193    /// Associated types like `<Type as Trait>::Name` and `T::Item` where
1194    /// `T: Iterator` or inherent associated types like `Struct::Name`.
1195    QualifiedPath {
1196        /// The name of the associated type in the parent type.
1197        ///
1198        /// ```ignore (incomplete expression)
1199        /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1200        /// //                                            ^^^^
1201        /// ```
1202        name: String,
1203        /// The generic arguments provided to the associated type.
1204        ///
1205        /// ```ignore (incomplete expression)
1206        /// <core::slice::IterMut<'static, u32> as BetterIterator>::Item<'static>
1207        /// //                                                          ^^^^^^^^^
1208        /// ```
1209        args: Option<Box<GenericArgs>>,
1210        /// The type with which this type is associated.
1211        ///
1212        /// ```ignore (incomplete expression)
1213        /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1214        /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1215        /// ```
1216        self_type: Box<Type>,
1217        /// `None` iff this is an *inherent* associated type.
1218        #[serde(rename = "trait")]
1219        trait_: Option<Path>,
1220    },
1221}
1222
1223/// A type that has a simple path to it. This is the kind of type of structs, unions, enums, etc.
1224#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1225pub struct Path {
1226    /// The path of the type.
1227    ///
1228    /// This will be the path that is *used* (not where it is defined), so
1229    /// multiple `Path`s may have different values for this field even if
1230    /// they all refer to the same item. e.g.
1231    ///
1232    /// ```rust
1233    /// pub type Vec1 = std::vec::Vec<i32>; // path: "std::vec::Vec"
1234    /// pub type Vec2 = Vec<i32>; // path: "Vec"
1235    /// pub type Vec3 = std::prelude::v1::Vec<i32>; // path: "std::prelude::v1::Vec"
1236    /// ```
1237    //
1238    // Example tested in ./tests/rustdoc-json/path_name.rs
1239    pub path: String,
1240    /// The ID of the type.
1241    pub id: Id,
1242    /// Generic arguments to the type.
1243    ///
1244    /// ```ignore (incomplete expression)
1245    /// std::borrow::Cow<'static, str>
1246    /// //              ^^^^^^^^^^^^^^
1247    /// ```
1248    pub args: Option<Box<GenericArgs>>,
1249}
1250
1251/// A type that is a function pointer.
1252#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1253pub struct FunctionPointer {
1254    /// The signature of the function.
1255    pub sig: FunctionSignature,
1256    /// Used for Higher-Rank Trait Bounds (HRTBs)
1257    ///
1258    /// ```ignore (incomplete expression)
1259    ///    for<'c> fn(val: &'c i32) -> i32
1260    /// // ^^^^^^^
1261    /// ```
1262    pub generic_params: Vec<GenericParamDef>,
1263    /// The core properties of the function, such as the ABI it conforms to, whether it's unsafe, etc.
1264    pub header: FunctionHeader,
1265}
1266
1267/// The signature of a function.
1268#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1269pub struct FunctionSignature {
1270    /// List of argument names and their type.
1271    ///
1272    /// Note that not all names will be valid identifiers, as some of
1273    /// them may be patterns.
1274    pub inputs: Vec<(String, Type)>,
1275    /// The output type, if specified.
1276    pub output: Option<Type>,
1277    /// Whether the function accepts an arbitrary amount of trailing arguments the C way.
1278    ///
1279    /// ```ignore (incomplete code)
1280    /// fn printf(fmt: &str, ...);
1281    /// ```
1282    pub is_c_variadic: bool,
1283}
1284
1285/// A `trait` declaration.
1286#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1287pub struct Trait {
1288    /// Whether the trait is marked `auto` and is thus implemented automatically
1289    /// for all applicable types.
1290    pub is_auto: bool,
1291    /// Whether the trait is marked as `unsafe`.
1292    pub is_unsafe: bool,
1293    /// Whether the trait is [dyn compatible](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility)[^1].
1294    ///
1295    /// [^1]: Formerly known as "object safe".
1296    pub is_dyn_compatible: bool,
1297    /// Associated [`Item`]s that can/must be implemented by the `impl` blocks.
1298    pub items: Vec<Id>,
1299    /// Information about the type parameters and `where` clauses of the trait.
1300    pub generics: Generics,
1301    /// Constraints that must be met by the implementor of the trait.
1302    pub bounds: Vec<GenericBound>,
1303    /// The implementations of the trait.
1304    pub implementations: Vec<Id>,
1305}
1306
1307/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
1308///
1309/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
1310#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1311pub struct TraitAlias {
1312    /// Information about the type parameters and `where` clauses of the alias.
1313    pub generics: Generics,
1314    /// The bounds that are associated with the alias.
1315    pub params: Vec<GenericBound>,
1316}
1317
1318/// An `impl` block.
1319#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1320pub struct Impl {
1321    /// Whether this impl is for an unsafe trait.
1322    pub is_unsafe: bool,
1323    /// Information about the impl’s type parameters and `where` clauses.
1324    pub generics: Generics,
1325    /// The list of the names of all the trait methods that weren't mentioned in this impl but
1326    /// were provided by the trait itself.
1327    ///
1328    /// For example, for this impl of the [`PartialEq`] trait:
1329    /// ```rust
1330    /// struct Foo;
1331    ///
1332    /// impl PartialEq for Foo {
1333    ///     fn eq(&self, other: &Self) -> bool { todo!() }
1334    /// }
1335    /// ```
1336    /// This field will be `["ne"]`, as it has a default implementation defined for it.
1337    pub provided_trait_methods: Vec<String>,
1338    /// The trait being implemented or `None` if the impl is inherent, which means
1339    /// `impl Struct {}` as opposed to `impl Trait for Struct {}`.
1340    #[serde(rename = "trait")]
1341    pub trait_: Option<Path>,
1342    /// The type that the impl block is for.
1343    #[serde(rename = "for")]
1344    pub for_: Type,
1345    /// The list of associated items contained in this impl block.
1346    pub items: Vec<Id>,
1347    /// Whether this is a negative impl (e.g. `!Sized` or `!Send`).
1348    pub is_negative: bool,
1349    /// Whether this is an impl that’s implied by the compiler
1350    /// (for autotraits, e.g. `Send` or `Sync`).
1351    pub is_synthetic: bool,
1352    // FIXME: document this
1353    pub blanket_impl: Option<Type>,
1354}
1355
1356/// A `use` statement.
1357#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1358#[serde(rename_all = "snake_case")]
1359pub struct Use {
1360    /// The full path being imported.
1361    pub source: String,
1362    /// May be different from the last segment of `source` when renaming imports:
1363    /// `use source as name;`
1364    pub name: String,
1365    /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
1366    /// ```rust
1367    /// pub use i32 as my_i32;
1368    /// ```
1369    pub id: Option<Id>,
1370    /// Whether this statement is a wildcard `use`, e.g. `use source::*;`
1371    pub is_glob: bool,
1372}
1373
1374/// A procedural macro.
1375#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1376pub struct ProcMacro {
1377    /// How this macro is supposed to be called: `foo!()`, `#[foo]` or `#[derive(foo)]`
1378    pub kind: MacroKind,
1379    /// Helper attributes defined by a macro to be used inside it.
1380    ///
1381    /// Defined only for derive macros.
1382    ///
1383    /// E.g. the [`Default`] derive macro defines a `#[default]` helper attribute so that one can
1384    /// do:
1385    ///
1386    /// ```rust
1387    /// #[derive(Default)]
1388    /// enum Option<T> {
1389    ///     #[default]
1390    ///     None,
1391    ///     Some(T),
1392    /// }
1393    /// ```
1394    pub helpers: Vec<String>,
1395}
1396
1397/// The way a [`ProcMacro`] is declared to be used.
1398#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1399#[serde(rename_all = "snake_case")]
1400pub enum MacroKind {
1401    /// A bang macro `foo!()`.
1402    Bang,
1403    /// An attribute macro `#[foo]`.
1404    Attr,
1405    /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
1406    Derive,
1407}
1408
1409/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
1410#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1411pub struct TypeAlias {
1412    /// The type referred to by this alias.
1413    #[serde(rename = "type")]
1414    pub type_: Type,
1415    /// Information about the type parameters and `where` clauses of the alias.
1416    pub generics: Generics,
1417}
1418
1419/// A `static` declaration.
1420#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1421pub struct Static {
1422    /// The type of the static.
1423    #[serde(rename = "type")]
1424    pub type_: Type,
1425    /// This is `true` for mutable statics, declared as `static mut X: T = f();`
1426    pub is_mutable: bool,
1427    /// The stringified expression for the initial value.
1428    ///
1429    /// It's not guaranteed that it'll match the actual source code for the initial value.
1430    pub expr: String,
1431
1432    /// Is the static `unsafe`?
1433    ///
1434    /// This is only true if it's in an `extern` block, and not explicitly marked
1435    /// as `safe`.
1436    ///
1437    /// ```rust
1438    /// unsafe extern {
1439    ///     static A: i32;      // unsafe
1440    ///     safe static B: i32; // safe
1441    /// }
1442    ///
1443    /// static C: i32 = 0;     // safe
1444    /// static mut D: i32 = 0; // safe
1445    /// ```
1446    pub is_unsafe: bool,
1447}
1448
1449/// A primitive type declaration. Declarations of this kind can only come from the core library.
1450#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1451pub struct Primitive {
1452    /// The name of the type.
1453    pub name: String,
1454    /// The implementations, inherent and of traits, on the primitive type.
1455    pub impls: Vec<Id>,
1456}
1457
1458#[cfg(test)]
1459mod tests;