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
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::quote;
use syn::{ItemEnum, ItemStruct, ItemType};

fn get_name(item: &proc_macro2::TokenStream) -> Option<Ident> {
    let ident = if let Ok(ItemStruct { ident, .. }) = syn::parse2(item.clone()) {
        ident
    } else if let Ok(ItemEnum { ident, .. }) = syn::parse2(item.clone()) {
        ident
    } else if let Ok(ItemType { ident, .. }) = syn::parse2(item.clone()) {
        ident
    } else {
        return None;
    };

    Some(ident)
}

#[allow(clippy::too_many_lines)]
fn jamsocket_wasm_impl(item: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
    let name =
        get_name(item).expect("Can only use #[jamsocket_wasm] on a struct, enum, or type alias.");

    quote! {
        #item

        mod _jamsocket_wasm_macro_autogenerated {
            extern crate alloc;

            use super::*;
            use jamsocket_wasm::prelude::{
                MessageRecipient,
                SimpleJamsocketService,
                JamsocketContext,
                ClientId,
            };

            // Instance-global jamsocket service.
            static mut SERVER_STATE: Option<#name> = None;

            #[no_mangle]
            pub static JAMSOCKET_API_VERSION: i32 = 1;

            #[no_mangle]
            pub static JAMSOCKET_API_PROTOCOL: i32 = 0;

            struct GlobalJamsocketContext;

            impl JamsocketContext for GlobalJamsocketContext {
                fn set_timer(&self, ms_delay: u32) {
                    unsafe {
                        ffi::set_timer(ms_delay);
                    }
                }

                fn send_message(&self, recipient: impl Into<MessageRecipient>, message: &str) {
                    unsafe {
                        ffi::send_message(
                            recipient.into().encode_u32(),
                            &message.as_bytes()[0] as *const u8 as u32,
                            message.len() as u32,
                        );
                    }
                }

                fn send_binary(&self, recipient: impl Into<MessageRecipient>, message: &[u8]) {
                    unsafe {
                        ffi::send_binary(
                            recipient.into().encode_u32(),
                            &message[0] as *const u8 as u32,
                            message.len() as u32,
                        );
                    }
                }
            }

            // Functions implemented by the host.
            mod ffi {
                extern "C" {
                    pub fn send_message(client: u32, message: u32, message_len: u32);

                    pub fn send_binary(client: u32, message: u32, message_len: u32);

                    pub fn set_timer(ms_delay: u32);
                }
            }

            // Functions provided to the host.
            #[no_mangle]
            extern "C" fn initialize(room_id_ptr: *const u8, room_id_len: usize) {
                let room_id = unsafe {
                    String::from_utf8(std::slice::from_raw_parts(room_id_ptr, room_id_len).to_vec()).map_err(|e| format!("Error parsing UTF-8 from host {:?}", e)).unwrap()
                };
                let mut c = #name::new(&room_id, &GlobalJamsocketContext);

                unsafe {
                    SERVER_STATE.replace(c);
                }
            }

            #[no_mangle]
            extern "C" fn connect(client_id: ClientId) {
                match unsafe { SERVER_STATE.as_mut() } {
                    Some(st) => SimpleJamsocketService::connect(st, client_id.into(), &GlobalJamsocketContext),
                    None => ()
                }
            }

            #[no_mangle]
            extern "C" fn disconnect(client_id: ClientId) {
                match unsafe { SERVER_STATE.as_mut() } {
                    Some(st) => SimpleJamsocketService::disconnect(st, client_id.into(), &GlobalJamsocketContext),
                    None => ()
                }
            }

            #[no_mangle]
            extern "C" fn timer() {
                match unsafe { SERVER_STATE.as_mut() } {
                    Some(st) => SimpleJamsocketService::timer(st, &GlobalJamsocketContext),
                    None => ()
                }
            }

            #[no_mangle]
            extern "C" fn message(client_id: ClientId, ptr: *const u8, len: usize) {
                unsafe {
                    let string = String::from_utf8(std::slice::from_raw_parts(ptr, len).to_vec()).map_err(|e| format!("Error parsing UTF-8 from host {:?}", e)).unwrap();

                    match SERVER_STATE.as_mut() {
                        Some(st) => SimpleJamsocketService::message(st, client_id.into(), &string, &GlobalJamsocketContext),
                        None => ()
                    }
                }
            }

            #[no_mangle]
            extern "C" fn binary(client_id: ClientId, ptr: *const u8, len: usize) {
                unsafe {
                    let data = std::slice::from_raw_parts(ptr, len);

                    match SERVER_STATE.as_mut() {
                        Some(st) => SimpleJamsocketService::binary(st, client_id.into(), data, &GlobalJamsocketContext),
                        None => ()
                    }
                }
            }

            #[no_mangle]
            pub unsafe extern "C" fn jam_malloc(size: u32) -> *mut u8 {
                let layout = core::alloc::Layout::from_size_align_unchecked(size as usize, 0);
                alloc::alloc::alloc(layout)
            }

            #[no_mangle]
            pub unsafe extern "C" fn jam_free(ptr: *mut u8, size: u32) {
                let layout = core::alloc::Layout::from_size_align_unchecked(size as usize, 0);
                alloc::alloc::dealloc(ptr, layout);
            }
        }
    }
}

/// Exposes a `jamsocket_wasm::SimpleJamsocketService`-implementing trait as a WebAssembly module.
#[proc_macro_attribute]
pub fn jamsocket_wasm(_attr: TokenStream, item: TokenStream) -> TokenStream {
    #[allow(clippy::needless_borrow)]
    jamsocket_wasm_impl(&item.into()).into()
}

#[cfg(test)]
mod test {
    use super::get_name;
    use quote::quote;

    #[test]
    fn test_parse_name() {
        assert_eq!(
            "MyStruct",
            get_name(&quote! {
                struct MyStruct {}
            })
            .unwrap()
            .to_string()
        );

        assert_eq!(
            "AnotherStruct",
            get_name(&quote! {
                struct AnotherStruct;
            })
            .unwrap()
            .to_string()
        );

        assert_eq!(
            "ATupleStruct",
            get_name(&quote! {
                struct ATupleStruct(u32, u32, u32);
            })
            .unwrap()
            .to_string()
        );

        assert_eq!(
            "AnEnum",
            get_name(&quote! {
                enum AnEnum {
                    Option1,
                    Option2(u32),
                }
            })
            .unwrap()
            .to_string()
        );

        assert_eq!(
            "ATypeDecl",
            get_name(&quote! {
                type ATypeDecl = u32;
            })
            .unwrap()
            .to_string()
        );

        assert!(get_name(&quote! {
            impl Foo {}
        })
        .is_none());
    }
}