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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::*;

/// Create a new, empty environment parented on global_env()
///
/// Use the Env{} wrapper for more detail.
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     let env = new_env();
///     assert_eq!(env.len(), 0);
/// }
/// ```
pub fn new_env() -> Robj {
    // 14 is a reasonable default.
    new_env_with_capacity(14)
}

/// Create a new, empty environment parented on global_env()
/// with a reserved size.
///
/// This function will guess the hash table size if required.
/// Use the Env{} wrapper for more detail.
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     let env = new_env_with_capacity(5);
///     env.set_local(sym!(a), 1);
///     env.set_local(sym!(b), 2);
///     assert_eq!(env.len(), 2);
/// }
/// ```
pub fn new_env_with_capacity(capacity: usize) -> Robj {
    if capacity <= 5 {
        // Unhashed envirnment
        call!("new.env", FALSE, global_env(), 0).unwrap()
    } else {
        // Hashed environment for larger hashmaps.
        call!("new.env", TRUE, global_env(), capacity as i32 * 2 + 1).unwrap()
    }
}

/// Get a global variable from global_env() and ancestors.
/// If the result is a promise, evaulate the promise.
///
/// See also [global_var()].
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    let iris = global_var(sym!(iris))?;
///    assert_eq!(iris.len(), 5);
/// }
/// ```
pub fn global_var<K: Into<Robj>>(key: K) -> Result<Robj> {
    global_env()
        .find_var(key)
        .ok_or_else(|| Error::NotFound)
        .and_then(|v| v.eval_promise())
}

/// Get a local variable from current_env() and ancestors.
///
/// If the result is a promise, evaulate the promise.
/// The result will come from the calling enviroment
/// of an R function which will enable you to use variables
/// from the caller.
///
/// See also [var!].
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    current_env().set_local(sym!(my_var), 1);
///    assert_eq!(local_var(sym!(my_var))?, r!(1));
/// }
/// ```
pub fn local_var<K: Into<Robj>>(key: K) -> Result<Robj> {
    current_env()
        .find_var(key)
        .ok_or_else(|| Error::NotFound)
        .and_then(|v| v.eval_promise())
}

/// Get a global function from global_env() and ancestors.
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     let ls = global_function(sym!(ls)).ok_or("ls failed")?;
///     assert_eq!(ls.is_function(), true);
/// }
/// ```
pub fn global_function<K: Into<Robj>>(key: K) -> Option<Robj> {
    global_env().find_function(key)
}

/// Find a namespace by name.
///
/// See also [Robj::double_colon].
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    assert_eq!(find_namespace("base").is_some(), true);
///    assert_eq!(find_namespace("stats").is_some(), true);
/// }
/// ```
pub fn find_namespace<K: Into<Robj>>(key: K) -> Option<Robj> {
    let res = single_threaded(|| call!(".getNamespace", key.into()));
    if let Ok(res) = res {
        Some(res)
    } else {
        None
    }
}

/// The current interpreter environment.
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    assert_eq!(current_env(), base_env());
/// }
/// ```
pub fn current_env() -> Robj {
    unsafe { new_owned(R_GetCurrentEnv()) }
}

/// The "global" environment
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     global_env().set_local(sym!(x), "hello");
///     assert_eq!(global_env().local(sym!(x)), Some(r!("hello")));
/// }
/// ```
pub fn global_env() -> Robj {
    unsafe { new_sys(R_GlobalEnv) }
}

/// An empty environment at the root of the environment tree
pub fn empty_env() -> Robj {
    unsafe { new_sys(R_EmptyEnv) }
}

/// The base environment; formerly R_NilValue
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     global_env().set_local(sym!(x), "hello");
///     assert_eq!(base_env().local(sym!(+)), Some(r!(Primitive("+"))));
/// }
/// ```
pub fn base_env() -> Robj {
    unsafe { new_sys(R_BaseEnv) }
}

/// The namespace for base.
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    assert_eq!(base_namespace().parent().ok_or("no parent")?, global_env());
/// }
/// ```
pub fn base_namespace() -> Robj {
    unsafe { new_sys(R_BaseNamespace) }
}

/// For registered namespaces.
///
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    assert_eq!(namespace_registry().is_environment(), true);
/// }
/// ```
pub fn namespace_registry() -> Robj {
    unsafe { new_sys(R_NamespaceRegistry) }
}

/// Current srcref, for debuggers
pub fn srcref() -> Robj {
    unsafe { new_sys(R_Srcref) }
}

/// The nil object
pub fn nil_value() -> Robj {
    unsafe { new_sys(R_NilValue) }
}

/// Unbound marker
pub fn unbound_value() -> Robj {
    unsafe { new_sys(R_UnboundValue) }
}

/// Missing argument marker
pub fn missing_arg() -> Robj {
    unsafe { new_sys(R_MissingArg) }
}

/// "base"
pub fn base_symbol() -> Robj {
    unsafe { new_sys(R_BaseSymbol) }
}

/// "{"
pub fn brace_symbol() -> Robj {
    unsafe { new_sys(R_BraceSymbol) }
}

/// "[["
pub fn bracket_2_symbol() -> Robj {
    unsafe { new_sys(R_Bracket2Symbol) }
}

/// "["
pub fn bracket_symbol() -> Robj {
    unsafe { new_sys(R_BracketSymbol) }
}

/// "class"
pub fn class_symbol() -> Robj {
    unsafe { new_sys(R_ClassSymbol) }
}

/// ".Device"
pub fn device_symbol() -> Robj {
    unsafe { new_sys(R_DeviceSymbol) }
}

