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