Skip to content

Commit

Permalink
Fix clippy::pedantic warnings (#40)
Browse files Browse the repository at this point in the history
Just some general cleanups
  • Loading branch information
GnomedDev authored Sep 20, 2024
1 parent 68805be commit 6d5c70a
Show file tree
Hide file tree
Showing 13 changed files with 106 additions and 54 deletions.
1 change: 1 addition & 0 deletions src/checks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::types::Context;

#[must_use]
pub fn is_moderator(ctx: Context<'_>) -> bool {
let mod_role_id = ctx.data().mod_role_id;
match ctx {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/crates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ fn format_number(mut n: u64) -> String {
output.insert_str(0, &format!(" {:03}", n % 1000));
n /= 1000;
}
output.insert_str(0, &format!("{}", n));
output.insert_str(0, &format!("{n}"));
output
}

Expand Down Expand Up @@ -161,7 +161,7 @@ pub async fn crate_(
/// Returns whether the given type name is the one of a primitive.
#[rustfmt::skip]
fn is_in_std(name: &str) -> bool {
name.chars().next().map(char::is_uppercase).unwrap_or(false)
name.chars().next().is_some_and(char::is_uppercase)
|| matches!(
name,
"f32" | "f64"
Expand Down
14 changes: 7 additions & 7 deletions src/commands/godbolt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ struct GodboltOutput(Vec<GodboltOutputSegment>);
impl GodboltOutput {
pub fn concatenate(&self) -> String {
let mut complete_text = String::new();
for segment in self.0.iter() {
for segment in &self.0 {
complete_text.push_str(&segment.text);
complete_text.push('\n');
}
Expand Down Expand Up @@ -185,16 +185,16 @@ async fn respond_codeblocks(
("", "") => respond_codeblock(ctx, "", " ", NO_OUTPUT, &godbolt_request).await?,
(output, "") => respond_codeblock(ctx, lang, output, note, &godbolt_request).await?,
("<Compilation failed>", errors) => {
respond_codeblock(ctx, "ansi", errors, "Compilation failed.", &godbolt_request).await?
respond_codeblock(ctx, "ansi", errors, "Compilation failed.", &godbolt_request).await?;
}
("", warnings) => {
respond_codeblock(ctx, "ansi", warnings, NO_OUTPUT, &godbolt_request).await?
respond_codeblock(ctx, "ansi", warnings, NO_OUTPUT, &godbolt_request).await?;
}
(output, errors) => {
ctx.say(
crate::helpers::trim_text(
&format!("```{}\n{}``````ansi\n{}", lang, output, errors),
&format!("\n```{}", note),
&format!("```{lang}\n{output}``````ansi\n{errors}"),
&format!("\n```{note}"),
async {
format!(
"Output too large. Godbolt link: <{}>",
Expand All @@ -219,8 +219,8 @@ async fn respond_codeblock(
) -> Result<(), Error> {
ctx.say(
crate::helpers::trim_text(
&format!("```{}\n{}", codeblock_lang, text),
&format!("\n```{}", note),
&format!("```{codeblock_lang}\n{text}"),
&format!("\n```{note}"),
async {
format!(
"Output too large. Godbolt link: <{}>",
Expand Down
8 changes: 5 additions & 3 deletions src/commands/godbolt/targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,11 @@ async fn update_godbolt_metadata(data: &Data) -> Result<(), Error> {
let update_period = std::env::var("GODBOLT_UPDATE_DURATION")
.ok()
.and_then(|duration| duration.parse::<u64>().ok())
.map(std::time::Duration::from_secs)
// Currently set to 12 hours
.unwrap_or_else(|| std::time::Duration::from_secs(60 * 60 * 12));
.map_or_else(
// Currently set for 12 hours
|| std::time::Duration::from_secs(60 * 60 * 12),
std::time::Duration::from_secs,
);

let time_since_update =
std::time::Instant::now().saturating_duration_since(last_update_time);
Expand Down
11 changes: 9 additions & 2 deletions src/commands/playground/microbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ use anyhow::Error;

use crate::types::Context;

use super::{api::*, util::*};
use super::{
api::{CrateType, Mode, PlayResult, PlaygroundRequest},
util::{
format_play_eval_stderr, generic_help, hoise_crate_attributes, parse_flags, send_reply,
stub_message, GenericHelp,
},
};

const BENCH_FUNCTION: &str = r#"
fn bench(functions: &[(&str, fn())]) {
Expand Down Expand Up @@ -97,7 +103,7 @@ pub async fn microbench(
};
let function_name = user_code[function_name_start..function_name_end].trim();

after_code += &format!("(\"{0}\", {0}), ", function_name);
after_code += &format!("(\"{function_name}\", {function_name}), ");
}
after_code += "]);\n}\n";

Expand Down Expand Up @@ -131,6 +137,7 @@ pub async fn microbench(
send_reply(ctx, result, &code, &flags, &flag_parse_errors).await
}

#[must_use]
pub fn microbench_help() -> String {
generic_help(GenericHelp {
command: "microbench",
Expand Down
15 changes: 14 additions & 1 deletion src/commands/playground/misc_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@ use tracing::warn;

use crate::types::Context;

use super::{api::*, util::*};
use super::{
api::{
apply_online_rustfmt, ClippyRequest, CrateType, MacroExpansionRequest, MiriRequest,
PlayResult,
},
util::{
extract_relevant_lines, generic_help, maybe_wrap, maybe_wrapped, parse_flags, send_reply,
strip_fn_main_boilerplate_from_formatted, stub_message, GenericHelp, ResultHandling,
},
};

/// Run code and detect undefined behavior using Miri
#[poise::command(
Expand Down Expand Up @@ -50,6 +59,7 @@ pub async fn miri(
send_reply(ctx, result, code, &flags, &flag_parse_errors).await
}

#[must_use]
pub fn miri_help() -> String {
generic_help(GenericHelp {
command: "miri",
Expand Down Expand Up @@ -116,6 +126,7 @@ pub async fn expand(
send_reply(ctx, result, &code, &flags, &flag_parse_errors).await
}

#[must_use]
pub fn expand_help() -> String {
generic_help(GenericHelp {
command: "expand",
Expand Down Expand Up @@ -182,6 +193,7 @@ pub async fn clippy(
send_reply(ctx, result, code, &flags, &flag_parse_errors).await
}

#[must_use]
pub fn clippy_help() -> String {
generic_help(GenericHelp {
command: "clippy",
Expand Down Expand Up @@ -220,6 +232,7 @@ pub async fn fmt(
send_reply(ctx, result, code, &flags, &flag_parse_errors).await
}

#[must_use]
pub fn fmt_help() -> String {
generic_help(GenericHelp {
command: "fmt",
Expand Down
11 changes: 10 additions & 1 deletion src/commands/playground/play_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ use anyhow::Error;

use crate::types::Context;

use super::{api::*, util::*};
use super::{
api::{CrateType, PlayResult, PlaygroundRequest},
util::{
format_play_eval_stderr, generic_help, maybe_wrapped, parse_flags, send_reply,
stub_message, GenericHelp, ResultHandling,
},
};

// play and eval work similarly, so this function abstracts over the two
async fn play_or_eval(
Expand Down Expand Up @@ -58,6 +64,7 @@ pub async fn play(
play_or_eval(ctx, flags, false, code, ResultHandling::None).await
}

#[must_use]
pub fn play_help() -> String {
generic_help(GenericHelp {
command: "play",
Expand All @@ -84,6 +91,7 @@ pub async fn playwarn(
play_or_eval(ctx, flags, true, code, ResultHandling::None).await
}

#[must_use]
pub fn playwarn_help() -> String {
generic_help(GenericHelp {
command: "playwarn",
Expand All @@ -110,6 +118,7 @@ pub async fn eval(
play_or_eval(ctx, flags, false, code, ResultHandling::Print).await
}

#[must_use]
pub fn eval_help() -> String {
generic_help(GenericHelp {
command: "eval",
Expand Down
9 changes: 8 additions & 1 deletion src/commands/playground/procmacro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ use anyhow::Error;

use crate::types::Context;

use super::{api::*, util::*};
use super::{
api::{Channel, CrateType, Edition, Mode, PlayResult, PlaygroundRequest},
util::{
format_play_eval_stderr, generic_help, maybe_wrap, parse_flags, send_reply, stub_message,
GenericHelp, ResultHandling,
},
};

/// Compile and use a procedural macro
#[poise::command(
Expand Down Expand Up @@ -94,6 +100,7 @@ fn main() -> std::io::Result<()> {
send_reply(ctx, result, &generated_code, &flags, &flag_parse_errors).await
}

#[must_use]
pub fn procmacro_help() -> String {
generic_help(GenericHelp {
command: "procmacro",
Expand Down
24 changes: 13 additions & 11 deletions src/commands/playground/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,13 @@ pub fn parse_flags(mut args: poise::KeyValueArgs) -> (api::CommandFlags, String)
pop_flag!("run", flags.run);

for (remaining_flag, _) in args.0 {
errors += &format!("unknown flag `{}`\n", remaining_flag);
errors += &format!("unknown flag `{remaining_flag}`\n");
}

(flags, errors)
}

#[derive(Clone, Copy)]
pub struct GenericHelp<'a> {
pub command: &'a str,
pub desc: &'a str,
Expand Down Expand Up @@ -151,6 +152,7 @@ pub fn extract_relevant_lines<'a>(
stderr
}

#[derive(Clone, Copy)]
pub enum ResultHandling {
/// Don't consume results at all, making rustc throw an error when the result isn't ()
None,
Expand Down Expand Up @@ -195,20 +197,20 @@ pub fn hoise_crate_attributes(code: &str, after_crate_attrs: &str, after_code: &
}

/// Utility used by the commands to wrap the given code in a `fn main` if not already wrapped.
/// To check, whether a wrap was done, check if the return type is Cow::Borrowed vs Cow::Owned
/// To check, whether a wrap was done, check if the return type is `Cow::Borrowed` vs `Cow::Owned`
/// If a wrap was done, also hoists crate attributes to the top so they keep working
pub fn maybe_wrap(code: &str, result_handling: ResultHandling) -> Cow<str> {
pub fn maybe_wrap(code: &str, result_handling: ResultHandling) -> Cow<'_, str> {
maybe_wrapped(code, result_handling, false)
}

pub fn maybe_wrapped(code: &str, result_handling: ResultHandling, unsf: bool) -> Cow<str> {
use syn::{parse::Parse, *};
pub fn maybe_wrapped(code: &str, result_handling: ResultHandling, unsf: bool) -> Cow<'_, str> {
use syn::{parse, parse::Parse, parse_str, Attribute, Block, Item, ItemFn, Result, Stmt};

// We use syn to check whether there is a main function.
struct Inline {}

impl Parse for Inline {
fn parse(input: parse::ParseStream) -> Result<Self> {
fn parse(input: parse::ParseStream<'_>) -> Result<Self> {
Attribute::parse_inner(input)?;
let stmts = Block::parse_within(input)?;
for stmt in &stmts {
Expand Down Expand Up @@ -273,7 +275,7 @@ pub async fn send_reply(
// Discord displays empty code blocks weirdly if they're not formatted in a specific style,
// so we special-case empty code blocks
if result.trim().is_empty() {
ctx.say(format!("{}``` ```", flag_parse_errors)).await?;
ctx.say(format!("{flag_parse_errors}``` ```")).await?;
return Ok(());
}

Expand All @@ -286,7 +288,7 @@ pub async fn send_reply(
}

let text = crate::helpers::trim_text(
&format!("{}```rust\n{}", flag_parse_errors, result),
&format!("{flag_parse_errors}```rust\n{result}"),
&text_end,
async {
format!(
Expand Down Expand Up @@ -362,7 +364,7 @@ pub fn strip_fn_main_boilerplate_from_formatted(text: &str) -> String {
/// Split stderr into compiler output and program stderr output and format the two nicely
///
/// If the program doesn't compile, the compiler output is returned. If it did compile and run,
/// compiler output (i.e. warnings) is shown only when show_compiler_warnings is true.
/// compiler output (i.e. warnings) is shown only when `show_compiler_warnings` is true.
pub fn format_play_eval_stderr(stderr: &str, show_compiler_warnings: bool) -> String {
// Extract core compiler output and remove boilerplate lines from top and bottom
let compiler_output = extract_relevant_lines(
Expand Down Expand Up @@ -392,7 +394,7 @@ pub fn format_play_eval_stderr(stderr: &str, show_compiler_warnings: bool) -> St
("", "") => String::new(),
(warnings, "") => warnings.to_owned(),
("", stderr) => stderr.to_owned(),
(warnings, stderr) => format!("{}\n{}", warnings, stderr),
(warnings, stderr) => format!("{warnings}\n{stderr}"),
}
} else {
program_stderr.to_owned()
Expand All @@ -405,7 +407,7 @@ pub fn format_play_eval_stderr(stderr: &str, show_compiler_warnings: bool) -> St
}
}

pub fn stub_message(ctx: Context) -> String {
pub fn stub_message(ctx: Context<'_>) -> String {
let mut stub_message = String::from("_Running code on playground..._\n");

if let Context::Prefix(ctx) = ctx {
Expand Down
15 changes: 6 additions & 9 deletions src/commands/utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub async fn register(ctx: Context<'_>) -> Result<(), Error> {
/// Tells you how long the bot has been up for
#[poise::command(prefix_command, slash_command, category = "Utilities")]
pub async fn uptime(ctx: Context<'_>) -> Result<(), Error> {
let uptime = std::time::Instant::now() - ctx.data().bot_start_time;
let uptime = ctx.data().bot_start_time.elapsed();

let div_mod = |a, b| (a / b, a % b);

Expand All @@ -88,11 +88,8 @@ pub async fn uptime(ctx: Context<'_>) -> Result<(), Error> {
let (hours, minutes) = div_mod(minutes, 60);
let (days, hours) = div_mod(hours, 24);

ctx.say(format!(
"Uptime: {}d {}h {}m {}s",
days, hours, minutes, seconds
))
.await?;
ctx.say(format!("Uptime: {days}d {hours}h {minutes}m {seconds}s"))
.await?;

Ok(())
}
Expand Down Expand Up @@ -121,12 +118,12 @@ pub async fn conradluget(
.decode()
.expect("failed to load image")
});
static FONT: LazyLock<rusttype::Font> = LazyLock::new(|| {
static FONT: LazyLock<rusttype::Font<'_>> = LazyLock::new(|| {
rusttype::Font::try_from_bytes(include_bytes!("../../assets/OpenSans.ttf"))
.expect("failed to load font")
});

let text = format!("Get {}", text);
let text = format!("Get {text}");
let image = imageproc::drawing::draw_text(
&*BASE_IMAGE,
image::Rgba([201, 209, 217, 255]),
Expand Down Expand Up @@ -214,7 +211,7 @@ pub async fn ban(
ctx.say(format!(
"Banned user {} {}",
banned_user.user.name,
crate::helpers::custom_emoji_code(ctx, "ferrisBanne", '🔨').await
crate::helpers::custom_emoji_code(ctx, "ferrisBanne", '🔨')
))
.await?;
Ok(())
Expand Down
Loading

0 comments on commit 6d5c70a

Please sign in to comment.