/// "dimnames"
pub fn dimnames_symbol() -> Robj {
    unsafe { new_sys(R_DimNamesSymbol) }
}

/// "dim"
pub fn dim_symbol() -> Robj {
    unsafe { new_sys(R_DimSymbol) }
}

/// "$"
pub fn dollar_symbol() -> Robj {
    unsafe { new_sys(R_DollarSymbol) }
}

/// "..."
pub fn dots_symbol() -> Robj {
    unsafe { new_sys(R_DotsSymbol) }
}
//     pub fn drop_symbol() -> Robj { unsafe { new_sys(R_DropSymbol) }}"drop"

/// "::"
pub fn double_colon_symbol() -> Robj {
    unsafe { new_sys(R_DoubleColonSymbol) }
}

/// ".Last.value"
pub fn lastvalue_symbol() -> Robj {
    unsafe { new_sys(R_LastvalueSymbol) }
}
/// "levels"
pub fn levels_symbol() -> Robj {
    unsafe { new_sys(R_LevelsSymbol) }
}
/// "mode"
pub fn mode_symbol() -> Robj {
    unsafe { new_sys(R_ModeSymbol) }
}
/// "na.rm"
pub fn na_rm_symbol() -> Robj {
    unsafe { new_sys(R_NaRmSymbol) }
}
/// "name"
pub fn name_symbol() -> Robj {
    unsafe { new_sys(R_NameSymbol) }
}
/// "names"
pub fn names_symbol() -> Robj {
    unsafe { new_sys(R_NamesSymbol) }
}
/// _NAMESPACE__."
pub fn namespace_env_symbol() -> Robj {
    unsafe { new_sys(R_NamespaceEnvSymbol) }
}
/// "package"
pub fn package_symbol() -> Robj {
    unsafe { new_sys(R_PackageSymbol) }
}
/// "previous"
pub fn previous_symbol() -> Robj {
    unsafe { new_sys(R_PreviousSymbol) }
}
/// "quote"
pub fn quote_symbol() -> Robj {
    unsafe { new_sys(R_QuoteSymbol) }
}
/// "row.names"
pub fn row_names_symbol() -> Robj {
    unsafe { new_sys(R_RowNamesSymbol) }
}
/// ".Random.seed"
pub fn seeds_symbol() -> Robj {
    unsafe { new_sys(R_SeedsSymbol) }
}
/// "sort.list"
pub fn sort_list_symbol() -> Robj {
    unsafe { new_sys(R_SortListSymbol) }
}
/// "source"
pub fn source_symbol() -> Robj {
    unsafe { new_sys(R_SourceSymbol) }
}
/// "spec"
pub fn spec_symbol() -> Robj {
    unsafe { new_sys(R_SpecSymbol) }
}
/// "tsp"
pub fn tsp_symbol() -> Robj {
    unsafe { new_sys(R_TspSymbol) }
}
/// ":::"
pub fn triple_colon_symbol() -> Robj {
    unsafe { new_sys(R_TripleColonSymbol) }
}
/// ".defined"
pub fn dot_defined() -> Robj {
    unsafe { new_sys(R_dot_defined) }
}
/// ".Method"
pub fn dot_method() -> Robj {
    unsafe { new_sys(R_dot_Method) }
}
/// "packageName"
pub fn dot_package_name() -> Robj {
    unsafe { new_sys(R_dot_packageName) }
}

/// ".target"
pub fn dot_target() -> Robj {
    unsafe { new_sys(R_dot_target) }
}

/* fix version issues.
/// ".Generic"
pub fn dot_Generic() -> Robj { unsafe { new_sys(R_dot_Generic) }}
*/

/// NA_STRING as a CHARSXP
pub fn na_string() -> Robj {
    unsafe { new_sys(R_NaString) }
}

/// "" as a CHARSXP
pub fn blank_string() -> Robj {
    unsafe { new_sys(R_BlankString) }
}

/// "" as a STRSXP
pub fn blank_scalar_string() -> Robj {
    unsafe { new_sys(R_BlankScalarString) }
}

/// Special "NA" string that represents null strings.
/// ```
/// use extendr_api::prelude::*;
/// test! {
///     assert!(na_str().as_ptr() != "NA".as_ptr());
///     assert_eq!(na_str(), "NA");
///     assert_eq!("NA".is_na(), false);
///     assert_eq!(na_str().is_na(), true);
/// }
/// ```
pub fn na_str() -> &'static str {
    unsafe { std::str::from_utf8_unchecked(&[b'N', b'A']) }
}

/// Parse a string into an R executable object
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    let expr = parse("1 + 2").unwrap();
///    assert!(expr.is_expr());
/// }
/// ```
pub fn parse(code: &str) -> Result<Robj> {
    single_threaded(|| unsafe {
        use libR_sys::*;
        let mut status = 0_u32;
        let status_ptr = &mut status as *mut u32;
        let codeobj: Robj = code.into();
        let parsed = new_owned(R_ParseVector(codeobj.get(), -1, status_ptr, R_NilValue));
        match status {
            1 => Ok(parsed),
            _ => Err(Error::ParseError {
                code: code.into(),
                status,
            }),
        }
    })
}

/// Parse a string into an R executable object and run it.
/// ```
/// use extendr_api::prelude::*;
/// test! {
///    let res = eval_string("1 + 2").unwrap();
///    assert_eq!(res, r!(3.));
/// }
/// ```
pub fn eval_string(code: &str) -> Result<Robj> {
    single_threaded(|| {
        let expr = parse(code)?;
        let mut res = Robj::from(());
        if let Some(iter) = expr.as_list_iter() {
            for lang in iter {
                res = lang.eval()?
            }
        }
        Ok(res)
    })
}