| @@ -7,6 +7,9 @@ |
| 7 | 7 | //! checking re-run over the whole package. That is well within budget at |
| 8 | 8 | //! v0 scale; finer caching keyed by stable item ids can replace the |
| 9 | 9 | //! internals of [`Db::analyze`] without changing its callers. |
| 10 | +//! |
| 11 | +//! A package's files are parsed on a few threads at once, and std's once |
| 12 | +//! per process, shared by every `Db` (issue #122). |
| 10 | 13 | |
| 11 | 14 | pub mod ide; |
| 12 | 15 | |
| @@ -97,8 +100,16 @@ impl Db { |
| 97 | 100 | load_errors: Vec::new(), |
| 98 | 101 | parse_time: Duration::ZERO, |
| 99 | 102 | }; |
| 100 | | − for (path, text) in STD { |
| 101 | | − db.add_module(path, &format!("<{path}.lse>"), (*text).to_owned()); |
| 103 | + let start = Instant::now(); |
| 104 | + let parses = std_parses(); |
| 105 | + db.parse_time += start.elapsed(); |
| 106 | + for ((path, text), parse) in STD.iter().zip(parses) { |
| 107 | + db.add_parsed( |
| 108 | + path, |
| 109 | + &format!("<{path}.lse>"), |
| 110 | + (*text).to_owned(), |
| 111 | + parse.clone(), |
| 112 | + ); |
| 102 | 113 | } |
| 103 | 114 | db |
| 104 | 115 | } |
| @@ -113,6 +124,17 @@ impl Db { |
| 113 | 124 | let start = Instant::now(); |
| 114 | 125 | let parse = louise_syntax::parse(&text); |
| 115 | 126 | self.parse_time += start.elapsed(); |
| 127 | + self.add_parsed(module_path, display_path, text, parse) |
| 128 | + } |
| 129 | + |
| 130 | + /// [`Db::add_module`] for a text already parsed. |
| 131 | + fn add_parsed( |
| 132 | + &mut self, |
| 133 | + module_path: &str, |
| 134 | + display_path: &str, |
| 135 | + text: String, |
| 136 | + parse: Parse, |
| 137 | + ) -> FileId { |
| 116 | 138 | let file = self.sources.add(SourceFile::new(display_path, text)); |
| 117 | 139 | self.modules.push(Module { |
| 118 | 140 | path: module_path.to_owned(), |
| @@ -312,20 +334,79 @@ impl Db { |
| 312 | 334 | let mut files = Vec::new(); |
| 313 | 335 | collect_til_files(src, &mut files)?; |
| 314 | 336 | files.sort(); |
| 337 | + let texts = files |
| 338 | + .iter() |
| 339 | + .map(std::fs::read_to_string) |
| 340 | + .collect::<std::io::Result<Vec<_>>>()?; |
| 341 | + let start = Instant::now(); |
| 342 | + let parses = parse_all(&texts.iter().map(String::as_str).collect::<Vec<_>>()); |
| 343 | + self.parse_time += start.elapsed(); |
| 315 | 344 | let mut ids = Vec::new(); |
| 316 | | − for path in files { |
| 317 | | − let text = std::fs::read_to_string(&path)?; |
| 318 | | − let module = match (prefix, module_path(src, &path)) { |
| 345 | + for ((path, text), parse) in files.iter().zip(texts).zip(parses) { |
| 346 | + let module = match (prefix, module_path(src, path)) { |
| 319 | 347 | (Some(p), m) if m == "lib" => p.to_owned(), |
| 320 | 348 | (Some(p), m) => format!("{p}/{m}"), |
| 321 | 349 | (None, m) => m, |
| 322 | 350 | }; |
| 323 | | − ids.push(self.add_module(&module, &path.display().to_string(), text)); |
| 351 | + ids.push(self.add_parsed(&module, &path.display().to_string(), text, parse)); |
| 324 | 352 | } |
| 325 | 353 | Ok(ids) |
| 326 | 354 | } |
| 327 | 355 | } |
| 328 | 356 | |
| 357 | +/// The standard library's modules, parsed once per process: every [`Db`] |
| 358 | +/// clones them, which only copies reference counts (a syntax tree is |
| 359 | +/// shared and immutable). Tests and the language server make many. |
| 360 | +fn std_parses() -> &'static [Parse] { |
| 361 | + static PARSES: std::sync::OnceLock<Vec<Parse>> = std::sync::OnceLock::new(); |
| 362 | + PARSES.get_or_init(|| parse_all(&STD.iter().map(|(_, text)| *text).collect::<Vec<_>>())) |
| 363 | +} |
| 364 | + |
| 365 | +/// Parse `texts`, a few at a time (issue #122); the results are in the |
| 366 | +/// same order. Modules are parsed independently: imports are resolved |
| 367 | +/// afterwards, on all of them. The largest texts go first, so that the |
| 368 | +/// prelude (a third of std) does not finish last; more than [`PARSERS`] |
| 369 | +/// threads cost more CPU to start than they saved. |
| 370 | +fn parse_all(texts: &[&str]) -> Vec<Parse> { |
| 371 | + let threads = std::thread::available_parallelism() |
| 372 | + .map_or(1, |n| n.get()) |
| 373 | + .min(PARSERS) |
| 374 | + .min(texts.len()); |
| 375 | + if threads <= 1 { |
| 376 | + return texts.iter().map(|t| louise_syntax::parse(t)).collect(); |
| 377 | + } |
| 378 | + let mut order: Vec<usize> = (0..texts.len()).collect(); |
| 379 | + order.sort_by_key(|i| std::cmp::Reverse(texts[*i].len())); |
| 380 | + let next = std::sync::atomic::AtomicUsize::new(0); |
| 381 | + let mut parsed: Vec<(usize, Parse)> = std::thread::scope(|scope| { |
| 382 | + let workers: Vec<_> = (0..threads) |
| 383 | + .map(|_| { |
| 384 | + std::thread::Builder::new() |
| 385 | + // The parser recurses up to its depth limit. |
| 386 | + .stack_size(8 << 20) |
| 387 | + .spawn_scoped(scope, || { |
| 388 | + let mut done = Vec::new(); |
| 389 | + loop { |
| 390 | + let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 391 | + let Some(&i) = order.get(k) else { break done }; |
| 392 | + done.push((i, louise_syntax::parse(texts[i]))); |
| 393 | + } |
| 394 | + }) |
| 395 | + .expect("louise: cannot start a parser thread") |
| 396 | + }) |
| 397 | + .collect(); |
| 398 | + workers |
| 399 | + .into_iter() |
| 400 | + .flat_map(|w| w.join().unwrap_or_else(|p| std::panic::resume_unwind(p))) |
| 401 | + .collect() |
| 402 | + }); |
| 403 | + parsed.sort_by_key(|(i, _)| *i); |
| 404 | + parsed.into_iter().map(|(_, parse)| parse).collect() |
| 405 | +} |
| 406 | + |
| 407 | +/// The most threads [`parse_all`] starts. |
| 408 | +const PARSERS: usize = 3; |
| 409 | + |
| 329 | 410 | fn collect_til_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> { |
| 330 | 411 | if !dir.is_dir() { |
| 331 | 412 | return Ok(()); |
| @@ -365,6 +446,59 @@ mod tests { |
| 365 | 446 | } |
| 366 | 447 | |
| 367 | 448 | #[test] |
| 449 | + fn parallel_parses_come_back_in_order() { |
| 450 | + let texts: Vec<String> = (0..40) |
| 451 | + .map(|i| format!("pub fn f{i}() -> Int {{ {} }}", "1 + ".repeat(i % 7) + "1")) |
| 452 | + .collect(); |
| 453 | + let refs: Vec<&str> = texts.iter().map(String::as_str).collect(); |
| 454 | + let parallel = parse_all(&refs); |
| 455 | + assert_eq!(parallel.len(), texts.len()); |
| 456 | + for (text, parse) in texts.iter().zip(¶llel) { |
| 457 | + assert_eq!( |
| 458 | + parse.syntax().to_string(), |
| 459 | + *text, |
| 460 | + "a parse is in another's place" |
| 461 | + ); |
| 462 | + } |
| 463 | + } |
| 464 | + |
| 465 | + #[test] |
| 466 | + fn a_package_loads_the_same_way_twice() { |
| 467 | + let dir = std::env::temp_dir().join(format!("louise-db-order-{}", std::process::id())); |
| 468 | + let src = dir.join("src"); |
| 469 | + std::fs::create_dir_all(src.join("app")).unwrap(); |
| 470 | + for (file, text) in [ |
| 471 | + ( |
| 472 | + "main.lse", |
| 473 | + "import app/b\npub fn main() -> Int { b.two() }\n", |
| 474 | + ), |
| 475 | + ("app/a.lse", "pub fn one() -> Int { 1 }\n"), |
| 476 | + ( |
| 477 | + "app/b.lse", |
| 478 | + "import app/a\npub fn two() -> Int { a.one() + true }\n", |
| 479 | + ), |
| 480 | + ] { |
| 481 | + std::fs::write(src.join(file), text).unwrap(); |
| 482 | + } |
| 483 | + let load = || { |
| 484 | + let mut db = Db::new(); |
| 485 | + db.load_dir(&src, None).unwrap(); |
| 486 | + let messages: Vec<String> = db |
| 487 | + .analyze() |
| 488 | + .diagnostics |
| 489 | + .iter() |
| 490 | + .map(|d| d.message.clone()) |
| 491 | + .collect(); |
| 492 | + (db.user_modules(), messages) |
| 493 | + }; |
| 494 | + let (modules, diagnostics) = load(); |
| 495 | + assert_eq!(modules, ["app/a", "app/b", "main"]); |
| 496 | + assert!(!diagnostics.is_empty(), "the type error in app/b"); |
| 497 | + assert_eq!(load(), (modules, diagnostics)); |
| 498 | + let _ = std::fs::remove_dir_all(&dir); |
| 499 | + } |
| 500 | + |
| 501 | + #[test] |
| 368 | 502 | fn edits_are_reanalyzed() { |
| 369 | 503 | let mut db = Db::new(); |
| 370 | 504 | let file = db.add_module("main", "main.lse", "pub fn f() -> Int { \"no\" }".into()); |