Skip to content

Commit

Permalink
Make a bunch of structs non_exhaustive...
Browse files Browse the repository at this point in the history
...and rename AutocompleteChoice.name to label (I think it fits better)
  • Loading branch information
kangalio authored and GnomedDev committed Nov 26, 2023
1 parent 4c21a73 commit 035e035
Show file tree
Hide file tree
Showing 15 changed files with 110 additions and 38 deletions.
15 changes: 6 additions & 9 deletions examples/feature_showcase/autocomplete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,12 @@ async fn autocomplete_number(
_partial: &str,
) -> impl Iterator<Item = poise::AutocompleteChoice<u32>> {
// Dummy choices
[1_u32, 2, 3, 4, 5]
.iter()
.map(|&n| poise::AutocompleteChoice {
name: format!(
"{} (why did discord even give autocomplete choices separate labels)",
n
),
value: n,
})
[1_u32, 2, 3, 4, 5].iter().map(|&n| {
poise::AutocompleteChoice::new_with_value(
format!("{n} (why did discord even give autocomplete choices separate labels)"),
n,
)
})
}

/// Greet a user. Showcasing autocomplete!
Expand Down
3 changes: 2 additions & 1 deletion macros/src/choice_parameter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ pub fn choice_parameter(input: syn::DeriveInput) -> Result<TokenStream, darling:

fn choices() -> Vec<poise::CommandParameterChoice> {
vec![ #( poise::CommandParameterChoice {
__non_exhaustive: (),
name: #names.to_string(),
localizations: std::collections::HashMap::from([
#( (#locales.to_string(), #localized_names.to_string()) ),*
Expand All @@ -111,7 +112,7 @@ pub fn choice_parameter(input: syn::DeriveInput) -> Result<TokenStream, darling:
Ok(Self::#variant_idents)
} else
)* {
Err(poise::InvalidChoice)
Err(poise::InvalidChoice::default())
}
}
}
Expand Down
1 change: 1 addition & 0 deletions macros/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ fn generate_command(mut inv: Invocation) -> Result<proc_macro2::TokenStream, dar
guild: #guild_cooldown.map(std::time::Duration::from_secs),
channel: #channel_cooldown.map(std::time::Duration::from_secs),
member: #member_cooldown.map(std::time::Duration::from_secs),
__non_exhaustive: (),
})),
reuse_response: #reuse_response,
default_member_permissions: #default_member_permissions,
Expand Down
3 changes: 2 additions & 1 deletion macros/src/command/slash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub fn generate_parameters(inv: &Invocation) -> Result<Vec<proc_macro2::TokenStr
.map(|value| poise::AutocompleteChoice::from(value))
// AutocompleteChoice<T> -> serde_json::Value
.map(|choice| poise::serenity_prelude::json::json!({
"name": choice.name,
"name": choice.label,
"value": choice.value,
}))
.collect()
Expand Down Expand Up @@ -118,6 +118,7 @@ pub fn generate_parameters(inv: &Invocation) -> Result<Vec<proc_macro2::TokenStr
type_setter: #type_setter,
choices: #choices,
autocomplete_callback: #autocomplete_callback,
__non_exhaustive: (),
}
},
required,
Expand Down
3 changes: 3 additions & 0 deletions src/builtins/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub struct HelpConfiguration<'a> {
pub show_context_menu_commands: bool,
/// Whether to list context menu commands as well
pub show_subcommands: bool,
#[doc(hidden)]
pub __non_exhaustive: (),
}

impl Default for HelpConfiguration<'_> {
Expand All @@ -23,6 +25,7 @@ impl Default for HelpConfiguration<'_> {
ephemeral: true,
show_context_menu_commands: false,
show_subcommands: false,
__non_exhaustive: (),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/cooldown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub struct CooldownConfig {
pub channel: Option<Duration>,
/// This cooldown operates on a per-member basis
pub member: Option<Duration>,
#[doc(hidden)]
pub __non_exhaustive: (),
}

/// Tracks all types of cooldowns for a single command
Expand Down
1 change: 1 addition & 0 deletions src/dispatch/prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ async fn strip_prefix<'a, U, E>(
serenity_context: ctx,
framework,
data: framework.user_data,
__non_exhaustive: (),
};

