yaslapi_sys/
lib.rs

1//! # yaslapi-sys
2//! yaslapi-sys is a Rust library that provides raw bindings to the [Yet Another Scripting Language (YASL)](https://github.com/yasl-lang/yasl) API.
3//!
4//! Then run cargo build to build your project.
5//!
6//! ## Usage
7//! Here’s an example of how to use yaslapi-sys in your Rust code:
8//!
9//! ```
10//! use yaslapi_sys::YASL_State;
11//! use std::ffi::CString;
12//!
13//! const SRC: &str = "let x = 5; echo x**x;";
14//! let state: *mut YASL_State = unsafe { yaslapi_sys::YASL_newstate_bb(SRC.as_ptr().cast(), SRC.len()) };
15//! assert!(!state.is_null());
16//! ```
17
18#![allow(
19    clippy::unreadable_literal,
20    improper_ctypes,
21    non_camel_case_types,
22    non_snake_case,
23    non_upper_case_globals
24)]
25include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use std::ffi::CString;
31
32    fn assert_success(r: i32) {
33        assert_eq!(r, YASL_Error_YASL_SUCCESS as i32)
34    }
35
36    #[no_mangle]
37    unsafe extern "C" fn rust_print_internal(_state: *mut YASL_State) -> i32 {
38        println!("This is a test");
39
40        // Return the number of return values pushed to the YASL stack.
41        0
42    }
43
44    #[test]
45    fn test_basic_functionality() {
46        unsafe {
47            // Initialize test script
48            let state = {
49                let test_file = CString::new("test.yasl").unwrap();
50                let state = YASL_newstate(test_file.as_ptr());
51                assert!(!state.is_null());
52                state
53            };
54
55            // Init new variable `answer` with the top of the stack (in this case, the `42` we just pushed)
56            // Push `42` onto the stack
57            YASL_pushint(state, 42);
58
59            let var_name = CString::new("answer").unwrap();
60            YASLX_initglobal(state, var_name.as_ptr());
61
62            YASL_pushcfunction(state, Some(rust_print_internal), 0);
63            let var_name = CString::new("rust_print").unwrap();
64            YASLX_initglobal(state, var_name.as_ptr());
65
66            // Execute `test.yasl`, now that we're done setting everything up
67            assert_success(YASL_execute(state));
68
69            // Clean up
70            assert_success(YASL_delstate(state));
71        }
72    }
73}