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