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