1use std::{
5 env,
6 ffi::OsStr,
7 ops::AddAssign,
8 panic::Location,
9 pin::Pin,
10 sync::OnceLock,
11 task::{Context, Poll},
12 time::Instant,
13};
14
15pub mod arc_cow;
16
17#[cfg(target_os = "windows")]
18const CREATE_NO_WINDOW: u32 = 0x0800_0000_u32;
19
20#[cfg(target_os = "windows")]
21pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
22 use std::os::windows::process::CommandExt;
23
24 let mut command = std::process::Command::new(program);
25 command.creation_flags(CREATE_NO_WINDOW);
26 command
27}
28
29#[cfg(not(target_os = "windows"))]
30pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
31 std::process::Command::new(program)
32}
33
34#[cfg(target_os = "windows")]
35pub fn get_windows_system_shell() -> String {
36 use std::path::PathBuf;
37
38 fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
39 #[cfg(target_pointer_width = "64")]
40 let env_var = if find_alternate {
41 "ProgramFiles(x86)"
42 } else {
43 "ProgramFiles"
44 };
45
46 #[cfg(target_pointer_width = "32")]
47 let env_var = if find_alternate {
48 "ProgramW6432"
49 } else {
50 "ProgramFiles"
51 };
52
53 let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
54 install_base_dir
55 .read_dir()
56 .ok()?
57 .filter_map(Result::ok)
58 .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
59 .filter_map(|entry| {
60 let dir_name = entry.file_name();
61 let dir_name = dir_name.to_string_lossy();
62
63 let version = if find_preview {
64 let dash_index = dir_name.find('-')?;
65 if &dir_name[dash_index + 1..] != "preview" {
66 return None;
67 };
68 dir_name[..dash_index].parse::<u32>().ok()?
69 } else {
70 dir_name.parse::<u32>().ok()?
71 };
72
73 let exe_path = entry.path().join("pwsh.exe");
74 if exe_path.exists() {
75 Some((version, exe_path))
76 } else {
77 None
78 }
79 })
80 .max_by_key(|(version, _)| *version)
81 .map(|(_, path)| path)
82 }
83
84 fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
85 let msix_app_dir =
86 PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
87 if !msix_app_dir.exists() {
88 return None;
89 }
90
91 let prefix = if find_preview {
92 "Microsoft.PowerShellPreview_"
93 } else {
94 "Microsoft.PowerShell_"
95 };
96 msix_app_dir
97 .read_dir()
98 .ok()?
99 .filter_map(|entry| {
100 let entry = entry.ok()?;
101 if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) {
102 return None;
103 }
104
105 if !entry.file_name().to_string_lossy().starts_with(prefix) {
106 return None;
107 }
108
109 let exe_path = entry.path().join("pwsh.exe");
110 exe_path.exists().then_some(exe_path)
111 })
112 .next()
113 }
114
115 fn find_pwsh_in_scoop() -> Option<PathBuf> {
116 let pwsh_exe =
117 PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe");
118 pwsh_exe.exists().then_some(pwsh_exe)
119 }
120
121 static SYSTEM_SHELL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
122 let locations = [
123 || find_pwsh_in_programfiles(false, false),
124 || find_pwsh_in_programfiles(true, false),
125 || find_pwsh_in_msix(false),
126 || find_pwsh_in_programfiles(false, true),
127 || find_pwsh_in_msix(true),
128 || find_pwsh_in_programfiles(true, true),
129 || find_pwsh_in_scoop(),
130 || which::which_global("pwsh.exe").ok(),
131 || which::which_global("powershell.exe").ok(),
132 ];
133
134 locations
135 .into_iter()
136 .find_map(|f| f())
137 .map(|p| p.to_string_lossy().trim().to_owned())
138 .inspect(|shell| log::info!("Found powershell in: {}", shell))
139 .unwrap_or_else(|| {
140 log::warn!("Powershell not found, falling back to `cmd`");
141 "cmd.exe".to_string()
142 })
143 });
144
145 (*SYSTEM_SHELL).clone()
146}
147
148pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
149 let prev = *value;
150 *value += T::from(1);
151 prev
152}
153
154pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
155 static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
156 let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
157 env::var("ZED_MEASUREMENTS")
158 .map(|measurements| measurements == "1" || measurements == "true")
159 .unwrap_or(false)
160 });
161
162 if *zed_measurements {
163 let start = Instant::now();
164 let result = f();
165 let elapsed = start.elapsed();
166 eprintln!("{}: {:?}", label, elapsed);
167 result
168 } else {
169 f()
170 }
171}
172
173#[macro_export]
174macro_rules! debug_panic {
175 ( $($fmt_arg:tt)* ) => {
176 if cfg!(debug_assertions) {
177 panic!( $($fmt_arg)* );
178 } else {
179 let backtrace = std::backtrace::Backtrace::capture();
180 log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
181 }
182 };
183}
184
185#[track_caller]
186pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
187 #[cfg(debug_assertions)]
188 if option.is_none() {
189 panic!("Unexpected None");
190 }
191 option
192}
193
194#[macro_export]
199macro_rules! maybe {
200 ($block:block) => {
201 (|| $block)()
202 };
203 (async $block:block) => {
204 (async || $block)()
205 };
206 (async move $block:block) => {
207 (async move || $block)()
208 };
209}
210pub trait ResultExt<E> {
211 type Ok;
212
213 fn log_err(self) -> Option<Self::Ok>;
214 fn log_err_with_backtrace(self) -> Option<Self::Ok>
218 where
219 E: std::fmt::Debug;
220 fn debug_assert_ok(self, reason: &str) -> Self;
222 fn warn_on_err(self) -> Option<Self::Ok>;
223 fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
224 fn anyhow(self) -> anyhow::Result<Self::Ok>
225 where
226 E: Into<anyhow::Error>;
227}
228
229impl<T, E> ResultExt<E> for Result<T, E>
230where
231 E: std::fmt::Display,
232{
233 type Ok = T;
234
235 #[track_caller]
236 fn log_err(self) -> Option<T> {
237 self.log_with_level(log::Level::Error)
238 }
239
240 #[track_caller]
241 fn log_err_with_backtrace(self) -> Option<T>
242 where
243 E: std::fmt::Debug,
244 {
245 match self {
246 Ok(value) => Some(value),
247 Err(error) => {
248 log_error_with_caller(
249 *Location::caller(),
250 DebugAsDisplay(&error),
251 log::Level::Error,
252 );
253 None
254 }
255 }
256 }
257
258 #[track_caller]
259 fn debug_assert_ok(self, reason: &str) -> Self {
260 if let Err(error) = &self {
261 debug_panic!("{reason} - {error:#}");
262 }
263 self
264 }
265
266 #[track_caller]
267 fn warn_on_err(self) -> Option<T> {
268 self.log_with_level(log::Level::Warn)
269 }
270
271 #[track_caller]
272 fn log_with_level(self, level: log::Level) -> Option<T> {
273 match self {
274 Ok(value) => Some(value),
275 Err(error) => {
276 log_error_with_caller(*Location::caller(), error, level);
277 None
278 }
279 }
280 }
281
282 fn anyhow(self) -> anyhow::Result<T>
283 where
284 E: Into<anyhow::Error>,
285 {
286 self.map_err(Into::into)
287 }
288}
289
290fn caller_log_metadata(file: &str) -> (String, Option<String>) {
293 let normalized = file.replace('\\', "/");
294 let parts: Vec<_> = normalized
295 .split('/')
296 .filter(|part| !part.is_empty())
297 .collect();
298 let source = parts
299 .windows(3)
300 .enumerate()
301 .find_map(|(i, segment)| {
302 if matches!(segment[0], "crates" | "vendor") && segment[2] == "src" {
303 Some((segment[1], i + 3))
304 } else {
305 None
306 }
307 })
308 .or_else(|| {
309 parts.windows(5).enumerate().find_map(|(i, segment)| {
310 if segment[0] != "registry" || segment[1] != "src" || segment[4] != "src" {
311 return None;
312 }
313 let package = segment[3];
314 package.match_indices('-').find_map(|(separator, _)| {
315 let (name, version) = (&package[..separator], &package[separator + 1..]);
316 let core = version.split(['-', '+']).next()?;
317 let numbers: Vec<_> = core.split('.').collect();
318 if name.is_empty()
319 || numbers.len() != 3
320 || !numbers
321 .iter()
322 .all(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()))
323 {
324 return None;
325 }
326 Some((name, i + 5))
327 })
328 })
329 });
330 if let Some((krate, start)) = source {
331 let krate = krate.replace('-', "_");
332 let mut modules: Vec<_> = parts[start..]
333 .iter()
334 .map(|s| s.trim_end_matches(".rs"))
335 .collect();
336 if modules
337 .last()
338 .is_some_and(|name| matches!(*name, "lib" | "main" | "mod"))
339 {
340 modules.pop();
341 }
342 if modules.first() == Some(&krate.as_str()) {
343 modules.remove(0);
344 }
345 let mut target = krate;
346 for module in modules {
347 target.push_str("::");
348 target.push_str(module);
349 }
350 if !target.is_empty() {
351 return (target.clone(), Some(target));
352 }
353 }
354 let stem = parts.last().copied().unwrap_or("").trim_end_matches(".rs");
355 let target = if stem.chars().any(|c| c.is_alphanumeric()) {
356 stem
357 } else {
358 "guic_gpui_util"
359 };
360 (target.to_owned(), None)
361}
362
363fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
364where
365 E: std::fmt::Display,
366{
367 let (target, module_path) = caller_log_metadata(caller.file());
368 log::logger().log(
369 &log::Record::builder()
370 .target(&target)
371 .module_path(module_path.as_deref())
372 .args(format_args!("{:#}", error))
373 .file(Some(caller.file()))
374 .line(Some(caller.line()))
375 .level(level)
376 .build(),
377 );
378}
379
380#[track_caller]
381pub fn log_err<E: std::fmt::Display>(error: &E) {
382 log_error_with_caller(*Location::caller(), error, log::Level::Error);
383}
384
385struct DebugAsDisplay<'a, E>(&'a E);
388
389impl<E: std::fmt::Debug> std::fmt::Display for DebugAsDisplay<'_, E> {
390 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391 write!(f, "{:?}", self.0)
392 }
393}
394
395pub trait TryFutureExt {
396 fn log_err(self) -> LogErrorFuture<Self>
397 where
398 Self: Sized;
399
400 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
401 where
402 Self: Sized;
403
404 fn warn_on_err(self) -> LogErrorFuture<Self>
405 where
406 Self: Sized;
407 fn unwrap(self) -> UnwrapFuture<Self>
408 where
409 Self: Sized;
410}
411
412pub trait TryFutureExtBacktrace {
415 fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture<Self>
416 where
417 Self: Sized;
418
419 fn log_tracked_err_with_backtrace(
420 self,
421 location: core::panic::Location<'static>,
422 ) -> LogErrorWithBacktraceFuture<Self>
423 where
424 Self: Sized;
425}
426
427impl<F, T, E> TryFutureExt for F
428where
429 F: Future<Output = Result<T, E>>,
430 E: std::fmt::Display,
431{
432 #[track_caller]
433 fn log_err(self) -> LogErrorFuture<Self>
434 where
435 Self: Sized,
436 {
437 let location = Location::caller();
438 LogErrorFuture(self, log::Level::Error, *location)
439 }
440
441 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
442 where
443 Self: Sized,
444 {
445 LogErrorFuture(self, log::Level::Error, location)
446 }
447
448 #[track_caller]
449 fn warn_on_err(self) -> LogErrorFuture<Self>
450 where
451 Self: Sized,
452 {
453 let location = Location::caller();
454 LogErrorFuture(self, log::Level::Warn, *location)
455 }
456
457 fn unwrap(self) -> UnwrapFuture<Self>
458 where
459 Self: Sized,
460 {
461 UnwrapFuture(self)
462 }
463}
464
465impl<F, T, E> TryFutureExtBacktrace for F
466where
467 F: Future<Output = Result<T, E>>,
468 E: std::fmt::Debug,
469{
470 #[track_caller]
471 fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture<Self>
472 where
473 Self: Sized,
474 {
475 let location = Location::caller();
476 LogErrorWithBacktraceFuture(self, log::Level::Error, *location)
477 }
478
479 fn log_tracked_err_with_backtrace(
480 self,
481 location: core::panic::Location<'static>,
482 ) -> LogErrorWithBacktraceFuture<Self>
483 where
484 Self: Sized,
485 {
486 LogErrorWithBacktraceFuture(self, log::Level::Error, location)
487 }
488}
489
490#[must_use]
491pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
492
493impl<F, T, E> Future for LogErrorFuture<F>
494where
495 F: Future<Output = Result<T, E>>,
496 E: std::fmt::Display,
497{
498 type Output = Option<T>;
499
500 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
501 let level = self.1;
502 let location = self.2;
503 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
504 match inner.poll(cx) {
505 Poll::Ready(output) => Poll::Ready(match output {
506 Ok(output) => Some(output),
507 Err(error) => {
508 log_error_with_caller(location, error, level);
509 None
510 }
511 }),
512 Poll::Pending => Poll::Pending,
513 }
514 }
515}
516
517#[must_use]
518pub struct LogErrorWithBacktraceFuture<F>(F, log::Level, core::panic::Location<'static>);
519
520impl<F, T, E> Future for LogErrorWithBacktraceFuture<F>
521where
522 F: Future<Output = Result<T, E>>,
523 E: std::fmt::Debug,
524{
525 type Output = Option<T>;
526
527 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
528 let level = self.1;
529 let location = self.2;
530 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
531 match inner.poll(cx) {
532 Poll::Ready(output) => Poll::Ready(match output {
533 Ok(output) => Some(output),
534 Err(error) => {
535 log_error_with_caller(location, DebugAsDisplay(&error), level);
536 None
537 }
538 }),
539 Poll::Pending => Poll::Pending,
540 }
541 }
542}
543
544pub struct UnwrapFuture<F>(F);
545
546impl<F, T, E> Future for UnwrapFuture<F>
547where
548 F: Future<Output = Result<T, E>>,
549 E: std::fmt::Debug,
550{
551 type Output = T;
552
553 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
554 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
555 match inner.poll(cx) {
556 Poll::Ready(result) => Poll::Ready(result.unwrap()),
557 Poll::Pending => Poll::Pending,
558 }
559 }
560}
561
562pub struct Deferred<F: FnOnce()>(Option<F>);
563
564impl<F: FnOnce()> Deferred<F> {
565 pub fn abort(mut self) {
567 self.0.take();
568 }
569}
570
571impl<F: FnOnce()> Drop for Deferred<F> {
572 fn drop(&mut self) {
573 if let Some(f) = self.0.take() {
574 f()
575 }
576 }
577}
578
579#[must_use]
581pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
582 Deferred(Some(f))
583}
584
585#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
586pub struct TypeIdHashBuilder;
587
588impl std::hash::BuildHasher for TypeIdHashBuilder {
589 type Hasher = TypeIdHasher;
590
591 fn build_hasher(&self) -> Self::Hasher {
592 TypeIdHasher::default()
593 }
594}
595
596#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
597pub struct TypeIdHasher {
598 value: u64,
599}
600
601impl std::hash::Hasher for TypeIdHasher {
602 #[inline]
603 fn write(&mut self, bytes: &[u8]) {
604 if let Some(bytes) = bytes.get(..8) {
606 bytes
607 .as_array()
608 .map(|&array| self.value = u64::from_ne_bytes(array))
609 .unwrap_or_else(|| unreachable!("slice was sliced to 8 bytes"));
610 } else {
611 debug_panic!(
612 "expected a 64-bit value, did you use this hasher with something other than a TypeId?"
613 );
614 }
615 }
616
617 #[inline]
618 fn finish(&self) -> u64 {
619 self.value
620 }
621}
622
623#[test]
624fn type_id_hasher() {
625 use core::any::TypeId;
626 use core::hash::{Hash, Hasher};
627 fn verify_hashing_with(type_id: TypeId) {
628 let mut hasher = TypeIdHasher::default();
629 type_id.hash(&mut hasher);
630 assert_ne!(hasher.finish(), 0);
631 }
632 verify_hashing_with(TypeId::of::<usize>());
634 verify_hashing_with(TypeId::of::<()>());
635 verify_hashing_with(TypeId::of::<str>());
636 verify_hashing_with(TypeId::of::<&str>());
637 verify_hashing_with(TypeId::of::<Vec<u8>>());
638}
639
640pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
641where
642 F: Fn(&T, &T) -> std::cmp::Ordering,
643{
644 if limit == 0 {
645 items.truncate(0);
646 }
647 if items.len() <= limit {
648 items.sort_by(compare);
649 return;
650 }
651 items.select_nth_unstable_by(limit, compare);
658 items.truncate(limit);
659 items.sort_by(compare);
660}
661
662#[cfg(test)]
663mod caller_metadata_tests {
664 use super::*;
665
666 #[test]
667 fn resolves_portable_caller_paths() {
668 for (path, target, module) in [
669 (
670 "/repo/crates/gpui/src/window.rs",
671 "gpui::window",
672 Some("gpui::window"),
673 ),
674 ("/repo/crates/gpui/src/lib.rs", "gpui", Some("gpui")),
675 ("/repo/crates/gpui/src/main.rs", "gpui", Some("gpui")),
676 (
677 "/repo/crates/gpui/src/input/mod.rs",
678 "gpui::input",
679 Some("gpui::input"),
680 ),
681 ("/repo/crates/gpui/src/gpui.rs", "gpui", Some("gpui")),
682 (
683 "/cargo/registry/src/index/guic-gpui-0.2.0/src/window.rs",
684 "guic_gpui::window",
685 Some("guic_gpui::window"),
686 ),
687 (
688 "/repo/vendor/guic-gpui/src/window.rs",
689 "guic_gpui::window",
690 Some("guic_gpui::window"),
691 ),
692 (
693 "/cargo/registry/src/index/guic-gpui-0.2.0-beta.1/src/main.rs",
694 "guic_gpui",
695 Some("guic_gpui"),
696 ),
697 (
698 "/cargo/registry/src/index/guic-gpui-2/src/window.rs",
699 "window",
700 None,
701 ),
702 ("/repo/src/window.rs", "window", None),
703 (
704 r"C:\repo\crates\gpui\src\window.rs",
705 "gpui::window",
706 Some("gpui::window"),
707 ),
708 ("/source/window.rs", "window", None),
709 ("window.rs", "window", None),
710 ("/repo/notcrates/gpui/src/window.rs", "window", None),
711 ("", "guic_gpui_util", None),
712 ("/", "guic_gpui_util", None),
713 ("..", "guic_gpui_util", None),
714 ] {
715 let actual = caller_log_metadata(path);
716 assert_eq!(
717 actual,
718 (target.to_owned(), module.map(str::to_owned)),
719 "{path}"
720 );
721 assert!(!actual.0.is_empty());
722 }
723 }
724
725 #[test]
726 fn emitted_errors_preserve_caller_metadata() {
727 struct Logger;
728 #[derive(Debug)]
729 struct Record {
730 target: String,
731 module: Option<String>,
732 level: log::Level,
733 message: String,
734 file: String,
735 line: u32,
736 }
737 thread_local! { static RECORDS: std::cell::RefCell<Vec<Record>> = const { std::cell::RefCell::new(Vec::new()) }; }
738 impl log::Log for Logger {
739 fn enabled(&self, _: &log::Metadata<'_>) -> bool {
740 true
741 }
742 fn log(&self, record: &log::Record<'_>) {
743 RECORDS.with_borrow_mut(|records| {
744 records.push(Record {
745 target: record.target().to_owned(),
746 module: record.module_path().map(str::to_owned),
747 level: record.level(),
748 message: record.args().to_string(),
749 file: record.file().unwrap().to_owned(),
750 line: record.line().unwrap(),
751 })
752 });
753 }
754 fn flush(&self) {}
755 }
756 log::set_logger(&Logger).unwrap();
758 log::set_max_level(log::LevelFilter::Trace);
759 let free_line = line!() + 1;
760 log_err(&"free error");
761 let result_line = line!() + 1;
762 let _: Option<()> = Err("result error").log_err();
763 let future_line = line!() + 1;
764 let mut future = std::pin::pin!(std::future::ready(Err::<(), _>("future error")).log_err());
765 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
766 assert!(std::future::Future::poll(future.as_mut(), &mut context).is_ready());
767 RECORDS.with_borrow(|records| {
768 assert_eq!(records.len(), 3);
769 for (record, line, message) in [
770 (&records[0], free_line, "free error"),
771 (&records[1], result_line, "result error"),
772 (&records[2], future_line, "future error"),
773 ] {
774 assert_eq!(
775 (record.target.clone(), record.module.clone()),
776 caller_log_metadata(file!())
777 );
778 assert_eq!(record.level, log::Level::Error);
779 assert_eq!(record.message, message);
780 assert_eq!(record.file, file!());
781 assert_eq!(record.line, line);
782 }
783 });
784 }
785}