From c690e7240514217c189adf870ffcabb594755b04 Mon Sep 17 00:00:00 2001 From: mat Date: Thu, 4 May 2023 20:11:29 -0500 Subject: export brigadier from azalea --- azalea-brigadier/src/command_dispatcher.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index 273b1681..ba41223e 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -8,6 +8,7 @@ use crate::{ }; use std::{cell::RefCell, cmp::Ordering, collections::HashMap, marker::PhantomData, mem, rc::Rc}; +/// The root of the command tree. You need to make this to register commands. #[derive(Default)] pub struct CommandDispatcher { pub root: Rc>>, -- cgit v1.2.3 From 2e2d874e27975721343ee69d20c1f034853111a8 Mon Sep 17 00:00:00 2001 From: mat Date: Thu, 4 May 2023 23:59:24 -0500 Subject: remove unnecessary clones in brigadier --- azalea-brigadier/src/builder/argument_builder.rs | 35 ++++++++---------------- 1 file changed, 11 insertions(+), 24 deletions(-) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/builder/argument_builder.rs b/azalea-brigadier/src/builder/argument_builder.rs index 38ccc98c..cfaff618 100755 --- a/azalea-brigadier/src/builder/argument_builder.rs +++ b/azalea-brigadier/src/builder/argument_builder.rs @@ -25,19 +25,6 @@ pub struct ArgumentBuilder { modifier: Option>>, } -impl Clone for ArgumentBuilder { - fn clone(&self) -> Self { - Self { - arguments: self.arguments.clone(), - command: self.command.clone(), - requirement: self.requirement.clone(), - target: self.target.clone(), - forks: self.forks, - modifier: self.modifier.clone(), - } - } -} - /// A node that isn't yet built. impl ArgumentBuilder { pub fn new(value: ArgumentBuilderType) -> Self { @@ -54,37 +41,37 @@ impl ArgumentBuilder { } } - pub fn then(&mut self, argument: ArgumentBuilder) -> Self { + pub fn then(self, argument: ArgumentBuilder) -> Self { self.then_built(argument.build()) } - pub fn then_built(&mut self, argument: CommandNode) -> Self { + pub fn then_built(mut self, argument: CommandNode) -> Self { self.arguments.add_child(&Rc::new(RefCell::new(argument))); - self.clone() + self } - pub fn executes(&mut self, f: F) -> Self + pub fn executes(mut self, f: F) -> Self where F: Fn(&CommandContext) -> i32 + 'static, { self.command = Some(Rc::new(f)); - self.clone() + self } - pub fn requires(&mut self, requirement: F) -> Self + pub fn requires(mut self, requirement: F) -> Self where F: Fn(Rc) -> bool + 'static, { self.requirement = Rc::new(requirement); - self.clone() + self } - pub fn redirect(&mut self, target: Rc>>) -> Self { + pub fn redirect(self, target: Rc>>) -> Self { self.forward(target, None, false) } pub fn fork( - &mut self, + self, target: Rc>>, modifier: Rc>, ) -> Self { @@ -92,7 +79,7 @@ impl ArgumentBuilder { } pub fn forward( - &mut self, + mut self, target: Rc>>, modifier: Option>>, fork: bool, @@ -103,7 +90,7 @@ impl ArgumentBuilder { self.target = Some(target); self.modifier = modifier; self.forks = fork; - self.clone() + self } pub fn build(self) -> CommandNode { -- cgit v1.2.3 From e4176937f0584a6bcc5aba15abb1e2df6ddf588d Mon Sep 17 00:00:00 2001 From: mat Date: Fri, 5 May 2023 19:37:40 +0000 Subject: remove more unnecessary brigadier cloning! --- azalea-brigadier/src/command_dispatcher.rs | 36 ++++++---------------- .../src/context/command_context_builder.rs | 16 +++++----- azalea-brigadier/src/parse_results.rs | 6 ++-- 3 files changed, 20 insertions(+), 38 deletions(-) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index ba41223e..29fadfd1 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -10,12 +10,12 @@ use std::{cell::RefCell, cmp::Ordering, collections::HashMap, marker::PhantomDat /// The root of the command tree. You need to make this to register commands. #[derive(Default)] -pub struct CommandDispatcher { +pub struct CommandDispatcher<'a, S> { pub root: Rc>>, - _marker: PhantomData, + _marker: PhantomData<(S, &'a ())>, } -impl CommandDispatcher { +impl<'a, S> CommandDispatcher<'a, S> { pub fn new() -> Self { Self { root: Rc::new(RefCell::new(CommandNode::default())), @@ -30,21 +30,16 @@ impl CommandDispatcher { } pub fn parse(&self, command: StringReader, source: Rc) -> ParseResults { - let context = CommandContextBuilder::new( - Rc::new(self.clone()), - source, - self.root.clone(), - command.cursor(), - ); + let context = CommandContextBuilder::new(self, source, self.root.clone(), command.cursor()); self.parse_nodes(&self.root, &command, context).unwrap() } fn parse_nodes( - &self, + &'a self, node: &Rc>>, original_reader: &StringReader, - context_so_far: CommandContextBuilder, - ) -> Result, CommandSyntaxException> { + context_so_far: CommandContextBuilder<'a, S>, + ) -> Result, CommandSyntaxException> { let source = context_so_far.source.clone(); let mut errors = HashMap::>, CommandSyntaxException>::new(); let mut potentials: Vec> = vec![]; @@ -91,12 +86,8 @@ impl CommandDispatcher { }) { reader.skip(); if let Some(redirect) = &child.borrow().redirect { - let child_context = CommandContextBuilder::new( - Rc::new(self.clone()), - source, - redirect.clone(), - reader.cursor, - ); + let child_context = + CommandContextBuilder::new(self, source, redirect.clone(), reader.cursor); let parse = self .parse_nodes(redirect, &reader, child_context) .expect("Parsing nodes failed"); @@ -287,12 +278,3 @@ impl CommandDispatcher { // Ok(if forked { successful_forks } else { result }) } } - -impl Clone for CommandDispatcher { - fn clone(&self) -> Self { - Self { - root: self.root.clone(), - _marker: PhantomData, - } - } -} diff --git a/azalea-brigadier/src/context/command_context_builder.rs b/azalea-brigadier/src/context/command_context_builder.rs index 7516ab9e..b0677158 100755 --- a/azalea-brigadier/src/context/command_context_builder.rs +++ b/azalea-brigadier/src/context/command_context_builder.rs @@ -9,20 +9,20 @@ use crate::{ }; use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc}; -pub struct CommandContextBuilder { +pub struct CommandContextBuilder<'a, S> { pub arguments: HashMap, pub root: Rc>>, pub nodes: Vec>, - pub dispatcher: Rc>, + pub dispatcher: &'a CommandDispatcher<'a, S>, pub source: Rc, pub command: Command, - pub child: Option>>, + pub child: Option>>, pub range: StringRange, pub modifier: Option>>, pub forks: bool, } -impl Clone for CommandContextBuilder { +impl Clone for CommandContextBuilder<'_, S> { fn clone(&self) -> Self { Self { arguments: self.arguments.clone(), @@ -39,9 +39,9 @@ impl Clone for CommandContextBuilder { } } -impl CommandContextBuilder { +impl<'a, S> CommandContextBuilder<'a, S> { pub fn new( - dispatcher: Rc>, + dispatcher: &'a CommandDispatcher, source: Rc, root_node: Rc>>, start: usize, @@ -64,7 +64,7 @@ impl CommandContextBuilder { self.command = command.clone(); self } - pub fn with_child(&mut self, child: Rc>) -> &Self { + pub fn with_child(&mut self, child: Rc>) -> &Self { self.child = Some(child); self } @@ -99,7 +99,7 @@ impl CommandContextBuilder { } } -impl Debug for CommandContextBuilder { +impl Debug for CommandContextBuilder<'_, S> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CommandContextBuilder") // .field("arguments", &self.arguments) diff --git a/azalea-brigadier/src/parse_results.rs b/azalea-brigadier/src/parse_results.rs index 3698ae82..aa7d79ea 100755 --- a/azalea-brigadier/src/parse_results.rs +++ b/azalea-brigadier/src/parse_results.rs @@ -4,13 +4,13 @@ use crate::{ }; use std::{collections::HashMap, fmt::Debug, rc::Rc}; -pub struct ParseResults { - pub context: CommandContextBuilder, +pub struct ParseResults<'a, S> { + pub context: CommandContextBuilder<'a, S>, pub reader: StringReader, pub exceptions: HashMap>, CommandSyntaxException>, } -impl Debug for ParseResults { +impl Debug for ParseResults<'_, S> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ParseResults") .field("context", &self.context) -- cgit v1.2.3 From 12370ab07609bf78baef4ec2302fa4ba44317dae Mon Sep 17 00:00:00 2001 From: mat Date: Fri, 5 May 2023 23:09:57 -0500 Subject: change some things to be Arc+RwLock in brigadier --- Cargo.lock | 1 + azalea-brigadier/Cargo.toml | 1 + azalea-brigadier/src/builder/argument_builder.rs | 14 +++-- azalea-brigadier/src/command_dispatcher.rs | 68 +++++++++++----------- azalea-brigadier/src/context/command_context.rs | 6 +- .../src/context/command_context_builder.rs | 18 +++--- .../src/context/parsed_command_node.rs | 6 +- azalea-brigadier/src/tree/mod.rs | 47 +++++++++------ .../tests/builder/argument_builder_test.rs | 13 +++-- azalea-brigadier/tests/command_dispatcher_test.rs | 25 ++++---- 10 files changed, 111 insertions(+), 88 deletions(-) (limited to 'azalea-brigadier/src') diff --git a/Cargo.lock b/Cargo.lock index cb1098cc..dcf982f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,6 +233,7 @@ version = "0.6.0" dependencies = [ "azalea-buf", "azalea-chat", + "parking_lot", ] [[package]] diff --git a/azalea-brigadier/Cargo.toml b/azalea-brigadier/Cargo.toml index 254ccc83..a1f5966b 100644 --- a/azalea-brigadier/Cargo.toml +++ b/azalea-brigadier/Cargo.toml @@ -11,6 +11,7 @@ version = "0.6.0" [dependencies] azalea-buf = {path = "../azalea-buf", version = "^0.6.0", optional = true} azalea-chat = {path = "../azalea-chat", version = "^0.6.0", optional = true} +parking_lot = "0.12.1" [features] azalea-buf = ["dep:azalea-buf", "dep:azalea-chat"] diff --git a/azalea-brigadier/src/builder/argument_builder.rs b/azalea-brigadier/src/builder/argument_builder.rs index cfaff618..a1f3d6ae 100755 --- a/azalea-brigadier/src/builder/argument_builder.rs +++ b/azalea-brigadier/src/builder/argument_builder.rs @@ -1,3 +1,5 @@ +use parking_lot::RwLock; + use crate::{ context::CommandContext, modifier::RedirectModifier, @@ -5,7 +7,7 @@ use crate::{ }; use super::{literal_argument_builder::Literal, required_argument_builder::Argument}; -use std::{cell::RefCell, fmt::Debug, rc::Rc}; +use std::{fmt::Debug, rc::Rc, sync::Arc}; #[derive(Debug, Clone)] pub enum ArgumentBuilderType { @@ -19,7 +21,7 @@ pub struct ArgumentBuilder { command: Command, requirement: Rc) -> bool>, - target: Option>>>, + target: Option>>>, forks: bool, modifier: Option>>, @@ -46,7 +48,7 @@ impl ArgumentBuilder { } pub fn then_built(mut self, argument: CommandNode) -> Self { - self.arguments.add_child(&Rc::new(RefCell::new(argument))); + self.arguments.add_child(&Arc::new(RwLock::new(argument))); self } @@ -66,13 +68,13 @@ impl ArgumentBuilder { self } - pub fn redirect(self, target: Rc>>) -> Self { + pub fn redirect(self, target: Arc>>) -> Self { self.forward(target, None, false) } pub fn fork( self, - target: Rc>>, + target: Arc>>, modifier: Rc>, ) -> Self { self.forward(target, Some(modifier), true) @@ -80,7 +82,7 @@ impl ArgumentBuilder { pub fn forward( mut self, - target: Rc>>, + target: Arc>>, modifier: Option>>, fork: bool, ) -> Self { diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index 29fadfd1..0d84171e 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -1,3 +1,5 @@ +use parking_lot::RwLock; + use crate::{ builder::argument_builder::ArgumentBuilder, context::{CommandContext, CommandContextBuilder}, @@ -6,26 +8,27 @@ use crate::{ string_reader::StringReader, tree::CommandNode, }; -use std::{cell::RefCell, cmp::Ordering, collections::HashMap, marker::PhantomData, mem, rc::Rc}; +use std::{cmp::Ordering, collections::HashMap, mem, rc::Rc, sync::Arc}; /// The root of the command tree. You need to make this to register commands. #[derive(Default)] -pub struct CommandDispatcher<'a, S> { - pub root: Rc>>, - _marker: PhantomData<(S, &'a ())>, +pub struct CommandDispatcher +// where +// Self: Sync + Send, +{ + pub root: Arc>>, } -impl<'a, S> CommandDispatcher<'a, S> { +impl CommandDispatcher { pub fn new() -> Self { Self { - root: Rc::new(RefCell::new(CommandNode::default())), - _marker: PhantomData, + root: Arc::new(RwLock::new(CommandNode::default())), } } - pub fn register(&mut self, node: ArgumentBuilder) -> Rc>> { - let build = Rc::new(RefCell::new(node.build())); - self.root.borrow_mut().add_child(&build); + pub fn register(&mut self, node: ArgumentBuilder) -> Arc>> { + let build = Arc::new(RwLock::new(node.build())); + self.root.write().add_child(&build); build } @@ -34,9 +37,9 @@ impl<'a, S> CommandDispatcher<'a, S> { self.parse_nodes(&self.root, &command, context).unwrap() } - fn parse_nodes( + fn parse_nodes<'a>( &'a self, - node: &Rc>>, + node: &Arc>>, original_reader: &StringReader, context_so_far: CommandContextBuilder<'a, S>, ) -> Result, CommandSyntaxException> { @@ -45,21 +48,18 @@ impl<'a, S> CommandDispatcher<'a, S> { let mut potentials: Vec> = vec![]; let cursor = original_reader.cursor(); - for child in node - .borrow() - .get_relevant_nodes(&mut original_reader.clone()) - { - if !child.borrow().can_use(source.clone()) { + for child in node.read().get_relevant_nodes(&mut original_reader.clone()) { + if !child.read().can_use(source.clone()) { continue; } let mut context = context_so_far.clone(); let mut reader = original_reader.clone(); let parse_with_context_result = - child.borrow().parse_with_context(&mut reader, &mut context); + child.read().parse_with_context(&mut reader, &mut context); if let Err(ex) = parse_with_context_result { errors.insert( - Rc::new((*child.borrow()).clone()), + Rc::new((*child.read()).clone()), BuiltInExceptions::DispatcherParseException { message: ex.message(), } @@ -70,7 +70,7 @@ impl<'a, S> CommandDispatcher<'a, S> { } if reader.can_read() && reader.peek() != ' ' { errors.insert( - Rc::new((*child.borrow()).clone()), + Rc::new((*child.read()).clone()), BuiltInExceptions::DispatcherExpectedArgumentSeparator .create_with_context(&reader), ); @@ -78,14 +78,14 @@ impl<'a, S> CommandDispatcher<'a, S> { continue; } - context.with_command(&child.borrow().command); - if reader.can_read_length(if child.borrow().redirect.is_none() { + context.with_command(&child.read().command); + if reader.can_read_length(if child.read().redirect.is_none() { 2 } else { 1 }) { reader.skip(); - if let Some(redirect) = &child.borrow().redirect { + if let Some(redirect) = &child.read().redirect { let child_context = CommandContextBuilder::new(self, source, redirect.clone(), reader.cursor); let parse = self @@ -151,30 +151,30 @@ impl<'a, S> CommandDispatcher<'a, S> { } pub fn add_paths( - node: Rc>>, - result: &mut Vec>>>>, - parents: Vec>>>, + node: Arc>>, + result: &mut Vec>>>>, + parents: Vec>>>, ) { let mut current = parents; current.push(node.clone()); result.push(current.clone()); - for child in node.borrow().children.values() { + for child in node.read().children.values() { Self::add_paths(child.clone(), result, current.clone()); } } pub fn get_path(&self, target: CommandNode) -> Vec { - let rc_target = Rc::new(RefCell::new(target)); - let mut nodes: Vec>>>> = Vec::new(); + let rc_target = Arc::new(RwLock::new(target)); + let mut nodes: Vec>>>> = Vec::new(); Self::add_paths(self.root.clone(), &mut nodes, vec![]); for list in nodes { - if *list.last().expect("Nothing in list").borrow() == *rc_target.borrow() { + if *list.last().expect("Nothing in list").read() == *rc_target.read() { let mut result: Vec = Vec::with_capacity(list.len()); for node in list { - if node != self.root { - result.push(node.borrow().name().to_string()); + if !Arc::ptr_eq(&node, &self.root) { + result.push(node.read().name().to_string()); } } return result; @@ -183,10 +183,10 @@ impl<'a, S> CommandDispatcher<'a, S> { vec![] } - pub fn find_node(&self, path: &[&str]) -> Option>>> { + pub fn find_node(&self, path: &[&str]) -> Option>>> { let mut node = self.root.clone(); for name in path { - if let Some(child) = node.clone().borrow().child(name) { + if let Some(child) = node.clone().read().child(name) { node = child; } else { return None; diff --git a/azalea-brigadier/src/context/command_context.rs b/azalea-brigadier/src/context/command_context.rs index 98609a6e..88af2002 100755 --- a/azalea-brigadier/src/context/command_context.rs +++ b/azalea-brigadier/src/context/command_context.rs @@ -1,9 +1,11 @@ +use parking_lot::RwLock; + use super::{parsed_command_node::ParsedCommandNode, string_range::StringRange, ParsedArgument}; use crate::{ modifier::RedirectModifier, tree::{Command, CommandNode}, }; -use std::{any::Any, cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc}; +use std::{any::Any, collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; /// A built `CommandContextBuilder`. pub struct CommandContext { @@ -11,7 +13,7 @@ pub struct CommandContext { pub input: String, pub arguments: HashMap, pub command: Command, - pub root_node: Rc>>, + pub root_node: Arc>>, pub nodes: Vec>, pub range: StringRange, pub child: Option>>, diff --git a/azalea-brigadier/src/context/command_context_builder.rs b/azalea-brigadier/src/context/command_context_builder.rs index b0677158..54063879 100755 --- a/azalea-brigadier/src/context/command_context_builder.rs +++ b/azalea-brigadier/src/context/command_context_builder.rs @@ -1,3 +1,5 @@ +use parking_lot::RwLock; + use super::{ command_context::CommandContext, parsed_command_node::ParsedCommandNode, string_range::StringRange, ParsedArgument, @@ -7,13 +9,13 @@ use crate::{ modifier::RedirectModifier, tree::{Command, CommandNode}, }; -use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc}; +use std::{collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; pub struct CommandContextBuilder<'a, S> { pub arguments: HashMap, - pub root: Rc>>, + pub root: Arc>>, pub nodes: Vec>, - pub dispatcher: &'a CommandDispatcher<'a, S>, + pub dispatcher: &'a CommandDispatcher, pub source: Rc, pub command: Command, pub child: Option>>, @@ -28,7 +30,7 @@ impl Clone for CommandContextBuilder<'_, S> { arguments: self.arguments.clone(), root: self.root.clone(), nodes: self.nodes.clone(), - dispatcher: self.dispatcher.clone(), + dispatcher: self.dispatcher, source: self.source.clone(), command: self.command.clone(), child: self.child.clone(), @@ -43,7 +45,7 @@ impl<'a, S> CommandContextBuilder<'a, S> { pub fn new( dispatcher: &'a CommandDispatcher, source: Rc, - root_node: Rc>>, + root_node: Arc>>, start: usize, ) -> Self { Self { @@ -72,14 +74,14 @@ impl<'a, S> CommandContextBuilder<'a, S> { self.arguments.insert(name.to_string(), argument); self } - pub fn with_node(&mut self, node: Rc>>, range: StringRange) -> &Self { + pub fn with_node(&mut self, node: Arc>>, range: StringRange) -> &Self { self.nodes.push(ParsedCommandNode { node: node.clone(), range: range.clone(), }); self.range = StringRange::encompassing(&self.range, &range); - self.modifier = node.borrow().modifier.clone(); - self.forks = node.borrow().forks; + self.modifier = node.read().modifier.clone(); + self.forks = node.read().forks; self } diff --git a/azalea-brigadier/src/context/parsed_command_node.rs b/azalea-brigadier/src/context/parsed_command_node.rs index ed49928d..bba5d121 100755 --- a/azalea-brigadier/src/context/parsed_command_node.rs +++ b/azalea-brigadier/src/context/parsed_command_node.rs @@ -1,10 +1,12 @@ +use parking_lot::RwLock; + use super::string_range::StringRange; use crate::tree::CommandNode; -use std::{cell::RefCell, rc::Rc}; +use std::sync::Arc; #[derive(Debug)] pub struct ParsedCommandNode { - pub node: Rc>>, + pub node: Arc>>, pub range: StringRange, } diff --git a/azalea-brigadier/src/tree/mod.rs b/azalea-brigadier/src/tree/mod.rs index bb6af68d..902e288b 100755 --- a/azalea-brigadier/src/tree/mod.rs +++ b/azalea-brigadier/src/tree/mod.rs @@ -1,3 +1,5 @@ +use parking_lot::RwLock; + use crate::{ builder::{ argument_builder::ArgumentBuilderType, literal_argument_builder::Literal, @@ -8,7 +10,7 @@ use crate::{ modifier::RedirectModifier, string_reader::StringReader, }; -use std::{cell::RefCell, collections::HashMap, fmt::Debug, hash::Hash, ptr, rc::Rc}; +use std::{collections::HashMap, fmt::Debug, hash::Hash, ptr, rc::Rc, sync::Arc}; pub type Command = Option) -> i32>>; @@ -17,13 +19,13 @@ pub type Command = Option) -> i32>>; pub struct CommandNode { pub value: ArgumentBuilderType, - pub children: HashMap>>>, - pub literals: HashMap>>>, - pub arguments: HashMap>>>, + pub children: HashMap>>>, + pub literals: HashMap>>>, + pub arguments: HashMap>>>, pub command: Command, pub requirement: Rc) -> bool>, - pub redirect: Option>>>, + pub redirect: Option>>>, pub forks: bool, pub modifier: Option>>, } @@ -62,7 +64,7 @@ impl CommandNode { } } - pub fn get_relevant_nodes(&self, input: &mut StringReader) -> Vec>>> { + pub fn get_relevant_nodes(&self, input: &mut StringReader) -> Vec>>> { let literals = &self.literals; if literals.is_empty() { @@ -92,20 +94,20 @@ impl CommandNode { (self.requirement)(source) } - pub fn add_child(&mut self, node: &Rc>>) { - let child = self.children.get(node.borrow().name()); + pub fn add_child(&mut self, node: &Arc>>) { + let child = self.children.get(node.read().name()); if let Some(child) = child { // We've found something to merge onto - if let Some(command) = &node.borrow().command { - child.borrow_mut().command = Some(command.clone()); + if let Some(command) = &node.read().command { + child.write().command = Some(command.clone()); } - for grandchild in node.borrow().children.values() { - child.borrow_mut().add_child(grandchild); + for grandchild in node.read().children.values() { + child.write().add_child(grandchild); } } else { self.children - .insert(node.borrow().name().to_string(), node.clone()); - match &node.borrow().value { + .insert(node.read().name().to_string(), node.clone()); + match &node.read().value { ArgumentBuilderType::Literal(literal) => { self.literals.insert(literal.value.clone(), node.clone()); } @@ -123,7 +125,7 @@ impl CommandNode { } } - pub fn child(&self, name: &str) -> Option>>> { + pub fn child(&self, name: &str) -> Option>>> { self.children.get(name).cloned() } @@ -142,7 +144,7 @@ impl CommandNode { }; context_builder.with_argument(&argument.name, parsed.clone()); - context_builder.with_node(Rc::new(RefCell::new(self.clone())), parsed.range); + context_builder.with_node(Arc::new(RwLock::new(self.clone())), parsed.range); Ok(()) } @@ -152,7 +154,7 @@ impl CommandNode { if let Some(end) = end { context_builder.with_node( - Rc::new(RefCell::new(self.clone())), + Arc::new(RwLock::new(self.clone())), StringRange::between(start, end), ); return Ok(()); @@ -232,7 +234,7 @@ impl Hash for CommandNode { // hash the children for (k, v) in &self.children { k.hash(state); - v.borrow().hash(state); + v.read().hash(state); } // i hope this works because if doesn't then that'll be a problem ptr::hash(&self.command, state); @@ -241,9 +243,16 @@ impl Hash for CommandNode { impl PartialEq for CommandNode { fn eq(&self, other: &Self) -> bool { - if self.children != other.children { + if self.children.len() != other.children.len() { return false; } + for (k, v) in &self.children { + let other_child = other.children.get(k).unwrap(); + if !Arc::ptr_eq(v, other_child) { + return false; + } + } + if let Some(selfexecutes) = &self.command { // idk how to do this better since we can't compare `dyn Fn`s if let Some(otherexecutes) = &other.command { diff --git a/azalea-brigadier/tests/builder/argument_builder_test.rs b/azalea-brigadier/tests/builder/argument_builder_test.rs index e570c988..ee44f5e6 100755 --- a/azalea-brigadier/tests/builder/argument_builder_test.rs +++ b/azalea-brigadier/tests/builder/argument_builder_test.rs @@ -17,13 +17,14 @@ use super::ArgumentBuilder; // @Test // public void testArguments() throws Exception { -// final RequiredArgumentBuilder argument = argument("bar", integer()); +// final RequiredArgumentBuilder argument = argument("bar", +// integer()); // builder.then(argument); // assertThat(builder.getArguments(), hasSize(1)); -// assertThat(builder.getArguments(), hasItem((CommandNode) argument.build())); -// } +// assertThat(builder.getArguments(), hasItem((CommandNode) +// argument.build())); } #[test] fn test_arguments() { @@ -37,7 +38,7 @@ fn test_arguments() { .arguments .children .values() - .any(|e| *e.borrow() == *built_argument)); + .any(|e| *e.read() == *built_argument)); } // @Test @@ -61,8 +62,8 @@ fn test_arguments() { // builder.then(literal("foo")); // } -// private static class TestableArgumentBuilder extends ArgumentBuilder> { -// @Override +// private static class TestableArgumentBuilder extends +// ArgumentBuilder> { @Override // protected TestableArgumentBuilder getThis() { // return this; // } diff --git a/azalea-brigadier/tests/command_dispatcher_test.rs b/azalea-brigadier/tests/command_dispatcher_test.rs index e30dd2c1..fb0085ba 100755 --- a/azalea-brigadier/tests/command_dispatcher_test.rs +++ b/azalea-brigadier/tests/command_dispatcher_test.rs @@ -251,31 +251,34 @@ fn execute_redirected_multiple_times() { let parse = subject.parse(input.into(), Rc::new(CommandSource {})); assert_eq!(parse.context.range.get(input), "redirected"); assert_eq!(parse.context.nodes.len(), 1); - assert_eq!(parse.context.root, root); + assert_eq!(*parse.context.root.read(), *root.read()); assert_eq!(parse.context.nodes[0].range, parse.context.range); - assert_eq!(parse.context.nodes[0].node, redirect_node); + assert_eq!(*parse.context.nodes[0].node.read(), *redirect_node.read()); let child1 = parse.context.child.clone(); assert!(child1.is_some()); assert_eq!(child1.clone().unwrap().range.get(input), "redirected"); assert_eq!(child1.clone().unwrap().nodes.len(), 1); - assert_eq!(child1.clone().unwrap().root, root); + assert_eq!(*child1.clone().unwrap().root.read(), *root.read()); assert_eq!( child1.clone().unwrap().nodes[0].range, child1.clone().unwrap().range ); - assert_eq!(child1.clone().unwrap().nodes[0].node, redirect_node); + assert_eq!( + *child1.clone().unwrap().nodes[0].node.read(), + *redirect_node.read() + ); let child2 = child1.unwrap().child.clone(); assert!(child2.is_some()); assert_eq!(child2.clone().unwrap().range.get(input), "actual"); assert_eq!(child2.clone().unwrap().nodes.len(), 1); - assert_eq!(child2.clone().unwrap().root, root); + assert_eq!(*child2.clone().unwrap().root.read(), *root.read()); assert_eq!( child2.clone().unwrap().nodes[0].range, child2.clone().unwrap().range ); - assert_eq!(child2.unwrap().nodes[0].node, concrete_node); + assert_eq!(*child2.unwrap().nodes[0].node.read(), *concrete_node.read()); assert_eq!(CommandDispatcher::execute_parsed(parse).unwrap(), 42); } @@ -299,18 +302,18 @@ fn execute_redirected() { let parse = subject.parse(input.into(), Rc::new(CommandSource {})); assert_eq!(parse.context.range.get(input), "redirected"); assert_eq!(parse.context.nodes.len(), 1); - assert_eq!(parse.context.root, subject.root); + assert_eq!(*parse.context.root.read(), *subject.root.read()); assert_eq!(parse.context.nodes[0].range, parse.context.range); - assert_eq!(parse.context.nodes[0].node, redirect_node); + assert_eq!(*parse.context.nodes[0].node.read(), *redirect_node.read()); let parent = parse.context.child.clone(); assert!(parent.is_some()); let parent = parent.unwrap(); assert_eq!(parent.range.get(input), "actual"); assert_eq!(parent.nodes.len(), 1); - assert_eq!(parse.context.root, subject.root); + assert_eq!(*parse.context.root.read(), *subject.root.read()); assert_eq!(parent.nodes[0].range, parent.range); - assert_eq!(parent.nodes[0].node, concrete_node); + assert_eq!(*parent.nodes[0].node.read(), *concrete_node.read()); assert_eq!(parent.source, Rc::new(CommandSource {})); assert_eq!(CommandDispatcher::execute_parsed(parse).unwrap(), 2); @@ -406,5 +409,5 @@ fn get_path() { fn find_node_doesnt_exist() { let subject = CommandDispatcher::<()>::new(); - assert_eq!(subject.find_node(&["foo", "bar"]), None) + assert!(subject.find_node(&["foo", "bar"]).is_none()) } -- cgit v1.2.3 From f825544e2776ab545ff0a9c674b68183120695cb Mon Sep 17 00:00:00 2001 From: mat Date: Fri, 5 May 2023 23:23:11 -0500 Subject: CommandDispatcher is now Send+Sync --- azalea-brigadier/src/builder/argument_builder.rs | 20 ++++---- .../src/builder/required_argument_builder.rs | 13 ++++-- azalea-brigadier/src/command_dispatcher.rs | 10 ++-- azalea-brigadier/src/context/command_context.rs | 10 ++-- .../src/context/command_context_builder.rs | 14 +++--- azalea-brigadier/src/modifier.rs | 4 +- azalea-brigadier/src/tree/mod.rs | 14 +++--- azalea-brigadier/tests/command_dispatcher_test.rs | 54 +++++++++++----------- 8 files changed, 71 insertions(+), 68 deletions(-) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/builder/argument_builder.rs b/azalea-brigadier/src/builder/argument_builder.rs index a1f3d6ae..c6f2146a 100755 --- a/azalea-brigadier/src/builder/argument_builder.rs +++ b/azalea-brigadier/src/builder/argument_builder.rs @@ -7,7 +7,7 @@ use crate::{ }; use super::{literal_argument_builder::Literal, required_argument_builder::Argument}; -use std::{fmt::Debug, rc::Rc, sync::Arc}; +use std::{fmt::Debug, sync::Arc}; #[derive(Debug, Clone)] pub enum ArgumentBuilderType { @@ -20,11 +20,11 @@ pub struct ArgumentBuilder { arguments: CommandNode, command: Command, - requirement: Rc) -> bool>, + requirement: Arc) -> bool + Send + Sync>, target: Option>>>, forks: bool, - modifier: Option>>, + modifier: Option>>, } /// A node that isn't yet built. @@ -36,7 +36,7 @@ impl ArgumentBuilder { ..Default::default() }, command: None, - requirement: Rc::new(|_| true), + requirement: Arc::new(|_| true), forks: false, modifier: None, target: None, @@ -54,17 +54,17 @@ impl ArgumentBuilder { pub fn executes(mut self, f: F) -> Self where - F: Fn(&CommandContext) -> i32 + 'static, + F: Fn(&CommandContext) -> i32 + Send + Sync + 'static, { - self.command = Some(Rc::new(f)); + self.command = Some(Arc::new(f)); self } pub fn requires(mut self, requirement: F) -> Self where - F: Fn(Rc) -> bool + 'static, + F: Fn(Arc) -> bool + Send + Sync + 'static, { - self.requirement = Rc::new(requirement); + self.requirement = Arc::new(requirement); self } @@ -75,7 +75,7 @@ impl ArgumentBuilder { pub fn fork( self, target: Arc>>, - modifier: Rc>, + modifier: Arc>, ) -> Self { self.forward(target, Some(modifier), true) } @@ -83,7 +83,7 @@ impl ArgumentBuilder { pub fn forward( mut self, target: Arc>>, - modifier: Option>>, + modifier: Option>>, fork: bool, ) -> Self { if !self.arguments.children.is_empty() { diff --git a/azalea-brigadier/src/builder/required_argument_builder.rs b/azalea-brigadier/src/builder/required_argument_builder.rs index 9d4d9e0a..0363d204 100755 --- a/azalea-brigadier/src/builder/required_argument_builder.rs +++ b/azalea-brigadier/src/builder/required_argument_builder.rs @@ -2,17 +2,17 @@ use super::argument_builder::{ArgumentBuilder, ArgumentBuilderType}; use crate::{ arguments::ArgumentType, exceptions::CommandSyntaxException, string_reader::StringReader, }; -use std::{any::Any, fmt::Debug, rc::Rc}; +use std::{any::Any, fmt::Debug, rc::Rc, sync::Arc}; /// An argument node type. The `T` type parameter is the type of the argument, /// which can be anything. #[derive(Clone)] pub struct Argument { pub name: String, - parser: Rc, + parser: Arc, } impl Argument { - pub fn new(name: &str, parser: Rc) -> Self { + pub fn new(name: &str, parser: Arc) -> Self { Self { name: name.to_string(), parser, @@ -40,6 +40,9 @@ impl Debug for Argument { } /// Shortcut for creating a new argument builder node. -pub fn argument(name: &str, parser: impl ArgumentType + 'static) -> ArgumentBuilder { - ArgumentBuilder::new(Argument::new(name, Rc::new(parser)).into()) +pub fn argument( + name: &str, + parser: impl ArgumentType + Send + Sync + 'static, +) -> ArgumentBuilder { + ArgumentBuilder::new(Argument::new(name, Arc::new(parser)).into()) } diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index 0d84171e..384a28dd 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -13,8 +13,8 @@ use std::{cmp::Ordering, collections::HashMap, mem, rc::Rc, sync::Arc}; /// The root of the command tree. You need to make this to register commands. #[derive(Default)] pub struct CommandDispatcher -// where -// Self: Sync + Send, +where + Self: Sync + Send, { pub root: Arc>>, } @@ -32,7 +32,7 @@ impl CommandDispatcher { build } - pub fn parse(&self, command: StringReader, source: Rc) -> ParseResults { + pub fn parse(&self, command: StringReader, source: Arc) -> ParseResults { let context = CommandContextBuilder::new(self, source, self.root.clone(), command.cursor()); self.parse_nodes(&self.root, &command, context).unwrap() } @@ -91,7 +91,7 @@ impl CommandDispatcher { let parse = self .parse_nodes(redirect, &reader, child_context) .expect("Parsing nodes failed"); - context.with_child(Rc::new(parse.context)); + context.with_child(Arc::new(parse.context)); return Ok(ParseResults { context, reader: parse.reader, @@ -144,7 +144,7 @@ impl CommandDispatcher { pub fn execute( &self, input: StringReader, - source: Rc, + source: Arc, ) -> Result { let parse = self.parse(input, source); Self::execute_parsed(parse) diff --git a/azalea-brigadier/src/context/command_context.rs b/azalea-brigadier/src/context/command_context.rs index 88af2002..1734bb05 100755 --- a/azalea-brigadier/src/context/command_context.rs +++ b/azalea-brigadier/src/context/command_context.rs @@ -9,15 +9,15 @@ use std::{any::Any, collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; /// A built `CommandContextBuilder`. pub struct CommandContext { - pub source: Rc, + pub source: Arc, pub input: String, pub arguments: HashMap, pub command: Command, pub root_node: Arc>>, pub nodes: Vec>, pub range: StringRange, - pub child: Option>>, - pub modifier: Option>>, + pub child: Option>>, + pub modifier: Option>>, pub forks: bool, } @@ -56,8 +56,8 @@ impl Debug for CommandContext { } impl CommandContext { - pub fn copy_for(&self, source: Rc) -> Self { - if Rc::ptr_eq(&source, &self.source) { + pub fn copy_for(&self, source: Arc) -> Self { + if Arc::ptr_eq(&source, &self.source) { return self.clone(); } CommandContext { diff --git a/azalea-brigadier/src/context/command_context_builder.rs b/azalea-brigadier/src/context/command_context_builder.rs index 54063879..78088941 100755 --- a/azalea-brigadier/src/context/command_context_builder.rs +++ b/azalea-brigadier/src/context/command_context_builder.rs @@ -9,18 +9,18 @@ use crate::{ modifier::RedirectModifier, tree::{Command, CommandNode}, }; -use std::{collections::HashMap, fmt::Debug, rc::Rc, sync::Arc}; +use std::{collections::HashMap, fmt::Debug, sync::Arc}; pub struct CommandContextBuilder<'a, S> { pub arguments: HashMap, pub root: Arc>>, pub nodes: Vec>, pub dispatcher: &'a CommandDispatcher, - pub source: Rc, + pub source: Arc, pub command: Command, - pub child: Option>>, + pub child: Option>>, pub range: StringRange, - pub modifier: Option>>, + pub modifier: Option>>, pub forks: bool, } @@ -44,7 +44,7 @@ impl Clone for CommandContextBuilder<'_, S> { impl<'a, S> CommandContextBuilder<'a, S> { pub fn new( dispatcher: &'a CommandDispatcher, - source: Rc, + source: Arc, root_node: Arc>>, start: usize, ) -> Self { @@ -66,7 +66,7 @@ impl<'a, S> CommandContextBuilder<'a, S> { self.command = command.clone(); self } - pub fn with_child(&mut self, child: Rc>) -> &Self { + pub fn with_child(&mut self, child: Arc>) -> &Self { self.child = Some(child); self } @@ -92,7 +92,7 @@ impl<'a, S> CommandContextBuilder<'a, S> { nodes: self.nodes.clone(), source: self.source.clone(), command: self.command.clone(), - child: self.child.clone().map(|c| Rc::new(c.build(input))), + child: self.child.clone().map(|c| Arc::new(c.build(input))), range: self.range.clone(), forks: self.forks, modifier: self.modifier.clone(), diff --git a/azalea-brigadier/src/modifier.rs b/azalea-brigadier/src/modifier.rs index d40d59f9..bebdd0cb 100755 --- a/azalea-brigadier/src/modifier.rs +++ b/azalea-brigadier/src/modifier.rs @@ -1,6 +1,6 @@ -use std::rc::Rc; +use std::sync::Arc; use crate::{context::CommandContext, exceptions::CommandSyntaxException}; pub type RedirectModifier = - dyn Fn(&CommandContext) -> Result>, CommandSyntaxException>; + dyn Fn(&CommandContext) -> Result>, CommandSyntaxException> + Send + Sync; diff --git a/azalea-brigadier/src/tree/mod.rs b/azalea-brigadier/src/tree/mod.rs index 902e288b..cec972dc 100755 --- a/azalea-brigadier/src/tree/mod.rs +++ b/azalea-brigadier/src/tree/mod.rs @@ -10,9 +10,9 @@ use crate::{ modifier::RedirectModifier, string_reader::StringReader, }; -use std::{collections::HashMap, fmt::Debug, hash::Hash, ptr, rc::Rc, sync::Arc}; +use std::{collections::HashMap, fmt::Debug, hash::Hash, ptr, sync::Arc}; -pub type Command = Option) -> i32>>; +pub type Command = Option) -> i32 + Send + Sync>>; /// An ArgumentBuilder that has been built. #[non_exhaustive] @@ -24,10 +24,10 @@ pub struct CommandNode { pub arguments: HashMap>>>, pub command: Command, - pub requirement: Rc) -> bool>, + pub requirement: Arc) -> bool + Send + Sync>, pub redirect: Option>>>, pub forks: bool, - pub modifier: Option>>, + pub modifier: Option>>, } impl Clone for CommandNode { @@ -90,7 +90,7 @@ impl CommandNode { } } - pub fn can_use(&self, source: Rc) -> bool { + pub fn can_use(&self, source: Arc) -> bool { (self.requirement)(source) } @@ -221,7 +221,7 @@ impl Default for CommandNode { arguments: HashMap::new(), command: None, - requirement: Rc::new(|_| true), + requirement: Arc::new(|_| true), redirect: None, forks: false, modifier: None, @@ -257,7 +257,7 @@ impl PartialEq for CommandNode { // idk how to do this better since we can't compare `dyn Fn`s if let Some(otherexecutes) = &other.command { #[allow(clippy::vtable_address_comparisons)] - if !Rc::ptr_eq(selfexecutes, otherexecutes) { + if !Arc::ptr_eq(selfexecutes, otherexecutes) { return false; } } else { diff --git a/azalea-brigadier/tests/command_dispatcher_test.rs b/azalea-brigadier/tests/command_dispatcher_test.rs index fb0085ba..4479cfa2 100755 --- a/azalea-brigadier/tests/command_dispatcher_test.rs +++ b/azalea-brigadier/tests/command_dispatcher_test.rs @@ -1,4 +1,4 @@ -use std::rc::Rc; +use std::sync::Arc; use azalea_brigadier::{ arguments::integer_argument_type::integer, @@ -25,7 +25,7 @@ fn create_and_execute_command() { assert_eq!( subject - .execute("foo".into(), Rc::new(CommandSource {})) + .execute("foo".into(), Arc::new(CommandSource {})) .unwrap(), 42 ); @@ -38,7 +38,7 @@ fn create_and_execute_offset_command() { assert_eq!( subject - .execute(input_with_offset("/foo", 1), Rc::new(CommandSource {})) + .execute(input_with_offset("/foo", 1), Arc::new(CommandSource {})) .unwrap(), 42 ); @@ -52,13 +52,13 @@ fn create_and_merge_commands() { assert_eq!( subject - .execute("base foo".into(), Rc::new(CommandSource {})) + .execute("base foo".into(), Arc::new(CommandSource {})) .unwrap(), 42 ); assert_eq!( subject - .execute("base bar".into(), Rc::new(CommandSource {})) + .execute("base bar".into(), Arc::new(CommandSource {})) .unwrap(), 42 ); @@ -70,7 +70,7 @@ fn execute_unknown_command() { subject.register(literal("bar")); subject.register(literal("baz")); - let execute_result = subject.execute("foo".into(), Rc::new(CommandSource {})); + let execute_result = subject.execute("foo".into(), Arc::new(CommandSource {})); let err = execute_result.err().unwrap(); match err.type_ { @@ -85,7 +85,7 @@ fn execute_impermissible_command() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").requires(|_| false)); - let execute_result = subject.execute("foo".into(), Rc::new(CommandSource {})); + let execute_result = subject.execute("foo".into(), Arc::new(CommandSource {})); let err = execute_result.err().unwrap(); match err.type_ { @@ -100,7 +100,7 @@ fn execute_empty_command() { let mut subject = CommandDispatcher::new(); subject.register(literal("")); - let execute_result = subject.execute("".into(), Rc::new(CommandSource {})); + let execute_result = subject.execute("".into(), Arc::new(CommandSource {})); let err = execute_result.err().unwrap(); match err.type_ { @@ -115,7 +115,7 @@ fn execute_unknown_subcommand() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").executes(|_| 42)); - let execute_result = subject.execute("foo bar".into(), Rc::new(CommandSource {})); + let execute_result = subject.execute("foo bar".into(), Arc::new(CommandSource {})); let err = execute_result.err().unwrap(); match err.type_ { @@ -130,7 +130,7 @@ fn execute_incorrect_literal() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").executes(|_| 42).then(literal("bar"))); - let execute_result = subject.execute("foo baz".into(), Rc::new(CommandSource {})); + let execute_result = subject.execute("foo baz".into(), Arc::new(CommandSource {})); let err = execute_result.err().unwrap(); match err.type_ { @@ -150,7 +150,7 @@ fn execute_ambiguous_incorrect_argument() { .then(literal("baz")), ); - let execute_result = subject.execute("foo unknown".into(), Rc::new(CommandSource {})); + let execute_result = subject.execute("foo unknown".into(), Arc::new(CommandSource {})); let err = execute_result.err().unwrap(); match err.type_ { @@ -174,7 +174,7 @@ fn execute_subcommand() { assert_eq!( subject - .execute("foo =".into(), Rc::new(CommandSource {})) + .execute("foo =".into(), Arc::new(CommandSource {})) .unwrap(), 100 ); @@ -185,7 +185,7 @@ fn parse_incomplete_literal() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").then(literal("bar").executes(|_| 42))); - let parse = subject.parse("foo ".into(), Rc::new(CommandSource {})); + let parse = subject.parse("foo ".into(), Arc::new(CommandSource {})); assert_eq!(parse.reader.remaining(), " "); assert_eq!(parse.context.nodes.len(), 1); } @@ -195,7 +195,7 @@ fn parse_incomplete_argument() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").then(argument("bar", integer()).executes(|_| 42))); - let parse = subject.parse("foo ".into(), Rc::new(CommandSource {})); + let parse = subject.parse("foo ".into(), Arc::new(CommandSource {})); assert_eq!(parse.reader.remaining(), " "); assert_eq!(parse.context.nodes.len(), 1); } @@ -212,7 +212,7 @@ fn execute_ambiguious_parent_subcommand() { assert_eq!( subject - .execute("test 1 2".into(), Rc::new(CommandSource {})) + .execute("test 1 2".into(), Arc::new(CommandSource {})) .unwrap(), 100 ); @@ -232,7 +232,7 @@ fn execute_ambiguious_parent_subcommand_via_redirect() { assert_eq!( subject - .execute("redirect 1 2".into(), Rc::new(CommandSource {})) + .execute("redirect 1 2".into(), Arc::new(CommandSource {})) .unwrap(), 100 ); @@ -248,7 +248,7 @@ fn execute_redirected_multiple_times() { let input = "redirected redirected actual"; - let parse = subject.parse(input.into(), Rc::new(CommandSource {})); + let parse = subject.parse(input.into(), Arc::new(CommandSource {})); assert_eq!(parse.context.range.get(input), "redirected"); assert_eq!(parse.context.nodes.len(), 1); assert_eq!(*parse.context.root.read(), *root.read()); @@ -287,19 +287,19 @@ fn execute_redirected_multiple_times() { fn execute_redirected() { let mut subject = CommandDispatcher::new(); - let source1 = Rc::new(CommandSource {}); - let source2 = Rc::new(CommandSource {}); + let source1 = Arc::new(CommandSource {}); + let source2 = Arc::new(CommandSource {}); - let modifier = move |_: &CommandContext| -> Result>, CommandSyntaxException> { + let modifier = move |_: &CommandContext| -> Result>, CommandSyntaxException> { Ok(vec![source1.clone(), source2.clone()]) }; let concrete_node = subject.register(literal("actual").executes(|_| 42)); let redirect_node = - subject.register(literal("redirected").fork(subject.root.clone(), Rc::new(modifier))); + subject.register(literal("redirected").fork(subject.root.clone(), Arc::new(modifier))); let input = "redirected actual"; - let parse = subject.parse(input.into(), Rc::new(CommandSource {})); + let parse = subject.parse(input.into(), Arc::new(CommandSource {})); assert_eq!(parse.context.range.get(input), "redirected"); assert_eq!(parse.context.nodes.len(), 1); assert_eq!(*parse.context.root.read(), *subject.root.read()); @@ -314,7 +314,7 @@ fn execute_redirected() { assert_eq!(*parse.context.root.read(), *subject.root.read()); assert_eq!(parent.nodes[0].range, parent.range); assert_eq!(*parent.nodes[0].node.read(), *concrete_node.read()); - assert_eq!(parent.source, Rc::new(CommandSource {})); + assert_eq!(parent.source, Arc::new(CommandSource {})); assert_eq!(CommandDispatcher::execute_parsed(parse).unwrap(), 2); } @@ -329,7 +329,7 @@ fn execute_orphaned_subcommand() { .executes(|_| 42), ); - let result = subject.execute("foo 5".into(), Rc::new(CommandSource {})); + let result = subject.execute("foo 5".into(), Arc::new(CommandSource {})); assert!(result.is_err()); let result = result.unwrap_err(); assert_eq!( @@ -348,7 +348,7 @@ fn execute_invalid_other() { assert_eq!( subject - .execute("world".into(), Rc::new(CommandSource {})) + .execute("world".into(), Arc::new(CommandSource {})) .unwrap(), 42 ); @@ -364,7 +364,7 @@ fn parse_no_space_separator() { .executes(|_| 42), ); - let result = subject.execute("foo$".into(), Rc::new(CommandSource {})); + let result = subject.execute("foo$".into(), Arc::new(CommandSource {})); assert!(result.is_err()); let result = result.unwrap_err(); assert_eq!( @@ -384,7 +384,7 @@ fn execute_invalid_subcommand() { .executes(|_| 42), ); - let result = subject.execute("foo bar".into(), Rc::new(CommandSource {})); + let result = subject.execute("foo bar".into(), Arc::new(CommandSource {})); assert!(result.is_err()); let result = result.unwrap_err(); // this fails for some reason, i blame mojang -- cgit v1.2.3 From 084953b89fa800d275b7f712d339f89056e48645 Mon Sep 17 00:00:00 2001 From: mat Date: Fri, 5 May 2023 23:31:27 -0500 Subject: fix CommandDispatcher::default --- azalea-brigadier/src/command_dispatcher.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index 384a28dd..a14b5009 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -11,7 +11,6 @@ use crate::{ use std::{cmp::Ordering, collections::HashMap, mem, rc::Rc, sync::Arc}; /// The root of the command tree. You need to make this to register commands. -#[derive(Default)] pub struct CommandDispatcher where Self: Sync + Send, @@ -278,3 +277,9 @@ impl CommandDispatcher { // Ok(if forked { successful_forks } else { result }) } } + +impl Default for CommandDispatcher { + fn default() -> Self { + Self::new() + } +} -- cgit v1.2.3 From 2823e508b389194ee1d8b3f4180fc3a15a7e077e Mon Sep 17 00:00:00 2001 From: mat Date: Sun, 7 May 2023 01:55:08 -0500 Subject: more brigadier argument types --- .../src/arguments/bool_argument_type.rs | 21 +++++++++ .../src/arguments/double_argument_type.rs | 54 ++++++++++++++++++++++ .../src/arguments/float_argument_type.rs | 54 ++++++++++++++++++++++ .../src/arguments/integer_argument_type.rs | 0 .../src/arguments/long_argument_type.rs | 54 ++++++++++++++++++++++ azalea-brigadier/src/arguments/mod.rs | 5 ++ .../src/arguments/string_argument_type.rs | 53 +++++++++++++++++++++ azalea-brigadier/src/lib.rs | 12 +++++ .../src/packets/game/clientbound_login_packet.rs | 2 + 9 files changed, 255 insertions(+) create mode 100644 azalea-brigadier/src/arguments/bool_argument_type.rs create mode 100644 azalea-brigadier/src/arguments/double_argument_type.rs create mode 100644 azalea-brigadier/src/arguments/float_argument_type.rs mode change 100755 => 100644 azalea-brigadier/src/arguments/integer_argument_type.rs create mode 100644 azalea-brigadier/src/arguments/long_argument_type.rs create mode 100644 azalea-brigadier/src/arguments/string_argument_type.rs (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/arguments/bool_argument_type.rs b/azalea-brigadier/src/arguments/bool_argument_type.rs new file mode 100644 index 00000000..01828c87 --- /dev/null +++ b/azalea-brigadier/src/arguments/bool_argument_type.rs @@ -0,0 +1,21 @@ +use std::{any::Any, rc::Rc}; + +use crate::{ + context::CommandContext, exceptions::CommandSyntaxException, string_reader::StringReader, +}; + +use super::ArgumentType; + +impl ArgumentType for bool { + fn parse(&self, reader: &mut StringReader) -> Result, CommandSyntaxException> { + Ok(Rc::new(reader.read_boolean())) + } +} + +pub fn get_bool<'a, S>(context: &'a CommandContext, name: &str) -> Option { + context + .argument(name) + .unwrap() + .downcast_ref::() + .cloned() +} diff --git a/azalea-brigadier/src/arguments/double_argument_type.rs b/azalea-brigadier/src/arguments/double_argument_type.rs new file mode 100644 index 00000000..117a11cc --- /dev/null +++ b/azalea-brigadier/src/arguments/double_argument_type.rs @@ -0,0 +1,54 @@ +use std::{any::Any, rc::Rc}; + +use crate::{ + context::CommandContext, + exceptions::{BuiltInExceptions, CommandSyntaxException}, + string_reader::StringReader, +}; + +use super::ArgumentType; + +#[derive(Default)] +struct Double { + pub minimum: Option, + pub maximum: Option, +} + +impl ArgumentType for Double { + fn parse(&self, reader: &mut StringReader) -> Result, CommandSyntaxException> { + let start = reader.cursor; + let result = reader.read_double()?; + if let Some(minimum) = self.minimum { + if result < minimum { + reader.cursor = start; + return Err(BuiltInExceptions::DoubleTooSmall { + found: result, + min: minimum, + } + .create_with_context(reader)); + } + } + if let Some(maximum) = self.maximum { + if result > maximum { + reader.cursor = start; + return Err(BuiltInExceptions::DoubleTooBig { + found: result, + max: maximum, + } + .create_with_context(reader)); + } + } + Ok(Rc::new(result)) + } +} + +pub fn double() -> impl ArgumentType { + Double::default() +} +pub fn get_integer(context: &CommandContext, name: &str) -> Option { + context + .argument(name) + .unwrap() + .downcast_ref::() + .copied() +} diff --git a/azalea-brigadier/src/arguments/float_argument_type.rs b/azalea-brigadier/src/arguments/float_argument_type.rs new file mode 100644 index 00000000..f335f11a --- /dev/null +++ b/azalea-brigadier/src/arguments/float_argument_type.rs @@ -0,0 +1,54 @@ +use std::{any::Any, rc::Rc}; + +use crate::{ + context::CommandContext, + exceptions::{BuiltInExceptions, CommandSyntaxException}, + string_reader::StringReader, +}; + +use super::ArgumentType; + +#[derive(Default)] +struct Float { + pub minimum: Option, + pub maximum: Option, +} + +impl ArgumentType for Float { + fn parse(&self, reader: &mut StringReader) -> Result, CommandSyntaxException> { + let start = reader.cursor; + let result = reader.read_float()?; + if let Some(minimum) = self.minimum { + if result < minimum { + reader.cursor = start; + return Err(BuiltInExceptions::FloatTooSmall { + found: result, + min: minimum, + } + .create_with_context(reader)); + } + } + if let Some(maximum) = self.maximum { + if result > maximum { + reader.cursor = start; + return Err(BuiltInExceptions::FloatTooBig { + found: result, + max: maximum, + } + .create_with_context(reader)); + } + } + Ok(Rc::new(result)) + } +} + +pub fn float() -> impl ArgumentType { + Float::default() +} +pub fn get_integer(context: &CommandContext, name: &str) -> Option { + context + .argument(name) + .unwrap() + .downcast_ref::() + .copied() +} diff --git a/azalea-brigadier/src/arguments/integer_argument_type.rs b/azalea-brigadier/src/arguments/integer_argument_type.rs old mode 100755 new mode 100644 diff --git a/azalea-brigadier/src/arguments/long_argument_type.rs b/azalea-brigadier/src/arguments/long_argument_type.rs new file mode 100644 index 00000000..435dd92a --- /dev/null +++ b/azalea-brigadier/src/arguments/long_argument_type.rs @@ -0,0 +1,54 @@ +use std::{any::Any, rc::Rc}; + +use crate::{ + context::CommandContext, + exceptions::{BuiltInExceptions, CommandSyntaxException}, + string_reader::StringReader, +}; + +use super::ArgumentType; + +#[derive(Default)] +struct Long { + pub minimum: Option, + pub maximum: Option, +} + +impl ArgumentType for Long { + fn parse(&self, reader: &mut StringReader) -> Result, CommandSyntaxException> { + let start = reader.cursor; + let result = reader.read_long()?; + if let Some(minimum) = self.minimum { + if result < minimum { + reader.cursor = start; + return Err(BuiltInExceptions::LongTooSmall { + found: result, + min: minimum, + } + .create_with_context(reader)); + } + } + if let Some(maximum) = self.maximum { + if result > maximum { + reader.cursor = start; + return Err(BuiltInExceptions::LongTooBig { + found: result, + max: maximum, + } + .create_with_context(reader)); + } + } + Ok(Rc::new(result)) + } +} + +pub fn long() -> impl ArgumentType { + Long::default() +} +pub fn get_integer(context: &CommandContext, name: &str) -> Option { + context + .argument(name) + .unwrap() + .downcast_ref::() + .copied() +} diff --git a/azalea-brigadier/src/arguments/mod.rs b/azalea-brigadier/src/arguments/mod.rs index dec39297..9d2c2cd0 100755 --- a/azalea-brigadier/src/arguments/mod.rs +++ b/azalea-brigadier/src/arguments/mod.rs @@ -1,4 +1,9 @@ mod argument_type; +pub mod bool_argument_type; +pub mod double_argument_type; +pub mod float_argument_type; pub mod integer_argument_type; +pub mod long_argument_type; +pub mod string_argument_type; pub use argument_type::ArgumentType; diff --git a/azalea-brigadier/src/arguments/string_argument_type.rs b/azalea-brigadier/src/arguments/string_argument_type.rs new file mode 100644 index 00000000..f23af3ba --- /dev/null +++ b/azalea-brigadier/src/arguments/string_argument_type.rs @@ -0,0 +1,53 @@ +use std::{any::Any, rc::Rc}; + +use crate::{ + context::CommandContext, exceptions::CommandSyntaxException, string_reader::StringReader, +}; + +use super::ArgumentType; + +pub enum StringArgument { + /// Match up until the next space. + SingleWord, + /// Same as single word unless the argument is wrapped in quotes, in which + /// case it can contain spaces. + QuotablePhrase, + /// Match the rest of the input. + GreedyPhrase, +} + +impl ArgumentType for StringArgument { + fn parse(&self, reader: &mut StringReader) -> Result, CommandSyntaxException> { + let result = match self { + StringArgument::SingleWord => reader.read_unquoted_string().to_string(), + StringArgument::QuotablePhrase => reader.read_string()?, + StringArgument::GreedyPhrase => { + let text = reader.remaining().to_string(); + reader.cursor = reader.total_length(); + text + } + }; + Ok(Rc::new(result)) + } +} + +/// Match up until the next space. +pub fn word() -> impl ArgumentType { + StringArgument::SingleWord +} +/// Same as single word unless the argument is wrapped in quotes, in which case +/// it can contain spaces. +pub fn string() -> impl ArgumentType { + StringArgument::QuotablePhrase +} +/// Match the rest of the input. +pub fn greedy_string() -> impl ArgumentType { + StringArgument::GreedyPhrase +} +pub fn get_string<'a, S>(context: &'a CommandContext, name: &str) -> Option { + context + .argument(name) + .unwrap() + .downcast_ref::() + .cloned() +} diff --git a/azalea-brigadier/src/lib.rs b/azalea-brigadier/src/lib.rs index eb670643..8b8e116e 100755 --- a/azalea-brigadier/src/lib.rs +++ b/azalea-brigadier/src/lib.rs @@ -10,3 +10,15 @@ pub mod parse_results; pub mod string_reader; pub mod suggestion; pub mod tree; + +pub mod prelude { + pub use crate::{ + arguments::{ + double_argument_type::double, float_argument_type::float, + integer_argument_type::integer, long_argument_type::long, string_argument_type::string, + }, + builder::{literal_argument_builder::literal, required_argument_builder::argument}, + command_dispatcher::CommandDispatcher, + context::CommandContext, + }; +} diff --git a/azalea-protocol/src/packets/game/clientbound_login_packet.rs b/azalea-protocol/src/packets/game/clientbound_login_packet.rs index bafead86..346c24fb 100755 --- a/azalea-protocol/src/packets/game/clientbound_login_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_login_packet.rs @@ -253,6 +253,8 @@ pub mod registry { pub struct DimensionTypeElement { pub height: u32, pub min_y: i32, + #[serde(flatten)] + pub _extra: HashMap, } /// The light level at which monsters can spawn. -- cgit v1.2.3 From 53d51a5ca92aa8ddea9d82b6b44ac7aaa06c2095 Mon Sep 17 00:00:00 2001 From: mat Date: Sun, 7 May 2023 02:50:52 -0500 Subject: more brigadier docs --- azalea-brigadier/README.md | 21 +++++- .../src/arguments/double_argument_type.rs | 2 +- .../src/arguments/float_argument_type.rs | 2 +- .../src/arguments/long_argument_type.rs | 2 +- azalea-brigadier/src/builder/argument_builder.rs | 41 +++++++++++ azalea-brigadier/src/command_dispatcher.rs | 27 ++++++- azalea-brigadier/src/lib.rs | 7 +- azalea-brigadier/tests/command_dispatcher_test.rs | 82 ++++++---------------- 8 files changed, 114 insertions(+), 70 deletions(-) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/README.md b/azalea-brigadier/README.md index c5aff629..6e573c8b 100755 --- a/azalea-brigadier/README.md +++ b/azalea-brigadier/README.md @@ -4,4 +4,23 @@ A Rust port of Mojang's [Brigadier](https://github.com/Mojang/brigadier) command # Examples -See the [tests](https://github.com/mat-1/azalea/tree/main/azalea-brigadier/tests). +```rust +use azalea_brigadier::prelude::*; +use std::sync::Arc; + +#[derive(Debug, PartialEq)] +struct CommandSource {} + +let mut subject = CommandDispatcher::new(); +subject.register(literal("foo").executes(|_| 42)); + +assert_eq!( + subject + .execute("foo", Arc::new(CommandSource {})) + .unwrap(), + 42 +); +``` + +See the [tests](https://github.com/mat-1/azalea/tree/main/azalea-brigadier/tests) for more. + diff --git a/azalea-brigadier/src/arguments/double_argument_type.rs b/azalea-brigadier/src/arguments/double_argument_type.rs index 117a11cc..d83bfb2a 100644 --- a/azalea-brigadier/src/arguments/double_argument_type.rs +++ b/azalea-brigadier/src/arguments/double_argument_type.rs @@ -45,7 +45,7 @@ impl ArgumentType for Double { pub fn double() -> impl ArgumentType { Double::default() } -pub fn get_integer(context: &CommandContext, name: &str) -> Option { +pub fn get_double(context: &CommandContext, name: &str) -> Option { context .argument(name) .unwrap() diff --git a/azalea-brigadier/src/arguments/float_argument_type.rs b/azalea-brigadier/src/arguments/float_argument_type.rs index f335f11a..0d194efe 100644 --- a/azalea-brigadier/src/arguments/float_argument_type.rs +++ b/azalea-brigadier/src/arguments/float_argument_type.rs @@ -45,7 +45,7 @@ impl ArgumentType for Float { pub fn float() -> impl ArgumentType { Float::default() } -pub fn get_integer(context: &CommandContext, name: &str) -> Option { +pub fn get_float(context: &CommandContext, name: &str) -> Option { context .argument(name) .unwrap() diff --git a/azalea-brigadier/src/arguments/long_argument_type.rs b/azalea-brigadier/src/arguments/long_argument_type.rs index 435dd92a..9b3469b6 100644 --- a/azalea-brigadier/src/arguments/long_argument_type.rs +++ b/azalea-brigadier/src/arguments/long_argument_type.rs @@ -45,7 +45,7 @@ impl ArgumentType for Long { pub fn long() -> impl ArgumentType { Long::default() } -pub fn get_integer(context: &CommandContext, name: &str) -> Option { +pub fn get_long(context: &CommandContext, name: &str) -> Option { context .argument(name) .unwrap() diff --git a/azalea-brigadier/src/builder/argument_builder.rs b/azalea-brigadier/src/builder/argument_builder.rs index c6f2146a..643a3bd0 100755 --- a/azalea-brigadier/src/builder/argument_builder.rs +++ b/azalea-brigadier/src/builder/argument_builder.rs @@ -43,15 +43,38 @@ impl ArgumentBuilder { } } + /// Continue building this node with a child node. + /// + /// ``` + /// # use azalea_brigadier::prelude::*; + /// # let mut subject = CommandDispatcher::<()>::new(); + /// literal("foo").then( + /// literal("bar").executes(|ctx: &CommandContext<()>| 42) + /// ) + /// # ; + /// ``` pub fn then(self, argument: ArgumentBuilder) -> Self { self.then_built(argument.build()) } + /// Add an already built child node to this node. + /// + /// You should usually use [`Self::then`] instead. pub fn then_built(mut self, argument: CommandNode) -> Self { self.arguments.add_child(&Arc::new(RwLock::new(argument))); self } + /// Set the command to be executed when this node is reached. If this is not + /// present on a node, it is not a valid command. + /// + /// ``` + /// # use azalea_brigadier::prelude::*; + /// # let mut subject = CommandDispatcher::<()>::new(); + /// # subject.register( + /// literal("foo").executes(|ctx: &CommandContext<()>| 42) + /// # ); + /// ``` pub fn executes(mut self, f: F) -> Self where F: Fn(&CommandContext) -> i32 + Send + Sync + 'static, @@ -60,6 +83,22 @@ impl ArgumentBuilder { self } + /// Set the requirement for this node to be considered. If this is not + /// present on a node, it is considered to always pass. + /// + /// ``` + /// # use azalea_brigadier::prelude::*; + /// # use std::sync::Arc; + /// # pub struct CommandSource { + /// # pub opped: bool, + /// # } + /// # let mut subject = CommandDispatcher::::new(); + /// # subject.register( + /// literal("foo") + /// .requires(|s: Arc| s.opped) + /// // ... + /// # .executes(|ctx: &CommandContext| 42) + /// # ); pub fn requires(mut self, requirement: F) -> Self where F: Fn(Arc) -> bool + Send + Sync + 'static, @@ -95,6 +134,8 @@ impl ArgumentBuilder { self } + /// Manually build this node into a [`CommandNode`]. You probably don't need + /// to do this yourself. pub fn build(self) -> CommandNode { let mut result = CommandNode { value: self.arguments.value, diff --git a/azalea-brigadier/src/command_dispatcher.rs b/azalea-brigadier/src/command_dispatcher.rs index a14b5009..595bc57d 100755 --- a/azalea-brigadier/src/command_dispatcher.rs +++ b/azalea-brigadier/src/command_dispatcher.rs @@ -11,6 +11,12 @@ use crate::{ use std::{cmp::Ordering, collections::HashMap, mem, rc::Rc, sync::Arc}; /// The root of the command tree. You need to make this to register commands. +/// +/// ``` +/// # use azalea_brigadier::prelude::*; +/// # struct CommandSource; +/// let mut subject = CommandDispatcher::::new(); +/// ``` pub struct CommandDispatcher where Self: Sync + Send, @@ -25,13 +31,22 @@ impl CommandDispatcher { } } + /// Add a new node to the root. + /// + /// ``` + /// # use azalea_brigadier::prelude::*; + /// # let mut subject = CommandDispatcher::<()>::new(); + /// subject.register(literal("foo").executes(|_| 42)); + /// ``` pub fn register(&mut self, node: ArgumentBuilder) -> Arc>> { let build = Arc::new(RwLock::new(node.build())); self.root.write().add_child(&build); build } - pub fn parse(&self, command: StringReader, source: Arc) -> ParseResults { + pub fn parse(&self, command: StringReader, source: S) -> ParseResults { + let source = Arc::new(source); + let context = CommandContextBuilder::new(self, source, self.root.clone(), command.cursor()); self.parse_nodes(&self.root, &command, context).unwrap() } @@ -140,11 +155,17 @@ impl CommandDispatcher { }) } + /// Parse and execute the command using the given input and context. The + /// number returned depends on the command, and may not be of significance. + /// + /// This is a shortcut for `Self::parse` and `Self::execute_parsed`. pub fn execute( &self, - input: StringReader, - source: Arc, + input: impl Into, + source: S, ) -> Result { + let input = input.into(); + let parse = self.parse(input, source); Self::execute_parsed(parse) } diff --git a/azalea-brigadier/src/lib.rs b/azalea-brigadier/src/lib.rs index 8b8e116e..161ef83a 100755 --- a/azalea-brigadier/src/lib.rs +++ b/azalea-brigadier/src/lib.rs @@ -14,8 +14,11 @@ pub mod tree; pub mod prelude { pub use crate::{ arguments::{ - double_argument_type::double, float_argument_type::float, - integer_argument_type::integer, long_argument_type::long, string_argument_type::string, + double_argument_type::{double, get_double}, + float_argument_type::{float, get_float}, + integer_argument_type::{get_integer, integer}, + long_argument_type::{get_long, long}, + string_argument_type::{get_string, greedy_string, string, word}, }, builder::{literal_argument_builder::literal, required_argument_builder::argument}, command_dispatcher::CommandDispatcher, diff --git a/azalea-brigadier/tests/command_dispatcher_test.rs b/azalea-brigadier/tests/command_dispatcher_test.rs index 4479cfa2..eecbf668 100755 --- a/azalea-brigadier/tests/command_dispatcher_test.rs +++ b/azalea-brigadier/tests/command_dispatcher_test.rs @@ -18,19 +18,6 @@ fn input_with_offset(input: &str, offset: usize) -> StringReader { result } -#[test] -fn create_and_execute_command() { - let mut subject = CommandDispatcher::new(); - subject.register(literal("foo").executes(|_| 42)); - - assert_eq!( - subject - .execute("foo".into(), Arc::new(CommandSource {})) - .unwrap(), - 42 - ); -} - #[test] fn create_and_execute_offset_command() { let mut subject = CommandDispatcher::new(); @@ -38,7 +25,7 @@ fn create_and_execute_offset_command() { assert_eq!( subject - .execute(input_with_offset("/foo", 1), Arc::new(CommandSource {})) + .execute(input_with_offset("/foo", 1), &CommandSource {}) .unwrap(), 42 ); @@ -50,18 +37,8 @@ fn create_and_merge_commands() { subject.register(literal("base").then(literal("foo").executes(|_| 42))); subject.register(literal("base").then(literal("bar").executes(|_| 42))); - assert_eq!( - subject - .execute("base foo".into(), Arc::new(CommandSource {})) - .unwrap(), - 42 - ); - assert_eq!( - subject - .execute("base bar".into(), Arc::new(CommandSource {})) - .unwrap(), - 42 - ); + assert_eq!(subject.execute("base foo", &CommandSource {}).unwrap(), 42); + assert_eq!(subject.execute("base bar", &CommandSource {}).unwrap(), 42); } #[test] @@ -70,7 +47,7 @@ fn execute_unknown_command() { subject.register(literal("bar")); subject.register(literal("baz")); - let execute_result = subject.execute("foo".into(), Arc::new(CommandSource {})); + let execute_result = subject.execute("foo", &CommandSource {}); let err = execute_result.err().unwrap(); match err.type_ { @@ -85,7 +62,7 @@ fn execute_impermissible_command() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").requires(|_| false)); - let execute_result = subject.execute("foo".into(), Arc::new(CommandSource {})); + let execute_result = subject.execute("foo", &CommandSource {}); let err = execute_result.err().unwrap(); match err.type_ { @@ -100,7 +77,7 @@ fn execute_empty_command() { let mut subject = CommandDispatcher::new(); subject.register(literal("")); - let execute_result = subject.execute("".into(), Arc::new(CommandSource {})); + let execute_result = subject.execute("", &CommandSource {}); let err = execute_result.err().unwrap(); match err.type_ { @@ -115,7 +92,7 @@ fn execute_unknown_subcommand() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").executes(|_| 42)); - let execute_result = subject.execute("foo bar".into(), Arc::new(CommandSource {})); + let execute_result = subject.execute("foo bar", &CommandSource {}); let err = execute_result.err().unwrap(); match err.type_ { @@ -130,7 +107,7 @@ fn execute_incorrect_literal() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").executes(|_| 42).then(literal("bar"))); - let execute_result = subject.execute("foo baz".into(), Arc::new(CommandSource {})); + let execute_result = subject.execute("foo baz", &CommandSource {}); let err = execute_result.err().unwrap(); match err.type_ { @@ -150,7 +127,7 @@ fn execute_ambiguous_incorrect_argument() { .then(literal("baz")), ); - let execute_result = subject.execute("foo unknown".into(), Arc::new(CommandSource {})); + let execute_result = subject.execute("foo unknown", &CommandSource {}); let err = execute_result.err().unwrap(); match err.type_ { @@ -172,12 +149,7 @@ fn execute_subcommand() { .executes(|_| 42), ); - assert_eq!( - subject - .execute("foo =".into(), Arc::new(CommandSource {})) - .unwrap(), - 100 - ); + assert_eq!(subject.execute("foo =", &CommandSource {}).unwrap(), 100); } #[test] @@ -185,7 +157,7 @@ fn parse_incomplete_literal() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").then(literal("bar").executes(|_| 42))); - let parse = subject.parse("foo ".into(), Arc::new(CommandSource {})); + let parse = subject.parse("foo ".into(), &CommandSource {}); assert_eq!(parse.reader.remaining(), " "); assert_eq!(parse.context.nodes.len(), 1); } @@ -195,7 +167,7 @@ fn parse_incomplete_argument() { let mut subject = CommandDispatcher::new(); subject.register(literal("foo").then(argument("bar", integer()).executes(|_| 42))); - let parse = subject.parse("foo ".into(), Arc::new(CommandSource {})); + let parse = subject.parse("foo ".into(), &CommandSource {}); assert_eq!(parse.reader.remaining(), " "); assert_eq!(parse.context.nodes.len(), 1); } @@ -210,12 +182,7 @@ fn execute_ambiguious_parent_subcommand() { .then(argument("right", integer()).then(argument("sub", integer()).executes(|_| 100))), ); - assert_eq!( - subject - .execute("test 1 2".into(), Arc::new(CommandSource {})) - .unwrap(), - 100 - ); + assert_eq!(subject.execute("test 1 2", &CommandSource {}).unwrap(), 100); } #[test] @@ -231,9 +198,7 @@ fn execute_ambiguious_parent_subcommand_via_redirect() { subject.register(literal("redirect").redirect(real)); assert_eq!( - subject - .execute("redirect 1 2".into(), Arc::new(CommandSource {})) - .unwrap(), + subject.execute("redirect 1 2", &CommandSource {}).unwrap(), 100 ); } @@ -248,7 +213,7 @@ fn execute_redirected_multiple_times() { let input = "redirected redirected actual"; - let parse = subject.parse(input.into(), Arc::new(CommandSource {})); + let parse = subject.parse(input.into(), &CommandSource {}); assert_eq!(parse.context.range.get(input), "redirected"); assert_eq!(parse.context.nodes.len(), 1); assert_eq!(*parse.context.root.read(), *root.read()); @@ -299,7 +264,7 @@ fn execute_redirected() { subject.register(literal("redirected").fork(subject.root.clone(), Arc::new(modifier))); let input = "redirected actual"; - let parse = subject.parse(input.into(), Arc::new(CommandSource {})); + let parse = subject.parse(input.into(), CommandSource {}); assert_eq!(parse.context.range.get(input), "redirected"); assert_eq!(parse.context.nodes.len(), 1); assert_eq!(*parse.context.root.read(), *subject.root.read()); @@ -314,7 +279,7 @@ fn execute_redirected() { assert_eq!(*parse.context.root.read(), *subject.root.read()); assert_eq!(parent.nodes[0].range, parent.range); assert_eq!(*parent.nodes[0].node.read(), *concrete_node.read()); - assert_eq!(parent.source, Arc::new(CommandSource {})); + assert_eq!(*parent.source, CommandSource {}); assert_eq!(CommandDispatcher::execute_parsed(parse).unwrap(), 2); } @@ -329,7 +294,7 @@ fn execute_orphaned_subcommand() { .executes(|_| 42), ); - let result = subject.execute("foo 5".into(), Arc::new(CommandSource {})); + let result = subject.execute("foo 5", &CommandSource {}); assert!(result.is_err()); let result = result.unwrap_err(); assert_eq!( @@ -346,12 +311,7 @@ fn execute_invalid_other() { subject.register(literal("w").executes(|_| panic!("This should not run"))); subject.register(literal("world").executes(|_| 42)); - assert_eq!( - subject - .execute("world".into(), Arc::new(CommandSource {})) - .unwrap(), - 42 - ); + assert_eq!(subject.execute("world", &CommandSource {}).unwrap(), 42); } #[test] @@ -364,7 +324,7 @@ fn parse_no_space_separator() { .executes(|_| 42), ); - let result = subject.execute("foo$".into(), Arc::new(CommandSource {})); + let result = subject.execute("foo$", &CommandSource {}); assert!(result.is_err()); let result = result.unwrap_err(); assert_eq!( @@ -384,7 +344,7 @@ fn execute_invalid_subcommand() { .executes(|_| 42), ); - let result = subject.execute("foo bar".into(), Arc::new(CommandSource {})); + let result = subject.execute("foo bar", &CommandSource {}); assert!(result.is_err()); let result = result.unwrap_err(); // this fails for some reason, i blame mojang -- cgit v1.2.3 From 80172e43640d2ec3c761611d2269d12a9abdd424 Mon Sep 17 00:00:00 2001 From: mat Date: Fri, 12 May 2023 18:53:08 +0000 Subject: fix warnings --- azalea-brigadier/src/arguments/bool_argument_type.rs | 2 +- azalea-brigadier/src/arguments/string_argument_type.rs | 2 +- azalea/src/pathfinder/astar.rs | 7 ++++++- 3 files changed, 8 insertions(+), 3 deletions(-) (limited to 'azalea-brigadier/src') diff --git a/azalea-brigadier/src/arguments/bool_argument_type.rs b/azalea-brigadier/src/arguments/bool_argument_type.rs index 01828c87..57fa8a03 100644 --- a/azalea-brigadier/src/arguments/bool_argument_type.rs +++ b/azalea-brigadier/src/arguments/bool_argument_type.rs @@ -12,7 +12,7 @@ impl ArgumentType for bool { } } -pub fn get_bool<'a, S>(context: &'a CommandContext, name: &str) -> Option { +pub fn get_bool(context: &CommandContext, name: &str) -> Option { context .argument(name) .unwrap() diff --git a/azalea-brigadier/src/arguments/string_argument_type.rs b/azalea-brigadier/src/arguments/string_argument_type.rs index f23af3ba..27363bd4 100644 --- a/azalea-brigadier/src/arguments/string_argument_type.rs +++ b/azalea-brigadier/src/arguments/string_argument_type.rs @@ -44,7 +44,7 @@ pub fn string() -> impl ArgumentType { pub fn greedy_string() -> impl ArgumentType { StringArgument::GreedyPhrase } -pub fn get_string<'a, S>(context: &'a CommandContext, name: &str) -> Option { +pub fn get_string(context: &CommandContext, name: &str) -> Option { context .argument(name) .unwrap() diff --git a/azalea/src/pathfinder/astar.rs b/azalea/src/pathfinder/astar.rs index 858e7720..65caf337 100644 --- a/azalea/src/pathfinder/astar.rs +++ b/azalea/src/pathfinder/astar.rs @@ -94,7 +94,7 @@ pub struct Edge { pub cost: W, } -#[derive(PartialOrd, PartialEq)] +#[derive(PartialEq)] pub struct Weight(W); impl Ord for Weight { fn cmp(&self, other: &Self) -> std::cmp::Ordering { @@ -104,3 +104,8 @@ impl Ord for Weight { } } impl Eq for Weight {} +impl PartialOrd for Weight { + fn partial_cmp(&self, other: &Self) -> Option { + self.0.partial_cmp(&other.0) + } +} -- cgit v1.2.3