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