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

//! Main entry point to the Julia api.

use std::io::Read;
use std::ffi::CStr;

use sys::*;
use error::{Result, Error};
use version::Version;
use string::IntoCString;

/// This macro checks for exceptions that might have occurred in the sys::*
/// functions. Should be used after calling any jl_* function that might throw
/// an exception.
#[macro_export]
macro_rules! jl_catch {
    () => {
        jl_catch!(|ex| { ex });
    };
    (|$ex:ident| $body:expr) => {
        jl_catch!(|$ex -> $crate::error::Error::UnhandledException| $crate::error::Error::UnhandledException($body));
    };
    (|$ex:ident -> $t:ty| $body:expr) => {
        #[allow(unused_variables)] // this shouldn't be necessary
        {
            if let Some($ex) = $crate::api::Exception::catch() {
                return Err($body);
            }
        }
    }
}

#[macro_use]
pub mod value;
#[macro_use]
pub mod array;
pub mod function;
pub mod sym;
pub mod module;
pub mod datatype;
pub mod task;
pub mod exception;
pub mod primitive;

pub use self::value::{Value, JlValue};
pub use self::array::{Array, Svec};
pub use self::function::Function;
pub use self::sym::{Symbol, IntoSymbol};
pub use self::module::Module;
pub use self::datatype::Datatype;
pub use self::task::Task;
pub use self::exception::Exception;
pub use self::primitive::*;

/// Blank struct for controlling the Julia garbage collector.
pub struct Gc;

impl Gc {
    /// Enable or disable the garbage collector.
    pub fn enable(&mut self, p: bool) -> Result<()> {
        unsafe {
            jl_gc_enable(p as i32);
        }
        jl_catch!();
        Ok(())
    }

    /// Check to see if gc is enabled.
    pub fn is_enabled(&self) -> bool {
        unsafe { jl_gc_is_enabled() != 0 }
    }

    /// Collect immediately. Set full to true if a full garbage collection
    /// should be issued
    pub fn collect(&mut self, full: bool) -> Result<()> {
        unsafe {
            jl_gc_collect(full as i32);
        }
        jl_catch!();
        Ok(())
    }

    /// Total bytes in use by the gc.
    pub fn total_bytes(&self) -> isize {
        unsafe { jl_gc_total_bytes() as isize }
    }

    pub fn total_hrtime(&self) -> usize {
        unsafe { jl_gc_total_hrtime() as usize }
    }

    pub fn diff_total_bytes(&self) -> isize {
        unsafe { jl_gc_diff_total_bytes() as isize }
    }
}

/// Struct for controlling the Julia runtime.
pub struct Julia {
    main: Module,
    core: Module,
    base: Module,
    top: Module,
    at_exit: Option<i32>,
    gc: Gc,
}

impl Julia {
    /// Assume that Julia was already initialized somewhere else and return a
    /// handle.
    ///
    /// This function is unsafe, because if any Julia operation is called, it
    /// will likely segfault. Also, the 4 jl_* modules might be null.
    ///
    /// ## Panics
    ///
    /// Panics if the Julia runtime was not previously initialized.
    pub unsafe fn new_unchecked() -> Julia {
        if !Julia::is_initialized() {
            panic!("Julia is not initialized");
        }

        let main = Module::new_unchecked(jl_main_module);
        let core = Module::new_unchecked(jl_core_module);
        let base = Module::new_unchecked(jl_base_module);
        let top = Module::new_unchecked(jl_top_module);

        Julia {
            main: main,
            core: core,
            base: base,
            top: top,
            at_exit: None,
            gc: Gc,
        }
    }

    /// Initialize the Julia runtime.
    ///
    /// ## Errors
    ///
    /// Returns Error::JuliaInitialized if Julia is already initialized.
    pub fn new() -> Result<Julia> {
        if Julia::is_initialized() {
            return Err(Error::JuliaInitialized);
        }

        unsafe {
            jl_init();
        }
        jl_catch!();

        let mut jl = unsafe { Julia::new_unchecked() };
        jl.at_exit = Some(0);
        Ok(jl)
    }

    /// Returns the version of currently running Julia runtime.
    pub fn version(&self) -> Version {
        unsafe {
            let major = jl_ver_major() as u32;
            let minor = jl_ver_minor() as u32;
            let patch = jl_ver_patch() as u32;
            let release = jl_ver_is_release() != 0;
            let branch = jl_git_branch();
            let commit = jl_git_commit();
            let mut branch = CStr::from_ptr(branch).to_str().ok();
            let commit = CStr::from_ptr(commit).to_str().ok();

            if branch == Some("(no branch)") {
                branch = None;
            }

            Version {
                name: "julia",
                major: major,
                minor: minor,
                patch: patch,
                release: release,
                branch: branch,
                commit: commit,
            }
        }
    }

    /// Returns a reference to the garbage collector.
    pub fn gc(&self) -> &Gc {
        &self.gc
    }

    /// Returns a mutable reference to the garbage collector.
    pub fn gc_mut(&mut self) -> &mut Gc {
        &mut self.gc
    }

    /// Checks if Julia was already initialized in the current thread.
    pub fn is_initialized() -> bool {
        unsafe { jl_is_initialized() != 0 }
    }

    /// Sets status to at_exit and consumes Julia, causing the value to be
    /// dropped.
    pub fn exit(mut self, at_exit: i32) {
        self.at_exit(Some(at_exit))
    }

    /// Sets status.
    pub fn at_exit(&mut self, at_exit: Option<i32>) {
        self.at_exit = at_exit;
    }

    /// Returns a handle to the main module.
    pub fn main(&self) -> &Module {
        &self.main
    }

    /// Returns a handle to the core module.
    pub fn core(&self) -> &Module {
        &self.core
    }

    /// Returns a handle to the base module.
    pub fn base(&self) -> &Module {
        &self.base
    }

    /// Returns a handle to the top module.
    pub fn top(&self) -> &Module {
        &self.top
    }

    /// Loads a Julia script from any Read without evaluating it.
    pub fn load<R: Read, S: IntoCString>(&mut self, r: &mut R, name: Option<S>) -> Result<Value> {
        let mut content = String::new();
        let len = r.read_to_string(&mut content)?;
        let content = content.into_cstring();
        let content = content.as_ptr();

        let name = name.map(|s| s.into_cstring()).unwrap_or_else(
            || "string".into_cstring(),
        );
        let name = name.as_ptr();

        //let raw = unsafe { jl_load_file_string(content, len, ptr::null::<i8>() as *mut _) };
        let raw = unsafe { jl_load_file_string(content, len, name as *mut _) };
        jl_catch!();
        Value::new(raw)
    }

    /// Parses and evaluates string.
    pub fn eval_string<S: IntoCString>(&mut self, string: S) -> Result<Value> {
        let string = string.into_cstring();
        let string = string.as_ptr();

        let ret = unsafe { jl_eval_string(string) };
        jl_catch!();
        Value::new(ret).map_err(|_| Error::EvalError)
    }
}

impl Drop for Julia {
    fn drop(&mut self) {
        self.at_exit.map(|s| unsafe { jl_atexit_hook(s) });
    }
}