mago_database/file.rs
1use std::borrow::Cow;
2use std::cell::RefCell;
3use std::hash::DefaultHasher;
4use std::hash::Hash;
5use std::hash::Hasher;
6use std::path::Path;
7use std::path::PathBuf;
8
9use crate::error::DatabaseError;
10use crate::utils::read_file;
11
12/// A stable, unique identifier for a file.
13///
14/// This ID is generated by hashing the file's logical name, ensuring it remains
15/// consistent across application runs and is unaffected by content modifications.
16#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[repr(transparent)]
19pub struct FileId(u64);
20
21/// Distinguishes between the origins of source files.
22#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
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 /// The file is a user-provided patch that overrides type information and supported semantic
41 /// PHPDoc flags for vendored or built-in code.
42 /// Like vendored files, patches are not actively analyzed, linted, or formatted,
43 /// but their metadata takes precedence over both vendored and built-in definitions.
44 Patch,
45
46 /// An in-memory source contributed by an external analyzer plugin during initialization.
47 /// External files are scanned for symbols, but are never analyzed, linted, formatted, or fixed.
48 External,
49}
50
51/// A file that's either stored on the host system's file system or in the vendored file system.
52///
53/// This struct encapsulates all the necessary information about a file, including its content,
54/// location, and metadata for change detection.
55#[derive(Debug, Eq, PartialEq, Hash)]
56#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
57pub struct File {
58 /// A stable, unique identifier for the file, generated from its logical name.
59 /// This ID persists across application runs and content modifications.
60 pub id: FileId,
61
62 /// The logical name of the file, typically the path relative to the root of the project.
63 pub name: Cow<'static, [u8]>,
64
65 /// The absolute path of the file on the host's filesystem, if it exists there.
66 /// This will be `None` for vendored files that don't have a physical counterpart.
67 pub path: Option<PathBuf>,
68
69 /// The type of the file, indicating its origin.
70 pub file_type: FileType,
71
72 /// The contents of the file, if available.
73 pub contents: Cow<'static, [u8]>,
74
75 /// The size of the file's contents in bytes.
76 pub size: u32,
77
78 /// A vector containing the starting byte offsets of each line in `contents`.
79 /// The first line always starts at offset 0. This is useful for quickly
80 /// navigating to a specific line number without scanning the whole file.
81 pub lines: Vec<u32>,
82}
83
84pub trait HasFileId {
85 /// Returns the unique identifier of the file.
86 fn file_id(&self) -> FileId;
87}
88
89impl File {
90 /// Creates a new `File` instance from its name, type, path, and contents.
91 ///
92 /// It automatically calculates the size, and line start offsets.
93 #[inline]
94 #[must_use]
95 pub fn new(
96 name: Cow<'static, [u8]>,
97 file_type: FileType,
98 path: Option<PathBuf>,
99 contents: Cow<'static, [u8]>,
100 ) -> Self {
101 let id = FileId::new(&name);
102 let size = contents.len() as u32;
103 let lines = line_starts(contents.as_ref());
104
105 Self { id, name, path, file_type, contents, size, lines }
106 }
107
108 /// Creates a new `File` instance by reading its contents from the filesystem.
109 ///
110 /// This is the primary factory function for creating a `File` from a disk source.
111 /// It handles determining the file's logical name relative to the workspace,
112 /// reading its contents, and robustly handling non-UTF-8 text via lossy conversion.
113 ///
114 /// # Arguments
115 ///
116 /// * `workspace`: The root directory of the project, used to calculate the logical name.
117 /// * `path`: The absolute path to the file to read from disk.
118 /// * `file_type`: The [`FileType`] to assign to the created file.
119 ///
120 /// # Errors
121 ///
122 /// Returns a [`DatabaseError::IOError`] if the file cannot be read from the disk.
123 #[inline(always)]
124 pub fn read(workspace: &Path, path: &Path, file_type: FileType) -> Result<Self, DatabaseError> {
125 read_file(workspace, path, file_type)
126 }
127
128 /// Creates an ephemeral, in-memory `File` from a name and content.
129 ///
130 /// This is a convenience method for situations like testing or formatting where
131 /// a full file context (e.g., a real path) is not required. It defaults to
132 /// `FileType::Host` and a `path` of `None`.
133 #[inline]
134 #[must_use]
135 pub fn ephemeral(name: Cow<'static, [u8]>, contents: Cow<'static, [u8]>) -> Self {
136 Self::new(name, FileType::Host, None, contents)
137 }
138
139 /// Retrieve the line number for the given byte offset.
140 ///
141 /// # Parameters
142 ///
143 /// - `offset`: The byte offset to retrieve the line number for.
144 ///
145 /// # Returns
146 ///
147 /// The line number for the given byte offset (0-based index).
148 #[inline]
149 #[must_use]
150 pub fn line_number(&self, offset: u32) -> u32 {
151 self.lines.binary_search(&offset).unwrap_or_else(|next_line| next_line - 1) as u32
152 }
153
154 /// Retrieve the byte offset for the start of the given line.
155 ///
156 /// # Parameters
157 ///
158 /// - `line`: The line number to retrieve the start offset for.
159 ///
160 /// # Returns
161 ///
162 /// The byte offset for the start of the given line (0-based index).
163 #[inline]
164 #[must_use]
165 pub fn get_line_start_offset(&self, line: u32) -> Option<u32> {
166 self.lines.get(line as usize).copied()
167 }
168
169 /// Retrieve the byte offset for the end of the given line.
170 ///
171 /// # Parameters
172 ///
173 /// - `line`: The line number to retrieve the end offset for.
174 ///
175 /// # Returns
176 ///
177 /// The byte offset for the end of the given line (0-based index).
178 #[inline]
179 #[must_use]
180 pub fn get_line_end_offset(&self, line: u32) -> Option<u32> {
181 match self.lines.get(line as usize + 1) {
182 Some(&end) => Some(end - 1),
183 None if line as usize == self.lines.len() - 1 => Some(self.size),
184 _ => None,
185 }
186 }
187
188 /// Retrieve the column number for the given byte offset.
189 ///
190 /// # Parameters
191 ///
192 /// - `offset`: The byte offset to retrieve the column number for.
193 ///
194 /// # Returns
195 ///
196 /// The column number for the given byte offset (0-based index).
197 #[inline]
198 #[must_use]
199 pub fn column_number(&self, offset: u32) -> u32 {
200 let line = self.line_number(offset) as usize;
201
202 offset - self.lines[line]
203 }
204}
205
206impl FileType {
207 /// Returns `true` if the file is a host file, meaning it is part of the project's source code.
208 #[inline]
209 #[must_use]
210 pub const fn is_host(self) -> bool {
211 matches!(self, FileType::Host)
212 }
213
214 /// Returns `true` if the file is a vendored file, meaning it comes from an external library or dependency.
215 #[inline]
216 #[must_use]
217 pub const fn is_vendored(self) -> bool {
218 matches!(self, FileType::Vendored)
219 }
220
221 /// Returns `true` if the file is a built-in file, meaning it represents a core language construct.
222 #[inline]
223 #[must_use]
224 pub const fn is_builtin(self) -> bool {
225 matches!(self, FileType::Builtin)
226 }
227
228 /// Returns `true` if the file is a patch, meaning it overrides type information and supported semantic PHPDoc
229 /// flags for vendored or built-in code.
230 #[must_use]
231 pub const fn is_patch(self) -> bool {
232 matches!(self, FileType::Patch)
233 }
234
235 /// Returns `true` if the file is an in-memory source contributed by an external analyzer plugin.
236 #[must_use]
237 pub const fn is_external(self) -> bool {
238 matches!(self, FileType::External)
239 }
240}
241
242impl FileId {
243 #[inline]
244 #[must_use]
245 pub fn new(logical_name: &[u8]) -> Self {
246 let mut hasher = DefaultHasher::new();
247 logical_name.hash(&mut hasher);
248 Self(hasher.finish())
249 }
250
251 #[inline]
252 #[must_use]
253 pub const fn zero() -> Self {
254 Self(0)
255 }
256
257 #[inline]
258 #[must_use]
259 pub const fn is_zero(self) -> bool {
260 self.0 == 0
261 }
262
263 #[inline]
264 #[must_use]
265 pub fn as_u64(self) -> u64 {
266 self.0
267 }
268}
269
270impl HasFileId for File {
271 #[inline]
272 fn file_id(&self) -> FileId {
273 self.id
274 }
275}
276
277impl std::fmt::Display for FileId {
278 #[inline]
279 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280 write!(f, "{}", self.0)
281 }
282}
283
284/// Returns a vec over the starting byte offsets of each line in `source`.
285#[inline]
286pub(crate) fn line_starts(source: &[u8]) -> Vec<u32> {
287 thread_local! {
288 static SCRATCH: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
289 }
290
291 SCRATCH.with(|scratch| {
292 let mut lines = scratch.borrow_mut();
293 lines.clear();
294 lines.push(0);
295
296 // Detect line ending style from the first \r or \n. Real files use one
297 // convention throughout, so we never need to handle mixed \r\n / bare \r.
298 match memchr::memchr2(b'\r', b'\n', source) {
299 // No line endings: single-line file, nothing more to push.
300 None => {}
301 // Old Mac (\r only): first line-ending char is a bare \r.
302 Some(cr) if source[cr] == b'\r' && source.get(cr + 1) != Some(&b'\n') => {
303 for pos in memchr::memchr_iter(b'\r', source) {
304 lines.push((pos + 1) as u32);
305 }
306 }
307 // Unix (\n only) or Windows (\r\n): \n marks every line start.
308 _ => {
309 for pos in memchr::memchr_iter(b'\n', source) {
310 lines.push((pos + 1) as u32);
311 }
312 }
313 }
314
315 lines.as_slice().to_vec()
316 })
317}