Skip to main content

cairo_lang_filesystem/
db.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use cairo_lang_utils::Intern;
7use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
8use salsa::{Database, Setter};
9use semver::Version;
10use serde::{Deserialize, Serialize};
11use smol_str::SmolStr;
12
13use crate::cfg::CfgSet;
14use crate::flag::Flag;
15use crate::ids::{
16    ArcStr, BlobId, BlobLongId, CodeMapping, CodeOrigin, CrateId, CrateInput, CrateLongId,
17    Directory, DirectoryInput, FileId, FileInput, FileLongId, FlagLongId, SmolStrId, SpanInFile,
18    Tracked, VirtualFile,
19};
20use crate::span::{FileSummary, TextOffset, TextSpan, TextWidth};
21
22#[cfg(test)]
23#[path = "db_test.rs"]
24mod test;
25
26pub const CORELIB_CRATE_NAME: &str = "core";
27pub const CORELIB_VERSION: &str = env!("CARGO_PKG_VERSION");
28
29/// Unique identifier of a crate.
30///
31/// This directly translates to [DependencySettings::discriminator] except the discriminator
32/// **must** be `None` for the core crate.
33#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Hash)]
34pub struct CrateIdentifier(String);
35
36impl<T: ToString> From<T> for CrateIdentifier {
37    fn from(value: T) -> Self {
38        Self(value.to_string())
39    }
40}
41
42impl From<CrateIdentifier> for String {
43    fn from(value: CrateIdentifier) -> Self {
44        value.0
45    }
46}
47
48/// Same as `CrateConfiguration` but without interning the root directory.
49/// This is used to avoid the need to intern the file id inside salsa database inputs.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct CrateConfigurationInput {
52    pub root: DirectoryInput,
53    pub settings: CrateSettings,
54    pub cache_file: Option<BlobLongId>,
55}
56
57impl CrateConfigurationInput {
58    /// Converts the input into an [`CrateConfiguration`].
59    pub fn into_crate_configuration(self, db: &dyn Database) -> CrateConfiguration<'_> {
60        CrateConfiguration {
61            root: self.root.into_directory(db),
62            settings: self.settings,
63            cache_file: self.cache_file.map(|blob_long_id| blob_long_id.intern(db)),
64        }
65    }
66}
67
68/// A configuration per crate.
69#[derive(Clone, Debug, PartialEq, Eq, Hash, salsa::Update)]
70pub struct CrateConfiguration<'db> {
71    /// The root directory of the crate.
72    pub root: Directory<'db>,
73    pub settings: CrateSettings,
74    pub cache_file: Option<BlobId<'db>>,
75}
76impl<'db> CrateConfiguration<'db> {
77    /// Returns a new configuration.
78    pub fn default_for_root(root: Directory<'db>) -> Self {
79        Self { root, settings: CrateSettings::default(), cache_file: None }
80    }
81
82    /// Converts the configuration into an [`CrateConfigurationInput`].
83    pub fn into_crate_configuration_input(self, db: &dyn Database) -> CrateConfigurationInput {
84        CrateConfigurationInput {
85            root: self.root.into_directory_input(db),
86            settings: self.settings,
87            cache_file: self.cache_file.map(|blob_id| blob_id.long(db).clone()),
88        }
89    }
90}
91
92/// Same as `CrateConfiguration` but without the root directory.
93#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
94pub struct CrateSettings {
95    /// The name reflecting how the crate is referred to in the Cairo code e.g. `use crate_name::`.
96    /// If set to [`None`] then [`CrateIdentifier`] key will be used as a name.
97    pub name: Option<String>,
98    /// The crate's Cairo edition.
99    pub edition: Edition,
100    /// The crate's version.
101    ///
102    /// ## [CrateSettings::version] vs. [DependencySettings::discriminator]
103    ///
104    /// Cairo uses semantic versioning for crates.
105    /// The version field is an optional piece of metadata that can be attached to a crate
106    /// and is used in various lints and can be used as a context in diagnostics.
107    ///
108    /// On the other hand, the discriminator is a unique identifier that allows including multiple
109    /// copies of a crate in a single compilation unit.
110    /// It is free-form and never reaches the user.
111    pub version: Option<Version>,
112    /// The `#[cfg(...)]` configuration.
113    pub cfg_set: Option<CfgSet>,
114    /// The crate's dependencies.
115    #[serde(default)]
116    pub dependencies: BTreeMap<String, DependencySettings>,
117
118    #[serde(default)]
119    pub experimental_features: ExperimentalFeaturesConfig,
120}
121
122/// Tracked function to return the default settings for a crate.
123/// This is used to initialize the default settings once, and return it by reference.
124#[salsa::tracked(returns(ref))]
125pub fn default_crate_settings<'db>(_db: &'db dyn Database) -> CrateSettings {
126    CrateSettings::default()
127}
128
129/// The Cairo edition of a crate.
130///
131/// Editions are a mechanism to allow breaking changes in the compiler.
132/// Compiler minor version updates will always support all editions supported by the previous
133/// updates with the same major version. Compiler major version updates may remove support for older
134/// editions. Editions may be added to provide features that are not backwards compatible, while
135/// allowing user to opt-in to them, and be ready for later compiler updates.
136#[derive(
137    Clone, Copy, Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize, salsa::Update,
138)]
139pub enum Edition {
140    /// The base edition, dated for the first release of the compiler.
141    #[default]
142    #[serde(rename = "2023_01")]
143    V2023_01,
144    #[serde(rename = "2023_10")]
145    V2023_10,
146    #[serde(rename = "2023_11")]
147    V2023_11,
148    #[serde(rename = "2024_07")]
149    V2024_07,
150    #[serde(rename = "2025_12")]
151    V2025_12,
152}
153impl Edition {
154    /// Returns the latest stable edition.
155    ///
156    /// This Cairo edition is recommended for use in new projects and, in case of existing projects,
157    /// to migrate to when possible.
158    pub const fn latest() -> Self {
159        Self::V2025_12
160    }
161
162    /// The name of the prelude submodule of `core::prelude` for this compatibility version.
163    pub fn prelude_submodule_name<'db>(&self, db: &'db dyn Database) -> SmolStrId<'db> {
164        SmolStrId::from(
165            db,
166            match self {
167                Self::V2023_01 => "v2023_01",
168                Self::V2023_10 | Self::V2023_11 => "v2023_10",
169                Self::V2024_07 | Self::V2025_12 => "v2024_07",
170            },
171        )
172    }
173
174    /// Whether to ignore visibility modifiers.
175    pub fn ignore_visibility(&self) -> bool {
176        match self {
177            Self::V2023_01 | Self::V2023_10 => true,
178            Self::V2023_11 | Self::V2024_07 | Self::V2025_12 => false,
179        }
180    }
181
182    /// Whether to member access have the original type of the member.
183    pub fn member_access_desnaps(&self) -> bool {
184        match self {
185            Self::V2023_01 | Self::V2023_10 | Self::V2023_11 | Self::V2024_07 => false,
186            Self::V2025_12 => true,
187        }
188    }
189}
190
191/// The settings for a dependency.
192#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
193pub struct DependencySettings {
194    /// A unique string allowing identifying different copies of the same dependency
195    /// in the compilation unit.
196    ///
197    /// Usually such copies differ by their versions or sources (or both).
198    /// It **must** be [`None`] for the core crate, for other crates it should be directly
199    /// translated from their [`CrateIdentifier`].
200    pub discriminator: Option<String>,
201}
202
203/// Configuration per crate.
204#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
205pub struct ExperimentalFeaturesConfig {
206    pub negative_impls: bool,
207    /// Allows using associated item constraints.
208    pub associated_item_constraints: bool,
209    /// Allows using coupon types and coupon calls.
210    ///
211    /// Each function has an associated `Coupon` type, which represents paying the cost of the
212    /// function before calling it.
213    #[serde(default)]
214    pub coupons: bool,
215    /// Allows using user defined inline macros.
216    #[serde(default)]
217    pub user_defined_inline_macros: bool,
218    /// Allows using representation pointer types (&T), which desugar to BoxTrait<@T>.
219    #[serde(default)]
220    pub repr_ptrs: bool,
221}
222
223/// Function to get a virtual file from an external id.
224pub type ExtAsVirtual =
225    Arc<dyn for<'a> Fn(&'a dyn Database, salsa::Id) -> &'a VirtualFile<'a> + Send + Sync>;
226
227#[salsa::input]
228// TODO(eytan-starkware): Change this mechanism to hold input handles on the db struct outside
229// salsa mechanism, and invalidate manually.
230pub struct FilesGroupInput {
231    /// Main input of the project. Lists all the crates configurations.
232    #[returns(ref)]
233    pub crate_configs: Option<OrderedHashMap<CrateInput, CrateConfigurationInput>>,
234    /// Overrides for file content. Mostly used by language server and tests.
235    #[returns(ref)]
236    pub file_overrides: Option<OrderedHashMap<FileInput, Arc<str>>>,
237    // TODO(yuval): consider moving this to a separate crate, or rename this crate.
238    /// The compilation flags.
239    #[returns(ref)]
240    pub flags: Option<OrderedHashMap<FlagLongId, Flag>>,
241    /// The `#[cfg(...)]` options.
242    #[returns(ref)]
243    pub cfg_set: Option<CfgSet>,
244    #[returns(ref)]
245    pub ext_as_virtual_obj: Option<ExtAsVirtual>,
246}
247
248#[salsa::tracked]
249pub fn files_group_input(db: &dyn Database) -> FilesGroupInput {
250    FilesGroupInput::new(db, None, None, None, None, None)
251}
252
253/// Queries over the files group.
254pub trait FilesGroup: Database {
255    /// Interned version of `crate_configs_input`.
256    fn crate_configs<'db>(&'db self) -> &'db OrderedHashMap<CrateId<'db>, CrateConfiguration<'db>> {
257        crate_configs(self.as_dyn_database())
258    }
259
260    /// Interned version of `file_overrides_input`.
261    fn file_overrides<'db>(&'db self) -> &'db OrderedHashMap<FileId<'db>, ArcStr> {
262        file_overrides(self.as_dyn_database())
263    }
264
265    /// List of crates in the project.
266    fn crates<'db>(&'db self) -> &'db [CrateId<'db>] {
267        crates(self.as_dyn_database())
268    }
269
270    /// Configuration of the crate.
271    fn crate_config<'db>(
272        &'db self,
273        crate_id: CrateId<'db>,
274    ) -> Option<&'db CrateConfiguration<'db>> {
275        crate_config(self.as_dyn_database(), crate_id)
276    }
277
278    /// Query for the file contents. This takes overrides into consideration.
279    fn file_content<'db>(&'db self, file_id: FileId<'db>) -> Option<&'db str> {
280        file_content(self.as_dyn_database(), file_id).as_ref().map(|content| content.as_ref())
281    }
282
283    fn file_summary<'db>(&'db self, file_id: FileId<'db>) -> Option<&'db FileSummary> {
284        file_summary(self.as_dyn_database(), file_id)
285    }
286
287    /// Query for the blob content.
288    fn blob_content<'db>(&'db self, blob_id: BlobId<'db>) -> Option<&'db [u8]> {
289        blob_content(self.as_dyn_database(), blob_id)
290    }
291
292    /// Creates an input file from an interned file id.
293    fn file_input<'db>(&'db self, file_id: FileId<'db>) -> &'db FileInput {
294        file_input(self.as_dyn_database(), file_id)
295    }
296
297    /// Creates an input crate from an interned crate id.
298    fn crate_input<'db>(&'db self, crt: CrateId<'db>) -> &'db CrateInput {
299        crate_input(self.as_dyn_database(), crt)
300    }
301
302    /// Merges specified [`CfgSet`] into one already stored in this db.
303    fn use_cfg(&mut self, cfg_set: &CfgSet) {
304        let db_ref = self.as_dyn_database();
305        let existing = cfg_set_helper(db_ref);
306        let merged = existing.union(cfg_set);
307        files_group_input(db_ref).set_cfg_set(self).to(Some(merged));
308    }
309
310    /// Returns the cfg set.
311    fn cfg_set(&self) -> &CfgSet {
312        cfg_set_helper(self.as_dyn_database())
313    }
314}
315
316impl<T: Database + ?Sized> FilesGroup for T {}
317
318pub fn init_files_group<'db>(db: &mut (dyn Database + 'db)) {
319    // Initialize inputs.
320    let inp = files_group_input(db);
321    inp.set_file_overrides(db).to(Some(Default::default()));
322    inp.set_crate_configs(db).to(Some(Default::default()));
323    inp.set_flags(db).to(Some(Default::default()));
324    inp.set_cfg_set(db).to(Some(Default::default()));
325}
326
327pub fn set_crate_configs_input(
328    db: &mut dyn Database,
329    crate_configs: Option<OrderedHashMap<CrateInput, CrateConfigurationInput>>,
330) {
331    files_group_input(db).set_crate_configs(db).to(crate_configs);
332}
333
334#[salsa::tracked(returns(ref))]
335pub fn file_overrides<'db>(db: &'db dyn Database) -> OrderedHashMap<FileId<'db>, ArcStr> {
336    let inp = files_group_input(db).file_overrides(db).as_ref().expect("file_overrides is not set");
337    inp.iter()
338        .map(|(file_id, content)| {
339            (file_id.clone().into_file_long_id(db).intern(db), ArcStr::new(content.clone()))
340        })
341        .collect()
342}
343
344#[salsa::tracked(returns(ref))]
345pub fn crate_configs<'db>(
346    db: &'db dyn Database,
347) -> OrderedHashMap<CrateId<'db>, CrateConfiguration<'db>> {
348    let inp = files_group_input(db).crate_configs(db).as_ref().expect("crate_configs is not set");
349    inp.iter()
350        .map(|(crate_input, config)| {
351            (
352                crate_input.clone().into_crate_long_id(db).intern(db),
353                config.clone().into_crate_configuration(db),
354            )
355        })
356        .collect()
357}
358
359#[salsa::tracked(returns(ref))]
360fn file_input(db: &dyn Database, file_id: FileId<'_>) -> FileInput {
361    file_id.long(db).into_file_input(db)
362}
363
364#[salsa::tracked(returns(ref))]
365fn crate_input(db: &dyn Database, crt: CrateId<'_>) -> CrateInput {
366    crt.long(db).clone().into_crate_input(db)
367}
368
369#[salsa::tracked(returns(ref))]
370fn crate_configuration_input_helper(
371    db: &dyn Database,
372    _tracked: Tracked,
373    config: CrateConfiguration<'_>,
374) -> CrateConfigurationInput {
375    config.clone().into_crate_configuration_input(db)
376}
377
378fn crate_configuration_input<'db>(
379    db: &'db dyn Database,
380    config: CrateConfiguration<'db>,
381) -> &'db CrateConfigurationInput {
382    crate_configuration_input_helper(db, (), config)
383}
384
385pub fn init_dev_corelib(db: &mut dyn salsa::Database, core_lib_dir: PathBuf) {
386    let core = CrateLongId::core(db).intern(db);
387    let root = CrateConfiguration {
388        root: Directory::Real(core_lib_dir),
389        settings: CrateSettings {
390            name: None,
391            edition: Edition::V2025_12,
392            version: Version::parse(CORELIB_VERSION).ok(),
393            cfg_set: Default::default(),
394            dependencies: Default::default(),
395            experimental_features: ExperimentalFeaturesConfig {
396                negative_impls: true,
397                associated_item_constraints: true,
398                coupons: true,
399                user_defined_inline_macros: true,
400                repr_ptrs: true,
401            },
402        },
403        cache_file: None,
404    };
405    let crate_configs = update_crate_configuration_input_helper(db, core, Some(root));
406    set_crate_configs_input(db, Some(crate_configs));
407}
408
409/// Updates crate configuration input for standalone use.
410pub fn update_crate_configuration_input_helper(
411    db: &dyn Database,
412    crt: CrateId<'_>,
413    root: Option<CrateConfiguration<'_>>,
414) -> OrderedHashMap<CrateInput, CrateConfigurationInput> {
415    let crt = db.crate_input(crt);
416    let db_ref: &dyn Database = db;
417    let mut crate_configs = files_group_input(db_ref).crate_configs(db_ref).clone().unwrap();
418    match root {
419        Some(root) => crate_configs.insert(crt.clone(), db.crate_configuration_input(root).clone()),
420        None => crate_configs.swap_remove(crt),
421    };
422    crate_configs
423}
424
425/// Sets the root directory of the crate. None value removes the crate.
426#[macro_export]
427macro_rules! set_crate_config {
428    ($self:expr, $crt:expr, $root:expr) => {
429        let crate_configs = $crate::db::update_crate_configuration_input_helper($self, $crt, $root);
430        $crate::db::set_crate_configs_input($self, Some(crate_configs));
431    };
432}
433
434/// Updates file overrides input for standalone use.
435pub fn update_file_overrides_input_helper(
436    db: &dyn Database,
437    file: FileInput,
438    content: Option<Arc<str>>,
439) -> OrderedHashMap<FileInput, Arc<str>> {
440    let db_ref: &dyn Database = db;
441    let mut overrides = files_group_input(db_ref).file_overrides(db_ref).clone().unwrap();
442    match content {
443        Some(content) => overrides.insert(file, content),
444        None => overrides.swap_remove(&file),
445    };
446    overrides
447}
448
449/// Overrides file content. None value removes the override.
450#[macro_export]
451macro_rules! override_file_content {
452    ($self:expr, $file:expr, $content:expr) => {
453        let file = $self.file_input($file).clone();
454        let overrides = $crate::db::update_file_overrides_input_helper($self, file, $content);
455        salsa::Setter::to(
456            $crate::db::files_group_input($self).set_file_overrides($self),
457            Some(overrides),
458        );
459    };
460}
461
462fn cfg_set_helper(db: &dyn Database) -> &CfgSet {
463    files_group_input(db).cfg_set(db).as_ref().expect("cfg_set is not set")
464}
465
466#[salsa::tracked(returns(ref))]
467fn crates<'db>(db: &'db dyn Database) -> Vec<CrateId<'db>> {
468    // TODO(spapini): Sort for stability.
469    db.crate_configs().keys().copied().collect()
470}
471
472/// Tracked function to return the configuration of a crate.
473#[salsa::tracked(returns(ref))]
474fn crate_config_helper<'db>(
475    db: &'db dyn Database,
476    crt: CrateId<'db>,
477) -> Option<CrateConfiguration<'db>> {
478    match crt.long(db) {
479        CrateLongId::Real { .. } => db.crate_configs().get(&crt).cloned(),
480        CrateLongId::Virtual { name: _, file_id, settings, cache_file } => {
481            Some(CrateConfiguration {
482                root: Directory::Virtual {
483                    files: BTreeMap::from([("lib.cairo".to_string(), *file_id)]),
484                    dirs: Default::default(),
485                },
486                settings: toml::from_str(settings)
487                    .expect("Failed to parse virtual crate settings."),
488                cache_file: *cache_file,
489            })
490        }
491    }
492}
493
494/// Returns a reference to the configuration of a crate.
495/// This is a wrapper around the tracked function `crate_config_helper` to return a
496/// reference to a type unsupported by salsa tracked functions.
497fn crate_config<'db>(
498    db: &'db dyn Database,
499    crt: CrateId<'db>,
500) -> Option<&'db CrateConfiguration<'db>> {
501    crate_config_helper(db, crt).as_ref()
502}
503
504#[salsa::tracked]
505fn priv_raw_file_content<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<SmolStrId<'db>> {
506    match file.long(db) {
507        FileLongId::OnDisk(path) => {
508            // This does not result in performance cost due to OS caching and the fact that salsa
509            // will re-execute only this single query if the file content did not change.
510            db.report_untracked_read();
511
512            match fs::read_to_string(path) {
513                Ok(content) => Some(SmolStrId::new(db, SmolStr::new(content))),
514                Err(_) => None,
515            }
516        }
517        FileLongId::Virtual(virt) => Some(virt.content),
518        FileLongId::External(external_id) => Some(ext_as_virtual(db, *external_id).content),
519    }
520}
521
522/// Tracked function to return the content of a file as a string.
523#[salsa::tracked(returns(ref))]
524fn file_summary_helper<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<FileSummary> {
525    let content = db.file_content(file)?;
526    let mut line_offsets = vec![TextOffset::START];
527    let mut offset = TextOffset::START;
528    for ch in content.chars() {
529        offset = offset.add_width(TextWidth::from_char(ch));
530        if ch == '\n' {
531            line_offsets.push(offset);
532        }
533    }
534    Some(FileSummary { line_offsets, last_offset: offset })
535}
536
537/// Query implementation of [FilesGroup::file_content].
538#[salsa::tracked(returns(ref))]
539fn file_content<'db>(db: &'db dyn Database, file_id: FileId<'db>) -> Option<Arc<str>> {
540    let overrides = db.file_overrides();
541    overrides.get(&file_id).map(|content| (**content).clone()).or_else(|| {
542        priv_raw_file_content(db, file_id).map(|content| content.long(db).clone().into())
543    })
544}
545
546/// Returns a reference to the content of a file as a string.
547/// This is a wrapper around the tracked function `file_summary_helper` to return a
548/// reference to a type unsupported by salsa tracked functions.
549fn file_summary<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<&'db FileSummary> {
550    file_summary_helper(db, file).as_ref()
551}
552
553/// Tracked function to return the blob's content.
554#[salsa::tracked(returns(ref))]
555fn blob_content_helper<'db>(db: &'db dyn Database, blob: BlobId<'db>) -> Option<Vec<u8>> {
556    blob.long(db).content()
557}
558
559/// Wrapper around the tracked function `blob_content_helper` to return a
560/// reference to a type unsupported by salsa tracked functions.
561fn blob_content<'db>(db: &'db dyn Database, blob: BlobId<'db>) -> Option<&'db [u8]> {
562    blob_content_helper(db, blob).as_ref().map(|content| content.as_slice())
563}
564
565/// Returns the location of the originating user code.
566pub fn get_originating_location<'db>(
567    db: &'db dyn Database,
568    mut location: SpanInFile<'db>,
569    mut parent_files: Option<&mut Vec<FileId<'db>>>,
570) -> SpanInFile<'db> {
571    if let Some(ref mut parent_files) = parent_files {
572        parent_files.push(location.file_id);
573    }
574    while let Some((parent, code_mappings)) = get_parent_and_mapping(db, location.file_id) {
575        location.file_id = parent.file_id;
576        if let Some(ref mut parent_files) = parent_files {
577            parent_files.push(location.file_id);
578        }
579        location.span = translate_location(code_mappings, location.span).unwrap_or(parent.span);
580    }
581    location
582}
583
584/// This function finds a span in original code that corresponds to the provided span in the
585/// generated code, using the provided code mappings.
586///
587/// Code mappings describe a mapping between the original code and the generated one.
588/// Each mapping has a resulting span in a generated file and an origin in the original file.
589///
590/// If any of the provided mappings fully contains the span, origin span of the mapping will be
591/// returned. Otherwise, the function will try to find a span that is a result of a concatenation of
592/// multiple consecutive mappings.
593pub fn translate_location(code_mapping: &[CodeMapping], span: TextSpan) -> Option<TextSpan> {
594    // If any of the mappings fully contains the span, return the origin span of the mapping.
595    if let Some(containing) = code_mapping.iter().find(|mapping| {
596        mapping.span.contains(span) && !matches!(mapping.origin, CodeOrigin::CallSite(_))
597    }) {
598        // Found a span that fully contains the current one - translates it.
599        return containing.translate(span);
600    }
601
602    // Find all mappings that have non-empty intersection with the provided span.
603    let intersecting_mappings = || {
604        code_mapping.iter().filter(|mapping| {
605            // Omit mappings to the left or to the right of current span.
606            mapping.span.end > span.start && mapping.span.start < span.end
607        })
608    };
609
610    // Call site can be treated as default origin.
611    let call_site = intersecting_mappings()
612        .find(|mapping| {
613            mapping.span.contains(span) && matches!(mapping.origin, CodeOrigin::CallSite(_))
614        })
615        .and_then(|containing| containing.translate(span));
616
617    let mut matched = intersecting_mappings()
618        .filter(|mapping| matches!(mapping.origin, CodeOrigin::Span(_)))
619        .collect::<Vec<_>>();
620
621    // If no mappings intersect with the span, translation is impossible.
622    if matched.is_empty() {
623        return call_site;
624    }
625
626    // Take the first mapping to the left.
627    matched.sort_by_key(|mapping| mapping.span);
628    let (first, matched) = matched.split_first().expect("non-empty vec always has first element");
629
630    // Find the last mapping which consecutively follows the first one.
631    // Note that all spans here intersect with the given one.
632    let mut last = first;
633    for mapping in matched {
634        if mapping.span.start > last.span.end {
635            break;
636        }
637
638        let mapping_origin =
639            mapping.origin.as_span().expect("mappings with start origin should be filtered out");
640        let last_origin =
641            last.origin.as_span().expect("mappings with start origin should be filtered out");
642        // Make sure, the origins are consecutive.
643        if mapping_origin.start > last_origin.end {
644            break;
645        }
646
647        last = mapping;
648    }
649
650    // We construct new span from the first and last mappings.
651    // If the new span does not contain the original span, there is no translation.
652    let constructed_span = TextSpan::new(first.span.start, last.span.end);
653    if !constructed_span.contains(span) {
654        return call_site;
655    }
656
657    // We use the boundaries of the first and last mappings to calculate new span origin.
658    let start = match first.origin {
659        CodeOrigin::Start(origin_start) => origin_start.add_width(span.start - first.span.start),
660        CodeOrigin::Span(span) => span.start,
661        CodeOrigin::CallSite(span) => span.start,
662    };
663
664    let end = match last.origin {
665        CodeOrigin::Start(_) => start.add_width(span.width()),
666        CodeOrigin::Span(span) => span.end,
667        CodeOrigin::CallSite(span) => span.start,
668    };
669
670    Some(TextSpan::new(start, end))
671}
672
673/// Returns the parent file and the code mappings of the file.
674pub fn get_parent_and_mapping<'db>(
675    db: &'db dyn Database,
676    file_id: FileId<'db>,
677) -> Option<(SpanInFile<'db>, &'db [CodeMapping])> {
678    let vf = match file_id.long(db) {
679        FileLongId::OnDisk(_) => return None,
680        FileLongId::Virtual(vf) => vf,
681        FileLongId::External(id) => ext_as_virtual(db, *id),
682    };
683    Some((vf.parent?, &vf.code_mappings))
684}
685
686/// Returns the virtual file matching the external id. Panics if the id is not found.
687pub fn ext_as_virtual<'db>(db: &'db dyn Database, id: salsa::Id) -> &'db VirtualFile<'db> {
688    files_group_input(db)
689        .ext_as_virtual_obj(db)
690        .as_ref()
691        .expect("`ext_as_virtual` was not set as input.")(db, id)
692}
693
694/// Non-pub queries over the files group.
695trait PrivFilesGroup: Database {
696    /// Creates an input crate configuration from a [`CrateConfiguration`].
697    fn crate_configuration_input<'db>(
698        &'db self,
699        config: CrateConfiguration<'db>,
700    ) -> &'db CrateConfigurationInput {
701        crate_configuration_input(self.as_dyn_database(), config)
702    }
703}
704
705impl<T: Database + ?Sized> PrivFilesGroup for T {}