ruggle_engine/
types.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt::{self, Display};
3use std::path::PathBuf;
4
5use serde::{de, Deserialize, Deserializer, Serialize};
6
7use crate::query::Qualifier;
8
9/// The root of the emitted JSON blob.
10///
11/// It contains all type/documentation information
12/// about the language items in the local crate, as well as info about external items to allow
13/// tools to find or link to them.
14#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Decode, bincode::Encode)]
15pub struct Crate {
16    pub name: Option<String>,
17    /// The id of the root [`Module`] item of the local crate.
18    pub root: Id,
19    /// The version string given to `--crate-version`, if any.
20    #[serde(
21        serialize_with = "crate_version_as_string",
22        deserialize_with = "crate_version_from_string"
23    )]
24    pub crate_version: String, // FIXME: This might cause problems because `rustdoc_types::crate_version` is optional.
25    /// Whether or not the output includes private items.
26    pub includes_private: bool,
27    /// A collection of all items in the local crate as well as some external traits and their
28    /// items that are referenced locally.
29    pub index: HashMap<Id, Item>,
30    /// Maps IDs to fully qualified paths and other info helpful for generating links.
31    pub paths: HashMap<Id, ItemSummary>,
32    /// Maps `crate_id` of items to a crate name and html_root_url if it exists.
33    pub external_crates: HashMap<u32, ExternalCrate>,
34    /// Information about the target for which this documentation was generated
35    pub target: Target,
36    /// A single version number to be used in the future when making backwards incompatible changes
37    /// to the JSON output.
38    pub format_version: u32,
39}
40
41fn crate_version_as_string<S>(version: &String, serializer: S) -> Result<S::Ok, S::Error>
42where
43    S: serde::Serializer,
44{
45    // Serialize the version as an Optional String for compatibility
46    serializer.serialize_some(version)
47}
48fn crate_version_from_string<'de, D>(deserializer: D) -> Result<String, D::Error>
49where
50    D: Deserializer<'de>,
51{
52    // Deserialize the version from an Optional String for compatibility
53    let opt: Option<String> = Option::deserialize(deserializer)?;
54    Ok(opt.unwrap_or("latest".to_string()))
55}
56
57#[derive(Debug, Clone, Deserialize, Serialize, Hash, PartialEq, Eq, PartialOrd, Ord)]
58pub struct CrateMetadata {
59    pub name: String,
60    pub version: String,
61}
62
63impl CrateMetadata {
64    pub fn new(name: String) -> Self {
65        CrateMetadata {
66            name,
67            version: "latest".to_string(),
68        }
69    }
70}
71
72impl std::fmt::Display for CrateMetadata {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        write!(f, "{}:{}", self.name, self.version)
75    }
76}
77
78impl Crate {
79    pub fn crate_metadata(&self) -> CrateMetadata {
80        CrateMetadata {
81            name: self
82                .name
83                .clone()
84                .expect("`.crate_metadata` SHOULD NEVER be called on anonymous crates"),
85            version: self.crate_version.clone(),
86        }
87    }
88}
89
90/// Information about a target
91#[derive(
92    Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default, bincode::Decode, bincode::Encode,
93)]
94pub struct Target {
95    /// The target triple for which this documentation was generated
96    pub triple: String,
97    /// A list of features valid for use in `#[target_feature]` attributes
98    /// for the target where this rustdoc JSON was generated.
99    pub target_features: Vec<TargetFeature>,
100}
101
102/// Information about a target feature.
103///
104/// Rust target features are used to influence code generation, especially around selecting
105/// instructions which are not universally supported by the target architecture.
106///
107/// Target features are commonly enabled by the [`#[target_feature]` attribute][1] to influence code
108/// generation for a particular function, and less commonly enabled by compiler options like
109/// `-Ctarget-feature` or `-Ctarget-cpu`. Targets themselves automatically enable certain target
110/// features by default, for example because the target's ABI specification requires saving specific
111/// registers which only exist in an architectural extension.
112///
113/// Target features can imply other target features: for example, x86-64 `avx2` implies `avx`, and
114/// aarch64 `sve2` implies `sve`, since both of these architectural extensions depend on their
115/// predecessors.
116///
117/// Target features can be probed at compile time by [`#[cfg(target_feature)]`][2] or `cfg!(…)`
118/// conditional compilation to determine whether a target feature is enabled in a particular
119/// context.
120///
121/// [1]: https://doc.rust-lang.org/stable/reference/attributes/codegen.html#the-target_feature-attribute
122/// [2]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature
123#[derive(
124    Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default, bincode::Decode, bincode::Encode,
125)]
126pub struct TargetFeature {
127    /// The name of this target feature.
128    pub name: String,
129    /// Other target features which are implied by this target feature, if any.
130    pub implies_features: Vec<String>,
131    /// If this target feature is unstable, the name of the associated language feature gate.
132    pub unstable_feature_gate: Option<String>,
133    /// Whether this feature is globally enabled for this compilation session.
134    ///
135    /// Target features can be globally enabled implicitly as a result of the target's definition.
136    /// For example, x86-64 hardware floating point ABIs require saving x87 and SSE2 registers,
137    /// which in turn requires globally enabling the `x87` and `sse2` target features so that the
138    /// generated machine code conforms to the target's ABI.
139    ///
140    /// Target features can also be globally enabled explicitly as a result of compiler flags like
141    /// [`-Ctarget-feature`][1] or [`-Ctarget-cpu`][2].
142    ///
143    /// [1]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-feature
144    /// [2]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-cpu
145    pub globally_enabled: bool,
146}
147
148/// Metadata of a crate, either the same crate on which `rustdoc` was invoked, or its dependency.
149#[derive(
150    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
151)]
152pub struct ExternalCrate {
153    /// The name of the crate.
154    ///
155    /// Note: This is the [*crate* name][crate-name], which may not be the same as the
156    /// [*package* name][package-name]. For example, for <https://crates.io/crates/regex-syntax>,
157    /// this field will be `regex_syntax` (which uses an `_`, not a `-`).
158    ///
159    /// [crate-name]: https://doc.rust-lang.org/stable/cargo/reference/cargo-targets.html#the-name-field
160    /// [package-name]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-name-field
161    pub name: String,
162    /// The root URL at which the crate's documentation lives.
163    pub html_root_url: Option<String>,
164}
165
166/// Information about an external (not defined in the local crate) [`Item`].
167///
168/// For external items, you don't get the same level of
169/// information. This struct should contain enough to generate a link/reference to the item in
170/// question, or can be used by a tool that takes the json output of multiple crates to find
171/// the actual item definition with all the relevant info.
172#[derive(
173    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
174)]
175pub struct ItemSummary {
176    /// Can be used to look up the name and html_root_url of the crate this item came from in the
177    /// `external_crates` map.
178    pub crate_id: u32,
179    /// The list of path components for the fully qualified path of this item (e.g.
180    /// `["std", "io", "lazy", "Lazy"]` for `std::io::lazy::Lazy`).
181    ///
182    /// Note that items can appear in multiple paths, and the one chosen is implementation
183    /// defined. Currently, this is the full path to where the item was defined. Eg
184    /// [`String`] is currently `["alloc", "string", "String"]` and [`HashMap`][`std::collections::HashMap`]
185    /// is `["std", "collections", "hash", "map", "HashMap"]`, but this is subject to change.
186    pub path: Vec<String>,
187    /// Whether this item is a struct, trait, macro, etc.
188    pub kind: ItemKind,
189}
190
191/// Anything that can hold documentation - modules, structs, enums, functions, traits, etc.
192///
193/// The `Item` data type holds fields that can apply to any of these,
194/// and leaves kind-specific details (like function args or enum variants) to the `inner` field.
195#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Decode, bincode::Encode)]
196pub struct Item {
197    /// The unique identifier of this item. Can be used to find this item in various mappings.
198    pub id: Id,
199    /// This can be used as a key to the `external_crates` map of [`Crate`] to see which crate
200    /// this item came from.
201    pub crate_id: u32,
202    /// Some items such as impls don't have names.
203    pub name: Option<String>,
204    /// The source location of this item (absent if it came from a macro expansion or inline
205    /// assembly).
206    pub span: Option<Span>,
207    /// By default all documented items are public, but you can tell rustdoc to output private items
208    /// so this field is needed to differentiate.
209    pub visibility: Visibility,
210    /// The full markdown docstring of this item. Absent if there is no documentation at all,
211    /// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
212    pub docs: Option<String>,
213    /// 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
214    pub links: HashMap<String, Id>,
215    /// Attributes on this item.
216    ///
217    /// Does not include `#[deprecated]` attributes: see the [`Self::deprecation`] field instead.
218    ///
219    /// Attributes appear in pretty-printed Rust form, regardless of their formatting
220    /// in the original source code. For example:
221    /// - `#[non_exhaustive]` and `#[must_use]` are represented as themselves.
222    /// - `#[no_mangle]` and `#[export_name]` are also represented as themselves.
223    /// - `#[repr(C)]` and other reprs also appear as themselves,
224    ///   though potentially with a different order: e.g. `repr(i8, C)` may become `repr(C, i8)`.
225    ///   Multiple repr attributes on the same item may be combined into an equivalent single attr.
226    pub attrs: Vec<Attribute>,
227    /// Information about the item’s deprecation, if present.
228    pub deprecation: Option<Deprecation>,
229    /// The type-specific fields describing this item.
230    pub inner: ItemEnum,
231}
232
233impl Display for Item {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        if let Some(name) = &self.name {
236            write!(f, "{} ", name)?;
237        }
238        write!(f, "{}", self.inner)
239    }
240}
241
242#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Decode, bincode::Encode)]
243#[serde(rename_all = "snake_case")]
244/// An attribute, e.g. `#[repr(C)]`
245///
246/// This doesn't include:
247/// - `#[doc = "Doc Comment"]` or `/// Doc comment`. These are in [`Item::docs`] instead.
248/// - `#[deprecated]`. These are in [`Item::deprecation`] instead.
249pub enum Attribute {
250    /// `#[non_exhaustive]`
251    NonExhaustive,
252
253    /// `#[must_use]`
254    MustUse { reason: Option<String> },
255
256    /// `#[macro_export]`
257    MacroExport,
258
259    /// `#[export_name = "name"]`
260    ExportName(String),
261
262    /// `#[link_section = "name"]`
263    LinkSection(String),
264
265    /// `#[automatically_derived]`
266    AutomaticallyDerived,
267
268    /// `#[repr]`
269    Repr(AttributeRepr),
270
271    /// `#[no_mangle]`
272    NoMangle,
273
274    /// #[target_feature(enable = "feature1", enable = "feature2")]
275    TargetFeature { enable: Vec<String> },
276
277    /// Something else.
278    ///
279    /// Things here are explicitly *not* covered by the [`FORMAT_VERSION`]
280    /// constant, and may change without bumping the format version.
281    ///
282    /// As an implementation detail, this is currently either:
283    /// 1. A HIR debug printing, like `"#[attr = Optimize(Speed)]"`
284    /// 2. The attribute as it appears in source form, like
285    ///    `"#[optimize(speed)]"`.
286    Other(String),
287}
288
289#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Decode, bincode::Encode)]
290/// The contents of a `#[repr(...)]` attribute.
291///
292/// Used in [`Attribute::Repr`].
293pub struct AttributeRepr {
294    /// The representation, e.g. `#[repr(C)]`, `#[repr(transparent)]`
295    pub kind: ReprKind,
296
297    /// Alignment in bytes, if explicitly specified by `#[repr(align(...)]`.
298    pub align: Option<u64>,
299    /// Alignment in bytes, if explicitly specified by `#[repr(packed(...)]]`.
300    pub packed: Option<u64>,
301
302    /// The integer type for an enum descriminant, if explicitly specified.
303    ///
304    /// e.g. `"i32"`, for `#[repr(C, i32)]`
305    pub int: Option<String>,
306}
307
308#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bincode::Decode, bincode::Encode)]
309#[serde(rename_all = "snake_case")]
310/// The kind of `#[repr]`.
311///
312/// See [AttributeRepr::kind]`.
313pub enum ReprKind {
314    /// `#[repr(Rust)]`
315    ///
316    /// Also the default.
317    Rust,
318    /// `#[repr(C)]`
319    C,
320    /// `#[repr(transparent)]
321    Transparent,
322    /// `#[repr(simd)]`
323    Simd,
324}
325
326/// A range of source code.
327#[derive(
328    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
329)]
330pub struct Span {
331    /// The path to the source file for this span relative to the path `rustdoc` was invoked with.
332    pub filename: PathBuf,
333    /// One indexed Line and Column of the first character of the `Span`.
334    pub begin: (usize, usize),
335    /// One indexed Line and Column of the last character of the `Span`.
336    pub end: (usize, usize),
337}
338
339/// Information about the deprecation of an [`Item`].
340#[derive(
341    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
342)]
343pub struct Deprecation {
344    /// Usually a version number when this [`Item`] first became deprecated.
345    pub since: Option<String>,
346    /// The reason for deprecation and/or what alternatives to use.
347    pub note: Option<String>,
348}
349
350/// Visibility of an [`Item`].
351#[derive(
352    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
353)]
354#[serde(rename_all = "snake_case")]
355pub enum Visibility {
356    /// Explicitly public visibility set with `pub`.
357    Public,
358    /// For the most part items are private by default. The exceptions are associated items of
359    /// public traits and variants of public enums.
360    Default,
361    /// Explicitly crate-wide visibility set with `pub(crate)`
362    Crate,
363    /// For `pub(in path)` visibility.
364    Restricted {
365        /// ID of the module to which this visibility restricts items.
366        parent: Id,
367        /// The path with which [`parent`] was referenced
368        /// (like `super::super` or `crate::foo::bar`).
369        ///
370        /// [`parent`]: Visibility::Restricted::parent
371        path: String,
372    },
373}
374
375/// Dynamic trait object type (`dyn Trait`).
376#[derive(
377    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
378)]
379pub struct DynTrait {
380    /// All the traits implemented. One of them is the vtable, and the rest must be auto traits.
381    pub traits: Vec<PolyTrait>,
382    /// The lifetime of the whole dyn object
383    /// ```text
384    /// dyn Debug + 'static
385    ///             ^^^^^^^
386    ///             |
387    ///             this part
388    /// ```
389    pub lifetime: Option<String>,
390}
391
392/// A trait and potential HRTBs
393#[derive(
394    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
395)]
396pub struct PolyTrait {
397    /// The path to the trait.
398    #[serde(rename = "trait")]
399    pub trait_: Path,
400    /// Used for Higher-Rank Trait Bounds (HRTBs)
401    /// ```text
402    /// dyn for<'a> Fn() -> &'a i32"
403    ///     ^^^^^^^
404    /// ```
405    pub generic_params: Vec<GenericParamDef>,
406}
407
408/// A set of generic arguments provided to a path segment, e.g.
409///
410/// ```text
411/// std::option::Option<u32>
412///                    ^^^^^
413/// ```
414#[derive(
415    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
416)]
417#[serde(rename_all = "snake_case")]
418pub enum GenericArgs {
419    /// `<'a, 32, B: Copy, C = u32>`
420    AngleBracketed {
421        /// The list of each argument on this type.
422        /// ```text
423        /// <'a, 32, B: Copy, C = u32>
424        ///  ^^^^^^
425        /// ```
426        args: Vec<GenericArg>,
427        /// Associated type or constant bindings (e.g. `Item=i32` or `Item: Clone`) for this type.
428        constraints: Vec<AssocItemConstraint>,
429    },
430    /// `Fn(A, B) -> C`
431    Parenthesized {
432        /// The input types, enclosed in parentheses.
433        inputs: Vec<Type>,
434        /// The output type provided after the `->`, if present.
435        output: Option<Type>,
436    },
437    /// `T::method(..)`
438    ReturnTypeNotation,
439}
440
441impl Display for GenericArgs {
442    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
443        match self {
444            GenericArgs::AngleBracketed { args, constraints } => {
445                write!(f, "<")?;
446                for (i, arg) in args.iter().enumerate() {
447                    if i > 0 {
448                        write!(f, ", ")?;
449                    }
450                    write!(f, "{}", arg)?;
451                }
452                for constraint in constraints {
453                    write!(f, ", {} ", constraint.name)?;
454                    match &constraint.binding {
455                        AssocItemConstraintKind::Equality(term) => {
456                            write!(f, "= {}", term)?;
457                        }
458                        AssocItemConstraintKind::Constraint(bounds) => {
459                            write!(f, ": ")?;
460                            for (i, bound) in bounds.iter().enumerate() {
461                                if i > 0 {
462                                    write!(f, " + ")?;
463                                }
464                                write!(f, "{}", bound)?;
465                            }
466                        }
467                    }
468                }
469                write!(f, ">")
470            }
471            GenericArgs::Parenthesized { inputs, output } => {
472                write!(f, "(")?;
473                for (i, input) in inputs.iter().enumerate() {
474                    if i > 0 {
475                        write!(f, ", ")?;
476                    }
477                    write!(f, "{}", input)?;
478                }
479                write!(f, ")")?;
480                if let Some(output) = output {
481                    write!(f, " -> {}", output)?;
482                }
483                Ok(())
484            }
485            GenericArgs::ReturnTypeNotation => write!(f, "..."),
486        }
487    }
488}
489
490/// One argument in a list of generic arguments to a path segment.
491///
492/// Part of [`GenericArgs`].
493#[derive(
494    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
495)]
496#[serde(rename_all = "snake_case")]
497pub enum GenericArg {
498    /// A lifetime argument.
499    /// ```text
500    /// std::borrow::Cow<'static, str>
501    ///                  ^^^^^^^
502    /// ```
503    Lifetime(String),
504    /// A type argument.
505    /// ```text
506    /// std::borrow::Cow<'static, str>
507    ///                           ^^^
508    /// ```
509    Type(Type),
510    /// A constant as a generic argument.
511    /// ```text
512    /// core::array::IntoIter<u32, { 640 * 1024 }>
513    ///                            ^^^^^^^^^^^^^^
514    /// ```
515    Const(Constant),
516    /// A generic argument that's explicitly set to be inferred.
517    /// ```text
518    /// std::vec::Vec::<_>
519    ///                 ^
520    /// ```
521    Infer,
522}
523
524impl Display for GenericArg {
525    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526        match self {
527            GenericArg::Lifetime(l) => write!(f, "{}", l),
528            GenericArg::Type(t) => write!(f, "{}", t),
529            GenericArg::Const(c) => write!(f, "{}", c),
530            GenericArg::Infer => write!(f, "_"),
531        }
532    }
533}
534
535/// A constant.
536#[derive(
537    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
538)]
539pub struct Constant {
540    /// The stringified expression of this constant. Note that its mapping to the original
541    /// source code is unstable and it's not guaranteed that it'll match the source code.
542    pub expr: String,
543    /// The value of the evaluated expression for this constant, which is only computed for numeric
544    /// types.
545    pub value: Option<String>,
546    /// Whether this constant is a bool, numeric, string, or char literal.
547    pub is_literal: bool,
548}
549
550impl Display for Constant {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        write!(f, "{}", self.expr)
553    }
554}
555
556/// Describes a bound applied to an associated type/constant.
557///
558/// Example:
559/// ```text
560/// IntoIterator<Item = u32, IntoIter: Clone>
561///              ^^^^^^^^^^  ^^^^^^^^^^^^^^^
562/// ```
563#[derive(
564    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
565)]
566pub struct AssocItemConstraint {
567    /// The name of the associated type/constant.
568    pub name: String,
569    /// Arguments provided to the associated type/constant.
570    pub args: Option<Box<GenericArgs>>,
571    /// The kind of bound applied to the associated type/constant.
572    pub binding: AssocItemConstraintKind,
573}
574
575/// The way in which an associate type/constant is bound.
576#[derive(
577    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
578)]
579#[serde(rename_all = "snake_case")]
580pub enum AssocItemConstraintKind {
581    /// The required value/type is specified exactly. e.g.
582    /// ```text
583    /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
584    ///          ^^^^^^^^^^
585    /// ```
586    Equality(Term),
587    /// The type is required to satisfy a set of bounds.
588    /// ```text
589    /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
590    ///                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
591    /// ```
592    Constraint(Vec<GenericBound>),
593}
594
595/// An opaque identifier for an item.
596///
597/// It can be used to lookup in [`Crate::index`] or [`Crate::paths`] to resolve it
598/// to an [`Item`].
599///
600/// Id's are only valid within a single JSON blob. They cannot be used to
601/// resolve references between the JSON output's for different crates.
602///
603/// Rustdoc makes no guarantees about the inner value of Id's. Applications
604/// should treat them as opaque keys to lookup items, and avoid attempting
605/// to parse them, or otherwise depend on any implementation details.
606#[derive(
607    Clone,
608    Copy,
609    Debug,
610    PartialEq,
611    Eq,
612    PartialOrd,
613    Ord,
614    Hash,
615    Serialize,
616    bincode::Decode,
617    bincode::Encode,
618)]
619// FIXME(aDotInTheVoid): Consider making this non-public in rustdoc-types.
620pub struct Id(pub u32);
621
622impl<'de> Deserialize<'de> for Id {
623    fn deserialize<D>(de: D) -> Result<Self, D::Error>
624    where
625        D: Deserializer<'de>,
626    {
627        struct IdVisitor;
628
629        impl<'de> de::Visitor<'de> for IdVisitor {
630            type Value = Id;
631
632            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
633                f.write_str("a u32 or a string containing a decimal u32")
634            }
635
636            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
637            where
638                E: de::Error,
639            {
640                u32::try_from(v)
641                    .map(Id)
642                    .map_err(|_| E::invalid_value(de::Unexpected::Unsigned(v), &"u32 in range"))
643            }
644
645            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
646            where
647                E: de::Error,
648            {
649                let s = s.trim();
650                // (Optional) allow underscores: "1_000" -> "1000"
651                let s = s.replace('_', "");
652                s.parse::<u32>()
653                    .map(Id)
654                    .map_err(|_| E::invalid_value(de::Unexpected::Str(&s), &"decimal u32 string"))
655            }
656
657            fn visit_string<E>(self, s: String) -> Result<Self::Value, E>
658            where
659                E: de::Error,
660            {
661                self.visit_str(&s)
662            }
663        }
664
665        de.deserialize_any(IdVisitor)
666    }
667}
668
669/// The fundamental kind of an item. Unlike [`ItemEnum`], this does not carry any additional info.
670///
671/// Part of [`ItemSummary`].
672#[derive(
673    Clone,
674    Copy,
675    Debug,
676    PartialEq,
677    Eq,
678    Hash,
679    Serialize,
680    Deserialize,
681    bincode::Decode,
682    bincode::Encode,
683)]
684#[serde(rename_all = "snake_case")]
685pub enum ItemKind {
686    /// A module declaration, e.g. `mod foo;` or `mod foo {}`
687    Module,
688    /// A crate imported via the `extern crate` syntax.
689    ExternCrate,
690    /// An import of 1 or more items into scope, using the `use` keyword.
691    Use,
692    /// A `struct` declaration.
693    Struct,
694    /// A field of a struct.
695    StructField,
696    /// A `union` declaration.
697    Union,
698    /// An `enum` declaration.
699    Enum,
700    /// A variant of a enum.
701    Variant,
702    /// A function declaration, e.g. `fn f() {}`
703    Function,
704    /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
705    TypeAlias,
706    /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
707    Constant,
708    /// A `trait` declaration.
709    Trait,
710    /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
711    ///
712    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
713    TraitAlias,
714    /// An `impl` block.
715    Impl,
716    /// A `static` declaration.
717    Static,
718    /// `type`s from an `extern` block.
719    ///
720    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
721    ExternType,
722    /// A macro declaration.
723    ///
724    /// Corresponds to either `ItemEnum::Macro(_)`
725    /// or `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Bang })`
726    Macro,
727    /// A procedural macro attribute.
728    ///
729    /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Attr })`
730    ProcAttribute,
731    /// A procedural macro usable in the `#[derive()]` attribute.
732    ///
733    /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Derive }
734    ProcDerive,
735    /// An associated constant of a trait or a type.
736    AssocConst,
737    /// An associated type of a trait or a type.
738    AssocType,
739    /// A primitive type, e.g. `u32`.
740    ///
741    /// [`Item`]s of this kind only come from the core library.
742    Primitive,
743    /// A keyword declaration.
744    ///
745    /// [`Item`]s of this kind only come from the come library and exist solely
746    /// to carry documentation for the respective keywords.
747    Keyword,
748    /// An attribute declaration.
749    ///
750    /// [`Item`]s of this kind only come from the core library and exist solely
751    /// to carry documentation for the respective builtin attributes.
752    Attribute,
753}
754
755/// Specific fields of an item.
756///
757/// Part of [`Item`].
758#[derive(
759    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
760)]
761#[serde(rename_all = "snake_case")]
762pub enum ItemEnum {
763    /// A module declaration, e.g. `mod foo;` or `mod foo {}`
764    Module(Module),
765    /// A crate imported via the `extern crate` syntax.
766    ExternCrate {
767        /// The name of the imported crate.
768        name: String,
769        /// If the crate is renamed, this is its name in the crate.
770        rename: Option<String>,
771    },
772    /// An import of 1 or more items into scope, using the `use` keyword.
773    Use(Use),
774
775    /// A `union` declaration.
776    Union(Union),
777    /// A `struct` declaration.
778    Struct(Struct),
779    /// A field of a struct.
780    StructField(Type),
781    /// An `enum` declaration.
782    Enum(Enum),
783    /// A variant of a enum.
784    Variant(Variant),
785
786    /// A function declaration (including methods and other associated functions)
787    Function(Function),
788
789    /// A `trait` declaration.
790    Trait(Trait),
791    /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
792    ///
793    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
794    TraitAlias(TraitAlias),
795    /// An `impl` block.
796    Impl(Impl),
797
798    /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
799    TypeAlias(TypeAlias),
800    /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
801    Constant {
802        /// The type of the constant.
803        #[serde(rename = "type")]
804        type_: Type,
805        /// The declared constant itself.
806        #[serde(rename = "const")]
807        const_: Constant,
808    },
809
810    /// A declaration of a `static`.
811    Static(Static),
812
813    /// `type`s from an `extern` block.
814    ///
815    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
816    ExternType,
817
818    /// A macro_rules! declarative macro. Contains a single string with the source
819    /// representation of the macro with the patterns stripped.
820    Macro(String),
821    /// A procedural macro.
822    ProcMacro(ProcMacro),
823
824    /// A primitive type, e.g. `u32`.
825    ///
826    /// [`Item`]s of this kind only come from the core library.
827    Primitive(Primitive),
828
829    /// An associated constant of a trait or a type.
830    AssocConst {
831        /// The type of the constant.
832        #[serde(rename = "type")]
833        type_: Type,
834        /// Inside a trait declaration, this is the default value for the associated constant,
835        /// if provided.
836        /// Inside an `impl` block, this is the value assigned to the associated constant,
837        /// and will always be present.
838        ///
839        /// The representation is implementation-defined and not guaranteed to be representative of
840        /// either the resulting value or of the source code.
841        ///
842        /// ```rust
843        /// const X: usize = 640 * 1024;
844        /// //               ^^^^^^^^^^
845        /// ```
846        value: Option<String>,
847    },
848    /// An associated type of a trait or a type.
849    AssocType {
850        /// The generic parameters and where clauses on ahis associated type.
851        generics: Generics,
852        /// The bounds for this associated type. e.g.
853        /// ```rust
854        /// trait IntoIterator {
855        ///     type Item;
856        ///     type IntoIter: Iterator<Item = Self::Item>;
857        /// //                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
858        /// }
859        /// ```
860        bounds: Vec<GenericBound>,
861        /// Inside a trait declaration, this is the default for the associated type, if provided.
862        /// Inside an impl block, this is the type assigned to the associated type, and will always
863        /// be present.
864        ///
865        /// ```rust
866        /// type X = usize;
867        /// //       ^^^^^
868        /// ```
869        #[serde(rename = "type")]
870        type_: Option<Type>,
871    },
872}
873
874impl Display for ItemEnum {
875    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876        match self {
877            ItemEnum::Module(_) => write!(f, "module"),
878            ItemEnum::ExternCrate { .. } => write!(f, "extern crate"),
879            ItemEnum::Use(_) => write!(f, "use"),
880            ItemEnum::Union(_) => write!(f, "union"),
881            ItemEnum::Struct(_) => write!(f, "struct"),
882            ItemEnum::StructField(_) => write!(f, "struct field"),
883            ItemEnum::Enum(_) => write!(f, "enum"),
884            ItemEnum::Variant(_) => write!(f, "variant"),
885            ItemEnum::Function(f_) => write!(f, "{}", f_),
886            ItemEnum::Trait(_) => write!(f, "trait"),
887            ItemEnum::TraitAlias(_) => write!(f, "trait alias"),
888            ItemEnum::Impl(_) => write!(f, "impl"),
889            ItemEnum::TypeAlias(_) => write!(f, "type alias"),
890            ItemEnum::Constant { .. } => write!(f, "constant"),
891            ItemEnum::Static(_) => write!(f, "static"),
892            ItemEnum::ExternType => write!(f, "extern type"),
893            ItemEnum::Macro(_) => write!(f, "macro"),
894            ItemEnum::ProcMacro(_) => write!(f, "procedural macro"),
895            ItemEnum::Primitive(_) => write!(f, "primitive type"),
896            ItemEnum::AssocConst { .. } => write!(f, "associated constant"),
897            ItemEnum::AssocType { .. } => write!(f, "associated type"),
898        }
899    }
900}
901
902/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
903#[derive(
904    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
905)]
906pub struct Module {
907    /// Whether this is the root item of a crate.
908    ///
909    /// This item doesn't correspond to any construction in the source code and is generated by the
910    /// compiler.
911    pub is_crate: bool,
912    /// [`Item`]s declared inside this module.
913    pub items: Vec<Id>,
914    /// If `true`, this module is not part of the public API, but it contains
915    /// items that are re-exported as public API.
916    pub is_stripped: bool,
917}
918
919/// A `union`.
920#[derive(
921    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
922)]
923pub struct Union {
924    /// The generic parameters and where clauses on this union.
925    pub generics: Generics,
926    /// Whether any fields have been removed from the result, due to being private or hidden.
927    pub has_stripped_fields: bool,
928    /// The list of fields in the union.
929    ///
930    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
931    pub fields: Vec<Id>,
932    /// All impls (both of traits and inherent) for this union.
933    ///
934    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
935    pub impls: Vec<Id>,
936}
937
938/// A `struct`.
939#[derive(
940    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
941)]
942pub struct Struct {
943    /// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
944    /// i.e. fields.
945    pub kind: StructKind,
946    /// The generic parameters and where clauses on this struct.
947    pub generics: Generics,
948    /// All impls (both of traits and inherent) for this struct.
949    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
950    pub impls: Vec<Id>,
951}
952
953/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
954#[derive(
955    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
956)]
957#[serde(rename_all = "snake_case")]
958pub enum StructKind {
959    /// A struct with no fields and no parentheses.
960    ///
961    /// ```rust
962    /// pub struct Unit;
963    /// ```
964    Unit,
965    /// A struct with unnamed fields.
966    ///
967    /// All [`Id`]'s will point to [`ItemEnum::StructField`].
968    /// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
969    /// instead of being omitted, because order matters.
970    ///
971    /// ```rust
972    /// pub struct TupleStruct(i32);
973    /// pub struct EmptyTupleStruct();
974    /// ```
975    Tuple(Vec<Option<Id>>),
976    /// A struct with named fields.
977    ///
978    /// ```rust
979    /// pub struct PlainStruct { x: i32 }
980    /// pub struct EmptyPlainStruct {}
981    /// ```
982    Plain {
983        /// The list of fields in the struct.
984        ///
985        /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
986        fields: Vec<Id>,
987        /// Whether any fields have been removed from the result, due to being private or hidden.
988        has_stripped_fields: bool,
989    },
990}
991
992/// An `enum`.
993#[derive(
994    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
995)]
996pub struct Enum {
997    /// Information about the type parameters and `where` clauses of the enum.
998    pub generics: Generics,
999    /// Whether any variants have been removed from the result, due to being private or hidden.
1000    pub has_stripped_variants: bool,
1001    /// The list of variants in the enum.
1002    ///
1003    /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
1004    pub variants: Vec<Id>,
1005    /// `impl`s for the enum.
1006    pub impls: Vec<Id>,
1007}
1008
1009/// A variant of an enum.
1010#[derive(
1011    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1012)]
1013pub struct Variant {
1014    /// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
1015    pub kind: VariantKind,
1016    /// The discriminant, if explicitly specified.
1017    pub discriminant: Option<Discriminant>,
1018}
1019
1020/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
1021#[derive(
1022    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1023)]
1024#[serde(rename_all = "snake_case")]
1025pub enum VariantKind {
1026    /// A variant with no parentheses
1027    ///
1028    /// ```rust
1029    /// enum Demo {
1030    ///     PlainVariant,
1031    ///     PlainWithDiscriminant = 1,
1032    /// }
1033    /// ```
1034    Plain,
1035    /// A variant with unnamed fields.
1036    ///
1037    /// All [`Id`]'s will point to [`ItemEnum::StructField`].
1038    /// Unlike most of JSON, `#[doc(hidden)]` fields will be given as `None`
1039    /// instead of being omitted, because order matters.
1040    ///
1041    /// ```rust
1042    /// enum Demo {
1043    ///     TupleVariant(i32),
1044    ///     EmptyTupleVariant(),
1045    /// }
1046    /// ```
1047    Tuple(Vec<Option<Id>>),
1048    /// A variant with named fields.
1049    ///
1050    /// ```rust
1051    /// enum Demo {
1052    ///     StructVariant { x: i32 },
1053    ///     EmptyStructVariant {},
1054    /// }
1055    /// ```
1056    Struct {
1057        /// The list of variants in the enum.
1058        /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`].
1059        fields: Vec<Id>,
1060        /// Whether any variants have been removed from the result, due to being private or hidden.
1061        has_stripped_fields: bool,
1062    },
1063}
1064
1065/// The value that distinguishes a variant in an [`Enum`] from other variants.
1066#[derive(
1067    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1068)]
1069pub struct Discriminant {
1070    /// The expression that produced the discriminant.
1071    ///
1072    /// Unlike `value`, this preserves the original formatting (eg suffixes,
1073    /// hexadecimal, and underscores), making it unsuitable to be machine
1074    /// interpreted.
1075    ///
1076    /// In some cases, when the value is too complex, this may be `"{ _ }"`.
1077    /// When this occurs is unstable, and may change without notice.
1078    pub expr: String,
1079    /// The numerical value of the discriminant. Stored as a string due to
1080    /// JSON's poor support for large integers, and the fact that it would need
1081    /// to store from [`i128::MIN`] to [`u128::MAX`].
1082    pub value: String,
1083}
1084
1085/// A set of fundamental properties of a function.
1086#[derive(
1087    Clone,
1088    Debug,
1089    PartialEq,
1090    Eq,
1091    Hash,
1092    Default,
1093    Serialize,
1094    Deserialize,
1095    bincode::Decode,
1096    bincode::Encode,
1097)]
1098pub struct FunctionHeader {
1099    /// Is this function marked as `const`?
1100    pub is_const: bool,
1101    /// Is this function unsafe?
1102    pub is_unsafe: bool,
1103    /// Is this function async?
1104    pub is_async: bool,
1105    /// The ABI used by the function.
1106    pub abi: Abi,
1107}
1108
1109impl Display for FunctionHeader {
1110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111        if self.is_const {
1112            write!(f, " const")?;
1113        }
1114        if self.is_unsafe {
1115            write!(f, " unsafe")?;
1116        }
1117        if self.is_async {
1118            write!(f, " async")?;
1119        }
1120        Ok(())
1121    }
1122}
1123
1124impl FunctionHeader {
1125    pub fn qualifiers(&self) -> HashSet<Qualifier> {
1126        let mut quals = HashSet::new();
1127        if self.is_const {
1128            quals.insert(Qualifier::Const);
1129        }
1130        if self.is_unsafe {
1131            quals.insert(Qualifier::Unsafe);
1132        }
1133        if self.is_async {
1134            quals.insert(Qualifier::Async);
1135        }
1136        quals
1137    }
1138}
1139
1140/// The ABI (Application Binary Interface) used by a function.
1141///
1142/// If a variant has an `unwind` field, this means the ABI that it represents can be specified in 2
1143/// ways: `extern "_"` and `extern "_-unwind"`, and a value of `true` for that field signifies the
1144/// latter variant.
1145///
1146/// See the [Rustonomicon section](https://doc.rust-lang.org/nightly/nomicon/ffi.html#ffi-and-unwinding)
1147/// on unwinding for more info.
1148#[derive(
1149    Clone,
1150    Debug,
1151    PartialEq,
1152    Eq,
1153    Hash,
1154    Default,
1155    Serialize,
1156    Deserialize,
1157    bincode::Decode,
1158    bincode::Encode,
1159)]
1160pub enum Abi {
1161    // We only have a concrete listing here for stable ABI's because there are so many
1162    // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
1163    /// The default ABI, but that can also be written explicitly with `extern "Rust"`.
1164    #[default]
1165    Rust,
1166    /// Can be specified as `extern "C"` or, as a shorthand, just `extern`.
1167    C { unwind: bool },
1168    /// Can be specified as `extern "cdecl"`.
1169    Cdecl { unwind: bool },
1170    /// Can be specified as `extern "stdcall"`.
1171    Stdcall { unwind: bool },
1172    /// Can be specified as `extern "fastcall"`.
1173    Fastcall { unwind: bool },
1174    /// Can be specified as `extern "aapcs"`.
1175    Aapcs { unwind: bool },
1176    /// Can be specified as `extern "win64"`.
1177    Win64 { unwind: bool },
1178    /// Can be specified as `extern "sysv64"`.
1179    SysV64 { unwind: bool },
1180    /// Can be specified as `extern "system"`.
1181    System { unwind: bool },
1182    /// Any other ABI, including unstable ones.
1183    Other(String),
1184}
1185
1186/// A function declaration (including methods and other associated functions).
1187#[derive(
1188    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1189)]
1190pub struct Function {
1191    /// Information about the function signature, or declaration.
1192    pub sig: FunctionSignature,
1193    /// Information about the function’s type parameters and `where` clauses.
1194    pub generics: Generics,
1195    /// Information about core properties of the function, e.g. whether it's `const`, its ABI, etc.
1196    pub header: FunctionHeader,
1197    /// Whether the function has a body, i.e. an implementation.
1198    pub has_body: bool,
1199}
1200
1201impl Display for Function {
1202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1203        write!(f, "{} {} {}", self.header, self.generics, self.sig)
1204    }
1205}
1206
1207/// Generic parameters accepted by an item and `where` clauses imposed on it and the parameters.
1208#[derive(
1209    Clone,
1210    Debug,
1211    PartialEq,
1212    Eq,
1213    Hash,
1214    Default,
1215    Serialize,
1216    Deserialize,
1217    bincode::Decode,
1218    bincode::Encode,
1219)]
1220pub struct Generics {
1221    /// A list of generic parameter definitions (e.g. `<T: Clone + Hash, U: Copy>`).
1222    pub params: Vec<GenericParamDef>,
1223    /// A list of where predicates (e.g. `where T: Iterator, T::Item: Copy`).
1224    pub where_predicates: Vec<WherePredicate>,
1225}
1226
1227impl Display for Generics {
1228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1229        if !self.params.is_empty() {
1230            write!(
1231                f,
1232                "<{}>",
1233                self.params
1234                    .iter()
1235                    .map(|p| p.to_string())
1236                    .collect::<Vec<_>>()
1237                    .join(", ")
1238            )?;
1239        }
1240        if !self.where_predicates.is_empty() {
1241            write!(
1242                f,
1243                " where {}",
1244                self.where_predicates
1245                    .iter()
1246                    .map(|p| p.to_string())
1247                    .collect::<Vec<_>>()
1248                    .join(", ")
1249            )?;
1250        }
1251        Ok(())
1252    }
1253}
1254
1255/// One generic parameter accepted by an item.
1256#[derive(
1257    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1258)]
1259pub struct GenericParamDef {
1260    /// Name of the parameter.
1261    /// ```rust
1262    /// fn f<'resource, Resource>(x: &'resource Resource) {}
1263    /// //    ^^^^^^^^  ^^^^^^^^
1264    /// ```
1265    pub name: String,
1266    /// The kind of the parameter and data specific to a particular parameter kind, e.g. type
1267    /// bounds.
1268    pub kind: GenericParamDefKind,
1269}
1270
1271impl Display for GenericParamDef {
1272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273        match &self.kind {
1274            GenericParamDefKind::Lifetime { outlives } => {
1275                write!(f, "{}", self.name)?;
1276                if !outlives.is_empty() {
1277                    write!(f, ": {}", outlives.join(" + "))?;
1278                }
1279                Ok(())
1280            }
1281            GenericParamDefKind::Type {
1282                bounds,
1283                default,
1284                is_synthetic,
1285            } => {
1286                if *is_synthetic {
1287                    write!(
1288                        f,
1289                        "impl {}",
1290                        bounds
1291                            .iter()
1292                            .map(|b| b.to_string())
1293                            .collect::<Vec<_>>()
1294                            .join(" + ")
1295                    )?;
1296                } else {
1297                    write!(f, "{}", self.name)?;
1298                    if !bounds.is_empty() {
1299                        write!(
1300                            f,
1301                            ": {}",
1302                            bounds
1303                                .iter()
1304                                .map(|b| b.to_string())
1305                                .collect::<Vec<_>>()
1306                                .join(" + ")
1307                        )?;
1308                    }
1309                }
1310                if let Some(default) = default {
1311                    write!(f, " = {}", default)?;
1312                }
1313                Ok(())
1314            }
1315            GenericParamDefKind::Const { type_, default } => {
1316                write!(f, "const {}: {}", self.name, type_)?;
1317                if let Some(default) = default {
1318                    write!(f, " = {}", default)?;
1319                }
1320                Ok(())
1321            }
1322        }
1323    }
1324}
1325
1326/// The kind of a [`GenericParamDef`].
1327#[derive(
1328    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1329)]
1330#[serde(rename_all = "snake_case")]
1331pub enum GenericParamDefKind {
1332    /// Denotes a lifetime parameter.
1333    Lifetime {
1334        /// Lifetimes that this lifetime parameter is required to outlive.
1335        ///
1336        /// ```rust
1337        /// fn f<'a, 'b, 'resource: 'a + 'b>(a: &'a str, b: &'b str, res: &'resource str) {}
1338        /// //                      ^^^^^^^
1339        /// ```
1340        outlives: Vec<String>,
1341    },
1342
1343    /// Denotes a type parameter.
1344    Type {
1345        /// Bounds applied directly to the type. Note that the bounds from `where` clauses
1346        /// that constrain this parameter won't appear here.
1347        ///
1348        /// ```rust
1349        /// fn default2<T: Default>() -> [T; 2] where T: Clone { todo!() }
1350        /// //             ^^^^^^^
1351        /// ```
1352        bounds: Vec<GenericBound>,
1353        /// The default type for this parameter, if provided, e.g.
1354        ///
1355        /// ```rust
1356        /// trait PartialEq<Rhs = Self> {}
1357        /// //                    ^^^^
1358        /// ```
1359        default: Option<Type>,
1360        /// This is normally `false`, which means that this generic parameter is
1361        /// declared in the Rust source text.
1362        ///
1363        /// If it is `true`, this generic parameter has been introduced by the
1364        /// compiler behind the scenes.
1365        ///
1366        /// # Example
1367        ///
1368        /// Consider
1369        ///
1370        /// ```ignore (pseudo-rust)
1371        /// pub fn f(_: impl Trait) {}
1372        /// ```
1373        ///
1374        /// The compiler will transform this behind the scenes to
1375        ///
1376        /// ```ignore (pseudo-rust)
1377        /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
1378        /// ```
1379        ///
1380        /// In this example, the generic parameter named `impl Trait` (and which
1381        /// is bound by `Trait`) is synthetic, because it was not originally in
1382        /// the Rust source text.
1383        is_synthetic: bool,
1384    },
1385
1386    /// Denotes a constant parameter.
1387    Const {
1388        /// The type of the constant as declared.
1389        #[serde(rename = "type")]
1390        type_: Type,
1391        /// The stringified expression for the default value, if provided. It's not guaranteed that
1392        /// it'll match the actual source code for the default value.
1393        default: Option<String>,
1394    },
1395}
1396
1397/// One `where` clause.
1398/// ```rust
1399/// fn default<T>() -> T where T: Default { T::default() }
1400/// //                         ^^^^^^^^^^
1401/// ```
1402#[derive(
1403    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1404)]
1405#[serde(rename_all = "snake_case")]
1406pub enum WherePredicate {
1407    /// A type is expected to comply with a set of bounds
1408    BoundPredicate {
1409        /// The type that's being constrained.
1410        ///
1411        /// ```rust
1412        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1413        /// //                              ^
1414        /// ```
1415        #[serde(rename = "type")]
1416        type_: Type,
1417        /// The set of bounds that constrain the type.
1418        ///
1419        /// ```rust
1420        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1421        /// //                                 ^^^^^^^^
1422        /// ```
1423        bounds: Vec<GenericBound>,
1424        /// Used for Higher-Rank Trait Bounds (HRTBs)
1425        /// ```rust
1426        /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1427        /// //                  ^^^^^^^
1428        /// ```
1429        generic_params: Vec<GenericParamDef>,
1430    },
1431
1432    /// A lifetime is expected to outlive other lifetimes.
1433    LifetimePredicate {
1434        /// The name of the lifetime.
1435        lifetime: String,
1436        /// The lifetimes that must be encompassed by the lifetime.
1437        outlives: Vec<String>,
1438    },
1439
1440    /// A type must exactly equal another type.
1441    EqPredicate {
1442        /// The left side of the equation.
1443        lhs: Type,
1444        /// The right side of the equation.
1445        rhs: Term,
1446    },
1447}
1448
1449impl Display for WherePredicate {
1450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1451        match self {
1452            WherePredicate::BoundPredicate {
1453                type_,
1454                bounds,
1455                generic_params,
1456            } => {
1457                if !generic_params.is_empty() {
1458                    write!(
1459                        f,
1460                        "for<{}> ",
1461                        generic_params
1462                            .iter()
1463                            .map(|p| p.to_string())
1464                            .collect::<Vec<_>>()
1465                            .join(", ")
1466                    )?;
1467                }
1468                write!(
1469                    f,
1470                    "{}: {}",
1471                    type_,
1472                    bounds
1473                        .iter()
1474                        .map(|b| b.to_string())
1475                        .collect::<Vec<_>>()
1476                        .join(" + ")
1477                )
1478            }
1479            WherePredicate::LifetimePredicate { lifetime, outlives } => {
1480                write!(f, "{}: {}", lifetime, outlives.join(" + "))
1481            }
1482            WherePredicate::EqPredicate { lhs, rhs } => {
1483                write!(f, "{} = {}", lhs, rhs)
1484            }
1485        }
1486    }
1487}
1488
1489/// Either a trait bound or a lifetime bound.
1490#[derive(
1491    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1492)]
1493#[serde(rename_all = "snake_case")]
1494pub enum GenericBound {
1495    /// A trait bound.
1496    TraitBound {
1497        /// The full path to the trait.
1498        #[serde(rename = "trait")]
1499        trait_: Path,
1500        /// Used for Higher-Rank Trait Bounds (HRTBs)
1501        /// ```text
1502        /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
1503        ///          ^^^^^^^^^^^
1504        ///          |
1505        ///          this part
1506        /// ```
1507        generic_params: Vec<GenericParamDef>,
1508        /// The context for which a trait is supposed to be used, e.g. `const
1509        modifier: TraitBoundModifier,
1510    },
1511    /// A lifetime bound, e.g.
1512    /// ```rust
1513    /// fn f<'a, T>(x: &'a str, y: &T) where T: 'a {}
1514    /// //                                     ^^^
1515    /// ```
1516    Outlives(String),
1517    /// `use<'a, T>` precise-capturing bound syntax
1518    Use(Vec<PreciseCapturingArg>),
1519}
1520
1521impl Display for GenericBound {
1522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1523        match self {
1524            GenericBound::TraitBound {
1525                trait_,
1526                generic_params,
1527                modifier,
1528            } => {
1529                if !generic_params.is_empty() {
1530                    write!(
1531                        f,
1532                        "for<{}> ",
1533                        generic_params
1534                            .iter()
1535                            .map(|p| p.to_string())
1536                            .collect::<Vec<_>>()
1537                            .join(", ")
1538                    )?;
1539                }
1540                write!(f, "{}", trait_)?;
1541                match modifier {
1542                    TraitBoundModifier::None => Ok(()),
1543                    TraitBoundModifier::Maybe => write!(f, "?"),
1544                    TraitBoundModifier::MaybeConst => write!(f, " + const"),
1545                }
1546            }
1547            GenericBound::Outlives(lifetime) => write!(f, "{}", lifetime),
1548            GenericBound::Use(args) => {
1549                write!(
1550                    f,
1551                    "use<{}>",
1552                    args.iter()
1553                        .map(|arg| match arg {
1554                            PreciseCapturingArg::Lifetime(name) => name.clone(),
1555                            PreciseCapturingArg::Param(name) => name.clone(),
1556                        })
1557                        .collect::<Vec<_>>()
1558                        .join(", ")
1559                )
1560            }
1561        }
1562    }
1563}
1564
1565/// A set of modifiers applied to a trait.
1566#[derive(
1567    Clone,
1568    Copy,
1569    Debug,
1570    PartialEq,
1571    Eq,
1572    Hash,
1573    Serialize,
1574    Deserialize,
1575    bincode::Decode,
1576    bincode::Encode,
1577)]
1578#[serde(rename_all = "snake_case")]
1579pub enum TraitBoundModifier {
1580    /// Marks the absence of a modifier.
1581    None,
1582    /// Indicates that the trait bound relaxes a trait bound applied to a parameter by default,
1583    /// e.g. `T: Sized?`, the `Sized` trait is required for all generic type parameters by default
1584    /// unless specified otherwise with this modifier.
1585    Maybe,
1586    /// Indicates that the trait bound must be applicable in both a run-time and a compile-time
1587    /// context.
1588    MaybeConst,
1589}
1590
1591/// One precise capturing argument. See [the rust reference](https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing).
1592#[derive(
1593    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1594)]
1595#[serde(rename_all = "snake_case")]
1596pub enum PreciseCapturingArg {
1597    /// A lifetime.
1598    /// ```rust
1599    /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1600    /// //                                                        ^^
1601    Lifetime(String),
1602    /// A type or constant parameter.
1603    /// ```rust
1604    /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1605    /// //                                                            ^  ^
1606    Param(String),
1607}
1608
1609/// Either a type or a constant, usually stored as the right-hand side of an equation in places like
1610/// [`AssocItemConstraint`]
1611#[derive(
1612    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1613)]
1614#[serde(rename_all = "snake_case")]
1615pub enum Term {
1616    /// A type.
1617    ///
1618    /// ```rust
1619    /// fn f(x: impl IntoIterator<Item = u32>) {}
1620    /// //                               ^^^
1621    /// ```
1622    Type(Type),
1623    /// A constant.
1624    ///
1625    /// ```ignore (incomplete feature in the snippet)
1626    /// trait Foo {
1627    ///     const BAR: usize;
1628    /// }
1629    ///
1630    /// fn f(x: impl Foo<BAR = 42>) {}
1631    /// //                     ^^
1632    /// ```
1633    Constant(Constant),
1634}
1635
1636impl Display for Term {
1637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1638        match self {
1639            Term::Type(t) => write!(f, "{}", t),
1640            Term::Constant(c) => write!(f, "{}", c),
1641        }
1642    }
1643}
1644
1645/// A type.
1646#[derive(
1647    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1648)]
1649#[serde(rename_all = "snake_case")]
1650pub enum Type {
1651    /// Structs, enums, unions and type aliases, e.g. `std::option::Option<u32>`
1652    ResolvedPath(Path),
1653    /// Dynamic trait object type (`dyn Trait`).
1654    DynTrait(DynTrait),
1655    /// Parameterized types. The contained string is the name of the parameter.
1656    Generic(String),
1657    /// Built-in numeric types (e.g. `u32`, `f32`), `bool`, `char`.
1658    Primitive(String),
1659    /// A function pointer type, e.g. `fn(u32) -> u32`, `extern "C" fn() -> *const u8`
1660    FunctionPointer(Box<FunctionPointer>),
1661    /// A tuple type, e.g. `(String, u32, Box<usize>)`
1662    Tuple(Vec<Type>),
1663    /// An unsized slice type, e.g. `[u32]`.
1664    Slice(Box<Type>),
1665    /// An array type, e.g. `[u32; 15]`
1666    Array {
1667        /// The type of the contained element.
1668        #[serde(rename = "type")]
1669        type_: Box<Type>,
1670        /// The stringified expression that is the length of the array.
1671        ///
1672        /// Keep in mind that it's not guaranteed to match the actual source code of the expression.
1673        len: String,
1674    },
1675    /// A pattern type, e.g. `u32 is 1..`
1676    ///
1677    /// See [the tracking issue](https://github.com/rust-lang/rust/issues/123646)
1678    Pat {
1679        /// The base type, e.g. the `u32` in `u32 is 1..`
1680        #[serde(rename = "type")]
1681        type_: Box<Type>,
1682        #[doc(hidden)]
1683        __pat_unstable_do_not_use: String,
1684    },
1685    /// An opaque type that satisfies a set of bounds, `impl TraitA + TraitB + ...`
1686    ImplTrait(Vec<GenericBound>),
1687    /// A type that's left to be inferred, `_`
1688    Infer,
1689    /// A raw pointer type, e.g. `*mut u32`, `*const u8`, etc.
1690    RawPointer {
1691        /// This is `true` for `*mut _` and `false` for `*const _`.
1692        is_mutable: bool,
1693        /// The type of the pointee.
1694        #[serde(rename = "type")]
1695        type_: Box<Type>,
1696    },
1697    /// `&'a mut String`, `&str`, etc.
1698    BorrowedRef {
1699        /// The name of the lifetime of the reference, if provided.
1700        lifetime: Option<String>,
1701        /// This is `true` for `&mut i32` and `false` for `&i32`
1702        is_mutable: bool,
1703        /// The type of the pointee, e.g. the `i32` in `&'a mut i32`
1704        #[serde(rename = "type")]
1705        type_: Box<Type>,
1706    },
1707    /// Associated types like `<Type as Trait>::Name` and `T::Item` where
1708    /// `T: Iterator` or inherent associated types like `Struct::Name`.
1709    QualifiedPath {
1710        /// The name of the associated type in the parent type.
1711        ///
1712        /// ```ignore (incomplete expression)
1713        /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1714        /// //                                            ^^^^
1715        /// ```
1716        name: String,
1717        /// The generic arguments provided to the associated type.
1718        ///
1719        /// ```ignore (incomplete expression)
1720        /// <core::slice::IterMut<'static, u32> as BetterIterator>::Item<'static>
1721        /// //                                                          ^^^^^^^^^
1722        /// ```
1723        args: Option<Box<GenericArgs>>,
1724        /// The type with which this type is associated.
1725        ///
1726        /// ```ignore (incomplete expression)
1727        /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1728        /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1729        /// ```
1730        self_type: Box<Type>,
1731        /// `None` iff this is an *inherent* associated type.
1732        #[serde(rename = "trait")]
1733        trait_: Option<Path>,
1734    },
1735}
1736
1737impl Display for Type {
1738    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1739        match self {
1740            Type::ResolvedPath(path) => write!(f, "{}", path.path),
1741            Type::DynTrait(_) => write!(f, "dyn <trait>"),
1742            Type::Generic(name) => write!(f, "{}", name),
1743            Type::Primitive(name) => write!(f, "{}", name),
1744            Type::FunctionPointer(_) => write!(f, "fn(...)"),
1745            Type::Tuple(t) => write!(
1746                f,
1747                "({})",
1748                t.iter()
1749                    .map(|ty| format!("{}", ty))
1750                    .collect::<Vec<_>>()
1751                    .join(", ")
1752            ),
1753            Type::Slice(s) => write!(f, "[{}]", s),
1754            Type::Array { type_, len } => write!(f, "[{}; {}]", type_, len),
1755            Type::Pat { .. } => write!(f, "<pattern type>"),
1756            Type::ImplTrait(_) => write!(f, "impl <trait bounds>"),
1757            Type::Infer => write!(f, "_"),
1758            Type::RawPointer { is_mutable, .. } => {
1759                if *is_mutable {
1760                    write!(f, "*mut ...")
1761                } else {
1762                    write!(f, "*const ...")
1763                }
1764            }
1765            Type::BorrowedRef {
1766                is_mutable,
1767                lifetime,
1768                type_,
1769            } => {
1770                if *is_mutable {
1771                    write!(
1772                        f,
1773                        "&mut{} {}",
1774                        lifetime.as_ref().unwrap_or(&"".into()),
1775                        type_
1776                    )
1777                } else {
1778                    write!(f, "&{} {}", lifetime.as_ref().unwrap_or(&"_".into()), type_)
1779                }
1780            }
1781            Type::QualifiedPath { name, .. } => write!(f, "<qualified path>::{}", name),
1782        }
1783    }
1784}
1785
1786/// A type that has a simple path to it. This is the kind of type of structs, unions, enums, etc.
1787#[derive(
1788    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1789)]
1790pub struct Path {
1791    /// The path of the type.
1792    ///
1793    /// This will be the path that is *used* (not where it is defined), so
1794    /// multiple `Path`s may have different values for this field even if
1795    /// they all refer to the same item. e.g.
1796    ///
1797    /// ```rust
1798    /// pub type Vec1 = std::vec::Vec<i32>; // path: "std::vec::Vec"
1799    /// pub type Vec2 = Vec<i32>; // path: "Vec"
1800    /// pub type Vec3 = std::prelude::v1::Vec<i32>; // path: "std::prelude::v1::Vec"
1801    /// ```
1802    //
1803    // Example tested in ./tests/rustdoc-json/path_name.rs
1804    pub path: String,
1805    /// The ID of the type.
1806    pub id: Id,
1807    /// Generic arguments to the type.
1808    ///
1809    /// ```ignore (incomplete expression)
1810    /// std::borrow::Cow<'static, str>
1811    /// //              ^^^^^^^^^^^^^^
1812    /// ```
1813    pub args: Option<Box<GenericArgs>>,
1814}
1815
1816impl Display for Path {
1817    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1818        write!(
1819            f,
1820            "{}<{}>",
1821            self.path,
1822            self.args
1823                .as_ref()
1824                .map(|args| args.to_string())
1825                .unwrap_or_default()
1826        )
1827    }
1828}
1829
1830/// A type that is a function pointer.
1831#[derive(
1832    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1833)]
1834pub struct FunctionPointer {
1835    /// The signature of the function.
1836    pub sig: FunctionSignature,
1837    /// Used for Higher-Rank Trait Bounds (HRTBs)
1838    ///
1839    /// ```ignore (incomplete expression)
1840    ///    for<'c> fn(val: &'c i32) -> i32
1841    /// // ^^^^^^^
1842    /// ```
1843    pub generic_params: Vec<GenericParamDef>,
1844    /// The core properties of the function, such as the ABI it conforms to, whether it's unsafe, etc.
1845    pub header: FunctionHeader,
1846}
1847
1848pub type Argument = (String, Type);
1849
1850/// The signature of a function.
1851#[derive(
1852    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1853)]
1854pub struct FunctionSignature {
1855    /// List of argument names and their type.
1856    ///
1857    /// Note that not all names will be valid identifiers, as some of
1858    /// them may be patterns.
1859    pub inputs: Vec<Argument>,
1860    /// The output type, if specified.
1861    pub output: Option<Type>,
1862    /// Whether the function accepts an arbitrary amount of trailing arguments the C way.
1863    ///
1864    /// ```ignore (incomplete code)
1865    /// fn printf(fmt: &str, ...);
1866    /// ```
1867    pub is_c_variadic: bool,
1868}
1869
1870impl Display for FunctionSignature {
1871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1872        write!(f, "fn(")?;
1873        for (i, (name, ty)) in self.inputs.iter().enumerate() {
1874            if i > 0 {
1875                write!(f, ", ")?;
1876            }
1877            write!(f, "{}: {}", name, ty)?;
1878        }
1879        if self.is_c_variadic {
1880            if !self.inputs.is_empty() {
1881                write!(f, ", ")?;
1882            }
1883            write!(f, "...")?;
1884        }
1885        write!(f, ")")?;
1886        if let Some(output) = &self.output {
1887            write!(f, " -> {}", output)?;
1888        }
1889        Ok(())
1890    }
1891}
1892
1893/// A `trait` declaration.
1894#[derive(
1895    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1896)]
1897pub struct Trait {
1898    /// Whether the trait is marked `auto` and is thus implemented automatically
1899    /// for all applicable types.
1900    pub is_auto: bool,
1901    /// Whether the trait is marked as `unsafe`.
1902    pub is_unsafe: bool,
1903    /// Whether the trait is [dyn compatible](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility)[^1].
1904    ///
1905    /// [^1]: Formerly known as "object safe".
1906    pub is_dyn_compatible: bool,
1907    /// Associated [`Item`]s that can/must be implemented by the `impl` blocks.
1908    pub items: Vec<Id>,
1909    /// Information about the type parameters and `where` clauses of the trait.
1910    pub generics: Generics,
1911    /// Constraints that must be met by the implementor of the trait.
1912    pub bounds: Vec<GenericBound>,
1913    /// The implementations of the trait.
1914    pub implementations: Vec<Id>,
1915}
1916
1917/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
1918///
1919/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
1920#[derive(
1921    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1922)]
1923pub struct TraitAlias {
1924    /// Information about the type parameters and `where` clauses of the alias.
1925    pub generics: Generics,
1926    /// The bounds that are associated with the alias.
1927    pub params: Vec<GenericBound>,
1928}
1929
1930/// An `impl` block.
1931#[derive(
1932    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1933)]
1934pub struct Impl {
1935    /// Whether this impl is for an unsafe trait.
1936    pub is_unsafe: bool,
1937    /// Information about the impl’s type parameters and `where` clauses.
1938    pub generics: Generics,
1939    /// The list of the names of all the trait methods that weren't mentioned in this impl but
1940    /// were provided by the trait itself.
1941    ///
1942    /// For example, for this impl of the [`PartialEq`] trait:
1943    /// ```rust
1944    /// struct Foo;
1945    ///
1946    /// impl PartialEq for Foo {
1947    ///     fn eq(&self, other: &Self) -> bool { todo!() }
1948    /// }
1949    /// ```
1950    /// This field will be `["ne"]`, as it has a default implementation defined for it.
1951    pub provided_trait_methods: Vec<String>,
1952    /// The trait being implemented or `None` if the impl is inherent, which means
1953    /// `impl Struct {}` as opposed to `impl Trait for Struct {}`.
1954    #[serde(rename = "trait")]
1955    pub trait_: Option<Path>,
1956    /// The type that the impl block is for.
1957    #[serde(rename = "for")]
1958    pub for_: Type,
1959    /// The list of associated items contained in this impl block.
1960    pub items: Vec<Id>,
1961    /// Whether this is a negative impl (e.g. `!Sized` or `!Send`).
1962    pub is_negative: bool,
1963    /// Whether this is an impl that’s implied by the compiler
1964    /// (for autotraits, e.g. `Send` or `Sync`).
1965    pub is_synthetic: bool,
1966    // FIXME: document this
1967    pub blanket_impl: Option<Type>,
1968}
1969
1970/// A `use` statement.
1971#[derive(
1972    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1973)]
1974#[serde(rename_all = "snake_case")]
1975pub struct Use {
1976    /// The full path being imported.
1977    pub source: String,
1978    /// May be different from the last segment of `source` when renaming imports:
1979    /// `use source as name;`
1980    pub name: String,
1981    /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
1982    /// ```rust
1983    /// pub use i32 as my_i32;
1984    /// ```
1985    pub id: Option<Id>,
1986    /// Whether this statement is a wildcard `use`, e.g. `use source::*;`
1987    pub is_glob: bool,
1988}
1989
1990/// A procedural macro.
1991#[derive(
1992    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
1993)]
1994pub struct ProcMacro {
1995    /// How this macro is supposed to be called: `foo!()`, `#[foo]` or `#[derive(foo), bincode::Decode, bincode::Encode]`
1996    pub kind: MacroKind,
1997    /// Helper attributes defined by a macro to be used inside it.
1998    ///
1999    /// Defined only for derive macro, bincode::Decode, bincode::Encodes.
2000    ///
2001    /// E.g. the [`Default`] derive macro defines a `#[default]` helper attribute so that one c, bincode::Decode, bincode::Encodean
2002    /// do:
2003    ///
2004    /// ```rust
2005    /// #[derive(Default, bincode::Decode, bincode::Encode)]
2006    /// enum Option<T> {
2007    ///     #[default]
2008    ///     None,
2009    ///     Some(T),
2010    /// }
2011    /// ```
2012    pub helpers: Vec<String>,
2013}
2014
2015/// The way a [`ProcMacro`] is declared to be used.
2016#[derive(
2017    Clone,
2018    Copy,
2019    Debug,
2020    PartialEq,
2021    Eq,
2022    Hash,
2023    Serialize,
2024    Deserialize,
2025    bincode::Decode,
2026    bincode::Encode,
2027)]
2028#[serde(rename_all = "snake_case")]
2029pub enum MacroKind {
2030    /// A bang macro `foo!()`.
2031    Bang,
2032    /// An attribute macro `#[foo]`.
2033    Attr,
2034    /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize), bincode::Decode, bincode::Encode]`
2035    Derive,
2036}
2037
2038/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
2039#[derive(
2040    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
2041)]
2042pub struct TypeAlias {
2043    /// The type referred to by this alias.
2044    #[serde(rename = "type")]
2045    pub type_: Type,
2046    /// Information about the type parameters and `where` clauses of the alias.
2047    pub generics: Generics,
2048}
2049
2050/// A `static` declaration.
2051#[derive(
2052    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
2053)]
2054pub struct Static {
2055    /// The type of the static.
2056    #[serde(rename = "type")]
2057    pub type_: Type,
2058    /// This is `true` for mutable statics, declared as `static mut X: T = f();`
2059    pub is_mutable: bool,
2060    /// The stringified expression for the initial value.
2061    ///
2062    /// It's not guaranteed that it'll match the actual source code for the initial value.
2063    pub expr: String,
2064
2065    /// Is the static `unsafe`?
2066    ///
2067    /// This is only true if it's in an `extern` block, and not explicitly marked
2068    /// as `safe`.
2069    ///
2070    /// ```rust
2071    /// unsafe extern {
2072    ///     static A: i32;      // unsafe
2073    ///     safe static B: i32; // safe
2074    /// }
2075    ///
2076    /// static C: i32 = 0;     // safe
2077    /// static mut D: i32 = 0; // safe
2078    /// ```
2079    pub is_unsafe: bool,
2080}
2081
2082/// A primitive type declaration. Declarations of this kind can only come from the core library.
2083#[derive(
2084    Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, bincode::Decode, bincode::Encode,
2085)]
2086pub struct Primitive {
2087    /// The name of the type.
2088    pub name: String,
2089    /// The implementations, inherent and of traits, on the primitive type.
2090    pub impls: Vec<Id>,
2091}