if let Some(dynamic_prefix) = framework.options.prefix_options.dynamic_prefix {
Expand Down
10 changes: 6 additions & 4 deletions src/prefix_argument/argument_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ where
msg: &serenity::Message,
) -> Result<(&'a str, usize, T), (Box<dyn std::error::Error + Send + Sync>, Option<String>)>
{
let (args, string) = pop_string(args).map_err(|_| (TooFewArguments.into(), None))?;
let (args, string) =
pop_string(args).map_err(|_| (TooFewArguments::default().into(), None))?;
let object = T::convert(ctx, msg.guild_id, Some(msg.channel_id), &string)
.await
.map_err(|e| (e.into(), Some(string)))?;
Expand Down Expand Up @@ -100,12 +101,13 @@ impl<'a> PopArgumentHack<'a, bool> for &PhantomData<bool> {
msg: &serenity::Message,
) -> Result<(&'a str, usize, bool), (Box<dyn std::error::Error + Send + Sync>, Option<String>)>
{
let (args, string) = pop_string(args).map_err(|_| (TooFewArguments.into(), None))?;
let (args, string) =
pop_string(args).map_err(|_| (TooFewArguments::default().into(), None))?;

let value = match string.to_ascii_lowercase().trim() {
"yes" | "y" | "true" | "t" | "1" | "enable" | "on" => true,
"no" | "n" | "false" | "f" | "0" | "disable" | "off" => false,
_ => return Err((InvalidBool.into(), Some(string))),
_ => return Err((InvalidBool::default().into(), Some(string))),
};

Ok((args.trim_start(), attachment_index, value))
Expand All @@ -127,7 +129,7 @@ impl<'a> PopArgumentHack<'a, serenity::Attachment> for &PhantomData<serenity::At
let attachment = msg
.attachments
.get(attachment_index)
.ok_or_else(|| (MissingAttachment.into(), None))?
.ok_or_else(|| (MissingAttachment::default().into(), None))?
.clone(); // `.clone()` is more clear than `.to_owned()` and is the same.

Ok((args, attachment_index + 1, attachment))
Expand Down
22 changes: 15 additions & 7 deletions src/prefix_argument/code_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
use super::*;

/// Error thrown when parsing a malformed [`CodeBlock`] ([`CodeBlock::pop_from`])
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CodeBlockError;
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct CodeBlockError {
#[doc(hidden)]
pub __non_exhaustive: (),
}
impl std::fmt::Display for CodeBlockError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("couldn't find a valid code block")
Expand All @@ -27,12 +30,14 @@ impl std::error::Error for CodeBlockError {}
/// ```
///
/// Can be used as a command parameter. For more information, see [`Self::pop_from`].
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[derive(Default, Debug, PartialEq, Eq, Clone, Hash)]
pub struct CodeBlock {
/// The text inside the code block
pub code: String,
/// In multiline code blocks, the language code, if present
pub language: Option<String>,
#[doc(hidden)]
pub __non_exhaustive: (),
}

impl std::fmt::Display for CodeBlock {
Expand All @@ -52,7 +57,7 @@ fn pop_from(args: &str) -> Result<(&str, CodeBlock), CodeBlockError> {

let rest;
let mut code_block = if let Some(code_block) = args.strip_prefix("```") {
let code_block_end = code_block.find("```").ok_or(CodeBlockError)?;
let code_block_end = code_block.find("```").ok_or(CodeBlockError::default())?;
rest = &code_block[(code_block_end + 3)..];
let mut code_block = &code_block[..code_block_end];

Expand All @@ -77,23 +82,25 @@ fn pop_from(args: &str) -> Result<(&str, CodeBlock), CodeBlockError> {
CodeBlock {
code: code_block.to_owned(),
language: language.map(|x| x.to_owned()),
__non_exhaustive: (),
}
} else if let Some(code_line) = args.strip_prefix('`') {
let code_line_end = code_line.find('`').ok_or(CodeBlockError)?;
let code_line_end = code_line.find('`').ok_or(CodeBlockError::default())?;
rest = &code_line[(code_line_end + 1)..];
let code_line = &code_line[..code_line_end];

CodeBlock {
code: code_line.to_owned(),
language: None,
__non_exhaustive: (),
}
} else {
return Err(CodeBlockError);
return Err(CodeBlockError::default());
};

// Empty codeblocks like `` are not rendered as codeblocks by Discord
if code_block.code.is_empty() {
Err(CodeBlockError)
Err(CodeBlockError::default())
} else {
// discord likes to insert hair spaces at the end of code blocks sometimes for no reason
code_block.code = code_block.code.trim_end_matches('\u{200a}').to_owned();
Expand Down Expand Up @@ -145,6 +152,7 @@ fn test_pop_code_block() {
CodeBlock {
code: code.into(),
language: language.map(|x| x.into())
__non_exhaustive: (),
}
);
}
Expand Down
4 changes: 2 additions & 2 deletions src/prefix_argument/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ macro_rules! _parse_prefix {
) => {
let input = $args.trim_start();
if input.is_empty() {
$error = ($crate::TooFewArguments.into(), None);
$error = ($crate::TooFewArguments::default().into(), None);
} else {
match <$type as $crate::serenity_prelude::ArgumentConvert>::convert(
$ctx, $msg.guild_id, Some($msg.channel_id), input
Expand Down Expand Up @@ -232,7 +232,7 @@ macro_rules! parse_prefix_args {
let attachment_index = $attachment_index;

let mut error: (Box<dyn std::error::Error + Send + Sync>, Option<String>)
= (Box::new($crate::TooManyArguments) as _, None);
= (Box::new($crate::TooManyArguments { __non_exhaustive: () }) as _, None);

$crate::_parse_prefix!(
ctx msg args attachment_index => [error]
Expand Down
37 changes: 26 additions & 11 deletions src/prefix_argument/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn pop_string(args: &str) -> Result<(&str, String), crate::TooFewArguments> {

let args = args.trim_start();
if args.is_empty() {
return Err(crate::TooFewArguments);
return Err(crate::TooFewArguments::default());
}

let mut output = String::new();
Expand Down Expand Up @@ -60,8 +60,11 @@ fn pop_string(args: &str) -> Result<(&str, String), crate::TooFewArguments> {
}

/// Error thrown if user passes too many arguments to a command
#[derive(Debug)]
pub struct TooManyArguments;
#[derive(Default, Debug)]
pub struct TooManyArguments {
#[doc(hidden)]
pub __non_exhaustive: (),
}
impl std::fmt::Display for TooManyArguments {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Too many arguments were passed")
Expand All @@ -70,8 +73,11 @@ impl std::fmt::Display for TooManyArguments {
impl std::error::Error for TooManyArguments {}

/// Error thrown if user passes too few arguments to a command
#[derive(Debug)]
pub struct TooFewArguments;
#[derive(Default, Debug)]
pub struct TooFewArguments {
#[doc(hidden)]
pub __non_exhaustive: (),
}
impl std::fmt::Display for TooFewArguments {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Too few arguments were passed")
Expand All @@ -80,8 +86,11 @@ impl std::fmt::Display for TooFewArguments {
impl std::error::Error for TooFewArguments {}

/// Error thrown in prefix invocation when there's too few attachments
#[derive(Debug)]
pub struct MissingAttachment;
#[derive(Default, Debug)]
pub struct MissingAttachment {
#[doc(hidden)]
pub __non_exhaustive: (),
}
impl std::fmt::Display for MissingAttachment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("A required attachment is missing")
Expand All @@ -91,8 +100,11 @@ impl std::error::Error for MissingAttachment {}

/// Error thrown when the user enters a string that is not recognized by a
/// ChoiceParameter-derived enum
#[derive(Debug)]
pub struct InvalidChoice;
#[derive(Default, Debug)]
pub struct InvalidChoice {
#[doc(hidden)]
pub __non_exhaustive: (),
}
impl std::fmt::Display for InvalidChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("You entered a non-existent choice")
Expand All @@ -101,8 +113,11 @@ impl std::fmt::Display for InvalidChoice {
impl std::error::Error for InvalidChoice {}

/// Error thrown when the user enters a string that is not recognized as a boolean
#[derive(Debug)]
pub struct InvalidBool;
#[derive(Default, Debug)]
pub struct InvalidBool {
#[doc(hidden)]
pub __non_exhaustive: (),
}
impl std::fmt::Display for InvalidBool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Expected a string like `yes` or `no` for the boolean parameter")
Expand Down
7 changes: 7 additions & 0 deletions src/reply/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub struct CreateReply<'att> {
pub allowed_mentions: Option<serenity::CreateAllowedMentions>,
/// Whether this message is an inline reply.
pub reply: bool,
#[doc(hidden)]
pub __non_exhaustive: (),
}

impl<'att> CreateReply<'att> {
Expand Down Expand Up @@ -107,6 +109,7 @@ impl<'att> CreateReply<'att> {
ephemeral,
allowed_mentions,
reply: _, // can't reply to a message in interactions
__non_exhaustive: (),
} = self;

if let Some(content) = content {
Expand Down Expand Up @@ -142,6 +145,7 @@ impl<'att> CreateReply<'att> {
ephemeral,
allowed_mentions,
reply: _,
__non_exhaustive: (),
} = self;

if let Some(content) = content {
Expand Down Expand Up @@ -174,6 +178,7 @@ impl<'att> CreateReply<'att> {
ephemeral: _, // can't edit ephemerality in retrospect
allowed_mentions,
reply: _,
__non_exhaustive: (),
} = self;

if let Some(content) = content {
Expand Down Expand Up @@ -204,6 +209,7 @@ impl<'att> CreateReply<'att> {
ephemeral: _, // not supported in prefix
allowed_mentions,
reply: _, // can't edit reference message afterwards
__non_exhaustive: (),
} = self;

if let Some(content) = content {
Expand Down Expand Up @@ -243,6 +249,7 @@ impl<'att> CreateReply<'att> {
ephemeral: _, // not supported in prefix
allowed_mentions,
reply,
__non_exhaustive: (),
} = self;

if let Some(content) = content {
Expand Down

0 comments on commit 035e035

Please sign in to comment.