Skip to main content

gpui_util/
lib.rs

1// FluentBuilder
2// pub use gpui_util::{FutureExt, Timeout, arc_cow::ArcCow};
3
4use std::{
5    env,
6    ffi::OsStr,
7    fmt,
8    ops::AddAssign,
9    panic::Location,
10    pin::Pin,
11    sync::OnceLock,
12    task::{Context, Poll},
13    time::Instant,
14};
15
16pub mod arc_cow;
17
18#[cfg(target_os = "windows")]
19const CREATE_NO_WINDOW: u32 = 0x0800_0000_u32;
20
21#[cfg(target_os = "windows")]
22pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
23    use std::os::windows::process::CommandExt;
24
25    let mut command = std::process::Command::new(program);
26    command.creation_flags(CREATE_NO_WINDOW);
27    command
28}
29
30#[cfg(not(target_os = "windows"))]
31pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
32    std::process::Command::new(program)
33}
34
35#[cfg(target_os = "windows")]
36pub fn get_powershell() -> Option<String> {
37    use std::path::PathBuf;
38
39    fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
40        #[cfg(target_pointer_width = "64")]
41        let env_var = if find_alternate {
42            "ProgramFiles(x86)"
43        } else {
44            "ProgramFiles"
45        };
46
47        #[cfg(target_pointer_width = "32")]
48        let env_var = if find_alternate {
49            "ProgramW6432"
50        } else {
51            "ProgramFiles"
52        };
53
54        let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
55        install_base_dir
56            .read_dir()
57            .ok()?
58            .filter_map(Result::ok)
59            .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
60            .filter_map(|entry| {
61                let dir_name = entry.file_name();
62                let dir_name = dir_name.to_string_lossy();
63
64                let version = if find_preview {
65                    let dash_index = dir_name.find('-')?;
66                    if &dir_name[dash_index + 1..] != "preview" {
67                        return None;
68                    };
69                    dir_name[..dash_index].parse::<u32>().ok()?
70                } else {
71                    dir_name.parse::<u32>().ok()?
72                };
73
74                let exe_path = entry.path().join("pwsh.exe");
75                if exe_path.is_file() {
76                    Some((version, exe_path))
77                } else {
78                    None
79                }
80            })
81            .max_by_key(|(version, _)| *version)
82            .map(|(_, path)| path)
83    }
84
85    fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
86        let msix_app_dir =
87            PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
88        let package_family_name = if find_preview {
89            "Microsoft.PowerShellPreview_8wekyb3d8bbwe"
90        } else {
91            "Microsoft.PowerShell_8wekyb3d8bbwe"
92        };
93        let pwsh_exe = msix_app_dir.join(package_family_name).join("pwsh.exe");
94        pwsh_exe.exists().then_some(pwsh_exe)
95    }
96
97    fn find_pwsh_in_scoop() -> Option<PathBuf> {
98        // Scoop can be installed to a custom location; $SCOOP points at the
99        // scoop root in that case and defaults to %USERPROFILE%\scoop otherwise.
100        let scoop_dir = std::env::var_os("SCOOP").map(PathBuf::from).or_else(|| {
101            std::env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("scoop"))
102        })?;
103        let pwsh_exe = scoop_dir.join("shims").join("pwsh.exe");
104        pwsh_exe.is_file().then_some(pwsh_exe)
105    }
106
107    fn find_pwsh_in_dotnet_tools() -> Option<PathBuf> {
108        let pwsh_exe =
109            PathBuf::from(std::env::var_os("USERPROFILE")?).join(".dotnet\\tools\\pwsh.exe");
110        pwsh_exe.is_file().then_some(pwsh_exe)
111    }
112
113    fn find_windows_powershell() -> Option<PathBuf> {
114        let system_root = PathBuf::from(std::env::var_os("SystemRoot")?);
115        let powershell = system_root.join("System32\\WindowsPowerShell\\v1.0\\powershell.exe");
116        powershell.is_file().then_some(powershell)
117    }
118
119    static POWERSHELL: std::sync::LazyLock<Option<String>> = std::sync::LazyLock::new(|| {
120        let locations = [
121            || find_pwsh_in_programfiles(false, false),
122            || find_pwsh_in_programfiles(true, false),
123            || find_pwsh_in_msix(false),
124            || find_pwsh_in_programfiles(false, true),
125            || find_pwsh_in_msix(true),
126            || find_pwsh_in_programfiles(true, true),
127            || find_pwsh_in_scoop(),
128            || find_pwsh_in_dotnet_tools(),
129            || which::which_global("pwsh.exe").ok(),
130            || which::which_global("powershell.exe").ok(),
131            || find_windows_powershell(),
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    });
140
141    (*POWERSHELL).clone()
142}
143
144#[cfg(target_os = "windows")]
145pub fn get_windows_system_shell() -> String {
146    static CMD: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
147        log::warn!("Powershell not found, falling back to `cmd`");
148        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
149        std::path::PathBuf::from(system_root)
150            .join("System32\\cmd.exe")
151            .to_string_lossy()
152            .into_owned()
153    });
154    get_powershell().unwrap_or_else(|| (*CMD).clone())
155}
156
157#[inline]
158pub const fn is_utf8_char_boundary(u8: u8) -> bool {
159    // This is bit magic equivalent to: b < 128 || b >= 192
160    (u8 as i8) >= -0x40
161}
162
163pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
164    let prev = *value;
165    *value += T::from(1);
166    prev
167}
168
169/// The bits of `value` with the sign of zero normalised away.
170///
171/// `PartialEq` for `f32` treats `0.0` and `-0.0` as equal, so a hash built on
172/// `to_bits` has to collapse them as well or equal keys land in different buckets.
173pub fn canonical_float_bits(value: f32) -> u32 {
174    if value == 0.0 {
175        0.0f32.to_bits()
176    } else {
177        value.to_bits()
178    }
179}
180
181pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
182    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
183    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
184        env::var("ZED_MEASUREMENTS")
185            .map(|measurements| measurements == "1" || measurements == "true")
186            .unwrap_or(false)
187    });
188
189    if *zed_measurements {
190        let start = Instant::now();
191        let result = f();
192        let elapsed = start.elapsed();
193        eprintln!("{}: {:?}", label, elapsed);
194        result
195    } else {
196        f()
197    }
198}
199
200#[macro_export]
201macro_rules! debug_panic {
202    ( $($fmt_arg:tt)* ) => {
203        if cfg!(debug_assertions) {
204            panic!( $($fmt_arg)* );
205        } else {
206            let backtrace = std::backtrace::Backtrace::capture();
207            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
208        }
209    };
210}
211
212#[track_caller]
213pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
214    #[cfg(debug_assertions)]
215    if option.is_none() {
216        panic!("Unexpected None");
217    }
218    option
219}
220
221/// Expands to an immediately-invoked function expression. Good for using the ? operator
222/// in functions which do not return an Option or Result.
223///
224/// Accepts a normal block, an async block, or an async move block.
225#[macro_export]
226macro_rules! maybe {
227    ($block:block) => {
228        (|| $block)()
229    };
230    (async $block:block) => {
231        (async || $block)()
232    };
233    (async move $block:block) => {
234        (async move || $block)()
235    };
236}
237pub trait ResultExt<E> {
238    type Ok;
239
240    fn log_err(self) -> Option<Self::Ok>;
241    /// Like [`ResultExt::log_err`], but uses `{:?}` formatting so `anyhow::Error` values emit their
242    /// full backtrace. Reach for this only when a backtrace is genuinely wanted — most call sites
243    /// should stick with `log_err` / `warn_on_err`, whose output is a single chained error message.
244    fn log_err_with_backtrace(self) -> Option<Self::Ok>
245    where
246        E: std::fmt::Debug;
247    /// Assert that this result should never be an error in development or tests.
248    fn debug_assert_ok(self, reason: &str) -> Self;
249    fn warn_on_err(self) -> Option<Self::Ok>;
250    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
251    fn anyhow(self) -> anyhow::Result<Self::Ok>
252    where
253        E: Into<anyhow::Error>;
254}
255
256impl<T, E> ResultExt<E> for Result<T, E>
257where
258    E: std::fmt::Display,
259{
260    type Ok = T;
261
262    #[track_caller]
263    fn log_err(self) -> Option<T> {
264        self.log_with_level(log::Level::Error)
265    }
266
267    #[track_caller]
268    fn log_err_with_backtrace(self) -> Option<T>
269    where
270        E: std::fmt::Debug,
271    {
272        match self {
273            Ok(value) => Some(value),
274            Err(error) => {
275                log_error_with_caller(
276                    *Location::caller(),
277                    format_args!("{:#}", DebugAsDisplay(&error)),
278                    log::Level::Error,
279                );
280                None
281            }
282        }
283    }
284
285    #[track_caller]
286    fn debug_assert_ok(self, reason: &str) -> Self {
287        if let Err(error) = &self {
288            debug_panic!("{reason} - {error:#}");
289        }
290        self
291    }
292
293    #[track_caller]
294    fn warn_on_err(self) -> Option<T> {
295        self.log_with_level(log::Level::Warn)
296    }
297
298    #[track_caller]
299    fn log_with_level(self, level: log::Level) -> Option<T> {
300        match self {
301            Ok(value) => Some(value),
302            Err(error) => {
303                log_error_with_caller(*Location::caller(), format_args!("{error:#}"), level);
304                None
305            }
306        }
307    }
308
309    fn anyhow(self) -> anyhow::Result<T>
310    where
311        E: Into<anyhow::Error>,
312    {
313        self.map_err(Into::into)
314    }
315}
316
317#[inline(never)]
318fn log_error_with_caller(
319    caller: core::panic::Location<'_>,
320    arguments: fmt::Arguments<'_>,
321    level: log::Level,
322) {
323    #[cfg(not(windows))]
324    let file = caller.file();
325    #[cfg(windows)]
326    let file = caller.file().replace('\\', "/");
327    // In this codebase all crates reside in a `crates` directory,
328    // so discard the prefix up to that segment to find the crate name
329    let file = file.split_once("crates/");
330    let target = file.as_ref().and_then(|(_, s)| s.split_once("/src/"));
331
332    let module_path = target.map(|(krate, module)| {
333        if module.starts_with(krate) {
334            module.trim_end_matches(".rs").replace('/', "::")
335        } else {
336            krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::")
337        }
338    });
339    let file = file.map(|(_, file)| format!("crates/{file}"));
340    log::logger().log(
341        &log::Record::builder()
342            .target(module_path.as_deref().unwrap_or(""))
343            .module_path(file.as_deref())
344            .args(arguments)
345            .file(Some(caller.file()))
346            .line(Some(caller.line()))
347            .level(level)
348            .build(),
349    );
350}
351
352#[track_caller]
353pub fn log_err<E: std::fmt::Display>(error: &E) {
354    log_error_with_caller(
355        *Location::caller(),
356        format_args!("{error:#}"),
357        log::Level::Error,
358    );
359}
360
361// Forces `{:?}` formatting through a `Display`-bounded logging helper so `anyhow::Error` emits a
362// backtrace instead of the single-line chained message produced by its `Display`/`{:#}` forms.
363struct DebugAsDisplay<'a, E>(&'a E);
364
365impl<E: std::fmt::Debug> std::fmt::Display for DebugAsDisplay<'_, E> {
366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367        write!(f, "{:?}", self.0)
368    }
369}
370
371pub trait TryFutureExt {
372    fn log_err(self) -> LogErrorFuture<Self>
373    where
374        Self: Sized;
375
376    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
377    where
378        Self: Sized;
379
380    fn warn_on_err(self) -> LogErrorFuture<Self>
381    where
382        Self: Sized;
383    fn unwrap(self) -> UnwrapFuture<Self>
384    where
385        Self: Sized;
386}
387
388/// `{:?}`-formatting companion to [`TryFutureExt`]; emits a backtrace for `anyhow::Error`. Prefer
389/// [`TryFutureExt`] unless a backtrace is genuinely wanted.
390pub trait TryFutureExtBacktrace {
391    fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture<Self>
392    where
393        Self: Sized;
394
395    fn log_tracked_err_with_backtrace(
396        self,
397        location: core::panic::Location<'static>,
398    ) -> LogErrorWithBacktraceFuture<Self>
399    where
400        Self: Sized;
401}
402
403impl<F, T, E> TryFutureExt for F
404where
405    F: Future<Output = Result<T, E>>,
406    E: std::fmt::Display,
407{
408    #[track_caller]
409    fn log_err(self) -> LogErrorFuture<Self>
410    where
411        Self: Sized,
412    {
413        let location = Location::caller();
414        LogErrorFuture(self, log::Level::Error, *location)
415    }
416
417    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
418    where
419        Self: Sized,
420    {
421        LogErrorFuture(self, log::Level::Error, location)
422    }
423
424    #[track_caller]
425    fn warn_on_err(self) -> LogErrorFuture<Self>
426    where
427        Self: Sized,
428    {
429        let location = Location::caller();
430        LogErrorFuture(self, log::Level::Warn, *location)
431    }
432
433    fn unwrap(self) -> UnwrapFuture<Self>
434    where
435        Self: Sized,
436    {
437        UnwrapFuture(self)
438    }
439}
440
441impl<F, T, E> TryFutureExtBacktrace for F
442where
443    F: Future<Output = Result<T, E>>,
444    E: std::fmt::Debug,
445{
446    #[track_caller]
447    fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture<Self>
448    where
449        Self: Sized,
450    {
451        let location = Location::caller();
452        LogErrorWithBacktraceFuture(self, log::Level::Error, *location)
453    }
454
455    fn log_tracked_err_with_backtrace(
456        self,
457        location: core::panic::Location<'static>,
458    ) -> LogErrorWithBacktraceFuture<Self>
459    where
460        Self: Sized,
461    {
462        LogErrorWithBacktraceFuture(self, log::Level::Error, location)
463    }
464}
465
466#[must_use]
467pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
468
469impl<F, T, E> Future for LogErrorFuture<F>
470where
471    F: Future<Output = Result<T, E>>,
472    E: std::fmt::Display,
473{
474    type Output = Option<T>;
475
476    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
477        let level = self.1;
478        let location = self.2;
479        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
480        match inner.poll(cx) {
481            Poll::Ready(output) => Poll::Ready(match output {
482                Ok(output) => Some(output),
483                Err(error) => {
484                    log_error_with_caller(location, format_args!("{error:#}"), level);
485                    None
486                }
487            }),
488            Poll::Pending => Poll::Pending,
489        }
490    }
491}
492
493#[must_use]
494pub struct LogErrorWithBacktraceFuture<F>(F, log::Level, core::panic::Location<'static>);
495
496impl<F, T, E> Future for LogErrorWithBacktraceFuture<F>
497where
498    F: Future<Output = Result<T, E>>,
499    E: std::fmt::Debug,
500{
501    type Output = Option<T>;
502
503    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
504        let level = self.1;
505        let location = self.2;
506        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
507        match inner.poll(cx) {
508            Poll::Ready(output) => Poll::Ready(match output {
509                Ok(output) => Some(output),
510                Err(error) => {
511                    log_error_with_caller(
512                        location,
513                        format_args!("{:#}", DebugAsDisplay(&error)),
514                        level,
515                    );
516                    None
517                }
518            }),
519            Poll::Pending => Poll::Pending,
520        }
521    }
522}
523
524pub struct UnwrapFuture<F>(F);
525
526impl<F, T, E> Future for UnwrapFuture<F>
527where
528    F: Future<Output = Result<T, E>>,
529    E: std::fmt::Debug,
530{
531    type Output = T;
532
533    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
534        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
535        match inner.poll(cx) {
536            Poll::Ready(result) => Poll::Ready(result.unwrap()),
537            Poll::Pending => Poll::Pending,
538        }
539    }
540}
541
542pub struct Deferred<F: FnOnce()>(Option<F>);
543
544impl<F: FnOnce()> Deferred<F> {
545    /// Drop without running the deferred function.
546    pub fn abort(mut self) {
547        self.0.take();
548    }
549}
550
551impl<F: FnOnce()> Drop for Deferred<F> {
552    fn drop(&mut self) {
553        if let Some(f) = self.0.take() {
554            f()
555        }
556    }
557}
558
559/// Run the given function when the returned value is dropped (unless it's cancelled).
560#[must_use]
561pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
562    Deferred(Some(f))
563}
564
565#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
566pub struct TypeIdHashBuilder;
567
568impl std::hash::BuildHasher for TypeIdHashBuilder {
569    type Hasher = TypeIdHasher;
570
571    fn build_hasher(&self) -> Self::Hasher {
572        TypeIdHasher::default()
573    }
574}
575
576#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
577pub struct TypeIdHasher {
578    value: u64,
579}
580
581impl std::hash::Hasher for TypeIdHasher {
582    #[inline]
583    fn write(&mut self, bytes: &[u8]) {
584        // TypeId should only hash its first 8 bytes
585        if let Some(bytes) = bytes.get(..8) {
586            bytes
587                .as_array()
588                .map(|&array| self.value = u64::from_ne_bytes(array))
589                .unwrap_or_else(|| unreachable!("slice was sliced to 8 bytes"));
590        } else {
591            debug_panic!(
592                "expected a 64-bit value, did you use this hasher with something other than a TypeId?"
593            );
594        }
595    }
596
597    #[inline]
598    fn finish(&self) -> u64 {
599        self.value
600    }
601}
602
603#[test]
604fn type_id_hasher() {
605    use core::any::TypeId;
606    use core::hash::{Hash, Hasher};
607    fn verify_hashing_with(type_id: TypeId) {
608        let mut hasher = TypeIdHasher::default();
609        type_id.hash(&mut hasher);
610        assert_ne!(hasher.finish(), 0);
611    }
612    // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
613    verify_hashing_with(TypeId::of::<usize>());
614    verify_hashing_with(TypeId::of::<()>());
615    verify_hashing_with(TypeId::of::<str>());
616    verify_hashing_with(TypeId::of::<&str>());
617    verify_hashing_with(TypeId::of::<Vec<u8>>());
618}
619
620pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
621where
622    F: Fn(&T, &T) -> std::cmp::Ordering,
623{
624    if limit == 0 {
625        items.clear();
626    }
627    if items.len() <= limit {
628        items.sort_by(compare);
629        return;
630    }
631    // When limit is near to items.len() it may be more efficient to sort the whole list and
632    // truncate, rather than always doing selection first as is done below. It's hard to analyze
633    // where the threshold for this should be since the quickselect style algorithm used by
634    // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
635    // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
636    // unsorted input.
637    items.select_nth_unstable_by(limit, compare);
638    items.truncate(limit);
639    items.sort_by(compare);
640}
641
642#[cfg(test)]
643mod logging_tests {
644    use super::{ResultExt, TryFutureExt, TryFutureExtBacktrace};
645    use log::{Level, Log, Metadata, Record};
646    use std::{
647        cell::RefCell,
648        future::ready,
649        pin::pin,
650        task::{Context, Poll, Waker},
651    };
652
653    #[test]
654    fn logging_preserves_diagnostics_and_callers() {
655        log::set_logger(&TestLogger).expect("failed to install test logger");
656        let error = anyhow::anyhow!("root failure")
657            .context("inner context")
658            .context("outer context");
659        let display = "outer context: inner context: root failure";
660        let debug = format!("{error:?}");
661        let line = line!() + 1;
662        assert_eq!(Err::<(), _>(&error).log_err(), None);
663        assert_logged(line, display);
664        let line = line!() + 1;
665        assert_eq!(Err::<(), _>(&error).log_err_with_backtrace(), None);
666        assert_logged(line, &debug);
667        let mut context = Context::from_waker(Waker::noop());
668        let line = line!() + 1;
669        let mut future = pin!(ready(Err::<(), _>(&error)).log_err());
670        assert_eq!(future.as_mut().poll(&mut context), Poll::Ready(None));
671        assert_logged(line, display);
672        let line = line!() + 1;
673        let mut future = pin!(ready(Err::<(), _>(&error)).log_err_with_backtrace());
674        assert_eq!(future.as_mut().poll(&mut context), Poll::Ready(None));
675        assert_logged(line, &debug);
676    }
677
678    thread_local! {
679        static RECORDS: RefCell<Vec<(Option<u32>, String)>> = const { RefCell::new(Vec::new()) };
680    }
681
682    struct TestLogger;
683
684    impl Log for TestLogger {
685        fn enabled(&self, _: &Metadata<'_>) -> bool {
686            true
687        }
688
689        fn log(&self, record: &Record<'_>) {
690            assert_eq!(record.target(), "gpui_util::lib");
691            assert_eq!(record.module_path(), Some("crates/gpui_util/src/lib.rs"));
692            assert_eq!(record.file(), Some(file!()));
693            assert_eq!(record.level(), Level::Error);
694            RECORDS.with_borrow_mut(|records| {
695                records.push((record.line(), record.args().to_string()));
696            });
697        }
698
699        fn flush(&self) {}
700    }
701
702    fn assert_logged(line: u32, message: &str) {
703        assert_eq!(RECORDS.take(), [(Some(line), message.to_owned())]);
704    }
705}