use std::path::{Path, PathBuf};
use std::time::Instant;
use cpp_code_analysis::file::coordinates::FileOffset;
use cpp_code_analysis::{DiskFiles, OpenDocuments, Session, SessionFiles, StoreStats, WatchFilter};
fn project() -> Option<PathBuf> {
let named = std::env::var_os("CPPLS_MODULES_PROJECT")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"C:\Users\zc\Desktop\cpp_modules"));
named.is_dir().then_some(named)
}
fn sources(root: &Path) -> Vec<PathBuf> {
let mut files: Vec<PathBuf> = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(directory) = pending.pop() {
let Ok(entries) = std::fs::read_dir(&directory) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("");
if name != "build" && name != "out" && !name.starts_with('.') {
pending.push(path);
}
continue;
}
let extension = path.extension().and_then(|extension| extension.to_str());
if matches!(extension, Some("cpp" | "cppm" | "cc" | "cxx" | "ixx")) {
files.push(path);
}
}
}
files.sort();
files
}
fn delta(before: StoreStats, after: StoreStats) -> String {
let change = after.since(before);
format!("parsed {} reused {}", change.rebuilt, change.reused)
}
#[test]
#[ignore = "opens a real project; run with --ignored"]
fn what_import_std_costs() {
let Some(root) = project() else {
eprintln!("skipped: no project (set CPPLS_MODULES_PROJECT)");
return;
};
let files = sources(&root);
if files.is_empty() {
eprintln!("skipped: no sources");
return;
}
if std::env::var_os("CPPLS_MODULES_COLD").is_some_and(|value| !value.is_empty()) {
let _ = std::fs::remove_dir_all(root.join(".cppls"));
}
let started = Instant::now();
let mut session = Session::open(
root.clone(),
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&root),
);
session.add_project_files(files.clone());
let before_index = session.stats();
session.index_everything();
println!(
"index of {} file(s): {:?} ({})",
files.len(),
started.elapsed(),
delta(before_index, session.stats())
);
let mut order = files.clone();
order.sort_by_key(|path| {
path.file_name()
.and_then(|name| name.to_str())
.map(|name| name == "main.cpp")
.unwrap_or(false)
});
cpp_code_analysis::cache::cache_db::io::reset();
let mut cumulative = StoreStats::default();
let mut total = std::time::Duration::ZERO;
for file in &order {
let before = session.stats();
let started = Instant::now();
let report = session.memory_report();
if std::env::var_os("CPPLS_MODULES_MEMORY").is_some_and(|value| !value.is_empty()) {
println!(
" memory: vfs {:.0} MB ({} files), summaries {:.0} MB ({}), cooked {:.0} MB ({}), units {:.0} MB ({}), renderings {:.0} MB ({}), views {:.0} MB ({})",
report.vfs_text_bytes as f64 / 1e6,
report.vfs_files,
report.summary_bytes as f64 / 1e6,
report.summaries,
report.cooked_bytes as f64 / 1e6,
report.cooked_files,
report.unit_bytes as f64 / 1e6,
report.units,
report.rendering_bytes as f64 / 1e6,
report.renderings,
report.view_bytes as f64 / 1e6,
report.views,
);
}
let imports_unread = session.imports_a_module_that_is_not_read(file);
let read = session.read_the_modules_a_file_imports(file);
let view_time = Instant::now();
let _ = session.view_of_the_file(file);
let view_time = view_time.elapsed();
let elapsed = started.elapsed();
total += elapsed;
let (parsed, reused) = {
let change = session.stats().since(before);
cumulative = session.stats();
(change.rebuilt, change.reused)
};
println!(
"{:<16} {:>8.1} ms (modules: unread {} read {}; view {:>6.1} ms) parsed {parsed} reused {reused}",
file.file_name()
.and_then(|name| name.to_str())
.unwrap_or("?"),
elapsed.as_secs_f64() * 1000.0,
imports_unread,
read,
view_time.as_secs_f64() * 1000.0,
);
let _ = before;
}
println!(
"total {:?}; the session parsed {} file(s) and reused {}",
total, cumulative.rebuilt, cumulative.reused
);
let (reads, read_nanos, writes, write_nanos) =
cpp_code_analysis::cache::cache_db::io::statistics();
println!(
"database: {reads} read(s) in {:.2} s, {writes} write(s) in {:.2} s",
read_nanos as f64 / 1e9,
write_nanos as f64 / 1e9,
);
let main = order
.iter()
.find(|path| path.file_name().and_then(|name| name.to_str()) == Some("main.cpp"));
if let Some(main) = main {
let text = std::fs::read_to_string(main).expect("the file is readable");
let Some(at) = text.find("std::format").map(|at| at + "std::".len()) else {
println!("main.cpp writes no `std::`");
return;
};
let started = Instant::now();
if std::env::var_os("CPPLS_MODULES_UNIT").is_some_and(|value| !value.is_empty()) {
for round in 1..=3 {
let one = Instant::now();
let read = session.read_a_unit_of_the_project();
println!(
"unit read {round}: {} file(s) in {:?}",
read.map_or(0, |reading| reading.files),
one.elapsed()
);
}
}
let Some(view) = session.view_of_the_file(main) else {
println!("main.cpp has no view");
return;
};
let offered = session.completions(&view, FileOffset::new(at));
let labels: Vec<&str> = offered
.items
.iter()
.map(|item| item.label.as_str())
.collect();
println!(
"completion after `std::`: {:?} in {:?} ({} item(s){} )",
&labels[..labels.len().min(10)],
started.elapsed(),
labels.len(),
if offered.truncated { ", truncated" } else { "" }
);
let offered_format = labels.contains(&"format");
let indexed_format = session
.index()
.declarations_in("std", main)
.iter()
.filter(|declaration| declaration.fact.name.as_str() == "format")
.count();
println!(
" `format`: {} in the completion (truncated: {}), {indexed_format} in the index of `std`",
if offered_format { "offered" } else { "absent" },
offered.truncated
);
if !offered_format {
let declared = session
.index()
.declarations_in("std", main)
.iter()
.filter(|declaration| declaration.fact.name.as_str() == "format")
.count();
println!(
" ← `format` is not among the {} offered (truncated: {}); the index holds {declared} `std::format`",
labels.len(),
offered.truncated
);
let macros = session.index().macros();
println!(
" _MSVC_LANG defined: {}, _HAS_CXX20 defined: {}",
macros.is_defined("_MSVC_LANG"),
macros.is_defined("_HAS_CXX20"),
);
println!(
" the program that read main.cpp: {:?}",
session.index().the_program_that_read(main)
);
if let Some(std_ixx) = session
.project_files()
.iter()
.find(|path| path.file_name().and_then(|name| name.to_str()) == Some("std.ixx"))
{
println!(
" the program that read std.ixx: {:?}",
session.index().the_program_that_read(std_ixx)
);
}
for name in ["vformat", "make_format_args", "format", "to_string"] {
let held = session
.index()
.declarations_in("std", main)
.iter()
.filter(|declaration| declaration.fact.name.as_str() == name)
.count();
println!(" std::{name} visible from main.cpp: {held}");
}
for header in ["/format", "/vector", "/ranges"] {
let path = session
.index()
.summaries()
.find(|summary| summary.path.to_string_lossy().ends_with(header));
if let Some(summary) = path {
let sample: Vec<String> = summary
.declarations
.iter()
.filter(|fact| fact.name.as_str() == "format")
.map(|fact| format!("format in scope {:?}", fact.scope))
.take(3)
.collect();
let first: Vec<String> = summary
.declarations
.iter()
.take(3)
.map(|fact| format!("{} in {:?}", fact.name, fact.scope))
.collect();
println!(
" summary of <{}>: {} declaration(s), {} macro fact(s); format facts {:?}; first {:?}",
&header[1..],
summary.declarations.len(),
summary.macros.len(),
sample,
first,
);
}
}
if std::env::var_os("CPPLS_MODULES_WHY").is_some_and(|value| !value.is_empty()) {
let formats: Vec<String> = session
.index()
.summaries()
.map(|summary| summary.path.to_string_lossy().to_string())
.filter(|path| path.contains("format"))
.collect();
println!(" summaries naming format: {formats:?}");
let imports = session
.index()
.summary(main)
.map(|summary| format!("{:?}", summary.modules.imports));
println!(" main.cpp imports: {imports:?}");
let std_ixx = session
.project_files()
.iter()
.find(|path| path.file_name().and_then(|name| name.to_str()) == Some("std.ixx"))
.cloned();
println!(" std.ixx among the project files: {std_ixx:?}");
if let Some(std_ixx) = std_ixx {
let own = session
.index()
.declarations_in("std", &std_ixx)
.iter()
.filter(|declaration| declaration.fact.name.as_str() == "format")
.count();
let from_main = session.index().declarations_in("std", main).len();
println!(
" declarations_in(std) holding format from std.ixx: {own}; \
all visible from main.cpp: {from_main}"
);
}
if let Some(header) = formats
.iter()
.find(|path| path.ends_with("/format"))
.map(std::path::PathBuf::from)
{
let held = session
.index()
.declarations_in("std", &header)
.iter()
.filter(|declaration| declaration.fact.name.as_str() == "format")
.count();
println!(" declarations_in(std) holding format from <format>: {held}");
}
}
}
}
}