diff --git a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs new file mode 100644 index 000000000..881b38292 --- /dev/null +++ b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs @@ -0,0 +1,96 @@ +//! Regression guards for two quadratic costs of reading a local through a long chain of flow +//! nodes that leave it alone or write it: +//! +//! ```lua +//! ---@param h H +//! local function f(h) +//! if h.a then elseif h.b then end -- n times +//! return h +//! end +//! +//! local function g() +//! local x = 0 +//! x = x + 1 -- n times +//! return x +//! end +//! ``` +//! +//! A value read met the memo only where it started, so each read walked back through every +//! earlier untouched merge, or every earlier write: n reads × n nodes. 0.25.1 is linear here. + +use crate::VirtualWorkspace; +use crate::semantic_model::flow::flow_metrics; +use emmylua_parser::{LuaAstNode, LuaNameExpr}; + +fn untouched_merge_chain(n: usize) -> String { + let mut content = String::from( + "---@class H\n---@field a? boolean\n---@field b? boolean\n\n---@param h H\nlocal function f(h)\n", + ); + for _ in 0..n { + content.push_str(" if h.a then elseif h.b then end\n"); + } + content.push_str(" return h\nend\nreturn f\n"); + content +} + +fn reassigned_chain(n: usize) -> String { + let mut content = String::from("local function g()\n local x = 0\n"); + for _ in 0..n { + content.push_str(" x = x + 1\n"); + } + content.push_str(" return x\nend\nreturn g\n"); + content +} + +/// Flow steps to read every `name` in `source`, and the type of the last read. +fn read_steps(source: &str, name: &str) -> (u64, String) { + let mut ws = VirtualWorkspace::new(); + let fid = ws.def_file("chain.lua", source); + let model = ws.analysis.semantic_model(fid); + flow_metrics::reset(); + let mut last = None; + for expr in model.chunk().expect("chunk").descendants::() { + if expr.get_name_text().as_deref() == Some(name) { + last = Some(model.type_of_expr_at(expr.get_syntax_id(), expr.get_position())); + } + } + let steps = flow_metrics::trace_steps() + flow_metrics::branch_scan_steps(); + (steps, ws.humanize_type(last.expect("a read"))) +} + +/// Steps at n = 16, 64, 256 stay within twice a linear extrapolation from n = 16, and the last +/// read has the type `expected` at every n. +fn assert_linear(what: &str, expected: &str, read_at: impl Fn(usize) -> (u64, String)) { + let measurements: Vec<_> = [16usize, 64, 256] + .into_iter() + .map(|n| { + let (steps, ty) = read_at(n); + assert_eq!(ty, expected, "type of the last read for {n} {what}"); + (n, steps) + }) + .collect(); + let (n_first, steps_first) = measurements[0]; + assert!(steps_first > 0, "no flow steps counted: {measurements:?}"); + for (n, steps) in &measurements { + let bound = steps_first * (*n as u64) / (n_first as u64) * 2; + assert!( + *steps <= bound, + "{steps} flow steps for {n} {what} (bound {bound}, linear from n = {n_first}): \ + each read walks back through all earlier ones. All: {measurements:?}" + ); + } +} + +#[test] +fn reads_past_untouched_merges_stay_linear() { + assert_linear("conditionals", "H", |n| { + read_steps(&untouched_merge_chain(n), "h") + }); +} + +#[test] +fn reads_of_a_reassigned_local_stay_linear() { + assert_linear("writes", "integer", |n| { + read_steps(&reassigned_chain(n), "x") + }); +} diff --git a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs index e1339e543..b813e9327 100644 --- a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs +++ b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs @@ -1,5 +1,6 @@ mod fix_tests; mod flow_loop_memo_tests; +mod flow_read_memo_tests; mod module_roots_tests; mod p0_tests; mod p10_tests; diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 8da2de74f..c64545dc8 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2334,7 +2334,52 @@ fn trace_decl_uncached( let root_mode = mode; let mut current = flow_id; let mut frames = Vec::new(); + // Set when the walk skipped a merge whose branches leave `decl` alone (below), and + // consumed on the very next iteration, where the walk lands on the merge's predecessor. + let mut just_skipped_merge = false; let result = 'trace: loop { + // A value read that lands here after skipping a merge, or that reaches a write of + // `decl`, uses and fills the memo, as `trace_decl` does at its start: the memo holds + // the state for an empty incoming path, and the guards collected so far narrow it. + // Without this, each read of a long chain of such merges or writes walks back + // through all of them. At a write, the memo frame sits under the write's own frame, + // so it saves the state after the write. + let landed = std::mem::take(&mut just_skipped_merge); + if matches!(purpose, DeclTracePurpose::ReadValue) + && (landed + || tree.get_flow_effects(current).iter().any( + |effect| matches!(effect, FlowEffect::AssignDecl { decl: d, .. } if d == decl), + )) + && mode == root_mode + && current != flow_id + && !tree.is_in_cycle(current) + && !path + .narrowings + .iter() + .any(|narrowing| matches!(narrowing, Narrowing::Correlated { .. })) + { + let key = decl_trace_key(model, decl, current, purpose, mode, path); + // An entry still in progress belongs to an outer query: walk on, and leave it alone. + let (memo, absent) = { + let cache = model.cache.borrow(); + match cache.trace_state.get(&key) { + None => (None, true), + Some(cache::CacheEntry::InProgress) => (None, false), + Some(entry) => (entry.get(&cache).cloned(), false), + } + }; + if let Some(state) = memo { + break 'trace state.map(|state| finalize(model, state, path)); + } + // Only an empty path may fill it: entries hold the empty-path state, as in + // `trace_decl`, and `finalize` applies the path's guards and casts on lookup. + if absent && path.narrowings.is_empty() && path.casts.is_empty() { + frames.push(DeclTraceFrame::Memo { + key, + revision: model.cache.borrow().revision(), + }); + } + } // trace_decl owns the starting node's cache entry. Save intermediate // nodes here; casts use separate frames even when caching is disabled. if matches!(purpose, DeclTracePurpose::OriginalSignatures(_)) @@ -2597,6 +2642,7 @@ fn trace_decl_uncached( decl_branch_is_pure(model, tree, decl, purpose, *branch, common) }) { current = common; + just_skipped_merge = true; continue; } if matches!(purpose, DeclTracePurpose::OriginalSignatures(_))