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
//! Rvs C API
//!
//! Provides a C API for parsing and evaluating random variables.

#![cfg_attr(feature = "cargo-clippy", allow(not_unsafe_ptr_arg_deref))]

use libc::c_char;
use std::ffi::CStr;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;

use rvs;

use crate::context::Context;
use crate::error::Error;
use crate::error::ErrorKind;

type SequenceHandleRaw = u32;
struct SequenceHandle(SequenceHandleRaw);

impl SequenceHandle {
    pub fn to_raw(&self) -> SequenceHandleRaw {
        self.0
    }
}

impl Into<usize> for SequenceHandle {
    fn into(self) -> usize {
        (self.to_raw() - 1) as usize
    }
}

impl From<usize> for SequenceHandle {
    fn from(index: usize) -> SequenceHandle {
        SequenceHandle((index + 1) as u32)
    }
}

/// Allocates and returns a new Context
///
/// The pointer returned is owned by the caller and is freed by a call to `rvs_transform` or
/// `rvs_context_free`.
///
/// # Arguments
///
/// * `search_path` - A colon separated list of paths to search for `import`s.
/// * `seed` - The initial seed for all variable PRNGs.
///
/// # Errors
///
/// An error will be reported if any of the parsed paths do not exist.  If the search path string
/// contains a mix of paths that do and do not exist, none of the paths will be added to the
/// interal search path.
///
/// A valid Context pointer will be returned and will need to be freed by the caller regardless of
/// error or no error.
#[no_mangle]
pub extern "C" fn rvs_context_new(
    search_path: *const c_char,
    seed: u32,
    error: *mut Error,
) -> *mut Context {
    let c_str = unsafe { CStr::from_ptr(search_path) };
    let r_str = c_str.to_str().unwrap();

    let search_path = match rvs::SearchPath::from_string(r_str) {
        Ok(search_path) => search_path,
        Err(e) => {
            if !error.is_null() {
                unsafe { *error = Error::new(ErrorKind::Io(e)) }
            }

            Default::default()
        }
    };

    let seed = rvs::Seed::from_u32(seed);

    Box::into_raw(Box::new(Context::new(search_path, seed)))
}

/// Parses a semicolon delimited string of Rvs statements and/or Rvs files.
///
/// A terminating semicolon is optional.
///
/// # Errors
///
/// Errors are reported via the optional error struct pointer if available.  The following errors
/// types are possible:
///
/// * Parsing errors
/// * IO errors
///
/// # Panics
///
/// If any pointer arguments are null.
///
/// # Examples
///
/// A single Rvs statement:
///
/// "a = 5"
///
/// A single Rvs file:
///
/// "example.rvs"
///
/// An Rvs file and an Rvs statement:
///
/// "example.rvs; a = 5;"
#[no_mangle]
pub extern "C" fn rvs_parse(context: *mut Context, s: *const c_char, error: *mut Error) {
    assert!(!context.is_null());
    assert!(!s.is_null());

    let c_str = unsafe { CStr::from_ptr(s) };
    let r_str = c_str.to_str().unwrap();
    let context = unsafe { &mut *context };

    for entry in r_str.split(';') {
        if !entry.is_empty() {
            let is_file = entry.ends_with(".rvs");

            let parser_string = if is_file {
                let path = Path::new(&entry);

                let path = match context.find_file(path) {
                    Ok(path) => path,
                    Err(e) => {
                        if !error.is_null() {
                            unsafe {
                                *error = Error::new(ErrorKind::Io(e));
                            }
                        }

                        return;
                    }
                };

                let mut file = match File::open(&path) {
                    Err(e) => {
                        if !error.is_null() {
                            unsafe {
                                *error = Error::new(ErrorKind::Io(e));
                            }
                        }

                        return;
                    }
                    Ok(file) => file,
                };

                let mut contents = String::new();
                if let Err(e) = file.read_to_string(&mut contents) {
                    if !error.is_null() {
                        unsafe {
                            *error = Error::new(ErrorKind::Io(e));
                        }
                    }

                    return;
                };

                contents
            } else {
                entry.to_owned() + ";"
            };

            if let Err(e) = context.parse(&parser_string) {
                if !error.is_null() {
                    unsafe { *error = Error::new(From::from(e)) }
                }
            }
        }
    }
}

/// Creates a new Model
///
/// The pointer returned is owned by the caller and is freed by a call to `rvs_model_free`.
#[no_mangle]
pub extern "C" fn rvs_model_new() -> *mut rvs::Model {
    Box::into_raw(Box::new(rvs::Model::new()))
}

