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 macro for routing #19

Open
wants to merge 10 commits into
base: master
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
6 changes: 5 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ before_script:
- cargo install -q cargo-travis || true

script:
- cargo test --all
- if [ "$TRAVIS_RUST_VERSION" = "nightly" ] ; then
cargo test --all --features "nightly";
else
cargo test --all --exclude "shio_macros" --exclude "hello_macros";
fi

after_success:
- cargo coveralls -p shio
Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ lto = true
[workspace]
members = [
"lib/",
"macros/",
"examples/hello",
"examples/json",
"examples/proxy",
Expand All @@ -12,4 +13,5 @@ members = [
"examples/templates_askama",
"examples/postgres",
"examples/managed_state",
"examples/hello_macros",
]
7 changes: 7 additions & 0 deletions examples/hello_macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "hello_macros"
version = "0.0.0"
workspace = "../.."

[dependencies]
shio = { path = "../../lib", features=["nightly"] }
24 changes: 24 additions & 0 deletions examples/hello_macros/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#![feature(proc_macro)]

extern crate shio;

use shio::prelude::*;

// Simple requests should be simple, even in the face of asynchronous design.
#[get("/")]
fn hello_world(_: Context) -> Response {
Response::with("Hello World!\n")
}

#[get("/{name}")]
fn hello(ctx: Context) -> Response {
Response::with(format!("Hello, {}!", &ctx.get::<Parameters>()["name"]))
}

fn main() {
Shio::default()
.route(hello_world)
.route(hello)
.run(":7878")
.unwrap();
}
4 changes: 3 additions & 1 deletion lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ log = "0.3"
unsafe-any = "0.4.2"
http = "0.1"

shio_macros = { path="../macros", optional=true }

[features]
default = []
nightly = []
nightly = ["shio_macros"]
11 changes: 10 additions & 1 deletion lib/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![cfg_attr(feature = "cargo-clippy", warn(clippy, clippy_pedantic))]
#![cfg_attr(feature = "cargo-clippy", allow(missing_docs_in_private_items, stutter))]
#![cfg_attr(feature = "nightly", feature(specialization))]
#![cfg_attr(feature = "nightly", feature(specialization, proc_macro))]

extern crate futures;
extern crate http as http_types;
Expand All @@ -14,6 +14,9 @@ extern crate tokio_core;
extern crate unsafe_any;

pub mod state;
#[cfg(feature = "nightly")]
extern crate shio_macros;

pub mod context;
mod handler;
mod shio;
Expand All @@ -36,6 +39,9 @@ pub use handler::Handler;
pub use data::Data;
pub use errors::Error;

#[cfg(feature = "nightly")]
pub use shio_macros::{get, post};

/// Re-exports important traits and types. Meant to be glob imported when using Shio.
pub mod prelude {
pub use {Context, Request, Response, Shio, http};
Expand All @@ -44,4 +50,7 @@ pub mod prelude {
pub use http::{Method, StatusCode};

pub use futures::{Future, Stream, IntoFuture};

#[cfg(feature = "nightly")]
pub use shio_macros::{get, post};
}
13 changes: 13 additions & 0 deletions macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "shio_macros"
version = "0.1.0"
authors = ["Quentin Laveau <qlaveau@gmail.com>"]
workspace = ".."

[dependencies]
syn = { version="0.11.11", features=["full","parsing","printing"] }
quote="0.3"

[lib]
proc-macro = true

111 changes: 111 additions & 0 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#![feature(proc_macro)]

#[macro_use]
extern crate quote;

extern crate proc_macro;
extern crate syn;

use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn get(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::GET").unwrap(), opts, item)
}

#[proc_macro_attribute]
pub fn post(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::POST").unwrap(), opts, item)
}

#[proc_macro_attribute]
pub fn patch(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::PATCH").unwrap(), opts, item)
}

#[proc_macro_attribute]
pub fn put(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::PUT").unwrap(), opts, item)
}

#[proc_macro_attribute]
pub fn delete(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::DELETE").unwrap(), opts, item)
}

#[proc_macro_attribute]
pub fn options(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::OPTIONS").unwrap(), opts, item)
}

#[proc_macro_attribute]
pub fn head(opts: TokenStream, item: TokenStream) -> TokenStream {
impl_route_rewrite(syn::parse_expr("::shio::http::Method::HEAD").unwrap(), opts, item)
}

fn impl_route_rewrite(meth: syn::Expr, opts: TokenStream, item: TokenStream) -> TokenStream {
let item = item.to_string();
let item = syn::parse_item(&item).expect("unable to parse item associated to get attribute");

match item.node {
syn::ItemKind::Fn(_, _, _, _, _, _) => {}
_ => panic!("get attribute is only for functions"),
}

let opts = opts.to_string();
let opts = syn::parse_token_trees(&opts).expect("unable to parse options of get attribute");
let opts = &opts[0];

let tts = match *opts {
syn::TokenTree::Delimited(ref delim) => &delim.tts,
_ => panic!("unvalid attribute options"),
};
let tt1 = &tts[0];
let tok = match *tt1 {
syn::TokenTree::Token(ref tok) => tok,
_ => panic!("expected a token as first attribute option"),
};
let lit = match *tok {
syn::Token::Literal(ref lit) => lit,
_ => panic!("expected a literal as first attribute option"),
};
match *lit {
syn::Lit::Str(_, _) => {}
_ => panic!("expected a string literal as first attribute option"),
};

Route {
handler: item,
shio_method: meth,
route: lit.clone(),
}.create_new_token_stream()
}

struct Route {
handler: syn::Item,
shio_method: syn::Expr,
route: syn::Lit,
}

impl Route {
fn create_new_token_stream(mut self) -> TokenStream {
let new_ident = syn::Ident::from(format!("__shio_handler_{}", self.handler.ident));
let prev_ident = self.handler.ident.clone();
self.handler.ident = new_ident.clone();

let Route { handler, shio_method, route } = self;

let tokens = quote! {
#handler
#[allow(non_camel_case_types)]
pub struct #prev_ident;
impl Into<::shio::router::Route> for #prev_ident {
fn into(self) -> ::shio::router::Route {
(#shio_method, #route, #new_ident).into()
}
}
};

tokens.parse().unwrap()
}
}