Skip to main content

GlobalDefId

Struct GlobalDefId 

Source
pub struct GlobalDefId {
    pub krate: CrateId,
    pub index: u32,
}
Expand description

Compact 8-byte global definition key ((CrateId, def_index)), mapping 1-to-1 to (shard_idx, def_idx) in WorkspaceIndex or (CrateId::LOCAL_OVERLAY, local_idx) for dirty-file definitions.

Fields§

§krate: CrateId§index: u32

Implementations§

Source§

impl GlobalDefId

Source

pub const NONE: Self

Source

pub const fn new(krate: CrateId, index: u32) -> Self

Examples found in repository?
examples/dirty_overlay_bench.rs (line 91)
86fn seed_minimal_sysroot(db: &mut MemItemDb) -> (CrateId, CrateId, CrateId) {
87    let core_k = db.add_crate("core", Edition::Edition2021);
88    let alloc_k = db.add_crate("alloc", Edition::Edition2021);
89    let std_k = db.add_crate("std", Edition::Edition2021);
90    for (idx, k) in [core_k, alloc_k, std_k].into_iter().enumerate() {
91        let root = GlobalDefId::new(k, 0);
92        let prel = GlobalDefId::new(k, 1);
93        db.set_crate_root_def(k, root);
94        db.set_prelude_module(k, prel);
95        let opt = GlobalDefId::new(k, 10 + idx as u32);
96        db.add_module_def(prel, OwnedDef { id: opt, name: "Option".into(), kind: ItemKind::Enum, vis: VisKind::Public, has_value_ctor: false });
97        db.add_module_use(
98            root,
99            OwnedUse {
100                name: "option".into(),
101                type_def: opt,
102                value_def: GlobalDefId::NONE,
103                macro_def: GlobalDefId::NONE,
104                vis: VisKind::Public,
105                is_glob: false,
106                is_reexport: true,
107                is_prelude: false,
108                is_underscore: false,
109                prim_ty_code: 0,
110            },
111        );
112    }
113    (core_k, alloc_k, std_k)
114}
115
116fn collect_repo(dir: &Path, out_rs: &mut Vec<PathBuf>, out_manifests: &mut Vec<PathBuf>) {
117    if dir.parent().is_none() {
118        return;
119    }
120    let Ok(rd) = std::fs::read_dir(dir) else {
121        return;
122    };
123    let mut entries: Vec<_> = rd.filter_map(|e| e.ok()).collect();
124    entries.sort_by_key(|e| e.file_name());
125    for e in entries {
126        let Ok(ft) = e.file_type() else { continue };
127        if ft.is_symlink() {
128            continue;
129        }
130        let p = e.path();
131        let s = e.file_name().to_string_lossy().into_owned();
132        if ft.is_dir() {
133            if !matches!(s.as_str(), "target" | ".git" | "node_modules" | "fixtures" | "proc" | "sys" | "dev") {
134                collect_repo(&p, out_rs, out_manifests);
135            }
136        } else if ft.is_file() && s == "Cargo.toml" {
137            out_manifests.push(p);
138        } else if ft.is_file() && p.extension().and_then(|x| x.to_str()) == Some("rs") {
139            out_rs.push(p);
140        }
141    }
142}
143
144fn parse_manifest_meta(toml_text: &str) -> (String, Edition, Option<String>, Vec<String>) {
145    let mut section = "";
146    let mut name = String::from("crate");
147    let mut edition = Edition::Edition2021;
148    let mut lib_path = None;
149    let mut features = Vec::new();
150    for raw in toml_text.lines() {
151        let line = raw.split('#').next().unwrap_or("").trim();
152        if line.is_empty() {
153            continue;
154        }
155        if line.starts_with('[') && line.ends_with(']') {
156            section = &line[1..line.len() - 1];
157            continue;
158        }
159        let Some((k, v)) = line.split_once('=') else {
160            continue;
161        };
162        let (k, v) = (k.trim().trim_matches('"'), v.trim().trim_matches('"'));
163        match section {
164            "package" if k == "name" => name = v.replace('-', "_"),
165            "package" if k == "edition" => {
166                edition = match v {
167                    "2015" => Edition::Edition2015,
168                    "2018" => Edition::Edition2018,
169                    "2024" => Edition::Edition2024,
170                    _ => Edition::Edition2021,
171                };
172            }
173            "lib" if k == "path" => lib_path = Some(v.to_string()),
174            "features" => features.push(k.to_string()),
175            _ => {}
176        }
177    }
178    (name, edition, lib_path, features)
179}
180
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}
More examples
Hide additional examples
examples/path_res_bench.rs (line 95)
90fn seed_minimal_sysroot(db: &mut MemItemDb) -> (CrateId, CrateId, CrateId) {
91    let core_k = db.add_crate("core", Edition::Edition2021);
92    let alloc_k = db.add_crate("alloc", Edition::Edition2021);
93    let std_k = db.add_crate("std", Edition::Edition2021);
94    for (idx, k) in [core_k, alloc_k, std_k].into_iter().enumerate() {
95        let root = GlobalDefId::new(k, 0);
96        let prel = GlobalDefId::new(k, 1);
97        db.set_crate_root_def(k, root);
98        db.set_prelude_module(k, prel);
99        let opt = GlobalDefId::new(k, 10 + idx as u32 * 4);
100        let some_d = GlobalDefId::new(k, 11 + idx as u32 * 4);
101        let none_d = GlobalDefId::new(k, 12 + idx as u32 * 4);
102        db.add_module_def(prel, OwnedDef { id: opt, name: "Option".into(), kind: ItemKind::Enum, vis: VisKind::Public, has_value_ctor: false });
103        db.add_assoc_item(opt, OwnedDef { id: some_d, name: "Some".into(), kind: ItemKind::Variant, vis: VisKind::Public, has_value_ctor: true });
104        db.add_assoc_item(opt, OwnedDef { id: none_d, name: "None".into(), kind: ItemKind::Variant, vis: VisKind::Public, has_value_ctor: true });
105        for (nm, vd) in [("Some", some_d), ("None", none_d)] {
106            db.add_module_use(
107                prel,
108                OwnedUse {
109                    name: nm.into(),
110                    type_def: vd,
111                    value_def: vd,
112                    macro_def: GlobalDefId::NONE,
113                    vis: VisKind::Public,
114                    is_glob: false,
115                    is_reexport: true,
116                    is_prelude: false,
117                    is_underscore: false,
118                    prim_ty_code: 0,
119                },
120            );
121        }
122    }
123    (core_k, alloc_k, std_k)
124}
125
126fn collect_repo(dir: &Path, out_rs: &mut Vec<PathBuf>, out_manifests: &mut Vec<PathBuf>) {
127    if dir.parent().is_none() {
128        return;
129    }
130    let Ok(rd) = std::fs::read_dir(dir) else {
131        return;
132    };
133    let mut entries: Vec<_> = rd.filter_map(|e| e.ok()).collect();
134    entries.sort_by_key(|e| e.file_name());
135    for e in entries {
136        let Ok(ft) = e.file_type() else { continue };
137        if ft.is_symlink() {
138            continue;
139        }
140        let p = e.path();
141        let s = e.file_name().to_string_lossy().into_owned();
142        if ft.is_dir() {
143            if !matches!(s.as_str(), "target" | ".git" | "node_modules" | "fixtures" | "proc" | "sys" | "dev") {
144                collect_repo(&p, out_rs, out_manifests);
145            }
146        } else if ft.is_file() && s == "Cargo.toml" {
147            out_manifests.push(p);
148        } else if ft.is_file() && p.extension().and_then(|x| x.to_str()) == Some("rs") {
149            out_rs.push(p);
150        }
151    }
152}
153
154fn parse_manifest_meta(toml_text: &str) -> (String, Edition, Option<String>, Vec<String>) {
155    let mut section = "";
156    let mut name = String::from("crate");
157    let mut edition = Edition::Edition2021;
158    let mut lib_path = None;
159    let mut features = Vec::new();
160    for raw in toml_text.lines() {
161        let line = raw.split('#').next().unwrap_or("").trim();
162        if line.is_empty() {
163            continue;
164        }
165        if line.starts_with('[') && line.ends_with(']') {
166            section = &line[1..line.len() - 1];
167            continue;
168        }
169        let Some((k, v)) = line.split_once('=') else {
170            continue;
171        };
172        let (k, v) = (k.trim().trim_matches('"'), v.trim().trim_matches('"'));
173        match section {
174            "package" if k == "name" => name = v.replace('-', "_"),
175            "package" if k == "edition" => {
176                edition = match v {
177                    "2015" => Edition::Edition2015,
178                    "2018" => Edition::Edition2018,
179                    "2024" => Edition::Edition2024,
180                    _ => Edition::Edition2021,
181                };
182            }
183            "lib" if k == "path" => lib_path = Some(v.to_string()),
184            "features" => features.push(k.to_string()),
185            _ => {}
186        }
187    }
188    (name, edition, lib_path, features)
189}
190
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}
examples/ty_infer_bench.rs (line 53)
51fn simulate_fn_inference(tab: &mut InferenceTable, subst: &mut Vec<InferTyId>) -> InferTyId {
52    tab.clear();
53    let vec_def = GlobalDefId::new(CrateId(1), 10);
54    let res_def = GlobalDefId::new(CrateId(1), 11);
55    let p0 = tab.arena.mk_param(0, GlobalDefId::new(CrateId(1), 100));
56    let p1 = tab.arena.mk_param(1, GlobalDefId::new(CrateId(1), 101));
57    let sig_vec = tab.arena.mk_adt(vec_def, &[p0]);
58    let sig_res = tab.arena.mk_adt(res_def, &[sig_vec, p1]);
59
60    tab.fresh_subst(2, subst);
61    let call_ret = tab.instantiate(sig_res, subst);
62
63    let sl_u16 = tab.arena.mk_slice(InferTyId::U16);
64    let ref_sl_u16 = tab.arena.mk_ref(false, sl_u16);
65    let elem_exp = Expectation::HasType(ref_sl_u16).peel_for_borrow(tab, false).array_elem_expectation(tab);
66    let exp_elem_ty = elem_exp.coercion_target(tab).unwrap_or(InferTyId::UNKNOWN);
67    for _ in 0..4 {
68        let lit = tab.new_int_var();
69        let _ = tab.coerce(lit, exp_elem_ty);
70    }
71
72    let snap = tab.start_snapshot();
73    let wrong_target = tab.arena.mk_adt(res_def, &[InferTyId::BOOL, InferTyId::STR_REF]);
74    if tab.equate(call_ret, wrong_target).is_err() {
75        tab.rollback_to(snap);
76    } else {
77        tab.commit(snap);
78    }
79
80    let vec_u16 = tab.arena.mk_adt(vec_def, &[exp_elem_ty]);
81    let ok_target = tab.arena.mk_adt(res_def, &[vec_u16, InferTyId::STR_REF]);
82    let _ = tab.equate(call_ret, ok_target);
83
84    let mut branches = BranchCoercer::new(tab, Expectation::None);
85    let rm = tab.arena.mk_ref(true, call_ret);
86    let rs = tab.arena.mk_ref(false, call_ret);
87    branches.merge_arm(tab, InferTyId::NEVER);
88    branches.merge_arm(tab, rm);
89    branches.merge_arm(tab, rs);
90    let joined = branches.finish(tab);
91
92    let free_int = tab.new_int_var();
93    let free_flt = tab.new_float_var();
94    let out_tup = tab.arena.mk_tuple(&[joined, free_int, free_flt]);
95    tab.resolve_with_fallback(out_tup)
96}
97
98const BENCH_SRC: &str = r#"
99struct Packet<T> {
100    id: u32,
101    payload: T,
102}
103
104fn map_opt<T, U, F: FnOnce(T) -> U>(opt: Option<T>, f: F) -> Option<U> {
105    match opt {
106        Some(v) => Some(f(v)),
107        None => None,
108    }
109}
110
111fn process(pkt: &Packet<Option<u64>>, slice: &[u64], flag: bool) -> Option<u64> {
112    let base: &[u64] = &[1, 2, 3, 4];
113    let sub = &slice[0..2];
114    let picked = if flag { base[0] } else { sub[0] };
115    let mapped = map_opt(pkt.payload, |x| x + picked)?;
116    let acc = loop {
117        if mapped > 0 {
118            break mapped + 10;
119        }
120        return None;
121    };
122    Some(acc)
123}
124
125fn process_methods(items: &Vec<u64>, pkt: &Packet<Option<u64>>) -> Option<u64> {
126    let n = items.len() as u64;
127    let first = *items.first()?;
128    let mapped = items.clone().into_iter().map(|v| v + first + n);
129    let _ = mapped;
130    pkt.payload
131}
132
133fn process_traits<I: Iterator<Item = u64>>(it: I, items: Vec<u64>) -> Vec<u64> {
134    let head: Option<<I as Iterator>::Item> = Some(42);
135    let extra = Vec::from([1u64, 2u64]);
136    let _ = (head, extra, it);
137    items.into_iter().collect::<Vec<_>>()
138}
139
140fn process_partial(items: &Vec<u64>, pkt: &Packet<Option<u64>>) -> Option<u64> {
141    let unk = missing_symbol + ;
142    let tup = (items, pkt);
143    let _ = tup.0.;
144    let _ = items.;
145    let _ = unk;
146    pkt.payload
147}
148"#;
149
150fn main() {
151    let mut tab = InferenceTable::with_capacity(128, 64);
152    let mut subst = Vec::with_capacity(8);
153    for _ in 0..16 {
154        black_box(simulate_fn_inference(&mut tab, &mut subst));
155    }
156    let iters_kernel: u64 = 100_000;
157    ALLOCS.store(0, Ordering::Relaxed);
158    BYTES.store(0, Ordering::Relaxed);
159    let t0 = Instant::now();
160    for _ in 0..iters_kernel {
161        black_box(simulate_fn_inference(&mut tab, &mut subst));
162    }
163    let ns_kernel = t0.elapsed().as_nanos() as f64;
164    let allocs_kernel = ALLOCS.load(Ordering::Relaxed);
165    let bytes_kernel = BYTES.load(Ordering::Relaxed);
166    println!(
167        "ty_infer_bench (3.1 kernel): iters={} total_ms={:.2} ns/fn={:.1} warm_allocs={} warm_bytes={}",
168        iters_kernel,
169        ns_kernel / 1_000_000.0,
170        ns_kernel / (iters_kernel as f64),
171        allocs_kernel,
172        bytes_kernel
173    );
174    assert_eq!(allocs_kernel, 0, "expected 0 heap allocations in 3.1 kernel");
175
176    // Full 3.2 CST body inference benchmark (`process`).
177    let mut item_db = MemItemDb::new();
178    let std_c = item_db.add_crate("std", Edition::Edition2021);
179    let app_c = item_db.add_crate("app", Edition::Edition2021);
180    let prelude = GlobalDefId::new(std_c, 1);
181    item_db.set_crate_root_def(std_c, GlobalDefId::new(std_c, 0));
182    item_db.set_prelude_module(app_c, prelude);
183    item_db.add_extern_crate(app_c, "std", std_c);
184    item_db.set_crate_root_def(app_c, GlobalDefId::new(app_c, 0));
185
186    let opt_def = GlobalDefId::new(std_c, 10);
187    let some_def = GlobalDefId::new(std_c, 11);
188    let none_def = GlobalDefId::new(std_c, 12);
189    let fn_once_def = GlobalDefId::new(std_c, 13);
190    let range_def = GlobalDefId::new(std_c, 14);
191    let vec_def = GlobalDefId::new(std_c, 15);
192    let clone_tr = GlobalDefId::new(std_c, 16);
193    let into_iter_tr = GlobalDefId::new(std_c, 17);
194    let iter_tr = GlobalDefId::new(std_c, 18);
195    let iter_item_assoc = GlobalDefId::new(std_c, 19);
196    let into_iter_adt = GlobalDefId::new(std_c, 20);
197    let map_adt = GlobalDefId::new(std_c, 21);
198    let fn_mut_def = GlobalDefId::new(std_c, 22);
199    let from_tr = GlobalDefId::new(std_c, 23);
200    let from_iter_tr = GlobalDefId::new(std_c, 24);
201    for (id, n, k, c) in [
202        (opt_def, "Option", ItemKind::Enum, false),
203        (some_def, "Some", ItemKind::Variant, true),
204        (none_def, "None", ItemKind::Variant, true),
205        (fn_once_def, "FnOnce", ItemKind::Trait, false),
206        (fn_mut_def, "FnMut", ItemKind::Trait, false),
207        (vec_def, "Vec", ItemKind::Struct, false),
208        (clone_tr, "Clone", ItemKind::Trait, false),
209        (into_iter_tr, "IntoIterator", ItemKind::Trait, false),
210        (iter_tr, "Iterator", ItemKind::Trait, false),
211        (from_tr, "From", ItemKind::Trait, false),
212        (from_iter_tr, "FromIterator", ItemKind::Trait, false),
213    ] {
214        item_db.add_module_def(prelude, OwnedDef { id, name: n.into(), kind: k, vis: VisKind::Public, has_value_ctor: c });
215    }
216    item_db.add_assoc_item(iter_tr, OwnedDef { id: iter_item_assoc, name: "Item".into(), kind: ItemKind::AssocTy, vis: VisKind::Public, has_value_ctor: false });
217    let mut ty_db = MemTyDefDb::new();
218    ty_db.add_lang_item(TyLangItem::Option, opt_def);
219    ty_db.add_lang_item(TyLangItem::OptionSome, some_def);
220    ty_db.add_lang_item(TyLangItem::OptionNone, none_def);
221    ty_db.add_lang_item(TyLangItem::FnOnce, fn_once_def);
222    ty_db.add_lang_item(TyLangItem::FnMut, fn_mut_def);
223    ty_db.add_lang_item(TyLangItem::Range, range_def);
224    ty_db.add_lang_item(TyLangItem::Iterator, iter_tr);
225    ty_db.add_lang_item(TyLangItem::IteratorItem, iter_item_assoc);
226    let (p0, p1, p2) = (ty_db.param(0), ty_db.param(1), ty_db.param(2));
227    ty_db.add_adt(opt_def, 1, CtorShapeKind::None);
228    ty_db.add_variant(some_def, opt_def, 1, CtorShapeKind::Tuple);
229    ty_db.set_tuple_fields(some_def, &[p0]);
230    ty_db.add_variant(none_def, opt_def, 1, CtorShapeKind::Unit);
231    ty_db.add_adt(range_def, 1, CtorShapeKind::Record);
232    let vec_p0 = ty_db.add_adt(vec_def, 1, CtorShapeKind::None);
233    let into_iter_p0 = ty_db.add_adt(into_iter_adt, 1, CtorShapeKind::None);
234    let _ = ty_db.add_adt(map_adt, 2, CtorShapeKind::None);
235    let sl_p0 = ty_db.templates.mk_slice(p0);
236    ty_db.add_assoc_rule(TyLangItem::DerefTarget, 1, vec_p0, &[], sl_p0);
237    let (ref_vec, ref_sl, ref_p0) = (ty_db.templates.mk_ref(false, vec_p0), ty_db.templates.mk_ref(false, sl_p0), ty_db.templates.mk_ref(false, p0));
238    let opt_ref_p0 = ty_db.templates.mk_adt(opt_def, &[ref_p0]);
239    let (vec_len_fn, sl_first_fn, vec_clone_fn, vec_ii_fn, iter_map_fn) =
240        (GlobalDefId::new(std_c, 50), GlobalDefId::new(std_c, 51), GlobalDefId::new(std_c, 52), GlobalDefId::new(std_c, 53), GlobalDefId::new(std_c, 54));
241    ty_db.add_fn(vec_len_fn, 1, &[ref_vec], InferTyId::USIZE);
242    ty_db.add_inherent_method(ImplTargetKey::Adt(vec_def), "len", vec_len_fn, 1, 0);
243    ty_db.add_fn(sl_first_fn, 1, &[ref_sl], opt_ref_p0);
244    ty_db.add_inherent_method(ImplTargetKey::Slice, "first", sl_first_fn, 1, 0);
245    ty_db.add_fn(vec_clone_fn, 1, &[ref_vec], vec_p0);
246    ty_db.add_trait_method(clone_tr, 0, "clone", vec_clone_fn, 0);
247    ty_db.add_trait_impl(clone_tr, 1, vec_p0, &[], &[("clone", vec_clone_fn, 0)]);
248    ty_db.add_fn(vec_ii_fn, 1, &[vec_p0], into_iter_p0);
249    ty_db.add_trait_method(into_iter_tr, 0, "into_iter", vec_ii_fn, 0);
250    ty_db.add_trait_impl(into_iter_tr, 1, vec_p0, &[], &[("into_iter", vec_ii_fn, 0)]);
251    let self_item = ty_db.templates.mk_alias(iter_tr, iter_item_assoc, p0, &[]);
252    let map_ret = ty_db.templates.mk_adt(map_adt, &[p0, p2]);
253    ty_db.add_fn(iter_map_fn, 3, &[p0, p2], map_ret);
254    ty_db.add_param_fn_bound(iter_map_fn, 2, TyLangItem::FnMut, &[self_item], p1);
255    ty_db.add_trait_method(iter_tr, 0, "map", iter_map_fn, 2);
256    ty_db.add_trait_assoc_rule(iter_tr, iter_item_assoc, 1, into_iter_p0, &[], p0);
257    ty_db.add_assoc_rule(TyLangItem::IteratorItem, 1, into_iter_p0, &[], p0);
258    ty_db.add_trait_impl(iter_tr, 1, into_iter_p0, &[], &[]);
259    let (from_fn, vec_from_arr_fn, iter_collect_fn, vec_from_imp) =
260        (GlobalDefId::new(std_c, 55), GlobalDefId::new(std_c, 56), GlobalDefId::new(std_c, 57), GlobalDefId::new(std_c, 58));
261    ty_db.add_fn(from_fn, 2, &[p1], p0);
262    ty_db.add_trait_method(from_tr, 1, "from", from_fn, 0);
263    item_db.add_assoc_item(from_tr, OwnedDef { id: from_fn, name: "from".into(), kind: ItemKind::AssocFn, vis: VisKind::Public, has_value_ctor: false });
264    let arr2_p0 = ty_db.templates.mk_array(p0, 2);
265    ty_db.add_fn(vec_from_arr_fn, 1, &[arr2_p0], vec_p0);
266    ty_db.add_trait_impl(from_tr, 1, vec_p0, &[arr2_p0], &[("from", vec_from_arr_fn, 0)]);
267    item_db.add_impl(IndexedImpl { id: vec_from_imp, file: FileId::NONE, target: ImplTargetKey::Adt(vec_def), trait_def: from_tr, is_negative: false });
268    item_db.add_assoc_item(vec_from_imp, OwnedDef { id: vec_from_arr_fn, name: "from".into(), kind: ItemKind::AssocFn, vis: VisKind::Public, has_value_ctor: false });
269    ty_db.add_fn(iter_collect_fn, 2, &[p0], p1);
270    ty_db.add_where_trait_bound(iter_collect_fn, p1, from_iter_tr, &[self_item]);
271    ty_db.add_trait_method(iter_tr, 0, "collect", iter_collect_fn, 1);
272    ty_db.add_trait_impl(from_iter_tr, 1, vec_p0, &[p0], &[]);
273
274    let mut sources = MemSourceDb::new();
275    let file = sources.add_file("src/lib.rs", BENCH_SRC);
276    let mod_tree = ModuleTree::build(&item_db, &sources, app_c, file);
277    let def_map = CrateDefMap::build(&item_db, &sources, &mod_tree);
278    let st = parse(BENCH_SRC);
279    let file_res = def_map.resolve_file_paths(&item_db, &sources, &mod_tree, file);
280    let local_defs = LocalCstDefs::from_file(&st, Some(&def_map), file);
281    let fn_node = st.descendants(st.root()).find(|&n| st.kind(n) == K::Fn && st.child(n, K::Name).is_some_and(|nn| st.text(nn) == "process")).expect("process fn");
282
283    let mut ctx = BodyInferCtx::new();
284    let mut res = FnInferResult::new();
285    for _ in 0..16 {
286        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, fn_node, &mut res);
287        black_box(res.body_ty);
288    }
289
290    let iters_body: u64 = 50_000;
291    ALLOCS.store(0, Ordering::Relaxed);
292    BYTES.store(0, Ordering::Relaxed);
293    let t1 = Instant::now();
294    for _ in 0..iters_body {
295        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, fn_node, &mut res);
296        black_box(res.body_ty);
297    }
298    let ns_body = t1.elapsed().as_nanos() as f64;
299    let allocs_body = ALLOCS.load(Ordering::Relaxed);
300    let bytes_body = BYTES.load(Ordering::Relaxed);
301    println!(
302        "ty_infer_bench (3.2 CST body): iters={} total_ms={:.2} ns/fn={:.1} warm_allocs={} warm_bytes={}",
303        iters_body,
304        ns_body / 1_000_000.0,
305        ns_body / (iters_body as f64),
306        allocs_body,
307        bytes_body
308    );
309    assert_eq!(allocs_body, 0, "expected 0 heap allocations in steady-state BodyInferCtx::infer_fn_into loop");
310
311    let m_node = st.descendants(st.root()).find(|&n| st.kind(n) == K::Fn && st.child(n, K::Name).is_some_and(|nn| st.text(nn) == "process_methods")).expect("process_methods fn");
312    for _ in 0..16 {
313        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, m_node, &mut res);
314        black_box(res.body_ty);
315    }
316    ALLOCS.store(0, Ordering::Relaxed);
317    BYTES.store(0, Ordering::Relaxed);
318    let t2 = Instant::now();
319    for _ in 0..iters_body {
320        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, m_node, &mut res);
321        black_box(res.body_ty);
322    }
323    let ns_m = t2.elapsed().as_nanos() as f64;
324    let allocs_m = ALLOCS.load(Ordering::Relaxed);
325    let bytes_m = BYTES.load(Ordering::Relaxed);
326    println!(
327        "ty_infer_bench (3.3 methods+autoderef): iters={} total_ms={:.2} ns/fn={:.1} warm_allocs={} warm_bytes={}",
328        iters_body,
329        ns_m / 1_000_000.0,
330        ns_m / (iters_body as f64),
331        allocs_m,
332        bytes_m
333    );
334    assert_eq!(allocs_m, 0, "expected 0 heap allocations in steady-state 3.3 method resolution loop");
335
336    let tr_node = st.descendants(st.root()).find(|&n| st.kind(n) == K::Fn && st.child(n, K::Name).is_some_and(|nn| st.text(nn) == "process_traits")).expect("process_traits fn");
337    for _ in 0..16 {
338        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, tr_node, &mut res);
339        black_box(res.body_ty);
340    }
341    ALLOCS.store(0, Ordering::Relaxed);
342    BYTES.store(0, Ordering::Relaxed);
343    let t3 = Instant::now();
344    for _ in 0..iters_body {
345        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, tr_node, &mut res);
346        black_box(res.body_ty);
347    }
348    let ns_tr = t3.elapsed().as_nanos() as f64;
349    let allocs_tr = ALLOCS.load(Ordering::Relaxed);
350    let bytes_tr = BYTES.load(Ordering::Relaxed);
351    println!(
352        "ty_infer_bench (3.4 trait-solve+proj): iters={} total_ms={:.2} ns/fn={:.1} warm_allocs={} warm_bytes={}",
353        iters_body,
354        ns_tr / 1_000_000.0,
355        ns_tr / (iters_body as f64),
356        allocs_tr,
357        bytes_tr
358    );
359    assert_eq!(allocs_tr, 0, "expected 0 heap allocations in steady-state 3.4 trait solving loop");
360
361    let p_node = st.descendants(st.root()).find(|&n| st.kind(n) == K::Fn && st.child(n, K::Name).is_some_and(|nn| st.text(nn) == "process_partial")).expect("process_partial fn");
362    for _ in 0..16 {
363        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, p_node, &mut res);
364        black_box(res.incomplete_dots.len());
365    }
366    ALLOCS.store(0, Ordering::Relaxed);
367    BYTES.store(0, Ordering::Relaxed);
368    let t4 = Instant::now();
369    for _ in 0..iters_body {
370        ctx.infer_fn_into(&st, &file_res, &ty_db, &local_defs, p_node, &mut res);
371        black_box(res.incomplete_dots.len());
372    }
373    let ns_p = t4.elapsed().as_nanos() as f64;
374    let allocs_p = ALLOCS.load(Ordering::Relaxed);
375    let bytes_p = BYTES.load(Ordering::Relaxed);
376    println!(
377        "ty_infer_bench (3.5 partial-dot+recovery): iters={} total_ms={:.2} ns/fn={:.1} warm_allocs={} warm_bytes={}",
378        iters_body,
379        ns_p / 1_000_000.0,
380        ns_p / (iters_body as f64),
381        allocs_p,
382        bytes_p
383    );
384    assert_eq!(allocs_p, 0, "expected 0 heap allocations in steady-state 3.5 partial-code recovery loop");
385    assert_eq!(res.incomplete_dots.len(), 2, "expected both `tup.0.` and `items.` incomplete dots to be recorded");
386}
examples/def_map_bench.rs (line 123)
104fn seed_minimal_sysroot(db: &mut MemItemDb) -> (CrateId, CrateId, CrateId) {
105    let core_k = db.add_crate("core", Edition::Edition2021);
106    let alloc_k = db.add_crate("alloc", Edition::Edition2021);
107    let std_k = db.add_crate("std", Edition::Edition2021);
108    for (k, items) in [
109        (
110            core_k,
111            &[
112                ("option", "Option", ItemKind::Enum),
113                ("result", "Result", ItemKind::Enum),
114                ("convert", "TryFrom", ItemKind::Trait),
115                ("iter", "Iterator", ItemKind::Trait),
116                ("fmt", "Display", ItemKind::Trait),
117                ("ops", "Deref", ItemKind::Trait),
118            ][..],
119        ),
120        (alloc_k, &[("vec", "Vec", ItemKind::Struct), ("string", "String", ItemKind::Struct), ("boxed", "Box", ItemKind::Struct)][..]),
121        (std_k, &[("collections", "HashMap", ItemKind::Struct), ("io", "Read", ItemKind::Trait), ("sync", "Arc", ItemKind::Struct)][..]),
122    ] {
123        let root = GlobalDefId::new(k, 0);
124        let pre = GlobalDefId::new(k, 1);
125        let pre21 = GlobalDefId::new(k, 2);
126        db.set_crate_root_def(k, root);
127        db.add_module_def(root, OwnedDef { id: pre, name: "prelude".into(), kind: ItemKind::Mod, vis: VisKind::Public, has_value_ctor: false });
128        db.add_module_def(pre, OwnedDef { id: pre21, name: "rust_2021".into(), kind: ItemKind::Mod, vis: VisKind::Public, has_value_ctor: false });
129        let mut next_idx = 3u32;
130        for &(mname, iname, ikind) in items {
131            let mid = GlobalDefId::new(k, next_idx);
132            let iid = GlobalDefId::new(k, next_idx + 1);
133            next_idx += 2;
134            db.add_module_def(root, OwnedDef { id: mid, name: mname.into(), kind: ItemKind::Mod, vis: VisKind::Public, has_value_ctor: false });
135            db.add_module_def(mid, OwnedDef { id: iid, name: iname.into(), kind: ikind, vis: VisKind::Public, has_value_ctor: false });
136            db.add_module_use(
137                pre21,
138                OwnedUse {
139                    name: iname.into(),
140                    type_def: iid,
141                    value_def: GlobalDefId::NONE,
142                    macro_def: GlobalDefId::NONE,
143                    vis: VisKind::Public,
144                    is_glob: false,
145                    is_reexport: true,
146                    is_prelude: false,
147                    is_underscore: false,
148                    prim_ty_code: 0,
149                },
150            );
151        }
152    }
153    (core_k, alloc_k, std_k)
154}
155
156fn collect_repo(dir: &Path, out_rs: &mut Vec<PathBuf>, out_manifests: &mut Vec<PathBuf>) {
157    if dir.parent().is_none() {
158        return;
159    }
160    let Ok(rd) = std::fs::read_dir(dir) else {
161        return;
162    };
163    let mut entries: Vec<_> = rd.flatten().collect();
164    entries.sort_by_key(|e| e.file_name());
165    for e in entries {
166        let Ok(ft) = e.file_type() else { continue };
167        if ft.is_symlink() {
168            continue;
169        }
170        let p = e.path();
171        let s = e.file_name().to_string_lossy().into_owned();
172        if ft.is_dir() {
173            if matches!(s.as_str(), "target" | ".git" | "node_modules" | "fixtures" | "proc" | "sys" | "dev") {
174                continue;
175            }
176            collect_repo(&p, out_rs, out_manifests);
177        } else if ft.is_file() && s == "Cargo.toml" {
178            out_manifests.push(p);
179        } else if ft.is_file() && p.extension().and_then(|x| x.to_str()) == Some("rs") {
180            out_rs.push(p);
181        }
182    }
183}
184
185fn parse_manifest_meta(toml_text: &str) -> (String, Edition, Option<String>, Vec<String>) {
186    let mut section = "";
187    let mut name = String::from("crate");
188    let mut edition = Edition::Edition2021;
189    let mut lib_path = None;
190    let mut features = Vec::new();
191    for raw in toml_text.lines() {
192        let line = raw.split('#').next().unwrap_or("").trim();
193        if line.is_empty() {
194            continue;
195        }
196        if line.starts_with('[') && line.ends_with(']') {
197            section = &line[1..line.len() - 1];
198            continue;
199        }
200        let Some((k, v)) = line.split_once('=') else {
201            continue;
202        };
203        let k = k.trim().trim_matches('"');
204        let v = v.trim().trim_matches('"');
205        match section {
206            "package" if k == "name" => name = v.replace('-', "_"),
207            "package" if k == "edition" => {
208                edition = match v {
209                    "2015" => Edition::Edition2015,
210                    "2018" => Edition::Edition2018,
211                    "2024" => Edition::Edition2024,
212                    _ => Edition::Edition2021,
213                };
214            }
215            "lib" if k == "path" => lib_path = Some(v.to_string()),
216            "features" => features.push(k.to_string()),
217            _ => {}
218        }
219    }
220    (name, edition, lib_path, features)
221}
222
223fn bench_dir(root: &Path) {
224    let mut rs_paths = Vec::new();
225    let mut manifests = Vec::new();
226    collect_repo(root, &mut rs_paths, &mut manifests);
227    if rs_paths.is_empty() {
228        return;
229    }
230    let mut sources = MemSourceDb::new();
231    for p in &rs_paths {
232        if let Ok(text) = std::fs::read_to_string(p) {
233            let rel = p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
234            sources.add_file(&rel, text);
235        }
236    }
237    let mut db = MemItemDb::new();
238    let (core_k, alloc_k, std_k) = seed_minimal_sysroot(&mut db);
239    let mut crates = Vec::new();
240    for mp in &manifests {
241        let Ok(t) = std::fs::read_to_string(mp) else {
242            continue;
243        };
244        if !t.contains("[package]") {
245            continue;
246        }
247        let (pkg, ed, explicit_lib, feats) = parse_manifest_meta(&t);
248        let cdir = mp.parent().unwrap_or(root);
249        let rel = cdir.strip_prefix(root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
250        let join_r = |s: &str| {
251            if rel.is_empty() {
252                s.to_string()
253            } else {
254                format!("{rel}/{s}")
255            }
256        };
257        let lib_fid = explicit_lib
258            .as_deref()
259            .and_then(|lp| sources.resolve_path(&join_r(lp)))
260            .or_else(|| sources.resolve_path(&join_r("src/lib.rs")))
261            .or_else(|| sources.resolve_path(&join_r("src/main.rs")));
262        let Some(rf) = lib_fid else { continue };
263        let cid = db.add_crate(&pkg, ed);
264        db.set_crate_root_def(cid, GlobalDefId::new(cid, 0));
265        for ext in [("core", core_k), ("alloc", alloc_k), ("std", std_k)] {
266            db.add_extern_crate(cid, ext.0, ext.1);
267        }
268        db.add_cfg_flag(cid, "unix");
269        for f in &feats {
270            db.add_cfg_kv(cid, "feature", f.as_str());
271        }
272        crates.push((cid, pkg, rf));
273    }
274    if crates.is_empty() {
275        return;
276    }
277    // Wire workspace sibling crates as extern crates so intra-workspace `use sibling::...` resolves!
278    for i in 0..crates.len() {
279        for j in 0..crates.len() {
280            if i != j {
281                db.add_extern_crate(crates[i].0, crates[j].1.clone(), crates[j].0);
282            }
283        }
284    }
285
286    let parsed: Vec<SyntaxTree<'_>> = (0..sources.len()).map(|i| parse(sources.file_text(FileId(i as u32)))).collect();
287    let mod_trees: Vec<ModuleTree> = crates.iter().map(|&(cid, _, rf)| ModuleTree::build_cached(&db, &sources, cid, rf, |fid| parsed.get(fid.0 as usize))).collect();
288    let reached_files: usize = mod_trees.iter().map(|t| t.modules.iter().filter(|m| !m.is_inline() && !m.is_unresolved()).count()).sum();
289
290    // Export root items of workspace crates into `db` so sibling re-run resolves cross-crate uses too:
291    for mt in &mod_trees {
292        let dm = CrateDefMap::build_cached(&db, &sources, mt, &[], |fid| parsed.get(fid.0 as usize));
293        let root_g = GlobalDefId::new(mt.krate, 0);
294        let mut seq = 1u32;
295        for (name, pns) in &dm.scope(ModuleId::ROOT).entries {
296            let tdef = pns
297                .types
298                .map(|_| {
299                    let g = GlobalDefId::new(mt.krate, seq);
300                    seq += 1;
301                    g
302                })
303                .unwrap_or(GlobalDefId::NONE);
304            let vdef = pns
305                .values
306                .map(|_| {
307                    let g = GlobalDefId::new(mt.krate, seq);
308                    seq += 1;
309                    g
310                })
311                .unwrap_or(GlobalDefId::NONE);
312            if let Some(tb) = pns.types {
313                db.set_def_kind(tdef, tb.kind);
314            }
315            db.add_module_use(
316                root_g,
317                OwnedUse {
318                    name: name.to_string(),
319                    type_def: tdef,
320                    value_def: vdef,
321                    macro_def: GlobalDefId::NONE,
322                    vis: VisKind::Public,
323                    is_glob: false,
324                    is_reexport: true,
325                    is_prelude: false,
326                    is_underscore: false,
327                    prim_ty_code: 0,
328                },
329            );
330        }
331    }
332
333    let ((total_items, total_uses, resolved_uses), allocs) = measure_allocs(|| {
334        let mut items = 0usize;
335        let mut uses = 0usize;
336        let mut res_ok = 0usize;
337        for mt in &mod_trees {
338            let dm = CrateDefMap::build_cached(&db, &sources, mt, &[], |fid| parsed.get(fid.0 as usize));
339            items += dm.items.len();
340            uses += dm.uses.uses.len();
341            res_ok += dm.resolved_uses.iter().filter(|p| !p.is_empty()).count();
342            black_box(&dm);
343        }
344        (items, uses, res_ok)
345    });
346
347    let mut best = Duration::MAX;
348    let iters = if reached_files > 800 { 4 } else { 8 };
349    let mut final_res_ok = resolved_uses;
350    for _ in 0..iters {
351        let t0 = Instant::now();
352        let mut rok = 0usize;
353        for mt in &mod_trees {
354            let dm = CrateDefMap::build_cached(&db, &sources, mt, &[], |fid| parsed.get(fid.0 as usize));
355            rok += dm.resolved_uses.iter().filter(|p| !p.is_empty()).count();
356            black_box(dm);
357        }
358        final_res_ok = rok;
359        best = best.min(t0.elapsed());
360    }
361
362    let denom = reached_files.max(1) as f64;
363    let label = root.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "repo".into());
364    let (ns_f, ms_t, all_f, b_f) =
365        (best.as_nanos() as f64 / denom, best.as_secs_f64() * 1000.0, (allocs.allocs + allocs.reallocs) as f64 / denom, allocs.total_bytes as f64 / denom);
366    println!("{label:<18} files={reached_files:>5} items={total_items:>6} uses={total_uses:>6} (ws+std_ok={final_res_ok:>5}) | def_map={ns_f:>8.1} ns/file ({ms_t:>6.2} ms) | allocs/file={all_f:>5.1} bytes/file={b_f:>7.1}");
367}
Source

pub const fn is_some(self) -> bool

Source

pub const fn is_overlay(self) -> bool

Trait Implementations§

Source§

impl Clone for GlobalDefId

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 GlobalDefId

Source§

impl Debug for GlobalDefId

Source§

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

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

impl Default for GlobalDefId

Source§

fn default() -> Self

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

impl Eq for GlobalDefId

Source§

impl Hash for GlobalDefId

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 GlobalDefId

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 GlobalDefId

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 GlobalDefId

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 GlobalDefId

Auto Trait Implementations§

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.