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