Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Procedural Macros for Valor #56

Open
wants to merge 2 commits into
base: feat/next_interface/core
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ version = "0.6.0"

[dependencies]
valor-core = {path = "./lib/core"}
valor-proc = {path = "./lib/proc"}

lazy_static = "1.4.0"

Expand Down
19 changes: 19 additions & 0 deletions lib/proc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
edition = "2021"
name = "valor-proc"
version = "0.1.0"

[lib]
proc-macro = true

[dependencies]
proc-macro2 = {version = "1.0.56", default_features = false}
quote = {version = "1.0.27", default_features = false}
syn = {version = "2.0.16", default_features = false}
valor-core = {path = "../core", default_features = false}

[features]
debug = ["std", "valor-core/debug", "syn/extra-traits"]
default = ["syn"]
std = ["valor-core/std"]
syn = ["syn/full", "syn/clone-impls", "syn/parsing", "syn/printing", "syn/proc-macro"]
48 changes: 48 additions & 0 deletions lib/proc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Procedural Macros for Virto

`virto_proc` is a procedural macros library that powers the Virto developer interfaces.

It provides the procedural macros for the Virto crate, including `#[virto::module]`, `#[virto::method]`, and `#[virto::extensions]`.

## Features

- Procedural macros that enable easy definition of Virto modules and methods.
- Convenient extensions attribute for adding custom functionality to your modules and methods.
- Built with `no_std` compatibility in mind, making it suitable for embedded systems and WebAssembly targets.

## Quick Start

```rust
use virto::*;

#[virto::module]
pub mod my_module {
#[virto::method]
#[virto::extensions(http_verb = "GET", http_path = "/")]
pub fn hello_world(_req: &Request) -> Result<Response, ResponseError> {
Response::new("Hello, world!")
}
}
```

This defines a module with a single method that responds to HTTP GET requests at the root path ("/") with the message "Hello, world!".

## Installation

Add the following to your `Cargo.toml`:

```toml
[dependencies]
virto_proc = "0.1.0"
```

<!-- ## Documentation
Visit our [documentation](http://www.example.com/documentation) for detailed instructions on using Virto Proc. -->

## Examples

Check out the `/examples` directory for example usage of Virto Proc.

## License

This project is licensed under the MIT License. See the [LICENSE](../../LICENSE) file for details.
152 changes: 152 additions & 0 deletions lib/proc/src/expand.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
use quote::{quote, ToTokens, TokenStreamExt};

use crate::structs::{MethodData, ModuleData, KV};

impl ToTokens for KV {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.0.as_str().to_tokens(tokens);
quote!(.to_owned()).to_tokens(tokens);

tokens.append(proc_macro2::Punct::new(',', proc_macro2::Spacing::Alone));

self.1.as_str().to_tokens(tokens);
quote!(.to_owned()).to_tokens(tokens);
}
}

impl ToTokens for MethodData {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = &self.name;
let ident = &self.ident;
let extensions = &self.extensions.0;

let method_call = quote! {
|request: &Request| -> Result<Response, ResponseError> {
#ident(request)
}
};

tokens.extend(quote! {
Method {
name: #name.to_owned(),
call: Some(Box::new(#method_call)),
extensions: {
let mut hm = BTreeMap::new();
#(
hm.insert(#extensions);
)*
hm
},
}
});
}
}

impl ToTokens for ModuleData {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = &self.name;
let extensions = &self.extensions.0;
let methods = &self.methods;

tokens.extend(quote! {
Module {
name: #name.to_owned(),
methods: vec![
#(
#methods,
)*
],
extensions: {
let mut hm = BTreeMap::new();
#(
hm.insert(#extensions);
)*
hm
},
}
});
}
}

#[cfg(test)]
mod tests {
use crate::structs::*;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};

#[test]
fn test_method_data_to_tokens() {
let method_tokens: TokenStream = quote! {
#[valor::method("custom_method")]
#[valor::extensions(http_verb = "GET", http_path = "/")]
pub fn example_method(_req: &Request) -> Result<Response, ResponseError> {
unimplemented!()
}
};

let parsed_method = syn::parse2::<MethodData>(method_tokens).unwrap();
let mut method_out: TokenStream = quote!();
parsed_method.to_tokens(&mut method_out);

let expected_out: TokenStream = quote! {
Method {
name: "custom_method".to_owned(),
call: Some(Box::new(|request: &Request| -> Result<Response, ResponseError> {
example_method(request)
})),
extensions: {
let mut hm = BTreeMap::new();
hm.insert("http_verb".to_owned(), "GET".to_owned());
hm.insert("http_path".to_owned(), "/".to_owned());
hm
},
}
};

assert_eq!(method_out.to_string(), expected_out.to_string());
}

