cairo_lang_filesystem/
ids.rs

1use std::collections::BTreeMap;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use cairo_lang_utils::{Intern, LookupIntern, define_short_id};
6use path_clean::PathClean;
7use serde::{Deserialize, Serialize};
8use smol_str::SmolStr;
9
10use crate::db::{CORELIB_CRATE_NAME, FilesGroup};
11use crate::span::{TextOffset, TextSpan};
12
13pub const CAIRO_FILE_EXTENSION: &str = "cairo";
14
15/// A crate is a standalone file tree representing a single compilation unit.
16#[derive(Clone, Debug, Hash, PartialEq, Eq)]
17pub enum CrateLongId {
18    /// A crate that appears in crate_roots(), and on the filesystem.
19    Real { name: SmolStr, discriminator: Option<SmolStr> },
20    /// A virtual crate, not a part of the crate_roots(). Used mainly for tests.
21    Virtual { name: SmolStr, file_id: FileId, settings: String, cache_file: Option<BlobId> },
22}
23impl CrateLongId {
24    pub fn name(&self) -> SmolStr {
25        match self {
26            CrateLongId::Real { name, .. } | CrateLongId::Virtual { name, .. } => name.clone(),
27        }
28    }
29}
30define_short_id!(CrateId, CrateLongId, FilesGroup, lookup_intern_crate, intern_crate);
31impl CrateId {
32    /// Gets the crate id for a real crate by name, without a discriminator.
33    pub fn plain(
34        db: &(impl cairo_lang_utils::Upcast<dyn FilesGroup> + ?Sized),
35        name: &str,
36    ) -> Self {
37        CrateLongId::Real { name: name.into(), discriminator: None }.intern(db)
38    }
39
40    /// Gets the crate id for `core`.
41    pub fn core(db: &(impl cairo_lang_utils::Upcast<dyn FilesGroup> + ?Sized)) -> Self {
42        CrateLongId::Real { name: CORELIB_CRATE_NAME.into(), discriminator: None }.intern(db)
43    }
44
45    pub fn name(&self, db: &dyn FilesGroup) -> SmolStr {
46        self.lookup_intern(db).name()
47    }
48}
49
50/// A trait for getting the internal salsa::InternId of a short id object.
51///
52/// This id is unstable across runs and should not be used to anything that is externally visible.
53/// This is currently used to pick representative for strongly connected components.
54pub trait UnstableSalsaId {
55    fn get_internal_id(&self) -> &salsa::InternId;
56}
57impl UnstableSalsaId for CrateId {
58    fn get_internal_id(&self) -> &salsa::InternId {
59        &self.0
60    }
61}
62
63/// The long ID for a compilation flag.
64#[derive(Clone, Debug, Hash, PartialEq, Eq)]
65pub struct FlagLongId(pub SmolStr);
66define_short_id!(FlagId, FlagLongId, FilesGroup, lookup_intern_flag, intern_flag);
67impl FlagId {
68    pub fn new(db: &dyn FilesGroup, name: &str) -> Self {
69        FlagLongId(name.into()).intern(db)
70    }
71}
72
73/// We use a higher level FileId struct, because not all files are on disk. Some might be online.
74/// Some might be virtual/computed on demand.
75#[derive(Clone, Debug, Hash, PartialEq, Eq)]
76pub enum FileLongId {
77    OnDisk(PathBuf),
78    Virtual(VirtualFile),
79    External(salsa::InternId),
80}
81/// Whether the file holds syntax for a module or for an expression.
82#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
83pub enum FileKind {
84    Module,
85    Expr,
86}
87
88/// A mapping for a code rewrite.
89#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
90pub struct CodeMapping {
91    pub span: TextSpan,
92    pub origin: CodeOrigin,
93}
94impl CodeMapping {
95    pub fn translate(&self, span: TextSpan) -> Option<TextSpan> {
96        if self.span.contains(span) {
97            Some(match self.origin {
98                CodeOrigin::Start(origin_start) => {
99                    let start = origin_start.add_width(span.start - self.span.start);
100                    TextSpan { start, end: start.add_width(span.width()) }
101                }
102                CodeOrigin::Span(span) => span,
103                CodeOrigin::CallSite(span) => span,
104            })
105        } else {
106            None
107        }
108    }
109}
110
111/// The origin of a code mapping.
112#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
113pub enum CodeOrigin {
114    /// The origin is a copied node starting at the given offset.
115    Start(TextOffset),
116    /// The origin was generated from this span, but there's no direct mapping.
117    Span(TextSpan),
118    /// The origin was generated because of this span, but no code has been copied.
119    /// E.g. a macro defined attribute on a function.
120    CallSite(TextSpan),
121}
122
123impl CodeOrigin {
124    pub fn as_span(&self) -> Option<TextSpan> {
125        match self {
126            CodeOrigin::Start(_) => None,
127            CodeOrigin::CallSite(_) => None,
128            CodeOrigin::Span(span) => Some(*span),
129        }
130    }
131}
132
133#[derive(Clone, Debug, Hash, PartialEq, Eq)]
134pub struct VirtualFile {
135    pub parent: Option<FileId>,
136    pub name: SmolStr,
137    pub content: Arc<str>,
138    pub code_mappings: Arc<[CodeMapping]>,
139    pub kind: FileKind,
140}
141impl VirtualFile {
142    fn full_path(&self, db: &dyn FilesGroup) -> String {
143        if let Some(parent) = self.parent {
144            // TODO(yuval): consider a different path format for virtual files.
145            format!("{}[{}]", parent.full_path(db), self.name)
146        } else {
147            self.name.clone().into()
148        }
149    }
150}
151
152define_short_id!(FileId, FileLongId, FilesGroup, lookup_intern_file, intern_file);
153impl FileId {
154    pub fn new(db: &dyn FilesGroup, path: PathBuf) -> FileId {
155        FileLongId::OnDisk(path.clean()).intern(db)
156    }
157    pub fn file_name(self, db: &dyn FilesGroup) -> String {
158        match self.lookup_intern(db) {
159            FileLongId::OnDisk(path) => {
160                path.file_name().and_then(|x| x.to_str()).unwrap_or("<unknown>").to_string()
161            }
162            FileLongId::Virtual(vf) => vf.name.to_string(),
163            FileLongId::External(external_id) => db.ext_as_virtual(external_id).name.to_string(),
164        }
165    }
166    pub fn full_path(self, db: &dyn FilesGroup) -> String {
167        match self.lookup_intern(db) {
168            FileLongId::OnDisk(path) => path.to_str().unwrap_or("<unknown>").to_string(),
169            FileLongId::Virtual(vf) => vf.full_path(db),
170            FileLongId::External(external_id) => db.ext_as_virtual(external_id).full_path(db),
171        }
172    }
173    pub fn kind(self, db: &dyn FilesGroup) -> FileKind {
174        match self.lookup_intern(db) {
175            FileLongId::OnDisk(_) => FileKind::Module,
176            FileLongId::Virtual(vf) => vf.kind.clone(),
177            FileLongId::External(_) => FileKind::Module,
178        }
179    }
180}
181
182#[derive(Clone, Debug, Hash, PartialEq, Eq)]
183pub enum Directory {
184    /// A directory on the file system.
185    Real(PathBuf),
186    /// A virtual directory, not on the file system. Used mainly for virtual crates.
187    Virtual { files: BTreeMap<SmolStr, FileId>, dirs: BTreeMap<SmolStr, Box<Directory>> },
188}
189
190impl Directory {
191    /// Returns a file inside this directory. The file and directory don't necessarily exist on
192    /// the file system. These are ids/paths to them.
193    pub fn file(&self, db: &dyn FilesGroup, name: SmolStr) -> FileId {
194        match self {
195            Directory::Real(path) => FileId::new(db, path.join(&name)),
196            Directory::Virtual { files, dirs: _ } => files
197                .get(&name)
198                .copied()
199                .unwrap_or_else(|| FileId::new(db, PathBuf::from(name.as_str()))),
200        }
201    }
202
203    /// Returns a sub directory inside this directory. These directories don't necessarily exist on
204    /// the file system. These are ids/paths to them.
205    pub fn subdir(&self, name: SmolStr) -> Directory {
206        match self {
207            Directory::Real(path) => Directory::Real(path.join(&name)),
208            Directory::Virtual { files: _, dirs } => {
209                if let Some(dir) = dirs.get(&name) {
210                    dir.as_ref().clone()
211                } else {
212                    Directory::Virtual { files: BTreeMap::new(), dirs: BTreeMap::new() }
213                }
214            }
215        }
216    }
217}
218
219/// A FileId for data that is not necessarily a valid UTF-8 string.
220#[derive(Clone, Debug, Hash, PartialEq, Eq)]
221pub enum BlobLongId {
222    OnDisk(PathBuf),
223    Virtual(Arc<[u8]>),
224}
225
226define_short_id!(BlobId, BlobLongId, FilesGroup, lookup_intern_blob, intern_blob);
227
228impl BlobId {
229    pub fn new(db: &dyn FilesGroup, path: PathBuf) -> BlobId {
230        BlobLongId::OnDisk(path.clean()).intern(db)
231    }
232}