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