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