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#[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#[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 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#[derive(Clone, Debug, PartialEq, Eq, Hash, salsa::Update)]
70pub struct CrateConfiguration<'db> {
71 pub root: Directory<'db>,
73 pub settings: CrateSettings,
74 pub cache_file: Option<BlobId<'db>>,
75}
76impl<'db> CrateConfiguration<'db> {
77 pub fn default_for_root(root: Directory<'db>) -> Self {
79 Self { root, settings: CrateSettings::default(), cache_file: None }
80 }
81
82 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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
94pub struct CrateSettings {
95 pub name: Option<String>,
98 pub edition: Edition,
100 pub version: Option<Version>,
112 pub cfg_set: Option<CfgSet>,
114 #[serde(default)]
116 pub dependencies: BTreeMap<String, DependencySettings>,
117
118 #[serde(default)]
119 pub experimental_features: ExperimentalFeaturesConfig,
120}
121
122#[salsa::tracked(returns(ref))]
125pub fn default_crate_settings<'db>(_db: &'db dyn Database) -> CrateSettings {
126 CrateSettings::default()
127}
128
129#[derive(
137 Clone, Copy, Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize, salsa::Update,
138)]
139pub enum Edition {
140 #[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 pub const fn latest() -> Self {
157 Self::V2024_07
158 }
159
160 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 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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
183pub struct DependencySettings {
184 pub discriminator: Option<String>,
191}
192
193#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize)]
195pub struct ExperimentalFeaturesConfig {
196 pub negative_impls: bool,
197 pub associated_item_constraints: bool,
199 #[serde(default)]
204 pub coupons: bool,
205 #[serde(default)]
207 pub user_defined_inline_macros: bool,
208 #[serde(default)]
210 pub repr_ptrs: bool,
211}
212
213pub type ExtAsVirtual =
215 Arc<dyn for<'a> Fn(&'a dyn Database, salsa::Id) -> &'a VirtualFile<'a> + Send + Sync>;
216
217#[salsa::input]
218pub struct FilesGroupInput {
221 #[returns(ref)]
223 pub crate_configs: Option<OrderedHashMap<CrateInput, CrateConfigurationInput>>,
224 #[returns(ref)]
226 pub file_overrides: Option<OrderedHashMap<FileInput, Arc<str>>>,
227 #[returns(ref)]
230 pub flags: Option<OrderedHashMap<FlagLongId, Arc<Flag>>>,
231 #[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
243pub trait FilesGroup: Database {
245 fn crate_configs<'db>(&'db self) -> &'db OrderedHashMap<CrateId<'db>, CrateConfiguration<'db>> {
247 crate_configs(self.as_dyn_database())
248 }
249
250 fn file_overrides<'db>(&'db self) -> &'db OrderedHashMap<FileId<'db>, ArcStr> {
252 file_overrides(self.as_dyn_database())
253 }
254
255 fn flags<'db>(&'db self) -> &'db OrderedHashMap<FlagId<'db>, Arc<Flag>> {
257 flags(self.as_dyn_database())
258 }
259
260 fn crates<'db>(&'db self) -> &'db [CrateId<'db>] {
262 crates(self.as_dyn_database())
263 }
264
265 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 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 fn blob_content<'db>(&'db self, blob_id: BlobId<'db>) -> Option<&'db [u8]> {
284 blob_content(self.as_dyn_database(), blob_id)
285 }
286 fn get_flag<'db>(&'db self, id: FlagId<'db>) -> Option<&'db Flag> {
288 get_flag(self.as_dyn_database(), id)
289 }
290
291 fn file_input<'db>(&'db self, file_id: FileId<'db>) -> &'db FileInput {
293 file_input(self.as_dyn_database(), file_id)
294 }
295
296 fn crate_input<'db>(&'db self, crt: CrateId<'db>) -> &'db CrateInput {
298 crate_input(self.as_dyn_database(), crt)
299 }
300
301 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 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 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 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
425pub 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#[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
450pub 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#[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 db.crate_configs().keys().copied().collect()
486}
487
488#[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
510fn 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 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#[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#[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
562fn file_summary<'db>(db: &'db dyn Database, file: FileId<'db>) -> Option<&'db FileSummary> {
566 file_summary_helper(db, file).as_ref()
567}
568
569#[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
575fn 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#[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
587fn 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
593pub 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
612pub fn translate_location(code_mapping: &[CodeMapping], span: TextSpan) -> Option<TextSpan> {
622 if let Some(containing) = code_mapping.iter().find(|mapping| {
624 mapping.span.contains(span) && !matches!(mapping.origin, CodeOrigin::CallSite(_))
625 }) {
626 return containing.translate(span);
628 }
629
630 let intersecting_mappings = || {
632 code_mapping.iter().filter(|mapping| {
633 mapping.span.end > span.start && mapping.span.start < span.end
635 })
636 };
637
638 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 matched.is_empty() {
651 return call_site;
652 }
653
654 matched.sort_by_key(|mapping| mapping.span);
656 let (first, matched) = matched.split_first().expect("non-empty vec always has first element");
657
658 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 if mapping_origin.start > last_origin.end {
672 break;
673 }
674
675 last = mapping;
676 }
677
678 let constructed_span = TextSpan::new(first.span.start, last.span.end);
681 if !constructed_span.contains(span) {
682 return call_site;
683 }
684
685 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
701pub 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
714pub 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
722trait PrivFilesGroup: Database {
724 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 {}