rustdoc_json_types/
lib.rs

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