mago_database/file.rs
1use std::borrow::Cow;
2use std::hash::DefaultHasher;
3use std::hash::Hash;
4use std::hash::Hasher;
5use std::path::Path;
6use std::path::PathBuf;
7
8use serde::Deserialize;
9use serde::Serialize;
10
11use crate::error::DatabaseError;
12use crate::utils::read_file;
13
14/// A stable, unique identifier for a file.
15///
16/// This ID is generated by hashing the file's logical name, ensuring it remains
17/// consistent across application runs and is unaffected by content modifications.
18#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
19#[repr(transparent)]
20pub struct FileId(u64);
21
22/// Distinguishes between the origins of source files.
23#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
24#[repr(u8)]
25pub enum FileType {
26 /// The file is part of the primary project source code.
27 /// These files typically reside on the filesystem and are actively developed.
28 Host,
29
30 /// The file belongs to a third-party dependency (e.g., a Composer package).
31 /// These files exist on the filesystem within the project (e.g., in `vendor/`)
32 /// but are not considered part of the primary source code.
33 Vendored,
34
35 /// The file represents a built-in language construct (e.g., a core PHP function or class).
36 /// These "files" do not exist on the filesystem and their content is typically
37 /// provided as pre-defined stubs for analysis.
38 Builtin,
39}
40
41/// A file that's either stored on the host system's file system or in the vendored file system.
42///
43/// This struct encapsulates all the necessary information about a file, including its content,
44/// location, and metadata for change detection.
45#[derive(Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
46pub struct File {
47 /// A stable, unique identifier for the file, generated from its logical name.
48 /// This ID persists across application runs and content modifications.
49 pub id: FileId,
50
51 /// The logical name of the file, typically the path relative to the root of the project.
52 pub name: Cow<'static, str>,
53
54 /// The absolute path of the file on the host's filesystem, if it exists there.
55 /// This will be `None` for vendored files that don't have a physical counterpart.
56 pub path: Option<PathBuf>,
57
58 /// The type of the file, indicating its origin.
59 pub file_type: FileType,
60
61 /// The contents of the file, if available.
62 pub contents: Cow<'static, str>,
63
64 /// The size of the file's contents in bytes.
65 pub size: u32,
66
67 /// A vector containing the starting byte offsets of each line in `contents`.
68 /// The first line always starts at offset 0. This is useful for quickly
69 /// navigating to a specific line number without scanning the whole file.
70 pub lines: Vec<u32>,
71}
72
73pub trait HasFileId {
74 /// Returns the unique identifier of the file.
75 fn file_id(&self) -> FileId;
76}
77
78impl File {
79 /// Creates a new `File` instance from its name, type, path, and contents.
80 ///
81 /// It automatically calculates the size, and line start offsets.
82 pub fn new(
83 name: Cow<'static, str>,
84 file_type: FileType,
85 path: Option<PathBuf>,
86 contents: Cow<'static, str>,
87 ) -> Self {
88 let id = FileId::new(&name);
89 let size = contents.len() as u32;
90 let lines = line_starts(contents.as_ref()).collect::<Vec<_>>();
91
92 Self { id, name, path, file_type, contents, size, lines }
93 }
94
95 /// Creates a new `File` instance by reading its contents from the filesystem.
96 ///
97 /// This is the primary factory function for creating a `File` from a disk source.
98 /// It handles determining the file's logical name relative to the workspace,
99 /// reading its contents, and robustly handling non-UTF-8 text via lossy conversion.
100 ///
101 /// # Arguments
102 ///
103 /// * `workspace`: The root directory of the project, used to calculate the logical name.
104 /// * `path`: The absolute path to the file to read from disk.
105 /// * `file_type`: The [`FileType`] to assign to the created file.
106 ///
107 /// # Errors
108 ///
109 /// Returns a [`DatabaseError::IOError`] if the file cannot be read from the disk.
110 pub fn read(workspace: &Path, path: &Path, file_type: FileType) -> Result<Self, DatabaseError> {
111 read_file(workspace, path, file_type)
112 }
113
114 /// Creates an ephemeral, in-memory `File` from a name and content.
115 ///
116 /// This is a convenience method for situations like testing or formatting where
117 /// a full file context (e.g., a real path) is not required. It defaults to
118 /// `FileType::Host` and a `path` of `None`.
119 pub fn ephemeral(name: Cow<'static, str>, contents: Cow<'static, str>) -> Self {
120 Self::new(name, FileType::Host, None, contents)
121 }
122
123 /// Retrieve the line number for the given byte offset.
124 ///
125 /// # Parameters
126 ///
127 /// - `offset`: The byte offset to retrieve the line number for.
128 ///
129 /// # Returns
130 ///
131 /// The line number for the given byte offset (0-based index).
132 #[inline]
133 pub fn line_number(&self, offset: u32) -> u32 {
134 self.lines.binary_search(&offset).unwrap_or_else(|next_line| next_line - 1) as u32
135 }
136
137 /// Retrieve the byte offset for the start of the given line.
138 ///
139 /// # Parameters
140 ///
141 /// - `line`: The line number to retrieve the start offset for.
142 ///
143 /// # Returns
144 ///
145 /// The byte offset for the start of the given line (0-based index).
146 pub fn get_line_start_offset(&self, line: u32) -> Option<u32> {
147 self.lines.get(line as usize).copied()
148 }
149
150 /// Retrieve the byte offset for the end of the given line.
151 ///
152 /// # Parameters
153 ///
154 /// - `line`: The line number to retrieve the end offset for.
155 ///
156 /// # Returns
157 ///
158 /// The byte offset for the end of the given line (0-based index).
159 pub fn get_line_end_offset(&self, line: u32) -> Option<u32> {
160 match self.lines.get(line as usize + 1) {
161 Some(&end) => Some(end - 1),
162 None if line as usize == self.lines.len() - 1 => Some(self.size),
163 _ => None,
164 }
165 }
166
167 /// Retrieve the column number for the given byte offset.
168 ///
169 /// # Parameters
170 ///
171 /// - `offset`: The byte offset to retrieve the column number for.
172 ///
173 /// # Returns
174 ///
175 /// The column number for the given byte offset (0-based index).
176 #[inline]
177 pub fn column_number(&self, offset: u32) -> u32 {
178 let line_start =
179 self.lines.binary_search(&offset).unwrap_or_else(|next_line| self.lines[next_line - 1] as usize);
180
181 offset - line_start as u32
182 }
183}
184
185impl FileType {
186 /// Returns `true` if the file is a host file, meaning it is part of the project's source code.
187 pub const fn is_host(self) -> bool {
188 matches!(self, FileType::Host)
189 }
190
191 /// Returns `true` if the file is a vendored file, meaning it comes from an external library or dependency.
192 pub const fn is_vendored(self) -> bool {
193 matches!(self, FileType::Vendored)
194 }
195
196 /// Returns `true` if the file is a built-in file, meaning it represents a core language construct.
197 pub const fn is_builtin(self) -> bool {
198 matches!(self, FileType::Builtin)
199 }
200}
201
202impl FileId {
203 pub fn new(logical_name: &str) -> Self {
204 let mut hasher = DefaultHasher::new();
205 logical_name.hash(&mut hasher);
206 Self(hasher.finish())
207 }
208
209 pub const fn zero() -> Self {
210 Self(0)
211 }
212
213 pub const fn is_zero(self) -> bool {
214 self.0 == 0
215 }
216
217 #[must_use]
218 pub fn as_u64(self) -> u64 {
219 self.0
220 }
221}
222
223impl HasFileId for File {
224 fn file_id(&self) -> FileId {
225 self.id
226 }
227}
228
229impl std::fmt::Display for FileId {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231 write!(f, "{}", self.0)
232 }
233}
234
235/// Returns an iterator over the starting byte offsets of each line in `source`.
236#[inline]
237pub(crate) fn line_starts(source: &str) -> impl Iterator<Item = u32> + '_ {
238 let bytes = source.as_bytes();
239
240 std::iter::once(0)
241 .chain(memchr::memchr_iter(b'\n', bytes).map(|i| if i > 0 && bytes[i - 1] == b'\r' { i } else { i + 1 }))
242 .map(|i| i as u32)
243}