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