From 4e0ecbe7eab072bfc011879a8a05a65154f2eb5a Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Fri, 15 Apr 2022 17:06:09 +0200 Subject: [PATCH] `alloc`: make `vec!` unavailable under `no_global_oom_handling` The `vec!` macro has 3 rules, but two are not usable under `no_global_oom_handling` builds of the standard library (even with a zero size): ```rust let _ = vec![42]; // Error: requires `exchange_malloc` lang_item. let _ = vec![42; 0]; // Error: cannot find function `from_elem`. ``` Thus those two rules should not be available to begin with. The remaining one, with an empty matcher, is just a shorthand for `new()` and may not make as much sense to have alone, since the idea behind `vec!` is to enable `Vec`s to be defined with the same syntax as array expressions. Furthermore, the documentation can be confusing since it shows the other rules. Thus perhaps it is better and simpler to disable `vec!` entirely under `no_global_oom_handling` environments, and let users call `new()` instead: ```rust let _: Vec = vec![]; let _: Vec = Vec::new(); ``` Notwithstanding this, a `try_vec!` macro would be useful, such as the one introduced in https://github.com/rust-lang/rust/pull/95051. If the shorthand for `new()` is deemed worth keeping on its own, then it may be interesting to have a separate `vec!` macro with a single rule and different, simpler documentation. Signed-off-by: Miguel Ojeda --- alloc/src/macros.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/alloc/src/macros.rs b/alloc/src/macros.rs index d3e9e65c3..22c19243e 100644 --- a/alloc/src/macros.rs +++ b/alloc/src/macros.rs @@ -34,7 +34,7 @@ /// be mindful of side effects. /// /// [`Vec`]: crate::vec::Vec -#[cfg(not(test))] +#[cfg(all(not(no_global_oom_handling), not(test)))] #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "vec_macro"] @@ -55,7 +55,7 @@ macro_rules! vec { // required for this macro definition, is not available. Instead use the // `slice::into_vec` function which is only available with cfg(test) // NB see the slice::hack module in slice.rs for more information -#[cfg(test)] +#[cfg(all(not(no_global_oom_handling), test))] macro_rules! vec { () => ( $crate::vec::Vec::new()