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