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