rustdoc_types/
lib.rs

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