Skip to content

Commit

Permalink
big daddy clippy is now satiated
Browse files Browse the repository at this point in the history
  • Loading branch information
JackCrumpLeys committed Sep 5, 2023
1 parent 1459a07 commit 7a18888
Show file tree
Hide file tree
Showing 9 changed files with 325 additions and 231 deletions.
23 changes: 13 additions & 10 deletions crates/valence_command/src/arg_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub trait CommandArgSet {
fn from_args(args: Vec<String>) -> Self;
}

pub trait CommandArg:Sized {
pub trait CommandArg: Sized {
fn arg_from_string(string: String) -> Result<Self, CommandArgParseError> {
Self::parse_arg(&mut ParseInput::new(string))
}
Expand All @@ -25,7 +25,10 @@ pub struct ParseInput {

impl ParseInput {
pub fn new(input: impl Into<String>) -> Self {
Self { input: input.into(), cursor: 0 }
Self {
input: input.into(),
cursor: 0,
}
}

pub fn set_cursor(&mut self, cursor: usize) {
Expand Down Expand Up @@ -206,8 +209,7 @@ macro_rules! impl_parser_for_number {

let parsed = s.parse::<$type>();

parsed
.map_err(|_| CommandArgParseError::InvalidArgument($name.to_string(), s))
parsed.map_err(|_| CommandArgParseError::InvalidArgument($name.to_string(), s))
}

fn display() -> Parser {
Expand Down Expand Up @@ -376,9 +378,10 @@ pub enum EntitySelectors {
}

impl CommandArg for EntitySelector {
// we want to get either a simple string [`@e`, `@a`, `@p`, `@r`, `<player_name>`] or a full
// selector: [`@e[<selector>]`, `@a[<selector>]`, `@p[<selector>]`, `@r[<selector>]`]
// the selectors can have spaces in them, so we need to be careful
// we want to get either a simple string [`@e`, `@a`, `@p`, `@r`,
// `<player_name>`] or a full selector: [`@e[<selector>]`, `@a[<selector>]`,
// `@p[<selector>]`, `@r[<selector>]`] the selectors can have spaces in
// them, so we need to be careful
fn parse_arg(input: &mut ParseInput) -> Result<Self, CommandArgParseError> {
input.skip_whitespace();
let mut s = String::new();
Expand Down Expand Up @@ -425,9 +428,9 @@ impl CommandArg for EntitySelector {
return Err(CommandArgParseError::InvalidArgLength);
}
_ => {
return Ok(EntitySelector::SimpleSelector(EntitySelectors::SinglePlayer(
String::parse_arg(input)?,
)))
return Ok(EntitySelector::SimpleSelector(
EntitySelectors::SinglePlayer(String::parse_arg(input)?),
))
}
}
}
Expand Down
42 changes: 24 additions & 18 deletions crates/valence_command/src/command_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,29 +67,24 @@
//! │ Argument: <destination:entity> │
//! └────────────────────────────────┘
//! ```
//! If you want a cool graph of your own command graph you can use the display trait on the
//! [CommandGraph] struct. Then you can use a tool like
//! If you want a cool graph of your own command graph you can use the display
//! trait on the [CommandGraph] struct. Then you can use a tool like
//! [Graphviz Online](https://dreampuf.github.io/GraphvizOnline) to look at the graph.
//!
use std::collections::{HashMap};
use std::collections::HashMap;
use std::fmt::{Display, Formatter};



use petgraph::dot::Dot;
use petgraph::prelude::*;
use serde_value::Value;
use valence_server::protocol::packets::play::command_tree_s2c::{
Node, NodeData as PacketNodeData, Parser, StringArg, Suggestion,
};
use valence_server::protocol::packets::play::CommandTreeS2c;
use valence_server::protocol::{VarInt};

use valence_server::protocol::VarInt;

use crate::arg_parser::{CommandArg, ParseInput};
use crate::{CommandRegistry};
use crate::modifier_value::ModifierValue;
use crate::CommandRegistry;

/// This struct is used to store the command graph.(see module level docs for
/// more info)
Expand Down Expand Up @@ -333,6 +328,7 @@ impl From<CommandGraph> for CommandTreeS2c {
///
/// the executables from these commands will both return a `TestCommand` with
/// the value `1`
#[allow(clippy::type_complexity)]
pub struct CommandGraphBuilder<'a, T> {
// We do not own the graph, we just have a mutable reference to it
graph: &'a mut CommandGraph,
Expand All @@ -348,11 +344,15 @@ impl<'a, T> CommandGraphBuilder<'a, T> {
/// # Arguments
/// * registry - the command registry to add the commands to
/// * executables - the map of node indices to executable parser functions
#[allow(clippy::type_complexity)]
pub fn new(
registry: &'a mut CommandRegistry,
executables: &'a mut HashMap<NodeIndex, fn(&mut ParseInput) -> T>,
parsers: &'a mut HashMap<NodeIndex, fn(&mut ParseInput) -> bool>,
modifiers: &'a mut HashMap<NodeIndex, fn(String, &mut HashMap<ModifierValue, ModifierValue>)>,
modifiers: &'a mut HashMap<
NodeIndex,
fn(String, &mut HashMap<ModifierValue, ModifierValue>),
>,
) -> Self {
CommandGraphBuilder {
current_node: registry.graph.root,
Expand Down Expand Up @@ -437,8 +437,12 @@ impl<'a, T> CommandGraphBuilder<'a, T> {
/// let mut executable_map = HashMap::new();
/// let mut parser_map = HashMap::new();
/// let mut modifier_map = HashMap::new();
/// let mut command_graph_builder =
/// CommandGraphBuilder::<TestCommand>::new(&mut command_graph, &mut executable_map, &mut parser_map, &mut modifier_map);
/// let mut command_graph_builder = CommandGraphBuilder::<TestCommand>::new(
/// &mut command_graph,
/// &mut executable_map,
/// &mut parser_map,
/// &mut modifier_map,
/// );
///
/// let simple_command = command_graph_builder
/// .root() // transition to the root node
Expand Down Expand Up @@ -512,7 +516,10 @@ impl<'a, T> CommandGraphBuilder<'a, T> {
/// .literal("command") // add a literal node then transition to it
/// .with_executable(|_| TestCommand);
/// ```
pub fn with_modifier(&mut self, modifier: fn(String, &mut HashMap<ModifierValue, ModifierValue>)) -> &mut Self {
pub fn with_modifier(
&mut self,
modifier: fn(String, &mut HashMap<ModifierValue, ModifierValue>),
) -> &mut Self {
let current_node = &mut self.current_node;

self.modifiers.insert(*current_node, modifier);
Expand Down Expand Up @@ -545,14 +552,13 @@ impl<'a, T> CommandGraphBuilder<'a, T> {
///
/// # Type Parameters
/// * `P` - the parser to use for the current node (must be [CommandArg])
pub fn with_parser<P:CommandArg>(&mut self) -> &mut Self {
pub fn with_parser<P: CommandArg>(&mut self) -> &mut Self {
let graph = &mut self.graph.graph;
let current_node = self.current_node;

let node = graph.node_weight_mut(current_node).unwrap();
self.parsers.insert(current_node,|input| {
P::parse_arg(input).is_ok()
});
self.parsers
.insert(current_node, |input| P::parse_arg(input).is_ok());

let parser = P::display();

Expand Down
6 changes: 5 additions & 1 deletion crates/valence_command/src/command_scopes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,11 @@ impl CommandScopeRegistry {
/// "valence:command:tp"
/// ));
/// ```
pub fn any_grants(&self, scopes: &Vec<impl Into<Scope> + Clone>, other: impl Into<Scope>) -> bool {
pub fn any_grants(
&self,
scopes: &Vec<impl Into<Scope> + Clone>,
other: impl Into<Scope>,
) -> bool {
let other = other.into();

for scope in scopes {
Expand Down
64 changes: 35 additions & 29 deletions crates/valence_command/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,32 @@ use std::marker::PhantomData;
use std::time::Instant;

use bevy_app::{App, Plugin, PostStartup, Update};
use bevy_ecs::change_detection::{Res, ResMut};
use bevy_ecs::change_detection::ResMut;
use bevy_ecs::event::{Event, EventReader, EventWriter};
use bevy_ecs::prelude::{Entity, Resource};
use bevy_ecs::system::Query;

use bevy_ecs::prelude::{Entity, IntoSystemConfigs, Resource};
use petgraph::prelude::NodeIndex;
use petgraph::Graph;
use tracing::trace;

use crate::arg_parser::ParseInput;
use crate::command_graph::{CommandEdgeType, CommandGraphBuilder, CommandNode, NodeData};
use crate::command_scopes::CommandScopes;
use crate::{Command, CommandExecutionEvent, CommandProcessedEvent, CommandRegistry, CommandScopeRegistry};
use crate::command_graph::CommandGraphBuilder;
use crate::modifier_value::ModifierValue;
use crate::{Command, CommandProcessedEvent, CommandRegistry, CommandSystemSet};

impl<T> Plugin for CommandHandler<T>
where
T: Command + Send + Sync + Debug + 'static,
{
fn build(&self, app: &mut App) {
app.add_event::<CommandResultEvent<T>>()
.insert_resource(CommandResource::<T>::new())
.add_systems(
Update,
command_event_system::<T>
.after(CommandSystemSet::Update)
.before(CommandSystemSet::PostUpdate),
)
.add_systems(PostStartup, command_startup_system::<T>);
}
}

pub struct CommandHandler<T>
where
Expand Down Expand Up @@ -63,18 +75,6 @@ where
pub modifiers: HashMap<ModifierValue, ModifierValue>,
}

impl<T> Plugin for CommandHandler<T>
where
T: Command + Send + Sync + Debug + 'static,
{
fn build(&self, app: &mut App) {
app.add_event::<CommandResultEvent<T>>()
.insert_resource(CommandResource::<T>::new())
.add_systems(Update, command_event_system::<T>)
.add_systems(PostStartup, command_startup_system::<T>);
}
}

fn command_startup_system<T>(
mut registry: ResMut<CommandRegistry>,
mut command: ResMut<CommandResource<T>>,
Expand All @@ -84,8 +84,12 @@ fn command_startup_system<T>(
let mut executables = HashMap::new();
let mut parsers = HashMap::new();
let mut modifiers = HashMap::new();
let graph_builder =
&mut CommandGraphBuilder::new(&mut registry, &mut executables, &mut parsers, &mut modifiers);
let graph_builder = &mut CommandGraphBuilder::new(
&mut registry,
&mut executables,
&mut parsers,
&mut modifiers,
);
T::assemble_graph(graph_builder);
command.executables.extend(executables.clone());
registry.parsers.extend(parsers);
Expand All @@ -106,13 +110,15 @@ fn command_event_system<T>(
for command_event in commands_executed.iter() {
if command.executables.contains_key(&command_event.node) {
let timer = Instant::now();
let result = command.executables.get(&command_event.node).unwrap()(&mut ParseInput::new(
&command_event.command,
));
events.send(CommandResultEvent { result, executor: command_event.executor, modifiers: command_event.modifiers.clone() });
let result = command.executables.get(&command_event.node).unwrap()(
&mut ParseInput::new(&command_event.command),
);
events.send(CommandResultEvent {
result,
executor: command_event.executor,
modifiers: command_event.modifiers.clone(),
});
println!("Command took: {:?}", timer.elapsed());
}
}
}


41 changes: 35 additions & 6 deletions crates/valence_command/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ pub mod manager;
mod modifier_value;

use std::collections::{HashMap, HashSet};
use std::fmt::Debug;

use bevy_app::{App, Update};
use bevy_ecs::event::Event;
use bevy_ecs::prelude::{Entity, Resource};
use petgraph::prelude::NodeIndex;
use bevy_ecs::prelude::{Entity, IntoSystemConfigs, Resource, SystemSet};
pub use command_scopes::CommandScopeRegistry;
pub use modifier_value::ModifierValue;
use crate::arg_parser::ParseInput;
use petgraph::prelude::NodeIndex;

use crate::arg_parser::ParseInput;
use crate::command_graph::{CommandGraph, CommandGraphBuilder};
use crate::handler::CommandHandler;

pub trait Command {
fn assemble_graph(graph: &mut CommandGraphBuilder<Self>) where Self: Sized;
fn assemble_graph(graph: &mut CommandGraphBuilder<Self>)
where
Self: Sized;
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Event)]
Expand All @@ -28,7 +34,8 @@ pub struct CommandExecutionEvent {
pub executor: Entity,
}

/// this will only be sent if the command was successfully parsed and an executable was found
/// this will only be sent if the command was successfully parsed and an
/// executable was found
#[derive(Debug, Clone, PartialEq, Eq, Event)]
pub struct CommandProcessedEvent {
/// the command that was executed eg. "teleport @p 0 ~ 0"
Expand All @@ -42,10 +49,32 @@ pub struct CommandProcessedEvent {
pub node: NodeIndex,
}

#[derive(SystemSet, Clone, PartialEq, Eq, Hash, Debug)]
pub enum CommandSystemSet {
Update,
PostUpdate,
}

#[derive(Resource, Default)]
#[allow(clippy::type_complexity)]
pub struct CommandRegistry {
pub graph: CommandGraph,
pub parsers: HashMap<NodeIndex, fn(&mut ParseInput) -> bool>,
pub modifiers: HashMap<NodeIndex, fn(String, &mut HashMap<ModifierValue, ModifierValue>)>,
pub executables: HashSet<NodeIndex>,
}
}

pub trait CommandApp {
fn add_command<T: Command + Send + Sync + Debug + 'static>(&mut self) -> &mut Self;
fn add_command_handlers<M>(&mut self, systems: impl IntoSystemConfigs<M>) -> &mut Self;
}

impl CommandApp for App {
fn add_command<T: Command + Send + Sync + Debug + 'static>(&mut self) -> &mut Self {
self.add_plugins(CommandHandler::<T>::from_command())
}

fn add_command_handlers<M>(&mut self, systems: impl IntoSystemConfigs<M>) -> &mut Self {
self.add_systems(Update, systems.in_set(CommandSystemSet::PostUpdate))
}
}
Loading

0 comments on commit 7a18888

Please sign in to comment.