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, FlagId, FlagLongId, SmolStrId,
18    SpanInFile, 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}
151impl Edition {
152    /// Returns the latest stable edition.
153    ///
154    /// This Cairo edition is recommended for use in new projects and, in case of existing projects,
155    /// to migrate to when possible.
156    pub const fn latest() -> Self {
157        Self::V2024_07
158    }
159
160    /// The name of the prelude submodule of `core::prelude` for this compatibility version.
161    pub fn prelude_submodule_name<'db>(&self, db: &'db dyn Database) -> SmolStrId<'db> {
162        SmolStrId::from(
163            db,
164            match self {
165                Self::V2023_01 => "v2023_01",
166                Self::V2023_10 | Self::V2023_11 => "v2023_10",
167                Self::V2024_07 => "v2024_07",
168            },
169        )
170    }
171
172    /// Whether to ignore visibility modifiers.
173    pub fn ignore_visibility(&self) -> bool {
174        match self {
175            Self::V2023_01 | Self::V2023_10 => true,
176            Self::V2023_11 | Self::V2024_07 => false,
177        }
178    }
179}
180
181/// The settings for a dependency.
182#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
183pub struct DependencySettings {
184    /// A unique string allowing identifying different copies of the same dependency
185    /// in the compilation unit.
186    ///
187    /// Usually such copies differ by their versions or sources (or both).
188    /// It **must** be [`None`] for the core crate, for other crates it should be directly
189    /// translated from their [`CrateIdentifier`].
190    pub discriminator: Option<String>,
191}
192
193/// Configuration per crate.
194#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
195pub struct ExperimentalFeaturesConfig {
196    pub negative_impls: bool,
197    /// Allows using associated item constraints.
198    pub associated_item_constraints: bool,
199    /// Allows using coupon types and coupon calls.
200    ///
201    /// Each function has an associated `Coupon` type, which represents paying the cost of the
202    /// function before calling it.
203    #[serde(default)]
204    pub coupons: bool,
205    /// Allows using user defined inline macros.
206    #[serde(default)]
207    pub user_defined_inline_macros: bool,
208    /// Allows using representation pointer types (&T), which desugar to BoxTrait<@T>.
209    #[serde(default)]
210    pub repr_ptrs: bool,
211}
212
213/// Function to get a virtual file from an external id.
214pub type ExtAsVirtual =
215    Arc<dyn for<'a> Fn(&'a dyn Database, salsa::Id) -> &'a VirtualFile<'a> + Send + Sync>;
216
217#[salsa::input]
218// TODO(eytan-starkware): Change this mechanism to hold input handles on the db struct outside
219// salsa mechanism, and invalidate manually.
220pub struct FilesGroupInput {
221    /// Main input of the project. Lists all the crates configurations.
222    #[returns(ref)]
223    pub crate_configs: Option<OrderedHashMap<CrateInput, CrateConfigurationInput>>,
224    /// Overrides for file content. Mostly used by language server and tests.
225    #[returns(ref)]
226    pub file_overrides: Option<OrderedHashMap<FileInput, Arc<str>>>,
227    // TODO(yuval): consider moving this to a separate crate, or rename this crate.
228    /// The compilation flags.
229    #[returns(ref)]
230    pub flags: Option<OrderedHashMap<FlagLongId, Arc<Flag>>>,
231    /// The `#[cfg(...)]` options.
232    #[returns(ref)]
233    pub cfg_set: Option<CfgSet>,
234    #[returns(ref)]
235    pub ext_as_virtual_obj: Option<ExtAsVirtual>,
236}
237
238#[salsa::tracked]
239pub fn files_group_input(db: &dyn Database) -> FilesGroupInput {
240    FilesGroupInput::new(db, None, None, None, None, None)
241}
242
243/// Queries over the files group.
244pub trait FilesGroup: Database {
245    /// Interned version of `crate_configs_input`.
246    fn crate_configs<'db>(&'db self) -> &'db OrderedHashMap<CrateId<'db>, CrateConfiguration<'db>> {
247        crate_configs(self.as_dyn_database())
248    }
249
250    /// Interned version of `file_overrides_input`.
251    fn file_overrides<'db>(&'db self) -> &'db OrderedHashMap<FileId<'db>, ArcStr> {
252        file_overrides(self.as_dyn_database())
253    }
254
255    /// Interned version of `flags_input`.
256    fn flags<'db>(&'db self) -> &'db OrderedHashMap<FlagId<'db>, Arc<Flag>> {
257        flags(self.as_dyn_database())
258    }
259
260    /// List of crates in the project.
261    fn crates<'db>(&'db self) -> &'db [CrateId<'db>] {
262        crates(self.as_dyn_database())
263    }
264
265    /// Configuration of the crate.
266    fn crate_config<'db>(
267        &'db self,
268        crate_id: CrateId<'db>,
269    ) -> Option<&'db CrateConfiguration<'db>> {
270        crate_config(self.as_dyn_database(), crate_id)
271    }
272
273    /// Query for the file contents. This takes overrides into consideration.
274    fn file_content<'db>(&'db self, file_id: FileId<'db>) -> Option<&'db str> {
275        file_content(self.as_dyn_database(), file_id).as_ref().map(|content| content.as_ref())
276    }
277
278    fn file_summary<'db>(&'db self, file_id: FileId<'db>) -> Option<&'db FileSummary> {
279        file_summary(self.as_dyn_database(), file_id)
280    }
281
282    /// Query for the blob content.
283    fn blob_content<'db>(&'db self, blob_id: BlobId<'db>) -> Option<&'db [u8]> {
284        blob_content(self.as_dyn_database(), blob_id)
285    }
286    /// Query to get a compilation flag by its ID.
287    fn get_flag<'db>(&'db self, id: FlagId<'db>) -> Option<&'db Flag> {
288        get_flag(self.as_dyn_database(), id)
289    }
290
291    /// Create an input file from an interned file id.
292    fn file_input<'db>(&'db self, file_id: FileId<'db>) -> &'db FileInput {
293        file_input(self.as_dyn_database(), file_id)
294    }
295
296    /// Create an input crate from an interned crate id.
297    fn crate_input<'db>(&'db self, crt: CrateId<'db>) -> &'db CrateInput {
298        crate_input(self.as_dyn_database(), crt)
299    }
300
301    /// Sets the given flag value. None value removes the flag.
302    fn set_flag(&mut self, flag: FlagLongId, value: Option<Arc<Flag>>) {
303        let db_ref = self.as_dyn_database();
304        let mut flags = files_group_input(db_ref).flags(db_ref).clone().unwrap();
305        match value {
306            Some(value) => flags.insert(flag, value),
307            None => flags.swap_remove(&flag),
308        };
309        files_group_input(db_ref).set_flags(self).to(Some(flags));
310    }
311
312    /// Merges specified [`CfgSet`] into one already stored in this db.
313    fn use_cfg(&mut self, cfg_set: &CfgSet) {
314        let db_ref = self.as_dyn_database();
315        let existing = cfg_set_helper(db_ref);
316        let merged = existing.union(cfg_set);
317        files_group_input(db_ref).set_cfg_set(self).to(Some(merged));
318    }
319
320    /// Returns the cfg set.
321    fn cfg_set(&self) -> &CfgSet {
322        cfg_set_helper(self.as_dyn_database())
323    }
324}
325
326impl<T: Database + ?Sized> FilesGroup for T {}
327
328pub fn init_files_group<'db>(db: &mut (dyn Database + 'db)) {
329    // Initialize inputs.
330    let inp = files_group_input(db);
331    inp.set_file_overrides(db).to(Some(Default::default()));
332    inp.set_crate_configs(db).to(Some(Default::default()));
333    inp.set_flags(db).to(Some(Default::default()));
334    inp.set_cfg_set(db).to(Some(Default::default()));
335}
336
337pub fn set_crate_configs_input(
338    db: &mut dyn Database,
339    crate_configs: Option<OrderedHashMap<CrateInput, CrateConfigurationInput>>,
340) {
341    files_group_input(db).set_crate_configs(db).to(crate_configs);
342}
343
344#[salsa::tracked(returns(ref))]
345pub fn file_overrides<'db>(db: &'db dyn Database) -> OrderedHashMap<FileId<'db>, ArcStr> {
346    let inp = files_group_input(db).file_overrides(db).as_ref().expect("file_overrides is not set");
347    inp.iter()
348        .map(|(file_id, content)| {
349            (file_id.clone().into_file_long_id(db).intern(db), ArcStr::new(content.clone()))
350        })
351        .collect()
352}
353
354#[salsa::tracked(returns(ref))]
355pub fn crate_configs<'db>(
356    db: &'db dyn Database,
357) -> OrderedHashMap<CrateId<'db>, CrateConfiguration<'db>> {
358    let inp = files_group_input(db).crate_configs(db).as_ref().expect("crate_configs is not set");
359    inp.iter()
360        .map(|(crate_input, config)| {
361            (
362                crate_input.clone().into_crate_long_id(db).intern(db),
363                config.clone().into_crate_configuration(db),
364            )
365        })
366        .collect()
367}
368
369#[salsa::tracked(returns(ref))]
370pub fn flags<'db>(db: &'db dyn Database) -> OrderedHashMap<FlagId<'db>, Arc<Flag>> {
371    let inp = files_group_input(db).flags(db).as_ref().expect("flags is not set");
372    inp.iter().map(|(flag_id, flag)| (flag_id.clone().intern(db), flag.clone())).collect()
373}
374
375#[salsa::tracked(returns(ref))]
376fn file_input(db: &dyn Database, file_id: FileId<'_>) -> FileInput {
377    file_id.long(db).into_file_input(db)
378}
379
380#[salsa::tracked(returns(ref))]
381fn crate_input(db: &dyn Database, crt: CrateId<'_>) -> CrateInput {
382    crt.long(db).clone().into_crate_input(db)
383}
384
385#[salsa::tracked(returns(ref))]
386fn crate_configuration_input_helper(
387    db: &dyn Database,
388    _tracked: Tracked,
389    config: CrateConfiguration<'_>,
390) -> CrateConfigurationInput {
391    config.clone().into_crate_configuration_input(db)
392}
393
394fn crate_configuration_input<'db>(
395    db: &'db dyn Database,
396    config: CrateConfiguration<'db>,
397) -> &'db CrateConfigurationInput {
398    crate_configuration_input_helper(db, (), config)
399}
400
401pub fn init_dev_corelib(db: &mut dyn salsa::Database, core_lib_dir: PathBuf) {
402    let core = CrateLongId::core(db).intern(db);
403    let root = CrateConfiguration {
404        root: Directory::Real(core_lib_dir),
405        settings: CrateSettings {
406            name: None,
407            edition: Edition::V2024_07,
408            version: Version::parse(CORELIB_VERSION).ok(),
409            cfg_set: Default::default(),
410            dependencies: Default::default(),
411            experimental_features: ExperimentalFeaturesConfig {
412                negative_impls: true,
413                associated_item_constraints: true,
414                coupons: true,
415                user_defined_inline_macros: true,
416                repr_ptrs: true,
417            },
418        },
419        cache_file: None,
420    };
421    let crate_configs = update_crate_configuration_input_helper(db, core, Some(root));
422    set_crate_configs_input(db, Some(crate_configs));
423}
424
425/// Updates crate configuration input for standalone use.
426pub fn update_crate_configuration_input_helper(
427    db: &dyn Database,
428    crt: CrateId<'_>,
429    root: Option<CrateConfiguration<'_>>,
430) -> OrderedHashMap<CrateInput, CrateConfigurationInput> {
431    let crt = db.crate_input(crt);
432    let db_ref: &dyn Database = db;
433    let mut crate_configs = files_group_input(db_ref).crate_configs(db_ref).clone().unwrap();
434    match root {
435        Some(root) => crate_configs.insert(crt.clone(), db.crate_configuration_input(root).clone()),
436        None => crate_configs.swap_remove(crt),
437    };
438    crate_configs
439}
440
441/// Sets the root directory of the crate. None value removes the crate.
442#[macro_export]
443macro_rules! set_crate_config {
444    ($self:expr, $crt:expr, $root:expr) => {
445        let crate_configs = $crate::db::update_crate_configuration_input_helper($self, $crt, $root);
446        $crate::db::set_crate_configs_input($self, Some(crate_configs));
447    };
448}
449
450/// Updates file overrides input for standalone use.
451pub fn update_file_overrides_input_helper(
452    db: &dyn Database,
453    file: FileInput,
454    content: Option<Arc<str>>,
455) -> OrderedHashMap<FileInput, Arc<str>> {
456    let db_ref: &dyn Database = db;
457    let mut overrides = files_group_input(db_ref).file_overrides(db_ref).clone().unwrap();
458    match content {
459        Some(content) => overrides.insert(file.clone(), content),
460        None => overrides.swap_remove(&file),
461    };
462    overrides
463}
464
465/// Overrides file content. None value removes the override.
466#[macro_export]
467macro_rules! override_file_content {
468    ($self:expr, $file:expr, $content:expr) => {
469        let file = $self.file_input($file).clone();
470        let overrides = $crate::db::update_file_overrides_input_helper($self, file, $content);
471        salsa::Setter::to(
472            $crate::db::files_group_input($self).set_file_overrides($self),
473            Some(overrides),
474        );
475    };
476}
477
478fn cfg_set_helper(db: &dyn Database) -> &CfgSet {
479    files_group_input(db).cfg_set(db).as_ref().expect("cfg_set is not set")
480}
481
482#[salsa::tracked(returns(ref))]
483fn crates<'db>(db: &'db dyn Database) -> Vec<CrateId<'db>> {
484    // TODO(spapini): Sort for stability.
485    db.crate_configs().keys().copied().collect()
486}
487
488/// Tracked function to return the configuration of a crate.
489#[salsa::tracked(returns(ref))]
490fn crate_config_helper<'db>(
491    db: &'db dyn Database,
492    crt: CrateId<'db>,
493) -> Option<CrateConfiguration<'db>> {
494    match crt.long(db) {
495        CrateLongId::Real { .. } => db.crate_configs().get(&crt).cloned(),
496        CrateLongId::Virtual { name: _, file_id, settings, cache_file } => {
497            Some(CrateConfiguration {
498                root: Directory::Virtual {
499                    files: BTreeMap::from([("lib.cairo".to_string(), *file_id)]),
500                    dirs: Default::default(),
501                },
502                settings: toml::from_str(settings)
503                    .expect("Failed to parse virtual crate settings."),
504                cache_file: *cache_file,
505            })
506        }
507    }
508}
509
510/// Return a reference to the configuration of a crate.
511/// This is a wrapper around the tracked function `crate_config_helper` to return a
512/// reference to a type unsupported by salsa tracked functions.
513fn crate_config<'db>(
514    db: &'db dyn Database,
515    crt: CrateId<'db>,
516) -> Option<&'db CrateConfiguration<'db>> {
517    crate_config_helper(db, crt).as_ref()
518}
519
520#[salsa::tracked]
521fn priv_raw_file_content<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<SmolStrId<'db>> {
522    match file.long(db) {
523        FileLongId::OnDisk(path) => {
524            // This does not result in performance cost due to OS caching and the fact that salsa
525            // will re-execute only this single query if the file content did not change.
526            db.report_untracked_read();
527
528            match fs::read_to_string(path) {
529                Ok(content) => Some(SmolStrId::new(db, SmolStr::new(content))),
530                Err(_) => None,
531            }
532        }
533        FileLongId::Virtual(virt) => Some(virt.content),
534        FileLongId::External(external_id) => Some(ext_as_virtual(db, *external_id).content),
535    }
536}
537
538/// Tracked function to return the content of a file as a string.
539#[salsa::tracked(returns(ref))]
540fn file_summary_helper<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<FileSummary> {
541    let content = db.file_content(file)?;
542    let mut line_offsets = vec![TextOffset::START];
543    let mut offset = TextOffset::START;
544    for ch in content.chars() {
545        offset = offset.add_width(TextWidth::from_char(ch));
546        if ch == '\n' {
547            line_offsets.push(offset);
548        }
549    }
550    Some(FileSummary { line_offsets, last_offset: offset })
551}
552
553/// Query implementation of [FilesGroup::file_content].
554#[salsa::tracked(returns(ref))]
555fn file_content<'db>(db: &'db dyn Database, file_id: FileId<'db>) -> Option<Arc<str>> {
556    let overrides = db.file_overrides();
557    overrides.get(&file_id).map(|content| (**content).clone()).or_else(|| {
558        priv_raw_file_content(db, file_id).map(|content| content.long(db).clone().into())
559    })
560}
561
562/// Return a reference to the content of a file as a string.
563/// This is a wrapper around the tracked function `file_summary_helper` to return a
564/// reference to a type unsupported by salsa tracked functions.
565fn file_summary<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<&'db FileSummary> {
566    file_summary_helper(db, file).as_ref()
567}
568
569/// Returns a reference to the flag value.
570#[salsa::tracked(returns(ref))]
571fn get_flag_helper<'db>(db: &'db dyn Database, id: FlagId<'db>) -> Option<Arc<Flag>> {
572    db.flags().get(&id).cloned()
573}
574
575/// Returns a reference to the flag value.
576// TODO(eytan-starkware): Remove helper function and use flags here.
577fn get_flag<'db>(db: &'db dyn Database, id: FlagId<'db>) -> Option<&'db Flag> {
578    db.flags().get(&id).map(|flag| flag.as_ref())
579}
580
581/// Tracked function to return the blob's content.
582#[salsa::tracked(returns(ref))]
583fn blob_content_helper<'db>(db: &'db dyn Database, blob: BlobId<'db>) -> Option<Vec<u8>> {
584    blob.long(db).content()
585}
586
587/// Wrapper around the tracked function `blob_content_helper` to return a
588/// reference to a type unsupported by salsa tracked functions.
589fn blob_content<'db>(db: &'db dyn Database, blob: BlobId<'db>) -> Option<&'db [u8]> {
590    blob_content_helper(db, blob).as_ref().map(|content| content.as_slice())
591}
592
593/// Returns the location of the originating user code.
594pub fn get_originating_location<'db>(
595    db: &'db dyn Database,
596    mut location: SpanInFile<'db>,
597    mut parent_files: Option<&mut Vec<FileId<'db>>>,
598) -> SpanInFile<'db> {
599    if let Some(ref mut parent_files) = parent_files {
600        parent_files.push(location.file_id);
601    }
602    while let Some((parent, code_mappings)) = get_parent_and_mapping(db, location.file_id) {
603        location.file_id = parent.file_id;
604        if let Some(ref mut parent_files) = parent_files {
605            parent_files.push(location.file_id);
606        }
607        location.span = translate_location(code_mappings, location.span).unwrap_or(parent.span);
608    }
609    location
610}
611
612/// This function finds a span in original code that corresponds to the provided span in the
613/// generated code, using the provided code mappings.
614///
615/// Code mappings describe a mapping between the original code and the generated one.
616/// Each mapping has a resulting span in a generated file and an origin in the original file.
617///
618/// If any of the provided mappings fully contains the span, origin span of the mapping will be
619/// returned. Otherwise, the function will try to find a span that is a result of a concatenation of
620/// multiple consecutive mappings.
621pub fn translate_location(code_mapping: &[CodeMapping], span: TextSpan) -> Option<TextSpan> {
622    // If any of the mappings fully contains the span, return the origin span of the mapping.
623    if let Some(containing) = code_mapping.iter().find(|mapping| {
624        mapping.span.contains(span) && !matches!(mapping.origin, CodeOrigin::CallSite(_))
625    }) {
626        // Found a span that fully contains the current one - translates it.
627        return containing.translate(span);
628    }
629
630    // Find all mappings that have non-empty intersection with the provided span.
631    let intersecting_mappings = || {
632        code_mapping.iter().filter(|mapping| {
633            // Omit mappings to the left or to the right of current span.
634            mapping.span.end > span.start && mapping.span.start < span.end
635        })
636    };
637
638    // Call site can be treated as default origin.
639    let call_site = intersecting_mappings()
640        .find(|mapping| {
641            mapping.span.contains(span) && matches!(mapping.origin, CodeOrigin::CallSite(_))
642        })
643        .and_then(|containing| containing.translate(span));
644
645    let mut matched = intersecting_mappings()
646        .filter(|mapping| matches!(mapping.origin, CodeOrigin::Span(_)))
647        .collect::<Vec<_>>();
648
649    // If no mappings intersect with the span, translation is impossible.
650    if matched.is_empty() {
651        return call_site;
652    }
653
654    // Take the first mapping to the left.
655    matched.sort_by_key(|mapping| mapping.span);
656    let (first, matched) = matched.split_first().expect("non-empty vec always has first element");
657
658    // Find the last mapping which consecutively follows the first one.
659    // Note that all spans here intersect with the given one.
660    let mut last = first;
661    for mapping in matched {
662        if mapping.span.start > last.span.end {
663            break;
664        }
665
666        let mapping_origin =
667            mapping.origin.as_span().expect("mappings with start origin should be filtered out");
668        let last_origin =
669            last.origin.as_span().expect("mappings with start origin should be filtered out");
670        // Make sure, the origins are consecutive.
671        if mapping_origin.start > last_origin.end {
672            break;
673        }
674
675        last = mapping;
676    }
677
678    // We construct new span from the first and last mappings.
679    // If the new span does not contain the original span, there is no translation.
680    let constructed_span = TextSpan::new(first.span.start, last.span.end);
681    if !constructed_span.contains(span) {
682        return call_site;
683    }
684
685    // We use the boundaries of the first and last mappings to calculate new span origin.
686    let start = match first.origin {
687        CodeOrigin::Start(origin_start) => origin_start.add_width(span.start - first.span.start),
688        CodeOrigin::Span(span) => span.start,
689        CodeOrigin::CallSite(span) => span.start,
690    };
691
692    let end = match last.origin {
693        CodeOrigin::Start(_) => start.add_width(span.width()),
694        CodeOrigin::Span(span) => span.end,
695        CodeOrigin::CallSite(span) => span.start,
696    };
697
698    Some(TextSpan::new(start, end))
699}
700
701/// Returns the parent file and the code mappings of the file.
702pub fn get_parent_and_mapping<'db>(
703    db: &'db dyn Database,
704    file_id: FileId<'db>,
705) -> Option<(SpanInFile<'db>, &'db [CodeMapping])> {
706    let vf = match file_id.long(db) {
707        FileLongId::OnDisk(_) => return None,
708        FileLongId::Virtual(vf) => vf,
709        FileLongId::External(id) => ext_as_virtual(db, *id),
710    };
711    Some((vf.parent?, &vf.code_mappings))
712}
713
714/// Returns the virtual file matching the external id. Panics if the id is not found.
715pub fn ext_as_virtual<'db>(db: &'db dyn Database, id: salsa::Id) -> &'db VirtualFile<'db> {
716    files_group_input(db)
717        .ext_as_virtual_obj(db)
718        .as_ref()
719        .expect("`ext_as_virtual` was not set as input.")(db, id)
720}
721
722/// Non-pub queries over the files group.
723trait PrivFilesGroup: Database {
724    /// Create an input crate configuration from a [`CrateConfiguration`].
725    fn crate_configuration_input<'db>(
726        &'db self,
727        config: CrateConfiguration<'db>,
728    ) -> &'db CrateConfigurationInput {
729        crate_configuration_input(self.as_dyn_database(), config)
730    }
731}
732
733impl<T: Database + ?Sized> PrivFilesGroup for T {}