Skip to main content

FileNameRes

Struct FileNameRes 

Source
pub struct FileNameRes {
    pub file: FileId,
    pub refs: Vec<ResolvedRef>,
    pub locals: Vec<LocalBindData>,
    pub generics: Vec<GenericBindData>,
    pub prelude_traits: Arc<[GlobalDefId]>,
    pub mod_trait_scopes: Vec<(NodeId, NodeId, Arc<[GlobalDefId]>, bool)>,
    pub block_trait_imports: Vec<(NodeId, NodeId, GlobalDefId)>,
    pub self_trait_scopes: Vec<(NodeId, NodeId, GlobalDefId)>,
    pub param_trait_bounds: Vec<(GenericBindId, GlobalDefId)>,
    /* private fields */
}
Expand description

Reusable output table of all resolved paths, locals, and generic parameters in one .rs file.

Fields§

§file: FileId§refs: Vec<ResolvedRef>§locals: Vec<LocalBindData>§generics: Vec<GenericBindData>§prelude_traits: Arc<[GlobalDefId]>§mod_trait_scopes: Vec<(NodeId, NodeId, Arc<[GlobalDefId]>, bool)>§block_trait_imports: Vec<(NodeId, NodeId, GlobalDefId)>§self_trait_scopes: Vec<(NodeId, NodeId, GlobalDefId)>§param_trait_bounds: Vec<(GenericBindId, GlobalDefId)>

Implementations§

Source§

impl FileNameRes

Source

pub fn new() -> Self

Examples found in repository?
examples/path_res_bench.rs (line 274)
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}
Source

pub fn swap_scratch(&mut self, other: &mut Self)

Source

pub fn clear(&mut self)

Source

pub fn collect_traits_in_scope_at( &self, node: NodeId, out: &mut Vec<GlobalDefId>, )

Appends all traits visible for method resolution at node into out (0 heap allocations when warm).

Source

pub fn has_inner_trait_scopes(&self, start: NodeId, end: u32) -> bool

Returns true if any inner impl Trait, block use Trait, or inline mod begins or ends inside (start..end).

Source

pub fn ref_at_offset(&self, byte_offset: u32) -> Option<&ResolvedRef>

Binary-searches for a reference covering byte_offset (start <= byte_offset < end).

Source

pub fn refs_at_span(&self, start: u32, end: u32) -> &[ResolvedRef]

Returns all resolved references with exact byte span [start..end).

Source

pub fn path_tail_ref(&self, path_node: NodeId) -> Option<&ResolvedRef>

Returns the tail segment resolution of path_node (K::Path), if resolved.

Source

pub fn path_tail_ref_in_st( &self, st: &SyntaxTree<'_>, path_node: NodeId, ) -> Option<&ResolvedRef>

O(log N) tail-segment resolution lookup bounded by path_node’s CST byte range.

Source

pub fn refs_starting_in(&self, start: u32, end: u32) -> &[ResolvedRef]

O(log N) slice of references starting inside [start..=end].

Source

pub fn local_data(&self, id: LocalBindId) -> &LocalBindData

Source

pub fn generic_data(&self, id: GenericBindId) -> &GenericBindData

Source

pub fn local_uses( &self, local_id: LocalBindId, ) -> impl Iterator<Item = &ResolvedRef>

Iterates over every reference resolving to local_id in source order.

Trait Implementations§

Source§

impl Clone for FileNameRes

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 Debug for FileNameRes

Source§

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

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

impl Default for FileNameRes

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl Forget for FileNameRes

§

impl Freeze for FileNameRes

§

impl Move for FileNameRes

§

impl RefUnwindSafe for FileNameRes

§

impl Send for FileNameRes
where RawVecInner: Send, Arc<[GlobalDefId]>: Send, RawTable<(IdentKey, PerNs)>: Send, BoxRaw<str>: Send,

§

impl Sync for FileNameRes
where RawVecInner: Sync, Arc<[GlobalDefId]>: Sync, RawTable<(IdentKey, PerNs)>: Sync, BoxRaw<str>: Sync,

§

impl Unpin for FileNameRes
where *const u8 is !null: Unpin, Arc<[GlobalDefId]>: Unpin, Box<str>: Unpin,

§

impl UnsafeUnpin for FileNameRes

§

impl UnwindSafe for FileNameRes

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.