/// Transforms an AST into an object model
///
/// # Arguments
///
/// * context - (required) A Context pointer.  Created by `rvs_context_new`.  Freed by `rvs_transform`.
/// * model - (required) A Model pointer.  Created by `rvs_model_new`.  Freed by `rvs_model_free`
/// * error - (optional) An Error pointer.  Used to report any errors that may occur.
///
/// # Errors
///
/// Errors are reported via the optional error struct pointer if available.  The following errors
/// types are possible:
///
/// * Transform errors
#[no_mangle]
pub extern "C" fn rvs_transform(context: *mut Context, model: *mut rvs::Model, error: *mut Error) {
    assert!(!context.is_null());
    assert!(!model.is_null());

    let context_deref = unsafe { &mut *context };
    let mut model = unsafe { &mut *model };

    if let Err(e) = context_deref.transform(&mut model) {
        if !error.is_null() {
            unsafe { *error = Error::new(From::from(e)) }
        }
    }

    unsafe { Box::from_raw(context) };
}

/// Frees a Context previously allocated by `rvs_context_new`
///
/// This is for error scenarios only.  In a non-error scenario, `rvs_transform` is used to free the
/// Context.
#[no_mangle]
pub extern "C" fn rvs_context_free(context: *mut Context) {
    assert!(!context.is_null());
    unsafe {
        Box::from_raw(context);
    }
}

/// Frees a Model previously allocated by `rvs_transform`
#[no_mangle]
pub extern "C" fn rvs_model_free(model: *mut rvs::Model) {
    assert!(!model.is_null());
    unsafe {
        Box::from_raw(model);
    }
}

/// Returns the handle of a variable
///
/// The callee owns the handle.  The handle is valid until `rvs_model_free()` is called.
///
/// # Errors
///
/// * Returns 0 if variable does not exist
///
/// # Panics
///
/// * If any pointer arguments are null
#[no_mangle]
pub extern "C" fn rvs_get(model: *mut rvs::Model, name: *const c_char) -> SequenceHandleRaw {
    assert!(!model.is_null());
    assert!(!name.is_null());

    let name_cstr = unsafe { CStr::from_ptr(name) };
    let name_rstr = name_cstr.to_str().unwrap();

    let model = unsafe { &mut *model };
    if let Some(index) = model.get_variable_index(name_rstr) {
        SequenceHandle::from(index).to_raw()
    } else {
        0
    }
}

/// Returns the next value of a variable via the result pointer
///
/// # Errors
///
/// Returns 0 if handle is invalid.
///
/// # Panics
///
/// * If any pointer arguments are null
/// * If handle doesn't exist
#[no_mangle]
pub extern "C" fn rvs_next(model: *mut rvs::Model, handle: SequenceHandleRaw) -> u32 {
    assert!(!model.is_null());

    let model = unsafe { &mut *model };
    let handle = SequenceHandle(handle);
    match model.get_variable_by_index(handle.into()) {
        Some(variable) => variable.borrow_mut().next(),
        None => 0,
    }
}

/// Returns the previous value of a variable
///
/// # Errors
///
/// * Returns 0 if handle is invalid
/// * Returns 0 if `rvs_next` has not been called
///
/// # Panics
///
/// * If any pointer arguments are null
/// * If handle doesn't exist
#[no_mangle]
pub extern "C" fn rvs_prev(model: *mut rvs::Model, handle: SequenceHandleRaw) -> u32 {
    assert!(!model.is_null());

    let model = unsafe { &mut *model };
    let handle = SequenceHandle(handle);

    match model.get_variable_by_index(handle.into()) {
        Some(variable) => variable.borrow().prev(),
        None => 0,
    }
}

/// Returns the done value of a variable via the result pointer
///
/// # Errors
///
/// * Returns false if handle is invalid
/// * Returns false if `rvs_next` has not been called
///
/// # Panics
///
/// * If any pointer arguments are null
/// * If handle doesn't exist
#[no_mangle]
pub extern "C" fn rvs_done(model: *mut rvs::Model, handle: SequenceHandleRaw) -> bool {
    assert!(!model.is_null());

    let model = unsafe { &mut *model };
    let handle = SequenceHandle(handle);

    match model.get_variable_by_index(handle.into()) {
        Some(variable) => variable.borrow().done(),
        None => false,
    }
}

#[no_mangle]
pub extern "C" fn rvs_write_definitions(
    model: *const rvs::Model,
    s: *const c_char,
    error: *mut Error,
) {
    assert!(!model.is_null());
    assert!(!s.is_null());

    let c_str = unsafe { CStr::from_ptr(s) };
    let r_str = c_str.to_str().unwrap();
    let model = unsafe { &*model };

    let path = Path::new(r_str);

    let mut file = match File::create(&path) {
        Err(e) => {
            if !error.is_null() {
                unsafe {
                    *error = Error::new(ErrorKind::Io(e));
                }
            }

            return;
        }
        Ok(file) => file,
    };

    let variables = format!("{}", model);
    if let Err(e) = file.write_all(variables.as_bytes()) {
        if !error.is_null() {
            unsafe {
                *error = Error::new(ErrorKind::Io(e));
            }

            return;
        }
    }
}