Hide tokio dependency

Before I tried to use #[::tokio::main] macro for a project template and it worked well... as long as the project template listed tokio as a dependency. (Note the :: prefix.) So I had this at the project template's Cargo configuration:

# do not remove "tokio" dependency
tokio = { version = "1", features = ["full"] }

My library containing the entry point macro, even if it lists tokio as a dependency, the macro won't work if the project template doesn't include tokio as dependency.

The only solution I found is to make tokio lexically available at the macro. The problem with this is that then the user can't use tokio as a customized item at the crate's root module (main.rs). Why? Because if it's not lexically available, the tokio::main proc. macro will fail since it uses the lexical tokio name.

I'm almost satisfied with what I've got now, but I'd appreciate if anyone has any idea.

This is the library macro:

#[doc(hidden)]
pub use tokio as _tokio;

#[macro_export]
macro_rules! initialize {
    ($lambda_exp:expr) => {
        use rialight::_tokio as tokio;

        #[tokio::main]
        async fn main() {
            use std::sync::{Arc};
            use rialight::app::Application;
            include!(concat!(env!("OUT_DIR"), "/rialight_entry.rs"));
            let app = Arc::new(Application {});
            let user_ie: fn(Arc<Application>) -> () = $lambda_exp;
            user_ie(app.clone());
        }
    };
}

The macro provides an option to set the path to the Tokio crate. main in tokio - Rust

1 Like

Here's how I'd do something akin to what @alice suggests as a declarative macro:

#[macro_export]
macro_rules! initialize {
    ($lambda_exp:expr; crate = $c:ident) => {
        #[$c::main]
        async fn main() {
            use std::sync::{Arc};
            use rialight::app::Application;
            include!(concat!(env!("OUT_DIR"), "/rialight_entry.rs"));
            let app = Arc::new(Application {});
            let user_ie: fn(Arc<Application>) -> () = $lambda_exp;
            user_ie(app.clone());
        }
    };
    ($lamda_exp:expr) => {
        initialize!($lamda_exp; crate = rialight::_tokio);
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.