rustdoc_types/
lib.rs

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