Skip to main content

FileId

Struct FileId 

Source
pub struct FileId(pub u32);
Expand description

Dense source-file identifier inside a SourceDb.

Tuple Fields§

§0: u32

Implementations§

Source§

impl FileId

Source

pub const NONE: Self

Source

pub const fn is_some(self) -> bool

Examples found in repository?
examples/path_res_bench.rs (line 261)
191fn bench_repo(root: &Path) {
192    let mut rs_paths = Vec::new();
193    let mut manifests = Vec::new();
194    collect_repo(root, &mut rs_paths, &mut manifests);
195    if rs_paths.is_empty() {
196        return;
197    }
198    let mut sources = MemSourceDb::new();
199    for p in &rs_paths {
200        if let Ok(text) = std::fs::read_to_string(p) {
201            let rel = p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
202            sources.add_file(&rel, text);
203        }
204    }
205    let mut db = MemItemDb::new();
206    let (core_k, alloc_k, std_k) = seed_minimal_sysroot(&mut db);
207    let mut crates = Vec::new();
208    for mp in &manifests {
209        let Ok(t) = std::fs::read_to_string(mp) else {
210            continue;
211        };
212        if !t.contains("[package]") {
213            continue;
214        }
215        let (pkg, ed, explicit_lib, feats) = parse_manifest_meta(&t);
216        let cdir = mp.parent().unwrap_or(root);
217        let rel = cdir.strip_prefix(root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
218        let join_r = |s: &str| {
219            if rel.is_empty() {
220                s.to_string()
221            } else {
222                format!("{rel}/{s}")
223            }
224        };
225        let lib_fid = explicit_lib
226            .as_deref()
227            .and_then(|lp| sources.resolve_path(&join_r(lp)))
228            .or_else(|| sources.resolve_path(&join_r("src/lib.rs")))
229            .or_else(|| sources.resolve_path(&join_r("src/main.rs")));
230        let Some(rf) = lib_fid else { continue };
231        let cid = db.add_crate(&pkg, ed);
232        db.set_crate_root_def(cid, GlobalDefId::new(cid, 0));
233        for ext in [("core", core_k), ("alloc", alloc_k), ("std", std_k)] {
234            db.add_extern_crate(cid, ext.0, ext.1);
235        }
236        db.add_cfg_flag(cid, "unix");
237        for f in &feats {
238            db.add_cfg_kv(cid, "feature", f.as_str());
239        }
240        crates.push((cid, pkg, rf));
241    }
242    if crates.is_empty() {
243        return;
244    }
245    for i in 0..crates.len() {
246        for j in 0..crates.len() {
247            if i != j {
248                db.add_extern_crate(crates[i].0, crates[j].1.clone(), crates[j].0);
249            }
250        }
251    }
252
253    let parsed: Vec<SyntaxTree<'_>> = (0..sources.len()).map(|i| parse(sources.file_text(FileId(i as u32)))).collect();
254    let mut snapshots = Vec::with_capacity(crates.len());
255    let mut crate_files: Vec<Vec<FileId>> = Vec::with_capacity(crates.len());
256    let mut total_files = 0usize;
257    for &(cid, _, rf) in &crates {
258        let snap = CrateSnapshot::build_clean_cached(&db, &sources, cid, rf, |fid| parsed.get(fid.0 as usize));
259        let mut fids = Vec::new();
260        for m in &snap.mod_tree.modules {
261            if m.file.is_some() && !m.is_inline() && !m.is_unresolved() && !fids.contains(&m.file) {
262                fids.push(m.file);
263            }
264        }
265        total_files += fids.len();
266        crate_files.push(fids);
267        snapshots.push(snap);
268    }
269    if total_files == 0 {
270        return;
271    }
272
273    // Warm up `ExtScopeCache` and reusable `FileNameRes` buffer once so steady-state per-file cost is measured cleanly:
274    let mut out_buf = FileNameRes::new();
275    for (ci, snap) in snapshots.iter().enumerate() {
276        for &fid in &crate_files[ci] {
277            snap.resolve_file_paths_into(&db, fid, &parsed[fid.0 as usize], &mut out_buf);
278        }
279    }
280
281    let mut total_refs = 0usize;
282    let mut total_locals = 0usize;
283    let (_, allocs) = measure_allocs(|| {
284        for (ci, snap) in snapshots.iter().enumerate() {
285            for &fid in &crate_files[ci] {
286                snap.resolve_file_paths_into(&db, fid, &parsed[fid.0 as usize], &mut out_buf);
287                total_refs += out_buf.refs.len();
288                total_locals += out_buf.locals.len();
289                black_box(&out_buf);
290            }
291        }
292    });
293
294    let rounds = if total_files > 400 { 5usize } else { 11usize };
295    let mut best = Duration::MAX;
296    for _ in 0..rounds {
297        let t0 = Instant::now();
298        for (ci, snap) in snapshots.iter().enumerate() {
299            for &fid in &crate_files[ci] {
300                snap.resolve_file_paths_into(&db, fid, &parsed[fid.0 as usize], &mut out_buf);
301                black_box(out_buf.refs.len());
302            }
303        }
304        best = best.min(t0.elapsed());
305    }
306
307    let files_f = total_files as f64;
308    let label = root.file_name().and_then(|s| s.to_str()).unwrap_or("repo");
309    println!(
310        "{label:<16} crates={:>3} files={:>4} refs={:>7} locals={:>6} | {:>8.1} ns/file ({:>5.2} ms total) | allocs/file={:>4.1} bytes/file={:>7.1}",
311        snapshots.len(),
312        total_files,
313        total_refs,
314        total_locals,
315        best.as_nanos() as f64 / files_f,
316        best.as_secs_f64() * 1000.0,
317        allocs.allocs as f64 / files_f,
318        allocs.total_bytes as f64 / files_f,
319    );
320}
More examples
Hide additional examples
examples/dirty_overlay_bench.rs (line 255)
181fn bench_repo(root: &Path) {
182    let mut rs_paths = Vec::new();
183    let mut manifests = Vec::new();
184    collect_repo(root, &mut rs_paths, &mut manifests);
185    if rs_paths.is_empty() {
186        return;
187    }
188    let mut sources = MemSourceDb::new();
189    for p in &rs_paths {
190        if let Ok(text) = std::fs::read_to_string(p) {
191            let rel = p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
192            sources.add_file(&rel, text);
193        }
194    }
195    let mut db = MemItemDb::new();
196    let (core_k, alloc_k, std_k) = seed_minimal_sysroot(&mut db);
197    let mut crates = Vec::new();
198    for mp in &manifests {
199        let Ok(t) = std::fs::read_to_string(mp) else {
200            continue;
201        };
202        if !t.contains("[package]") {
203            continue;
204        }
205        let (pkg, ed, explicit_lib, feats) = parse_manifest_meta(&t);
206        let cdir = mp.parent().unwrap_or(root);
207        let rel = cdir.strip_prefix(root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
208        let join_r = |s: &str| {
209            if rel.is_empty() {
210                s.to_string()
211            } else {
212                format!("{rel}/{s}")
213            }
214        };
215        let lib_fid = explicit_lib
216            .as_deref()
217            .and_then(|lp| sources.resolve_path(&join_r(lp)))
218            .or_else(|| sources.resolve_path(&join_r("src/lib.rs")))
219            .or_else(|| sources.resolve_path(&join_r("src/main.rs")));
220        let Some(rf) = lib_fid else { continue };
221        let cid = db.add_crate(&pkg, ed);
222        db.set_crate_root_def(cid, GlobalDefId::new(cid, 0));
223        for ext in [("core", core_k), ("alloc", alloc_k), ("std", std_k)] {
224            db.add_extern_crate(cid, ext.0, ext.1);
225        }
226        db.add_cfg_flag(cid, "unix");
227        for f in &feats {
228            db.add_cfg_kv(cid, "feature", f.as_str());
229        }
230        crates.push((cid, pkg, rf));
231    }
232    if crates.is_empty() {
233        return;
234    }
235    for i in 0..crates.len() {
236        for j in 0..crates.len() {
237            if i != j {
238                db.add_extern_crate(crates[i].0, crates[j].1.clone(), crates[j].0);
239            }
240        }
241    }
242
243    let parsed: Vec<SyntaxTree<'_>> = (0..sources.len()).map(|i| parse(sources.file_text(FileId(i as u32)))).collect();
244    let mut setups = Vec::new();
245    let mut total_files = 0usize;
246
247    for &(cid, _, rf) in &crates {
248        let snap = CrateSnapshot::build_clean_cached(&db, &sources, cid, rf, |fid| parsed.get(fid.0 as usize));
249        total_files += snap.mod_tree.modules.iter().filter(|m| !m.is_inline() && !m.is_unresolved()).count();
250        // Pick the non-root leaf file with the largest byte length (or root_file for single-file crates):
251        let dirty_fid = snap
252            .mod_tree
253            .modules
254            .iter()
255            .filter(|m| m.file.is_some() && !m.is_inline() && !m.is_unresolved())
256            .max_by_key(|m| (m.id != ridx_syntax::name_res::ModuleId::ROOT, sources.file_text(m.file).len()))
257            .map_or(rf, |m| m.file);
258        let mut edited = String::from(sources.file_text(dirty_fid));
259        edited.push_str("\npub struct __RidxOverlayProbe;\nimpl __RidxOverlayProbe { pub fn ping(&self) -> usize { 1 } }\n");
260        let mut ov = OverlaySourceDb::new(&sources, sources.len() as u32);
261        ov.set_file_override(dirty_fid, edited);
262        setups.push((snap, ov, dirty_fid));
263    }
264
265    let edited_trees: Vec<SyntaxTree<'_>> = setups.iter().map(|(_, ov, df)| parse(ov.file_text(*df))).collect();
266
267    // Measure 1-dirty-file overlay update across all crates in this repo:
268    let mut dirty_impls = 0usize;
269    let mut dirty_assocs = 0usize;
270    let (_, allocs) = measure_allocs(|| {
271        for (idx, (snap, ov, df)) in setups.iter().enumerate() {
272            let dirty_st = &edited_trees[idx];
273            let res = snap.with_dirty_files(&db, ov, ov.dirty_files(), |fid| if fid == *df { Some(dirty_st) } else { parsed.get(fid.0 as usize) });
274            dirty_impls += res.1.local_impls.impls.len();
275            dirty_assocs += res.1.local_impls.assoc_items.len();
276            black_box(res);
277        }
278    });
279
280    let rounds = if total_files > 400 { 7usize } else { 15usize };
281    let mut best = Duration::MAX;
282    let mut fast_hits = 0usize;
283    for r in 0..rounds {
284        let t0 = Instant::now();
285        for (idx, (snap, ov, df)) in setups.iter().enumerate() {
286            let dirty_st = &edited_trees[idx];
287            let (rebuilt_mt, dm) = snap.with_dirty_files(&db, ov, ov.dirty_files(), |fid| if fid == *df { Some(dirty_st) } else { parsed.get(fid.0 as usize) });
288            if r == 0 && rebuilt_mt.is_none() {
289                fast_hits += 1;
290            }
291            black_box(dm);
292        }
293        best = best.min(t0.elapsed());
294    }
295
296    let edits = setups.len().max(1) as f64;
297    let files_f = total_files.max(1) as f64;
298    let label = root.file_name().and_then(|s| s.to_str()).unwrap_or("repo");
299    println!(
300        "{label:<16} crates={:>3} files={:>4} dirty_impls={:>4} dirty_assocs={:>4} fast={:>3}/{:<3} | {:>8.1} ns/edit ({:>6.1} ns/file, {:>5.2} ms) | allocs/edit={:>5.1} ({:>4.1} allocs/file) bytes/edit={:>8.1}",
301        setups.len(),
302        total_files,
303        dirty_impls,
304        dirty_assocs,
305        fast_hits,
306        setups.len(),
307        best.as_nanos() as f64 / edits,
308        best.as_nanos() as f64 / files_f,
309        best.as_secs_f64() * 1000.0,
310        allocs.allocs as f64 / edits,
311        allocs.allocs as f64 / files_f,
312        allocs.total_bytes as f64 / edits,
313    );
314}

Trait Implementations§

Source§

impl Clone for FileId

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for FileId

Source§

impl Debug for FileId

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for FileId

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for FileId

Source§

impl Hash for FileId

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for FileId

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for FileId

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for FileId

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl StructuralPartialEq for FileId

Auto Trait Implementations§

§

impl Forget for FileId

§

impl Freeze for FileId

§

impl Move for FileId

§

impl RefUnwindSafe for FileId

§

impl Send for FileId

§

impl Sync for FileId

§

impl Unpin for FileId

§

impl UnsafeUnpin for FileId

§

impl UnwindSafe for FileId

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.