rustdoc_json_types/
lib.rs

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