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