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

feat(macro): add group macro #267

Open
wants to merge 18 commits into
base: current
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
8 changes: 3 additions & 5 deletions examples/group_testing/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use poise::{serenity_prelude as serenity};
use poise::{serenity_prelude as serenity, Command, CommandGroup};
use std::{env::var, sync::Arc, time::Duration, vec};
// Types used by all command functions
type Error = Box<dyn std::error::Error + Send + Sync>;
Expand All @@ -14,7 +14,7 @@ struct Test {}
impl Test {
// Just a test
#[poise::command(slash_command, prefix_command, rename = "test")]
async fn aaa(ctx: Context<'_>) -> Result<(), Error> {
async fn test_command(ctx: Context<'_>) -> Result<(), Error> {
let name = ctx.author();
ctx.say(format!("Hello, {}", name)).await?;
Ok(())
Expand All @@ -39,13 +39,12 @@ async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {
}
}


#[tokio::main]
async fn main() {
// FrameworkOptions contains all of poise's configuration option in one struct
// Every option can be omitted to use its default value
// println!("{:#?}", Test::commands());
let commands = Test::commands();
let commands: Vec<Command<Data, Error>> = Test::commands();

let options = poise::FrameworkOptions {
commands: commands,
Expand Down Expand Up @@ -120,4 +119,3 @@ async fn main() {

client.unwrap().start().await.unwrap()
}

34 changes: 32 additions & 2 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod util;

use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::spanned::Spanned;

/**
This macro transforms plain functions into poise bot commands.
Expand Down Expand Up @@ -336,6 +337,9 @@ fn group_impl(args: TokenStream, input_item: TokenStream) -> Result<TokenStream,
// collect each ImplItem in a stream
let mut impl_body = proc_macro2::TokenStream::new();

// context type for correct type inference in CommandGroup
let mut ctx_type_with_static: Option<syn::Type> = None;

for item in item_impl.items.iter() {
let mut item_stream = quote!(#item);

Expand All @@ -361,6 +365,26 @@ fn group_impl(args: TokenStream, input_item: TokenStream) -> Result<TokenStream,
sig: f.sig.clone(),
block: Box::new(f.block.clone()),
};

if let None = ctx_type_with_static {
TitaniumBrain marked this conversation as resolved.
Show resolved Hide resolved
let context_type = match function.sig.inputs.first() {
Some(syn::FnArg::Typed(syn::PatType { ty, .. })) => Some(&**ty),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why return Some here just to unwrap it, there isn't a branch that returns None?

_ => {
return Err(syn::Error::new(
function.sig.span(),
"expected a Context parameter",
)
.into())
}
};
// Needed because we're not allowed to have lifetimes in the hacky use case below (in command::mod.rs)
ctx_type_with_static = Some(syn::fold::fold_type(
&mut crate::util::AllLifetimesToStatic,
context_type
.expect("context_type has already been set to Some")
TitaniumBrain marked this conversation as resolved.
Show resolved Hide resolved
.clone(),
));
}
item_stream = command::command(new_args, function)?.into();
}
}
Expand All @@ -371,8 +395,14 @@ fn group_impl(args: TokenStream, input_item: TokenStream) -> Result<TokenStream,
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle ctx_type_with_static being none here?

Ok(quote! {
impl<D, E> ::poise::CommandGroup<D, E> for #name {
fn commands() -> Vec<::poise::Command<D, E>> {
impl ::poise::CommandGroup for #name {
type Data = <#ctx_type_with_static as poise::_GetGenerics>::U;
type Error = <#ctx_type_with_static as poise::_GetGenerics>::E;

fn commands() -> Vec<::poise::Command<
<#ctx_type_with_static as poise::_GetGenerics>::U,
<#ctx_type_with_static as poise::_GetGenerics>::E,
>> {
vec![#(#name::#command_idents()),*]
TitaniumBrain marked this conversation as resolved.
Show resolved Hide resolved
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
/// Trait for a struct with a group of commands.
///
/// You should not implement this yourself, but instead use the `poise::group` macro
pub trait CommandGroup<D, E> {
// /// User data, which is stored and accessible in all command invocations
// type Data;
// /// The error type of your commands
// type Error;
pub trait CommandGroup {
/// User data, which is stored and accessible in all command invocations
type Data;
/// The error type of your commands
type Error;
/// Return a Vec of the `poise::commands` defined in this group
/// Automatically generated by the macro
fn commands() -> Vec<crate::Command<D, E>>;
fn commands() -> Vec<crate::Command<Self::Data, Self::Error>>;
}