#[test]
fn test_module_data_to_tokens() {
let module_tokens: TokenStream = quote! {
#[valor::module]
pub mod test_module {
#[valor::method("custom_method")]
#[valor::extensions(http_verb = "GET", http_path = "/")]
pub fn example_method<'a>(req: &Request<'a>) -> Result<Response, ResponseError> {
unimplemented!()
}
}
};

let parsed_module = syn::parse2::<ModuleData>(module_tokens).unwrap();
let mut module_out: TokenStream = quote!();
parsed_module.to_tokens(&mut module_out);

let expected_out: TokenStream = quote! {
Module {
name: "test_module".to_owned(),
methods: vec![
Method {
name: "custom_method".to_owned(),
call: Some(Box::new(|request: &Request| -> Result<Response, ResponseError> {
example_method(request)
})),
extensions: {
let mut hm = BTreeMap::new();
hm.insert("http_verb".to_owned(), "GET".to_owned());
hm.insert("http_path".to_owned(), "/".to_owned());
hm
},
},
],
extensions: {
let mut hm = BTreeMap::new();
hm
},
}
};

assert_eq!(module_out.to_string(), expected_out.to_string());
}
}
109 changes: 109 additions & 0 deletions lib/proc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
extern crate alloc;

pub(crate) mod expand;
pub(crate) mod parse;
pub(crate) mod structs;

use proc_macro::TokenStream;
use quote::quote;
use structs::ModuleData;

/// The `module` attribute macro for the `valor` crate.
///
/// This macro marks a module to be included in the `valor` runtime.
/// It processes the functions within the module, generating a vector of `Method` structures.
/// Each `Method` represents a function within the module, including its name, the function call as a closure,
/// and any associated extensions defined by `valor::extensions`.
///
/// # Example
/// ```ignore
/// use valor_proc::{module, method, extensions};
/// use valor_core::structures::{Request, Response, ResponseError};
///
/// #[module("a_module")]
/// pub mod a_module {
/// #[method("a_method")]
/// #[extensions(http_verb = "GET", http_path = "/")]
/// pub fn a_method<'a> (request: &Request<'a>) -> Result<Response, ResponseError> {
/// unimplemented!()
/// }
/// }
/// ```
/// In the example above, the `module` macro will generate a `Module` structure for `a_module`
/// and a `Method` for `a_method` with the extensions `http_verb` and `http_path`.
#[proc_macro_attribute]
pub fn module(_attr: TokenStream, item: TokenStream) -> TokenStream {
let mod_item: proc_macro2::TokenStream = item.clone().into();

match syn::parse::<ModuleData>(item) {
Ok(module) => {
let mod_ident = &module.ident;

quote! {
#[cfg(no_std)]
extern crate alloc;
#[cfg(no_std)]
use alloc::{sync::Arc, collections::BTreeMap};

#[cfg(not(no_std))]
use std::{sync::Arc, collections::BTreeMap};

use self::#mod_ident::*;
use valor::{
lazy_static,
structures::{Module, Method}
};

#mod_item

lazy_static! {
static ref MODULE: Arc<Module> = Arc::new(#module);
}

// #[cfg(not(target_arch = "wasm32"))]
// #[ctor::ctor]
// fn init() {
// valor::registry::add_module(&MODULE);
// }

#[cfg(target_arch = "wasm32")]
#[no_mangle]
pub extern "C" fn __valor_export_module() -> (*const u8, usize) {
valor::interop::export_module(Arc::clone(&MODULE))
}

#[cfg(target_arch = "wasm32")]
#[no_mangle]
pub extern "C" fn __valor_make_call<'a>(method_name: &str, request: &str) -> (*const u8, usize) {
valor::interop::make_call(Arc::clone(&MODULE), method_name, request)
}

#[cfg(target_arch = "wasm32")]
fn main () {
valor::interop::handle_command(Arc::clone(&MODULE));
}
}
.into()
}
Err(error) => error.to_compile_error().into(),
}
}

/// The `valor::method` attribute macro is used to mark methods within a
/// `valor::module`. The `module` macro uses this to recognize the methods.
/// This macro currently doesn't perform any transformation or generation of code.
#[proc_macro_attribute]
pub fn method(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Return the input item as is
item
}

/// The `valor::extensions` attribute macro is used to provide metadata for
/// methods within a `valor::module`. The `module` macro uses this to extract the
/// extensions. This macro currently doesn't perform any transformation or generation
/// of code.
#[proc_macro_attribute]
pub fn extensions(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Return the input item as is
item
}
Loading