extendr_api/rmacros.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
//!
//! rmacros - a set of macros to call actual R functions in a rusty way.
//!
/// Convert a rust expression to an R object.
///
/// Shorthand for `Robj::from(x)`.
///
/// Example:
/// ```
/// use extendr_api::prelude::*;
/// test! {
/// let fred = r!(1);
/// assert_eq!(fred, Robj::from(1));
///
/// let int_array = r!([1, 2, 3]);
/// assert_eq!(int_array.len(), 3);
///
/// let numeric_array = r!([1., 2., 3.]);
/// assert_eq!(numeric_array.len(), 3);
///
/// let logical_array = r!([true, false, true]);
/// assert_eq!(logical_array.len(), 3);
///
/// let numeric_array_with_na = r!([Some(1.), None, Some(3.)]);
/// assert_eq!(numeric_array_with_na.len(), 3);
/// }
/// ```
#[macro_export]
macro_rules! r {
($e: expr) => {
extendr_api::Robj::from($e)
};
}
/// Get a local variable from the calling function
/// or a global variable if no such variable exists.
///
/// Variables with embedded "." may not work.
#[macro_export]
macro_rules! var {
($($tokens: tt)*) => {{
local_var(sym!($($tokens)*))
}};
}
/// Get a global variable.
///
/// Variables with embedded "." may not work.
#[macro_export]
macro_rules! global {
($($tokens: tt)*) => {{
global_var(sym!($($tokens)*))
}};
}
/// The sym! macro install symbols.
/// You should cache your symbols in variables
/// as generating them is costly.
/// ```
/// use extendr_api::prelude::*;
/// test! {
///
/// let wombat = sym!(wombat);
/// assert_eq!(wombat, r!(Symbol::from_string("wombat")));
/// }
/// ```
#[macro_export]
macro_rules! sym {
($($tokens: tt)*) => {
Robj::from(Symbol::from_string(stringify!($($tokens)*)))
};
}
/// Create a dataframe.
///
/// Example:
/// ```
/// use extendr_api::prelude::*;
/// test! {
/// let mydata = data_frame!(x=1, y=2);
/// assert_eq!(mydata.inherits("data.frame"), true);
/// //assert_eq!(mydata, r!(List::from_pairs(vec![("x", r!(1)), ("y", r!(2))])).set_class(&["data.frame"])?);
/// }
/// ```
///
/// Panics on error.
#[macro_export]
macro_rules! data_frame {
() => {
call!("data.frame").unwrap()
};
($($rest: tt)*) => {
call!("data.frame", $($rest)*).unwrap()
};
}
/// Create a factor.
///
/// Example:
/// ```
/// use extendr_api::prelude::*;
/// test! {
/// let factor = factor!(vec!["abcd", "def", "fg", "fg"]);
/// assert_eq!(factor.levels().unwrap().collect::<Vec<_>>(), vec!["abcd", "def", "fg"]);
/// assert_eq!(factor.as_integer_vector().unwrap(), vec![1, 2, 3, 3]);
/// assert_eq!(factor.as_str_iter().unwrap().collect::<Vec<_>>(), vec!["abcd", "def", "fg", "fg"]);
/// }
/// ```
///
/// Panics on error.
#[macro_export]
macro_rules! factor {
($($rest: tt)*) => {
call!("factor", $($rest)*).unwrap()
};
}
/// Print via the R output stream.
///
/// Works like [`print!`] but integrates with R and respects
/// redirection with functions like `sink()` and `capture.output()`
#[macro_export]
macro_rules! rprint {
() => {
};
($($rest: tt)*) => {
print_r_output(format!($($rest)*));
};
}
/// Print with a newline via the R output stream.
///
/// Works like [`println!`] but integrates with R and respects
/// redirection with functions like `sink()` and `capture.output()`
#[macro_export]
macro_rules! rprintln {
() => {
print_r_output("\n");
};
($($rest: tt)*) => {
print_r_output(format!($($rest)*));
print_r_output("\n");
};
}
/// Print via the R error stream.
#[macro_export]
macro_rules! reprint {
() => {
};
($($rest: tt)*) => {
print_r_error(format!($($rest)*));
};
}
/// Print with a newline via the R output stream.
#[macro_export]
macro_rules! reprintln {
() => {
print_r_error("\n");
};
($($rest: tt)*) => {
print_r_error(format!($($rest)*));
print_r_error("\n");
};
}
/// Macro for running tests.
///
/// This starts up the underlying [`extendr_engine`] so that interactions with R will work.
/// Additionally, this allows us to use `?` in example code instead of `unwrap()`.
///
/// **Note:** This macro is meant to be used in test code (annotated with
/// `#[cfg(test)]`) or in doc strings. If it is used in library code that
/// gets incorporated into an R package, R CMD check will complain about
/// non-API calls.
///
/// [`extendr_engine`]: https://extendr.github.io/extendr/extendr_engine/
#[macro_export]
macro_rules! test {
() => {
test(|| Ok(()))
};
($($rest: tt)*) => {
{
use extendr_engine;
// this helper function must reside in the macro so it doesn't get compiled
// unless the macro actually gets used (e.g., in testing code)
fn test<F: FnOnce() -> extendr_api::Result<()>>(f: F) {
extendr_engine::start_r();
f().unwrap();
}
test(|| {
$($rest)*
Ok(())
})
}
};
}