Skip to main content

bynk_check/
phase_timing.rs

1//! Opt-in per-level timing of one project analysis (#1523, step 2).
2//!
3//! #1523's trigger asks for keystroke-to-diagnostic latency "attributed by
4//! level": R3.13's four query levels. This attributes the wall time of
5//! [`crate::analysis::analyse_project_with_policy`], the pass the language
6//! server runs on every edit, to those levels:
7//!
8//! | Level | What it covers here |
9//! |---|---|
10//! | `file` | discovery, and reading and parsing every source file (through the shared parse cache) |
11//! | `unit` | grouping, the per-unit symbol tables and signatures, `uses`/`consumes` resolution, and each unit's symbol composition and prelude |
12//! | `definition` | resolving and checking every declaration body, plus test bodies and the platform lock |
13//! | `project` | the whole-project validations (consumes cycles, name conflicts, exports, providers, event wiring), and assembling the result |
14//!
15//! The buckets partition the call: every instant belongs to exactly one, so
16//! they sum to the round's time. The boundaries are marked where the
17//! pipeline's own phase comments already put them, so the attribution is as
18//! good as that decomposition; it does not claim to be a profile.
19//!
20//! **Off by default and free when off.** Nothing is recorded unless the
21//! `BYNK_PHASE_TIMING` environment variable is set when the process first
22//! asks; each mark is then one cached boolean test. When on, [`finish`] writes
23//! one line to stderr, which `cargo xtask bench` reads from the language
24//! server.
25
26use std::cell::RefCell;
27use std::sync::OnceLock;
28use std::time::{Duration, Instant};
29
30/// One of R3.13's query levels.
31#[derive(Clone, Copy, Debug)]
32pub enum Level {
33    File,
34    Unit,
35    Definition,
36    Project,
37}
38
39const NAMES: [&str; 4] = ["file", "unit", "definition", "project"];
40
41struct Stopwatch {
42    at: Instant,
43    level: Level,
44    spent: [Duration; 4],
45}
46
47thread_local! {
48    static STOPWATCH: RefCell<Option<Stopwatch>> = const { RefCell::new(None) };
49}
50
51fn enabled() -> bool {
52    static ENABLED: OnceLock<bool> = OnceLock::new();
53    *ENABLED.get_or_init(|| std::env::var_os("BYNK_PHASE_TIMING").is_some())
54}
55
56/// Start timing the current analysis, charging time to `level` until the next
57/// [`mark`]. A no-op unless `BYNK_PHASE_TIMING` is set.
58pub fn begin(level: Level) {
59    if !enabled() {
60        return;
61    }
62    STOPWATCH.with(|s| {
63        *s.borrow_mut() = Some(Stopwatch {
64            at: Instant::now(),
65            level,
66            spent: [Duration::ZERO; 4],
67        });
68    });
69}
70
71/// From here, charge time to `level`; the time since the last mark goes to the
72/// level that was current. A no-op unless timing is on and [`begin`] ran.
73pub fn mark(level: Level) {
74    if !enabled() {
75        return;
76    }
77    STOPWATCH.with(|s| {
78        if let Some(w) = s.borrow_mut().as_mut() {
79            let now = Instant::now();
80            w.spent[w.level as usize] += now - w.at;
81            w.at = now;
82            w.level = level;
83        }
84    });
85}
86
87/// Close the current analysis and write one line to stderr:
88/// `bynk-phase-timing file=<ms> unit=<ms> definition=<ms> project=<ms>`.
89pub fn finish() {
90    if !enabled() {
91        return;
92    }
93    mark(Level::Project);
94    let spent = STOPWATCH.with(|s| s.borrow_mut().take().map(|w| w.spent));
95    if let Some(spent) = spent {
96        let mut line = String::from("bynk-phase-timing");
97        for (name, d) in NAMES.iter().zip(spent) {
98            line.push_str(&format!(" {name}={:.1}", d.as_secs_f64() * 1000.0));
99        }
100        eprintln!("{line}");
101    }
102}