gluon-lang / gluon

A static, type inferred and embeddable language written in Rust.
https://gluon-lang.org
MIT License
3.2k stars 145 forks source link

doc: Explain the vm_type attribute better #883

Closed Marwes closed 4 years ago

Marwes commented 4 years ago

@crides does this explain it?

Closes #882

crides commented 4 years ago

Yes, that does clear up the confusion!

If I may go a bit further on the original question, how is registering the type different from including the type inside the module? Does the naming of the type (e.g. example.Either) matter i.e. does it have to be the same path when the type is imported (e.g. if I register the type as example.Either, does the type Either have to be inside the module example)? Thanks!

Marwes commented 4 years ago

If you look at the WindowHandle type in marshalling you can see that register_type is called with the path that vm_type wants.

Marwes commented 4 years ago

bors r+

bors[bot] commented 4 years ago

Build succeeded:

crides commented 4 years ago

So using the WindowHandle example. There are 3 paths in the example:

#[derive(Userdata, Trace, Clone, Debug, VmType)]
#[gluon_userdata(clone)]
// Lets gluon know that the value can be cloned which can be needed when transferring the value between threads
#[gluon(vm_type = "WindowHandle")] //1
struct WindowHandle {
    id: Arc<u64>,
    metadata: Arc<str>,
}

fn load_mod(thread: &gluon::Thread) -> vm::Result<ExternModule> {
    thread.register_type::<WindowHandle>("WindowHandle", &[])?; //2

    let module = record! {
        type WindowHandle => WindowHandle, //3
        create_hwnd => primitive!(2, create_hwnd),
        id => primitive!(1, id),
        metadata => primitive!(1, metadata),
        default_hwnd => create_hwnd(0, "default".into()),
    };

    ExternModule::new(thread, module)
}

The 3 are: 1) the vm_type attribute, 2) the first argument to register_type, and 3) the actual import path for the type (i.e. if I import the module as window, the actual path to the type would be window.WindowHandle). So 1 and 2 have to be the same*. So can 3 be anything? How would 3 be used? Would the actual path to the type be 1& 2 or 3?

*side question: can you point some rust type using the vm_type attribute to some Gluon type, and not register the type?