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