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
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;
use syn::parse_macro_input;

// *Heavily* inspired by mlua's `lua_module` proc macro.
//
/// Marks the plugin entrypoint.
///
/// # Examples
///
/// ```ignore
/// use nvim_oxi as nvim;
///
/// #[nvim::module]
/// fn foo() -> nvim::Result<()> {
///     Ok(())
/// }
/// ```
#[cfg(feature = "module")]
#[proc_macro_attribute]
pub fn oxi_module(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as syn::ItemFn);

    #[allow(clippy::redundant_clone)]
    let module_name = item.sig.ident.clone();

    let lua_module =
        Ident::new(&format!("luaopen_{module_name}"), Span::call_site());

    let module_body = quote! {
        #item

        #[no_mangle]
        unsafe extern "C" fn #lua_module(
            state: *mut ::nvim_oxi::lua::ffi::lua_State,
        ) -> ::std::ffi::c_int {
            ::nvim_oxi::entrypoint(state, #module_name)
        }
    };

    module_body.into()
}

/// Tests a piece of code inside a Neovim session.
///
/// # Examples
///
/// ```ignore
/// use nvim_oxi::{self as nvim, api};
///
/// #[nvim::test]
/// fn set_get_del_var() {
///     api::set_var("foo", 42).unwrap();
///     assert_eq!(Ok(42), api::get_var("foo"));
///     assert_eq!(Ok(()), api::del_var("foo"));
/// }
/// ```
#[cfg(feature = "test")]
#[proc_macro_attribute]
pub fn oxi_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as syn::ItemFn);

    let syn::ItemFn { sig, block, .. } = item;

    // TODO: here we'd need to append something like the module path of the
    // call site to `test_name` to avoid collisions between equally named tests
    // across different modules. Unfortunately that doesn't seem to be possible
    // yet?
    // See https://www.reddit.com/r/rust/comments/a3fgp6/procmacro_determining_the_callers_module_path/
    let test_name = sig.ident;
    let test_body = block;

    let module_name = Ident::new(&format!("__{test_name}"), Span::call_site());

    quote! {
        #[test]
        fn #test_name() {
            let mut library_filename = String::new();
            library_filename.push_str(::std::env::consts::DLL_PREFIX);
            library_filename.push_str(env!("CARGO_CRATE_NAME"));
            library_filename.push_str(::std::env::consts::DLL_SUFFIX);

            let mut target_filename = String::from("__");
            target_filename.push_str(stringify!(#test_name));

            #[cfg(not(target_os = "macos"))]
            target_filename.push_str(::std::env::consts::DLL_SUFFIX);

            #[cfg(target_os = "macos")]
            target_filename.push_str(".so");

            let manifest_dir = env!("CARGO_MANIFEST_DIR");
            let target_dir = nvim_oxi::__test::get_target_dir(manifest_dir.as_ref()).join("debug");

            let library_filepath = target_dir.join(library_filename);

            if !library_filepath.exists() {
                panic!(
                    "Compiled library not found in '{}'. Please run `cargo \
                     build` before running the tests.",
                    library_filepath.display()
                )
            }

            let target_filepath =
                target_dir.join("oxi-test").join("lua").join(target_filename);

            if !target_filepath.parent().unwrap().exists() {
                if let Err(err) = ::std::fs::create_dir_all(
                    target_filepath.parent().unwrap(),
                ) {
                    // It might happen that another test created the `lua`
                    // directory between the first if and the `create_dir_all`.
                    if !matches!(
                        err.kind(),
                        ::std::io::ErrorKind::AlreadyExists
                    ) {
                        panic!("{}", err)
                    }
                }
            }

            #[cfg(unix)]
            let res = ::std::os::unix::fs::symlink(
                &library_filepath,
                &target_filepath,
            );

            #[cfg(windows)]
            let res = ::std::os::windows::fs::symlink_file(
                &library_filepath,
                &target_filepath,
            );

            if let Err(err) = res {
                if !matches!(err.kind(), ::std::io::ErrorKind::AlreadyExists) {
                    panic!("{}", err)
                }
            }

            let out = ::std::process::Command::new("nvim")
                .args(["-u", "NONE", "--headless"])
                .args(["-c", "set noswapfile"])
                .args([
                    "-c",
                    &format!(
                        "set rtp+={}",
                        target_dir.join("oxi-test").display()
                    ),
                ])
                .args([
                    "-c",
                    &format!("lua require('__{}')", stringify!(#test_name)),
                ])
                .args(["+quit"])
                .output()
                .expect("Couldn't find `nvim` binary in $PATH");

            if out.status.success() {
                return;
            }

            let stderr = String::from_utf8_lossy(&out.stderr);

            if !stderr.is_empty() {
                // Remove the last 2 lines from stderr for a cleaner error msg.
                let stderr = {
                    let lines = stderr.lines().collect::<Vec<_>>();
                    let len = lines.len();
                    lines[..lines.len() - 2].join("\n")
                };

                // The first 31 bytes are `thread '<unnamed>' panicked at `.
                let (_, stderr) = stderr.split_at(31);

                panic!("{}", stderr)
            } else if let Some(code) = out.status.code() {
                panic!("Neovim exited with non-zero exit code: {}", code);
            } else {
                panic!("Neovim segfaulted");
            }
        }

        #[::nvim_oxi::module]
        fn #module_name() -> ::nvim_oxi::Result<()> {
            let result = ::std::panic::catch_unwind(|| {
                #test_body
            });

            ::std::process::exit(match result {
                Ok(_) => 0,

                Err(err) => {
                    eprintln!("{:?}", err);
                    1
                },
            })
        }
    }
    .into()
}