rustc_metadata/rmeta/
mod.rs

1use std::marker::PhantomData;
2use std::num::NonZero;
3
4pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob, TargetModifiers};
5use decoder::{DecodeContext, Metadata};
6use def_path_hash_map::DefPathHashMapRef;
7use encoder::EncodeContext;
8pub use encoder::{EncodedMetadata, encode_metadata, rendered_const};
9pub(crate) use parameterized::ParameterizedOverTcx;
10use rustc_abi::{FieldIdx, ReprOptions, VariantIdx};
11use rustc_data_structures::fx::FxHashMap;
12use rustc_data_structures::svh::Svh;
13use rustc_hir::attrs::StrippedCfgItem;
14use rustc_hir::def::{CtorKind, DefKind, DocLinkResMap, MacroKinds};
15use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIndex, DefPathHash, StableCrateId};
16use rustc_hir::definitions::DefKey;
17use rustc_hir::lang_items::LangItem;
18use rustc_hir::{PreciseCapturingArgKind, attrs};
19use rustc_index::IndexVec;
20use rustc_index::bit_set::DenseBitSet;
21use rustc_macros::{
22    Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable,
23};
24use rustc_middle::metadata::ModChild;
25use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
26use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
27use rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs;
28use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
29use rustc_middle::middle::lib_features::FeatureStability;
30use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
31use rustc_middle::mir;
32use rustc_middle::ty::fast_reject::SimplifiedType;
33use rustc_middle::ty::{self, Ty, TyCtxt, UnusedGenericParams};
34use rustc_middle::util::Providers;
35use rustc_serialize::opaque::FileEncoder;
36use rustc_session::config::{SymbolManglingVersion, TargetModifier};
37use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
38use rustc_span::edition::Edition;
39use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextKey};
40use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Ident, Span, Symbol};
41use rustc_target::spec::{PanicStrategy, TargetTuple};
42use table::TableBuilder;
43use {rustc_ast as ast, rustc_hir as hir};
44
45use crate::creader::CrateMetadataRef;
46
47mod decoder;
48mod def_path_hash_map;
49mod encoder;
50mod parameterized;
51mod table;
52
53pub(crate) fn rustc_version(cfg_version: &'static str) -> String {
54    format!("rustc {cfg_version}")
55}
56
57/// Metadata encoding version.
58/// N.B., increment this if you change the format of metadata such that
59/// the rustc version can't be found to compare with `rustc_version()`.
60const METADATA_VERSION: u8 = 10;
61
62/// Metadata header which includes `METADATA_VERSION`.
63///
64/// This header is followed by the length of the compressed data, then
65/// the position of the `CrateRoot`, which is encoded as a 64-bit little-endian
66/// unsigned integer, and further followed by the rustc version string.
67pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
68
69/// A value of type T referred to by its absolute position
70/// in the metadata, and which can be decoded lazily.
71///
72/// Metadata is effective a tree, encoded in post-order,
73/// and with the root's position written next to the header.
74/// That means every single `LazyValue` points to some previous
75/// location in the metadata and is part of a larger node.
76///
77/// The first `LazyValue` in a node is encoded as the backwards
78/// distance from the position where the containing node
79/// starts and where the `LazyValue` points to, while the rest
80/// use the forward distance from the previous `LazyValue`.
81/// Distances start at 1, as 0-byte nodes are invalid.
82/// Also invalid are nodes being referred in a different
83/// order than they were encoded in.
84#[must_use]
85struct LazyValue<T> {
86    position: NonZero<usize>,
87    _marker: PhantomData<fn() -> T>,
88}
89
90impl<T> LazyValue<T> {
91    fn from_position(position: NonZero<usize>) -> LazyValue<T> {
92        LazyValue { position, _marker: PhantomData }
93    }
94}
95
96/// A list of lazily-decoded values.
97///
98/// Unlike `LazyValue<Vec<T>>`, the length is encoded next to the
99/// position, not at the position, which means that the length
100/// doesn't need to be known before encoding all the elements.
101///
102/// If the length is 0, no position is encoded, but otherwise,
103/// the encoding is that of `LazyArray`, with the distinction that
104/// the minimal distance the length of the sequence, i.e.
105/// it's assumed there's no 0-byte element in the sequence.
106struct LazyArray<T> {
107    position: NonZero<usize>,
108    num_elems: usize,
109    _marker: PhantomData<fn() -> T>,
110}
111
112impl<T> Default for LazyArray<T> {
113    fn default() -> LazyArray<T> {
114        LazyArray::from_position_and_num_elems(NonZero::new(1).unwrap(), 0)
115    }
116}
117
118impl<T> LazyArray<T> {
119    fn from_position_and_num_elems(position: NonZero<usize>, num_elems: usize) -> LazyArray<T> {
120        LazyArray { position, num_elems, _marker: PhantomData }
121    }
122}
123
124/// A list of lazily-decoded values, with the added capability of random access.
125///
126/// Random-access table (i.e. offering constant-time `get`/`set`), similar to
127/// `LazyArray<T>`, but without requiring encoding or decoding all the values
128/// eagerly and in-order.
129struct LazyTable<I, T> {
130    position: NonZero<usize>,
131    /// The encoded size of the elements of a table is selected at runtime to drop
132    /// trailing zeroes. This is the number of bytes used for each table element.
133    width: usize,
134    /// How many elements are in the table.
135    len: usize,
136    _marker: PhantomData<fn(I) -> T>,
137}
138
139impl<I, T> LazyTable<I, T> {
140    fn from_position_and_encoded_size(
141        position: NonZero<usize>,
142        width: usize,
143        len: usize,
144    ) -> LazyTable<I, T> {
145        LazyTable { position, width, len, _marker: PhantomData }
146    }
147}
148
149impl<T> Copy for LazyValue<T> {}
150impl<T> Clone for LazyValue<T> {
151    fn clone(&self) -> Self {
152        *self
153    }
154}
155
156impl<T> Copy for LazyArray<T> {}
157impl<T> Clone for LazyArray<T> {
158    fn clone(&self) -> Self {
159        *self
160    }
161}
162
163impl<I, T> Copy for LazyTable<I, T> {}
164impl<I, T> Clone for LazyTable<I, T> {
165    fn clone(&self) -> Self {
166        *self
167    }
168}
169
170/// Encoding / decoding state for `Lazy`s (`LazyValue`, `LazyArray`, and `LazyTable`).
171#[derive(Copy, Clone, PartialEq, Eq, Debug)]
172enum LazyState {
173    /// Outside of a metadata node.
174    NoNode,
175
176    /// Inside a metadata node, and before any `Lazy`s.
177    /// The position is that of the node itself.
178    NodeStart(NonZero<usize>),
179
180    /// Inside a metadata node, with a previous `Lazy`s.
181    /// The position is where that previous `Lazy` would start.
182    Previous(NonZero<usize>),
183}
184
185type SyntaxContextTable = LazyTable<u32, Option<LazyValue<SyntaxContextKey>>>;
186type ExpnDataTable = LazyTable<ExpnIndex, Option<LazyValue<ExpnData>>>;
187type ExpnHashTable = LazyTable<ExpnIndex, Option<LazyValue<ExpnHash>>>;
188
189#[derive(MetadataEncodable, MetadataDecodable)]
190pub(crate) struct ProcMacroData {
191    proc_macro_decls_static: DefIndex,
192    stability: Option<hir::Stability>,
193    macros: LazyArray<DefIndex>,
194}
195
196/// Serialized crate metadata.
197///
198/// This contains just enough information to determine if we should load the `CrateRoot` or not.
199/// Prefer [`CrateRoot`] whenever possible to avoid ICEs when using `omit-git-hash` locally.
200/// See #76720 for more details.
201///
202/// If you do modify this struct, also bump the [`METADATA_VERSION`] constant.
203#[derive(MetadataEncodable, MetadataDecodable)]
204pub(crate) struct CrateHeader {
205    pub(crate) triple: TargetTuple,
206    pub(crate) hash: Svh,
207    pub(crate) name: Symbol,
208    /// Whether this is the header for a proc-macro crate.
209    ///
210    /// This is separate from [`ProcMacroData`] to avoid having to update [`METADATA_VERSION`] every
211    /// time ProcMacroData changes.
212    pub(crate) is_proc_macro_crate: bool,
213    /// Whether this crate metadata section is just a stub.
214    /// Stubs do not contain the full metadata (it will be typically stored
215    /// in a separate rmeta file).
216    ///
217    /// This is used inside rlibs and dylibs when using `-Zembed-metadata=no`.
218    pub(crate) is_stub: bool,
219}
220
221/// Serialized `.rmeta` data for a crate.
222///
223/// When compiling a proc-macro crate, we encode many of
224/// the `LazyArray<T>` fields as `Lazy::empty()`. This serves two purposes:
225///
226/// 1. We avoid performing unnecessary work. Proc-macro crates can only
227/// export proc-macros functions, which are compiled into a shared library.
228/// As a result, a large amount of the information we normally store
229/// (e.g. optimized MIR) is unneeded by downstream crates.
230/// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
231/// a proc-macro crate, we don't load any of its dependencies (since we
232/// just need to invoke a native function from the shared library).
233/// This means that any foreign `CrateNum`s that we serialize cannot be
234/// deserialized, since we will not know how to map them into the current
235/// compilation session. If we were to serialize a proc-macro crate like
236/// a normal crate, much of what we serialized would be unusable in addition
237/// to being unused.
238#[derive(MetadataEncodable, MetadataDecodable)]
239pub(crate) struct CrateRoot {
240    /// A header used to detect if this is the right crate to load.
241    header: CrateHeader,
242
243    extra_filename: String,
244    stable_crate_id: StableCrateId,
245    required_panic_strategy: Option<PanicStrategy>,
246    panic_in_drop_strategy: PanicStrategy,
247    edition: Edition,
248    has_global_allocator: bool,
249    has_alloc_error_handler: bool,
250    has_panic_handler: bool,
251    has_default_lib_allocator: bool,
252
253    crate_deps: LazyArray<CrateDep>,
254    dylib_dependency_formats: LazyArray<Option<LinkagePreference>>,
255    lib_features: LazyArray<(Symbol, FeatureStability)>,
256    stability_implications: LazyArray<(Symbol, Symbol)>,
257    lang_items: LazyArray<(DefIndex, LangItem)>,
258    lang_items_missing: LazyArray<LangItem>,
259    stripped_cfg_items: LazyArray<StrippedCfgItem<DefIndex>>,
260    diagnostic_items: LazyArray<(Symbol, DefIndex)>,
261    native_libraries: LazyArray<NativeLib>,
262    foreign_modules: LazyArray<ForeignModule>,
263    traits: LazyArray<DefIndex>,
264    impls: LazyArray<TraitImpls>,
265    incoherent_impls: LazyArray<IncoherentImpls>,
266    interpret_alloc_index: LazyArray<u64>,
267    proc_macro_data: Option<ProcMacroData>,
268
269    tables: LazyTables,
270    debugger_visualizers: LazyArray<DebuggerVisualizerFile>,
271
272    exportable_items: LazyArray<DefIndex>,
273    stable_order_of_exportable_impls: LazyArray<(DefIndex, usize)>,
274    exported_non_generic_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
275    exported_generic_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
276
277    syntax_contexts: SyntaxContextTable,
278    expn_data: ExpnDataTable,
279    expn_hashes: ExpnHashTable,
280
281    def_path_hash_map: LazyValue<DefPathHashMapRef<'static>>,
282
283    source_map: LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>>,
284    target_modifiers: LazyArray<TargetModifier>,
285
286    compiler_builtins: bool,
287    needs_allocator: bool,
288    needs_panic_runtime: bool,
289    no_builtins: bool,
290    panic_runtime: bool,
291    profiler_runtime: bool,
292    symbol_mangling_version: SymbolManglingVersion,
293
294    specialization_enabled_in: bool,
295}
296
297/// On-disk representation of `DefId`.
298/// This creates a type-safe way to enforce that we remap the CrateNum between the on-disk
299/// representation and the compilation session.
300#[derive(Copy, Clone)]
301pub(crate) struct RawDefId {
302    krate: u32,
303    index: u32,
304}
305
306impl From<DefId> for RawDefId {
307    fn from(val: DefId) -> Self {
308        RawDefId { krate: val.krate.as_u32(), index: val.index.as_u32() }
309    }
310}
311
312impl RawDefId {
313    /// This exists so that `provide_one!` is happy
314    fn decode(self, meta: (CrateMetadataRef<'_>, TyCtxt<'_>)) -> DefId {
315        self.decode_from_cdata(meta.0)
316    }
317
318    fn decode_from_cdata(self, cdata: CrateMetadataRef<'_>) -> DefId {
319        let krate = CrateNum::from_u32(self.krate);
320        let krate = cdata.map_encoded_cnum_to_current(krate);
321        DefId { krate, index: DefIndex::from_u32(self.index) }
322    }
323}
324
325#[derive(Encodable, Decodable)]
326pub(crate) struct CrateDep {
327    pub name: Symbol,
328    pub hash: Svh,
329    pub host_hash: Option<Svh>,
330    pub kind: CrateDepKind,
331    pub extra_filename: String,
332    pub is_private: bool,
333}
334
335#[derive(MetadataEncodable, MetadataDecodable)]
336pub(crate) struct TraitImpls {
337    trait_id: (u32, DefIndex),
338    impls: LazyArray<(DefIndex, Option<SimplifiedType>)>,
339}
340
341#[derive(MetadataEncodable, MetadataDecodable)]
342pub(crate) struct IncoherentImpls {
343    self_ty: SimplifiedType,
344    impls: LazyArray<DefIndex>,
345}
346
347/// Define `LazyTables` and `TableBuilders` at the same time.
348macro_rules! define_tables {
349    (
350        - defaulted: $($name1:ident: Table<$IDX1:ty, $T1:ty>,)+
351        - optional: $($name2:ident: Table<$IDX2:ty, $T2:ty>,)+
352    ) => {
353        #[derive(MetadataEncodable, MetadataDecodable)]
354        pub(crate) struct LazyTables {
355            $($name1: LazyTable<$IDX1, $T1>,)+
356            $($name2: LazyTable<$IDX2, Option<$T2>>,)+
357        }
358
359        #[derive(Default)]
360        struct TableBuilders {
361            $($name1: TableBuilder<$IDX1, $T1>,)+
362            $($name2: TableBuilder<$IDX2, Option<$T2>>,)+
363        }
364
365        impl TableBuilders {
366            fn encode(&self, buf: &mut FileEncoder) -> LazyTables {
367                LazyTables {
368                    $($name1: self.$name1.encode(buf),)+
369                    $($name2: self.$name2.encode(buf),)+
370                }
371            }
372        }
373    }
374}
375
376define_tables! {
377- defaulted:
378    intrinsic: Table<DefIndex, Option<LazyValue<ty::IntrinsicDef>>>,
379    is_macro_rules: Table<DefIndex, bool>,
380    type_alias_is_lazy: Table<DefIndex, bool>,
381    attr_flags: Table<DefIndex, AttrFlags>,
382    // The u64 is the crate-local part of the DefPathHash. All hashes in this crate have the same
383    // StableCrateId, so we omit encoding those into the table.
384    //
385    // Note also that this table is fully populated (no gaps) as every DefIndex should have a
386    // corresponding DefPathHash.
387    def_path_hashes: Table<DefIndex, u64>,
388    explicit_item_bounds: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
389    explicit_item_self_bounds: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
390    inferred_outlives_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
391    explicit_super_predicates_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
392    explicit_implied_predicates_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
393    explicit_implied_const_bounds: Table<DefIndex, LazyArray<(ty::PolyTraitRef<'static>, Span)>>,
394    inherent_impls: Table<DefIndex, LazyArray<DefIndex>>,
395    opt_rpitit_info: Table<DefIndex, Option<LazyValue<ty::ImplTraitInTraitData>>>,
396    // Reexported names are not associated with individual `DefId`s,
397    // e.g. a glob import can introduce a lot of names, all with the same `DefId`.
398    // That's why the encoded list needs to contain `ModChild` structures describing all the names
399    // individually instead of `DefId`s.
400    module_children_reexports: Table<DefIndex, LazyArray<ModChild>>,
401    cross_crate_inlinable: Table<DefIndex, bool>,
402
403- optional:
404    attributes: Table<DefIndex, LazyArray<hir::Attribute>>,
405    // For non-reexported names in a module every name is associated with a separate `DefId`,
406    // so we can take their names, visibilities etc from other encoded tables.
407    module_children_non_reexports: Table<DefIndex, LazyArray<DefIndex>>,
408    associated_item_or_field_def_ids: Table<DefIndex, LazyArray<DefIndex>>,
409    def_kind: Table<DefIndex, DefKind>,
410    visibility: Table<DefIndex, LazyValue<ty::Visibility<DefIndex>>>,
411    safety: Table<DefIndex, hir::Safety>,
412    def_span: Table<DefIndex, LazyValue<Span>>,
413    def_ident_span: Table<DefIndex, LazyValue<Span>>,
414    lookup_stability: Table<DefIndex, LazyValue<hir::Stability>>,
415    lookup_const_stability: Table<DefIndex, LazyValue<hir::ConstStability>>,
416    lookup_default_body_stability: Table<DefIndex, LazyValue<hir::DefaultBodyStability>>,
417    lookup_deprecation_entry: Table<DefIndex, LazyValue<attrs::Deprecation>>,
418    explicit_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'static>>>,
419    generics_of: Table<DefIndex, LazyValue<ty::Generics>>,
420    type_of: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, Ty<'static>>>>,
421    variances_of: Table<DefIndex, LazyArray<ty::Variance>>,
422    fn_sig: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, ty::PolyFnSig<'static>>>>,
423    codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>,
424    impl_trait_header: Table<DefIndex, LazyValue<ty::ImplTraitHeader<'static>>>,
425    const_param_default: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, rustc_middle::ty::Const<'static>>>>,
426    object_lifetime_default: Table<DefIndex, LazyValue<ObjectLifetimeDefault>>,
427    optimized_mir: Table<DefIndex, LazyValue<mir::Body<'static>>>,
428    mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>,
429    closure_saved_names_of_captured_variables: Table<DefIndex, LazyValue<IndexVec<FieldIdx, Symbol>>>,
430    mir_coroutine_witnesses: Table<DefIndex, LazyValue<mir::CoroutineLayout<'static>>>,
431    promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'static>>>>,
432    thir_abstract_const: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, ty::Const<'static>>>>,
433    impl_parent: Table<DefIndex, RawDefId>,
434    constness: Table<DefIndex, hir::Constness>,
435    const_conditions: Table<DefIndex, LazyValue<ty::ConstConditions<'static>>>,
436    defaultness: Table<DefIndex, hir::Defaultness>,
437    // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
438    coerce_unsized_info: Table<DefIndex, LazyValue<ty::adjustment::CoerceUnsizedInfo>>,
439    mir_const_qualif: Table<DefIndex, LazyValue<mir::ConstQualifs>>,
440    rendered_const: Table<DefIndex, LazyValue<String>>,
441    rendered_precise_capturing_args: Table<DefIndex, LazyArray<PreciseCapturingArgKind<Symbol, Symbol>>>,
442    asyncness: Table<DefIndex, ty::Asyncness>,
443    fn_arg_idents: Table<DefIndex, LazyArray<Option<Ident>>>,
444    coroutine_kind: Table<DefIndex, hir::CoroutineKind>,
445    coroutine_for_closure: Table<DefIndex, RawDefId>,
446    adt_destructor: Table<DefIndex, LazyValue<ty::Destructor>>,
447    adt_async_destructor: Table<DefIndex, LazyValue<ty::AsyncDestructor>>,
448    coroutine_by_move_body_def_id: Table<DefIndex, RawDefId>,
449    eval_static_initializer: Table<DefIndex, LazyValue<mir::interpret::ConstAllocation<'static>>>,
450    trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>,
451    expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>,
452    default_fields: Table<DefIndex, LazyValue<DefId>>,
453    params_in_repr: Table<DefIndex, LazyValue<DenseBitSet<u32>>>,
454    repr_options: Table<DefIndex, LazyValue<ReprOptions>>,
455    // `def_keys` and `def_path_hashes` represent a lazy version of a
456    // `DefPathTable`. This allows us to avoid deserializing an entire
457    // `DefPathTable` up front, since we may only ever use a few
458    // definitions from any given crate.
459    def_keys: Table<DefIndex, LazyValue<DefKey>>,
460    proc_macro_quoted_spans: Table<usize, LazyValue<Span>>,
461    variant_data: Table<DefIndex, LazyValue<VariantData>>,
462    assoc_container: Table<DefIndex, LazyValue<ty::AssocContainer>>,
463    macro_definition: Table<DefIndex, LazyValue<ast::DelimArgs>>,
464    proc_macro: Table<DefIndex, MacroKind>,
465    deduced_param_attrs: Table<DefIndex, LazyArray<DeducedParamAttrs>>,
466    trait_impl_trait_tys: Table<DefIndex, LazyValue<DefIdMap<ty::EarlyBinder<'static, Ty<'static>>>>>,
467    doc_link_resolutions: Table<DefIndex, LazyValue<DocLinkResMap>>,
468    doc_link_traits_in_scope: Table<DefIndex, LazyArray<DefId>>,
469    assumed_wf_types_for_rpitit: Table<DefIndex, LazyArray<(Ty<'static>, Span)>>,
470    opaque_ty_origin: Table<DefIndex, LazyValue<hir::OpaqueTyOrigin<DefId>>>,
471    anon_const_kind: Table<DefIndex, LazyValue<ty::AnonConstKind>>,
472    associated_types_for_impl_traits_in_trait_or_impl: Table<DefIndex, LazyValue<DefIdMap<Vec<DefId>>>>,
473}
474
475#[derive(TyEncodable, TyDecodable)]
476struct VariantData {
477    idx: VariantIdx,
478    discr: ty::VariantDiscr,
479    /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
480    ctor: Option<(CtorKind, DefIndex)>,
481    is_non_exhaustive: bool,
482}
483
484bitflags::bitflags! {
485    #[derive(Default)]
486    pub struct AttrFlags: u8 {
487        const IS_DOC_HIDDEN = 1 << 0;
488    }
489}
490
491/// A span tag byte encodes a bunch of data, so that we can cut out a few extra bytes from span
492/// encodings (which are very common, for example, libcore has ~650,000 unique spans and over 1.1
493/// million references to prior-written spans).
494///
495/// The byte format is split into several parts:
496///
497/// [ a a a a a c d d ]
498///
499/// `a` bits represent the span length. We have 5 bits, so we can store lengths up to 30 inline, with
500/// an all-1s pattern representing that the length is stored separately.
501///
502/// `c` represents whether the span context is zero (and then it is not stored as a separate varint)
503/// for direct span encodings, and whether the offset is absolute or relative otherwise (zero for
504/// absolute).
505///
506/// d bits represent the kind of span we are storing (local, foreign, partial, indirect).
507#[derive(Encodable, Decodable, Copy, Clone)]
508struct SpanTag(u8);
509
510#[derive(Debug, Copy, Clone, PartialEq, Eq)]
511enum SpanKind {
512    Local = 0b00,
513    Foreign = 0b01,
514    Partial = 0b10,
515    // Indicates the actual span contents are elsewhere.
516    // If this is the kind, then the span context bit represents whether it is a relative or
517    // absolute offset.
518    Indirect = 0b11,
519}
520
521impl SpanTag {
522    fn new(kind: SpanKind, context: rustc_span::SyntaxContext, length: usize) -> SpanTag {
523        let mut data = 0u8;
524        data |= kind as u8;
525        if context.is_root() {
526            data |= 0b100;
527        }
528        let all_1s_len = (0xffu8 << 3) >> 3;
529        // strictly less than - all 1s pattern is a sentinel for storage being out of band.
530        if length < all_1s_len as usize {
531            data |= (length as u8) << 3;
532        } else {
533            data |= all_1s_len << 3;
534        }
535
536        SpanTag(data)
537    }
538
539    fn indirect(relative: bool, length_bytes: u8) -> SpanTag {
540        let mut tag = SpanTag(SpanKind::Indirect as u8);
541        if relative {
542            tag.0 |= 0b100;
543        }
544        assert!(length_bytes <= 8);
545        tag.0 |= length_bytes << 3;
546        tag
547    }
548
549    fn kind(self) -> SpanKind {
550        let masked = self.0 & 0b11;
551        match masked {
552            0b00 => SpanKind::Local,
553            0b01 => SpanKind::Foreign,
554            0b10 => SpanKind::Partial,
555            0b11 => SpanKind::Indirect,
556            _ => unreachable!(),
557        }
558    }
559
560    fn is_relative_offset(self) -> bool {
561        debug_assert_eq!(self.kind(), SpanKind::Indirect);
562        self.0 & 0b100 != 0
563    }
564
565    fn context(self) -> Option<rustc_span::SyntaxContext> {
566        if self.0 & 0b100 != 0 { Some(rustc_span::SyntaxContext::root()) } else { None }
567    }
568
569    fn length(self) -> Option<rustc_span::BytePos> {
570        let all_1s_len = (0xffu8 << 3) >> 3;
571        let len = self.0 >> 3;
572        if len != all_1s_len { Some(rustc_span::BytePos(u32::from(len))) } else { None }
573    }
574}
575
576// Tags for encoding Symbol's
577const SYMBOL_STR: u8 = 0;
578const SYMBOL_OFFSET: u8 = 1;
579const SYMBOL_PREDEFINED: u8 = 2;
580
581pub fn provide(providers: &mut Providers) {
582    encoder::provide(providers);
583    decoder::provide(providers);
584}