]> git.lizzy.rs Git - rust.git/blob - src/rustdoc-json-types/lib.rs
Auto merge of #98866 - nagisa:nagisa/align-offset-wroom, r=Mark-Simulacrum
[rust.git] / src / rustdoc-json-types / lib.rs
1 //! Rustdoc's JSON output interface
2 //!
3 //! These types are the public API exposed through the `--output-format json` flag. The [`Crate`]
4 //! struct is the root of the JSON blob and all other items are contained within.
5
6 use std::collections::HashMap;
7 use std::path::PathBuf;
8
9 use serde::{Deserialize, Serialize};
10
11 /// rustdoc format-version.
12 pub const FORMAT_VERSION: u32 = 16;
13
14 /// A `Crate` is the root of the emitted JSON blob. It contains all type/documentation information
15 /// about the language items in the local crate, as well as info about external items to allow
16 /// tools to find or link to them.
17 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18 pub struct Crate {
19     /// The id of the root [`Module`] item of the local crate.
20     pub root: Id,
21     /// The version string given to `--crate-version`, if any.
22     pub crate_version: Option<String>,
23     /// Whether or not the output includes private items.
24     pub includes_private: bool,
25     /// A collection of all items in the local crate as well as some external traits and their
26     /// items that are referenced locally.
27     pub index: HashMap<Id, Item>,
28     /// Maps IDs to fully qualified paths and other info helpful for generating links.
29     pub paths: HashMap<Id, ItemSummary>,
30     /// Maps `crate_id` of items to a crate name and html_root_url if it exists.
31     pub external_crates: HashMap<u32, ExternalCrate>,
32     /// A single version number to be used in the future when making backwards incompatible changes
33     /// to the JSON output.
34     pub format_version: u32,
35 }
36
37 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
38 pub struct ExternalCrate {
39     pub name: String,
40     pub html_root_url: Option<String>,
41 }
42
43 /// For external (not defined in the local crate) items, you don't get the same level of
44 /// information. This struct should contain enough to generate a link/reference to the item in
45 /// question, or can be used by a tool that takes the json output of multiple crates to find
46 /// the actual item definition with all the relevant info.
47 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
48 pub struct ItemSummary {
49     /// Can be used to look up the name and html_root_url of the crate this item came from in the
50     /// `external_crates` map.
51     pub crate_id: u32,
52     /// The list of path components for the fully qualified path of this item (e.g.
53     /// `["std", "io", "lazy", "Lazy"]` for `std::io::lazy::Lazy`).
54     pub path: Vec<String>,
55     /// Whether this item is a struct, trait, macro, etc.
56     pub kind: ItemKind,
57 }
58
59 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60 pub struct Item {
61     /// The unique identifier of this item. Can be used to find this item in various mappings.
62     pub id: Id,
63     /// This can be used as a key to the `external_crates` map of [`Crate`] to see which crate
64     /// this item came from.
65     pub crate_id: u32,
66     /// Some items such as impls don't have names.
67     pub name: Option<String>,
68     /// The source location of this item (absent if it came from a macro expansion or inline
69     /// assembly).
70     pub span: Option<Span>,
71     /// By default all documented items are public, but you can tell rustdoc to output private items
72     /// so this field is needed to differentiate.
73     pub visibility: Visibility,
74     /// The full markdown docstring of this item. Absent if there is no documentation at all,
75     /// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
76     pub docs: Option<String>,
77     /// 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
78     pub links: HashMap<String, Id>,
79     /// Stringified versions of the attributes on this item (e.g. `"#[inline]"`)
80     pub attrs: Vec<String>,
81     pub deprecation: Option<Deprecation>,
82     #[serde(flatten)]
83     pub inner: ItemEnum,
84 }
85
86 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
87 pub struct Span {
88     /// The path to the source file for this span relative to the path `rustdoc` was invoked with.
89     pub filename: PathBuf,
90     /// Zero indexed Line and Column of the first character of the `Span`
91     pub begin: (usize, usize),
92     /// Zero indexed Line and Column of the last character of the `Span`
93     pub end: (usize, usize),
94 }
95
96 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
97 pub struct Deprecation {
98     pub since: Option<String>,
99     pub note: Option<String>,
100 }
101
102 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
103 #[serde(rename_all = "snake_case")]
104 pub enum Visibility {
105     Public,
106     /// For the most part items are private by default. The exceptions are associated items of
107     /// public traits and variants of public enums.
108     Default,
109     Crate,
110     /// For `pub(in path)` visibility. `parent` is the module it's restricted to and `path` is how
111     /// that module was referenced (like `"super::super"` or `"crate::foo::bar"`).
112     Restricted {
113         parent: Id,
114         path: String,
115     },
116 }
117
118 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
119 #[serde(rename_all = "snake_case")]
120 pub enum GenericArgs {
121     /// <'a, 32, B: Copy, C = u32>
122     AngleBracketed { args: Vec<GenericArg>, bindings: Vec<TypeBinding> },
123     /// Fn(A, B) -> C
124     Parenthesized { inputs: Vec<Type>, output: Option<Type> },
125 }
126
127 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
128 #[serde(rename_all = "snake_case")]
129 pub enum GenericArg {
130     Lifetime(String),
131     Type(Type),
132     Const(Constant),
133     Infer,
134 }
135
136 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
137 pub struct Constant {
138     #[serde(rename = "type")]
139     pub type_: Type,
140     pub expr: String,
141     pub value: Option<String>,
142     pub is_literal: bool,
143 }
144
145 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
146 pub struct TypeBinding {
147     pub name: String,
148     pub args: GenericArgs,
149     pub binding: TypeBindingKind,
150 }
151
152 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
153 #[serde(rename_all = "snake_case")]
154 pub enum TypeBindingKind {
155     Equality(Term),
156     Constraint(Vec<GenericBound>),
157 }
158
159 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
160 pub struct Id(pub String);
161
162 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
163 #[serde(rename_all = "snake_case")]
164 pub enum ItemKind {
165     Module,
166     ExternCrate,
167     Import,
168     Struct,
169     StructField,
170     Union,
171     Enum,
172     Variant,
173     Function,
174     Typedef,
175     OpaqueTy,
176     Constant,
177     Trait,
178     TraitAlias,
179     Method,
180     Impl,
181     Static,
182     ForeignType,
183     Macro,
184     ProcAttribute,
185     ProcDerive,
186     AssocConst,
187     AssocType,
188     Primitive,
189     Keyword,
190 }
191
192 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
193 #[serde(tag = "kind", content = "inner", rename_all = "snake_case")]
194 pub enum ItemEnum {
195     Module(Module),
196     ExternCrate {
197         name: String,
198         rename: Option<String>,
199     },
200     Import(Import),
201
202     Union(Union),
203     Struct(Struct),
204     StructField(Type),
205     Enum(Enum),
206     Variant(Variant),
207
208     Function(Function),
209
210     Trait(Trait),
211     TraitAlias(TraitAlias),
212     Method(Method),
213     Impl(Impl),
214
215     Typedef(Typedef),
216     OpaqueTy(OpaqueTy),
217     Constant(Constant),
218
219     Static(Static),
220
221     /// `type`s from an extern block
222     ForeignType,
223
224     /// Declarative macro_rules! macro
225     Macro(String),
226     ProcMacro(ProcMacro),
227
228     PrimitiveType(String),
229
230     AssocConst {
231         #[serde(rename = "type")]
232         type_: Type,
233         /// e.g. `const X: usize = 5;`
234         default: Option<String>,
235     },
236     AssocType {
237         generics: Generics,
238         bounds: Vec<GenericBound>,
239         /// e.g. `type X = usize;`
240         default: Option<Type>,
241     },
242 }
243
244 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
245 pub struct Module {
246     pub is_crate: bool,
247     pub items: Vec<Id>,
248     /// If `true`, this module is not part of the public API, but it contains
249     /// items that are re-exported as public API.
250     pub is_stripped: bool,
251 }
252
253 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
254 pub struct Union {
255     pub generics: Generics,
256     pub fields_stripped: bool,
257     pub fields: Vec<Id>,
258     pub impls: Vec<Id>,
259 }
260
261 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
262 pub struct Struct {
263     pub struct_type: StructType,
264     pub generics: Generics,
265     pub fields_stripped: bool,
266     pub fields: Vec<Id>,
267     pub impls: Vec<Id>,
268 }
269
270 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
271 pub struct Enum {
272     pub generics: Generics,
273     pub variants_stripped: bool,
274     pub variants: Vec<Id>,
275     pub impls: Vec<Id>,
276 }
277
278 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
279 #[serde(rename_all = "snake_case")]
280 #[serde(tag = "variant_kind", content = "variant_inner")]
281 pub enum Variant {
282     Plain,
283     Tuple(Vec<Type>),
284     Struct(Vec<Id>),
285 }
286
287 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
288 #[serde(rename_all = "snake_case")]
289 pub enum StructType {
290     Plain,
291     Tuple,
292     Unit,
293 }
294
295 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
296 pub struct Header {
297     #[serde(rename = "const")]
298     pub const_: bool,
299     #[serde(rename = "unsafe")]
300     pub unsafe_: bool,
301     #[serde(rename = "async")]
302     pub async_: bool,
303     pub abi: Abi,
304 }
305
306 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
307 pub enum Abi {
308     // We only have a concrete listing here for stable ABI's because their are so many
309     // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
310     Rust,
311     C { unwind: bool },
312     Cdecl { unwind: bool },
313     Stdcall { unwind: bool },
314     Fastcall { unwind: bool },
315     Aapcs { unwind: bool },
316     Win64 { unwind: bool },
317     SysV64 { unwind: bool },
318     System { unwind: bool },
319     Other(String),
320 }
321
322 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
323 pub struct Function {
324     pub decl: FnDecl,
325     pub generics: Generics,
326     pub header: Header,
327 }
328
329 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
330 pub struct Method {
331     pub decl: FnDecl,
332     pub generics: Generics,
333     pub header: Header,
334     pub has_body: bool,
335 }
336
337 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
338 pub struct Generics {
339     pub params: Vec<GenericParamDef>,
340     pub where_predicates: Vec<WherePredicate>,
341 }
342
343 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
344 pub struct GenericParamDef {
345     pub name: String,
346     pub kind: GenericParamDefKind,
347 }
348
349 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
350 #[serde(rename_all = "snake_case")]
351 pub enum GenericParamDefKind {
352     Lifetime {
353         outlives: Vec<String>,
354     },
355     Type {
356         bounds: Vec<GenericBound>,
357         default: Option<Type>,
358         /// This is normally `false`, which means that this generic parameter is
359         /// declared in the Rust source text.
360         ///
361         /// If it is `true`, this generic parameter has been introduced by the
362         /// compiler behind the scenes.
363         ///
364         /// # Example
365         ///
366         /// Consider
367         ///
368         /// ```ignore (pseudo-rust)
369         /// pub fn f(_: impl Trait) {}
370         /// ```
371         ///
372         /// The compiler will transform this behind the scenes to
373         ///
374         /// ```ignore (pseudo-rust)
375         /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
376         /// ```
377         ///
378         /// In this example, the generic parameter named `impl Trait` (and which
379         /// is bound by `Trait`) is synthetic, because it was not originally in
380         /// the Rust source text.
381         synthetic: bool,
382     },
383     Const {
384         #[serde(rename = "type")]
385         type_: Type,
386         default: Option<String>,
387     },
388 }
389
390 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
391 #[serde(rename_all = "snake_case")]
392 pub enum WherePredicate {
393     BoundPredicate {
394         #[serde(rename = "type")]
395         type_: Type,
396         bounds: Vec<GenericBound>,
397         /// Used for Higher-Rank Trait Bounds (HRTBs)
398         /// ```plain
399         /// where for<'a> &'a T: Iterator,"
400         ///       ^^^^^^^
401         ///       |
402         ///       this part
403         /// ```
404         generic_params: Vec<GenericParamDef>,
405     },
406     RegionPredicate {
407         lifetime: String,
408         bounds: Vec<GenericBound>,
409     },
410     EqPredicate {
411         lhs: Type,
412         rhs: Term,
413     },
414 }
415
416 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
417 #[serde(rename_all = "snake_case")]
418 pub enum GenericBound {
419     TraitBound {
420         #[serde(rename = "trait")]
421         trait_: Type,
422         /// Used for Higher-Rank Trait Bounds (HRTBs)
423         /// ```plain
424         /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
425         ///          ^^^^^^^^^^^
426         ///          |
427         ///          this part
428         /// ```
429         generic_params: Vec<GenericParamDef>,
430         modifier: TraitBoundModifier,
431     },
432     Outlives(String),
433 }
434
435 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
436 #[serde(rename_all = "snake_case")]
437 pub enum TraitBoundModifier {
438     None,
439     Maybe,
440     MaybeConst,
441 }
442
443 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
444 #[serde(rename_all = "snake_case")]
445 pub enum Term {
446     Type(Type),
447     Constant(Constant),
448 }
449
450 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
451 #[serde(rename_all = "snake_case")]
452 #[serde(tag = "kind", content = "inner")]
453 pub enum Type {
454     /// Structs, enums, and traits
455     ResolvedPath {
456         name: String,
457         id: Id,
458         args: Option<Box<GenericArgs>>,
459         param_names: Vec<GenericBound>,
460     },
461     /// Parameterized types
462     Generic(String),
463     /// Fixed-size numeric types (plus int/usize/float), char, arrays, slices, and tuples
464     Primitive(String),
465     /// `extern "ABI" fn`
466     FunctionPointer(Box<FunctionPointer>),
467     /// `(String, u32, Box<usize>)`
468     Tuple(Vec<Type>),
469     /// `[u32]`
470     Slice(Box<Type>),
471     /// [u32; 15]
472     Array {
473         #[serde(rename = "type")]
474         type_: Box<Type>,
475         len: String,
476     },
477     /// `impl TraitA + TraitB + ...`
478     ImplTrait(Vec<GenericBound>),
479     /// `_`
480     Infer,
481     /// `*mut u32`, `*u8`, etc.
482     RawPointer {
483         mutable: bool,
484         #[serde(rename = "type")]
485         type_: Box<Type>,
486     },
487     /// `&'a mut String`, `&str`, etc.
488     BorrowedRef {
489         lifetime: Option<String>,
490         mutable: bool,
491         #[serde(rename = "type")]
492         type_: Box<Type>,
493     },
494     /// `<Type as Trait>::Name` or associated types like `T::Item` where `T: Iterator`
495     QualifiedPath {
496         name: String,
497         args: Box<GenericArgs>,
498         self_type: Box<Type>,
499         #[serde(rename = "trait")]
500         trait_: Box<Type>,
501     },
502 }
503
504 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
505 pub struct FunctionPointer {
506     pub decl: FnDecl,
507     /// Used for Higher-Rank Trait Bounds (HRTBs)
508     /// ```plain
509     /// for<'c> fn(val: &'c i32) -> i32
510     /// ^^^^^^^
511     ///       |
512     ///       this part
513     /// ```
514     pub generic_params: Vec<GenericParamDef>,
515     pub header: Header,
516 }
517
518 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
519 pub struct FnDecl {
520     pub inputs: Vec<(String, Type)>,
521     pub output: Option<Type>,
522     pub c_variadic: bool,
523 }
524
525 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
526 pub struct Trait {
527     pub is_auto: bool,
528     pub is_unsafe: bool,
529     pub items: Vec<Id>,
530     pub generics: Generics,
531     pub bounds: Vec<GenericBound>,
532     pub implementations: Vec<Id>,
533 }
534
535 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
536 pub struct TraitAlias {
537     pub generics: Generics,
538     pub params: Vec<GenericBound>,
539 }
540
541 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
542 pub struct Impl {
543     pub is_unsafe: bool,
544     pub generics: Generics,
545     pub provided_trait_methods: Vec<String>,
546     #[serde(rename = "trait")]
547     pub trait_: Option<Type>,
548     #[serde(rename = "for")]
549     pub for_: Type,
550     pub items: Vec<Id>,
551     pub negative: bool,
552     pub synthetic: bool,
553     pub blanket_impl: Option<Type>,
554 }
555
556 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
557 #[serde(rename_all = "snake_case")]
558 pub struct Import {
559     /// The full path being imported.
560     pub source: String,
561     /// May be different from the last segment of `source` when renaming imports:
562     /// `use source as name;`
563     pub name: String,
564     /// The ID of the item being imported.
565     pub id: Option<Id>, // FIXME is this actually ever None?
566     /// Whether this import uses a glob: `use source::*;`
567     pub glob: bool,
568 }
569
570 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
571 pub struct ProcMacro {
572     pub kind: MacroKind,
573     pub helpers: Vec<String>,
574 }
575
576 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
577 #[serde(rename_all = "snake_case")]
578 pub enum MacroKind {
579     /// A bang macro `foo!()`.
580     Bang,
581     /// An attribute macro `#[foo]`.
582     Attr,
583     /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
584     Derive,
585 }
586
587 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
588 pub struct Typedef {
589     #[serde(rename = "type")]
590     pub type_: Type,
591     pub generics: Generics,
592 }
593
594 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
595 pub struct OpaqueTy {
596     pub bounds: Vec<GenericBound>,
597     pub generics: Generics,
598 }
599
600 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
601 pub struct Static {
602     #[serde(rename = "type")]
603     pub type_: Type,
604     pub mutable: bool,
605     pub expr: String,
606 }
607
608 #[cfg(test)]
609 mod tests;