chore(refactor): add pumpkin-command crate
This commit is contained in:
1 parent
b961f97760
commit
4f88d77ab1
95 files changed
+2978
-2022
No files matched your search
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "pumpkin-command"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
pumpkin-util.workspace = true
|
||||
pumpkin-protocol = { workspace = true, features = ["default"] }
|
||||
pumpkin-data = { workspace = true, features = ["default"] }
|
||||
pumpkin-nbt.workspace = true
|
||||
pumpkin-world.workspace = true
|
||||
pumpkin-codecs.workspace = true
|
||||
|
||||
uuid.workspace = true
|
||||
rustc-hash.workspace = true
|
||||
thiserror.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
itertools.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,589 @@
|
||||
use crate::argument_builder::private::Sealed;
|
||||
use crate::argument_types::argument_type::AnyArgumentType;
|
||||
use crate::node::detached::{
|
||||
ArgumentDetachedNode, CommandDetachedNode, DetachedNode, GlobalNodeId, LiteralDetachedNode,
|
||||
};
|
||||
use crate::node::{
|
||||
Command, CommandExecutor, RedirectModifier, Redirection, Requirement, Requirements,
|
||||
};
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::suggestion::provider::SuggestionProvider;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Represents an intermediate struct for
|
||||
/// building arguments for commands.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// This is an implementation detail.
|
||||
struct CommonArgumentBuilder<S: CommandSource = DummySource> {
|
||||
pub global_id: GlobalNodeId,
|
||||
pub arguments: FxHashMap<String, DetachedNode<S>>,
|
||||
pub command: Option<Command<S>>,
|
||||
pub requirements: Requirements<S>,
|
||||
pub target: Option<Redirection>,
|
||||
pub modifier: RedirectModifier<S>,
|
||||
pub forks: bool,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> CommonArgumentBuilder<S> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
global_id: GlobalNodeId::new(),
|
||||
arguments: FxHashMap::default(),
|
||||
command: None,
|
||||
requirements: Requirements::new(),
|
||||
target: None,
|
||||
modifier: RedirectModifier::KeepSource,
|
||||
forks: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> Default for CommonArgumentBuilder<S> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// A short-form way to create a new [`CommandArgumentBuilder`]
|
||||
/// from a literal and a command description.
|
||||
///
|
||||
/// This can be imported directly without a prefix, or imported with the `argument_builder::` prefix. Here's an example of usage:
|
||||
/// ```
|
||||
/// use pumpkin_command::argument_builder::command;
|
||||
/// use pumpkin_command::source::DummySource;
|
||||
///
|
||||
/// let builder = command::<DummySource>("foo", "A test command");
|
||||
/// ```
|
||||
///
|
||||
/// The builder returned will eventually construct a [`CommandDetachedNode`].
|
||||
/// This node can then be registered into a dispatcher.
|
||||
pub fn command<S: CommandSource>(
|
||||
literal: impl Into<Cow<'static, str>>,
|
||||
description: impl Into<Cow<'static, str>>,
|
||||
) -> CommandArgumentBuilder<S> {
|
||||
CommandArgumentBuilder::new(literal, description)
|
||||
}
|
||||
|
||||
/// A short-form way to create a new [`LiteralArgumentBuilder`]
|
||||
/// from a literal.
|
||||
///
|
||||
/// This can be imported directly without a prefix, or imported with the `argument_builder::` prefix. Here's an example of usage:
|
||||
/// ```
|
||||
/// use pumpkin_command::argument_builder::literal;
|
||||
/// use pumpkin_command::source::DummySource;
|
||||
///
|
||||
/// let builder = literal::<DummySource>("bar");
|
||||
/// ```
|
||||
///
|
||||
/// The builder returned will eventually construct a [`LiteralDetachedNode`].
|
||||
pub fn literal<S: CommandSource>(
|
||||
literal: impl Into<Cow<'static, str>>,
|
||||
) -> LiteralArgumentBuilder<S> {
|
||||
LiteralArgumentBuilder::new(literal)
|
||||
}
|
||||
|
||||
/// A short-form way to create a new [`RequiredArgumentBuilder`]
|
||||
/// from an argument type and name.
|
||||
///
|
||||
/// This can be imported directly without a prefix, or imported with the `argument_builder::` prefix. Here's an example of usage:
|
||||
/// ```
|
||||
/// use pumpkin_command::{
|
||||
/// argument_builder::argument,
|
||||
/// argument_types::core::integer::IntegerArgumentType,
|
||||
/// source::DummySource,
|
||||
/// };
|
||||
///
|
||||
/// let argument_builder = argument::<DummySource>("bar", IntegerArgumentType::new(1, 10));
|
||||
/// ```
|
||||
///
|
||||
/// The builder returned will eventually construct a [`ArgumentDetachedNode`].
|
||||
pub fn argument<S: CommandSource>(
|
||||
name: impl Into<Cow<'static, str>>,
|
||||
arg_type: impl AnyArgumentType<S> + 'static,
|
||||
) -> RequiredArgumentBuilder<S> {
|
||||
RequiredArgumentBuilder::new(name, arg_type)
|
||||
}
|
||||
|
||||
/// A builder that builds a literal, non-command [`DetachedNode`].
|
||||
pub struct LiteralArgumentBuilder<S: CommandSource = DummySource> {
|
||||
common: CommonArgumentBuilder<S>,
|
||||
literal: Cow<'static, str>,
|
||||
}
|
||||
|
||||
/// A builder that builds a command [`DetachedNode`].
|
||||
pub struct CommandArgumentBuilder<S: CommandSource = DummySource> {
|
||||
common: CommonArgumentBuilder<S>,
|
||||
literal: Cow<'static, str>,
|
||||
description: Cow<'static, str>,
|
||||
source: Option<String>,
|
||||
}
|
||||
|
||||
/// A builder that builds an argument [`DetachedNode`].
|
||||
pub struct RequiredArgumentBuilder<S: CommandSource = DummySource> {
|
||||
common: CommonArgumentBuilder<S>,
|
||||
name: Cow<'static, str>,
|
||||
argument_type: Arc<dyn AnyArgumentType<S>>,
|
||||
suggestion_provider: Option<Arc<dyn SuggestionProvider<S>>>,
|
||||
}
|
||||
|
||||
mod private {
|
||||
// We want to make this trait private so that
|
||||
// we can implement it for only our
|
||||
// argument builders defined here.
|
||||
pub trait Sealed {}
|
||||
}
|
||||
|
||||
pub trait ArgumentBuilder<
|
||||
S: CommandSource = DummySource,
|
||||
N: Into<DetachedNode<S>> = DetachedNode<S>,
|
||||
>: Sized + Sealed
|
||||
{
|
||||
/// Puts an argument to be specified, right after this one is specified.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if this node is redirected to another node, or the child
|
||||
/// provided is of the type [`CommandDetachedNode`].
|
||||
#[must_use]
|
||||
fn then(self, child: impl Into<DetachedNode<S>>) -> Self;
|
||||
|
||||
/// Gets the command to execute for the node being built.
|
||||
#[must_use]
|
||||
fn command(&self) -> Option<Command<S>>;
|
||||
|
||||
/// Sets the command to execute for the node being built.
|
||||
#[must_use]
|
||||
fn executes(self, command: impl CommandExecutor<S> + 'static) -> Self {
|
||||
self.executes_arc(Arc::new(command))
|
||||
}
|
||||
|
||||
/// Sets the command to execute for the node being built.
|
||||
#[must_use]
|
||||
fn executes_arc(self, command: Arc<dyn CommandExecutor<S> + 'static>) -> Self;
|
||||
|
||||
/// Sets the redirect target of the node being built to another, without a modifier.
|
||||
#[must_use]
|
||||
fn redirect(self, redirection: impl Into<Redirection>) -> Self;
|
||||
|
||||
/// Sets the redirect target of the node being built to another, with a given modifier.
|
||||
#[must_use]
|
||||
fn redirect_with_modifier(
|
||||
self,
|
||||
redirection: impl Into<Redirection>,
|
||||
redirect_modifier: RedirectModifier<S>,
|
||||
) -> Self;
|
||||
|
||||
/// Forks the given context, using multiple for later.
|
||||
#[must_use]
|
||||
fn fork(
|
||||
self,
|
||||
redirection: impl Into<Redirection>,
|
||||
redirect_modifier: RedirectModifier<S>,
|
||||
) -> Self;
|
||||
|
||||
/// Forwards the given context, with the given `fork` flag.
|
||||
#[must_use]
|
||||
fn forward(
|
||||
self,
|
||||
redirection: impl Into<Redirection>,
|
||||
redirect_modifier: RedirectModifier<S>,
|
||||
fork: bool,
|
||||
) -> Self;
|
||||
|
||||
/// Gets a reference to the arguments of the node to be built.
|
||||
#[must_use]
|
||||
fn arguments(&self) -> &FxHashMap<String, DetachedNode<S>>;
|
||||
|
||||
/// Gets the node to which the node being built by this [`ArgumentBuilder`] redirects.
|
||||
#[must_use]
|
||||
fn target(&self) -> Option<Redirection>;
|
||||
|
||||
/// Adds a given predicate to this list of requirements of the node being built.
|
||||
///
|
||||
/// This means that it is possible to chain multiple predicates together, which must all
|
||||
/// be satisfied.
|
||||
///
|
||||
/// Permissions can also be inserted directly into this method as a `requirement`.
|
||||
#[must_use]
|
||||
fn requires(self, requirement: impl Into<Requirement<S>>) -> Self;
|
||||
|
||||
/// Overwrites the current requirements of this node to a new value.
|
||||
#[must_use]
|
||||
fn overwrite_requirements(self, requirements: Requirements<S>) -> Self;
|
||||
|
||||
/// Gets the redirect modifier of the node this [`ArgumentBuilder`] is building.
|
||||
#[must_use]
|
||||
fn redirect_modifier(&self) -> RedirectModifier<S>;
|
||||
|
||||
/// Whether this builder forks.
|
||||
#[must_use]
|
||||
fn forks(&self) -> bool;
|
||||
|
||||
/// Returns the 'future [`GlobalNodeId`]' of the node that will be produced by this Builder.
|
||||
/// Very useful for redirects.
|
||||
#[must_use]
|
||||
fn id(&self) -> GlobalNodeId;
|
||||
|
||||
/// Builds the node represented by this builder, consuming itself in the process.
|
||||
#[must_use]
|
||||
fn build(self) -> N;
|
||||
}
|
||||
|
||||
// Implement the private trait for our builders!
|
||||
impl<S: CommandSource> Sealed for LiteralArgumentBuilder<S> {}
|
||||
impl<S: CommandSource> Sealed for CommandArgumentBuilder<S> {}
|
||||
impl<S: CommandSource> Sealed for RequiredArgumentBuilder<S> {}
|
||||
|
||||
/// Helper macro to implement repeated code of `ArgumentBuilder` for our types.
|
||||
macro_rules! impl_boilerplate_argument_builder {
|
||||
($S:ident) => {
|
||||
fn then(mut self, argument: impl Into<DetachedNode<$S>>) -> Self {
|
||||
assert!(
|
||||
self.target().is_none(),
|
||||
"Cannot add children to a redirected node"
|
||||
);
|
||||
let node = argument.into();
|
||||
assert!(
|
||||
!matches!(node, DetachedNode::Command(_)),
|
||||
"Cannot add a CommandDetachedNode as a child of a builder"
|
||||
);
|
||||
|
||||
self.common.arguments.insert(node.name(), node);
|
||||
self
|
||||
}
|
||||
|
||||
fn command(&self) -> Option<Command<$S>> {
|
||||
self.common.command.clone()
|
||||
}
|
||||
|
||||
fn executes_arc(mut self, command: Arc<dyn CommandExecutor<$S> + 'static>) -> Self {
|
||||
self.common.command = Some(command);
|
||||
self
|
||||
}
|
||||
|
||||
fn requires(mut self, requirement: impl Into<Requirement<$S>>) -> Self {
|
||||
self.common.requirements.0.push(requirement.into());
|
||||
self
|
||||
}
|
||||
|
||||
fn overwrite_requirements(mut self, requirements: Requirements<$S>) -> Self {
|
||||
self.common.requirements = requirements;
|
||||
self
|
||||
}
|
||||
|
||||
fn redirect(self, redirection: impl Into<Redirection>) -> Self {
|
||||
self.forward(redirection.into(), RedirectModifier::KeepSource, false)
|
||||
}
|
||||
|
||||
fn redirect_with_modifier(
|
||||
self,
|
||||
redirection: impl Into<Redirection>,
|
||||
redirect_modifier: RedirectModifier<$S>,
|
||||
) -> Self {
|
||||
self.forward(redirection.into(), redirect_modifier, false)
|
||||
}
|
||||
|
||||
fn fork(
|
||||
self,
|
||||
redirection: impl Into<Redirection>,
|
||||
redirect_modifier: RedirectModifier<$S>,
|
||||
) -> Self {
|
||||
self.forward(redirection.into(), redirect_modifier, true)
|
||||
}
|
||||
|
||||
fn forward(
|
||||
mut self,
|
||||
redirection: impl Into<Redirection>,
|
||||
redirect_modifier: RedirectModifier<$S>,
|
||||
fork: bool,
|
||||
) -> Self {
|
||||
assert!(
|
||||
self.common.arguments.is_empty(),
|
||||
"Cannot forward a node with children. The node must have no children to redirect somewhere else"
|
||||
);
|
||||
self.common.target = Some(redirection.into());
|
||||
self.common.modifier = redirect_modifier;
|
||||
self.common.forks = fork;
|
||||
self
|
||||
}
|
||||
|
||||
fn arguments(&self) -> &FxHashMap<String, DetachedNode<$S>> {
|
||||
&self.common.arguments
|
||||
}
|
||||
|
||||
fn target(&self) -> Option<Redirection> {
|
||||
self.common.target.clone()
|
||||
}
|
||||
|
||||
fn redirect_modifier(&self) -> RedirectModifier<$S> {
|
||||
self.common.modifier.clone()
|
||||
}
|
||||
|
||||
fn forks(&self) -> bool {
|
||||
self.common.forks
|
||||
}
|
||||
|
||||
fn id(&self) -> GlobalNodeId {
|
||||
self.common.global_id
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Helper macro to generate `From` impl blocks for each builder.
|
||||
macro_rules! impl_builder_from_impls {
|
||||
($builder: ident => $detached_node: ident) => {
|
||||
impl<S: CommandSource> From<$builder<S>> for $detached_node<S> {
|
||||
fn from(value: $builder<S>) -> Self {
|
||||
value.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> From<$builder<S>> for DetachedNode<S> {
|
||||
fn from(value: $builder<S>) -> Self {
|
||||
value.build().into()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_builder_from_impls!(LiteralArgumentBuilder => LiteralDetachedNode);
|
||||
impl_builder_from_impls!(CommandArgumentBuilder => CommandDetachedNode);
|
||||
impl_builder_from_impls!(RequiredArgumentBuilder => ArgumentDetachedNode);
|
||||
|
||||
impl<S: CommandSource> LiteralArgumentBuilder<S> {
|
||||
/// Creates a new [`LiteralArgumentBuilder`] from a literal.
|
||||
pub fn new(literal: impl Into<Cow<'static, str>>) -> Self {
|
||||
Self {
|
||||
common: CommonArgumentBuilder::new(),
|
||||
literal: literal.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> CommandArgumentBuilder<S> {
|
||||
/// Creates a new [`CommandArgumentBuilder`] from a literal and a command description.
|
||||
pub fn new(
|
||||
literal: impl Into<Cow<'static, str>>,
|
||||
description: impl Into<Cow<'static, str>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
common: CommonArgumentBuilder::new(),
|
||||
literal: literal.into(),
|
||||
description: description.into(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the source (e.g. plugin name) that registered this command.
|
||||
#[must_use]
|
||||
pub fn with_source(mut self, source: impl Into<String>) -> Self {
|
||||
self.source = Some(source.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> RequiredArgumentBuilder<S> {
|
||||
/// Creates a new [`RequiredArgumentBuilder`] from a name and an argument type.
|
||||
pub fn new(
|
||||
name: impl Into<Cow<'static, str>>,
|
||||
arg_type: impl AnyArgumentType<S> + 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
common: CommonArgumentBuilder::new(),
|
||||
name: name.into(),
|
||||
argument_type: Arc::new(arg_type),
|
||||
suggestion_provider: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the [`SuggestionProvider`] of this builder for the `ArgumentDetachedNode`.
|
||||
#[must_use]
|
||||
pub fn suggests(self, provider: impl SuggestionProvider<S> + 'static) -> Self {
|
||||
self.suggests_arc(Arc::new(provider))
|
||||
}
|
||||
|
||||
/// Sets the [`SuggestionProvider`] of this builder for the `ArgumentDetachedNode`.
|
||||
#[must_use]
|
||||
pub fn suggests_arc(mut self, provider: Arc<dyn SuggestionProvider<S>>) -> Self {
|
||||
self.suggestion_provider = Some(provider);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> ArgumentBuilder<S, LiteralDetachedNode<S>> for LiteralArgumentBuilder<S> {
|
||||
impl_boilerplate_argument_builder!(S);
|
||||
|
||||
fn build(self) -> LiteralDetachedNode<S> {
|
||||
let mut node = LiteralDetachedNode::new(
|
||||
self.common.global_id,
|
||||
self.literal,
|
||||
self.common.command,
|
||||
self.common.requirements,
|
||||
self.common.target,
|
||||
self.common.modifier,
|
||||
self.common.forks,
|
||||
);
|
||||
node.children = self.common.arguments;
|
||||
node
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> ArgumentBuilder<S, CommandDetachedNode<S>> for CommandArgumentBuilder<S> {
|
||||
impl_boilerplate_argument_builder!(S);
|
||||
|
||||
fn build(self) -> CommandDetachedNode<S> {
|
||||
let mut node = CommandDetachedNode::new(
|
||||
self.common.global_id,
|
||||
self.literal,
|
||||
self.description,
|
||||
self.common.command,
|
||||
self.common.requirements,
|
||||
self.common.target,
|
||||
self.common.modifier,
|
||||
self.common.forks,
|
||||
);
|
||||
node.meta.source = self.source;
|
||||
node.children = self.common.arguments;
|
||||
node
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> ArgumentBuilder<S, ArgumentDetachedNode<S>> for RequiredArgumentBuilder<S> {
|
||||
impl_boilerplate_argument_builder!(S);
|
||||
|
||||
fn build(self) -> ArgumentDetachedNode<S> {
|
||||
let mut node = ArgumentDetachedNode::new(
|
||||
self.common.global_id,
|
||||
self.name,
|
||||
self.argument_type,
|
||||
self.common.command,
|
||||
self.common.requirements,
|
||||
self.common.target,
|
||||
self.common.modifier,
|
||||
self.common.forks,
|
||||
self.suggestion_provider,
|
||||
);
|
||||
node.children = self.common.arguments;
|
||||
node
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::argument_builder::{ArgumentBuilder, argument, command, literal};
|
||||
use crate::argument_types::core::double::DoubleArgumentType;
|
||||
use crate::argument_types::core::integer::IntegerArgumentType;
|
||||
use crate::argument_types::core::string::StringArgumentType;
|
||||
use crate::errors::error_types;
|
||||
use crate::node::Redirection;
|
||||
use crate::node::attached::AttachedNode;
|
||||
use crate::node::tree::Tree;
|
||||
use crate::source::DummySource;
|
||||
use crate::string_reader::StringReader;
|
||||
|
||||
#[test]
|
||||
fn literal_one() {
|
||||
let builder = literal::<DummySource>("test");
|
||||
let node = builder.build();
|
||||
|
||||
assert_eq!(node.meta.literal, "test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_one() {
|
||||
let builder = argument::<DummySource>("test", IntegerArgumentType::new(1, 10));
|
||||
let node = builder.build();
|
||||
|
||||
assert_eq!(node.meta.name, "test");
|
||||
|
||||
let mut reader1 = StringReader::new("5");
|
||||
let mut reader2 = StringReader::new("11");
|
||||
|
||||
let boxed_result = node
|
||||
.meta
|
||||
.argument_type
|
||||
.parse(&mut reader1)
|
||||
.expect("The parsing should not have errored");
|
||||
let result = boxed_result
|
||||
.downcast::<i32>()
|
||||
.expect("Downcasting shouldn't have failed");
|
||||
assert_eq!(result, Box::new(5));
|
||||
|
||||
let error = node
|
||||
.meta
|
||||
.argument_type
|
||||
.parse(&mut reader2)
|
||||
.expect_err("The parsing should have errored as 11 is outside the range");
|
||||
assert!(error.is(&error_types::INTEGER_TOO_HIGH));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_multiple() {
|
||||
let mut builder = command::<DummySource>("letter", "A test command");
|
||||
for letter in 'a'..='z' {
|
||||
// Add a node per letter for the argument.
|
||||
let letter_string = letter.to_string();
|
||||
builder = builder.then(literal(letter_string));
|
||||
}
|
||||
|
||||
let node = builder.build();
|
||||
assert_eq!(node.children.len(), 26);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_multiple() {
|
||||
let builder = command::<DummySource>("test", "A test command")
|
||||
.then(argument("number", DoubleArgumentType::any()))
|
||||
.then(argument("word", StringArgumentType::SingleWord));
|
||||
|
||||
let node = builder.build();
|
||||
assert_eq!(node.children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirect() {
|
||||
let builder = command::<DummySource>("test", "A test command").redirect(Redirection::Root);
|
||||
|
||||
let mut tree = Tree::<DummySource>::new();
|
||||
let node_id = tree.add_child_to_root(builder);
|
||||
|
||||
let node = &tree[node_id];
|
||||
let redirect = node
|
||||
.redirect
|
||||
.expect("Redirection should exist as it was added before");
|
||||
|
||||
let target_id = tree
|
||||
.resolve(redirect)
|
||||
.expect("Target should have been resolved properly");
|
||||
let target = &tree[target_id];
|
||||
|
||||
assert!(matches!(target, AttachedNode::Root(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic = "Cannot forward a node with children. The node must have no children to redirect somewhere else"]
|
||||
fn redirect_after_child() {
|
||||
let _ = command::<DummySource>("test", "A test command")
|
||||
.then(literal("child"))
|
||||
.redirect(Redirection::Root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic = "Cannot add children to a redirected node"]
|
||||
fn redirect_before_child() {
|
||||
let _ = command::<DummySource>("test", "A test command")
|
||||
.redirect(Redirection::Root)
|
||||
.then(literal("child"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic = "Cannot add a CommandDetachedNode as a child of a builder"]
|
||||
fn add_command_as_child() {
|
||||
let _ = command::<DummySource>("foo", "A test command")
|
||||
.then(command("bar", "Another test command"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::suggestion::suggestions::Suggestions;
|
||||
use crate::suggestion::suggestions::SuggestionsBuilder;
|
||||
use crate::{errors::command_syntax_error::CommandSyntaxError, string_reader::StringReader};
|
||||
use std::any::Any;
|
||||
|
||||
pub type JavaClientArgumentType = pumpkin_protocol::java::client::play::ArgumentType;
|
||||
pub type ParseWithSourceAnyResult = Result<Box<dyn Any + Send + Sync>, CommandSyntaxError>;
|
||||
|
||||
/// Represents an argument type that parses a particular type `Item`.
|
||||
pub trait ArgumentType<S: CommandSource = DummySource>: Send + Sync {
|
||||
/// The data type that this argument type parses.
|
||||
type Item: Send + Sync;
|
||||
|
||||
/// Parses a `T` by using a [`StringReader`]. Call this only if you have no source.
|
||||
///
|
||||
/// Errors should be propagated using the `?` operator, which will
|
||||
/// replicate Brigadier's behavior of exceptions.
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError>;
|
||||
|
||||
/// Parses a `T` by using a [`StringReader`],
|
||||
/// along with a particular source of type `S`.
|
||||
///
|
||||
/// Errors should be propagated using the `?` operator, which will
|
||||
/// replicate Brigadier's behavior of exceptions.
|
||||
fn parse_with_source(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
_source: &S,
|
||||
) -> Result<Self::Item, CommandSyntaxError> {
|
||||
self.parse(reader)
|
||||
}
|
||||
|
||||
/// Provides a list of suggestions from this argument type.
|
||||
#[must_use]
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
_builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
Suggestions::empty()
|
||||
}
|
||||
|
||||
/// Returns the Java client-side parser used for this argument type.
|
||||
#[must_use]
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType;
|
||||
|
||||
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
||||
/// is returned.
|
||||
#[must_use]
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Gets a selected list of examples which are considered
|
||||
/// valid when parsed into type `T`.
|
||||
///
|
||||
/// Used for conflicts.
|
||||
#[must_use]
|
||||
fn examples(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent other crates from using this trait
|
||||
// Thus, we can effectively 'seal' our trait meant
|
||||
// only for `AnyArgumentType`.
|
||||
mod sealed {
|
||||
/// Private trait to ensure only types implementing `ArgumentType` can implement `AnyArgumentType`.
|
||||
pub trait Sealed<S> {}
|
||||
}
|
||||
|
||||
/// Represents an argument type with any parsable type.
|
||||
pub trait AnyArgumentType<S: CommandSource = DummySource>: sealed::Sealed<S> + Send + Sync {
|
||||
/// Parses a value by using a [`StringReader`]. Call this only if you have no source.
|
||||
///
|
||||
/// Errors should be propagated using the `?` operator, which will
|
||||
/// replicate Brigadier's behavior of exceptions.
|
||||
fn parse(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
) -> Result<Box<dyn Any + Send + Sync>, CommandSyntaxError>;
|
||||
|
||||
/// Parses a value by using a [`StringReader`], with a given source.
|
||||
///
|
||||
/// Errors should be propagated using the `?` operator, which will
|
||||
/// replicate Brigadier's behavior of exceptions.
|
||||
fn parse_with_source(&self, reader: &mut StringReader, source: &S) -> ParseWithSourceAnyResult;
|
||||
|
||||
/// Provides a list of suggestions from this argument type.
|
||||
#[must_use]
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions;
|
||||
|
||||
/// Returns the Java client-side parser used for this argument type.
|
||||
#[must_use]
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType;
|
||||
|
||||
/// Overrides the suggestion providers provided from this argument if a [`Some`] containing them
|
||||
/// is returned.
|
||||
#[must_use]
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Gets a selected list of examples which are considered
|
||||
/// valid when parsed into type `T`.
|
||||
///
|
||||
/// Used for conflicts.
|
||||
#[must_use]
|
||||
fn examples(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
}
|
||||
|
||||
// Implement our private trait for all argument types.
|
||||
impl<U: ArgumentType<S>, S: CommandSource> sealed::Sealed<S> for U {}
|
||||
|
||||
impl<U: ArgumentType<S> + 'static, S: CommandSource + 'static> AnyArgumentType<S> for U
|
||||
where
|
||||
U::Item: 'static,
|
||||
{
|
||||
fn parse(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
) -> Result<Box<dyn Any + Send + Sync>, CommandSyntaxError> {
|
||||
match self.parse(reader) {
|
||||
Ok(value) => Ok(Box::new(value)),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_with_source(&self, reader: &mut StringReader, source: &S) -> ParseWithSourceAnyResult {
|
||||
match self.parse_with_source(reader, source) {
|
||||
Ok(value) => {
|
||||
let value: Box<dyn Any + Send + Sync> = Box::new(value);
|
||||
Ok(value)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
self.list_suggestions(context, builder)
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
self.client_side_parser()
|
||||
}
|
||||
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
self.override_suggestion_providers()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
self.examples()
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use crate::{
|
||||
argument_types::FromStringReader,
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
context::command_context::CommandContext,
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
errors::error_types::CommandErrorType,
|
||||
string_reader::StringReader,
|
||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||
};
|
||||
use pumpkin_data::attributes::Attributes;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const INVALID_ATTRIBUTE_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ID_INVALID,
|
||||
translation::java::ARGUMENT_ID_INVALID,
|
||||
);
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct AttributeArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for AttributeArgumentType {
|
||||
type Item = Attributes;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let identifier = Identifier::from_reader(reader)?;
|
||||
let ident_str = identifier.to_string();
|
||||
|
||||
let attr = Attributes::ALL
|
||||
.iter()
|
||||
.find(|a| a.name == ident_str)
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
INVALID_ATTRIBUTE_ERROR_TYPE.create(reader, TextComponent::text(ident_str))
|
||||
})?;
|
||||
|
||||
Ok(attr)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Resource {
|
||||
identifier: Identifier::vanilla_static("attribute"),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder
|
||||
.filter_and_suggest_iter(Attributes::ALL.iter().map(|a| a.name))
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl AttributeArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Attributes, CommandSyntaxError> {
|
||||
context.get_argument::<Attributes>(name).cloned()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use crate::{
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
context::command_context::CommandContext,
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
errors::error_types::CommandErrorType,
|
||||
string_reader::StringReader,
|
||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||
};
|
||||
use pumpkin_data::{Block, translation};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const INVALID_BLOCK_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_BLOCK_ID_INVALID,
|
||||
translation::java::ARGUMENT_BLOCK_ID_INVALID,
|
||||
);
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct BlockArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for BlockArgumentType {
|
||||
type Item = &'static Block;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == ':' || c == '/' || c == '.' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let block_name = &reader.string()[start..reader.cursor()];
|
||||
let normalized = if block_name.contains(':') {
|
||||
block_name.to_string()
|
||||
} else {
|
||||
format!("minecraft:{block_name}")
|
||||
};
|
||||
|
||||
Block::from_name(&normalized)
|
||||
.ok_or_else(|| INVALID_BLOCK_ERROR_TYPE.create(reader, TextComponent::text(normalized)))
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::BlockState
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'static Block, CommandSyntaxError> {
|
||||
context.get_argument::<&'static Block>(name).copied()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use pumpkin_data::tag::{RegistryKey, get_tag_ids};
|
||||
use pumpkin_data::{Block, translation};
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::argument_types::block::INVALID_BLOCK_ERROR_TYPE;
|
||||
use crate::argument_types::nbt::NbtCompoundArgumentType;
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub const ERROR_UNKNOWN_TAG: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENTS_BLOCK_TAG_UNKNOWN,
|
||||
translation::java::ARGUMENTS_BLOCK_TAG_UNKNOWN,
|
||||
);
|
||||
|
||||
pub const ERROR_NO_VALUE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_BLOCK_PROPERTY_NOVALUE,
|
||||
translation::java::ARGUMENT_BLOCK_PROPERTY_NOVALUE,
|
||||
);
|
||||
|
||||
pub const ERROR_UNCLOSED_PROPERTIES: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_BLOCK_PROPERTY_UNCLOSED,
|
||||
translation::java::ARGUMENT_BLOCK_PROPERTY_UNCLOSED,
|
||||
);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum BlockPredicate {
|
||||
Block {
|
||||
block: &'static Block,
|
||||
properties: HashMap<String, String>,
|
||||
nbt: Option<NbtCompound>,
|
||||
},
|
||||
Tag {
|
||||
tag_name: String,
|
||||
block_ids: Vec<u16>,
|
||||
properties: HashMap<String, String>,
|
||||
nbt: Option<NbtCompound>,
|
||||
},
|
||||
}
|
||||
|
||||
impl BlockPredicate {
|
||||
#[must_use]
|
||||
pub fn test(&self, block: &Block) -> bool {
|
||||
match self {
|
||||
Self::Block {
|
||||
block: expected, ..
|
||||
} => block.id == expected.id,
|
||||
Self::Tag { block_ids, .. } => block_ids.contains(&block.id.as_u16()),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn requires_nbt(&self) -> bool {
|
||||
match self {
|
||||
Self::Block { nbt, .. } | Self::Tag { nbt, .. } => nbt.is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_properties(
|
||||
reader: &mut StringReader,
|
||||
) -> Result<HashMap<String, String>, CommandSyntaxError> {
|
||||
let mut properties = HashMap::new();
|
||||
if reader.peek() == Some('[') {
|
||||
reader.skip();
|
||||
reader.skip_whitespace();
|
||||
while reader.can_read_char() && reader.peek() != Some(']') {
|
||||
let start_key = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let key = reader.string()[start_key..reader.cursor()].to_string();
|
||||
reader.skip_whitespace();
|
||||
if reader.peek() != Some('=') {
|
||||
return Err(ERROR_NO_VALUE.create(reader, TextComponent::text(key)));
|
||||
}
|
||||
reader.skip();
|
||||
reader.skip_whitespace();
|
||||
let start_val = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let val = reader.string()[start_val..reader.cursor()].to_string();
|
||||
properties.insert(key, val);
|
||||
reader.skip_whitespace();
|
||||
if reader.peek() == Some(',') {
|
||||
reader.skip();
|
||||
reader.skip_whitespace();
|
||||
} else if reader.peek() == Some(']') {
|
||||
break;
|
||||
} else {
|
||||
return Err(ERROR_UNCLOSED_PROPERTIES.create_without_context());
|
||||
}
|
||||
}
|
||||
if reader.peek() == Some(']') {
|
||||
reader.skip();
|
||||
} else {
|
||||
return Err(ERROR_UNCLOSED_PROPERTIES.create_without_context());
|
||||
}
|
||||
}
|
||||
Ok(properties)
|
||||
}
|
||||
|
||||
fn parse_nbt(reader: &mut StringReader) -> Result<Option<NbtCompound>, CommandSyntaxError> {
|
||||
if reader.peek() == Some('{') {
|
||||
let tag =
|
||||
ArgumentType::<crate::source::DummySource>::parse(&NbtCompoundArgumentType, reader)?;
|
||||
Ok(Some(tag))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlockPredicateArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for BlockPredicateArgumentType {
|
||||
type Item = BlockPredicate;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if reader.peek() == Some('#') {
|
||||
reader.skip();
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == ':' || c == '/' || c == '.' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let tag_str = &reader.string()[start..reader.cursor()];
|
||||
let normalized = if tag_str.contains(':') {
|
||||
tag_str.to_string()
|
||||
} else {
|
||||
format!("minecraft:{tag_str}")
|
||||
};
|
||||
let stripped = normalized.strip_prefix("minecraft:").unwrap_or(&normalized);
|
||||
|
||||
let tag_ids = get_tag_ids(RegistryKey::Block, &normalized)
|
||||
.or_else(|| get_tag_ids(RegistryKey::Block, stripped));
|
||||
|
||||
let block_ids = match tag_ids {
|
||||
Some(ids) => ids.to_vec(),
|
||||
None => {
|
||||
return Err(ERROR_UNKNOWN_TAG.create(reader, TextComponent::text(normalized)));
|
||||
}
|
||||
};
|
||||
|
||||
let properties = parse_properties(reader)?;
|
||||
let nbt = parse_nbt(reader)?;
|
||||
|
||||
Ok(BlockPredicate::Tag {
|
||||
tag_name: normalized,
|
||||
block_ids,
|
||||
properties,
|
||||
nbt,
|
||||
})
|
||||
} else {
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == ':' || c == '/' || c == '.' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let block_str = &reader.string()[start..reader.cursor()];
|
||||
let normalized = if block_str.contains(':') {
|
||||
block_str.to_string()
|
||||
} else {
|
||||
format!("minecraft:{block_str}")
|
||||
};
|
||||
|
||||
let block = Block::from_name(&normalized).ok_or_else(|| {
|
||||
INVALID_BLOCK_ERROR_TYPE.create(reader, TextComponent::text(normalized))
|
||||
})?;
|
||||
|
||||
let properties = parse_properties(reader)?;
|
||||
let nbt = parse_nbt(reader)?;
|
||||
|
||||
Ok(BlockPredicate::Block {
|
||||
block,
|
||||
properties,
|
||||
nbt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::BlockPredicate
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"stone".to_string(),
|
||||
"minecraft:stone".to_string(),
|
||||
"stone[foo=bar]".to_string(),
|
||||
"#stone".to_string(),
|
||||
"#stone[foo=bar]{baz=nbt}".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockPredicateArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<BlockPredicate, CommandSyntaxError> {
|
||||
Ok(context.get_argument::<BlockPredicate>(name)?.clone())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub const ERROR_INVALID_JSON: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_COMPONENT_INVALID,
|
||||
translation::java::ARGUMENT_COMPONENT_INVALID,
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ComponentArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ComponentArgumentType {
|
||||
type Item = TextComponent;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let remaining = reader.remaining_part();
|
||||
if let Ok(comp) = serde_json::from_str::<TextComponent>(remaining) {
|
||||
reader.set_cursor(reader.string().len());
|
||||
return Ok(comp);
|
||||
}
|
||||
|
||||
let s = reader.read_string()?;
|
||||
if let Ok(comp) = serde_json::from_str::<TextComponent>(&s) {
|
||||
return Ok(comp);
|
||||
}
|
||||
|
||||
Ok(TextComponent::text(s))
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Component
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl ComponentArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<TextComponent, CommandSyntaxError> {
|
||||
context.get_argument::<TextComponent>(name).cloned()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::wrap_degrees;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::source::CommandSource;
|
||||
use crate::string_reader::StringReader;
|
||||
|
||||
pub const ERROR_NOT_COMPLETE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ANGLE_INCOMPLETE,
|
||||
translation::java::ARGUMENT_ANGLE_INCOMPLETE,
|
||||
);
|
||||
|
||||
pub const ERROR_INVALID_ANGLE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ANGLE_INVALID,
|
||||
translation::java::ARGUMENT_ANGLE_INVALID,
|
||||
);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Angle {
|
||||
pub angle: f32,
|
||||
pub is_relative: bool,
|
||||
}
|
||||
|
||||
impl Angle {
|
||||
#[must_use]
|
||||
pub const fn new(angle: f32, is_relative: bool) -> Self {
|
||||
Self { angle, is_relative }
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_angle(&self, source: &impl CommandSource) -> f32 {
|
||||
let base = if self.is_relative {
|
||||
source.rotation().y
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
wrap_degrees(base + self.angle)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AngleArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for AngleArgumentType {
|
||||
type Item = Angle;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if !reader.can_read_char() {
|
||||
return Err(ERROR_NOT_COMPLETE.create(reader));
|
||||
}
|
||||
|
||||
let mut is_relative = false;
|
||||
if reader.peek() == Some('~') {
|
||||
is_relative = true;
|
||||
reader.skip();
|
||||
}
|
||||
|
||||
let angle = if reader.can_read_char() && reader.peek() != Some(' ') {
|
||||
reader.read_float()?
|
||||
} else if is_relative {
|
||||
0.0
|
||||
} else {
|
||||
return Err(ERROR_NOT_COMPLETE.create(reader));
|
||||
};
|
||||
|
||||
if angle.is_nan() || angle.is_infinite() {
|
||||
return Err(ERROR_INVALID_ANGLE.create(reader));
|
||||
}
|
||||
|
||||
Ok(Angle::new(angle, is_relative))
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Angle
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0", "~", "~-5")
|
||||
}
|
||||
}
|
||||
|
||||
impl AngleArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Angle, CommandSyntaxError> {
|
||||
context.get_argument::<Angle>(name).copied()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::argument_types::coordinates::Coordinates;
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder, TextCoordinates};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
|
||||
pub const NOT_LOADED_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS_UNLOADED,
|
||||
translation::java::ARGUMENT_POS_UNLOADED,
|
||||
);
|
||||
pub const OUT_OF_WORLD_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS_OUTOFWORLD,
|
||||
translation::java::ARGUMENT_POS_OUTOFWORLD,
|
||||
);
|
||||
pub const OUT_OF_BOUNDS_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
translation::java::ARGUMENT_POS_OUTOFBOUNDS,
|
||||
);
|
||||
|
||||
/// An argument type for a 3-dimensional vector representing a block position.
|
||||
///
|
||||
/// The parsed [`Coordinates`] can be converted to a [`BlockPos`] via one of the
|
||||
/// following associated methods:
|
||||
/// - [`BlockPosArgumentType::get_block_pos`]: Normal conversion.
|
||||
/// - [`BlockPosArgumentType::get_loaded_block_pos`]: Converts the coordinates to a *loaded* `BlockPos`.
|
||||
/// This is what you want to use most of the time (if you need to update the loaded position somehow).
|
||||
/// - [`BlockPosArgumentType::get_loaded_block_pos_in_world`]: Converts the coordinates to a *loaded* `BlockPos`
|
||||
/// in the provided world.
|
||||
/// - [`BlockPosArgumentType::get_spawnable_pos`]: Converts the coordinates to a `BlockPos` where
|
||||
/// a player can spawn.
|
||||
pub struct BlockPosArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for BlockPosArgumentType {
|
||||
type Item = Coordinates;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if reader.peek() == Some('^') {
|
||||
Coordinates::parse_local(reader)
|
||||
} else {
|
||||
Coordinates::parse_world_integers(reader)
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::BlockPos
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("1 3 5", "-3 ~24 ~-1", "80 80 80", "^ ^9 ^56")
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_3d_coordinates(suggested_coordinates, |value| {
|
||||
ArgumentType::<S>::parse(self, &mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockPosArgumentType {
|
||||
/// Returns a [`CommandContext`]'s parsed coordinate argument in the form of a [`BlockPos`].
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `context` - The [`CommandContext`] that has the parsed `Coordinates` with the provided argument name.
|
||||
/// * `name` - The name of the argument that was parsed.
|
||||
///
|
||||
/// # Returns
|
||||
/// The loaded `BlockPos` containing the position represented by the parsed argument, wrapped in an `Ok`,
|
||||
/// or an `Err` with the appropriate [`CommandSyntaxError`] if it could not be resolved.
|
||||
pub fn get_block_pos<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<BlockPos, CommandSyntaxError> {
|
||||
Ok(BlockPos::floored_v(
|
||||
context
|
||||
.get_argument::<Coordinates>(name)?
|
||||
.resolve(context.source.as_ref()),
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns a [`CommandContext`]'s parsed coordinate argument in the form of a loaded [`BlockPos`].
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `context` - The [`CommandContext`] that has the parsed `Coordinates` with the provided argument name.
|
||||
/// Its `CommandSource` also decides the world to check the load status in.
|
||||
/// * `name` - The name of the argument that was parsed.
|
||||
///
|
||||
/// # Returns
|
||||
/// The loaded `BlockPos` containing the position represented by the parsed argument, wrapped in an `Ok`,
|
||||
/// or an `Err` with the appropriate [`CommandSyntaxError`] if it could not be resolved.
|
||||
pub fn get_loaded_block_pos<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<BlockPos, CommandSyntaxError> {
|
||||
let pos = Self::get_block_pos(context, name)?;
|
||||
context.source.check_block_loaded(&pos)?;
|
||||
Ok(pos)
|
||||
}
|
||||
|
||||
/// Returns a [`CommandContext`]'s parsed coordinate argument in the form of a [`BlockPos`]
|
||||
/// where players can spawn.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `context` - The [`CommandContext`] that has the parsed `Coordinates` with the provided argument name.
|
||||
/// * `name` - The name of the argument that was parsed.
|
||||
///
|
||||
/// # Returns
|
||||
/// The loaded `BlockPos` containing the position represented by the parsed argument, wrapped in an `Ok`,
|
||||
/// or an `Err` with the appropriate [`CommandSyntaxError`] if it could not be resolved.
|
||||
pub fn get_spawnable_pos<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<BlockPos, CommandSyntaxError> {
|
||||
let pos = Self::get_block_pos(context, name)?;
|
||||
if is_valid_block_pos(pos) {
|
||||
Ok(pos)
|
||||
} else {
|
||||
Err(OUT_OF_BOUNDS_ERROR_TYPE.create_without_context())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_valid_block_pos(dest: BlockPos) -> bool {
|
||||
(-30_000_000..30_000_000).contains(&dest.0.x)
|
||||
&& (-30_000_000..30_000_000).contains(&dest.0.z)
|
||||
&& (-20_000_000..20_000_000).contains(&dest.0.y)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::position::{BlockPos, ColumnPos};
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
|
||||
use crate::suggestion::suggestions::TextCoordinates;
|
||||
use crate::{
|
||||
argument_types::{
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
coordinates::{Coordinates, WorldCoordinate},
|
||||
},
|
||||
context::command_context::CommandContext,
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types::CommandErrorType},
|
||||
string_reader::StringReader,
|
||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||
};
|
||||
|
||||
pub const INCOMPLETE_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS2D_INCOMPLETE,
|
||||
translation::java::ARGUMENT_POS2D_INCOMPLETE,
|
||||
);
|
||||
|
||||
pub struct ColumnPosArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ColumnPosArgumentType {
|
||||
type Item = Coordinates;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if !reader.can_read_char() {
|
||||
return Err(INCOMPLETE_ERROR_TYPE.create(reader));
|
||||
}
|
||||
|
||||
let start = reader.cursor();
|
||||
let x = WorldCoordinate::parse_integer(reader)?;
|
||||
if reader.peek() == Some(' ') {
|
||||
reader.skip();
|
||||
let z = WorldCoordinate::parse_integer(reader)?;
|
||||
Ok(Coordinates::World(Vector3 {
|
||||
x,
|
||||
y: WorldCoordinate::Relative(0.0),
|
||||
z,
|
||||
}))
|
||||
} else {
|
||||
reader.set_cursor(start);
|
||||
Err(INCOMPLETE_ERROR_TYPE.create(reader))
|
||||
}
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_2d_coordinates(suggested_coordinates, |value| {
|
||||
ArgumentType::<S>::parse(self, &mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ColumnPos
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0 0", "~ ~", "~-1 ~2")
|
||||
}
|
||||
}
|
||||
|
||||
impl ColumnPosArgumentType {
|
||||
/// Returns a [`CommandContext`]'s parsed coordinate argument in the form of a [`ColumnPos`].
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `context` - The [`CommandContext`] that has the parsed `Coordinates` with the provided argument name.
|
||||
/// * `name` - The name of the argument that was parsed.
|
||||
///
|
||||
/// # Returns
|
||||
/// The `ColumnPos` containing the position represented by the parsed argument, wrapped in an `Ok`,
|
||||
/// or an `Err` with the appropriate [`CommandSyntaxError`] if it could not be resolved.
|
||||
pub fn get_column_pos<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<ColumnPos, CommandSyntaxError> {
|
||||
let block_pos = BlockPos::floored_v(
|
||||
context
|
||||
.get_argument::<Coordinates>(name)?
|
||||
.resolve(context.source.as_ref()),
|
||||
);
|
||||
Ok(ColumnPos(Vector2::new(block_pos.0.x, block_pos.0.z)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::{CommandErrorType, READER_EXPECTED_DOUBLE, READER_EXPECTED_INT};
|
||||
use crate::source::CommandSource;
|
||||
use crate::string_reader::StringReader;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::{Axis, Vector3};
|
||||
|
||||
pub mod angle;
|
||||
pub mod block_pos;
|
||||
pub mod column_pos;
|
||||
pub mod rotation;
|
||||
pub mod swizzle;
|
||||
pub mod vec2;
|
||||
pub mod vec3;
|
||||
|
||||
pub const MIXED_TYPE_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS_MIXED,
|
||||
translation::java::ARGUMENT_POS_MIXED,
|
||||
);
|
||||
|
||||
/// Represents a single world coordinate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum WorldCoordinate {
|
||||
Absolute(f64),
|
||||
Relative(f64),
|
||||
}
|
||||
|
||||
impl WorldCoordinate {
|
||||
/// Creates a new `WorldCoordinate`.
|
||||
#[must_use]
|
||||
pub const fn new(is_relative: bool, value: f64) -> Self {
|
||||
if is_relative {
|
||||
Self::Relative(value)
|
||||
} else {
|
||||
Self::Absolute(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether this coordinate is relative.
|
||||
#[must_use]
|
||||
pub const fn is_relative(&self) -> bool {
|
||||
matches!(self, Self::Relative(_))
|
||||
}
|
||||
|
||||
/// Returns the physical coordinate value this [`WorldCoordinate`] represents, given
|
||||
/// an absolute coordinate origin.
|
||||
#[must_use]
|
||||
pub const fn resolve(&self, origin: f64) -> f64 {
|
||||
match self {
|
||||
Self::Absolute(absolute) => *absolute,
|
||||
Self::Relative(relative) => origin + *relative,
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if a `StringReader` is about to describle a relative coordinate.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `reader` - The `StringReader` to check.
|
||||
///
|
||||
/// # Returns
|
||||
/// - `true` if a `~` (tilde) can be found. It is also skipped by this method.
|
||||
/// - `false` if no `~` can be found.
|
||||
pub fn consume_relative_start(reader: &mut StringReader) -> bool {
|
||||
if reader.peek() == Some('~') {
|
||||
reader.skip();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to parse a [`WorldCoordinate`] from a single number.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `reader` - The `StringReader` to parse the coordinate from.
|
||||
/// * `center_integers` - Whether to correct integral coordinates by adding `+0.5` to them
|
||||
/// (as mentioned by `Vec3ArgumentType::Default`).
|
||||
///
|
||||
/// # Returns
|
||||
/// - The `WorldCoordinate` if it was correctly parsed, wrapped in an `Ok`.
|
||||
/// - A [`CommandSyntaxError`] describing an error if it could not be correctly parsed,
|
||||
/// wrapped in an `Err`.
|
||||
pub fn parse(
|
||||
reader: &mut StringReader,
|
||||
center_integers: bool,
|
||||
) -> Result<Self, CommandSyntaxError> {
|
||||
if reader.peek() == Some('^') {
|
||||
Err(MIXED_TYPE_ERROR_TYPE.create(reader))
|
||||
} else if !reader.can_read_char() {
|
||||
Err(READER_EXPECTED_DOUBLE.create(reader))
|
||||
} else {
|
||||
let is_relative = Self::consume_relative_start(reader);
|
||||
let i = reader.cursor();
|
||||
let mut value = if reader.can_read_char() && reader.peek() != Some(' ') {
|
||||
reader.read_double()?
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let slice = &reader.string()[i..reader.cursor()];
|
||||
if is_relative && slice.is_empty() {
|
||||
Ok(Self::Relative(0.0))
|
||||
} else {
|
||||
if !slice.contains('.') && !is_relative && center_integers {
|
||||
value += 0.5;
|
||||
}
|
||||
Ok(Self::new(is_relative, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to parse a [`WorldCoordinate`] from a single number, expecting an integral non-relative coordinate
|
||||
/// or any relative coordinate.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `reader` - The `StringReader` to parse the coordinate from.
|
||||
///
|
||||
/// # Returns
|
||||
/// - The `WorldCoordinate` if it was correctly parsed, wrapped in an `Ok`.
|
||||
/// - A [`CommandSyntaxError`] describing an error if it could not be correctly parsed,
|
||||
/// wrapped in an `Err`.
|
||||
pub fn parse_integer(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
if reader.peek() == Some('^') {
|
||||
Err(MIXED_TYPE_ERROR_TYPE.create(reader))
|
||||
} else if !reader.can_read_char() {
|
||||
Err(READER_EXPECTED_INT.create(reader))
|
||||
} else {
|
||||
let is_relative = Self::consume_relative_start(reader);
|
||||
let value = if reader.can_read_char() && reader.peek() != Some(' ') {
|
||||
if is_relative {
|
||||
reader.read_double()?
|
||||
} else {
|
||||
reader.read_int()? as f64
|
||||
}
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
Ok(Self::new(is_relative, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object representing some command coordinates.
|
||||
///
|
||||
/// A set of [`Coordinates`] can be *resolved* via the [`Coordinates::resolve`] method.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Coordinates {
|
||||
/// Normal coordinates (each coordinate can be *absolute* or *relative*.)
|
||||
World(Vector3<WorldCoordinate>),
|
||||
/// Local coordinates (can be different depending on the command source.)
|
||||
Local { left: f64, up: f64, forward: f64 },
|
||||
}
|
||||
|
||||
macro_rules! check_for_space_char {
|
||||
($reader:ident, $i:ident, $value:ident) => {
|
||||
if $reader.peek() == Some(' ') {
|
||||
$reader.skip();
|
||||
Ok($value)
|
||||
} else {
|
||||
$reader.set_cursor($i);
|
||||
Err(vec3::INCOMPLETE_ERROR_TYPE.create($reader))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl Coordinates {
|
||||
/// Returns whether a coordinate (of the given [`Axis`]) of these [`Coordinates`] is relative.
|
||||
///
|
||||
/// This also returns `true` for a *local coordinate*.
|
||||
#[must_use]
|
||||
pub const fn is_relative(&self, axis: Axis) -> bool {
|
||||
match self {
|
||||
Self::World(vector) => vector.get_axis(axis).is_relative(),
|
||||
Self::Local { .. } => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the physical position that these [`Coordinates`] represent.
|
||||
#[must_use]
|
||||
pub fn resolve(&self, source: &impl CommandSource) -> Vector3<f64> {
|
||||
match self {
|
||||
Self::World(vector) => {
|
||||
let pos = source.position();
|
||||
Vector3::new(
|
||||
vector.x.resolve(pos.x),
|
||||
vector.y.resolve(pos.y),
|
||||
vector.z.resolve(pos.z),
|
||||
)
|
||||
}
|
||||
Self::Local { left, up, forward } => {
|
||||
let start = source.entity_anchor().position_at_source(source);
|
||||
convert_local_coordinates(*left, *up, *forward, source.rotation()).add(&start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the rotation, as a [`Vector2`], that these [`Coordinates`] represent.
|
||||
///
|
||||
/// - The returned *x*-component of the vector is the **pitch**.
|
||||
/// - The returned *y*-component of the vector is the **yaw**.
|
||||
#[must_use]
|
||||
pub fn rotation(&self, source: &impl CommandSource) -> Vector2<f32> {
|
||||
match self {
|
||||
Self::World(coords) => {
|
||||
let rotation = source.rotation();
|
||||
Vector2::new(
|
||||
coords.x.resolve(rotation.x as f64) as f32,
|
||||
coords.y.resolve(rotation.y as f64) as f32,
|
||||
)
|
||||
}
|
||||
Self::Local { .. } => Vector2::new(0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to parse a set of world [`Coordinates`], expecting coordinates, each either being
|
||||
/// an integral non-relative coordinate or any relative coordinate.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `reader` - The `StringReader` to parse the coordinates from.
|
||||
/// * `center_integers` - Whether to correct integral coordinates by adding `+0.5` to them
|
||||
/// (as mentioned by `Vec3ArgumentType::Default`).
|
||||
///
|
||||
/// # Returns
|
||||
/// - The world `Coordinates` if they were correctly parsed, wrapped in an `Ok`.
|
||||
/// - A [`CommandSyntaxError`] describing an error if they could not be correctly parsed,
|
||||
/// wrapped in an `Err`.
|
||||
pub fn parse_world(
|
||||
reader: &mut StringReader,
|
||||
center_integers: bool,
|
||||
) -> Result<Self, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let coordinate_1 = Self::parse_world_single(i, reader, center_integers)?;
|
||||
// The Y coordinate is never centered.
|
||||
let coordinate_2 = Self::parse_world_single(i, reader, false)?;
|
||||
let coordinate_3 = WorldCoordinate::parse(reader, center_integers)?;
|
||||
Ok(Self::World(Vector3::new(
|
||||
coordinate_1,
|
||||
coordinate_2,
|
||||
coordinate_3,
|
||||
)))
|
||||
}
|
||||
|
||||
fn parse_world_single(
|
||||
i: usize,
|
||||
reader: &mut StringReader,
|
||||
center_integers: bool,
|
||||
) -> Result<WorldCoordinate, CommandSyntaxError> {
|
||||
let coordinate = WorldCoordinate::parse(reader, center_integers)?;
|
||||
check_for_space_char!(reader, i, coordinate)
|
||||
}
|
||||
|
||||
/// Tries to parse a set of world [`Coordinates`].
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `reader` - The `StringReader` to parse the coordinate from.
|
||||
///
|
||||
/// # Returns
|
||||
/// - The world `Coordinates` if they were correctly parsed, wrapped in an `Ok`.
|
||||
/// - A [`CommandSyntaxError`] describing an error if they could not be correctly parsed,
|
||||
/// wrapped in an `Err`.
|
||||
pub fn parse_world_integers(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let coordinate_1 = Self::parse_world_single_integer(i, reader)?;
|
||||
let coordinate_2 = Self::parse_world_single_integer(i, reader)?;
|
||||
let coordinate_3 = WorldCoordinate::parse_integer(reader)?;
|
||||
Ok(Self::World(Vector3::new(
|
||||
coordinate_1,
|
||||
coordinate_2,
|
||||
coordinate_3,
|
||||
)))
|
||||
}
|
||||
|
||||
fn parse_world_single_integer(
|
||||
i: usize,
|
||||
reader: &mut StringReader,
|
||||
) -> Result<WorldCoordinate, CommandSyntaxError> {
|
||||
let coordinate = WorldCoordinate::parse_integer(reader)?;
|
||||
check_for_space_char!(reader, i, coordinate)
|
||||
}
|
||||
|
||||
/// Tries to parse a set of local [`Coordinates`].
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `reader` - The `StringReader` to parse the coordinate from.
|
||||
///
|
||||
/// # Returns
|
||||
/// - The local `Coordinates` if they were correctly parsed, wrapped in an `Ok`.
|
||||
/// - A [`CommandSyntaxError`] describing an error if they could not be correctly parsed,
|
||||
/// wrapped in an `Err`.
|
||||
pub fn parse_local(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let left = Self::parse_local_single(i, reader)?;
|
||||
let up = Self::parse_local_single(i, reader)?;
|
||||
let forward = Self::parse_local_number(i, reader)?;
|
||||
Ok(Self::Local { left, up, forward })
|
||||
}
|
||||
|
||||
fn parse_local_single(i: usize, reader: &mut StringReader) -> Result<f64, CommandSyntaxError> {
|
||||
let number = Self::parse_local_number(i, reader)?;
|
||||
check_for_space_char!(reader, i, number)
|
||||
}
|
||||
|
||||
fn parse_local_number(i: usize, reader: &mut StringReader) -> Result<f64, CommandSyntaxError> {
|
||||
if !reader.can_read_char() {
|
||||
Err(READER_EXPECTED_DOUBLE.create(reader))
|
||||
} else if reader.peek() != Some('^') {
|
||||
reader.set_cursor(i);
|
||||
Err(MIXED_TYPE_ERROR_TYPE.create(reader))
|
||||
} else {
|
||||
reader.skip();
|
||||
let number = if reader.can_read_char() && reader.peek() != Some(' ') {
|
||||
reader.read_double()?
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
Ok(number)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a set of local coordinates to their physical [`Vector3`] form.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `left` - The left component of the coordinates.
|
||||
/// * `up` - The up component of the coordinates.
|
||||
/// * `forward` - The forward component of the coordinates.
|
||||
/// * `rotation` - The rotation to use to calculate the physical coordinates.
|
||||
/// Both coordinates must be in *degrees*.
|
||||
///
|
||||
/// # Returns
|
||||
/// The physical position represented by the local coordinates.
|
||||
#[must_use]
|
||||
fn convert_local_coordinates(
|
||||
left: f64,
|
||||
up: f64,
|
||||
forward: f64,
|
||||
rotation: Vector2<f32>,
|
||||
) -> Vector3<f64> {
|
||||
let pitch = rotation.x;
|
||||
let yaw = rotation.y;
|
||||
|
||||
let y = (yaw + 90.0).to_radians() as f64;
|
||||
let y_cos = y.cos();
|
||||
let y_sin = y.sin();
|
||||
let x = (-pitch).to_radians() as f64;
|
||||
let x_cos = x.cos();
|
||||
let x_sin = x.sin();
|
||||
let x_up = (-pitch + 90.0).to_radians() as f64;
|
||||
let x_up_cos = x_up.cos();
|
||||
let x_up_sin = x_up.sin();
|
||||
|
||||
let forward_vector = Vector3::new(y_cos * x_cos, x_sin, y_sin * x_cos);
|
||||
let up_vector = Vector3::new(y_cos * x_up_cos, x_up_sin, y_sin * x_up_cos);
|
||||
let left_vector = forward_vector.cross(&up_vector) * -1.0;
|
||||
|
||||
Vector3::new(
|
||||
forward_vector.x * forward + up_vector.x * up + left_vector.x * left,
|
||||
forward_vector.y * forward + up_vector.y * up + left_vector.y * left,
|
||||
forward_vector.z * forward + up_vector.z * up + left_vector.z * left,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::argument_types::coordinates::{Coordinates, WorldCoordinate};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
|
||||
pub const NOT_COMPLETE_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ROTATION_INCOMPLETE,
|
||||
translation::java::ARGUMENT_ROTATION_INCOMPLETE,
|
||||
);
|
||||
|
||||
pub struct RotationArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for RotationArgumentType {
|
||||
type Item = Coordinates;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
if reader.can_read_char() {
|
||||
let y = WorldCoordinate::parse(reader, false)?;
|
||||
if reader.peek() == Some(' ') {
|
||||
reader.skip();
|
||||
let x = WorldCoordinate::parse(reader, false)?;
|
||||
Ok(Coordinates::World(Vector3::new(
|
||||
x,
|
||||
y,
|
||||
WorldCoordinate::Relative(0.0),
|
||||
)))
|
||||
} else {
|
||||
reader.set_cursor(i);
|
||||
Err(Self::syntax_error(reader))
|
||||
}
|
||||
} else {
|
||||
Err(Self::syntax_error(reader))
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Rotation
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("1 1", "~5 4", "~-6 ~-6")
|
||||
}
|
||||
}
|
||||
|
||||
impl RotationArgumentType {
|
||||
fn syntax_error(reader: &StringReader) -> CommandSyntaxError {
|
||||
NOT_COMPLETE_ERROR_TYPE.create(reader)
|
||||
}
|
||||
|
||||
/// Returns the [`Coordinates`] representing the rotation of a parsed rotation argument.
|
||||
///
|
||||
/// Use [`Coordinates::rotation`] to resolve the coordinates to a rotation `Vector22`.
|
||||
///
|
||||
/// If the rotation is successfully provided in an `Ok`:
|
||||
/// - The returned *x*-coordinate of the coordinates is the absolute/relative **pitch**.
|
||||
/// - The returned *y*-coordinate of the coordinates is the absolute/relative **yaw**.
|
||||
/// - The returned *z*-coordinate of the coordinates is always 0.
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Coordinates, CommandSyntaxError> {
|
||||
context.get_argument::<Coordinates>(name).copied()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
|
||||
pub const ERROR_INVALID_SWIZZLE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENTS_SWIZZLE_INVALID,
|
||||
translation::java::ARGUMENTS_SWIZZLE_INVALID,
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub struct Swizzle {
|
||||
pub x: bool,
|
||||
pub y: bool,
|
||||
pub z: bool,
|
||||
}
|
||||
|
||||
impl Swizzle {
|
||||
#[must_use]
|
||||
pub const fn align(&self, pos: Vector3<f64>) -> Vector3<f64> {
|
||||
Vector3::new(
|
||||
if self.x { pos.x.floor() } else { pos.x },
|
||||
if self.y { pos.y.floor() } else { pos.y },
|
||||
if self.z { pos.z.floor() } else { pos.z },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SwizzleArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for SwizzleArgumentType {
|
||||
type Item = Swizzle;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let mut swizzle = Swizzle::default();
|
||||
let mut count = 0;
|
||||
|
||||
while reader.can_read_char() && reader.peek() != Some(' ') {
|
||||
let c = reader.read().unwrap();
|
||||
match c {
|
||||
'x' => {
|
||||
if swizzle.x {
|
||||
return Err(ERROR_INVALID_SWIZZLE.create(reader));
|
||||
}
|
||||
swizzle.x = true;
|
||||
}
|
||||
'y' => {
|
||||
if swizzle.y {
|
||||
return Err(ERROR_INVALID_SWIZZLE.create(reader));
|
||||
}
|
||||
swizzle.y = true;
|
||||
}
|
||||
'z' => {
|
||||
if swizzle.z {
|
||||
return Err(ERROR_INVALID_SWIZZLE.create(reader));
|
||||
}
|
||||
swizzle.z = true;
|
||||
}
|
||||
_ => return Err(ERROR_INVALID_SWIZZLE.create(reader)),
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
return Err(ERROR_INVALID_SWIZZLE.create(reader));
|
||||
}
|
||||
|
||||
Ok(swizzle)
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Swizzle
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec!["xyz".to_string(), "x".to_string()]
|
||||
}
|
||||
}
|
||||
|
||||
impl SwizzleArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Swizzle, CommandSyntaxError> {
|
||||
Ok(*context.get_argument::<Swizzle>(name)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::argument_types::coordinates::{Coordinates, WorldCoordinate};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder, TextCoordinates};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
|
||||
pub const INCOMPLETE_2D_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS2D_INCOMPLETE,
|
||||
translation::java::ARGUMENT_POS2D_INCOMPLETE,
|
||||
);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub enum Vec2ArgumentType {
|
||||
#[default]
|
||||
Default,
|
||||
Uncorrected,
|
||||
}
|
||||
|
||||
impl Vec2ArgumentType {
|
||||
#[must_use]
|
||||
pub const fn centers_integers(&self) -> bool {
|
||||
matches!(self, Self::Default)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn new(centers_integers: bool) -> Self {
|
||||
if centers_integers {
|
||||
Self::Default
|
||||
} else {
|
||||
Self::Uncorrected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for Vec2ArgumentType {
|
||||
type Item = Coordinates;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
if !reader.can_read_char() {
|
||||
return Err(INCOMPLETE_2D_ERROR_TYPE.create(reader));
|
||||
}
|
||||
|
||||
let x = WorldCoordinate::parse(reader, self.centers_integers())?;
|
||||
if reader.can_read_char() && reader.peek() == Some(' ') {
|
||||
reader.skip();
|
||||
let z = WorldCoordinate::parse(reader, self.centers_integers())?;
|
||||
Ok(Coordinates::World(Vector3::new(
|
||||
x,
|
||||
WorldCoordinate::Relative(0.0),
|
||||
z,
|
||||
)))
|
||||
} else {
|
||||
reader.set_cursor(start);
|
||||
Err(INCOMPLETE_2D_ERROR_TYPE.create(reader))
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Vec2
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"0 0".to_string(),
|
||||
"~ ~".to_string(),
|
||||
"0.1 -0.5".to_string(),
|
||||
"~1 ~-2".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggested_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_2d_coordinates(suggested_coordinates, |value| {
|
||||
ArgumentType::<S>::parse(self, &mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Vec2ArgumentType {
|
||||
pub fn get_coordinates<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Coordinates, CommandSyntaxError> {
|
||||
Ok(*context.get_argument(name)?)
|
||||
}
|
||||
|
||||
pub fn get_vector2<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Vector2<f64>, CommandSyntaxError> {
|
||||
let resolved = Self::get_coordinates(context, name)?.resolve(context.source.as_ref());
|
||||
Ok(Vector2::new(resolved.x, resolved.z))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::argument_types::coordinates::{Coordinates, MIXED_TYPE_ERROR_TYPE};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder, TextCoordinates};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
|
||||
pub const INCOMPLETE_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_POS3D_INCOMPLETE,
|
||||
translation::java::ARGUMENT_POS3D_INCOMPLETE,
|
||||
);
|
||||
pub const ERROR_NOT_COMPLETE: CommandErrorType<0> = INCOMPLETE_ERROR_TYPE;
|
||||
pub const ERROR_MIXED_TYPE: CommandErrorType<0> = MIXED_TYPE_ERROR_TYPE;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
/// An argument type for a 3-dimensional vector.
|
||||
pub enum Vec3ArgumentType {
|
||||
/// The default `Vec3ArgumentType` variant.
|
||||
///
|
||||
/// To represent some position in the world,
|
||||
/// you'll almost always want to use this.
|
||||
///
|
||||
/// For each coordinate, if it does not use the decimal (`.`) sign
|
||||
/// (the coordinate is integral) and it is not relative,
|
||||
/// a `+0.5` offset is added to it.
|
||||
///
|
||||
#[default]
|
||||
Default,
|
||||
/// No center correction occurs for this `Vec3ArgumentType` variant.
|
||||
Uncorrected,
|
||||
}
|
||||
|
||||
impl Vec3ArgumentType {
|
||||
/// Returns whether this argument type centers integers.
|
||||
#[must_use]
|
||||
pub const fn centers_integers(&self) -> bool {
|
||||
matches!(self, Self::Default)
|
||||
}
|
||||
|
||||
/// Creates a new `Vec3ArgumentType` with the given center correction.
|
||||
#[must_use]
|
||||
pub const fn new(centers_integers: bool) -> Self {
|
||||
if centers_integers {
|
||||
Self::Default
|
||||
} else {
|
||||
Self::Uncorrected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for Vec3ArgumentType {
|
||||
type Item = Coordinates;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if reader.peek() == Some('^') {
|
||||
Coordinates::parse_local(reader)
|
||||
} else {
|
||||
Coordinates::parse_world(reader, self.centers_integers())
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Vec3
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"0 0 0".to_string(),
|
||||
"~ ~ ~".to_string(),
|
||||
"^ ^ ^".to_string(),
|
||||
"^1 ^ ^-5".to_string(),
|
||||
"0.1 -0.5 .9".to_string(),
|
||||
"~0.5 ~1 ~-5".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let remainder = builder.remaining();
|
||||
|
||||
let suggestioned_coordinates = if remainder.bytes().next() == Some(b'^') {
|
||||
TextCoordinates::Local
|
||||
} else {
|
||||
TextCoordinates::Global
|
||||
};
|
||||
|
||||
builder.suggest_3d_coordinates(suggestioned_coordinates, |value| {
|
||||
ArgumentType::<S>::parse(self, &mut StringReader::new(value)).is_ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Vec3ArgumentType {
|
||||
/// Returns a [`CommandContext`]'s parsed three-dimensional vector as a set of [`Coordinates`].
|
||||
pub fn get_coordinates<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Coordinates, CommandSyntaxError> {
|
||||
Ok(*context.get_argument(name)?)
|
||||
}
|
||||
|
||||
/// Returns a [`CommandContext`]'s parsed three-dimensional vector and resolves it to a [`Vector3`].
|
||||
pub fn get_vector3<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Vector3<f64>, CommandSyntaxError> {
|
||||
Ok(Self::get_coordinates(context, name)?.resolve(context.source.as_ref()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// Represents an argument type parsing a [`bool`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct BoolArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for BoolArgumentType {
|
||||
type Item = bool;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<bool, CommandSyntaxError> {
|
||||
reader.read_bool()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Bool
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("true", "false")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(BoolArgumentType, bool);
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::core::bool::BoolArgumentType, errors::error_types,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_test() {
|
||||
let mut reader = StringReader::new("true");
|
||||
assert_parse_ok_reset!(&mut reader, BoolArgumentType, true);
|
||||
|
||||
reader = StringReader::new("false");
|
||||
assert_parse_ok_reset!(&mut reader, BoolArgumentType, false);
|
||||
|
||||
reader = StringReader::new("1");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
BoolArgumentType,
|
||||
&error_types::READER_INVALID_BOOL
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use crate::{
|
||||
argument_types::{
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
core::within_or_err,
|
||||
},
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// Represents an argument type parsing an [`f64`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub struct DoubleArgumentType {
|
||||
pub min: f64,
|
||||
pub max: f64,
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for DoubleArgumentType {
|
||||
type Item = f64;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<f64, CommandSyntaxError> {
|
||||
let reader_start = reader.cursor();
|
||||
let result = reader.read_double()?;
|
||||
within_or_err(
|
||||
reader,
|
||||
reader_start,
|
||||
result,
|
||||
self.min,
|
||||
self.max,
|
||||
&error_types::DOUBLE_TOO_LOW,
|
||||
&error_types::DOUBLE_TOO_HIGH,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Double {
|
||||
min: (self.min != f64::MIN).then_some(self.min),
|
||||
max: (self.max != f64::MAX).then_some(self.max),
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0", "1.2", ".5", "-1", "-.5", "-1234.56")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(DoubleArgumentType, f64);
|
||||
|
||||
impl DoubleArgumentType {
|
||||
/// Constructs a new [`DoubleArgumentType`] with no minimum or maximum bounds.
|
||||
#[must_use]
|
||||
pub const fn any() -> Self {
|
||||
Self {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new [`DoubleArgumentType`] with *only* the specified minimum bound.
|
||||
#[must_use]
|
||||
pub const fn with_min(min: f64) -> Self {
|
||||
Self { min, max: f64::MAX }
|
||||
}
|
||||
|
||||
/// Constructs a new [`DoubleArgumentType`] with *only* the specified maximum bound.
|
||||
#[must_use]
|
||||
pub const fn with_max(max: f64) -> Self {
|
||||
Self { min: f64::MIN, max }
|
||||
}
|
||||
|
||||
/// Constructs a new [`DoubleArgumentType`] with the given bounds.
|
||||
#[must_use]
|
||||
pub const fn new(min: f64, max: f64) -> Self {
|
||||
Self { min, max }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::core::double::DoubleArgumentType, errors::error_types,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_test() {
|
||||
let mut reader = StringReader::new("-1234.56");
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, DoubleArgumentType::any());
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, DoubleArgumentType::with_min(-1240.0));
|
||||
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
DoubleArgumentType::with_min(-1230.0),
|
||||
&error_types::DOUBLE_TOO_LOW
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, DoubleArgumentType::with_max(-1230.0));
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
DoubleArgumentType::with_max(-1240.0),
|
||||
&error_types::DOUBLE_TOO_HIGH
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, DoubleArgumentType::new(-1235.0, -1230.0));
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
DoubleArgumentType::new(-1240.0, -1235.0),
|
||||
&error_types::DOUBLE_TOO_HIGH
|
||||
);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
DoubleArgumentType::new(-1230.0, -1225.0),
|
||||
&error_types::DOUBLE_TOO_LOW
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use crate::{
|
||||
argument_types::{
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
core::within_or_err,
|
||||
},
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// Represents an argument type parsing an [`f32`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub struct FloatArgumentType {
|
||||
pub min: f32,
|
||||
pub max: f32,
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for FloatArgumentType {
|
||||
type Item = f32;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<f32, CommandSyntaxError> {
|
||||
let reader_start = reader.cursor();
|
||||
let result = reader.read_float()?;
|
||||
within_or_err(
|
||||
reader,
|
||||
reader_start,
|
||||
result,
|
||||
self.min,
|
||||
self.max,
|
||||
&error_types::FLOAT_TOO_LOW,
|
||||
&error_types::FLOAT_TOO_HIGH,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Float {
|
||||
min: (self.min != f32::MIN).then_some(self.min),
|
||||
max: (self.max != f32::MAX).then_some(self.max),
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0", "1.2", ".5", "-1", "-.5", "-1234.56")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(FloatArgumentType, f32);
|
||||
|
||||
impl FloatArgumentType {
|
||||
/// Constructs a new [`FloatArgumentType`] with no minimum or maximum bounds.
|
||||
#[must_use]
|
||||
pub const fn any() -> Self {
|
||||
Self {
|
||||
min: f32::MIN,
|
||||
max: f32::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new [`FloatArgumentType`] with *only* the specified minimum bound.
|
||||
#[must_use]
|
||||
pub const fn with_min(min: f32) -> Self {
|
||||
Self { min, max: f32::MAX }
|
||||
}
|
||||
|
||||
/// Constructs a new [`FloatArgumentType`] with *only* the specified maximum bound.
|
||||
#[must_use]
|
||||
pub const fn with_max(max: f32) -> Self {
|
||||
Self { min: f32::MIN, max }
|
||||
}
|
||||
|
||||
/// Constructs a new [`FloatArgumentType`] with the given bounds.
|
||||
#[must_use]
|
||||
pub const fn new(min: f32, max: f32) -> Self {
|
||||
Self { min, max }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::core::float::FloatArgumentType, errors::error_types,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_test() {
|
||||
let mut reader = StringReader::new("-1234.56");
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, FloatArgumentType::any());
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, FloatArgumentType::with_min(-1240.0));
|
||||
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
FloatArgumentType::with_min(-1230.0),
|
||||
&error_types::FLOAT_TOO_LOW
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, FloatArgumentType::with_max(-1230.0));
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
FloatArgumentType::with_max(-1240.0),
|
||||
&error_types::FLOAT_TOO_HIGH
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, FloatArgumentType::new(-1235.0, -1230.0));
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
FloatArgumentType::new(-1240.0, -1235.0),
|
||||
&error_types::FLOAT_TOO_HIGH
|
||||
);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
FloatArgumentType::new(-1230.0, -1225.0),
|
||||
&error_types::FLOAT_TOO_LOW
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
use crate::{
|
||||
argument_types::{
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
core::within_or_err,
|
||||
},
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// Represents an argument type parsing an [`i32`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct IntegerArgumentType {
|
||||
pub min: i32,
|
||||
pub max: i32,
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for IntegerArgumentType {
|
||||
type Item = i32;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<i32, CommandSyntaxError> {
|
||||
let reader_start = reader.cursor();
|
||||
let result = reader.read_int()?;
|
||||
within_or_err(
|
||||
reader,
|
||||
reader_start,
|
||||
result,
|
||||
self.min,
|
||||
self.max,
|
||||
&error_types::INTEGER_TOO_LOW,
|
||||
&error_types::INTEGER_TOO_HIGH,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Integer {
|
||||
min: (self.min != i32::MIN).then_some(self.min),
|
||||
max: (self.max != i32::MAX).then_some(self.max),
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0", "123", "-123")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(IntegerArgumentType, i32);
|
||||
|
||||
impl IntegerArgumentType {
|
||||
/// Constructs a new [`IntegerArgumentType`] with no minimum or maximum bounds.
|
||||
#[must_use]
|
||||
pub const fn any() -> Self {
|
||||
Self {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new [`IntegerArgumentType`] with *only* the specified minimum bound.
|
||||
#[must_use]
|
||||
pub const fn with_min(min: i32) -> Self {
|
||||
Self { min, max: i32::MAX }
|
||||
}
|
||||
|
||||
/// Constructs a new [`IntegerArgumentType`] with *only* the specified maximum bound.
|
||||
#[must_use]
|
||||
pub const fn with_max(max: i32) -> Self {
|
||||
Self { min: i32::MIN, max }
|
||||
}
|
||||
|
||||
/// Constructs a new [`IntegerArgumentType`] with the given bounds.
|
||||
#[must_use]
|
||||
pub const fn new(min: i32, max: i32) -> Self {
|
||||
Self { min, max }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::core::integer::IntegerArgumentType, errors::error_types,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_test() {
|
||||
let mut reader = StringReader::new("123");
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, IntegerArgumentType::any(), 123);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, IntegerArgumentType::with_min(120), 123);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
IntegerArgumentType::with_min(130),
|
||||
&error_types::INTEGER_TOO_LOW
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, IntegerArgumentType::with_max(200), 123);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
IntegerArgumentType::with_max(100),
|
||||
&error_types::INTEGER_TOO_HIGH
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, IntegerArgumentType::new(100, 125), 123);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
IntegerArgumentType::new(100, 120),
|
||||
&error_types::INTEGER_TOO_HIGH
|
||||
);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
IntegerArgumentType::new(125, 150),
|
||||
&error_types::INTEGER_TOO_LOW
|
||||
);
|
||||
|
||||
// 500_000_000 fits into an i32.
|
||||
reader = StringReader::new("500000000");
|
||||
assert_parse_ok_reset!(&mut reader, IntegerArgumentType::any(), 500_000_000);
|
||||
|
||||
// 5_000_000_000 does not fit into an i32.
|
||||
reader = StringReader::new("5000000000");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
IntegerArgumentType::any(),
|
||||
&error_types::READER_INVALID_INT
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use crate::{
|
||||
argument_types::{
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
core::within_or_err,
|
||||
},
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// Represents an argument type parsing an [`i64`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct LongArgumentType {
|
||||
pub min: i64,
|
||||
pub max: i64,
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for LongArgumentType {
|
||||
type Item = i64;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<i64, CommandSyntaxError> {
|
||||
let reader_start = reader.cursor();
|
||||
let result = reader.read_long()?;
|
||||
within_or_err(
|
||||
reader,
|
||||
reader_start,
|
||||
result,
|
||||
self.min,
|
||||
self.max,
|
||||
&error_types::LONG_TOO_LOW,
|
||||
&error_types::LONG_TOO_HIGH,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Long {
|
||||
min: (self.min != i64::MIN).then_some(self.min),
|
||||
max: (self.max != i64::MAX).then_some(self.max),
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0", "123", "-123")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(LongArgumentType, i64);
|
||||
|
||||
impl LongArgumentType {
|
||||
/// Constructs a new [`LongArgumentType`] with no minimum or maximum bounds.
|
||||
#[must_use]
|
||||
pub const fn any() -> Self {
|
||||
Self {
|
||||
min: i64::MIN,
|
||||
max: i64::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new [`LongArgumentType`] with *only* the specified minimum bound.
|
||||
#[must_use]
|
||||
pub const fn with_min(min: i64) -> Self {
|
||||
Self { min, max: i64::MAX }
|
||||
}
|
||||
|
||||
/// Constructs a new [`LongArgumentType`] with *only* the specified maximum bound.
|
||||
#[must_use]
|
||||
pub const fn with_max(max: i64) -> Self {
|
||||
Self { min: i64::MIN, max }
|
||||
}
|
||||
|
||||
/// Constructs a new [`LongArgumentType`] with the given bounds.
|
||||
#[must_use]
|
||||
pub const fn new(min: i64, max: i64) -> Self {
|
||||
Self { min, max }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::core::long::LongArgumentType, errors::error_types,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_test() {
|
||||
let mut reader = StringReader::new("123");
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, LongArgumentType::any(), 123);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, LongArgumentType::with_min(120), 123);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
LongArgumentType::with_min(130),
|
||||
&error_types::LONG_TOO_LOW
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, LongArgumentType::with_max(200), 123);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
LongArgumentType::with_max(100),
|
||||
&error_types::LONG_TOO_HIGH
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, LongArgumentType::new(100, 125), 123);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
LongArgumentType::new(100, 120),
|
||||
&error_types::LONG_TOO_HIGH
|
||||
);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
LongArgumentType::new(125, 150),
|
||||
&error_types::LONG_TOO_LOW
|
||||
);
|
||||
|
||||
// 5_000_000_000_000_000_000 fits into an i64.
|
||||
reader = StringReader::new("5000000000000000000");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
LongArgumentType::any(),
|
||||
5_000_000_000_000_000_000
|
||||
);
|
||||
|
||||
// 10_000_000_000_000_000_000 does not fit into an i64.
|
||||
reader = StringReader::new("10000000000000000000");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
LongArgumentType::any(),
|
||||
&error_types::READER_INVALID_LONG
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::{
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types::CommandErrorType},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
pub mod bool;
|
||||
pub mod double;
|
||||
pub mod float;
|
||||
pub mod integer;
|
||||
pub mod long;
|
||||
pub mod string;
|
||||
|
||||
/// Helper method for parsing with a reader and returning an [`Err`] if outside the range.
|
||||
#[inline]
|
||||
pub fn within_or_err<T>(
|
||||
reader: &mut StringReader,
|
||||
reader_start: usize,
|
||||
value: T,
|
||||
min: T,
|
||||
max: T,
|
||||
too_low_error_type: &'static CommandErrorType<2>,
|
||||
too_high_error_type: &'static CommandErrorType<2>,
|
||||
) -> Result<T, CommandSyntaxError>
|
||||
where
|
||||
T: PartialOrd + ToString + Copy,
|
||||
{
|
||||
if value < min {
|
||||
reader.set_cursor(reader_start);
|
||||
Err(too_low_error_type.create(
|
||||
reader,
|
||||
TextComponent::text(min.to_string()),
|
||||
TextComponent::text(value.to_string()),
|
||||
))
|
||||
} else if value > max {
|
||||
reader.set_cursor(reader_start);
|
||||
Err(too_high_error_type.create(
|
||||
reader,
|
||||
TextComponent::text(max.to_string()),
|
||||
TextComponent::text(value.to_string()),
|
||||
))
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
use pumpkin_protocol::java::client::play::StringProtoArgBehavior;
|
||||
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::{
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
pub enum StringArgumentType {
|
||||
/// Accepts a single unquoted word.
|
||||
SingleWord,
|
||||
|
||||
/// Accepts a quoted or unquoted string.
|
||||
QuotablePhrase,
|
||||
|
||||
/// Takes the remaining text from the [`StringReader`] and returns that.
|
||||
GreedyPhrase,
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for StringArgumentType {
|
||||
type Item = String;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<String, CommandSyntaxError> {
|
||||
match self {
|
||||
Self::SingleWord => Ok(reader.read_unquoted_string()),
|
||||
Self::QuotablePhrase => reader.read_string(),
|
||||
Self::GreedyPhrase => {
|
||||
let text = reader.remaining_part().to_owned();
|
||||
reader.set_cursor(reader.total_length());
|
||||
Ok(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::String(match self {
|
||||
Self::SingleWord => StringProtoArgBehavior::SingleWord,
|
||||
Self::QuotablePhrase => StringProtoArgBehavior::QuotablePhrase,
|
||||
Self::GreedyPhrase => StringProtoArgBehavior::GreedyPhrase,
|
||||
})
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
match self {
|
||||
Self::SingleWord => examples!("word", "words_with_underscores"),
|
||||
Self::QuotablePhrase => examples!("\"quoted phrase\"", "word", "\"\""),
|
||||
Self::GreedyPhrase => examples!("word", "words with spaces", "\"and symbols\""),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StringArgumentType {
|
||||
/// Returns a [`CommandContext`]'s parsed `String` argument as a string slice.
|
||||
pub fn get<'a, S: crate::source::CommandSource>(
|
||||
context: &'a CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'a str, CommandSyntaxError> {
|
||||
Ok(context.get_argument::<String>(name)?.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::core::string::StringArgumentType, errors::error_types,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_single_quoted() {
|
||||
let mut reader = StringReader::new("'single-quoted string!'");
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::QuotablePhrase,
|
||||
"single-quoted string!".to_owned()
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, StringArgumentType::SingleWord, String::new());
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::GreedyPhrase,
|
||||
"'single-quoted string!'".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_double_quoted() {
|
||||
let mut reader = StringReader::new("\"double-quoted string!\"");
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::QuotablePhrase,
|
||||
"double-quoted string!".to_owned()
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, StringArgumentType::SingleWord, String::new());
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::GreedyPhrase,
|
||||
"\"double-quoted string!\"".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_identifier() {
|
||||
let mut reader = StringReader::new(".i_AM_an-1den+ifier.");
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::QuotablePhrase,
|
||||
".i_AM_an-1den+ifier.".to_owned()
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::SingleWord,
|
||||
".i_AM_an-1den+ifier.".to_owned()
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::GreedyPhrase,
|
||||
".i_AM_an-1den+ifier.".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_incorrectly() {
|
||||
let mut reader = StringReader::new("'incorrect\"");
|
||||
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::QuotablePhrase,
|
||||
&error_types::READER_EXPECTED_END_QUOTE
|
||||
);
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, StringArgumentType::SingleWord, String::new());
|
||||
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
StringArgumentType::GreedyPhrase,
|
||||
"'incorrect\"".to_owned()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
use crate::{
|
||||
argument_types::{
|
||||
FromStringReader,
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
nbt::NbtCompoundArgumentType,
|
||||
},
|
||||
context::command_context::CommandContext,
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum DialogArg {
|
||||
Id(Identifier),
|
||||
Nbt(NbtCompound),
|
||||
}
|
||||
|
||||
pub struct DialogArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for DialogArgumentType {
|
||||
type Item = DialogArg;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if reader.peek() == Some('{') {
|
||||
let compound = ArgumentType::<S>::parse(&NbtCompoundArgumentType, reader)?;
|
||||
Ok(DialogArg::Nbt(compound))
|
||||
} else {
|
||||
let id = Identifier::from_reader(reader)?;
|
||||
Ok(DialogArg::Id(id))
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Dialog
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!(
|
||||
"minecraft:server_links",
|
||||
"custom:my_dialog",
|
||||
"{type:\"minecraft:notice\",title:\"Hello\"}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl DialogArgumentType {
|
||||
/// Returns the parsed [`DialogArg`] from the name of the argument.
|
||||
pub fn get<'a, S: crate::source::CommandSource>(
|
||||
context: &'a CommandContext<S>,
|
||||
name: &'_ str,
|
||||
) -> Result<&'a DialogArg, CommandSyntaxError> {
|
||||
context.get_argument(name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::source::CommandSource;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ANCHOR_INVALID,
|
||||
translation::java::ARGUMENT_ANCHOR_INVALID,
|
||||
);
|
||||
|
||||
pub struct EntityAnchorArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for EntityAnchorArgumentType {
|
||||
type Item = EntityAnchor;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let anchor = reader.read_unquoted_string();
|
||||
EntityAnchor::from_id(anchor.as_str()).map_or_else(
|
||||
|| {
|
||||
reader.set_cursor(i);
|
||||
Err(INVALID_ERROR_TYPE.create(reader, TextComponent::text(anchor)))
|
||||
},
|
||||
Ok,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::EntityAnchor
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&["eyes", "feet"]).build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("eyes", "feet")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(EntityAnchorArgumentType, EntityAnchor);
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
|
||||
pub enum EntityAnchor {
|
||||
#[default]
|
||||
Feet,
|
||||
Eyes,
|
||||
}
|
||||
|
||||
impl EntityAnchor {
|
||||
/// Gets the [`EntityAnchor`] whose identity is the ID provided.
|
||||
#[must_use]
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
match id {
|
||||
"feet" => Some(Self::Feet),
|
||||
"eyes" => Some(Self::Eyes),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the ID of this [`EntityAnchor`]
|
||||
#[must_use]
|
||||
pub const fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Feet => "feet",
|
||||
Self::Eyes => "eyes",
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the position of a source with respect to this anchor.
|
||||
#[must_use]
|
||||
pub fn position_at_source(self, command_source: &impl CommandSource) -> Vector3<f64> {
|
||||
command_source.anchor_position(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::GameMode;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::str::FromStr;
|
||||
|
||||
pub const INVALID_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_GAMEMODE_INVALID,
|
||||
translation::java::ARGUMENT_GAMEMODE_INVALID,
|
||||
);
|
||||
|
||||
pub struct GameModeArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for GameModeArgumentType {
|
||||
type Item = GameMode;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let string = reader.read_unquoted_string();
|
||||
GameMode::from_str(&string)
|
||||
.map_err(|_| INVALID_ERROR_TYPE.create(reader, TextComponent::text(string)))
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Gamemode
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
mut builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
for gamemode in GameMode::VALUES {
|
||||
builder = builder.filter_and_suggest_one(gamemode.name());
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("survival", "creative")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(GameModeArgumentType, GameMode);
|
||||
@@ -0,0 +1,111 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::{CommandErrorType, DISPATCHER_PARSE_EXCEPTION};
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation::java::ARGUMENT_HEXCOLOR_INVALID;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::RGBColor;
|
||||
|
||||
pub const INVALID_HEX_ERROR_TYPE: CommandErrorType<1> =
|
||||
CommandErrorType::new(ARGUMENT_HEXCOLOR_INVALID, ARGUMENT_HEXCOLOR_INVALID);
|
||||
|
||||
pub struct HexColorArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for HexColorArgumentType {
|
||||
type Item = RGBColor;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let string = reader.read_unquoted_string();
|
||||
match string.len() {
|
||||
3 => Ok(RGBColor {
|
||||
red: Self::parse_one_hex_digit(reader, &string, 0)?,
|
||||
green: Self::parse_one_hex_digit(reader, &string, 1)?,
|
||||
blue: Self::parse_one_hex_digit(reader, &string, 2)?,
|
||||
}),
|
||||
6 => Ok(RGBColor {
|
||||
red: Self::parse_two_hex_digits(reader, &string, 0)?,
|
||||
green: Self::parse_two_hex_digits(reader, &string, 2)?,
|
||||
blue: Self::parse_two_hex_digits(reader, &string, 4)?,
|
||||
}),
|
||||
_ => Err(INVALID_HEX_ERROR_TYPE.create(reader, TextComponent::text(string))),
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::HexColor
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&["F00", "FF0000"]).build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("F00", "FF0000")
|
||||
}
|
||||
}
|
||||
|
||||
impl HexColorArgumentType {
|
||||
fn parse_one_hex_digit(
|
||||
reader: &StringReader,
|
||||
string: &str,
|
||||
index: usize,
|
||||
) -> Result<u8, CommandSyntaxError> {
|
||||
Self::parse_hex_digit(reader, &string[index..=index], 0)
|
||||
// We want to map:
|
||||
// 0x0 -> 0x00
|
||||
// 0x1 -> 0x11
|
||||
// 0x2 -> 0x22 ...
|
||||
.map(|x| x * 0x11)
|
||||
}
|
||||
|
||||
fn parse_two_hex_digits(
|
||||
reader: &StringReader,
|
||||
string: &str,
|
||||
index_start: usize,
|
||||
) -> Result<u8, CommandSyntaxError> {
|
||||
Ok(
|
||||
Self::parse_hex_digit(reader, &string[index_start..index_start + 2], 0)? << 4
|
||||
| Self::parse_hex_digit(reader, &string[index_start..index_start + 2], 1)?,
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_hex_digit(
|
||||
reader: &StringReader,
|
||||
slice: &str,
|
||||
index: usize,
|
||||
) -> Result<u8, CommandSyntaxError> {
|
||||
// This should be fine as `read_unquoted_string` parses only ASCII characters.
|
||||
let b = slice.as_bytes()[index];
|
||||
match b {
|
||||
b'0' => Ok(0x0),
|
||||
b'1' => Ok(0x1),
|
||||
b'2' => Ok(0x2),
|
||||
b'3' => Ok(0x3),
|
||||
b'4' => Ok(0x4),
|
||||
b'5' => Ok(0x5),
|
||||
b'6' => Ok(0x6),
|
||||
b'7' => Ok(0x7),
|
||||
b'8' => Ok(0x8),
|
||||
b'9' => Ok(0x9),
|
||||
b'a' | b'A' => Ok(0xA),
|
||||
b'b' | b'B' => Ok(0xB),
|
||||
b'c' | b'C' => Ok(0xC),
|
||||
b'd' | b'D' => Ok(0xD),
|
||||
b'e' | b'E' => Ok(0xE),
|
||||
b'f' | b'F' => Ok(0xF),
|
||||
_ => Err(DISPATCHER_PARSE_EXCEPTION.create(
|
||||
reader,
|
||||
TextComponent::text(format!("Error at index {index} in: \"{slice}\"")),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(HexColorArgumentType, RGBColor);
|
||||
@@ -0,0 +1,38 @@
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
use crate::{
|
||||
argument_types::{
|
||||
FromStringReader,
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
},
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// An argument type that parses a generic [`Identifier`] with a namespace and path.
|
||||
pub struct IdentifierArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for IdentifierArgumentType {
|
||||
type Item = Identifier;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceLocation
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("foo", "foo:bar")
|
||||
}
|
||||
}
|
||||
|
||||
impl IdentifierArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &crate::context::command_context::CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Identifier, CommandSyntaxError> {
|
||||
Ok(context.get_argument::<Identifier>(name)?.clone())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use pumpkin_data::data_component::DataComponent;
|
||||
use pumpkin_data::item::Item;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::snbt::SnbtParser;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub const ERROR_UNKNOWN_ITEM: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ITEM_ID_INVALID,
|
||||
translation::java::ARGUMENT_ITEM_ID_INVALID,
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ItemStackArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ItemStackArgumentType {
|
||||
type Item = ItemStack;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == ':' || c == '/' || c == '.' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let raw_id = &reader.string()[start..reader.cursor()];
|
||||
let item = Item::from_registry_key(raw_id).ok_or_else(|| {
|
||||
let full_name = if raw_id.contains(':') {
|
||||
raw_id.to_string()
|
||||
} else {
|
||||
format!("minecraft:{raw_id}")
|
||||
};
|
||||
ERROR_UNKNOWN_ITEM.create(reader, TextComponent::text(full_name))
|
||||
})?;
|
||||
|
||||
let mut stack = ItemStack::new(1, item);
|
||||
|
||||
// Optional components [...]
|
||||
if reader.peek() == Some('[') {
|
||||
reader.skip();
|
||||
let mut patch = Vec::new();
|
||||
while reader.can_read_char() && reader.peek() != Some(']') {
|
||||
let key_start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == ':' || c == '.' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let key_str = reader.string()[key_start..reader.cursor()]
|
||||
.trim()
|
||||
.to_string();
|
||||
|
||||
reader.skip_whitespace();
|
||||
if reader.peek() == Some('=') {
|
||||
reader.skip();
|
||||
reader.skip_whitespace();
|
||||
let nbt_tag = SnbtParser::parse_for_commands(reader)?;
|
||||
if let (Some(data_comp), Some(comp_impl)) = (
|
||||
DataComponent::try_from_name(&key_str),
|
||||
pumpkin_data::data_component_impl::read_data(
|
||||
DataComponent::try_from_name(&key_str)
|
||||
.unwrap_or(DataComponent::CustomData),
|
||||
&nbt_tag,
|
||||
),
|
||||
) {
|
||||
patch.push((data_comp, Some(comp_impl)));
|
||||
}
|
||||
}
|
||||
reader.skip_whitespace();
|
||||
if reader.peek() == Some(',') {
|
||||
reader.skip();
|
||||
reader.skip_whitespace();
|
||||
}
|
||||
}
|
||||
if reader.peek() == Some(']') {
|
||||
reader.skip();
|
||||
}
|
||||
if !patch.is_empty() {
|
||||
stack.patch = patch;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(stack)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ItemStack
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemStackArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<ItemStack, CommandSyntaxError> {
|
||||
context.get_argument::<ItemStack>(name).cloned()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use pumpkin_data::item::Item;
|
||||
use pumpkin_data::item_stack::ItemStack;
|
||||
use pumpkin_data::tag::{RegistryKey, get_tag_ids};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub const ERROR_UNKNOWN_ITEM: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ITEM_ID_INVALID,
|
||||
translation::java::ARGUMENT_ITEM_ID_INVALID,
|
||||
);
|
||||
|
||||
pub const ERROR_UNKNOWN_TAG: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENTS_ITEM_TAG_UNKNOWN,
|
||||
translation::java::ARGUMENTS_ITEM_TAG_UNKNOWN,
|
||||
);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum ItemPredicate {
|
||||
Item(&'static Item),
|
||||
Tag(Vec<u16>),
|
||||
Any,
|
||||
}
|
||||
|
||||
impl ItemPredicate {
|
||||
#[must_use]
|
||||
pub fn test(&self, stack: &ItemStack) -> bool {
|
||||
match self {
|
||||
Self::Any => true,
|
||||
Self::Item(item) => stack.get_item().id == item.id,
|
||||
Self::Tag(tag) => tag.contains(&stack.get_item().id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ItemPredicateArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ItemPredicateArgumentType {
|
||||
type Item = ItemPredicate;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
if reader.peek() == Some('#') {
|
||||
reader.skip();
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric() || c == '_' || c == ':' || c == '/' || c == '.' || c == '-' {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let tag_str = &reader.string()[start..reader.cursor()];
|
||||
let normalized = if tag_str.contains(':') {
|
||||
tag_str.to_string()
|
||||
} else {
|
||||
format!("minecraft:{tag_str}")
|
||||
};
|
||||
let stripped = normalized.strip_prefix("minecraft:").unwrap_or(&normalized);
|
||||
|
||||
let tag_ids = get_tag_ids(RegistryKey::Item, &normalized)
|
||||
.or_else(|| get_tag_ids(RegistryKey::Item, stripped));
|
||||
|
||||
let items = match tag_ids {
|
||||
Some(ids) => ids.to_vec(),
|
||||
None => {
|
||||
return Err(ERROR_UNKNOWN_TAG.create(reader, TextComponent::text(normalized)));
|
||||
}
|
||||
};
|
||||
|
||||
skip_components_and_nbt(reader);
|
||||
|
||||
Ok(ItemPredicate::Tag(items))
|
||||
} else {
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if c.is_alphanumeric()
|
||||
|| c == '_'
|
||||
|| c == ':'
|
||||
|| c == '/'
|
||||
|| c == '.'
|
||||
|| c == '-'
|
||||
|| c == '*'
|
||||
{
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let item_str = &reader.string()[start..reader.cursor()];
|
||||
if item_str == "*" {
|
||||
return Ok(ItemPredicate::Any);
|
||||
}
|
||||
|
||||
let normalized = if item_str.contains(':') {
|
||||
item_str.to_string()
|
||||
} else {
|
||||
format!("minecraft:{item_str}")
|
||||
};
|
||||
let stripped = normalized.strip_prefix("minecraft:").unwrap_or(&normalized);
|
||||
|
||||
let item = Item::from_registry_key(&normalized)
|
||||
.or_else(|| Item::from_registry_key(stripped))
|
||||
.ok_or_else(|| {
|
||||
ERROR_UNKNOWN_ITEM.create(reader, TextComponent::text(normalized))
|
||||
})?;
|
||||
|
||||
skip_components_and_nbt(reader);
|
||||
|
||||
Ok(ItemPredicate::Item(item))
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ItemPredicate
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"stick".to_string(),
|
||||
"minecraft:stick".to_string(),
|
||||
"#stick".to_string(),
|
||||
"#stick{foo:'bar'}".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_components_and_nbt(reader: &mut StringReader) {
|
||||
if reader.peek() == Some('[') {
|
||||
reader.skip();
|
||||
let mut depth = 1;
|
||||
while reader.can_read_char() && depth > 0 {
|
||||
match reader.read() {
|
||||
Some('[') => depth += 1,
|
||||
Some(']') => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if reader.peek() == Some('{') {
|
||||
reader.skip();
|
||||
let mut depth = 1;
|
||||
while reader.can_read_char() && depth > 0 {
|
||||
match reader.read() {
|
||||
Some('{') => depth += 1,
|
||||
Some('}') => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemPredicateArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<ItemPredicate, CommandSyntaxError> {
|
||||
Ok(context.get_argument::<ItemPredicate>(name)?.clone())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::{
|
||||
CommandErrorType, READER_INVALID_DOUBLE, READER_INVALID_FLOAT, READER_INVALID_INT,
|
||||
};
|
||||
use crate::string_reader::StringReader;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::math::bounds::{Bounds, DoubleBounds, FloatDegreeBounds, IntBounds};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Creates a [`Vec<String>`] of examples from
|
||||
/// the given string literals.
|
||||
macro_rules! examples {
|
||||
( $( $example:literal ),* ) => {
|
||||
vec! [
|
||||
$( $example.to_string(), )*
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
// Helper methods for assertion with a `StringReader`:
|
||||
|
||||
/// Asserts that the result read by `reader` with the argument
|
||||
/// type `$argument_type` used to parse is equal to `Ok($value)`.
|
||||
/// Also resets the reader's cursor back to the start.
|
||||
#[cfg(test)]
|
||||
macro_rules! assert_parse_ok_reset {
|
||||
($reader: expr, $argument_type: expr, $value: expr) => {{
|
||||
assert_eq!(
|
||||
$crate::argument_types::argument_type::ArgumentType::<crate::source::DummySource>::parse(
|
||||
&$argument_type,
|
||||
&mut $reader
|
||||
),
|
||||
Ok($value)
|
||||
);
|
||||
$reader.set_cursor(0)
|
||||
}};
|
||||
($reader: expr, $argument_type: expr) => {{
|
||||
assert!(
|
||||
$crate::argument_types::argument_type::ArgumentType::<crate::source::DummySource>::parse(
|
||||
&$argument_type,
|
||||
&mut $reader
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
$reader.set_cursor(0)
|
||||
}};
|
||||
}
|
||||
|
||||
/// Asserts that the result read by `reader` with the argument
|
||||
/// type `$argument_type` used to parse is an `Err` containing the type of error as `$error_type`.
|
||||
/// Also resets the reader's cursor back to the start.
|
||||
#[cfg(test)]
|
||||
macro_rules! assert_parse_err_reset {
|
||||
($reader: expr, $argument_type: expr, $error_type: expr) => {
|
||||
let error_type_dyn: &'static dyn crate::errors::error_types::AnyCommandErrorType =
|
||||
$error_type;
|
||||
assert_eq!(
|
||||
$crate::argument_types::argument_type::ArgumentType::<crate::source::DummySource>::parse(
|
||||
&$argument_type,
|
||||
&mut $reader
|
||||
)
|
||||
.map_err(|e| e.error_type),
|
||||
Err(error_type_dyn)
|
||||
);
|
||||
$reader.set_cursor(0)
|
||||
};
|
||||
}
|
||||
|
||||
/// Macro to implement a single `get()` function for an argument type whose `Item` is `Copy`.
|
||||
macro_rules! impl_copy_get {
|
||||
($ty:ty, $item:ty) => {
|
||||
impl $ty {
|
||||
#[doc = concat!("Returns a `CommandContext`'s parsed `", stringify!($item), "` argument.")]
|
||||
pub fn get<S: $crate::source::CommandSource>(context: &$crate::context::command_context::CommandContext<S>, name: &str) -> Result<$item, CommandSyntaxError> {
|
||||
Ok(*context.get_argument(name)?)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const EMPTY_BOUNDS_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_RANGE_EMPTY,
|
||||
translation::java::ARGUMENT_RANGE_EMPTY,
|
||||
);
|
||||
const SWAPPED_BOUNDS_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_RANGE_SWAPPED,
|
||||
translation::java::ARGUMENT_RANGE_SWAPPED,
|
||||
);
|
||||
const INVALID_IDENTIFIER_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ID_INVALID,
|
||||
translation::java::ARGUMENT_ID_INVALID,
|
||||
);
|
||||
|
||||
/// A trait to try getting a value from a [`StringReader`].
|
||||
pub trait FromStringReader: Sized {
|
||||
/// Tries to parse a value of this type from a [`StringReader`].
|
||||
///
|
||||
/// If this fails, a [`CommandSyntaxError`] is returned with the erroring details.
|
||||
fn from_reader(reader: &mut StringReader) -> Result<Self, CommandSyntaxError>;
|
||||
}
|
||||
|
||||
fn bounds_from_reader<T: Copy + FromStr + PartialOrd>(
|
||||
reader: &mut StringReader,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
) -> Result<Bounds<T>, CommandSyntaxError> {
|
||||
if reader.can_read_char() {
|
||||
let i = reader.cursor();
|
||||
try_bounds_from_reader(reader, error_type).map_err(|e| {
|
||||
// On catching any error, set the reader's cursor position to be at where the range starts.
|
||||
if let Some(mut context) = e.context {
|
||||
context.cursor = i;
|
||||
CommandSyntaxError::create(e.error_type, e.message, &context)
|
||||
} else {
|
||||
CommandSyntaxError::create_without_context(e.error_type, e.message)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Err(EMPTY_BOUNDS_ERROR_TYPE.create(reader))
|
||||
}
|
||||
}
|
||||
|
||||
fn try_bounds_from_reader<T: Copy + FromStr + PartialOrd>(
|
||||
reader: &mut StringReader,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
) -> Result<Bounds<T>, CommandSyntaxError> {
|
||||
let min = read_number_from_reader(reader, error_type)?;
|
||||
let max = if reader.peek() == Some('.') && reader.peek_with_offset(1) == Some('.') {
|
||||
reader.skip();
|
||||
reader.skip();
|
||||
read_number_from_reader(reader, error_type)?
|
||||
} else {
|
||||
min
|
||||
};
|
||||
if min.is_none() && max.is_none() {
|
||||
Err(EMPTY_BOUNDS_ERROR_TYPE.create(reader))
|
||||
} else {
|
||||
Ok(Bounds::<T>::new(min, max))
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to read a number of a type from a reader.
|
||||
fn read_number_from_reader<T: FromStr>(
|
||||
reader: &mut StringReader,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
) -> Result<Option<T>, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
while has_allowed_peaked_character(reader) {
|
||||
reader.skip();
|
||||
}
|
||||
let string = &reader.string()[i..reader.cursor()].to_string();
|
||||
if string.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
string.parse::<T>().map_or_else(
|
||||
|_| Err(error_type.create(reader, TextComponent::text(string.clone()))),
|
||||
|t| Ok(Some(t)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_allowed_peaked_character(reader: &StringReader) -> bool {
|
||||
let c = reader.peek();
|
||||
if matches!(c, Some('0'..='9' | '-')) {
|
||||
true
|
||||
} else {
|
||||
c.is_some_and(|c| {
|
||||
c == '.' && (!reader.can_read_chars(2) || reader.peek_with_offset(1) != Some('.'))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStringReader for IntBounds {
|
||||
fn from_reader(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let bounds = bounds_from_reader(reader, &READER_INVALID_INT)?;
|
||||
if bounds.are_swapped() {
|
||||
reader.set_cursor(i);
|
||||
Err(SWAPPED_BOUNDS_ERROR_TYPE.create(reader))
|
||||
} else {
|
||||
Ok(Self::from_bounds(bounds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStringReader for DoubleBounds {
|
||||
fn from_reader(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let bounds = bounds_from_reader(reader, &READER_INVALID_DOUBLE)?;
|
||||
if bounds.are_swapped() {
|
||||
reader.set_cursor(i);
|
||||
Err(SWAPPED_BOUNDS_ERROR_TYPE.create(reader))
|
||||
} else {
|
||||
Ok(Self::from_bounds(bounds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStringReader for FloatDegreeBounds {
|
||||
fn from_reader(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
let i = reader.cursor();
|
||||
let bounds = bounds_from_reader(reader, &READER_INVALID_FLOAT)?;
|
||||
if bounds.are_swapped() {
|
||||
reader.set_cursor(i);
|
||||
Err(SWAPPED_BOUNDS_ERROR_TYPE.create(reader))
|
||||
} else {
|
||||
Ok(Self::from_bounds(bounds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStringReader for Identifier {
|
||||
fn from_reader(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek()
|
||||
&& Self::is_valid_char(c)
|
||||
{
|
||||
reader.skip();
|
||||
}
|
||||
|
||||
let raw_identifier = &reader.string()[start..reader.cursor()];
|
||||
let identifier_result = Self::parse(raw_identifier);
|
||||
|
||||
identifier_result.map_or_else(
|
||||
|_| {
|
||||
reader.set_cursor(start);
|
||||
Err(INVALID_IDENTIFIER_ERROR_TYPE.create(reader))
|
||||
},
|
||||
Ok,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod argument_type;
|
||||
pub mod attribute;
|
||||
pub mod block;
|
||||
pub mod block_predicate;
|
||||
pub mod component;
|
||||
pub mod coordinates;
|
||||
pub mod core;
|
||||
pub mod dialog;
|
||||
pub mod entity_anchor;
|
||||
pub mod gamemode;
|
||||
pub mod hex_color;
|
||||
pub mod identifier;
|
||||
pub mod item;
|
||||
pub mod item_predicate;
|
||||
pub mod nbt;
|
||||
pub mod nbt_path;
|
||||
pub mod particle;
|
||||
pub mod placed_feature;
|
||||
pub mod pool;
|
||||
pub mod range;
|
||||
pub mod resource;
|
||||
pub mod resource_or_tag;
|
||||
pub mod slot;
|
||||
pub mod sound_category;
|
||||
pub mod structure;
|
||||
pub mod team_color;
|
||||
pub mod template;
|
||||
pub mod time;
|
||||
pub mod uuid;
|
||||
@@ -0,0 +1,92 @@
|
||||
use pumpkin_nbt::tag::NbtTag;
|
||||
|
||||
use crate::{
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
context::command_context::CommandContext,
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types::CommandErrorType},
|
||||
snbt::SnbtParser,
|
||||
string_reader::StringReader,
|
||||
suggestion::suggestions::{Suggestions, SuggestionsBuilder},
|
||||
};
|
||||
|
||||
use pumpkin_data::translation::java::ARGUMENT_NBT_EXPECTED_COMPOUND;
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
|
||||
/// Parses any type of NBT tag from SNBT.
|
||||
pub struct NbtTagArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for NbtTagArgumentType {
|
||||
type Item = NbtTag;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
SnbtParser::parse_for_commands(reader)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::NbtTag
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
SnbtParser::parse_for_suggestions(builder)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("0", "0b", "0l", "0.0", "\"foo\"", "{foo=bar}", "[0]")
|
||||
}
|
||||
}
|
||||
|
||||
impl NbtTagArgumentType {
|
||||
/// Returns the parsed [`NbtTag`] from the name of the argument.
|
||||
pub fn get<'a, S: crate::source::CommandSource>(
|
||||
context: &'a CommandContext<S>,
|
||||
name: &'_ str,
|
||||
) -> Result<&'a NbtTag, CommandSyntaxError> {
|
||||
context.get_argument(name)
|
||||
}
|
||||
}
|
||||
|
||||
pub const EXPECTED_COMPOUND_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
ARGUMENT_NBT_EXPECTED_COMPOUND,
|
||||
ARGUMENT_NBT_EXPECTED_COMPOUND,
|
||||
);
|
||||
|
||||
/// Parses **only** compound NBT tags from SNBT.
|
||||
pub struct NbtCompoundArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for NbtCompoundArgumentType {
|
||||
type Item = NbtCompound;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
SnbtParser::parse_for_commands(reader).and_then(|tag| {
|
||||
if let NbtTag::Compound(compound) = tag {
|
||||
Ok(compound)
|
||||
} else {
|
||||
Err(EXPECTED_COMPOUND_ERROR_TYPE.create(reader))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::NbtCompound
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("{}", "{x: 3}")
|
||||
}
|
||||
}
|
||||
|
||||
impl NbtCompoundArgumentType {
|
||||
/// Returns the parsed [`NbtCompound`] from the name of the argument.
|
||||
pub fn get<'a, S: crate::source::CommandSource>(
|
||||
context: &'a CommandContext<S>,
|
||||
name: &'_ str,
|
||||
) -> Result<&'a NbtCompound, CommandSyntaxError> {
|
||||
context.get_argument(name)
|
||||
}
|
||||
}
|
||||
|
||||
pub use super::nbt_path::{NbtPath, NbtPathArgumentType, NbtPathNode};
|
||||
@@ -0,0 +1,802 @@
|
||||
#![allow(
|
||||
clippy::borrow_as_ptr,
|
||||
clippy::ref_as_ptr,
|
||||
clippy::manual_let_else,
|
||||
clippy::undocumented_unsafe_blocks,
|
||||
clippy::explicit_counter_loop,
|
||||
clippy::collapsible_if,
|
||||
clippy::must_use_candidate,
|
||||
clippy::needless_pass_by_value,
|
||||
clippy::redundant_closure_for_method_calls,
|
||||
clippy::cast_possible_wrap,
|
||||
clippy::cast_sign_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::missing_const_for_fn,
|
||||
clippy::bool_to_int_with_if,
|
||||
clippy::if_not_else
|
||||
)]
|
||||
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_nbt::tag::NbtTag;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::snbt::SnbtParser;
|
||||
use crate::string_reader::StringReader;
|
||||
|
||||
pub const ERROR_INVALID_NODE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENTS_NBTPATH_NODE_INVALID,
|
||||
translation::java::ARGUMENTS_NBTPATH_NODE_INVALID,
|
||||
);
|
||||
|
||||
pub const ERROR_DATA_TOO_DEEP: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENTS_NBTPATH_TOO_DEEP,
|
||||
translation::java::ARGUMENTS_NBTPATH_TOO_DEEP,
|
||||
);
|
||||
|
||||
pub const ERROR_NOTHING_FOUND: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENTS_NBTPATH_NOTHING_FOUND,
|
||||
translation::java::ARGUMENTS_NBTPATH_NOTHING_FOUND,
|
||||
);
|
||||
|
||||
pub const ERROR_EXPECTED_LIST: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_DATA_MODIFY_EXPECTED_LIST,
|
||||
translation::java::COMMANDS_DATA_MODIFY_EXPECTED_LIST,
|
||||
);
|
||||
|
||||
pub const ERROR_INVALID_INDEX: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMANDS_DATA_MODIFY_INVALID_INDEX,
|
||||
translation::java::COMMANDS_DATA_MODIFY_INVALID_INDEX,
|
||||
);
|
||||
|
||||
/// Checks if an NBT tag exceeds the maximum nesting depth (512).
|
||||
pub fn is_too_deep(tag: &NbtTag, depth: usize) -> bool {
|
||||
if depth >= 512 {
|
||||
return true;
|
||||
}
|
||||
match tag {
|
||||
NbtTag::Compound(compound) => {
|
||||
for child in compound.child_tags.values() {
|
||||
if is_too_deep(child, depth + 1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
NbtTag::List(list) => {
|
||||
for child in list {
|
||||
if is_too_deep(child, depth + 1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Recursively compares whether `target` satisfies the `pattern`.
|
||||
pub fn compare_nbt(pattern: &NbtTag, target: &NbtTag) -> bool {
|
||||
if pattern == target {
|
||||
return true;
|
||||
}
|
||||
match (pattern, target) {
|
||||
(NbtTag::Compound(pattern_compound), NbtTag::Compound(target_compound)) => {
|
||||
for (key, pattern_value) in &pattern_compound.child_tags {
|
||||
match target_compound.child_tags.get(key) {
|
||||
Some(target_value) => {
|
||||
if !compare_nbt(pattern_value, target_value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
(NbtTag::List(pattern_list), NbtTag::List(target_list)) => {
|
||||
if pattern_list.is_empty() {
|
||||
return target_list.is_empty();
|
||||
}
|
||||
for pattern_elem in pattern_list {
|
||||
let mut matched = false;
|
||||
for target_elem in target_list {
|
||||
if compare_nbt(pattern_elem, target_elem) {
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => pattern == target,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum NbtPathNode {
|
||||
AllElements,
|
||||
CompoundChild(String),
|
||||
IndexedElement(i32),
|
||||
MatchElement(NbtCompound),
|
||||
MatchObject(String, NbtCompound),
|
||||
MatchRootObject(NbtCompound),
|
||||
}
|
||||
|
||||
impl NbtPathNode {
|
||||
pub fn get_tag(&self, parent: &NbtTag, output: &mut Vec<NbtTag>) {
|
||||
match self {
|
||||
Self::AllElements => match parent {
|
||||
NbtTag::List(list) => output.extend(list.iter().cloned()),
|
||||
NbtTag::ByteArray(arr) => {
|
||||
output.extend(arr.iter().map(|&b| NbtTag::Byte(b)));
|
||||
}
|
||||
NbtTag::IntArray(arr) => {
|
||||
output.extend(arr.iter().map(|&i| NbtTag::Int(i)));
|
||||
}
|
||||
NbtTag::LongArray(arr) => {
|
||||
output.extend(arr.iter().map(|&l| NbtTag::Long(l)));
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Self::CompoundChild(name) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
if let Some(tag) = compound.child_tags.get(name.as_str()) {
|
||||
output.push(tag.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::IndexedElement(index) => match parent {
|
||||
NbtTag::List(list) => {
|
||||
let size = list.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < list.len() {
|
||||
output.push(list[actual_index as usize].clone());
|
||||
}
|
||||
}
|
||||
NbtTag::ByteArray(arr) => {
|
||||
let size = arr.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < arr.len() {
|
||||
output.push(NbtTag::Byte(arr[actual_index as usize]));
|
||||
}
|
||||
}
|
||||
NbtTag::IntArray(arr) => {
|
||||
let size = arr.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < arr.len() {
|
||||
output.push(NbtTag::Int(arr[actual_index as usize]));
|
||||
}
|
||||
}
|
||||
NbtTag::LongArray(arr) => {
|
||||
let size = arr.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < arr.len() {
|
||||
output.push(NbtTag::Long(arr[actual_index as usize]));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Self::MatchElement(pattern) => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
for elem in list {
|
||||
if compare_nbt(&pattern_tag, elem) {
|
||||
output.push(elem.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::MatchObject(name, pattern) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
if let Some(tag) = compound.child_tags.get(name.as_str()) {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if compare_nbt(&pattern_tag, tag) {
|
||||
output.push(tag.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::MatchRootObject(pattern) => {
|
||||
if let NbtTag::Compound(_) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if compare_nbt(&pattern_tag, parent) {
|
||||
output.push(parent.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_preferred_parent_tag(&self) -> NbtTag {
|
||||
match self {
|
||||
Self::AllElements | Self::IndexedElement(_) | Self::MatchElement(_) => {
|
||||
NbtTag::List(Vec::new())
|
||||
}
|
||||
Self::CompoundChild(_) | Self::MatchObject(_, _) | Self::MatchRootObject(_) => {
|
||||
NbtTag::Compound(NbtCompound::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_tag(&self, parent: &mut NbtTag, to_add: &mut impl FnMut() -> NbtTag) -> i32 {
|
||||
match self {
|
||||
Self::AllElements => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let size = list.len();
|
||||
if size == 0 {
|
||||
list.push(to_add());
|
||||
return 1;
|
||||
}
|
||||
let new_val = to_add();
|
||||
let changed_count = list.iter().filter(|&x| x != &new_val).count() as i32;
|
||||
if changed_count == 0 {
|
||||
return 0;
|
||||
}
|
||||
list.clear();
|
||||
list.push(new_val);
|
||||
for _ in 1..size {
|
||||
list.push(to_add());
|
||||
}
|
||||
changed_count
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Self::CompoundChild(name) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
let new_val = to_add();
|
||||
let prev = compound
|
||||
.child_tags
|
||||
.insert(name.clone().into(), new_val.clone());
|
||||
i32::from(prev.as_ref() != Some(&new_val))
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Self::IndexedElement(index) => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let size = list.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < list.len() {
|
||||
let new_val = to_add();
|
||||
if list[actual_index as usize] != new_val {
|
||||
list[actual_index as usize] = new_val;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Self::MatchElement(pattern) => {
|
||||
let mut changed_count = 0;
|
||||
if let NbtTag::List(list) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if list.is_empty() {
|
||||
list.push(to_add());
|
||||
changed_count += 1;
|
||||
} else {
|
||||
for elem in list.iter_mut() {
|
||||
if compare_nbt(&pattern_tag, elem) {
|
||||
let new_val = to_add();
|
||||
if *elem != new_val {
|
||||
*elem = new_val;
|
||||
changed_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
changed_count
|
||||
}
|
||||
Self::MatchObject(name, pattern) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if let Some(curr) = compound.child_tags.get_mut(name.as_str()) {
|
||||
if compare_nbt(&pattern_tag, curr) {
|
||||
let new_val = to_add();
|
||||
if *curr != new_val {
|
||||
*curr = new_val;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Self::MatchRootObject(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_tag(&self, parent: &mut NbtTag) -> i32 {
|
||||
match self {
|
||||
Self::AllElements => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let size = list.len() as i32;
|
||||
if size > 0 {
|
||||
list.clear();
|
||||
return size;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Self::CompoundChild(name) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
if compound.child_tags.remove(name.as_str()).is_some() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Self::IndexedElement(index) => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let size = list.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < list.len() {
|
||||
list.remove(actual_index as usize);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Self::MatchElement(pattern) => {
|
||||
let mut changed_count = 0;
|
||||
if let NbtTag::List(list) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
let mut i = 0;
|
||||
while i < list.len() {
|
||||
if compare_nbt(&pattern_tag, &list[i]) {
|
||||
list.remove(i);
|
||||
changed_count += 1;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
changed_count
|
||||
}
|
||||
Self::MatchObject(name, pattern) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if let Some(curr) = compound.child_tags.get(name.as_str()) {
|
||||
if compare_nbt(&pattern_tag, curr) {
|
||||
compound.child_tags.remove(name.as_str());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Self::MatchRootObject(_) => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a parsed NBT path.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NbtPath {
|
||||
original: String,
|
||||
nodes: Vec<NbtPathNode>,
|
||||
node_to_original_position: Vec<usize>,
|
||||
}
|
||||
|
||||
impl NbtPath {
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
original: String,
|
||||
nodes: Vec<NbtPathNode>,
|
||||
node_to_original_position: Vec<usize>,
|
||||
) -> Self {
|
||||
Self {
|
||||
original,
|
||||
nodes,
|
||||
node_to_original_position,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.original
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn nodes(&self) -> &[NbtPathNode] {
|
||||
&self.nodes
|
||||
}
|
||||
|
||||
fn create_not_found_exception(&self, node_index: usize) -> CommandSyntaxError {
|
||||
let index = self
|
||||
.node_to_original_position
|
||||
.get(node_index)
|
||||
.copied()
|
||||
.unwrap_or(self.original.len());
|
||||
ERROR_NOTHING_FOUND
|
||||
.create_without_context(TextComponent::text(self.original[..index].to_string()))
|
||||
}
|
||||
|
||||
/// Gets matching tags from the given root tag.
|
||||
pub fn get(&self, tag: &NbtTag) -> Result<Vec<NbtTag>, CommandSyntaxError> {
|
||||
let mut current = vec![tag.clone()];
|
||||
for (i, node) in self.nodes.iter().enumerate() {
|
||||
let mut next = Vec::new();
|
||||
for parent in ¤t {
|
||||
node.get_tag(parent, &mut next);
|
||||
}
|
||||
if next.is_empty() {
|
||||
return Err(self.create_not_found_exception(i));
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
/// Counts how many elements match the path.
|
||||
pub fn count_matching(&self, tag: &NbtTag) -> usize {
|
||||
let mut current = vec![tag.clone()];
|
||||
for node in &self.nodes {
|
||||
let mut next = Vec::new();
|
||||
for parent in ¤t {
|
||||
node.get_tag(parent, &mut next);
|
||||
}
|
||||
if next.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
current.len()
|
||||
}
|
||||
|
||||
fn get_or_create_parents(
|
||||
&self,
|
||||
tag: &mut NbtTag,
|
||||
) -> Result<Vec<*mut NbtTag>, CommandSyntaxError> {
|
||||
let mut current: Vec<*mut NbtTag> = vec![tag as *mut NbtTag];
|
||||
for i in 0..self.nodes.len().saturating_sub(1) {
|
||||
let node = &self.nodes[i];
|
||||
let next_node = &self.nodes[i + 1];
|
||||
let mut next = Vec::new();
|
||||
for &parent_ptr in ¤t {
|
||||
// SAFETY: We traverse disjoint paths in the NBT tree.
|
||||
let parent = unsafe { &mut *parent_ptr };
|
||||
match node {
|
||||
NbtPathNode::CompoundChild(name) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
if !compound.child_tags.contains_key(name.as_str()) {
|
||||
compound.child_tags.insert(
|
||||
name.clone().into(),
|
||||
next_node.create_preferred_parent_tag(),
|
||||
);
|
||||
}
|
||||
if let Some(child) = compound.child_tags.get_mut(name.as_str()) {
|
||||
next.push(child as *mut NbtTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
NbtPathNode::AllElements => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
if list.is_empty() {
|
||||
list.push(next_node.create_preferred_parent_tag());
|
||||
}
|
||||
for elem in list.iter_mut() {
|
||||
next.push(elem as *mut NbtTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
NbtPathNode::IndexedElement(index) => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let size = list.len() as i32;
|
||||
let actual_index = if *index < 0 { size + index } else { *index };
|
||||
if actual_index >= 0 && (actual_index as usize) < list.len() {
|
||||
next.push(&mut list[actual_index as usize] as *mut NbtTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
NbtPathNode::MatchElement(pattern) => {
|
||||
if let NbtTag::List(list) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
let mut found = false;
|
||||
for elem in list.iter_mut() {
|
||||
if compare_nbt(&pattern_tag, elem) {
|
||||
next.push(elem as *mut NbtTag);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
list.push(pattern_tag.clone());
|
||||
if let Some(last) = list.last_mut() {
|
||||
next.push(last as *mut NbtTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
NbtPathNode::MatchObject(name, pattern) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if !compound.child_tags.contains_key(name.as_str()) {
|
||||
compound
|
||||
.child_tags
|
||||
.insert(name.clone().into(), pattern_tag.clone());
|
||||
}
|
||||
if let Some(child) = compound.child_tags.get_mut(name.as_str()) {
|
||||
if compare_nbt(&pattern_tag, child) {
|
||||
next.push(child as *mut NbtTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
NbtPathNode::MatchRootObject(pattern) => {
|
||||
let pattern_tag = NbtTag::Compound(pattern.clone());
|
||||
if compare_nbt(&pattern_tag, parent) {
|
||||
next.push(parent as *mut NbtTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if next.is_empty() {
|
||||
return Err(self.create_not_found_exception(i));
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
/// Sets the value at this path on the given root tag.
|
||||
pub fn set(&self, tag: &mut NbtTag, to_add: NbtTag) -> Result<i32, CommandSyntaxError> {
|
||||
if is_too_deep(&to_add, self.nodes.len()) {
|
||||
return Err(ERROR_DATA_TOO_DEEP.create_without_context());
|
||||
}
|
||||
let parents = self.get_or_create_parents(tag)?;
|
||||
if parents.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let last_node = match self.nodes.last() {
|
||||
Some(node) => node,
|
||||
None => return Ok(0),
|
||||
};
|
||||
let mut changed_count = 0;
|
||||
for &parent_ptr in &parents {
|
||||
let parent = unsafe { &mut *parent_ptr };
|
||||
let val_clone = to_add.clone();
|
||||
changed_count += last_node.set_tag(parent, &mut || val_clone.clone());
|
||||
}
|
||||
Ok(changed_count)
|
||||
}
|
||||
|
||||
/// Inserts elements at the given index into list targets matching this path.
|
||||
pub fn insert(
|
||||
&self,
|
||||
index: i32,
|
||||
target: &mut NbtTag,
|
||||
to_insert: &[NbtTag],
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
for tag in to_insert {
|
||||
if is_too_deep(tag, self.nodes.len()) {
|
||||
return Err(ERROR_DATA_TOO_DEEP.create_without_context());
|
||||
}
|
||||
}
|
||||
let parents = self.get_or_create_parents(target)?;
|
||||
let last_node = match self.nodes.last() {
|
||||
Some(node) => node,
|
||||
None => return Ok(0),
|
||||
};
|
||||
|
||||
let mut modified_count = 0;
|
||||
for &parent_ptr in &parents {
|
||||
let parent = unsafe { &mut *parent_ptr };
|
||||
let target_tags = match last_node {
|
||||
NbtPathNode::CompoundChild(name) => {
|
||||
if let NbtTag::Compound(compound) = parent {
|
||||
if !compound.child_tags.contains_key(name.as_str()) {
|
||||
compound
|
||||
.child_tags
|
||||
.insert(name.clone().into(), NbtTag::List(Vec::new()));
|
||||
}
|
||||
compound.child_tags.get_mut(name.as_str())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
NbtPathNode::MatchRootObject(_) => Some(parent),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(target_tag) = target_tags {
|
||||
match target_tag {
|
||||
NbtTag::List(list) => {
|
||||
let mut modified = false;
|
||||
let size = list.len() as i32;
|
||||
let mut actual_index = if index < 0 { size + index + 1 } else { index };
|
||||
for source_tag in to_insert {
|
||||
if actual_index < 0 || (actual_index as usize) > list.len() {
|
||||
return Err(ERROR_INVALID_INDEX.create_without_context(
|
||||
TextComponent::text(actual_index.to_string()),
|
||||
));
|
||||
}
|
||||
list.insert(actual_index as usize, source_tag.clone());
|
||||
actual_index += 1;
|
||||
modified = true;
|
||||
}
|
||||
if modified {
|
||||
modified_count += 1;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(ERROR_EXPECTED_LIST.create_without_context(
|
||||
TextComponent::text(format!("{target_tag:?}")),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(modified_count)
|
||||
}
|
||||
|
||||
/// Removes tags at this path from the given root tag.
|
||||
pub fn remove(&self, tag: &mut NbtTag) -> i32 {
|
||||
let parents = match self.get_or_create_parents(tag) {
|
||||
Ok(p) => p,
|
||||
Err(_) => return 0,
|
||||
};
|
||||
let last_node = match self.nodes.last() {
|
||||
Some(node) => node,
|
||||
None => return 0,
|
||||
};
|
||||
let mut total_removed = 0;
|
||||
for &parent_ptr in &parents {
|
||||
let parent = unsafe { &mut *parent_ptr };
|
||||
total_removed += last_node.remove_tag(parent);
|
||||
}
|
||||
total_removed
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NbtPath {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.original)
|
||||
}
|
||||
}
|
||||
|
||||
/// Argument type for parsing NBT Paths.
|
||||
pub struct NbtPathArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for NbtPathArgumentType {
|
||||
type Item = NbtPath;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let mut nodes = Vec::new();
|
||||
let start = reader.cursor();
|
||||
let mut node_to_original_position = Vec::new();
|
||||
let mut first_node = true;
|
||||
|
||||
while reader.can_read_char() && reader.peek() != Some(' ') {
|
||||
let node = parse_node(reader, first_node)?;
|
||||
nodes.push(node);
|
||||
node_to_original_position.push(reader.cursor() - start);
|
||||
first_node = false;
|
||||
if reader.can_read_char() {
|
||||
let next = reader.peek().unwrap();
|
||||
if next != ' ' && next != '[' && next != '{' {
|
||||
reader.expect('.')?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if nodes.is_empty() {
|
||||
return Err(ERROR_INVALID_NODE.create(reader));
|
||||
}
|
||||
|
||||
let original = reader.string()[start..reader.cursor()].to_string();
|
||||
Ok(NbtPath::new(original, nodes, node_to_original_position))
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::NbtPath
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("foo", "foo.bar", "foo[0]", "[0]", "[]", "{foo:\"bar\"}")
|
||||
}
|
||||
}
|
||||
|
||||
impl NbtPathArgumentType {
|
||||
pub fn get<'a, S: crate::source::CommandSource>(
|
||||
context: &'a CommandContext<S>,
|
||||
name: &'_ str,
|
||||
) -> Result<&'a NbtPath, CommandSyntaxError> {
|
||||
context.get_argument(name)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_node(
|
||||
reader: &mut StringReader,
|
||||
first_node: bool,
|
||||
) -> Result<NbtPathNode, CommandSyntaxError> {
|
||||
let peek = match reader.peek() {
|
||||
Some(c) => c,
|
||||
None => return Err(ERROR_INVALID_NODE.create(reader)),
|
||||
};
|
||||
match peek {
|
||||
'"' | '\'' => {
|
||||
let name = reader.read_string()?;
|
||||
read_object_node(reader, name)
|
||||
}
|
||||
'[' => {
|
||||
reader.skip();
|
||||
let next = match reader.peek() {
|
||||
Some(c) => c,
|
||||
None => return Err(ERROR_INVALID_NODE.create(reader)),
|
||||
};
|
||||
if next == '{' {
|
||||
let pattern = parse_compound_pattern(reader)?;
|
||||
reader.expect(']')?;
|
||||
Ok(NbtPathNode::MatchElement(pattern))
|
||||
} else if next == ']' {
|
||||
reader.skip();
|
||||
Ok(NbtPathNode::AllElements)
|
||||
} else {
|
||||
let index = reader.read_int()?;
|
||||
reader.expect(']')?;
|
||||
Ok(NbtPathNode::IndexedElement(index))
|
||||
}
|
||||
}
|
||||
'{' => {
|
||||
if !first_node {
|
||||
return Err(ERROR_INVALID_NODE.create(reader));
|
||||
}
|
||||
let pattern = parse_compound_pattern(reader)?;
|
||||
Ok(NbtPathNode::MatchRootObject(pattern))
|
||||
}
|
||||
_ => {
|
||||
let name = read_unquoted_name(reader)?;
|
||||
read_object_node(reader, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_object_node(
|
||||
reader: &mut StringReader,
|
||||
name: String,
|
||||
) -> Result<NbtPathNode, CommandSyntaxError> {
|
||||
if name.is_empty() {
|
||||
return Err(ERROR_INVALID_NODE.create(reader));
|
||||
}
|
||||
if reader.peek() == Some('{') {
|
||||
let pattern = parse_compound_pattern(reader)?;
|
||||
Ok(NbtPathNode::MatchObject(name, pattern))
|
||||
} else {
|
||||
Ok(NbtPathNode::CompoundChild(name))
|
||||
}
|
||||
}
|
||||
|
||||
fn read_unquoted_name(reader: &mut StringReader) -> Result<String, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
while let Some(c) = reader.peek() {
|
||||
if is_allowed_in_unquoted_name(c) {
|
||||
reader.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if reader.cursor() == start {
|
||||
return Err(ERROR_INVALID_NODE.create(reader));
|
||||
}
|
||||
Ok(reader.string()[start..reader.cursor()].to_string())
|
||||
}
|
||||
|
||||
const fn is_allowed_in_unquoted_name(c: char) -> bool {
|
||||
!matches!(c, ' ' | '"' | '\'' | '[' | ']' | '.' | '{' | '}')
|
||||
}
|
||||
|
||||
fn parse_compound_pattern(reader: &mut StringReader) -> Result<NbtCompound, CommandSyntaxError> {
|
||||
match SnbtParser::parse_for_commands(reader)? {
|
||||
NbtTag::Compound(compound) => Ok(compound),
|
||||
_ => Err(ERROR_INVALID_NODE.create(reader)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::particle::Particle;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const ERROR_UNKNOWN_PARTICLE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARTICLE_NOTFOUND,
|
||||
translation::bedrock::COMMANDS_PARTICLE_NOTFOUND,
|
||||
);
|
||||
|
||||
pub struct ParticleArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ParticleArgumentType {
|
||||
type Item = Particle;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let identifier = Identifier::from_reader(reader)?;
|
||||
Particle::from_name(identifier.path())
|
||||
.or_else(|| Particle::from_name(&identifier.to_string()))
|
||||
.ok_or_else(|| {
|
||||
ERROR_UNKNOWN_PARTICLE.create(reader, TextComponent::text(identifier.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Particle
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"foo".to_string(),
|
||||
"foo:bar".to_string(),
|
||||
"particle".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let particles = (0..=124u16)
|
||||
.filter_map(Particle::from_id)
|
||||
.map(|p| format!("{p:?}").to_lowercase())
|
||||
.collect();
|
||||
builder.filter_and_suggest_lowercase(particles).build()
|
||||
}
|
||||
}
|
||||
|
||||
impl ParticleArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<Particle, CommandSyntaxError> {
|
||||
Ok(*context.get_argument::<Particle>(name)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub struct PlacedFeatureNameArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for PlacedFeatureNameArgumentType {
|
||||
type Item = Identifier;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::feature::placed_features::all_placed_feature_names();
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().copied())
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceLocation
|
||||
}
|
||||
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
Some(SuggestionProviders::AskServer)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"minecraft:acacia".to_string(),
|
||||
"minecraft:amethyst_geode".to_string(),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
pub struct PoolNameArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for PoolNameArgumentType {
|
||||
type Item = Identifier;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::structure::template::all_pool_names();
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceLocation
|
||||
}
|
||||
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
Some(SuggestionProviders::AskServer)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec!["minecraft:village/plains/houses".to_string()]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use pumpkin_util::math::bounds::{DoubleBounds, IntBounds};
|
||||
|
||||
use crate::{
|
||||
argument_types::{
|
||||
FromStringReader,
|
||||
argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
},
|
||||
errors::command_syntax_error::CommandSyntaxError,
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// Parses an inclusive range of `i32`s that can be represented in the following ways:
|
||||
/// - `value`: Only includes the integer `value`.
|
||||
/// - `min..`: All integers above or equal to `min`.
|
||||
/// - `..max`: All integers below or equal to `max`.
|
||||
/// - `min..max`: All integers that are between `min` and `max`, inclusive. Mathematically representable as `[min, max]`.
|
||||
pub struct IntRangeArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for IntRangeArgumentType {
|
||||
type Item = IntBounds;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
IntBounds::from_reader(reader)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::IntRange
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("8", "2..", "..-3", "-4..5")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(IntRangeArgumentType, IntBounds);
|
||||
|
||||
/// Parses an inclusive range of `f64`s that can be represented in the following ways:
|
||||
/// - `value`: Only includes the number `value`.
|
||||
/// - `min..`: All numbers above or equal to `min`.
|
||||
/// - `..max`: All numbers below or equal to `max`.
|
||||
/// - `min..max`: All numbers that are between `min` and `max`, inclusive. Mathematically representable as `[min, max]`.
|
||||
pub struct FloatRangeArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for FloatRangeArgumentType {
|
||||
type Item = DoubleBounds;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
DoubleBounds::from_reader(reader)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::FloatRange
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("8", "8.0", "5..", "..-3.8", "-4.2..5", "0.1..0.2")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(FloatRangeArgumentType, DoubleBounds);
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use pumpkin_util::math::bounds::{DoubleBounds, IntBounds};
|
||||
|
||||
use crate::{
|
||||
argument_types::{
|
||||
SWAPPED_BOUNDS_ERROR_TYPE,
|
||||
range::{FloatRangeArgumentType, IntRangeArgumentType},
|
||||
},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_int_ranges() {
|
||||
let mut reader = StringReader::new("-7");
|
||||
assert_parse_ok_reset!(&mut reader, IntRangeArgumentType, IntBounds::new(-7, -7));
|
||||
|
||||
let mut reader = StringReader::new("3..");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
IntRangeArgumentType,
|
||||
IntBounds::new_at_least(3)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("..4");
|
||||
assert_parse_ok_reset!(&mut reader, IntRangeArgumentType, IntBounds::new_at_most(4));
|
||||
|
||||
let mut reader = StringReader::new("3..4");
|
||||
assert_parse_ok_reset!(&mut reader, IntRangeArgumentType, IntBounds::new(3, 4));
|
||||
|
||||
let mut reader = StringReader::new("-0..0");
|
||||
assert_parse_ok_reset!(&mut reader, IntRangeArgumentType, IntBounds::new(0, 0));
|
||||
|
||||
let mut reader = StringReader::new("2..1");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
IntRangeArgumentType,
|
||||
&SWAPPED_BOUNDS_ERROR_TYPE
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_float_ranges() {
|
||||
let mut reader = StringReader::new("-1");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(-1.0, -1.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("-1.0");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(-1.0, -1.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("0.");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(0.0, 0.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("3..");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new_at_least(3.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("..4");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new_at_most(4.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("3..4");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(3.0, 4.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("0.9");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(0.9, 0.9)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("0..9");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(0.0, 9.0)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("0...9");
|
||||
assert_parse_ok_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
DoubleBounds::new(0.0, 0.9)
|
||||
);
|
||||
|
||||
let mut reader = StringReader::new("2..1");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
FloatRangeArgumentType,
|
||||
&SWAPPED_BOUNDS_ERROR_TYPE
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::{CommandErrorType, DISPATCHER_PARSE_EXCEPTION};
|
||||
use crate::node::attached::AttachedNode;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::entity::EntityType;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::any::Any;
|
||||
use std::iter::Iterator;
|
||||
|
||||
pub static ENTITY_TYPE_REGISTRY: &Identifier = &Identifier::vanilla_static("entity_type");
|
||||
pub static ENCHANTMENT_REGISTRY: &Identifier = &Identifier::vanilla_static("enchantment");
|
||||
pub static MOB_EFFECT_REGISTRY: &Identifier = &Identifier::vanilla_static("mob_effect");
|
||||
pub static DAMAGE_TYPE_REGISTRY: &Identifier = &Identifier::vanilla_static("damage_type");
|
||||
|
||||
static DAMAGE_TYPES: [pumpkin_data::damage::DamageType; 51] = [
|
||||
pumpkin_data::damage::DamageType::ARROW,
|
||||
pumpkin_data::damage::DamageType::BAD_RESPAWN_POINT,
|
||||
pumpkin_data::damage::DamageType::CACTUS,
|
||||
pumpkin_data::damage::DamageType::CAMPFIRE,
|
||||
pumpkin_data::damage::DamageType::CRAMMING,
|
||||
pumpkin_data::damage::DamageType::DRAGON_BREATH,
|
||||
pumpkin_data::damage::DamageType::DROWN,
|
||||
pumpkin_data::damage::DamageType::DRY_OUT,
|
||||
pumpkin_data::damage::DamageType::ENDER_PEARL,
|
||||
pumpkin_data::damage::DamageType::EXPLOSION,
|
||||
pumpkin_data::damage::DamageType::FALL,
|
||||
pumpkin_data::damage::DamageType::FALLING_ANVIL,
|
||||
pumpkin_data::damage::DamageType::FALLING_BLOCK,
|
||||
pumpkin_data::damage::DamageType::FALLING_STALACTITE,
|
||||
pumpkin_data::damage::DamageType::FIREBALL,
|
||||
pumpkin_data::damage::DamageType::FIREWORKS,
|
||||
pumpkin_data::damage::DamageType::FLY_INTO_WALL,
|
||||
pumpkin_data::damage::DamageType::FREEZE,
|
||||
pumpkin_data::damage::DamageType::GENERIC,
|
||||
pumpkin_data::damage::DamageType::GENERIC_KILL,
|
||||
pumpkin_data::damage::DamageType::HOT_FLOOR,
|
||||
pumpkin_data::damage::DamageType::IN_FIRE,
|
||||
pumpkin_data::damage::DamageType::IN_WALL,
|
||||
pumpkin_data::damage::DamageType::INDIRECT_MAGIC,
|
||||
pumpkin_data::damage::DamageType::LAVA,
|
||||
pumpkin_data::damage::DamageType::LIGHTNING_BOLT,
|
||||
pumpkin_data::damage::DamageType::MACE_SMASH,
|
||||
pumpkin_data::damage::DamageType::MAGIC,
|
||||
pumpkin_data::damage::DamageType::MOB_ATTACK,
|
||||
pumpkin_data::damage::DamageType::MOB_ATTACK_NO_AGGRO,
|
||||
pumpkin_data::damage::DamageType::MOB_PROJECTILE,
|
||||
pumpkin_data::damage::DamageType::ON_FIRE,
|
||||
pumpkin_data::damage::DamageType::OUT_OF_WORLD,
|
||||
pumpkin_data::damage::DamageType::OUTSIDE_BORDER,
|
||||
pumpkin_data::damage::DamageType::PLAYER_ATTACK,
|
||||
pumpkin_data::damage::DamageType::PLAYER_EXPLOSION,
|
||||
pumpkin_data::damage::DamageType::SONIC_BOOM,
|
||||
pumpkin_data::damage::DamageType::SPEAR,
|
||||
pumpkin_data::damage::DamageType::SPIT,
|
||||
pumpkin_data::damage::DamageType::STALAGMITE,
|
||||
pumpkin_data::damage::DamageType::STARVE,
|
||||
pumpkin_data::damage::DamageType::STING,
|
||||
pumpkin_data::damage::DamageType::SULFUR_CUBE_HOT,
|
||||
pumpkin_data::damage::DamageType::SWEET_BERRY_BUSH,
|
||||
pumpkin_data::damage::DamageType::THORNS,
|
||||
pumpkin_data::damage::DamageType::THROWN,
|
||||
pumpkin_data::damage::DamageType::TRIDENT,
|
||||
pumpkin_data::damage::DamageType::UNATTRIBUTED_FIREBALL,
|
||||
pumpkin_data::damage::DamageType::WIND_CHARGE,
|
||||
pumpkin_data::damage::DamageType::WITHER,
|
||||
pumpkin_data::damage::DamageType::WITHER_SKULL,
|
||||
];
|
||||
|
||||
static ERROR_UNKNOWN_RESOURCE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_RESOURCE_NOT_FOUND,
|
||||
translation::java::ARGUMENT_RESOURCE_NOT_FOUND,
|
||||
);
|
||||
|
||||
static ERROR_INVALID_RESOURCE_TYPE: CommandErrorType<3> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_RESOURCE_INVALID_TYPE,
|
||||
translation::java::ARGUMENT_RESOURCE_INVALID_TYPE,
|
||||
);
|
||||
|
||||
static ERROR_NOT_SUMMONABLE_ENTITY: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ENTITY_NOT_SUMMONABLE,
|
||||
translation::java::ENTITY_NOT_SUMMONABLE,
|
||||
);
|
||||
|
||||
pub static ENTITY_TYPE_ARGUMENT: ResourceArgument =
|
||||
ResourceArgument(ENTITY_TYPE_REGISTRY, &|id: Identifier| {
|
||||
EntityType::from_name(id.path()).map(|value| value as &'static (dyn Any + Send + Sync))
|
||||
});
|
||||
|
||||
pub static ENCHANTMENT_ARGUMENT: ResourceArgument =
|
||||
ResourceArgument(ENCHANTMENT_REGISTRY, &|id: Identifier| {
|
||||
pumpkin_data::Enchantment::from_name(id.path())
|
||||
.or_else(|| pumpkin_data::Enchantment::from_name(&id.to_string()))
|
||||
.map(|value| value as &'static (dyn Any + Send + Sync))
|
||||
});
|
||||
|
||||
pub static MOB_EFFECT_ARGUMENT: ResourceArgument =
|
||||
ResourceArgument(MOB_EFFECT_REGISTRY, &|id: Identifier| {
|
||||
pumpkin_data::effect::StatusEffect::from_name(id.path())
|
||||
.or_else(|| pumpkin_data::effect::StatusEffect::from_minecraft_name(&id.to_string()))
|
||||
.map(|value| value as &'static (dyn Any + Send + Sync))
|
||||
});
|
||||
|
||||
pub static DAMAGE_TYPE_ARGUMENT: ResourceArgument =
|
||||
ResourceArgument(DAMAGE_TYPE_REGISTRY, &|id: Identifier| {
|
||||
let dt = pumpkin_data::damage::DamageType::from_name(id.path())
|
||||
.or_else(|| pumpkin_data::damage::DamageType::from_name(&id.to_string()))?;
|
||||
let idx = dt.id as usize;
|
||||
DAMAGE_TYPES
|
||||
.get(idx)
|
||||
.map(|val| val as &'static (dyn Any + Send + Sync))
|
||||
});
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ResourceArgument(
|
||||
pub &'static Identifier,
|
||||
pub &'static (dyn Fn(Identifier) -> Option<&'static (dyn Any + Send + Sync)> + Send + Sync),
|
||||
);
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ResourceArgument {
|
||||
type Item = &'static (dyn Any + Send + Sync);
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let identifier = Identifier::from_reader(reader)?;
|
||||
self.1(identifier.clone()).ok_or_else(|| {
|
||||
ERROR_UNKNOWN_RESOURCE.create(
|
||||
reader,
|
||||
TextComponent::text(identifier.path().to_string()),
|
||||
TextComponent::text(self.0.to_string()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
suggestions_builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
if self.0 == ENTITY_TYPE_REGISTRY {
|
||||
let entity_types = EntityType::ALL
|
||||
.iter()
|
||||
.filter(|entity_type| entity_type.summonable)
|
||||
.map(|entity_type| format!("minecraft:{}", entity_type.resource_name));
|
||||
suggestions_builder
|
||||
.filter_and_suggest_iter(entity_types)
|
||||
.build()
|
||||
} else if self.0 == ENCHANTMENT_REGISTRY {
|
||||
let enchantments = pumpkin_data::Enchantment::ALL
|
||||
.iter()
|
||||
.map(|e| format!("minecraft:{}", e.name));
|
||||
suggestions_builder
|
||||
.filter_and_suggest_iter(enchantments)
|
||||
.build()
|
||||
} else if self.0 == MOB_EFFECT_REGISTRY {
|
||||
let effects = [
|
||||
&pumpkin_data::effect::StatusEffect::ABSORPTION,
|
||||
&pumpkin_data::effect::StatusEffect::BAD_OMEN,
|
||||
&pumpkin_data::effect::StatusEffect::BLINDNESS,
|
||||
&pumpkin_data::effect::StatusEffect::BREATH_OF_THE_NAUTILUS,
|
||||
&pumpkin_data::effect::StatusEffect::CONDUIT_POWER,
|
||||
&pumpkin_data::effect::StatusEffect::DARKNESS,
|
||||
&pumpkin_data::effect::StatusEffect::DOLPHINS_GRACE,
|
||||
&pumpkin_data::effect::StatusEffect::FIRE_RESISTANCE,
|
||||
&pumpkin_data::effect::StatusEffect::GLOWING,
|
||||
&pumpkin_data::effect::StatusEffect::HASTE,
|
||||
&pumpkin_data::effect::StatusEffect::HEALTH_BOOST,
|
||||
&pumpkin_data::effect::StatusEffect::HERO_OF_THE_VILLAGE,
|
||||
&pumpkin_data::effect::StatusEffect::HUNGER,
|
||||
&pumpkin_data::effect::StatusEffect::INFESTED,
|
||||
&pumpkin_data::effect::StatusEffect::INSTANT_DAMAGE,
|
||||
&pumpkin_data::effect::StatusEffect::INSTANT_HEALTH,
|
||||
&pumpkin_data::effect::StatusEffect::INVISIBILITY,
|
||||
&pumpkin_data::effect::StatusEffect::JUMP_BOOST,
|
||||
&pumpkin_data::effect::StatusEffect::LEVITATION,
|
||||
&pumpkin_data::effect::StatusEffect::LUCK,
|
||||
&pumpkin_data::effect::StatusEffect::MINING_FATIGUE,
|
||||
&pumpkin_data::effect::StatusEffect::NAUSEA,
|
||||
&pumpkin_data::effect::StatusEffect::NIGHT_VISION,
|
||||
&pumpkin_data::effect::StatusEffect::OOZING,
|
||||
&pumpkin_data::effect::StatusEffect::POISON,
|
||||
&pumpkin_data::effect::StatusEffect::RAID_OMEN,
|
||||
&pumpkin_data::effect::StatusEffect::REGENERATION,
|
||||
&pumpkin_data::effect::StatusEffect::RESISTANCE,
|
||||
&pumpkin_data::effect::StatusEffect::SATURATION,
|
||||
&pumpkin_data::effect::StatusEffect::SLOW_FALLING,
|
||||
&pumpkin_data::effect::StatusEffect::SLOWNESS,
|
||||
&pumpkin_data::effect::StatusEffect::SPEED,
|
||||
&pumpkin_data::effect::StatusEffect::STRENGTH,
|
||||
&pumpkin_data::effect::StatusEffect::TRIAL_OMEN,
|
||||
&pumpkin_data::effect::StatusEffect::UNLUCK,
|
||||
&pumpkin_data::effect::StatusEffect::WATER_BREATHING,
|
||||
&pumpkin_data::effect::StatusEffect::WEAKNESS,
|
||||
&pumpkin_data::effect::StatusEffect::WEAVING,
|
||||
&pumpkin_data::effect::StatusEffect::WIND_CHARGED,
|
||||
&pumpkin_data::effect::StatusEffect::WITHER,
|
||||
]
|
||||
.iter()
|
||||
.map(|e| e.minecraft_name.to_string());
|
||||
suggestions_builder.filter_and_suggest_iter(effects).build()
|
||||
} else if self.0 == DAMAGE_TYPE_REGISTRY {
|
||||
let types = DAMAGE_TYPES
|
||||
.iter()
|
||||
.map(|dt| format!("minecraft:{}", dt.message_id));
|
||||
suggestions_builder.filter_and_suggest_iter(types).build()
|
||||
} else {
|
||||
Suggestions::empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Resource {
|
||||
identifier: self.0.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
(self.0 == ENTITY_TYPE_REGISTRY).then_some(SuggestionProviders::SummonableEntities)
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceArgument {
|
||||
pub fn get_resource<T: 'static, S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
registry_key: &Identifier,
|
||||
) -> Result<&'static T, CommandSyntaxError> {
|
||||
let missing_argument = DISPATCHER_PARSE_EXCEPTION.create_without_context(
|
||||
TextComponent::text(format!("Could not find argument with name '{name}'")),
|
||||
);
|
||||
let node = context
|
||||
.nodes
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|parsed| {
|
||||
if let AttachedNode::Argument(cur) = &context.tree[parsed.node]
|
||||
&& cur.meta.name == name
|
||||
{
|
||||
Some(cur)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.or_else(|| {
|
||||
context.tree.iter().find_map(|node| {
|
||||
if let AttachedNode::Argument(cur) = node
|
||||
&& cur.meta.name == name
|
||||
{
|
||||
Some(cur)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
.ok_or(missing_argument.clone())?;
|
||||
let invalid_argument =
|
||||
DISPATCHER_PARSE_EXCEPTION.create_without_context(TextComponent::text(format!(
|
||||
"argument with name '{name}' isn't a ResourceArgument"
|
||||
)));
|
||||
let result_argument = node
|
||||
.meta
|
||||
.argument_type
|
||||
.as_any()
|
||||
.downcast_ref::<Self>()
|
||||
.ok_or(invalid_argument)?;
|
||||
let registry_name = result_argument.0;
|
||||
let identifier = context
|
||||
.arguments
|
||||
.get(name)
|
||||
.ok_or(missing_argument)?
|
||||
.range
|
||||
.substring_slice(context.input.as_str())
|
||||
.to_string();
|
||||
let err = ERROR_INVALID_RESOURCE_TYPE.create_without_context(
|
||||
TextComponent::text(identifier),
|
||||
TextComponent::text(registry_name.to_string()),
|
||||
TextComponent::text(registry_key.to_string()),
|
||||
);
|
||||
if registry_name == registry_key {
|
||||
context
|
||||
.get_argument::<&'static (dyn Any + Send + Sync)>(name)?
|
||||
.downcast_ref::<T>()
|
||||
.ok_or(err)
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_entity_type<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'static EntityType, CommandSyntaxError> {
|
||||
Self::get_resource(context, name, ENTITY_TYPE_REGISTRY)
|
||||
}
|
||||
|
||||
pub fn get_enchantment<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'static pumpkin_data::Enchantment, CommandSyntaxError> {
|
||||
Self::get_resource(context, name, ENCHANTMENT_REGISTRY)
|
||||
}
|
||||
|
||||
pub fn get_mob_effect<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'static pumpkin_data::effect::StatusEffect, CommandSyntaxError> {
|
||||
Self::get_resource(context, name, MOB_EFFECT_REGISTRY)
|
||||
}
|
||||
|
||||
pub fn get_damage_type<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'static pumpkin_data::damage::DamageType, CommandSyntaxError> {
|
||||
Self::get_resource(context, name, DAMAGE_TYPE_REGISTRY)
|
||||
}
|
||||
|
||||
pub fn get_summonable_entity_type<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<&'static EntityType, CommandSyntaxError> {
|
||||
let val: &'static EntityType = Self::get_resource(context, name, ENTITY_TYPE_REGISTRY)?;
|
||||
if val.summonable {
|
||||
Ok(val)
|
||||
} else {
|
||||
Err(ERROR_NOT_SUMMONABLE_ENTITY
|
||||
.create_without_context(TextComponent::text(val.resource_name)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use pumpkin_data::structures::StructureSet;
|
||||
use pumpkin_data::tag::{self, RegistryKey};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub static BIOME_REGISTRY: Identifier = Identifier::vanilla_static("worldgen/biome");
|
||||
pub static STRUCTURE_REGISTRY: Identifier = Identifier::vanilla_static("worldgen/structure");
|
||||
pub static POI_REGISTRY: Identifier = Identifier::vanilla_static("point_of_interest_type");
|
||||
|
||||
pub static ERROR_UNKNOWN_RESOURCE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_RESOURCE_NOT_FOUND,
|
||||
translation::java::ARGUMENT_RESOURCE_NOT_FOUND,
|
||||
);
|
||||
|
||||
pub static ERROR_UNKNOWN_TAG: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_RESOURCE_TAG_NOT_FOUND,
|
||||
translation::java::ARGUMENT_RESOURCE_TAG_NOT_FOUND,
|
||||
);
|
||||
|
||||
/// A parsed reference to either a single registry entry or a `#`-prefixed tag
|
||||
/// of entries, as produced by [`ResourceOrTagKeyArgument`] and
|
||||
/// [`ResourceOrTagArgument`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ResourceOrTag {
|
||||
Resource(Identifier),
|
||||
Tag(Identifier),
|
||||
}
|
||||
|
||||
impl ResourceOrTag {
|
||||
/// The user-facing form of this reference (vanilla's `asPrintable`):
|
||||
/// `namespace:path` for entries, `#namespace:path` for tags.
|
||||
#[must_use]
|
||||
pub fn printable(&self) -> String {
|
||||
match self {
|
||||
Self::Resource(id) => id.to_string(),
|
||||
Self::Tag(id) => format!("#{id}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_string_reader(reader: &mut StringReader) -> Result<Self, CommandSyntaxError> {
|
||||
if reader.peek() == Some('#') {
|
||||
reader.skip();
|
||||
Ok(Self::Tag(Identifier::from_reader(reader)?))
|
||||
} else {
|
||||
Ok(Self::Resource(Identifier::from_reader(reader)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Registry-aware suggestions shared by both argument types: the known entry
|
||||
/// ids plus, when tag data exists for the registry, its `#`-prefixed tags.
|
||||
fn suggest_for_registry(registry: &Identifier, builder: SuggestionsBuilder) -> Suggestions {
|
||||
let tag_names = |key: RegistryKey| {
|
||||
tag::get_latest_map(key)
|
||||
.into_iter()
|
||||
.flat_map(|map| map.keys().map(|tag| format!("#{tag}")))
|
||||
};
|
||||
|
||||
if *registry == STRUCTURE_REGISTRY {
|
||||
// The generator models vanilla's structure sets, so those are the
|
||||
// locatable names. There is no structure tag data to offer.
|
||||
builder
|
||||
.filter_and_suggest_iter(
|
||||
StructureSet::NAMES
|
||||
.iter()
|
||||
.map(|name| format!("minecraft:{name}")),
|
||||
)
|
||||
.build()
|
||||
} else if *registry == BIOME_REGISTRY {
|
||||
let biomes = pumpkin_data::biome::Biome::ALL
|
||||
.iter()
|
||||
.map(|biome| format!("minecraft:{}", biome.registry_id));
|
||||
builder
|
||||
.filter_and_suggest_iter(biomes.chain(tag_names(RegistryKey::WorldgenBiome)))
|
||||
.build()
|
||||
} else if *registry == POI_REGISTRY {
|
||||
// There is no generated POI type registry (yet), so offer the types
|
||||
// known from tag data plus the ones the server actually creates.
|
||||
let poi_types = [
|
||||
"minecraft:armorer",
|
||||
"minecraft:butcher",
|
||||
"minecraft:cartographer",
|
||||
"minecraft:cleric",
|
||||
"minecraft:farmer",
|
||||
"minecraft:fisherman",
|
||||
"minecraft:fletcher",
|
||||
"minecraft:leatherworker",
|
||||
"minecraft:librarian",
|
||||
"minecraft:mason",
|
||||
"minecraft:shepherd",
|
||||
"minecraft:toolsmith",
|
||||
"minecraft:weaponsmith",
|
||||
"minecraft:home",
|
||||
"minecraft:meeting",
|
||||
"minecraft:beehive",
|
||||
"minecraft:bee_nest",
|
||||
"minecraft:nether_portal",
|
||||
"minecraft:lodestone",
|
||||
"minecraft:lightning_rod",
|
||||
];
|
||||
builder
|
||||
.filter_and_suggest_iter(
|
||||
poi_types
|
||||
.iter()
|
||||
.map(|&s| s.to_string())
|
||||
.chain(tag_names(RegistryKey::PointOfInterestType)),
|
||||
)
|
||||
.build()
|
||||
} else {
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
/// An argument type that parses an entry id or `#`-tag of a registry.
|
||||
///
|
||||
/// The value is not validated against the registry, like vanilla's
|
||||
/// `ResourceOrTagKeyArgument`; resolution (and the matching error) is left to
|
||||
/// the command.
|
||||
pub struct ResourceOrTagKeyArgument(pub Identifier);
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ResourceOrTagKeyArgument {
|
||||
type Item = ResourceOrTag;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
ResourceOrTag::from_string_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
suggest_for_registry(&self.0, builder)
|
||||
}
|
||||
|
||||
fn client_side_parser(&self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceOrTagKey {
|
||||
identifier: self.0.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("foo", "foo:bar", "#foo")
|
||||
}
|
||||
}
|
||||
|
||||
/// An argument type that parses and validates an entry id or `#`-tag of a
|
||||
/// registry.
|
||||
///
|
||||
/// Validation happens at parse time where registry data is available, like
|
||||
/// vanilla's `ResourceOrTagArgument`: it currently covers biome ids and the
|
||||
/// tags of every registry with generated tag data; ids of registries without
|
||||
/// generated entry data (such as POI types) are accepted as-is.
|
||||
pub struct ResourceOrTagArgument(pub Identifier);
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for ResourceOrTagArgument {
|
||||
type Item = ResourceOrTag;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let value = ResourceOrTag::from_string_reader(reader)?;
|
||||
|
||||
match &value {
|
||||
ResourceOrTag::Resource(id) => {
|
||||
if self.0 == BIOME_REGISTRY
|
||||
&& !(id.is_vanilla()
|
||||
&& pumpkin_data::biome::Biome::from_name(id.path()).is_some())
|
||||
{
|
||||
return Err(ERROR_UNKNOWN_RESOURCE.create_without_context(
|
||||
TextComponent::text(id.to_string()),
|
||||
TextComponent::text(self.0.to_string()),
|
||||
));
|
||||
}
|
||||
}
|
||||
ResourceOrTag::Tag(id) => {
|
||||
let registry_key = if self.0 == BIOME_REGISTRY {
|
||||
Some(RegistryKey::WorldgenBiome)
|
||||
} else if self.0 == POI_REGISTRY {
|
||||
Some(RegistryKey::PointOfInterestType)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(key) = registry_key
|
||||
&& tag::get_tag_values(key, &id.to_string()).is_none()
|
||||
{
|
||||
return Err(ERROR_UNKNOWN_TAG.create_without_context(
|
||||
TextComponent::text(id.to_string()),
|
||||
TextComponent::text(self.0.to_string()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
suggest_for_registry(&self.0, builder)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceOrTag {
|
||||
identifier: self.0.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("foo", "foo:bar", "#foo")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::slot_ranges::{
|
||||
SLOT_RANGE_ALL_NAMES, SLOT_RANGE_SINGLE_SLOT_NAMES, get_slot_range,
|
||||
};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const UNKNOWN_SLOT_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SLOT_UNKNOWN,
|
||||
translation::java::SLOT_UNKNOWN,
|
||||
);
|
||||
|
||||
pub const ONLY_SINGLE_SLOT_ALLOWED_ERROR_TYPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SLOT_ONLY_SINGLE_ALLOWED,
|
||||
translation::java::SLOT_ONLY_SINGLE_ALLOWED,
|
||||
);
|
||||
|
||||
pub struct SlotArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for SlotArgumentType {
|
||||
type Item = usize;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
reader.read_until_space();
|
||||
let name = &reader.string()[start..reader.cursor()];
|
||||
|
||||
match get_slot_range(name) {
|
||||
Some([slot]) => Ok(*slot),
|
||||
Some(_) => Err(ONLY_SINGLE_SLOT_ALLOWED_ERROR_TYPE
|
||||
.create(reader, TextComponent::text(name.to_string()))),
|
||||
None => {
|
||||
Err(UNKNOWN_SLOT_ERROR_TYPE.create(reader, TextComponent::text(name.to_string())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ItemSlot
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder
|
||||
.filter_and_suggest(&SLOT_RANGE_SINGLE_SLOT_NAMES)
|
||||
.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("weapon", "container.2", "enderchest.0")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(SlotArgumentType, usize);
|
||||
|
||||
pub struct SlotsArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for SlotsArgumentType {
|
||||
type Item = &'static [usize];
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
reader.read_until_space();
|
||||
let name = &reader.string()[start..reader.cursor()];
|
||||
|
||||
get_slot_range(name).ok_or_else(|| {
|
||||
let text = name.to_string();
|
||||
UNKNOWN_SLOT_ERROR_TYPE.create(reader, TextComponent::text(text))
|
||||
})
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ItemSlots
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&SLOT_RANGE_ALL_NAMES).build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("weapon", "container.2", "enderchest.*")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(SlotsArgumentType, &'static [usize]);
|
||||
@@ -0,0 +1,71 @@
|
||||
use pumpkin_data::sound::SoundCategory;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
pub const ERROR_INVALID_SOURCE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_ENUM_INVALID,
|
||||
translation::java::ARGUMENT_ENUM_INVALID,
|
||||
);
|
||||
|
||||
const CATEGORIES: [&str; 10] = [
|
||||
"master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient",
|
||||
"voice",
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct SoundCategoryArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for SoundCategoryArgumentType {
|
||||
type Item = SoundCategory;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
let s = reader.read_unquoted_string();
|
||||
match s.to_lowercase().as_str() {
|
||||
"master" => Ok(SoundCategory::Master),
|
||||
"music" => Ok(SoundCategory::Music),
|
||||
"record" => Ok(SoundCategory::Records),
|
||||
"weather" => Ok(SoundCategory::Weather),
|
||||
"block" => Ok(SoundCategory::Blocks),
|
||||
"hostile" => Ok(SoundCategory::Hostile),
|
||||
"neutral" => Ok(SoundCategory::Neutral),
|
||||
"player" => Ok(SoundCategory::Players),
|
||||
"ambient" => Ok(SoundCategory::Ambient),
|
||||
"voice" => Ok(SoundCategory::Voice),
|
||||
_ => {
|
||||
reader.set_cursor(start);
|
||||
Err(ERROR_INVALID_SOURCE.create(reader, TextComponent::text(s)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::String(
|
||||
pumpkin_protocol::java::client::play::StringProtoArgBehavior::SingleWord,
|
||||
)
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder.filter_and_suggest(&CATEGORIES).build()
|
||||
}
|
||||
}
|
||||
|
||||
impl SoundCategoryArgumentType {
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<SoundCategory, CommandSyntaxError> {
|
||||
context.get_argument::<SoundCategory>(name).copied()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
pub struct StructureNameArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for StructureNameArgumentType {
|
||||
type Item = Identifier;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
Identifier::from_reader(reader)
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::structure::template::all_structure_names();
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().copied())
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceLocation
|
||||
}
|
||||
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
Some(SuggestionProviders::AskServer)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec![
|
||||
"minecraft:village_plains".to_string(),
|
||||
"minecraft:ancient_city".to_string(),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation::java::ARGUMENT_COLOR_INVALID;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use pumpkin_util::text::color::NamedColor;
|
||||
|
||||
pub const INVALID_VALUE_ERROR_TYPE: CommandErrorType<1> =
|
||||
CommandErrorType::new(ARGUMENT_COLOR_INVALID, ARGUMENT_COLOR_INVALID);
|
||||
|
||||
pub struct TeamColorArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for TeamColorArgumentType {
|
||||
type Item = NamedColor;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let id = reader.read_unquoted_string();
|
||||
|
||||
(&*id).try_into().map_or_else(
|
||||
|()| Err(INVALID_VALUE_ERROR_TYPE.create(reader, TextComponent::text(id))),
|
||||
Ok,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Color
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
builder
|
||||
.filter_and_suggest(&[
|
||||
"black",
|
||||
"dark_blue",
|
||||
"dark_green",
|
||||
"dark_aqua",
|
||||
"dark_red",
|
||||
"dark_purple",
|
||||
"gold",
|
||||
"gray",
|
||||
"dark_gray",
|
||||
"blue",
|
||||
"green",
|
||||
"aqua",
|
||||
"red",
|
||||
"light_purple",
|
||||
"yellow",
|
||||
"white",
|
||||
])
|
||||
.build()
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("red", "blue", "yellow")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(TeamColorArgumentType, NamedColor);
|
||||
@@ -0,0 +1,42 @@
|
||||
use crate::argument_types::FromStringReader;
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_protocol::java::client::play::SuggestionProviders;
|
||||
use pumpkin_util::identifier::Identifier;
|
||||
|
||||
pub struct TemplateNameArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for TemplateNameArgumentType {
|
||||
type Item = String;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let identifier = Identifier::from_reader(reader)?;
|
||||
Ok(identifier.path().to_string())
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let names = pumpkin_world::generation::structure::template::all_template_names();
|
||||
builder
|
||||
.filter_and_suggest_iter(names.iter().map(|n| format!("minecraft:{n}")))
|
||||
.build()
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::ResourceLocation
|
||||
}
|
||||
|
||||
fn override_suggestion_providers(&self) -> Option<SuggestionProviders> {
|
||||
Some(SuggestionProviders::AskServer)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
vec!["igloo/top".to_string()]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
use crate::argument_types::argument_type::{ArgumentType, JavaClientArgumentType};
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::CommandErrorType;
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const INVALID_UNIT_ERROR_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_TIME_INVALID_UNIT,
|
||||
translation::java::ARGUMENT_TIME_INVALID_UNIT,
|
||||
);
|
||||
pub const TICK_COUNT_TOO_LOW_ERROR_TYPE: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_TIME_TICK_COUNT_TOO_LOW,
|
||||
translation::java::ARGUMENT_TIME_TICK_COUNT_TOO_LOW,
|
||||
);
|
||||
|
||||
/// Represents an argument type parsing a time value, which can
|
||||
/// have one of these suffixes:
|
||||
/// - `t` or *no suffix*: ticks
|
||||
/// - `s`: real-life seconds (20 ticks)
|
||||
/// - `d`: Minecraft days (24,000 ticks)
|
||||
///
|
||||
/// The provided `i32` by this argument type represents the value in *ticks*.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct TimeArgumentType {
|
||||
/// The minimum amount of time, in ticks, that this type accepts.
|
||||
pub min: i32,
|
||||
}
|
||||
|
||||
impl TimeArgumentType {
|
||||
/// Returns a [`TimeArgumentType`] that accepts any value of time.
|
||||
#[must_use]
|
||||
pub const fn any() -> Self {
|
||||
Self::new(0)
|
||||
}
|
||||
|
||||
/// Returns a [`TimeArgumentType`] that accepts any value of time lasting for at least `min` ticks.
|
||||
#[must_use]
|
||||
pub const fn new(min: i32) -> Self {
|
||||
Self { min }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for TimeArgumentType {
|
||||
type Item = i32;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let value = reader.read_float()?;
|
||||
let unit = reader.read_unquoted_string();
|
||||
// Find our unit's translation to ticks.
|
||||
let ticks_per_unit = match unit.as_str() {
|
||||
"t" | "" => 1,
|
||||
"s" => 20,
|
||||
"d" => 24000,
|
||||
_ => return Err(INVALID_UNIT_ERROR_TYPE.create(reader)),
|
||||
};
|
||||
let ticks = (ticks_per_unit as f32 * value).round() as i32;
|
||||
if ticks < self.min {
|
||||
Err(TICK_COUNT_TOO_LOW_ERROR_TYPE.create(
|
||||
reader,
|
||||
TextComponent::text(self.min.to_string()),
|
||||
TextComponent::text(ticks.to_string()),
|
||||
))
|
||||
} else {
|
||||
Ok(ticks)
|
||||
}
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Time { min: self.min }
|
||||
}
|
||||
|
||||
fn list_suggestions(
|
||||
&self,
|
||||
_context: &CommandContext<S>,
|
||||
suggestions_builder: SuggestionsBuilder,
|
||||
) -> Suggestions {
|
||||
let mut reader = StringReader::new(suggestions_builder.remaining());
|
||||
if reader.read_float().is_err() {
|
||||
suggestions_builder.build()
|
||||
} else {
|
||||
suggestions_builder
|
||||
.filter_and_suggest(&["t", "s", "d"])
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("12d", "14s", "789", "450t")
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeArgumentType {
|
||||
/// Returns a [`CommandContext`]'s parsed time argument in the form
|
||||
/// of its duration, in ticks.
|
||||
pub fn get<S: crate::source::CommandSource>(
|
||||
context: &CommandContext<S>,
|
||||
name: &str,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
Ok(*context.get_argument(name)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
argument_types::{time, time::TimeArgumentType},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_ticks() {
|
||||
// No unit
|
||||
let mut reader = StringReader::new("15");
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 15);
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::new(10), 15);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
TimeArgumentType::new(20),
|
||||
&time::TICK_COUNT_TOO_LOW_ERROR_TYPE
|
||||
);
|
||||
|
||||
// Unit
|
||||
let mut reader = StringReader::new("95t");
|
||||
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 95);
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::new(50), 95);
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
TimeArgumentType::new(150),
|
||||
&time::TICK_COUNT_TOO_LOW_ERROR_TYPE
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_other_units() {
|
||||
// Seconds
|
||||
let mut reader = StringReader::new("6s");
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 120);
|
||||
|
||||
// The argument type rounds decimals after multiplication
|
||||
// to the nearest integer.
|
||||
let mut reader = StringReader::new("4.5s");
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 90);
|
||||
let mut reader = StringReader::new("4.633s");
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 93);
|
||||
|
||||
let mut reader = StringReader::new("-0.2s");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
TimeArgumentType::any(),
|
||||
&time::TICK_COUNT_TOO_LOW_ERROR_TYPE
|
||||
);
|
||||
|
||||
// Minecraft days
|
||||
let mut reader = StringReader::new("9d");
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 24000 * 9);
|
||||
let mut reader = StringReader::new("7.1234d");
|
||||
assert_parse_ok_reset!(&mut reader, TimeArgumentType::any(), 170962);
|
||||
|
||||
// Invalid units
|
||||
let mut reader = StringReader::new("14m");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
TimeArgumentType::any(),
|
||||
&time::INVALID_UNIT_ERROR_TYPE
|
||||
);
|
||||
let mut reader = StringReader::new("1w");
|
||||
assert_parse_err_reset!(
|
||||
&mut reader,
|
||||
TimeArgumentType::any(),
|
||||
&time::INVALID_UNIT_ERROR_TYPE
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use pumpkin_data::translation::java::ARGUMENT_UUID_INVALID;
|
||||
use pumpkin_util::uuid::parse_uuid;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
argument_types::argument_type::{ArgumentType, JavaClientArgumentType},
|
||||
errors::{command_syntax_error::CommandSyntaxError, error_types::CommandErrorType},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
pub const INVALID_UUID_ERROR_TYPE: CommandErrorType<0> =
|
||||
CommandErrorType::new(ARGUMENT_UUID_INVALID, ARGUMENT_UUID_INVALID);
|
||||
|
||||
/// Represents an argument type parsing a [`Uuid`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct UuidArgumentType;
|
||||
|
||||
impl<S: crate::source::CommandSource> ArgumentType<S> for UuidArgumentType {
|
||||
type Item = Uuid;
|
||||
|
||||
fn parse(&self, reader: &mut StringReader) -> Result<Self::Item, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
|
||||
while matches!(reader.peek(), Some('A'..='F' | 'a'..='f' | '0'..='9' | '-')) {
|
||||
reader.skip();
|
||||
}
|
||||
|
||||
parse_uuid(&reader.string()[start..reader.cursor()]).map_or_else(
|
||||
|| {
|
||||
reader.set_cursor(start);
|
||||
Err(INVALID_UUID_ERROR_TYPE.create(reader))
|
||||
},
|
||||
Ok,
|
||||
)
|
||||
}
|
||||
|
||||
fn client_side_parser(&'_ self) -> JavaClientArgumentType {
|
||||
JavaClientArgumentType::Uuid
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<String> {
|
||||
examples!("3d569d3a-93ef-44a0-9f1c-f69db9d37a56")
|
||||
}
|
||||
}
|
||||
|
||||
impl_copy_get!(UuidArgumentType, Uuid);
|
||||
@@ -0,0 +1,730 @@
|
||||
use crate::context::string_range::StringRange;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::DISPATCHER_PARSE_EXCEPTION;
|
||||
use crate::node::attached::NodeId;
|
||||
use crate::node::dispatcher::{CommandDispatcher, ResultConsumer};
|
||||
use crate::node::tree::Tree;
|
||||
use crate::node::{Command, RedirectModifier};
|
||||
use crate::source::{CommandSource, DummySource, ReturnValue};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Represents the current stage of the chain.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub enum Stage {
|
||||
MODIFY,
|
||||
EXECUTE,
|
||||
}
|
||||
|
||||
/// Represents a parsed node.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct ParsedNode {
|
||||
pub node: NodeId,
|
||||
pub range: StringRange,
|
||||
}
|
||||
|
||||
/// Represents a suggestional context involving a node.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct SuggestionContext {
|
||||
pub parent: NodeId,
|
||||
pub starting_position: usize,
|
||||
}
|
||||
|
||||
/// Represents a parsed argument of any type.
|
||||
pub struct ParsedArgument {
|
||||
/// The range of this parsed argument.
|
||||
pub range: StringRange,
|
||||
|
||||
/// The result of this parsed argument.
|
||||
pub result: Box<dyn Any + Send + Sync>,
|
||||
}
|
||||
|
||||
impl ParsedArgument {
|
||||
/// Creates a new [`ParsedArgument`] from its range and resultant value.
|
||||
#[must_use]
|
||||
pub fn new(range: StringRange, result: Box<dyn Any + Send + Sync>) -> Self {
|
||||
Self { range, result }
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the context used when commands are run.
|
||||
#[derive(Clone)]
|
||||
pub struct CommandContext<'a, S: CommandSource = DummySource> {
|
||||
/// The source running the commands.
|
||||
pub source: Arc<S>,
|
||||
|
||||
/// The input string ran as the command.
|
||||
pub input: String,
|
||||
|
||||
/// Arguments which have been parsed and
|
||||
/// can be fetched for command execution.
|
||||
pub arguments: FxHashMap<String, Arc<ParsedArgument>>,
|
||||
|
||||
/// The tree this context is related to.
|
||||
pub tree: &'a Tree<S>,
|
||||
|
||||
/// The root that this context will use, bound to the tree.
|
||||
/// Not necessarily the root node of the tree, however.
|
||||
pub root: NodeId,
|
||||
|
||||
/// All the parsed nodes of the command.
|
||||
pub nodes: Vec<ParsedNode>,
|
||||
|
||||
/// The string range of input.
|
||||
pub range: StringRange,
|
||||
|
||||
/// The child context of this context.
|
||||
pub child: Option<Arc<Self>>,
|
||||
|
||||
/// The redirect modifier of this context.
|
||||
pub modifier: RedirectModifier<S>,
|
||||
|
||||
/// Whether this context forks or not.
|
||||
pub forks: bool,
|
||||
|
||||
/// The command stored in this context which
|
||||
/// is run to get a command result.
|
||||
pub command: Option<Command<S>>,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> std::ops::Deref for CommandContext<'_, S> {
|
||||
type Target = S;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.source
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> CommandContext<'_, S> {
|
||||
/// Copies this context with the source provided.
|
||||
#[must_use]
|
||||
pub fn with_source(&self, source: Arc<S>) -> Self {
|
||||
Self {
|
||||
source,
|
||||
input: self.input.clone(),
|
||||
arguments: self.arguments.clone(),
|
||||
nodes: self.nodes.clone(),
|
||||
range: self.range,
|
||||
child: self.child.clone(),
|
||||
modifier: self.modifier.clone(),
|
||||
forks: self.forks,
|
||||
command: self.command.clone(),
|
||||
tree: self.tree,
|
||||
root: self.root,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the child immediately below this node.
|
||||
#[must_use]
|
||||
pub const fn get_child(&self) -> Option<&Arc<Self>> {
|
||||
self.child.as_ref()
|
||||
}
|
||||
|
||||
/// Returns the child which does not have a child which originated from this node.
|
||||
/// This may return itself.
|
||||
#[must_use]
|
||||
pub fn get_last_child(&self) -> &Self {
|
||||
let mut current_child = self;
|
||||
while let Some(child) = ¤t_child.child {
|
||||
current_child = child;
|
||||
}
|
||||
current_child
|
||||
}
|
||||
|
||||
/// Returns a reference to a particular argument with type `T`.
|
||||
/// If it fails, an error with the appropriate message is returned.
|
||||
///
|
||||
/// Ideally should be used with the `?` operator.
|
||||
///
|
||||
/// # Example
|
||||
/// A simple example that takes two arguments specified from the node
|
||||
/// and returns their sum as the status output of the `Executor`:
|
||||
/// ```
|
||||
/// use pumpkin_command::context::command_context::CommandContext;
|
||||
/// use pumpkin_command::node::{CommandExecutor, CommandExecutorResult};
|
||||
///
|
||||
/// struct Executor;
|
||||
/// impl CommandExecutor for Executor {
|
||||
/// fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
/// // The `get_argument` method returns a `Result<&i32, CommandSyntaxError>`.
|
||||
/// // We apply the `?` operator first, propagating the `CommandSyntaxError` if contained.
|
||||
/// // Finally, we dereference the `&i32`, as `i32` implements Copy.
|
||||
/// let operand1: i32 = *context.get_argument("operand1")?;
|
||||
/// let operand2: i32 = *context.get_argument("operand2")?;
|
||||
/// Ok(operand1 + operand2)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub fn get_argument<T: 'static>(&self, name: &str) -> Result<&T, CommandSyntaxError> {
|
||||
// The errors below should never happen due to user input.
|
||||
// If an error below this comment is returned, that means the command was
|
||||
// improperly defined.
|
||||
//
|
||||
// Still, we provide helpful errors instead of panicking.
|
||||
|
||||
let arg = self.arguments.get(name).ok_or_else(|| {
|
||||
DISPATCHER_PARSE_EXCEPTION.create_without_context(TextComponent::text(format!(
|
||||
"Could not find argument with name '{name}'"
|
||||
)))
|
||||
})?;
|
||||
let dyn_ref = &*arg.result;
|
||||
dyn_ref.downcast_ref::<T>().ok_or_else(|| {
|
||||
DISPATCHER_PARSE_EXCEPTION.create_without_context(TextComponent::text(format!(
|
||||
"Could not downcast argument '{name}'"
|
||||
)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a linked chain of [`CommandContext`]s, where the previous links to the next as a child.
|
||||
#[derive(Clone)]
|
||||
pub struct ContextChain<'a, S: CommandSource = DummySource> {
|
||||
/// The modifiers of this context chain.
|
||||
modifiers: Vec<Arc<CommandContext<'a, S>>>,
|
||||
|
||||
/// That specific [`CommandContext`] to execute.
|
||||
execute: Arc<CommandContext<'a, S>>,
|
||||
}
|
||||
|
||||
impl<'a, S: CommandSource> ContextChain<'a, S> {
|
||||
/// Creates a new chain of contexts from a vector of them and one to execute.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the `execute` given is non-executable.
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
modifiers: Vec<Arc<CommandContext<'a, S>>>,
|
||||
execute: Arc<CommandContext<'a, S>>,
|
||||
) -> Self {
|
||||
assert!(
|
||||
execute.command.is_some(),
|
||||
"Expected last command in chain to be executable"
|
||||
);
|
||||
Self { modifiers, execute }
|
||||
}
|
||||
|
||||
/// Tries to flatten a [`CommandContext`]. If no command
|
||||
/// is available at the end of chain, [`None`] is returned.
|
||||
#[must_use]
|
||||
pub fn try_flatten(root: &CommandContext<'a, S>) -> Option<Self> {
|
||||
let mut modifiers = Vec::new();
|
||||
let mut current = Arc::new(root.clone());
|
||||
loop {
|
||||
if let Some(child) = current.get_child() {
|
||||
let temp_child = child.clone();
|
||||
modifiers.push(current);
|
||||
current = temp_child;
|
||||
} else {
|
||||
return current
|
||||
.command
|
||||
.is_some()
|
||||
.then(|| Self::new(modifiers, current));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the given modifier with provided details.
|
||||
pub fn run_modifier(
|
||||
modifier: &CommandContext<'a, S>,
|
||||
source: &Arc<S>,
|
||||
result_consumer: &dyn ResultConsumer<S>,
|
||||
forked_mode: bool,
|
||||
) -> Result<Vec<Arc<S>>, CommandSyntaxError> {
|
||||
let source_modifier = &modifier.modifier;
|
||||
|
||||
if matches!(source_modifier, RedirectModifier::KeepSource) {
|
||||
return Ok(vec![source.clone()]);
|
||||
}
|
||||
|
||||
let context_to_use = modifier.with_source(source.clone());
|
||||
let mut result = source_modifier.sources(&context_to_use);
|
||||
|
||||
if result.is_err() {
|
||||
result_consumer.on_command_completion(&context_to_use, ReturnValue::Failure);
|
||||
if forked_mode {
|
||||
result = Ok(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs the given executable, returning an [`i32`] on success.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the `executable` provided cannot be executed.
|
||||
pub fn run_executable(
|
||||
executable: &CommandContext<'a, S>,
|
||||
source: &Arc<S>,
|
||||
result_consumer: &dyn ResultConsumer<S>,
|
||||
forked_mode: bool,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
let context_to_use = executable.with_source(source.clone());
|
||||
|
||||
let mut result = executable.command.as_ref().map_or_else(
|
||||
|| panic!("Expected `executable` to be executable"),
|
||||
|command| command.execute(&context_to_use),
|
||||
);
|
||||
|
||||
if let Ok(result) = result {
|
||||
result_consumer.on_command_completion(&context_to_use, ReturnValue::Success(result));
|
||||
Ok(if forked_mode { 1 } else { result })
|
||||
} else {
|
||||
result_consumer.on_command_completion(&context_to_use, ReturnValue::Failure);
|
||||
if forked_mode {
|
||||
result = Ok(0);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes all contexts in the chain, returning the ultimate result.
|
||||
pub fn execute_all(
|
||||
&self,
|
||||
source: &Arc<S>,
|
||||
result_consumer: &dyn ResultConsumer<S>,
|
||||
) -> Result<i32, CommandSyntaxError> {
|
||||
if self.modifiers.is_empty() {
|
||||
return Self::run_executable(&self.execute, source, result_consumer, false);
|
||||
}
|
||||
|
||||
let mut forked_mode = false;
|
||||
let mut current_sources: Vec<Arc<S>> = vec![source.clone()];
|
||||
|
||||
for modifier in &self.modifiers {
|
||||
forked_mode |= modifier.forks;
|
||||
|
||||
let mut next_sources = Vec::new();
|
||||
for source in current_sources {
|
||||
let mut to_add =
|
||||
Self::run_modifier(modifier, &source, result_consumer, forked_mode)?;
|
||||
next_sources.append(&mut to_add);
|
||||
}
|
||||
if next_sources.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
current_sources = next_sources;
|
||||
}
|
||||
|
||||
let mut result = 0;
|
||||
for execution_source in current_sources {
|
||||
result += Self::run_executable(
|
||||
&self.execute,
|
||||
&execution_source,
|
||||
result_consumer,
|
||||
forked_mode,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Gets the current stage of this context.
|
||||
#[must_use]
|
||||
pub const fn get_stage(&self) -> Stage {
|
||||
if self.modifiers.is_empty() {
|
||||
Stage::EXECUTE
|
||||
} else {
|
||||
Stage::MODIFY
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a reference to the top context of this chain.
|
||||
#[must_use]
|
||||
pub fn get_top_context(&'_ self) -> &'_ Arc<CommandContext<'a, S>> {
|
||||
if self.modifiers.is_empty() {
|
||||
&self.execute
|
||||
} else {
|
||||
&self.modifiers[0]
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the top context of this chain.
|
||||
pub fn get_top_context_mut(&'_ mut self) -> &mut Arc<CommandContext<'a, S>> {
|
||||
if self.modifiers.is_empty() {
|
||||
&mut self.execute
|
||||
} else {
|
||||
&mut self.modifiers[0]
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the next stage of this chain.
|
||||
#[must_use]
|
||||
pub fn next_stage(&self) -> Option<Self> {
|
||||
if self.modifiers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(Self::new(
|
||||
self.modifiers[1..].to_vec(),
|
||||
self.execute.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder that helps to create a [`CommandContext`].
|
||||
///
|
||||
/// This builder's lifetime is bound to the dispatcher provided to it.
|
||||
#[derive(Clone)]
|
||||
pub struct CommandContextBuilder<'a, S: CommandSource = DummySource> {
|
||||
/// The dispatcher this builder is related to.
|
||||
pub dispatcher: &'a CommandDispatcher<S>,
|
||||
|
||||
/// The source running the commands.
|
||||
pub source: Arc<S>,
|
||||
|
||||
/// Arguments which have been parsed and
|
||||
/// can be fetched for command execution.
|
||||
pub arguments: FxHashMap<String, Arc<ParsedArgument>>,
|
||||
|
||||
/// The root that this context will use, bound to the tree
|
||||
/// Not necessarily the root node of the tree, however.
|
||||
pub root: NodeId,
|
||||
|
||||
/// All the parsed nodes of the command.
|
||||
pub nodes: Vec<ParsedNode>,
|
||||
|
||||
/// The string range of input.
|
||||
pub range: StringRange,
|
||||
|
||||
/// The child context of this context.
|
||||
pub child: Option<Box<Self>>,
|
||||
|
||||
/// The redirect modifier of this context.
|
||||
pub modifier: RedirectModifier<S>,
|
||||
|
||||
/// Whether this context forks or not.
|
||||
pub forks: bool,
|
||||
|
||||
/// The command stored in this context which
|
||||
/// is run to get a command result.
|
||||
pub command: Option<Command<S>>,
|
||||
}
|
||||
|
||||
impl<'a, S: CommandSource> CommandContextBuilder<'a, S> {
|
||||
/// Creates a new [`CommandContextBuilder`] from the properties required to initialize one.
|
||||
///
|
||||
/// Note that builder's lifetime is bound to the dispatcher provided to it.
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
dispatcher: &'a CommandDispatcher<S>,
|
||||
source: Arc<S>,
|
||||
root: NodeId,
|
||||
start: usize,
|
||||
) -> Self {
|
||||
CommandContextBuilder {
|
||||
dispatcher,
|
||||
source,
|
||||
arguments: FxHashMap::default(),
|
||||
root,
|
||||
nodes: Vec::new(),
|
||||
range: StringRange::at(start),
|
||||
child: None,
|
||||
modifier: RedirectModifier::KeepSource,
|
||||
forks: false,
|
||||
command: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the required [`CommandContext`], consuming itself in the process.
|
||||
#[must_use]
|
||||
pub fn build(self, input: &str) -> CommandContext<'a, S> {
|
||||
CommandContext {
|
||||
source: self.source,
|
||||
input: input.to_string(),
|
||||
arguments: self.arguments,
|
||||
tree: &self.dispatcher.tree,
|
||||
root: self.root,
|
||||
nodes: self.nodes,
|
||||
range: self.range,
|
||||
child: self.child.map(|child| Arc::new(child.build(input))),
|
||||
modifier: self.modifier,
|
||||
forks: self.forks,
|
||||
command: self.command,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutates itself with the new source set.
|
||||
pub fn with_source(&mut self, source: Arc<S>) {
|
||||
self.source = source;
|
||||
}
|
||||
|
||||
/// Mutates itself with a new argument added.
|
||||
pub fn with_argument(&mut self, name: String, argument: Arc<ParsedArgument>) {
|
||||
self.arguments.insert(name, argument);
|
||||
}
|
||||
|
||||
/// Mutates itself with the new command set.
|
||||
pub fn with_command(&mut self, command: Option<Command<S>>) {
|
||||
self.command = command;
|
||||
}
|
||||
|
||||
/// Mutates itself with a new node added to this builder.
|
||||
pub fn with_node(&mut self, node: NodeId, range: StringRange) {
|
||||
self.nodes.push(ParsedNode { node, range });
|
||||
self.range = StringRange::encompass(self.range, range);
|
||||
self.modifier = self.dispatcher.tree[node].modifier().clone();
|
||||
self.forks = self.dispatcher.tree[node].forks();
|
||||
}
|
||||
|
||||
/// Mutates itself with the new child set.
|
||||
pub fn with_child(&mut self, child: Self) {
|
||||
self.child = Some(Box::new(child));
|
||||
}
|
||||
|
||||
/// Mutates the last child of this builder.
|
||||
#[must_use]
|
||||
pub fn last_child(&self) -> &Self {
|
||||
let mut result = self;
|
||||
while let Some(child) = &result.child {
|
||||
result = child;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Creates a [`SuggestionContext`] from the provided cursor position.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the node couldn't be found before the cursor.
|
||||
#[must_use]
|
||||
pub fn find_suggestion_context(&self, cursor: usize) -> SuggestionContext {
|
||||
assert!(
|
||||
self.range.start <= cursor,
|
||||
"Could not find node before cursor"
|
||||
);
|
||||
if self.range.end < cursor {
|
||||
self.child.as_ref().map_or_else(
|
||||
|| {
|
||||
self.nodes.last().as_ref().map_or_else(
|
||||
|| SuggestionContext {
|
||||
parent: self.root,
|
||||
starting_position: self.range.start,
|
||||
},
|
||||
|last_node| SuggestionContext {
|
||||
parent: last_node.node,
|
||||
starting_position: last_node.range.end + 1,
|
||||
},
|
||||
)
|
||||
},
|
||||
|child| child.find_suggestion_context(cursor),
|
||||
)
|
||||
} else {
|
||||
let mut previous = self.root;
|
||||
for node in &self.nodes {
|
||||
let node_range = node.range;
|
||||
if (node_range.start..=node_range.end).contains(&cursor) {
|
||||
return SuggestionContext {
|
||||
parent: previous,
|
||||
starting_position: node_range.start,
|
||||
};
|
||||
}
|
||||
previous = node.node;
|
||||
}
|
||||
SuggestionContext {
|
||||
parent: previous,
|
||||
starting_position: self.range.start,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::argument_builder::{ArgumentBuilder, CommandArgumentBuilder};
|
||||
use crate::context::command_context::{
|
||||
CommandContext, CommandContextBuilder, ContextChain, ParsedArgument, Stage,
|
||||
};
|
||||
use crate::context::string_range::StringRange;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::node::dispatcher::{CommandDispatcher, EmptyResultConsumer};
|
||||
use crate::node::tree::ROOT_NODE_ID;
|
||||
use crate::node::{CommandExecutor, CommandExecutorResult, RedirectModifier, Redirection};
|
||||
use crate::source::DummySource;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct TenExecutor;
|
||||
impl CommandExecutor for TenExecutor {
|
||||
fn execute(&self, _context: &CommandContext) -> CommandExecutorResult {
|
||||
Ok(10)
|
||||
}
|
||||
}
|
||||
|
||||
// For testing purposes
|
||||
fn builder(dispatcher: &'_ CommandDispatcher) -> CommandContextBuilder<'_> {
|
||||
let mut builder =
|
||||
CommandContextBuilder::new(dispatcher, Arc::new(DummySource::dummy()), ROOT_NODE_ID, 0);
|
||||
|
||||
let parsed_argument = ParsedArgument::new(StringRange::between(0, 1), Box::new(6789i32));
|
||||
|
||||
builder.with_argument("foo".to_string(), Arc::new(parsed_argument));
|
||||
|
||||
builder
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_argument() -> Result<(), CommandSyntaxError> {
|
||||
let dispatcher = CommandDispatcher::new();
|
||||
let builder = builder(&dispatcher);
|
||||
|
||||
let context = builder.build("6789");
|
||||
assert_eq!(context.get_argument::<i32>("foo")?, &6789);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_nonexistent_argument() {
|
||||
let dispatcher = CommandDispatcher::new();
|
||||
let builder = builder(&dispatcher);
|
||||
|
||||
let context = builder.build("6789");
|
||||
assert!(context.get_argument::<i32>("bar").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_different_type_argument() {
|
||||
let dispatcher = CommandDispatcher::new();
|
||||
let builder = builder(&dispatcher);
|
||||
|
||||
let context = builder.build("6789");
|
||||
assert!(context.get_argument::<f32>("foo").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_single_command_chain() {
|
||||
let mut dispatcher = CommandDispatcher::new();
|
||||
dispatcher
|
||||
.register(CommandArgumentBuilder::new("foo", "A test command").executes(TenExecutor));
|
||||
|
||||
let source = Arc::new(DummySource::dummy());
|
||||
let result = dispatcher.parse_input("foo", &source);
|
||||
let top_context = result.context.build("foo");
|
||||
let chain = ContextChain::try_flatten(&top_context)
|
||||
.expect("The context should have properly flattened, as it has a command to execute");
|
||||
|
||||
assert_eq!(chain.execute_all(&source, &EmptyResultConsumer), Ok(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_redirected_command_chain() {
|
||||
let mut dispatcher = CommandDispatcher::new();
|
||||
dispatcher
|
||||
.register(CommandArgumentBuilder::new("foo", "A test command").executes(TenExecutor));
|
||||
dispatcher.register(
|
||||
CommandArgumentBuilder::new("bar", "Another test command").redirect(Redirection::Root),
|
||||
);
|
||||
|
||||
let source = Arc::new(DummySource::dummy());
|
||||
let result = dispatcher.parse_input("bar foo", &source);
|
||||
let top_context = result.context.build("bar foo");
|
||||
let chain = ContextChain::try_flatten(&top_context)
|
||||
.expect("The context should have properly flattened, as it has a command to execute");
|
||||
|
||||
assert_eq!(chain.execute_all(&source, &EmptyResultConsumer), Ok(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_stage_execution() {
|
||||
let mut dispatcher = CommandDispatcher::new();
|
||||
dispatcher
|
||||
.register(CommandArgumentBuilder::new("foo", "A test command").executes(TenExecutor));
|
||||
|
||||
let source = Arc::new(DummySource::dummy());
|
||||
let result = dispatcher.parse_input("foo", &source);
|
||||
let top_context = result.context.build("foo");
|
||||
let chain = ContextChain::try_flatten(&top_context)
|
||||
.expect("The context should have properly flattened, as it has a command to execute");
|
||||
|
||||
assert_eq!(chain.get_stage(), Stage::EXECUTE);
|
||||
assert!(chain.next_stage().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_stage_execution() {
|
||||
let mut dispatcher = CommandDispatcher::new();
|
||||
dispatcher
|
||||
.register(CommandArgumentBuilder::new("foo", "A test command").executes(TenExecutor));
|
||||
dispatcher.register(
|
||||
CommandArgumentBuilder::new("bar", "Another test command").redirect(Redirection::Root),
|
||||
);
|
||||
dispatcher.register(
|
||||
CommandArgumentBuilder::new("qux", "Yet another test command")
|
||||
.redirect(Redirection::Root),
|
||||
);
|
||||
|
||||
let source = Arc::new(DummySource::dummy());
|
||||
let result = dispatcher.parse_input("bar qux foo", &source);
|
||||
let top_context = result.context.build("bar qux foo");
|
||||
let chain = ContextChain::try_flatten(&top_context)
|
||||
.expect("The context should have properly flattened, as it has a command to execute");
|
||||
assert_eq!(chain.get_stage(), Stage::MODIFY);
|
||||
|
||||
let chain2 = chain
|
||||
.next_stage()
|
||||
.expect("There should have been the next stage");
|
||||
assert_eq!(chain2.get_stage(), Stage::MODIFY);
|
||||
|
||||
let chain3 = chain2
|
||||
.next_stage()
|
||||
.expect("There should have been the next stage");
|
||||
assert_eq!(chain3.get_stage(), Stage::EXECUTE);
|
||||
assert!(chain3.next_stage().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_command() {
|
||||
let mut dispatcher = CommandDispatcher::new();
|
||||
dispatcher.register(CommandArgumentBuilder::new("foo", "A test command"));
|
||||
|
||||
let source = DummySource::dummy();
|
||||
let result = dispatcher.parse_input("foo", &source);
|
||||
let top_context = result.context.build("foo");
|
||||
|
||||
assert!(ContextChain::try_flatten(&top_context).is_none());
|
||||
}
|
||||
|
||||
struct CustomExecutor;
|
||||
impl CommandExecutor for CustomExecutor {
|
||||
fn execute(&self, context: &CommandContext) -> CommandExecutorResult {
|
||||
let source = &context.source;
|
||||
assert_eq!(source.position, Vector3::new(0f64, 10f64, 0f64));
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_stage_modifier_execution() {
|
||||
let mut dispatcher = CommandDispatcher::new();
|
||||
dispatcher.register(
|
||||
CommandArgumentBuilder::new("foo", "A test command").executes(CustomExecutor),
|
||||
);
|
||||
dispatcher.register(
|
||||
CommandArgumentBuilder::new("bar", "Another test command").redirect_with_modifier(
|
||||
Redirection::Root,
|
||||
RedirectModifier::Custom(Arc::new(|context: &CommandContext<DummySource>| {
|
||||
let mut new_source = context.source.as_ref().clone();
|
||||
new_source.position = Vector3::new(0f64, 10f64, 0f64);
|
||||
Ok(vec![Arc::new(new_source)])
|
||||
})),
|
||||
),
|
||||
);
|
||||
let source = Arc::new(DummySource::dummy());
|
||||
let result = dispatcher.parse_input("bar foo", source.as_ref());
|
||||
let top_context = result.context.build("bar foo");
|
||||
let chain = ContextChain::try_flatten(&top_context)
|
||||
.expect("The context should have properly flattened, as it has a command to execute");
|
||||
assert_eq!(chain.get_top_context().source.position, Vector3::default());
|
||||
let chain2 = chain
|
||||
.next_stage()
|
||||
.expect("There should have been the next stage");
|
||||
assert!(chain2.next_stage().is_none());
|
||||
let res = chain.execute_all(&source, dispatcher.consumer.as_ref());
|
||||
assert!(res.is_ok_and(|val| val == 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod command_context;
|
||||
pub mod string_range;
|
||||
|
||||
pub use command_context::*;
|
||||
pub use string_range::*;
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use crate::string_reader::StringReader;
|
||||
|
||||
/// Indicates a range that is effectively
|
||||
/// a substring of a string from its `start`
|
||||
/// and `end` byte-indices.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct StringRange {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl StringRange {
|
||||
/// Constructs a new substring range, with indices
|
||||
/// inclusive to `start`, but exclusive to `end`.
|
||||
#[must_use]
|
||||
pub const fn between(start: usize, end: usize) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
/// Constructs an empty range on the left side of
|
||||
/// one character with index `pos`.
|
||||
#[must_use]
|
||||
pub const fn at(pos: usize) -> Self {
|
||||
Self::between(pos, pos)
|
||||
}
|
||||
|
||||
/// Constructs a new substring range encompassing two
|
||||
/// [`StringRange`]s, returning a new one that covers
|
||||
/// both the required ranges.
|
||||
#[must_use]
|
||||
pub fn encompass(a: Self, b: Self) -> Self {
|
||||
Self::between(a.start.min(b.start), a.end.max(b.end))
|
||||
}
|
||||
|
||||
/// Gets a [`str`] substring slice bound
|
||||
/// to a [`StringReader`] from this range.
|
||||
#[must_use]
|
||||
pub fn slice_from_reader<'a>(&self, reader: &'a StringReader) -> &'a str {
|
||||
&reader.string()[self.start..self.end]
|
||||
}
|
||||
|
||||
/// Gets a [`str`] substring slice bound
|
||||
/// to a [`String`] from this range.
|
||||
#[must_use]
|
||||
pub fn substring_slice<'a>(&self, string: &'a str) -> &'a str {
|
||||
&string[self.start..self.end]
|
||||
}
|
||||
|
||||
/// Returns if the length of this range is zero.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.start == self.end
|
||||
}
|
||||
|
||||
/// Returns the length of this range.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn len(&self) -> usize {
|
||||
self.end - self.start
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Range<usize>> for StringRange {
|
||||
fn from(value: Range<usize>) -> Self {
|
||||
Self::between(value.start, value.end)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StringRange> for Range<usize> {
|
||||
fn from(value: StringRange) -> Self {
|
||||
value.start..value.end
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub use crate::node::dispatcher::*;
|
||||
@@ -0,0 +1,80 @@
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
use crate::errors::error_types::AnyCommandErrorType;
|
||||
|
||||
/// A struct detailing the context of a syntax error, including where it happened.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CommandSyntaxErrorContext {
|
||||
pub input: String,
|
||||
pub cursor: usize,
|
||||
}
|
||||
|
||||
/// Indicates an object that can provide context of a command syntax error from itself.
|
||||
pub trait ContextProvider {
|
||||
fn context(&self) -> CommandSyntaxErrorContext;
|
||||
}
|
||||
|
||||
impl ContextProvider for CommandSyntaxErrorContext {
|
||||
fn context(&self) -> CommandSyntaxErrorContext {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A struct detailing a syntax error.
|
||||
///
|
||||
/// Despite its name, this error can
|
||||
/// also be caused during command execution.
|
||||
///
|
||||
/// However, most `CommandSyntaxError`s are thrown during
|
||||
/// parsing, which carry an additional detail about where
|
||||
/// they occurred (in the command) compared to the
|
||||
/// `CommandSyntaxError`s thrown during command execution.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CommandSyntaxError {
|
||||
pub error_type: &'static dyn AnyCommandErrorType,
|
||||
pub message: TextComponent,
|
||||
pub context: Option<CommandSyntaxErrorContext>,
|
||||
}
|
||||
|
||||
impl CommandSyntaxError {
|
||||
/// Constructs a new [`CommandSyntaxError`] without any context of the error,
|
||||
/// and only the error message itself.
|
||||
///
|
||||
/// This means this error will not print a context to the client, which
|
||||
/// includes the string and the location the error was caused.
|
||||
#[must_use]
|
||||
pub const fn create_without_context(
|
||||
error_type: &'static dyn AnyCommandErrorType,
|
||||
message: TextComponent,
|
||||
) -> Self {
|
||||
Self {
|
||||
error_type,
|
||||
message,
|
||||
context: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new [`CommandSyntaxError`] with a given context of the error,
|
||||
/// which includes the string and the location the error was caused,
|
||||
/// along with the error message itself.
|
||||
#[must_use]
|
||||
pub fn create<C>(
|
||||
error_type: &'static dyn AnyCommandErrorType,
|
||||
message: TextComponent,
|
||||
context_provider: &C,
|
||||
) -> Self
|
||||
where
|
||||
C: ContextProvider,
|
||||
{
|
||||
Self {
|
||||
error_type,
|
||||
message,
|
||||
context: Some(context_provider.context()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether this error's type is similar to the provided type.
|
||||
pub fn is(&self, error_type: &'static dyn AnyCommandErrorType) -> bool {
|
||||
self.error_type == error_type
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
use pumpkin_data::translation;
|
||||
|
||||
// These are akin to the translatable built-in exceptions in Minecraft.
|
||||
pub const READER_EXPECTED_START_QUOTE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_QUOTE_EXPECTED_START,
|
||||
translation::java::PARSING_QUOTE_EXPECTED_START,
|
||||
);
|
||||
pub const READER_EXPECTED_END_QUOTE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_QUOTE_EXPECTED_END,
|
||||
translation::java::PARSING_QUOTE_EXPECTED_END,
|
||||
);
|
||||
pub const READER_INVALID_ESCAPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_QUOTE_ESCAPE,
|
||||
translation::java::PARSING_QUOTE_ESCAPE,
|
||||
);
|
||||
pub const READER_INVALID_BOOL: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_BOOL_INVALID,
|
||||
translation::java::PARSING_BOOL_INVALID,
|
||||
);
|
||||
pub const READER_EXPECTED_BOOL: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_BOOL_EXPECTED,
|
||||
translation::java::PARSING_BOOL_EXPECTED,
|
||||
);
|
||||
pub const READER_INVALID_INT: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
translation::java::PARSING_INT_INVALID,
|
||||
);
|
||||
pub const READER_EXPECTED_INT: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_INT_EXPECTED,
|
||||
translation::java::PARSING_INT_EXPECTED,
|
||||
);
|
||||
pub const READER_INVALID_LONG: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_LONG_INVALID,
|
||||
translation::java::PARSING_LONG_INVALID,
|
||||
);
|
||||
pub const READER_EXPECTED_LONG: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_LONG_EXPECTED,
|
||||
translation::java::PARSING_LONG_EXPECTED,
|
||||
);
|
||||
pub const READER_INVALID_DOUBLE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_DOUBLE_INVALID,
|
||||
translation::java::PARSING_DOUBLE_INVALID,
|
||||
);
|
||||
pub const READER_EXPECTED_DOUBLE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_DOUBLE_EXPECTED,
|
||||
translation::java::PARSING_DOUBLE_EXPECTED,
|
||||
);
|
||||
pub const READER_INVALID_FLOAT: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_FLOAT_INVALID,
|
||||
translation::java::PARSING_FLOAT_INVALID,
|
||||
);
|
||||
pub const READER_EXPECTED_FLOAT: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::PARSING_FLOAT_EXPECTED,
|
||||
translation::java::PARSING_FLOAT_EXPECTED,
|
||||
);
|
||||
pub const READER_EXPECTED_SYMBOL: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::PARSING_EXPECTED,
|
||||
translation::java::PARSING_EXPECTED,
|
||||
);
|
||||
|
||||
pub const LITERAL_INCORRECT: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_LITERAL_INCORRECT,
|
||||
translation::java::ARGUMENT_LITERAL_INCORRECT,
|
||||
);
|
||||
|
||||
pub const DOUBLE_TOO_LOW: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_DOUBLE_LOW,
|
||||
translation::java::ARGUMENT_DOUBLE_LOW,
|
||||
);
|
||||
pub const DOUBLE_TOO_HIGH: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_DOUBLE_BIG,
|
||||
translation::java::ARGUMENT_DOUBLE_BIG,
|
||||
);
|
||||
pub const FLOAT_TOO_LOW: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_FLOAT_LOW,
|
||||
translation::java::ARGUMENT_FLOAT_LOW,
|
||||
);
|
||||
pub const FLOAT_TOO_HIGH: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_FLOAT_BIG,
|
||||
translation::java::ARGUMENT_FLOAT_BIG,
|
||||
);
|
||||
pub const INTEGER_TOO_LOW: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_INTEGER_LOW,
|
||||
translation::java::ARGUMENT_INTEGER_LOW,
|
||||
);
|
||||
pub const INTEGER_TOO_HIGH: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_INTEGER_BIG,
|
||||
translation::java::ARGUMENT_INTEGER_BIG,
|
||||
);
|
||||
pub const LONG_TOO_LOW: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_LONG_LOW,
|
||||
translation::java::ARGUMENT_LONG_LOW,
|
||||
);
|
||||
pub const LONG_TOO_HIGH: CommandErrorType<2> = CommandErrorType::new(
|
||||
translation::java::ARGUMENT_LONG_BIG,
|
||||
translation::java::ARGUMENT_LONG_BIG,
|
||||
);
|
||||
|
||||
pub const DISPATCHER_UNKNOWN_COMMAND: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMAND_UNKNOWN_COMMAND,
|
||||
translation::bedrock::COMMANDS_GENERIC_UNKNOWN,
|
||||
);
|
||||
pub const DISPATCHER_UNKNOWN_ARGUMENT: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMAND_UNKNOWN_ARGUMENT,
|
||||
translation::java::COMMAND_UNKNOWN_ARGUMENT,
|
||||
);
|
||||
pub const DISPATCHER_EXPECTED_ARGUMENT_SEPARATOR: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMAND_EXPECTED_SEPARATOR,
|
||||
translation::java::COMMAND_EXPECTED_SEPARATOR,
|
||||
);
|
||||
pub const DISPATCHER_PARSE_EXCEPTION: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::COMMAND_EXCEPTION,
|
||||
translation::bedrock::COMMANDS_GENERIC_SYNTAX,
|
||||
);
|
||||
|
||||
use crate::errors::{
|
||||
command_syntax_error::{CommandSyntaxError, ContextProvider},
|
||||
error_types::sealed::Sealed,
|
||||
};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
/// Represents text which can be used as a template that is generated at
|
||||
/// compile time and cannot change at runtime.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum TemplateText {
|
||||
/// This is first translated, then arguments are substituted (which are not constant)
|
||||
/// when it needs to be displayed.
|
||||
TranslationKey(&'static str, &'static str),
|
||||
|
||||
/// Directly shows up to the user without any translation done.
|
||||
Literal(&'static str),
|
||||
}
|
||||
|
||||
/// A command error that requires **exactly** `N` translation arguments.
|
||||
/// This takes a translation key. If you want the non-translatable version,
|
||||
/// use [`LiteralCommandErrorType`].
|
||||
///
|
||||
/// **Comparison with Brigadier**:
|
||||
/// - [`CommandErrorType<0>`] = `SimpleCommandExceptionType`
|
||||
/// - [`CommandErrorType<1>`] = `DynamicCommandExceptionType`
|
||||
/// - [`CommandErrorType<2>`] = `Dynamic2CommandExceptionType`
|
||||
/// - [`CommandErrorType<3>`] = `Dynamic3CommandExceptionType`
|
||||
/// - [`CommandErrorType<4>`] = `Dynamic4CommandExceptionType`
|
||||
/// - `CommandErrorType<N>` = `DynamicNCommandExceptionType`
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct CommandErrorType<const N: usize> {
|
||||
pub java_translation_key: &'static str,
|
||||
pub bedrock_translation_key: &'static str,
|
||||
}
|
||||
|
||||
impl<const N: usize> CommandErrorType<N> {
|
||||
/// Creates an error type from a given translation string.
|
||||
#[must_use]
|
||||
pub const fn new(
|
||||
java_translation_key: &'static str,
|
||||
bedrock_translation_key: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
java_translation_key,
|
||||
bedrock_translation_key,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an error without context from itself and from a slice of `N` arguments.
|
||||
#[must_use]
|
||||
#[expect(deprecated)]
|
||||
pub fn create_without_context_args_slice(
|
||||
&'static self,
|
||||
args: &[TextComponent; N],
|
||||
) -> CommandSyntaxError {
|
||||
CommandSyntaxError::create_without_context(
|
||||
self,
|
||||
TextComponent::translate_cross(
|
||||
self.java_translation_key,
|
||||
self.bedrock_translation_key,
|
||||
args.to_vec(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates an error with context from itself and from a slice of `N` arguments.
|
||||
#[expect(deprecated)]
|
||||
pub fn create_args_slice<C>(
|
||||
&'static self,
|
||||
context_provider: &C,
|
||||
args: &[TextComponent; N],
|
||||
) -> CommandSyntaxError
|
||||
where
|
||||
C: ContextProvider,
|
||||
{
|
||||
CommandSyntaxError::create(
|
||||
self,
|
||||
TextComponent::translate_cross(
|
||||
self.java_translation_key,
|
||||
self.bedrock_translation_key,
|
||||
args.to_vec(),
|
||||
),
|
||||
context_provider,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A command error that is not translated, and cannot take any arguments.
|
||||
/// This takes a constant string literal. If you want the translatable version,
|
||||
/// use [`CommandErrorType`].
|
||||
///
|
||||
/// [`CommandErrorType`] should be preferred to this whenever possible.
|
||||
///
|
||||
/// Use this for custom error messages, which don't have any
|
||||
/// translation in vanilla.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct LiteralCommandErrorType {
|
||||
pub literal: &'static str,
|
||||
}
|
||||
|
||||
impl LiteralCommandErrorType {
|
||||
/// Creates an error type from a given literal string.
|
||||
///
|
||||
/// Used during command parsing. (i.e. in `ArgumentType`s)
|
||||
#[must_use]
|
||||
pub const fn new(literal: &'static str) -> Self {
|
||||
Self { literal }
|
||||
}
|
||||
|
||||
/// Creates an error without context from itself.
|
||||
///
|
||||
/// Used during command execution.
|
||||
#[must_use]
|
||||
pub fn create_without_context(&'static self) -> CommandSyntaxError {
|
||||
CommandSyntaxError::create_without_context(self, TextComponent::text(self.literal))
|
||||
}
|
||||
|
||||
/// Creates an error with context from itself.
|
||||
pub fn create<C>(&'static self, context_provider: &C) -> CommandSyntaxError
|
||||
where
|
||||
C: ContextProvider,
|
||||
{
|
||||
CommandSyntaxError::create(self, TextComponent::text(self.literal), context_provider)
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent other crates from using this trait
|
||||
// Thus, we can effectively 'seal' our trait meant
|
||||
// only for `CommandErrorType<N>`.
|
||||
mod sealed {
|
||||
/// Private trait to ensure only `CommandErrorType<N>` can implement `AnyCommandErrorType`.
|
||||
pub trait Sealed {}
|
||||
}
|
||||
|
||||
/// A trait which is only implemented by [`CommandErrorType<N>`] types.
|
||||
///
|
||||
/// It exposes the common properties of such types, while making
|
||||
/// it more dynamic to access its properties, like the translation
|
||||
/// key and the number of arguments (at runtime).
|
||||
pub trait AnyCommandErrorType: Sealed + std::fmt::Debug + Send + Sync {
|
||||
/// Returns the underlying translation key of this specific error type.
|
||||
fn text(&self) -> TemplateText;
|
||||
|
||||
/// Returns the number of arguments supported by this error type.
|
||||
fn argument_count(&self) -> usize;
|
||||
}
|
||||
|
||||
impl Eq for dyn AnyCommandErrorType {}
|
||||
|
||||
impl PartialEq for dyn AnyCommandErrorType {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.text() == other.text() && self.argument_count() == other.argument_count()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AnyCommandErrorType> PartialEq<T> for dyn AnyCommandErrorType {
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
self.text() == other.text() && self.argument_count() == other.argument_count()
|
||||
}
|
||||
}
|
||||
|
||||
// Implement the private trait for our types.
|
||||
impl<const N: usize> Sealed for CommandErrorType<N> {}
|
||||
impl<const N: usize> AnyCommandErrorType for CommandErrorType<N> {
|
||||
fn text(&self) -> TemplateText {
|
||||
TemplateText::TranslationKey(self.java_translation_key, self.bedrock_translation_key)
|
||||
}
|
||||
|
||||
fn argument_count(&self) -> usize {
|
||||
N
|
||||
}
|
||||
}
|
||||
|
||||
impl Sealed for LiteralCommandErrorType {}
|
||||
impl AnyCommandErrorType for LiteralCommandErrorType {
|
||||
fn text(&self) -> TemplateText {
|
||||
TemplateText::Literal(self.literal)
|
||||
}
|
||||
|
||||
fn argument_count(&self) -> usize {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
// Ease-of-use Implementations:
|
||||
|
||||
/// Generates a specific implementation for `CommandErrorType<N>` with two methods to create
|
||||
/// an error without using a slice. Instead, they take a specific number of
|
||||
/// arguments. Each `impl` is given a specific value of `N` and some argument names.
|
||||
macro_rules! error_type_no_arg_slice_impl {
|
||||
(N = $N: literal => $($arg:ident),* | $doc: expr) => {
|
||||
impl CommandErrorType<$N> {
|
||||
/// Creates an error without context from this error type
|
||||
#[doc = $doc]
|
||||
#[must_use]
|
||||
pub fn create_without_context(
|
||||
&'static self,
|
||||
$($arg: TextComponent),*
|
||||
) -> CommandSyntaxError {
|
||||
self.create_without_context_args_slice(&[
|
||||
$($arg),*
|
||||
])
|
||||
}
|
||||
|
||||
/// Creates an error with context from this error type
|
||||
#[doc = $doc]
|
||||
#[must_use]
|
||||
pub fn create<C>(
|
||||
&'static self,
|
||||
context_provider: &C,
|
||||
$($arg: TextComponent),*
|
||||
) -> CommandSyntaxError
|
||||
where
|
||||
C: ContextProvider,
|
||||
{
|
||||
self.create_args_slice(context_provider, &[
|
||||
$($arg),*
|
||||
])
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Implementations are defined below:
|
||||
|
||||
error_type_no_arg_slice_impl!(N = 0 => | "without taking any translation arguments.");
|
||||
error_type_no_arg_slice_impl!(N = 1 => arg1 | "by taking 1 translation argument.");
|
||||
error_type_no_arg_slice_impl!(N = 2 => arg1, arg2 | "by taking 2 translation arguments.");
|
||||
error_type_no_arg_slice_impl!(N = 3 => arg1, arg2, arg3 | "by taking 3 translation arguments.");
|
||||
error_type_no_arg_slice_impl!(N = 4 => arg1, arg2, arg3, arg4 | "by taking 4 translation arguments.");
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::errors::error_types::{CommandErrorType, LiteralCommandErrorType};
|
||||
use crate::string_reader::StringReader;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
const TEST_LITERAL_ERROR_TYPE: LiteralCommandErrorType =
|
||||
LiteralCommandErrorType::new("Test error");
|
||||
const TEST_TRANSLATABLE_ERROR_TYPE: CommandErrorType<1> =
|
||||
CommandErrorType::new("this.key.is.arbitrary", "this.key.is.arbitrary");
|
||||
|
||||
#[test]
|
||||
fn create_literal_error() {
|
||||
let mut reader = StringReader::new("foo bar");
|
||||
reader.set_cursor(4);
|
||||
|
||||
let error = TEST_LITERAL_ERROR_TYPE.create(&reader);
|
||||
|
||||
assert_eq!(error.error_type, &TEST_LITERAL_ERROR_TYPE);
|
||||
assert_eq!(error.message, TextComponent::text("Test error"));
|
||||
|
||||
match &error.context {
|
||||
Some(context) => {
|
||||
assert_eq!(context.cursor, 4);
|
||||
assert_eq!(context.input, "foo bar");
|
||||
}
|
||||
None => panic!("There should have been a context for the error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_literal_error_without_context() {
|
||||
let error = TEST_LITERAL_ERROR_TYPE.create_without_context();
|
||||
|
||||
assert_eq!(error.error_type, &TEST_LITERAL_ERROR_TYPE);
|
||||
assert_eq!(error.message, TextComponent::text("Test error"));
|
||||
assert_eq!(error.context, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(deprecated)]
|
||||
fn create_translatable_error() {
|
||||
let mut reader = StringReader::new("foo bar");
|
||||
reader.set_cursor(4);
|
||||
|
||||
let error =
|
||||
TEST_TRANSLATABLE_ERROR_TYPE.create(&reader, TextComponent::text("some argument"));
|
||||
|
||||
assert_eq!(error.error_type, &TEST_TRANSLATABLE_ERROR_TYPE);
|
||||
assert_eq!(
|
||||
error.message,
|
||||
TextComponent::translate_cross(
|
||||
"this.key.is.arbitrary",
|
||||
"this.key.is.arbitrary",
|
||||
[TextComponent::text("some argument")]
|
||||
)
|
||||
);
|
||||
|
||||
match &error.context {
|
||||
Some(context) => {
|
||||
assert_eq!(context.cursor, 4);
|
||||
assert_eq!(context.input, "foo bar");
|
||||
}
|
||||
None => panic!("There should have been a context for the error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod command_syntax_error;
|
||||
pub mod error_types;
|
||||
@@ -0,0 +1,20 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
pub mod argument_builder;
|
||||
pub mod argument_types;
|
||||
pub mod context;
|
||||
pub mod dispatcher;
|
||||
pub mod errors;
|
||||
pub mod node;
|
||||
pub mod parser;
|
||||
pub mod snbt;
|
||||
pub mod source;
|
||||
pub mod string_reader;
|
||||
pub mod suggestion;
|
||||
|
||||
pub use argument_builder::{ArgumentBuilder, CommandArgumentBuilder, LiteralArgumentBuilder};
|
||||
pub use argument_types::argument_type::{AnyArgumentType, ArgumentType};
|
||||
pub use context::command_context::CommandContext;
|
||||
pub use node::dispatcher::CommandDispatcher;
|
||||
pub use node::{Command, CommandExecutor, CommandExecutorResult, Requirement};
|
||||
pub use source::CommandSource;
|
||||
@@ -0,0 +1,411 @@
|
||||
use crate::context::string_range::StringRange;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::LITERAL_INCORRECT;
|
||||
use crate::node::detached::GlobalNodeId;
|
||||
use crate::node::tree::ROOT_NODE_ID;
|
||||
use crate::node::{
|
||||
ArgumentNodeMetadata, Command, CommandNodeMetadata, LiteralNodeMetadata, NodeMetadata,
|
||||
OwnedNodeData, RedirectModifier, Redirection, Requirements,
|
||||
};
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::string_reader::StringReader;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::num::NonZero;
|
||||
|
||||
/// Represents the unique integral number
|
||||
/// of any node, with respect to a tree.
|
||||
///
|
||||
/// A [`NonZero<usize>`] is used internally in this
|
||||
/// struct. This means [`Option<NodeId>`] carries the
|
||||
/// same size as of [`NodeId`], but comes at the cost of
|
||||
/// ID `0` being unassignable.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
|
||||
pub struct NodeId(pub NonZero<usize>);
|
||||
|
||||
/// Represents the unique integral number
|
||||
/// of the root node, with respect to a tree.
|
||||
///
|
||||
/// This is unit-sized as it is constant.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
|
||||
pub struct RootNodeId;
|
||||
|
||||
/// Represents the unique integral number
|
||||
/// of a specific literal node, with respect to a tree.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
|
||||
pub struct LiteralNodeId(pub NonZero<usize>);
|
||||
|
||||
/// Represents the unique integral number
|
||||
/// of a specific command node, with respect to a tree.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
|
||||
pub struct CommandNodeId(pub NonZero<usize>);
|
||||
|
||||
/// Represents the unique integral number
|
||||
/// of a specific argument node, with respect to a tree.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
|
||||
pub struct ArgumentNodeId(pub NonZero<usize>);
|
||||
|
||||
impl From<RootNodeId> for NodeId {
|
||||
fn from(_id: RootNodeId) -> Self {
|
||||
ROOT_NODE_ID
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LiteralNodeId> for NodeId {
|
||||
fn from(id: LiteralNodeId) -> Self {
|
||||
Self(id.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CommandNodeId> for NodeId {
|
||||
fn from(id: CommandNodeId) -> Self {
|
||||
Self(id.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ArgumentNodeId> for NodeId {
|
||||
fn from(id: ArgumentNodeId) -> Self {
|
||||
Self(id.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a node which has been attached as the root of a `Tree`.
|
||||
#[derive(Clone)]
|
||||
pub struct RootAttachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, NodeId>,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> Default for RootAttachedNode<S> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> RootAttachedNode<S> {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
owned: OwnedNodeData {
|
||||
global_id: GlobalNodeId::new(),
|
||||
requirements: Requirements::new(),
|
||||
modifier: RedirectModifier::KeepSource,
|
||||
forks: false,
|
||||
command: None,
|
||||
},
|
||||
children: FxHashMap::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a literal, non-command node that has already been attached
|
||||
/// to a `Tree`.
|
||||
#[derive(Clone)]
|
||||
pub struct LiteralAttachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, NodeId>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: LiteralNodeMetadata,
|
||||
}
|
||||
|
||||
/// Represents a literal, command node that has already been attached
|
||||
/// to a `Tree`.
|
||||
#[derive(Clone)]
|
||||
pub struct CommandAttachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, NodeId>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: CommandNodeMetadata,
|
||||
}
|
||||
|
||||
/// Represents a node that accepts a specific type of argument that has already been attached
|
||||
/// to a `Tree`.
|
||||
#[derive(Clone)]
|
||||
pub struct ArgumentAttachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, NodeId>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: ArgumentNodeMetadata<S>,
|
||||
}
|
||||
|
||||
/// Allows a way to store the kind of node
|
||||
/// without any actual cloning of [`NodeMetadata`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum NodeClassification {
|
||||
Root,
|
||||
Literal,
|
||||
Command,
|
||||
Argument,
|
||||
}
|
||||
|
||||
/// Represents a node not attached to a `Tree` yet.
|
||||
#[derive(Clone)]
|
||||
pub enum AttachedNode<S: CommandSource = DummySource> {
|
||||
Root(RootAttachedNode<S>),
|
||||
Literal(LiteralAttachedNode<S>),
|
||||
Command(CommandAttachedNode<S>),
|
||||
Argument(ArgumentAttachedNode<S>),
|
||||
}
|
||||
|
||||
/// Returned when a literal could not be parsed.
|
||||
pub struct CouldNotParseLiteral;
|
||||
|
||||
impl<S: CommandSource> AttachedNode<S> {
|
||||
/// Creates an [`AttachedNode`] from its properties allowing any [`NodeMetadata`].
|
||||
#[must_use]
|
||||
pub fn from_parts(
|
||||
owned: OwnedNodeData<S>,
|
||||
children: FxHashMap<String, NodeId>,
|
||||
redirect: Option<Redirection>,
|
||||
meta: NodeMetadata<S>,
|
||||
) -> Self {
|
||||
match meta {
|
||||
NodeMetadata::Root => Self::Root(RootAttachedNode { owned, children }),
|
||||
NodeMetadata::Literal(meta) => Self::Literal(LiteralAttachedNode {
|
||||
owned,
|
||||
children,
|
||||
redirect,
|
||||
meta,
|
||||
}),
|
||||
NodeMetadata::Command(meta) => Self::Command(CommandAttachedNode {
|
||||
owned,
|
||||
children,
|
||||
redirect,
|
||||
meta,
|
||||
}),
|
||||
NodeMetadata::Argument(meta) => Self::Argument(ArgumentAttachedNode {
|
||||
owned,
|
||||
children,
|
||||
redirect,
|
||||
meta,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the classification of this node.
|
||||
/// This is a relatively cheap operation.
|
||||
#[must_use]
|
||||
pub const fn classification(&self) -> NodeClassification {
|
||||
match self {
|
||||
Self::Root(_) => NodeClassification::Root,
|
||||
Self::Literal(_) => NodeClassification::Literal,
|
||||
Self::Command(_) => NodeClassification::Command,
|
||||
Self::Argument(_) => NodeClassification::Argument,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the global ID from this node.
|
||||
#[must_use]
|
||||
pub const fn global_id(&self) -> GlobalNodeId {
|
||||
self.owned_node_data_ref().global_id
|
||||
}
|
||||
|
||||
/// Gets a reference to the owned data of this node.
|
||||
#[must_use]
|
||||
pub const fn owned_node_data_ref(&self) -> &OwnedNodeData<S> {
|
||||
match self {
|
||||
Self::Root(node) => &node.owned,
|
||||
Self::Literal(node) => &node.owned,
|
||||
Self::Command(node) => &node.owned,
|
||||
Self::Argument(node) => &node.owned,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the owned data of this node.
|
||||
pub const fn owned_node_data_mut_ref(&mut self) -> &mut OwnedNodeData<S> {
|
||||
match self {
|
||||
Self::Root(node) => &mut node.owned,
|
||||
Self::Literal(node) => &mut node.owned,
|
||||
Self::Command(node) => &mut node.owned,
|
||||
Self::Argument(node) => &mut node.owned,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a reference to the children IDs of this node.
|
||||
#[must_use]
|
||||
pub const fn children_ref(&self) -> &FxHashMap<String, NodeId> {
|
||||
match self {
|
||||
Self::Root(node) => &node.children,
|
||||
Self::Literal(node) => &node.children,
|
||||
Self::Command(node) => &node.children,
|
||||
Self::Argument(node) => &node.children,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the children IDs of this node.
|
||||
pub const fn children_mut_ref(&mut self) -> &mut FxHashMap<String, NodeId> {
|
||||
match self {
|
||||
Self::Root(node) => &mut node.children,
|
||||
Self::Literal(node) => &mut node.children,
|
||||
Self::Command(node) => &mut node.children,
|
||||
Self::Argument(node) => &mut node.children,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the name of this node.
|
||||
#[must_use]
|
||||
pub fn name(&self) -> String {
|
||||
match self {
|
||||
Self::Root(_) => String::new(),
|
||||
Self::Literal(node) => node.meta.literal.to_string(),
|
||||
Self::Command(node) => node.meta.literal.to_string(),
|
||||
Self::Argument(node) => node.meta.name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the redirection of this node.
|
||||
#[must_use]
|
||||
pub const fn redirect(&self) -> Option<Redirection> {
|
||||
match self {
|
||||
Self::Root(_) => None,
|
||||
Self::Literal(node) => node.redirect,
|
||||
Self::Command(node) => node.redirect,
|
||||
Self::Argument(node) => node.redirect,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets an [`Option`] of a mutable reference to the redirection of this node.
|
||||
pub const fn redirect_mut_ref(&mut self) -> Option<&mut Redirection> {
|
||||
match self {
|
||||
Self::Root(_) => None,
|
||||
Self::Literal(node) => node.redirect.as_mut(),
|
||||
Self::Command(node) => node.redirect.as_mut(),
|
||||
Self::Argument(node) => node.redirect.as_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the redirection of this node.
|
||||
pub const fn set_redirect(&mut self, redirect: Option<Redirection>) {
|
||||
match self {
|
||||
Self::Root(_) => {}
|
||||
Self::Literal(node) => node.redirect = redirect,
|
||||
Self::Command(node) => node.redirect = redirect,
|
||||
Self::Argument(node) => node.redirect = redirect,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets all the requirements required for this node to be run.
|
||||
#[must_use]
|
||||
pub const fn requirements(&self) -> &Requirements<S> {
|
||||
&self.owned_node_data_ref().requirements
|
||||
}
|
||||
|
||||
/// Overrides all the requirements for this node to be run to a value.
|
||||
pub fn set_requirement(&mut self, requirements: Requirements<S>) {
|
||||
self.owned_node_data_mut_ref().requirements = requirements;
|
||||
}
|
||||
|
||||
/// Gets the modifier for this node to be run.
|
||||
#[must_use]
|
||||
pub const fn modifier(&self) -> &RedirectModifier<S> {
|
||||
&self.owned_node_data_ref().modifier
|
||||
}
|
||||
|
||||
/// Sets the modifier for this node to a value.
|
||||
pub fn set_modifier(&mut self, modifier: RedirectModifier<S>) {
|
||||
self.owned_node_data_mut_ref().modifier = modifier;
|
||||
}
|
||||
|
||||
/// Whether this node forks `CommandSources` or not.
|
||||
#[must_use]
|
||||
pub const fn forks(&self) -> bool {
|
||||
self.owned_node_data_ref().forks
|
||||
}
|
||||
|
||||
/// Sets whether this node forks `CommandSources` or not.
|
||||
pub const fn set_forks(&mut self, forks: bool) {
|
||||
self.owned_node_data_mut_ref().forks = forks;
|
||||
}
|
||||
|
||||
/// Gets the executable command for this node.
|
||||
#[must_use]
|
||||
pub fn command(&self) -> &Option<Command<S>> {
|
||||
&self.owned_node_data_ref().command
|
||||
}
|
||||
|
||||
/// Sets the executable command for this node.
|
||||
pub fn set_command(&mut self, command: Option<Command<S>>) {
|
||||
self.owned_node_data_mut_ref().command = command;
|
||||
}
|
||||
|
||||
/// Get the usage text of this node.
|
||||
#[must_use]
|
||||
pub fn usage_text(&self) -> String {
|
||||
match self {
|
||||
Self::Root(_) => String::new(),
|
||||
Self::Literal(node) => node.meta.literal.to_string(),
|
||||
Self::Command(node) => node.meta.literal.to_string(),
|
||||
Self::Argument(node) => format!("<{}>", node.meta.name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if the given input is valid for this node.
|
||||
#[must_use]
|
||||
pub fn is_valid_input(&self, input: &str) -> bool {
|
||||
match self {
|
||||
Self::Root(_) => false,
|
||||
Self::Literal(node) => {
|
||||
let mut reader = StringReader::new(input);
|
||||
Self::parse_literal(&mut reader, &node.meta.literal).is_ok()
|
||||
}
|
||||
Self::Command(node) => {
|
||||
let mut reader = StringReader::new(input);
|
||||
Self::parse_literal(&mut reader, &node.meta.literal).is_ok()
|
||||
}
|
||||
Self::Argument(node) => {
|
||||
let mut reader = StringReader::new(input);
|
||||
let parsed = node.meta.argument_type.parse(&mut reader);
|
||||
if parsed.is_ok() {
|
||||
matches!(reader.peek(), Some(' ') | None)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the given input for this node.
|
||||
/// Prefer using a `CommandDispatcher` over this function directly.
|
||||
pub fn parse(
|
||||
&self,
|
||||
reader: &mut StringReader,
|
||||
literal: &str,
|
||||
) -> Result<StringRange, CommandSyntaxError> {
|
||||
let start = reader.cursor();
|
||||
Self::parse_literal(reader, literal).map_or_else(
|
||||
|_| Err(LITERAL_INCORRECT.create(reader, TextComponent::text(literal.to_string()))),
|
||||
|end| Ok(StringRange::between(start, end)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Internal function to parse a literal. Used by `Tree`.
|
||||
pub fn parse_literal(
|
||||
reader: &mut StringReader,
|
||||
literal: &str,
|
||||
) -> Result<usize, CouldNotParseLiteral> {
|
||||
let start = reader.cursor();
|
||||
let len = literal.len();
|
||||
if reader.can_read_bytes(len) {
|
||||
let end = start + len;
|
||||
if &reader.string()[start..end] == literal {
|
||||
reader.set_cursor(end);
|
||||
if matches!(reader.peek(), Some(' ') | None) {
|
||||
return Ok(end);
|
||||
}
|
||||
reader.set_cursor(start);
|
||||
}
|
||||
}
|
||||
Err(CouldNotParseLiteral)
|
||||
}
|
||||
|
||||
/// Gets examples accepted by this node.
|
||||
#[must_use]
|
||||
pub fn examples(&self) -> Vec<String> {
|
||||
match self {
|
||||
Self::Root(_) => Vec::new(),
|
||||
Self::Literal(node) => vec![node.meta.literal.to_string()],
|
||||
Self::Command(node) => vec![node.meta.literal.to_string()],
|
||||
Self::Argument(node) => node.meta.argument_type.examples(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
use crate::argument_types::argument_type::AnyArgumentType;
|
||||
use crate::node::{
|
||||
ArgumentNodeMetadata, Command, CommandNodeMetadata, LiteralNodeMetadata, NodeMetadata,
|
||||
OwnedNodeData, RedirectModifier, Redirection, Requirements,
|
||||
};
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::suggestion::provider::SuggestionProvider;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::borrow::Cow;
|
||||
use std::num::NonZero;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static NEXT_DETACHED_NODE_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Represents a **global** integral number of
|
||||
/// any type of node which is unique at runtime.
|
||||
///
|
||||
/// This is important for nodes not bound to a
|
||||
/// tree.
|
||||
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
|
||||
pub struct GlobalNodeId(pub NonZero<u64>);
|
||||
|
||||
impl GlobalNodeId {
|
||||
/// Generates an ID that is guaranteed
|
||||
/// to be unique at runtime, by using atomics.
|
||||
pub fn new() -> Self {
|
||||
Self(
|
||||
NonZero::new(NEXT_DETACHED_NODE_ID.fetch_add(1, Ordering::Relaxed))
|
||||
.expect("expected a non-zero id"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GlobalNodeId {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a literal, non-command node that has not been attached
|
||||
/// to a tree yet.
|
||||
///
|
||||
/// If you want to start a command with this node, use [`CommandDetachedNode`] instead.
|
||||
///
|
||||
/// To be of any utility, this must be attached to a tree later.
|
||||
#[derive(Clone)]
|
||||
pub struct LiteralDetachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, DetachedNode<S>>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: LiteralNodeMetadata,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> LiteralDetachedNode<S> {
|
||||
/// Creates a detached literal node from its properties,
|
||||
/// without any children.
|
||||
///
|
||||
/// # Note
|
||||
/// Prefer using the [`literal`](crate::argument_builder::literal) function over this one.
|
||||
pub fn new(
|
||||
global_id: GlobalNodeId,
|
||||
literal: impl Into<Cow<'static, str>>,
|
||||
command: Option<Command<S>>,
|
||||
requirements: Requirements<S>,
|
||||
redirect: Option<Redirection>,
|
||||
modifier: RedirectModifier<S>,
|
||||
forks: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
owned: OwnedNodeData {
|
||||
global_id,
|
||||
requirements,
|
||||
modifier,
|
||||
forks,
|
||||
command,
|
||||
},
|
||||
children: FxHashMap::default(),
|
||||
redirect,
|
||||
meta: LiteralNodeMetadata::new(literal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a literal, command node that has not been attached
|
||||
/// to a tree yet.
|
||||
///
|
||||
/// If you don't want to start a command with this node, use [`LiteralDetachedNode`] instead.
|
||||
///
|
||||
/// To be of any utility, this must be attached to a tree later.
|
||||
#[derive(Clone)]
|
||||
pub struct CommandDetachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, DetachedNode<S>>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: CommandNodeMetadata,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> CommandDetachedNode<S> {
|
||||
/// Creates a detached literal node from its properties,
|
||||
/// without any children.
|
||||
///
|
||||
/// # Note
|
||||
/// Prefer using the [`command`](crate::argument_builder::command) function over this one.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
global_id: GlobalNodeId,
|
||||
literal: impl Into<Cow<'static, str>>,
|
||||
description: impl Into<Cow<'static, str>>,
|
||||
command: Option<Command<S>>,
|
||||
requirements: Requirements<S>,
|
||||
redirect: Option<Redirection>,
|
||||
modifier: RedirectModifier<S>,
|
||||
forks: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
owned: OwnedNodeData {
|
||||
global_id,
|
||||
requirements,
|
||||
modifier,
|
||||
forks,
|
||||
command,
|
||||
},
|
||||
children: FxHashMap::default(),
|
||||
redirect,
|
||||
meta: CommandNodeMetadata::new(literal, description),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a node that accepts a specific type of argument.
|
||||
///
|
||||
/// To be of any utility, this must be attached to a tree later.
|
||||
#[derive(Clone)]
|
||||
pub struct ArgumentDetachedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, DetachedNode<S>>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: ArgumentNodeMetadata<S>,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> ArgumentDetachedNode<S> {
|
||||
/// Creates a detached argument node from its properties,
|
||||
/// without any children.
|
||||
///
|
||||
/// # Note
|
||||
/// Prefer using the [`argument`](crate::argument_builder::argument) function over this one.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
global_id: GlobalNodeId,
|
||||
name: impl Into<Cow<'static, str>>,
|
||||
argument_type: Arc<dyn AnyArgumentType<S>>,
|
||||
command: Option<Command<S>>,
|
||||
requirements: Requirements<S>,
|
||||
redirect: Option<Redirection>,
|
||||
modifier: RedirectModifier<S>,
|
||||
forks: bool,
|
||||
suggestion_provider: Option<Arc<dyn SuggestionProvider<S>>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
owned: OwnedNodeData {
|
||||
global_id,
|
||||
requirements,
|
||||
modifier,
|
||||
forks,
|
||||
command,
|
||||
},
|
||||
children: FxHashMap::default(),
|
||||
redirect,
|
||||
meta: ArgumentNodeMetadata::new(name, argument_type, suggestion_provider),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a node not attached to a `Tree` yet.
|
||||
#[derive(Clone)]
|
||||
pub enum DetachedNode<S: CommandSource = DummySource> {
|
||||
Literal(LiteralDetachedNode<S>),
|
||||
Command(CommandDetachedNode<S>),
|
||||
Argument(ArgumentDetachedNode<S>),
|
||||
}
|
||||
|
||||
/// Represents a [`DetachedNode`] that has been irreversibly
|
||||
/// decomposed into its elements so that it can be recast
|
||||
/// into a new `AttachedNode`.
|
||||
pub struct DecomposedNode<S: CommandSource = DummySource> {
|
||||
pub owned: OwnedNodeData<S>,
|
||||
pub children: FxHashMap<String, DetachedNode<S>>,
|
||||
pub redirect: Option<Redirection>,
|
||||
pub meta: NodeMetadata<S>,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> From<LiteralDetachedNode<S>> for DetachedNode<S> {
|
||||
fn from(node: LiteralDetachedNode<S>) -> Self {
|
||||
Self::Literal(node)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> From<CommandDetachedNode<S>> for DetachedNode<S> {
|
||||
fn from(node: CommandDetachedNode<S>) -> Self {
|
||||
Self::Command(node)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> From<ArgumentDetachedNode<S>> for DetachedNode<S> {
|
||||
fn from(node: ArgumentDetachedNode<S>) -> Self {
|
||||
Self::Argument(node)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> DetachedNode<S> {
|
||||
/// Irreversibly decomposes this [`DetachedNode`] into its constituent elements.
|
||||
/// This allows it to then be recast into a new `AttachedNode`.
|
||||
#[must_use]
|
||||
pub fn decompose(self) -> DecomposedNode<S> {
|
||||
match self {
|
||||
Self::Literal(node) => DecomposedNode {
|
||||
owned: node.owned,
|
||||
children: node.children,
|
||||
redirect: node.redirect,
|
||||
meta: NodeMetadata::Literal(node.meta),
|
||||
},
|
||||
Self::Command(node) => DecomposedNode {
|
||||
owned: node.owned,
|
||||
children: node.children,
|
||||
redirect: node.redirect,
|
||||
meta: NodeMetadata::Command(node.meta),
|
||||
},
|
||||
Self::Argument(node) => DecomposedNode {
|
||||
owned: node.owned,
|
||||
children: node.children,
|
||||
redirect: node.redirect,
|
||||
meta: NodeMetadata::Argument(node.meta),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn name(&self) -> String {
|
||||
match self {
|
||||
Self::Literal(node) => node.meta.literal.to_string(),
|
||||
Self::Command(node) => node.meta.literal.to_string(),
|
||||
Self::Argument(node) => node.meta.name.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,267 @@
|
||||
pub mod attached;
|
||||
pub mod detached;
|
||||
pub mod dispatcher;
|
||||
pub mod tree;
|
||||
|
||||
use crate::argument_types::argument_type::AnyArgumentType;
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::node::attached::NodeId;
|
||||
use crate::node::detached::GlobalNodeId;
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::suggestion::provider::SuggestionProvider;
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Represents a [`CommandExecutor`]'s result.
|
||||
///
|
||||
/// If the command **ran successfully**, an [`Ok`] is returned containing an [`i32`].
|
||||
/// This represents the 'output value' of the command, which is *homologous* to the
|
||||
/// `int` that command executors in vanilla return **upon success**.
|
||||
///
|
||||
/// **You should choose the successful result as `1` if**:
|
||||
/// - you don't know what value to use for a success for your
|
||||
/// own commands, or
|
||||
/// - you don't understand what this value means, or
|
||||
/// - you just simply don't care about this value at all
|
||||
///
|
||||
/// If the command **fails**, an [`Err`] is returned, containing the [`CommandSyntaxError`]
|
||||
/// that led to this result.
|
||||
pub type CommandExecutorResult = Result<i32, CommandSyntaxError>;
|
||||
|
||||
/// A struct implementing this trait is able to run with a given context.
|
||||
pub trait CommandExecutor<S: CommandSource = DummySource>: Sync + Send {
|
||||
/// Executes this executor for a command.
|
||||
fn execute(&self, context: &CommandContext<S>) -> CommandExecutorResult;
|
||||
}
|
||||
|
||||
impl<F, S: CommandSource> CommandExecutor<S> for F
|
||||
where
|
||||
F: Fn(&CommandContext<S>) -> CommandExecutorResult + Send + Sync,
|
||||
{
|
||||
fn execute(&self, context: &CommandContext<S>) -> CommandExecutorResult {
|
||||
self(context)
|
||||
}
|
||||
}
|
||||
|
||||
/// A function that takes a context and returns a command result.
|
||||
pub type Command<S = DummySource> = Arc<dyn CommandExecutor<S>>;
|
||||
|
||||
/// Represents the result of [`Arc<S>`]s from a [`CommandContext`].
|
||||
pub type RedirectModifierResult<S = DummySource> = Result<Vec<Arc<S>>, CommandSyntaxError>;
|
||||
|
||||
/// A function that performs the required modification.
|
||||
pub type RedirectModifierExecutor<S = DummySource> =
|
||||
dyn Fn(&CommandContext<S>) -> RedirectModifierResult<S> + Send + Sync;
|
||||
|
||||
/// A function that returns a new collection of sources from a given context.
|
||||
#[derive(Clone)]
|
||||
pub enum RedirectModifier<S: CommandSource = DummySource> {
|
||||
/// Always returns only the source from the given context.
|
||||
KeepSource,
|
||||
|
||||
/// Returns multiple [`CommandSource`]s from one context via
|
||||
/// custom behavior.
|
||||
Custom(Arc<RedirectModifierExecutor<S>>),
|
||||
}
|
||||
|
||||
impl<S: CommandSource> RedirectModifier<S> {
|
||||
/// Tries to provide a [`Vec`] of [`Arc<S>`] from a
|
||||
/// given [`CommandContext`].
|
||||
pub fn sources(&self, command_context: &CommandContext<S>) -> RedirectModifierResult<S> {
|
||||
match self {
|
||||
Self::KeepSource => Ok(vec![command_context.source.clone()]),
|
||||
Self::Custom(function) => function(command_context),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the result of a node requirement.
|
||||
pub type RequirementResult = bool;
|
||||
|
||||
/// A predicate that returns if the provided source satisfies it.
|
||||
#[derive(Clone)]
|
||||
pub struct Requirement<S: CommandSource = DummySource>(
|
||||
pub Arc<dyn Fn(&S) -> RequirementResult + Send + Sync>,
|
||||
);
|
||||
|
||||
impl<S: CommandSource> Requirement<S> {
|
||||
/// Evaluates the given condition, returning whether the
|
||||
/// given [`CommandSource`] satisfies this requirement.
|
||||
#[must_use]
|
||||
pub fn evaluate(&self, command_source: &S) -> RequirementResult {
|
||||
self.0(command_source)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S: CommandSource> From<F> for Requirement<S>
|
||||
where
|
||||
F: Fn(&S) -> RequirementResult + Send + Sync + 'static,
|
||||
{
|
||||
fn from(value: F) -> Self {
|
||||
Self(Arc::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
// Permissions
|
||||
impl<S: CommandSource> From<String> for Requirement<S> {
|
||||
fn from(value: String) -> Self {
|
||||
Self(Arc::new({
|
||||
let permission = Arc::new(value);
|
||||
|
||||
move |source: &S| source.has_permission(&permission)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> From<&'static str> for Requirement<S> {
|
||||
fn from(value: &'static str) -> Self {
|
||||
Self(Arc::new(move |source: &S| source.has_permission(value)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A structure that returns if the source is qualified enough to run the command.
|
||||
#[derive(Clone)]
|
||||
pub struct Requirements<S: CommandSource = DummySource>(pub Vec<Requirement<S>>);
|
||||
|
||||
impl<S: CommandSource> Requirements<S> {
|
||||
/// Creates a new `Requirements` with no requirements in it.
|
||||
/// If used, this will always return `true` when evaluated.
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self(Vec::new())
|
||||
}
|
||||
|
||||
/// Evaluates the given condition, returning whether the
|
||||
/// given [`CommandSource`] satisfies all contained requirements.
|
||||
#[must_use]
|
||||
pub fn evaluate(&self, command_source: &S) -> RequirementResult {
|
||||
for predicate in &self.0 {
|
||||
if !predicate.evaluate(command_source) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> Default for Requirements<S> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores common owned data for a node.
|
||||
#[derive(Clone)]
|
||||
pub struct OwnedNodeData<S: CommandSource = DummySource> {
|
||||
pub global_id: GlobalNodeId,
|
||||
pub requirements: Requirements<S>,
|
||||
pub modifier: RedirectModifier<S>,
|
||||
pub forks: bool,
|
||||
pub command: Option<Command<S>>,
|
||||
}
|
||||
|
||||
/// Represents the extra metadata of a node storing a literal.
|
||||
#[derive(Clone)]
|
||||
pub struct LiteralNodeMetadata {
|
||||
pub literal: Cow<'static, str>,
|
||||
pub literal_lowercase: String,
|
||||
}
|
||||
|
||||
impl LiteralNodeMetadata {
|
||||
pub fn new(literal: impl Into<Cow<'static, str>>) -> Self {
|
||||
let literal = literal.into();
|
||||
Self {
|
||||
literal: literal.clone(),
|
||||
literal_lowercase: literal.to_lowercase(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A special type of [`LiteralNodeMetadata`], containing
|
||||
/// a description for the command as well.
|
||||
#[derive(Clone)]
|
||||
pub struct CommandNodeMetadata {
|
||||
pub literal: Cow<'static, str>,
|
||||
pub literal_lowercase: String,
|
||||
pub description: Cow<'static, str>,
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
impl CommandNodeMetadata {
|
||||
pub fn new(
|
||||
literal: impl Into<Cow<'static, str>>,
|
||||
description: impl Into<Cow<'static, str>>,
|
||||
) -> Self {
|
||||
let literal = literal.into();
|
||||
Self {
|
||||
literal: literal.clone(),
|
||||
literal_lowercase: literal.to_lowercase(),
|
||||
description: description.into(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the extra metadata of an argument of any type.
|
||||
#[derive(Clone)]
|
||||
pub struct ArgumentNodeMetadata<S: CommandSource = DummySource> {
|
||||
pub name: Cow<'static, str>,
|
||||
pub argument_type: Arc<dyn AnyArgumentType<S>>,
|
||||
pub suggestion_provider: Option<Arc<dyn SuggestionProvider<S>>>,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> ArgumentNodeMetadata<S> {
|
||||
pub fn new(
|
||||
name: impl Into<Cow<'static, str>>,
|
||||
argument_type: Arc<dyn AnyArgumentType<S>>,
|
||||
suggestion_provider: Option<Arc<dyn SuggestionProvider<S>>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
argument_type,
|
||||
suggestion_provider,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the extra metadata for nodes of different types. Can be of the root, a literal, command or an argument.
|
||||
pub enum NodeMetadata<S: CommandSource = DummySource> {
|
||||
/// Metadata of the root node.
|
||||
Root,
|
||||
|
||||
/// Metadata of a literal node that doesn't start a command.
|
||||
Literal(LiteralNodeMetadata),
|
||||
|
||||
/// Metadata of a literal node that starts a command.
|
||||
Command(CommandNodeMetadata),
|
||||
|
||||
/// Metadata of an argument node.
|
||||
Argument(ArgumentNodeMetadata<S>),
|
||||
}
|
||||
|
||||
/// Stores where this redirection would lead to.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
pub enum Redirection {
|
||||
/// Leads to the root of the tree.
|
||||
Root,
|
||||
|
||||
/// Leads to a node in the tree from its tree-local ID.
|
||||
Local(NodeId),
|
||||
|
||||
/// Leads to a node in the tree from its global ID.
|
||||
Global(GlobalNodeId),
|
||||
}
|
||||
|
||||
impl<T: Into<NodeId>> From<T> for Redirection {
|
||||
fn from(value: T) -> Self {
|
||||
Self::Local(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<GlobalNodeId> for Redirection {
|
||||
fn from(value: GlobalNodeId) -> Self {
|
||||
Self::Global(value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
use crate::context::command_context::{CommandContextBuilder, ParsedArgument};
|
||||
use crate::context::string_range::StringRange;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
use crate::errors::error_types::LITERAL_INCORRECT;
|
||||
use crate::node::Redirection;
|
||||
use crate::node::attached::{
|
||||
ArgumentAttachedNode, ArgumentNodeId, AttachedNode, CommandAttachedNode, CommandNodeId,
|
||||
LiteralAttachedNode, LiteralNodeId, NodeClassification, NodeId, RootAttachedNode,
|
||||
};
|
||||
use crate::node::detached::{CommandDetachedNode, DetachedNode, GlobalNodeId};
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::string_reader::StringReader;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
|
||||
use std::num::NonZero;
|
||||
use std::ops::{Index, IndexMut};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The constant local ID occupied by the root node.
|
||||
pub const ROOT_NODE_ID: NodeId = NodeId(NonZero::new(1).expect("1 is non-zero"));
|
||||
|
||||
/// A consumer which takes ambiguity of input (when two or more nodes are satisfied)
|
||||
pub trait AmbiguityConsumer<S: CommandSource = DummySource> {
|
||||
fn ambiguous(
|
||||
&mut self,
|
||||
tree: &Tree<S>,
|
||||
parent: NodeId,
|
||||
child: NodeId,
|
||||
sibling: NodeId,
|
||||
inputs: Vec<String>,
|
||||
);
|
||||
}
|
||||
|
||||
/// Allows a way to store the kind of node
|
||||
/// along with its ID.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum NodeIdClassification {
|
||||
Root,
|
||||
Literal(LiteralNodeId),
|
||||
Command(CommandNodeId),
|
||||
Argument(ArgumentNodeId),
|
||||
}
|
||||
|
||||
/// Represents an entire tree of nodes.
|
||||
/// It all starts from the root node, which arise
|
||||
/// to children nodes, which arise to their children,
|
||||
/// and so on.
|
||||
///
|
||||
/// This allows redirection and forking
|
||||
/// between two nodes, even if from different commands.
|
||||
///
|
||||
/// This tree can be indexed like an array but with [`NodeId`].
|
||||
///
|
||||
/// # Hierarchy
|
||||
/// This tree can have four different types of nodes, which are the following:
|
||||
///
|
||||
/// - **Root**:
|
||||
/// Does not have a parent. Exactly one instance of this type of node
|
||||
/// exists per [`Tree`]. Always identifiable by [`ROOT_NODE_ID`] (= 1).
|
||||
/// Only command nodes can be the children of this node.
|
||||
///
|
||||
/// **In any `Tree`**, the root node always has the ID of 1.
|
||||
///
|
||||
/// **Violating this constraint is a logic error** and breaks the assumptions
|
||||
/// made in this structure's functionality and that of outside as well.
|
||||
///
|
||||
/// In other words, a non-root node CANNOT HAVE an ID of 1!
|
||||
///
|
||||
/// - **Command**:
|
||||
/// Its parent must be the root node, and specifies the start of a
|
||||
/// command definition.
|
||||
///
|
||||
/// - **Literal**:
|
||||
/// Accepts a particular constant word.
|
||||
///
|
||||
/// - **Argument**:
|
||||
/// Parses and accepts a specific type of value. This is very dynamic.
|
||||
#[derive(Clone)]
|
||||
pub struct Tree<S: CommandSource = DummySource> {
|
||||
/// All the nodes stored in this tree.
|
||||
///
|
||||
/// In this vector, indices starting at 0 indicates the first node (ID = 1),
|
||||
/// 1 indicates the second node (ID = 2) and so on.
|
||||
nodes: Vec<AttachedNode<S>>,
|
||||
|
||||
/// Keys linking [`GlobalNodeId`] to the [`NodeId`] for this tree.
|
||||
/// Useful for redirecting.
|
||||
ids_map: FxHashMap<GlobalNodeId, NodeId>,
|
||||
|
||||
/// Cached mappings for each command.
|
||||
command_node_mappings: FxHashMap<String, CommandNodeId>,
|
||||
}
|
||||
|
||||
impl<S: CommandSource> Default for Tree<S> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> Tree<S> {
|
||||
/// Constructs a new tree, containing a new root node without children.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
let node = RootAttachedNode::new();
|
||||
let mut ids_map = FxHashMap::default();
|
||||
ids_map.insert(node.owned.global_id, ROOT_NODE_ID);
|
||||
Self {
|
||||
nodes: vec![AttachedNode::Root(node)],
|
||||
ids_map,
|
||||
command_node_mappings: FxHashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of nodes in this tree.
|
||||
#[must_use]
|
||||
pub const fn len(&self) -> usize {
|
||||
self.nodes.len()
|
||||
}
|
||||
|
||||
/// Returns `true` if the tree has no nodes.
|
||||
#[must_use]
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty()
|
||||
}
|
||||
|
||||
/// Allocates a new [`NodeId`] by creating a new unique one.
|
||||
const fn alloc(&self) -> NodeId {
|
||||
NodeId(NonZero::new(self.nodes.len() + 1).expect("expected a non-zero id"))
|
||||
}
|
||||
|
||||
/// Helper to attach a given [`AttachedNode`], returning
|
||||
/// its [`NodeId`].
|
||||
fn add(&mut self, node: AttachedNode<S>) -> NodeId {
|
||||
let global_id = node.global_id();
|
||||
let local_id = self.alloc();
|
||||
|
||||
// Update state variables.
|
||||
self.nodes.push(node);
|
||||
self.ids_map.insert(global_id, local_id);
|
||||
|
||||
local_id
|
||||
}
|
||||
|
||||
/// Helper to attach a [`DetachedNode`] irreversibly
|
||||
/// into this [`Tree`], returning the ID of the now attached
|
||||
/// node.
|
||||
fn attach(&mut self, node: DetachedNode<S>) -> NodeId {
|
||||
// First, we decompose this node.
|
||||
let node = node.decompose();
|
||||
|
||||
// Add its children to this tree.
|
||||
let mut children = FxHashMap::with_capacity_and_hasher(node.children.len(), FxBuildHasher);
|
||||
for (child_name, child) in node.children {
|
||||
let child_id = self.attach(child);
|
||||
children.insert(child_name, child_id);
|
||||
}
|
||||
|
||||
// Now create the node to be 'attached'.
|
||||
let node = AttachedNode::from_parts(node.owned, children, node.redirect, node.meta);
|
||||
|
||||
self.add(node)
|
||||
}
|
||||
|
||||
/// Gets the size of this [`Tree`], which is the number of nodes this tree contains.
|
||||
#[must_use]
|
||||
pub const fn size(&self) -> usize {
|
||||
self.nodes.len()
|
||||
}
|
||||
|
||||
/// Gets the size of this [`Tree`], which is the number of nodes this tree contains.
|
||||
#[must_use]
|
||||
pub fn size_nonzero(&self) -> NonZero<usize> {
|
||||
self.nodes
|
||||
.len()
|
||||
.try_into()
|
||||
.expect("Expected non-zero size, but Tree was somehow zero-sized")
|
||||
}
|
||||
|
||||
/// Adds a [`CommandDetachedNode`] to the root node of this tree.
|
||||
pub fn add_child_to_root(&mut self, node: impl Into<CommandDetachedNode<S>>) -> CommandNodeId {
|
||||
// First, attach the node to this tree.
|
||||
let node = node.into();
|
||||
let name = node.meta.literal.to_string();
|
||||
let node = self.attach(node.into());
|
||||
let node = self.add_attached_child(ROOT_NODE_ID, node);
|
||||
|
||||
// This is safe as the node ID now points to a `CommandAttachedNode`.
|
||||
let node = CommandNodeId(node.0);
|
||||
|
||||
self.command_node_mappings.insert(name, node);
|
||||
node
|
||||
}
|
||||
|
||||
/// Adds a child to a given node.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the node to be added to a non-root node is a [`CommandDetachedNode`].
|
||||
///
|
||||
/// Essentially, this means that a [`CommandDetachedNode`] must have the root node
|
||||
/// of the tree *as its parent*, to be attached to the tree.
|
||||
pub fn add_child(&mut self, parent: NodeId, node: impl Into<DetachedNode<S>>) -> NodeId {
|
||||
let node = node.into();
|
||||
assert!(
|
||||
parent == ROOT_NODE_ID || !matches!(node, DetachedNode::Command(_)),
|
||||
"Cannot add a CommandDetachedNode as a child of a non-root node"
|
||||
);
|
||||
|
||||
// First, attach the node to this tree.
|
||||
let node = self.attach(node);
|
||||
self.add_attached_child(parent, node)
|
||||
}
|
||||
|
||||
/// Adds an already-attached child to a given node.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the node to be added to a non-root node is a [`CommandAttachedNode`],
|
||||
/// or if the node to be added to a node is a [`RootAttachedNode`],
|
||||
///
|
||||
/// Essentially, this means that a [`CommandAttachedNode`] must have the root node
|
||||
/// of the tree *as its parent*, and [`RootAttachedNode`] cannot have a parent.
|
||||
fn add_attached_child(&mut self, parent: NodeId, node: NodeId) -> NodeId {
|
||||
assert!(
|
||||
parent == ROOT_NODE_ID || self[node].classification() != NodeClassification::Command,
|
||||
"Cannot add a CommandAttachedNode as a child of a non-root node"
|
||||
);
|
||||
|
||||
let node_name = self[node].name();
|
||||
|
||||
let child = self[parent].children_ref().get(&node_name);
|
||||
if let Some(child) = child {
|
||||
let node_command = self[node].command().clone();
|
||||
let node_children: Vec<NodeId> = self[node].children_ref().values().copied().collect();
|
||||
|
||||
let child = *child;
|
||||
// Merge onto the child.
|
||||
if let Some(command) = node_command {
|
||||
self[child].set_command(Some(command));
|
||||
}
|
||||
for grandchild in node_children {
|
||||
self.add_attached_child(child, grandchild);
|
||||
}
|
||||
child
|
||||
} else {
|
||||
self[parent].children_mut_ref().insert(node_name, node);
|
||||
node
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the children of a given node in the tree.
|
||||
#[must_use]
|
||||
pub fn get_children(&self, node: NodeId) -> Vec<NodeId> {
|
||||
self[node].children_ref().values().copied().collect()
|
||||
}
|
||||
|
||||
/// Gets the children of the root node in the tree.
|
||||
#[must_use]
|
||||
pub fn get_root_children(&self) -> Vec<CommandNodeId> {
|
||||
self[ROOT_NODE_ID]
|
||||
.children_ref()
|
||||
.values()
|
||||
.copied()
|
||||
// This should be fine as all children of the
|
||||
// root node are Command Nodes.
|
||||
.map(|id| CommandNodeId(id.0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns whether the given node is able to be used by a given source.
|
||||
#[must_use]
|
||||
pub fn can_use(&self, node: NodeId, source: &S) -> bool {
|
||||
self[node].requirements().evaluate(source)
|
||||
}
|
||||
|
||||
/// Finds ambiguities of input and gives them to the [`AmbiguityConsumer`].
|
||||
pub fn find_ambiguities(&self, node: NodeId, consumer: &mut impl AmbiguityConsumer<S>) {
|
||||
let mut matches: FxHashSet<String> = FxHashSet::default();
|
||||
|
||||
for child in self.get_children(node) {
|
||||
for sibling in self.get_children(node) {
|
||||
if child == sibling {
|
||||
continue;
|
||||
}
|
||||
for input in self[child].examples() {
|
||||
if self[sibling].is_valid_input(&input) {
|
||||
matches.insert(input.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if !matches.is_empty() {
|
||||
consumer.ambiguous(self, node, child, sibling, matches.drain().collect());
|
||||
}
|
||||
}
|
||||
|
||||
self.find_ambiguities(child, consumer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies a given node to a typed ID.
|
||||
#[must_use]
|
||||
pub fn classify_id(&self, node: NodeId) -> NodeIdClassification {
|
||||
match self[node].classification() {
|
||||
NodeClassification::Root => NodeIdClassification::Root,
|
||||
NodeClassification::Literal => NodeIdClassification::Literal(LiteralNodeId(node.0)),
|
||||
NodeClassification::Command => NodeIdClassification::Command(CommandNodeId(node.0)),
|
||||
NodeClassification::Argument => NodeIdClassification::Argument(ArgumentNodeId(node.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether the given ID points to a command node.
|
||||
#[must_use]
|
||||
pub fn is_command_node(&self, node: NodeId) -> bool {
|
||||
matches!(self[node].classification(), NodeClassification::Command)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_relevant_nodes(&self, reader: &mut StringReader, node: NodeId) -> Vec<NodeId> {
|
||||
let children = self.get_children(node);
|
||||
let mut literals = Vec::new();
|
||||
let mut commands = Vec::new();
|
||||
let mut arguments = Vec::new();
|
||||
for child in children {
|
||||
let id = self.classify_id(child);
|
||||
match id {
|
||||
NodeIdClassification::Root => {}
|
||||
NodeIdClassification::Literal(literal) => literals.push(literal),
|
||||
NodeIdClassification::Command(command) => commands.push(command),
|
||||
NodeIdClassification::Argument(arg) => arguments.push(arg),
|
||||
}
|
||||
}
|
||||
|
||||
// Priority order:
|
||||
// 1. Commands > Literals
|
||||
// 2. Arguments
|
||||
|
||||
if !literals.is_empty() || !commands.is_empty() {
|
||||
let cursor = reader.cursor();
|
||||
while !matches!(reader.peek(), None | Some(' ')) {
|
||||
reader.skip();
|
||||
}
|
||||
let new_cursor = reader.cursor();
|
||||
reader.set_cursor(cursor);
|
||||
let text = &reader.string()[cursor..new_cursor];
|
||||
|
||||
for command in commands {
|
||||
if self[command].meta.literal == text {
|
||||
return vec![command.into()];
|
||||
}
|
||||
}
|
||||
for literal in literals {
|
||||
if self[literal].meta.literal == text {
|
||||
return vec![literal.into()];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
arguments.into_iter().map(ArgumentNodeId::into).collect()
|
||||
}
|
||||
|
||||
/// Parses the given node, returning an error on failure.
|
||||
pub fn parse<'a>(
|
||||
&self,
|
||||
node_id: NodeId,
|
||||
reader: &'a mut StringReader<'_>,
|
||||
command_context_builder: &'a mut CommandContextBuilder<'_, S>,
|
||||
) -> Result<(), CommandSyntaxError> {
|
||||
match &self[node_id] {
|
||||
AttachedNode::Root(_) => {}
|
||||
AttachedNode::Literal(node) => {
|
||||
let start = reader.cursor();
|
||||
let Ok(end) = AttachedNode::<S>::parse_literal(reader, &node.meta.literal) else {
|
||||
return Err(LITERAL_INCORRECT
|
||||
.create(reader, TextComponent::text(node.meta.literal.to_string())));
|
||||
};
|
||||
command_context_builder.with_node(node_id, StringRange::between(start, end));
|
||||
}
|
||||
AttachedNode::Command(node) => {
|
||||
let start = reader.cursor();
|
||||
let Ok(end) = AttachedNode::<S>::parse_literal(reader, &node.meta.literal) else {
|
||||
return Err(LITERAL_INCORRECT
|
||||
.create(reader, TextComponent::text(node.meta.literal.to_string())));
|
||||
};
|
||||
command_context_builder.with_node(node_id, StringRange::between(start, end));
|
||||
}
|
||||
AttachedNode::Argument(node) => {
|
||||
let start = reader.cursor();
|
||||
let result = node
|
||||
.meta
|
||||
.argument_type
|
||||
.parse_with_source(reader, &command_context_builder.source)?;
|
||||
let range = StringRange::between(start, reader.cursor());
|
||||
let parsed = ParsedArgument::new(range, result);
|
||||
command_context_builder.with_argument(node.meta.name.to_string(), Arc::new(parsed));
|
||||
command_context_builder.with_node(node_id, range);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolves the given redirection with respect to this tree, which is the node from
|
||||
/// which redirection takes place.
|
||||
///
|
||||
/// Returns [`Some`] if the node required could be found, and
|
||||
/// returns [`None`] otherwise.
|
||||
#[must_use]
|
||||
pub fn resolve(&self, redirect: Redirection) -> Option<NodeId> {
|
||||
match redirect {
|
||||
Redirection::Root => Some(ROOT_NODE_ID),
|
||||
Redirection::Global(id) => self.ids_map.get(&id).copied(),
|
||||
Redirection::Local(id) => (id.0 < self.size_nonzero()).then_some(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the command node by ID, given its literal.
|
||||
#[must_use]
|
||||
pub fn get(&self, name: &str) -> Option<CommandNodeId> {
|
||||
self.command_node_mappings.get(name).copied()
|
||||
}
|
||||
|
||||
/// Returns an iterator to all the nodes of this tree.
|
||||
pub fn iter(&self) -> std::slice::Iter<'_, AttachedNode<S>> {
|
||||
self.nodes.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> Index<NodeId> for Tree<S> {
|
||||
type Output = AttachedNode<S>;
|
||||
|
||||
fn index(&self, index: NodeId) -> &Self::Output {
|
||||
&self.nodes[index.0.get() - 1]
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> IndexMut<NodeId> for Tree<S> {
|
||||
fn index_mut(&mut self, index: NodeId) -> &mut Self::Output {
|
||||
&mut self.nodes[index.0.get() - 1]
|
||||
}
|
||||
}
|
||||
|
||||
/// Macro helper to create [`Index`] and [`IndexMut`] for [`Tree`] with typed IDs.
|
||||
macro_rules! impl_index_index_mut {
|
||||
($node_id: ident -> AttachedNode::$attached_node_enum: ident($attached_node: ident)) => {
|
||||
impl<S: CommandSource> Index<$node_id> for Tree<S> {
|
||||
type Output = $attached_node<S>;
|
||||
|
||||
fn index(&self, index: $node_id) -> &Self::Output {
|
||||
if let AttachedNode::$attached_node_enum(node) = &self.nodes[index.0.get() - 1] {
|
||||
node
|
||||
} else {
|
||||
unreachable!(
|
||||
"Node should have been AttachedNode::{}",
|
||||
stringify!($attached_node_enum)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> IndexMut<$node_id> for Tree<S> {
|
||||
fn index_mut(&mut self, index: $node_id) -> &mut Self::Output {
|
||||
if let AttachedNode::$attached_node_enum(node) = &mut self.nodes[index.0.get() - 1]
|
||||
{
|
||||
node
|
||||
} else {
|
||||
unreachable!(
|
||||
"Node should have been AttachedNode::{}",
|
||||
stringify!($attached_node_enum)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_index_index_mut!(LiteralNodeId -> AttachedNode::Literal(LiteralAttachedNode));
|
||||
impl_index_index_mut!(CommandNodeId -> AttachedNode::Command(CommandAttachedNode));
|
||||
impl_index_index_mut!(ArgumentNodeId -> AttachedNode::Argument(ArgumentAttachedNode));
|
||||
|
||||
impl<'a, S: CommandSource> IntoIterator for &'a Tree<S> {
|
||||
type Item = &'a AttachedNode<S>;
|
||||
type IntoIter = std::slice::Iter<'a, AttachedNode<S>>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::argument_builder::{
|
||||
ArgumentBuilder, CommandArgumentBuilder, LiteralArgumentBuilder, RequiredArgumentBuilder,
|
||||
};
|
||||
use crate::argument_types::core::string::StringArgumentType;
|
||||
use crate::node::attached::NodeId;
|
||||
use crate::node::tree::{AmbiguityConsumer, Tree};
|
||||
use crate::source::DummySource;
|
||||
|
||||
#[test]
|
||||
fn adding_nodes() {
|
||||
// New tree (containing only one root node)
|
||||
let mut tree = Tree::<DummySource>::new();
|
||||
assert_eq!(tree.size(), 1);
|
||||
|
||||
// Adding one node.
|
||||
tree.add_child_to_root(CommandArgumentBuilder::new("foo", "A test command"));
|
||||
assert_eq!(tree.size(), 2);
|
||||
|
||||
// Adding a node with children.
|
||||
tree.add_child_to_root(
|
||||
// Each subcommand is a child.
|
||||
CommandArgumentBuilder::new("bar", "Another test command")
|
||||
.then(LiteralArgumentBuilder::new("baz"))
|
||||
.then(LiteralArgumentBuilder::new("qux")),
|
||||
);
|
||||
assert_eq!(tree.size(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_children_to_attached_node() {
|
||||
let mut tree = Tree::<DummySource>::new();
|
||||
|
||||
let parent: NodeId = tree
|
||||
.add_child_to_root(CommandArgumentBuilder::new("foo", "A test command"))
|
||||
.into();
|
||||
|
||||
tree.add_child(parent, LiteralArgumentBuilder::new("baz"));
|
||||
tree.add_child(parent, LiteralArgumentBuilder::new("qux"));
|
||||
|
||||
assert_eq!(tree.size(), 4);
|
||||
assert_eq!(tree.get_children(parent).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic = "Cannot add a CommandDetachedNode as a child of a non-root node"]
|
||||
fn adding_command_node_to_non_root_node() {
|
||||
let mut tree = Tree::<DummySource>::new();
|
||||
|
||||
let parent: NodeId = tree
|
||||
.add_child_to_root(CommandArgumentBuilder::new("foo", "A test command"))
|
||||
.into();
|
||||
|
||||
tree.add_child(
|
||||
parent,
|
||||
CommandArgumentBuilder::new("bar", "Another test command"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_ambiguities() {
|
||||
struct Consumer {
|
||||
inputs_received: usize,
|
||||
expected_parent: NodeId,
|
||||
expected_sibling: NodeId,
|
||||
}
|
||||
|
||||
impl AmbiguityConsumer for Consumer {
|
||||
fn ambiguous(
|
||||
&mut self,
|
||||
_tree: &Tree,
|
||||
parent: NodeId,
|
||||
_child: NodeId,
|
||||
sibling: NodeId,
|
||||
inputs: Vec<String>,
|
||||
) {
|
||||
self.inputs_received += inputs.len();
|
||||
|
||||
assert_eq!(self.expected_parent, parent);
|
||||
assert_eq!(self.expected_sibling, sibling);
|
||||
}
|
||||
}
|
||||
|
||||
let mut tree = Tree::new();
|
||||
|
||||
let parent: NodeId = tree
|
||||
.add_child_to_root(CommandArgumentBuilder::new("foo", "A test command"))
|
||||
.into();
|
||||
|
||||
tree.add_child(parent, LiteralArgumentBuilder::new("hello"));
|
||||
tree.add_child(parent, LiteralArgumentBuilder::new("bye"));
|
||||
let sibling = tree.add_child(
|
||||
parent,
|
||||
RequiredArgumentBuilder::new("string", StringArgumentType::SingleWord),
|
||||
);
|
||||
|
||||
let mut consumer = Consumer {
|
||||
inputs_received: 0,
|
||||
expected_parent: parent,
|
||||
expected_sibling: sibling,
|
||||
};
|
||||
tree.find_ambiguities(parent, &mut consumer);
|
||||
|
||||
assert_eq!(consumer.inputs_received, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::{
|
||||
errors::error_types::{AnyCommandErrorType, CommandErrorType},
|
||||
string_reader::StringReader,
|
||||
};
|
||||
|
||||
/// A delayed version of `CommandSyntaxError`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DelayedCommandSyntaxError {
|
||||
pub error_type: &'static dyn AnyCommandErrorType,
|
||||
pub java_translation_key: &'static str,
|
||||
pub bedrock_translation_key: &'static str,
|
||||
pub arguments: Vec<Cow<'static, str>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ParserErrors {
|
||||
pub cursor: usize,
|
||||
pub command_error: Option<DelayedCommandSyntaxError>,
|
||||
pub suggestions: Vec<Cow<'static, str>>,
|
||||
}
|
||||
|
||||
/// A trait so that a parser specializing
|
||||
/// to keep track of errors don't need to keep track
|
||||
/// of suggestions, and vice versa.
|
||||
impl ParserErrors {
|
||||
pub fn simple_static(
|
||||
&mut self,
|
||||
reader: &StringReader,
|
||||
error_type: &'static CommandErrorType<0>,
|
||||
suggestions: &[&'static str],
|
||||
) {
|
||||
self.store(
|
||||
reader,
|
||||
|| DelayedCommandSyntaxError {
|
||||
error_type,
|
||||
java_translation_key: error_type.java_translation_key,
|
||||
bedrock_translation_key: error_type.bedrock_translation_key,
|
||||
arguments: vec![],
|
||||
},
|
||||
|entries| {
|
||||
for suggestion in suggestions {
|
||||
entries.push(Cow::Borrowed(*suggestion));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn dynamic_static<A: Into<Cow<'static, str>>>(
|
||||
&mut self,
|
||||
reader: &StringReader,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
arg1: A,
|
||||
suggestions: &[&'static str],
|
||||
) {
|
||||
self.store(
|
||||
reader,
|
||||
|| DelayedCommandSyntaxError {
|
||||
error_type,
|
||||
java_translation_key: error_type.java_translation_key,
|
||||
bedrock_translation_key: error_type.bedrock_translation_key,
|
||||
arguments: vec![arg1.into()],
|
||||
},
|
||||
|entries| {
|
||||
for suggestion in suggestions {
|
||||
entries.push(Cow::Borrowed(*suggestion));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn simple(
|
||||
&mut self,
|
||||
reader: &StringReader,
|
||||
error_type: &'static CommandErrorType<0>,
|
||||
suggestions: Vec<String>,
|
||||
) {
|
||||
self.store(
|
||||
reader,
|
||||
|| DelayedCommandSyntaxError {
|
||||
error_type,
|
||||
java_translation_key: error_type.java_translation_key,
|
||||
bedrock_translation_key: error_type.bedrock_translation_key,
|
||||
arguments: vec![],
|
||||
},
|
||||
|entries| {
|
||||
for suggestion in suggestions {
|
||||
entries.push(Cow::Owned(suggestion));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn dynamic<A: Into<Cow<'static, str>>>(
|
||||
&mut self,
|
||||
reader: &StringReader,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
arg1: A,
|
||||
suggestions: Vec<String>,
|
||||
) {
|
||||
self.store(
|
||||
reader,
|
||||
|| DelayedCommandSyntaxError {
|
||||
error_type,
|
||||
java_translation_key: error_type.java_translation_key,
|
||||
bedrock_translation_key: error_type.bedrock_translation_key,
|
||||
arguments: vec![arg1.into()],
|
||||
},
|
||||
|entries| {
|
||||
for suggestion in suggestions {
|
||||
entries.push(Cow::Owned(suggestion));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn store(
|
||||
&mut self,
|
||||
reader: &StringReader,
|
||||
error: impl FnOnce() -> DelayedCommandSyntaxError,
|
||||
suggestions: impl FnOnce(&mut Vec<Cow<'static, str>>),
|
||||
) {
|
||||
let current = self.cursor;
|
||||
let new = reader.cursor();
|
||||
|
||||
if self.command_error.is_none() || new > current {
|
||||
self.command_error = Some(error());
|
||||
self.cursor = new;
|
||||
self.suggestions.clear();
|
||||
suggestions(&mut self.suggestions);
|
||||
} else if new == current {
|
||||
suggestions(&mut self.suggestions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait that rule-like parsers like `SnbtParser` implement.
|
||||
pub trait Parser<'r, 's> {
|
||||
fn state_mut(&mut self) -> (&mut StringReader<'s>, &mut ParserErrors);
|
||||
|
||||
/// Records that a simple error occurred while parsing, and adds suggestions to counteract it.
|
||||
fn store_simple_error_and_suggest(
|
||||
&mut self,
|
||||
error_type: &'static CommandErrorType<0>,
|
||||
suggestions: &[&'static str],
|
||||
) {
|
||||
let (reader, errors) = self.state_mut();
|
||||
errors.simple_static(reader, error_type, suggestions);
|
||||
}
|
||||
|
||||
/// Records that a dynamic error occurred while parsing, and adds suggestions to counteract it.
|
||||
fn store_dynamic_error_and_suggest(
|
||||
&mut self,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
arg1: impl Into<Cow<'static, str>>,
|
||||
suggestions: &[&'static str],
|
||||
) {
|
||||
let (reader, errors) = self.state_mut();
|
||||
errors.dynamic_static(reader, error_type, arg1, suggestions);
|
||||
}
|
||||
|
||||
/// Records that a simple error occurred while parsing.
|
||||
fn store_simple_error(&mut self, error_type: &'static CommandErrorType<0>) {
|
||||
let (reader, errors) = self.state_mut();
|
||||
errors.simple(reader, error_type, Vec::new());
|
||||
}
|
||||
|
||||
/// Records that a dynamic error occurred while parsing.
|
||||
fn store_dynamic_error(
|
||||
&mut self,
|
||||
error_type: &'static CommandErrorType<1>,
|
||||
arg1: impl Into<Cow<'static, str>>,
|
||||
) {
|
||||
let (reader, errors) = self.state_mut();
|
||||
errors.dynamic(reader, error_type, arg1, Vec::new());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
use crate::{
|
||||
errors::error_types::CommandErrorType,
|
||||
snbt::rules::{EXPECTED_BINARY_NUMERAL, EXPECTED_DECIMAL_NUMERAL, EXPECTED_HEX_NUMERAL},
|
||||
};
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Sign {
|
||||
Plus = 0,
|
||||
Minus = 1,
|
||||
}
|
||||
|
||||
impl Sign {
|
||||
/// Returns the minimum number of characters required to express this sign to be parsed.
|
||||
///
|
||||
/// For example, between `5.0` and `+5.0`, the former takes no space for the `+` symbol,
|
||||
/// while for `-5.0`, there must be a `-` symbol, so the minimum size there is `1` instead of `0`.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn minimum_size_parsable(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
|
||||
/// Appends the slice containing the minimum characters required to express this sign to be parsed to a String
|
||||
/// referred by the given mutable reference.
|
||||
///
|
||||
/// This is a no-op for [`Sign::Plus`], while for [`Sign::Minus`], a `-` is appended.
|
||||
#[inline]
|
||||
pub fn append_minimum_str_parsable(self, buffer: &mut String) {
|
||||
if self == Self::Minus {
|
||||
buffer.push('-');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SignedPrefix {
|
||||
None,
|
||||
Unsigned,
|
||||
Signed,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TypeSuffix {
|
||||
None,
|
||||
Byte,
|
||||
Short,
|
||||
Int,
|
||||
Long,
|
||||
Float,
|
||||
Double,
|
||||
}
|
||||
|
||||
impl TypeSuffix {
|
||||
#[must_use]
|
||||
/// Returns the `default` suffix if this suffix is [`TypeSuffix::None`], otherwise
|
||||
/// it returns itself.
|
||||
pub fn or(self, default: Self) -> Self {
|
||||
if self == Self::None { default } else { self }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct IntegerSuffix(pub SignedPrefix, pub TypeSuffix);
|
||||
|
||||
impl IntegerSuffix {
|
||||
pub const EMPTY: Self = Self(SignedPrefix::None, TypeSuffix::None);
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Base {
|
||||
Binary,
|
||||
Decimal,
|
||||
Hexadecimal,
|
||||
}
|
||||
|
||||
impl Base {
|
||||
#[must_use]
|
||||
pub const fn should_allow(self, c: char) -> bool {
|
||||
matches!(
|
||||
(self, c),
|
||||
(_, '_') |
|
||||
(Self::Binary, '0' | '1') |
|
||||
(Self::Decimal, '0'..='9') |
|
||||
(Self::Hexadecimal, '0'..='9' | 'A'..='F' | 'a'..='f')
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn no_value_error_type(self) -> &'static CommandErrorType<0> {
|
||||
match self {
|
||||
Self::Binary => &EXPECTED_BINARY_NUMERAL,
|
||||
Self::Decimal => &EXPECTED_DECIMAL_NUMERAL,
|
||||
Self::Hexadecimal => &EXPECTED_HEX_NUMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn radix(self) -> u32 {
|
||||
match self {
|
||||
Self::Binary => 2,
|
||||
Self::Decimal => 10,
|
||||
Self::Hexadecimal => 16,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct IntegerLiteral {
|
||||
pub sign: Sign,
|
||||
pub base: Base,
|
||||
pub digits: String,
|
||||
pub suffix: IntegerSuffix,
|
||||
}
|
||||
|
||||
impl IntegerLiteral {
|
||||
pub const fn get_signed_prefix_or_default(&self) -> SignedPrefix {
|
||||
match (self.suffix.0, self.base) {
|
||||
(SignedPrefix::None, Base::Binary | Base::Hexadecimal) => SignedPrefix::Unsigned,
|
||||
(SignedPrefix::None, Base::Decimal) => SignedPrefix::Signed,
|
||||
(prefix, _) => prefix,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Signed<T> {
|
||||
pub sign: Sign,
|
||||
pub value: T,
|
||||
}
|
||||
|
||||
/// Represents a explicit prefix set for an array.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ArrayPrefix {
|
||||
Byte,
|
||||
Long,
|
||||
Int,
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
mod markers;
|
||||
mod operations;
|
||||
mod rules;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use crate::errors::command_syntax_error::{CommandSyntaxError, CommandSyntaxErrorContext};
|
||||
use crate::errors::error_types::{CommandErrorType, LITERAL_INCORRECT};
|
||||
use crate::parser::{Parser, ParserErrors};
|
||||
use crate::snbt::markers::{ArrayPrefix, Base, IntegerLiteral, Sign, SignedPrefix, TypeSuffix};
|
||||
use crate::string_reader::StringReader;
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use pumpkin_codecs::Number;
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_nbt::tag::NbtTag;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
|
||||
pub const NUMBER_PARSE_FAILURE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_NUMBER_PARSE_FAILURE,
|
||||
translation::java::SNBT_PARSER_NUMBER_PARSE_FAILURE,
|
||||
);
|
||||
|
||||
pub const UNDERSCORE_NOT_ALLOWED: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_UNDESCORE_NOT_ALLOWED,
|
||||
translation::java::SNBT_PARSER_UNDESCORE_NOT_ALLOWED,
|
||||
);
|
||||
|
||||
pub const EXPECTED_HEX_ESCAPE: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_HEX_ESCAPE,
|
||||
translation::java::SNBT_PARSER_EXPECTED_HEX_ESCAPE,
|
||||
);
|
||||
|
||||
pub const EXPECTED_NON_NEGATIVE_NUMBER: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_NON_NEGATIVE_NUMBER,
|
||||
translation::java::SNBT_PARSER_EXPECTED_NON_NEGATIVE_NUMBER,
|
||||
);
|
||||
|
||||
pub const INVALID_ARRAY_ELEMENT_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_INVALID_ARRAY_ELEMENT_TYPE,
|
||||
translation::java::SNBT_PARSER_INVALID_ARRAY_ELEMENT_TYPE,
|
||||
);
|
||||
|
||||
pub const EXPECTED_INTEGER_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_INTEGER_TYPE,
|
||||
translation::java::SNBT_PARSER_EXPECTED_INTEGER_TYPE,
|
||||
);
|
||||
|
||||
/// A structure that parses SNBT.
|
||||
///
|
||||
/// This stores a reader and gives the furthest error, or suggestions
|
||||
/// to fix errors that have ever occurred while parsing.
|
||||
pub struct SnbtParser<'r, 's> {
|
||||
reader: &'r mut StringReader<'s>,
|
||||
errors: ParserErrors,
|
||||
}
|
||||
|
||||
//
|
||||
// USAGE
|
||||
//
|
||||
impl SnbtParser<'_, '_> {
|
||||
/// Parses SNBT with a given [`StringReader`], giving the result or error from parsing.
|
||||
#[expect(deprecated)]
|
||||
pub fn parse_for_commands(reader: &mut StringReader) -> Result<NbtTag, CommandSyntaxError> {
|
||||
let (result, errors) = {
|
||||
let mut parser = SnbtParser {
|
||||
reader,
|
||||
errors: ParserErrors::default(),
|
||||
};
|
||||
|
||||
let literal = parser.parse();
|
||||
let errors = parser.errors;
|
||||
|
||||
(literal, errors)
|
||||
};
|
||||
|
||||
result.ok_or_else(|| {
|
||||
if let Some(error) = errors.command_error {
|
||||
CommandSyntaxError {
|
||||
error_type: error.error_type,
|
||||
message: TextComponent::translate_cross(
|
||||
error.java_translation_key,
|
||||
error.bedrock_translation_key,
|
||||
error
|
||||
.arguments
|
||||
.into_iter()
|
||||
.map(TextComponent::text)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
context: Some(CommandSyntaxErrorContext { input: reader.string().to_string(), cursor: errors.cursor }),
|
||||
}
|
||||
} else {
|
||||
// This shouldn't happen... If it didn't parse successfully, there should be an error to supplement it.
|
||||
// Hacky way to report an error:
|
||||
const PARSING_FAILED_WITHOUT_ERRORS: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::COMMAND_FAILED,
|
||||
translation::java::COMMAND_FAILED
|
||||
);
|
||||
tracing::error!("Failed to parse SNBT, while having zero errors to report (report this to Pumpkin): {}", reader.string());
|
||||
PARSING_FAILED_WITHOUT_ERRORS.create(reader)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Parses SNBT with a given [`StringReader`], giving the suggestions to fix errors from parsing.
|
||||
#[must_use]
|
||||
pub fn parse_for_suggestions(mut builder: SuggestionsBuilder) -> Suggestions {
|
||||
let errors = {
|
||||
let mut reader = StringReader::new(&builder.input);
|
||||
reader.set_cursor(builder.start);
|
||||
|
||||
let mut parser = SnbtParser {
|
||||
reader: &mut reader,
|
||||
errors: ParserErrors::default(),
|
||||
};
|
||||
|
||||
let _ = parser.parse();
|
||||
parser.errors
|
||||
};
|
||||
|
||||
if !errors.suggestions.is_empty() {
|
||||
builder = builder.create_offset(errors.cursor);
|
||||
for suggestion in &errors.suggestions {
|
||||
builder = builder.filter_and_suggest_one(suggestion.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// HELPER FUNCTIONS
|
||||
//
|
||||
impl SnbtParser<'_, '_> {
|
||||
/// Utility method that parses a type suffix of an integer.
|
||||
fn integer_type_suffix(&mut self) -> Option<TypeSuffix> {
|
||||
self.reader.skip_whitespace();
|
||||
match self.reader.peek() {
|
||||
Some('b' | 'B') => {
|
||||
self.reader.skip();
|
||||
Some(TypeSuffix::Byte)
|
||||
}
|
||||
Some('s' | 'S') => {
|
||||
self.reader.skip();
|
||||
Some(TypeSuffix::Short)
|
||||
}
|
||||
Some('i' | 'I') => {
|
||||
self.reader.skip();
|
||||
Some(TypeSuffix::Int)
|
||||
}
|
||||
Some('l' | 'L') => {
|
||||
self.reader.skip();
|
||||
Some(TypeSuffix::Long)
|
||||
}
|
||||
_ => {
|
||||
// Only b|B is given as the error, being the first errored choice.
|
||||
self.store_dynamic_error_and_suggest(
|
||||
&LITERAL_INCORRECT,
|
||||
"b|B",
|
||||
&["b", "B", "s", "S", "i", "I", "l", "L"],
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// General method that parses an integer of a specific base.
|
||||
fn parse_numeral(&mut self, base: Base) -> Option<String> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
let slice = parser.reader.string();
|
||||
|
||||
let start = parser.reader.cursor();
|
||||
|
||||
let mut end = start;
|
||||
for (i, c) in slice[start..].char_indices() {
|
||||
if !base.should_allow(c) {
|
||||
break;
|
||||
}
|
||||
end = start + i + c.len_utf8();
|
||||
}
|
||||
|
||||
if start == end {
|
||||
parser.store_simple_error(base.no_value_error_type());
|
||||
None
|
||||
} else if slice.as_bytes()[start] == b'_' || slice.as_bytes()[end - 1] == b'_' {
|
||||
parser.store_simple_error(&UNDERSCORE_NOT_ALLOWED);
|
||||
None
|
||||
} else {
|
||||
parser.reader.set_cursor(end);
|
||||
Some(parser.reader.string()[start..end].to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses a value, and if unsuccessful, reverts back to what the state initially was.
|
||||
#[inline]
|
||||
fn parse_or_revert<T>(&mut self, closure: impl FnOnce(&mut Self) -> Option<T>) -> Option<T> {
|
||||
let start = self.reader.cursor();
|
||||
let result = closure(self);
|
||||
if result.is_none() {
|
||||
self.reader.set_cursor(start);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Appends every character given in the `reference` slice except `_` in the provided `buffer`.
|
||||
fn clean_and_append(buffer: &mut String, reference: &str) {
|
||||
// This could really be optimized further
|
||||
// with bytes instead of chars, but that
|
||||
// probably requires unsafe code. Is that worth it?
|
||||
// TODO
|
||||
for c in reference.chars() {
|
||||
if c != '_' {
|
||||
buffer.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// General method to parse a specific number of hexadecimal digits greedily (no underscores are allowed).
|
||||
fn hex_literal(&mut self, digits: usize) -> Option<String> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
let slice = parser.reader.string();
|
||||
|
||||
let start = parser.reader.cursor();
|
||||
|
||||
let mut end = start;
|
||||
for (count, (i, c)) in slice[start..].char_indices().enumerate() {
|
||||
if count == digits || !c.is_ascii_hexdigit() {
|
||||
break;
|
||||
}
|
||||
end = start + i + c.len_utf8();
|
||||
}
|
||||
|
||||
if end - start < digits {
|
||||
parser.store_dynamic_error(&EXPECTED_HEX_ESCAPE, digits.to_string());
|
||||
None
|
||||
} else {
|
||||
parser.reader.set_cursor(end);
|
||||
Some(parser.reader.string()[start..end].to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn repeated_with_trailing_comma<T, S>(
|
||||
&mut self,
|
||||
rule: impl Fn(&mut Self) -> Option<T>,
|
||||
new: S,
|
||||
insert: impl Fn(&mut S, T),
|
||||
) -> S {
|
||||
let mut elements = new;
|
||||
let mut first = true;
|
||||
|
||||
loop {
|
||||
if !first {
|
||||
let parse_comma = self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() == Some(',') {
|
||||
parser.reader.skip();
|
||||
Some(())
|
||||
} else {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, ",", &[","]);
|
||||
None
|
||||
}
|
||||
});
|
||||
if parse_comma.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(parsed) = self.parse_or_revert(&rule) {
|
||||
insert(&mut elements, parsed);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
first = false;
|
||||
}
|
||||
|
||||
elements
|
||||
}
|
||||
|
||||
fn repeated_with_trailing_comma_vec<T>(
|
||||
&mut self,
|
||||
rule: impl Fn(&mut Self) -> Option<T>,
|
||||
) -> Vec<T> {
|
||||
self.repeated_with_trailing_comma(rule, Vec::new(), Vec::push)
|
||||
}
|
||||
|
||||
fn parse_integer_literal(
|
||||
&mut self,
|
||||
literal: &IntegerLiteral,
|
||||
suffix: TypeSuffix,
|
||||
) -> Option<Number> {
|
||||
let signed = literal.get_signed_prefix_or_default() == SignedPrefix::Signed;
|
||||
if !signed && literal.sign == Sign::Minus {
|
||||
self.store_simple_error(&EXPECTED_NON_NEGATIVE_NUMBER);
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut number =
|
||||
String::with_capacity(literal.digits.len() + literal.sign.minimum_size_parsable());
|
||||
|
||||
literal.sign.append_minimum_str_parsable(&mut number);
|
||||
Self::clean_and_append(&mut number, &literal.digits);
|
||||
|
||||
let radix = literal.base.radix();
|
||||
|
||||
// The error messages vary by a lot to match the error messages in Java.
|
||||
match (signed, suffix) {
|
||||
(true, TypeSuffix::Byte) => {
|
||||
let integer = self.parse_int_or_error(&number, radix)?;
|
||||
|
||||
integer.try_into().map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("Value out of range. Value:\"{number}\" Radix:{radix}"),
|
||||
);
|
||||
None
|
||||
},
|
||||
|byte| Some(Number::Byte(byte)),
|
||||
)
|
||||
}
|
||||
(true, TypeSuffix::Short) => {
|
||||
let integer = self.parse_int_or_error(&number, radix)?;
|
||||
|
||||
integer.try_into().map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("Value out of range. Value:\"{number}\" Radix:{radix}"),
|
||||
);
|
||||
None
|
||||
},
|
||||
|short| Some(Number::Short(short)),
|
||||
)
|
||||
}
|
||||
(true, TypeSuffix::Int) => Some(Number::Int(self.parse_int_or_error(&number, radix)?)),
|
||||
(true, TypeSuffix::Long) => i64::from_str_radix(&number, radix).map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("For input string: \"{number}\""),
|
||||
);
|
||||
None
|
||||
},
|
||||
|long| Some(Number::Long(long)),
|
||||
),
|
||||
(false, TypeSuffix::Byte) => {
|
||||
let integer = self.parse_int_or_error(&number, radix)?;
|
||||
|
||||
TryInto::<u8>::try_into(integer).map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("out of range: {number}"),
|
||||
);
|
||||
None
|
||||
},
|
||||
|byte| Some(Number::Byte(byte as i8)),
|
||||
)
|
||||
}
|
||||
(false, TypeSuffix::Short) => {
|
||||
let integer = self.parse_int_or_error(&number, radix)?;
|
||||
|
||||
TryInto::<u16>::try_into(integer).map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("out of range: {number}"),
|
||||
);
|
||||
None
|
||||
},
|
||||
|short| Some(Number::Short(short as i16)),
|
||||
)
|
||||
}
|
||||
(false, TypeSuffix::Int) => u32::from_str_radix(&number, radix).map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("String value {number} exceeds range of unsigned int."),
|
||||
);
|
||||
None
|
||||
},
|
||||
|int| Some(Number::Int(int as i32)),
|
||||
),
|
||||
(false, TypeSuffix::Long) => u64::from_str_radix(&number, radix).map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("String value {number} exceeds range of unsigned long."),
|
||||
);
|
||||
None
|
||||
},
|
||||
|long| Some(Number::Long(long as i64)),
|
||||
),
|
||||
_ => {
|
||||
self.store_simple_error(&EXPECTED_INTEGER_TYPE);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_int_or_error(&mut self, number: &str, radix: u32) -> Option<i32> {
|
||||
i32::from_str_radix(number, radix).map_or_else(
|
||||
|_| {
|
||||
self.store_dynamic_error(
|
||||
&NUMBER_PARSE_FAILURE,
|
||||
format!("For input string: \"{number}\""),
|
||||
);
|
||||
None
|
||||
},
|
||||
Some,
|
||||
)
|
||||
}
|
||||
|
||||
fn create_prefixed_array(
|
||||
&mut self,
|
||||
values: &[IntegerLiteral],
|
||||
prefix: ArrayPrefix,
|
||||
) -> Option<NbtTag> {
|
||||
match prefix {
|
||||
ArrayPrefix::Byte => self.create_byte_array(values),
|
||||
ArrayPrefix::Int => self.create_int_array(values),
|
||||
ArrayPrefix::Long => self.create_long_array(values),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_byte_array(&mut self, values: &[IntegerLiteral]) -> Option<NbtTag> {
|
||||
let mut bytes = Vec::with_capacity(values.len());
|
||||
for value in values {
|
||||
if !matches!(value.suffix.1, TypeSuffix::None | TypeSuffix::Byte) {
|
||||
self.store_simple_error(&INVALID_ARRAY_ELEMENT_TYPE);
|
||||
return None;
|
||||
}
|
||||
bytes.push(self.parse_integer_literal(value, TypeSuffix::Byte)?.into());
|
||||
}
|
||||
Some(NbtTag::ByteArray(bytes.into()))
|
||||
}
|
||||
|
||||
fn create_int_array(&mut self, values: &[IntegerLiteral]) -> Option<NbtTag> {
|
||||
let mut ints = Vec::with_capacity(values.len());
|
||||
for value in values {
|
||||
let suffix = value.suffix.1.or(TypeSuffix::Int);
|
||||
if !matches!(
|
||||
suffix,
|
||||
TypeSuffix::Byte | TypeSuffix::Short | TypeSuffix::Int
|
||||
) {
|
||||
self.store_simple_error(&INVALID_ARRAY_ELEMENT_TYPE);
|
||||
return None;
|
||||
}
|
||||
ints.push(self.parse_integer_literal(value, suffix)?.into());
|
||||
}
|
||||
Some(NbtTag::IntArray(ints))
|
||||
}
|
||||
|
||||
fn create_long_array(&mut self, values: &[IntegerLiteral]) -> Option<NbtTag> {
|
||||
let mut longs = Vec::with_capacity(values.len());
|
||||
for value in values {
|
||||
let suffix = value.suffix.1.or(TypeSuffix::Long);
|
||||
if !matches!(
|
||||
suffix,
|
||||
TypeSuffix::Byte | TypeSuffix::Short | TypeSuffix::Int | TypeSuffix::Long
|
||||
) {
|
||||
self.store_simple_error(&INVALID_ARRAY_ELEMENT_TYPE);
|
||||
return None;
|
||||
}
|
||||
longs.push(self.parse_integer_literal(value, suffix)?.into());
|
||||
}
|
||||
Some(NbtTag::LongArray(longs))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r, 's> Parser<'r, 's> for SnbtParser<'r, 's> {
|
||||
fn state_mut(&mut self) -> (&mut StringReader<'s>, &mut ParserErrors) {
|
||||
(self.reader, &mut self.errors)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_nbt::{nbt_ops::NbtOps, tag::NbtTag};
|
||||
use pumpkin_util::uuid::parse_uuid_vec;
|
||||
|
||||
use crate::{errors::error_types::CommandErrorType, parser::Parser, snbt::SnbtParser};
|
||||
use pumpkin_codecs::DynamicOps;
|
||||
|
||||
pub const EXPECTED_NUMBER_OR_BOOLEAN: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_NUMBER_OR_BOOLEAN,
|
||||
translation::java::SNBT_PARSER_EXPECTED_NUMBER_OR_BOOLEAN,
|
||||
);
|
||||
|
||||
pub const EXPECTED_STRING_UUID: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_STRING_UUID,
|
||||
translation::java::SNBT_PARSER_EXPECTED_STRING_UUID,
|
||||
);
|
||||
|
||||
/// Represents an *operation* that can take *operands* and return a required *result*.
|
||||
pub type SnbtOperation = fn(parser: &mut SnbtParser, args: &[NbtTag]) -> Option<NbtTag>;
|
||||
|
||||
/// A manager for SNBT operations baked at compile-time.
|
||||
pub struct SnbtOperations;
|
||||
|
||||
impl SnbtOperations {
|
||||
pub const BUILTIN_IDS: &[&str] = &["true", "false", "bool", "uuid"];
|
||||
|
||||
/// Searches for an operation to be run from the
|
||||
/// given identifier and argument count.
|
||||
pub fn search(id: &str, arg_count: usize) -> Option<SnbtOperation> {
|
||||
match (id, arg_count) {
|
||||
("bool", 1) => Some(Self::bool),
|
||||
("uuid", 1) => Some(Self::uuid),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the `bool` unary operator in SNBT.
|
||||
///
|
||||
/// Acts like an identity operation for booleans,
|
||||
/// and returns `true` for non-zero numbers.
|
||||
fn bool(parser: &mut SnbtParser, args: &[NbtTag]) -> Option<NbtTag> {
|
||||
NbtOps.get_bool(&args[0]).into_result().map_or_else(
|
||||
|| {
|
||||
parser.store_simple_error(&EXPECTED_NUMBER_OR_BOOLEAN);
|
||||
None
|
||||
},
|
||||
|result| Some(NbtTag::Byte(result as i8)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Represents the `uuid` unary operator in SNBT.
|
||||
///
|
||||
/// Parses a UUID in a string to an array of 4 integers.
|
||||
fn uuid(parser: &mut SnbtParser, args: &[NbtTag]) -> Option<NbtTag> {
|
||||
if let NbtTag::String(string) = &args[0]
|
||||
&& let Some(ints) = parse_uuid_vec(string)
|
||||
{
|
||||
Some(NbtTag::IntArray(ints))
|
||||
} else {
|
||||
parser.store_simple_error(&EXPECTED_STRING_UUID);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,853 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::errors::error_types::{CommandErrorType, LITERAL_INCORRECT};
|
||||
use crate::parser::Parser;
|
||||
use crate::snbt::markers::{
|
||||
ArrayPrefix, Base, IntegerLiteral, IntegerSuffix, Sign, Signed, SignedPrefix, TypeSuffix,
|
||||
};
|
||||
use crate::snbt::operations::SnbtOperations;
|
||||
use crate::snbt::{NUMBER_PARSE_FAILURE, SnbtParser};
|
||||
use pumpkin_codecs::{DynamicOps, Number};
|
||||
use pumpkin_data::translation;
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_nbt::nbt_ops::NbtOps;
|
||||
use pumpkin_nbt::tag::NbtTag;
|
||||
|
||||
pub const INVALID_CODEPOINT: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_INVALID_CODEPOINT,
|
||||
translation::java::SNBT_PARSER_INVALID_CODEPOINT,
|
||||
);
|
||||
|
||||
pub const NO_SUCH_OPERATION: CommandErrorType<1> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_NO_SUCH_OPERATION,
|
||||
translation::java::SNBT_PARSER_NO_SUCH_OPERATION,
|
||||
);
|
||||
|
||||
pub const EXPECTED_FLOAT_TYPE: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_FLOAT_TYPE,
|
||||
translation::java::SNBT_PARSER_EXPECTED_FLOAT_TYPE,
|
||||
);
|
||||
|
||||
pub const INVALID_CHARACTER_NAME: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_INVALID_CHARACTER_NAME,
|
||||
translation::java::SNBT_PARSER_INVALID_CHARACTER_NAME,
|
||||
);
|
||||
|
||||
pub const INVALID_UNQUOTED_START: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_INVALID_UNQUOTED_START,
|
||||
translation::java::SNBT_PARSER_INVALID_UNQUOTED_START,
|
||||
);
|
||||
|
||||
pub const EXPECTED_UNQUOTED_STRING: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_UNQUOTED_STRING,
|
||||
translation::java::SNBT_PARSER_EXPECTED_UNQUOTED_STRING,
|
||||
);
|
||||
|
||||
pub const INVALID_STRING_CONTENTS: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_INVALID_STRING_CONTENTS,
|
||||
translation::java::SNBT_PARSER_INVALID_STRING_CONTENTS,
|
||||
);
|
||||
|
||||
pub const EXPECTED_BINARY_NUMERAL: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_BINARY_NUMERAL,
|
||||
translation::java::SNBT_PARSER_EXPECTED_BINARY_NUMERAL,
|
||||
);
|
||||
|
||||
pub const EXPECTED_DECIMAL_NUMERAL: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_DECIMAL_NUMERAL,
|
||||
translation::java::SNBT_PARSER_EXPECTED_DECIMAL_NUMERAL,
|
||||
);
|
||||
|
||||
pub const EXPECTED_HEX_NUMERAL: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EXPECTED_HEX_NUMERAL,
|
||||
translation::java::SNBT_PARSER_EXPECTED_HEX_NUMERAL,
|
||||
);
|
||||
|
||||
pub const EMPTY_KEY: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_EMPTY_KEY,
|
||||
translation::java::SNBT_PARSER_EMPTY_KEY,
|
||||
);
|
||||
|
||||
pub const LEADING_ZERO_NOT_ALLOWED: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_LEADING_ZERO_NOT_ALLOWED,
|
||||
translation::java::SNBT_PARSER_LEADING_ZERO_NOT_ALLOWED,
|
||||
);
|
||||
|
||||
pub const INFINITY_NOT_ALLOWED: CommandErrorType<0> = CommandErrorType::new(
|
||||
translation::java::SNBT_PARSER_INFINITY_NOT_ALLOWED,
|
||||
translation::java::SNBT_PARSER_INFINITY_NOT_ALLOWED,
|
||||
);
|
||||
|
||||
/// Parses a string literal.
|
||||
macro_rules! parse_string_literal {
|
||||
($parser:expr, $quote:literal) => {{
|
||||
let mut buffer = String::new();
|
||||
let mut high_surrogate_queue: u32 = 0;
|
||||
|
||||
loop {
|
||||
match $parser.reader.read() {
|
||||
Some($quote) => break Some(buffer),
|
||||
Some('\\') => {
|
||||
let i = $parser.escape_sequence()?;
|
||||
if let Some(c) = char::from_u32(i) {
|
||||
buffer.push(c);
|
||||
} else if high_surrogate_queue == 0 && matches!(i, 0xD800..=0xDBFF) {
|
||||
// High surrogate incoming.
|
||||
high_surrogate_queue = i;
|
||||
} else if high_surrogate_queue != 0 && matches!(i, 0xDC00..=0xDFFF) {
|
||||
// Low surrogate incoming.
|
||||
let high_bits = high_surrogate_queue - 0xD800;
|
||||
let low_bits = i - 0xDC00;
|
||||
let bits = high_bits << 10 | low_bits;
|
||||
let i = bits + 0x10000;
|
||||
// This really shouldn't fail though.
|
||||
if let Some(c) = char::from_u32(i) {
|
||||
buffer.push(c);
|
||||
} else {
|
||||
buffer.push('\u{FFFD}');
|
||||
}
|
||||
high_surrogate_queue = 0;
|
||||
} else {
|
||||
// Add replacement character.
|
||||
buffer.push('\u{FFFD}');
|
||||
if high_surrogate_queue != 0 {
|
||||
buffer.push('\u{FFFD}');
|
||||
}
|
||||
high_surrogate_queue = 0;
|
||||
}
|
||||
}
|
||||
Some(ch) => {
|
||||
if high_surrogate_queue != 0 {
|
||||
// Add replacement character.
|
||||
buffer.push('\u{FFFD}');
|
||||
high_surrogate_queue = 0;
|
||||
}
|
||||
buffer.push(ch);
|
||||
}
|
||||
None => {
|
||||
// reached EOL
|
||||
$parser.store_simple_error_and_suggest(
|
||||
&INVALID_STRING_CONTENTS,
|
||||
&["'", "\"", "\\"],
|
||||
);
|
||||
break None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
impl SnbtParser<'_, '_> {
|
||||
fn sign(&mut self) -> Option<Sign> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
match parser.reader.peek() {
|
||||
Some('+') => {
|
||||
parser.reader.skip();
|
||||
Some(Sign::Plus)
|
||||
}
|
||||
Some('-') => {
|
||||
parser.reader.skip();
|
||||
Some(Sign::Minus)
|
||||
}
|
||||
_ => {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "+", &["+", "-"]);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn integer_suffix(&mut self) -> Option<IntegerSuffix> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
match parser.reader.peek() {
|
||||
Some('u' | 'U') => {
|
||||
parser.reader.skip();
|
||||
Some(IntegerSuffix(
|
||||
SignedPrefix::Unsigned,
|
||||
parser.integer_type_suffix()?,
|
||||
))
|
||||
}
|
||||
Some('s' | 'S') => {
|
||||
// Can mean signed or short.
|
||||
Some(
|
||||
if let Some(suffix) = parser.parse_or_revert(|parser| {
|
||||
parser.reader.skip();
|
||||
parser.integer_type_suffix()
|
||||
}) {
|
||||
IntegerSuffix(SignedPrefix::Signed, suffix)
|
||||
} else {
|
||||
IntegerSuffix(SignedPrefix::None, parser.integer_type_suffix()?)
|
||||
},
|
||||
)
|
||||
}
|
||||
Some('b' | 'B' | 'i' | 'I' | 'l' | 'L') => Some(IntegerSuffix(
|
||||
SignedPrefix::None,
|
||||
parser.integer_type_suffix()?,
|
||||
)),
|
||||
_ => {
|
||||
parser.store_dynamic_error_and_suggest(
|
||||
&LITERAL_INCORRECT,
|
||||
"u|U",
|
||||
&["u", "U", "s", "S", "b", "B", "s", "S", "i", "I", "l", "L"],
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn binary_numeral(&mut self) -> Option<String> {
|
||||
self.parse_numeral(Base::Binary)
|
||||
}
|
||||
|
||||
fn decimal_numeral(&mut self) -> Option<String> {
|
||||
self.parse_numeral(Base::Decimal)
|
||||
}
|
||||
|
||||
fn hexadecimal_numeral(&mut self) -> Option<String> {
|
||||
self.parse_numeral(Base::Hexadecimal)
|
||||
}
|
||||
|
||||
/// Parses an integer literal.
|
||||
fn integer_literal(&mut self) -> Option<IntegerLiteral> {
|
||||
let mut result = self.parse_or_revert(|parser| {
|
||||
let sign = parser.parse_or_revert(Self::sign).unwrap_or(Sign::Plus);
|
||||
parser.reader.skip_whitespace();
|
||||
|
||||
// We need to be careful to make sure that
|
||||
// `0b` parses as a byte literal and NOT a prefix.
|
||||
let after_sign_cursor = parser.reader.cursor();
|
||||
if parser.reader.peek() == Some('0') {
|
||||
parser.reader.skip();
|
||||
parser.reader.skip_whitespace();
|
||||
match parser.reader.peek() {
|
||||
Some('x' | 'X') => {
|
||||
parser.reader.skip();
|
||||
return parser.hexadecimal_numeral().map(|number| IntegerLiteral {
|
||||
sign,
|
||||
base: Base::Hexadecimal,
|
||||
suffix: IntegerSuffix::EMPTY,
|
||||
digits: number,
|
||||
});
|
||||
}
|
||||
Some('b' | 'B') => {
|
||||
parser.reader.skip();
|
||||
if let Some(number) = parser.binary_numeral() {
|
||||
return Some(IntegerLiteral {
|
||||
sign,
|
||||
base: Base::Binary,
|
||||
suffix: IntegerSuffix::EMPTY,
|
||||
digits: number,
|
||||
});
|
||||
}
|
||||
parser.reader.set_cursor(after_sign_cursor);
|
||||
}
|
||||
_ => {
|
||||
return if parser.decimal_numeral().is_none() {
|
||||
Some(IntegerLiteral {
|
||||
sign,
|
||||
base: Base::Decimal,
|
||||
suffix: IntegerSuffix::EMPTY,
|
||||
digits: "0".to_string(),
|
||||
})
|
||||
} else {
|
||||
parser.store_simple_error(&LEADING_ZERO_NOT_ALLOWED);
|
||||
None
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(number) = parser.decimal_numeral() {
|
||||
return Some(IntegerLiteral {
|
||||
sign,
|
||||
base: Base::Decimal,
|
||||
suffix: IntegerSuffix::EMPTY,
|
||||
digits: number,
|
||||
});
|
||||
}
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "0", &["0"]);
|
||||
None
|
||||
})?;
|
||||
|
||||
result.suffix = self
|
||||
.parse_or_revert(Self::integer_suffix)
|
||||
.unwrap_or(IntegerSuffix::EMPTY);
|
||||
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn float_type_suffix(&mut self) -> Option<TypeSuffix> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
match parser.reader.peek() {
|
||||
Some('f' | 'F') => {
|
||||
parser.reader.skip();
|
||||
Some(TypeSuffix::Float)
|
||||
}
|
||||
Some('d' | 'D') => {
|
||||
parser.reader.skip();
|
||||
Some(TypeSuffix::Double)
|
||||
}
|
||||
_ => {
|
||||
parser.store_dynamic_error_and_suggest(
|
||||
&LITERAL_INCORRECT,
|
||||
"f|F",
|
||||
&["f", "F", "d", "D"],
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn float_exponent_part(&mut self) -> Option<Signed<String>> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
if matches!(parser.reader.peek(), Some('e' | 'E')) {
|
||||
parser.reader.skip();
|
||||
let sign = parser.parse_or_revert(Self::sign).unwrap_or(Sign::Plus);
|
||||
let value = parser.decimal_numeral()?;
|
||||
|
||||
Some(Signed { sign, value })
|
||||
} else {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "e|E", &["e", "E"]);
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn float_literal(&mut self) -> Option<NbtTag> {
|
||||
struct FloatingPointIntermediate {
|
||||
whole_part: String,
|
||||
fraction_part: Option<String>,
|
||||
exponent_part: Option<Signed<String>>,
|
||||
type_suffix: Option<TypeSuffix>,
|
||||
}
|
||||
|
||||
// Paths:
|
||||
// A --- XXX.[yyy][eZZZ][suffix]
|
||||
// B --- .yyy[eZZZ][suffix]
|
||||
// C --- XXXeZZZ[suffix]
|
||||
// D --- XXX[eZZZ]suffix
|
||||
//
|
||||
// where [a] means 'optionally parse a',
|
||||
// XXX is the whole part, yyy is the decimal part,
|
||||
// eZZZ is the float exponent path, and
|
||||
// suffix is float type suffix.
|
||||
//
|
||||
// Ruleset:
|
||||
// If we encounter a digit, we must parse a decimal number. Then:
|
||||
// If we encounter a decimal point, we must choose path A.
|
||||
// Try to parse [eZZZ] AND [suffix]:
|
||||
// if [eZZZ] parses, then irrespective of [suffix], choose path D.
|
||||
// if ONLY [suffix] parses, choose path C.
|
||||
// if none parse, FAIL.
|
||||
// If we encounter a decimal point, we must choose path B.
|
||||
// FAIL if nether a period or a digit
|
||||
|
||||
let sign = self.parse_or_revert(Self::sign).unwrap_or(Sign::Plus);
|
||||
|
||||
let intermediate = self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
if let Some(whole_part) = parser.parse_or_revert(Self::decimal_numeral) {
|
||||
// Must be pathway A, C, or D.
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() == Some('.') {
|
||||
// We choose pathway A.
|
||||
parser.reader.skip();
|
||||
|
||||
let fraction_part = parser.decimal_numeral();
|
||||
let exponent_part = parser.float_exponent_part();
|
||||
let type_suffix = parser.float_type_suffix();
|
||||
|
||||
Some(FloatingPointIntermediate {
|
||||
whole_part,
|
||||
fraction_part,
|
||||
exponent_part,
|
||||
type_suffix,
|
||||
})
|
||||
} else {
|
||||
// This error won't actually matter if the following part
|
||||
// parses successfully.
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, ".", &["."]);
|
||||
|
||||
// Must be pathway C or D.
|
||||
let exponent_part = parser.float_exponent_part();
|
||||
let type_suffix = parser.float_type_suffix();
|
||||
|
||||
(exponent_part.is_some() || type_suffix.is_some()).then_some(
|
||||
FloatingPointIntermediate {
|
||||
whole_part,
|
||||
fraction_part: None,
|
||||
exponent_part,
|
||||
type_suffix,
|
||||
},
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// We must parse a decimal point.
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() == Some('.') {
|
||||
parser.reader.skip();
|
||||
// We choose pathway B.
|
||||
let fraction_part = parser.decimal_numeral()?;
|
||||
let exponent_part = parser.float_exponent_part();
|
||||
let type_suffix = parser.float_type_suffix();
|
||||
|
||||
Some(FloatingPointIntermediate {
|
||||
whole_part: String::new(),
|
||||
fraction_part: Some(fraction_part),
|
||||
exponent_part,
|
||||
type_suffix,
|
||||
})
|
||||
} else {
|
||||
// We cannot choose a pathway.
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, ".", &["."]);
|
||||
None
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
// Parsing the float:
|
||||
let mut buffer = String::with_capacity(
|
||||
sign.minimum_size_parsable()
|
||||
+ intermediate.whole_part.len()
|
||||
+ intermediate
|
||||
.fraction_part
|
||||
.as_ref()
|
||||
.map_or(0, |s| 1 + s.len())
|
||||
+ intermediate
|
||||
.exponent_part
|
||||
.as_ref()
|
||||
.map_or(0, |s| 1 + s.sign.minimum_size_parsable() + s.value.len()),
|
||||
);
|
||||
|
||||
sign.append_minimum_str_parsable(&mut buffer);
|
||||
Self::clean_and_append(&mut buffer, &intermediate.whole_part);
|
||||
if let Some(fraction) = &intermediate.fraction_part {
|
||||
buffer.push('.');
|
||||
Self::clean_and_append(&mut buffer, fraction);
|
||||
}
|
||||
if let Some(exponent) = &intermediate.exponent_part {
|
||||
buffer.push('e');
|
||||
exponent.sign.append_minimum_str_parsable(&mut buffer);
|
||||
Self::clean_and_append(&mut buffer, &exponent.value);
|
||||
}
|
||||
|
||||
match intermediate.type_suffix {
|
||||
None | Some(TypeSuffix::Double) => match buffer.parse::<f64>() {
|
||||
Err(_) => self.store_dynamic_error(&NUMBER_PARSE_FAILURE, "Invalid float literal"),
|
||||
Ok(value) if value.is_finite() => {
|
||||
return Some(NbtTag::Double(value));
|
||||
}
|
||||
Ok(_) => self.store_simple_error(&INFINITY_NOT_ALLOWED),
|
||||
},
|
||||
Some(TypeSuffix::Float) => match buffer.parse::<f32>() {
|
||||
Err(_) => {
|
||||
self.store_dynamic_error(&NUMBER_PARSE_FAILURE, "Invalid float literal");
|
||||
}
|
||||
Ok(value) if value.is_finite() => {
|
||||
return Some(NbtTag::Float(value));
|
||||
}
|
||||
Ok(_) => self.store_simple_error(&INFINITY_NOT_ALLOWED),
|
||||
},
|
||||
_ => self.store_simple_error(&EXPECTED_FLOAT_TYPE),
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn string_hex_2(&mut self) -> Option<String> {
|
||||
self.hex_literal(2)
|
||||
}
|
||||
|
||||
fn string_hex_4(&mut self) -> Option<String> {
|
||||
self.hex_literal(4)
|
||||
}
|
||||
|
||||
fn string_hex_8(&mut self) -> Option<String> {
|
||||
self.hex_literal(8)
|
||||
}
|
||||
|
||||
/// Parses a unicode name pattern.
|
||||
fn string_unicode_name(&mut self) -> Option<String> {
|
||||
self.parse_or_revert(|parser| {
|
||||
let start = parser.reader.cursor();
|
||||
let mut end = start;
|
||||
|
||||
// Since the only characters allowed are all ASCII, it should
|
||||
// be fine to go byte by byte.
|
||||
let bytes = parser.reader.string().as_bytes();
|
||||
|
||||
while end < bytes.len() {
|
||||
let b = bytes[end];
|
||||
if matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b' ' | b'-') {
|
||||
end += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if start == end {
|
||||
parser.store_simple_error(&INVALID_CHARACTER_NAME);
|
||||
None
|
||||
} else {
|
||||
parser.reader.set_cursor(end);
|
||||
Some(parser.reader.string()[start..end].to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses an escape sequence (without the \)
|
||||
/// The returned character will be expressed as a `u32`
|
||||
/// due to Rust's strictness on `char` of surrogate codepoints.
|
||||
fn escape_sequence(&mut self) -> Option<u32> {
|
||||
enum EscapeSequenceBranch {
|
||||
Return(char),
|
||||
CheckValidity(u32),
|
||||
UnicodeName(String),
|
||||
}
|
||||
|
||||
let cursor_at_escaping_char = self.reader.cursor();
|
||||
let branch = match self.reader.read() {
|
||||
Some('b') => Some(EscapeSequenceBranch::Return('\x08')),
|
||||
Some('s') => Some(EscapeSequenceBranch::Return(' ')),
|
||||
Some('t') => Some(EscapeSequenceBranch::Return('\t')),
|
||||
Some('n') => Some(EscapeSequenceBranch::Return('\n')),
|
||||
Some('f') => Some(EscapeSequenceBranch::Return('\x0C')),
|
||||
Some('r') => Some(EscapeSequenceBranch::Return('\r')),
|
||||
Some('\\') => Some(EscapeSequenceBranch::Return('\\')),
|
||||
Some('\'') => Some(EscapeSequenceBranch::Return('\'')),
|
||||
Some('"') => Some(EscapeSequenceBranch::Return('"')),
|
||||
Some('x') => Some(EscapeSequenceBranch::CheckValidity(
|
||||
u32::from_str_radix(&self.string_hex_2()?, 16).ok()?,
|
||||
)),
|
||||
Some('u') => Some(EscapeSequenceBranch::CheckValidity(
|
||||
u32::from_str_radix(&self.string_hex_4()?, 16).ok()?,
|
||||
)),
|
||||
Some('U') => Some(EscapeSequenceBranch::CheckValidity(
|
||||
u32::from_str_radix(&self.string_hex_8()?, 16).ok()?,
|
||||
)),
|
||||
Some('N') => {
|
||||
if self.reader.peek() != Some('{') {
|
||||
self.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "{", &["}"]);
|
||||
return None;
|
||||
}
|
||||
self.reader.skip();
|
||||
let string_unicode_name = self.string_unicode_name()?;
|
||||
if self.reader.peek() != Some('}') {
|
||||
self.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "}", &["}"]);
|
||||
return None;
|
||||
}
|
||||
self.reader.skip();
|
||||
Some(EscapeSequenceBranch::UnicodeName(string_unicode_name))
|
||||
}
|
||||
_ => {
|
||||
self.reader.set_cursor(cursor_at_escaping_char);
|
||||
self.store_dynamic_error_and_suggest(
|
||||
&LITERAL_INCORRECT,
|
||||
"b",
|
||||
&[
|
||||
"b", "s", "t", "n", "f", "r", "\\", "'", "\"", "x", "u", "U", "N",
|
||||
],
|
||||
);
|
||||
None
|
||||
}
|
||||
}?;
|
||||
|
||||
match branch {
|
||||
EscapeSequenceBranch::Return(ch) => Some(ch as u32),
|
||||
EscapeSequenceBranch::CheckValidity(value) => {
|
||||
// Value must be <= 0x10FFFF to be a valid codepoint.
|
||||
// (Surrogates are handled outside this function)
|
||||
if value <= 0x10FFFF {
|
||||
Some(value)
|
||||
} else {
|
||||
self.store_dynamic_error(&INVALID_CODEPOINT, format!("U+{value:08X}"));
|
||||
None
|
||||
}
|
||||
}
|
||||
EscapeSequenceBranch::UnicodeName(_name) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn quoted_string_literal(&mut self) -> Option<String> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
match parser.reader.peek() {
|
||||
Some('\'') => {
|
||||
parser.reader.skip();
|
||||
parse_string_literal!(parser, '\'')
|
||||
}
|
||||
Some('"') => {
|
||||
parser.reader.skip();
|
||||
parse_string_literal!(parser, '"')
|
||||
}
|
||||
_ => {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "\"", &["'", "\""]);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn unquoted_string_literal(&mut self) -> Option<String> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
let value = parser.reader.read_unquoted_string();
|
||||
if value.is_empty() {
|
||||
parser.store_simple_error(&EXPECTED_UNQUOTED_STRING);
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn arguments(&mut self) -> Vec<NbtTag> {
|
||||
self.repeated_with_trailing_comma_vec(Self::literal)
|
||||
}
|
||||
|
||||
fn unquoted_string_or_built_in(&mut self) -> Option<NbtTag> {
|
||||
let literal = self.unquoted_string_literal()?;
|
||||
// Trying to match the same behaviour of storing arguments
|
||||
// in the scope even if the right bracket failed to parse:
|
||||
let mut arguments = None;
|
||||
|
||||
let _ = self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() != Some('(') {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "(", &["("]);
|
||||
return None;
|
||||
}
|
||||
parser.reader.skip();
|
||||
arguments = Some(parser.arguments());
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() == Some(')') {
|
||||
parser.reader.skip();
|
||||
Some(())
|
||||
} else {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, ")", &[")"]);
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
// This should be fine as the characters in the predicate are all ASCII.
|
||||
if literal.is_empty() || matches!(literal.as_bytes()[0], b'0'..=b'9' | b'+' | b'-' | b'.') {
|
||||
self.store_simple_error_and_suggest(
|
||||
&INVALID_UNQUOTED_START,
|
||||
SnbtOperations::BUILTIN_IDS,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(arguments) = arguments {
|
||||
let count = arguments.len();
|
||||
if let Some(operation) = SnbtOperations::search(&literal, count) {
|
||||
operation(self, &arguments[..])
|
||||
} else {
|
||||
self.store_dynamic_error(&NO_SUCH_OPERATION, format!("{literal}/{count}"));
|
||||
None
|
||||
}
|
||||
} else if literal.eq_ignore_ascii_case("true") {
|
||||
Some(NbtTag::Byte(1))
|
||||
} else if literal.eq_ignore_ascii_case("false") {
|
||||
Some(NbtTag::Byte(0))
|
||||
} else {
|
||||
Some(NbtTag::String(literal.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn map_key(&mut self) -> Option<String> {
|
||||
self.parse_or_revert(Self::quoted_string_literal)
|
||||
.map_or_else(|| self.unquoted_string_literal(), Some)
|
||||
}
|
||||
|
||||
fn map_entry(&mut self) -> Option<(String, NbtTag)> {
|
||||
let entry = self.parse_or_revert(|parser| {
|
||||
let key = parser.map_key()?;
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() == Some(':') {
|
||||
parser.reader.skip();
|
||||
Some((key, parser.literal()?))
|
||||
} else {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, ":", &[":"]);
|
||||
None
|
||||
}
|
||||
})?;
|
||||
|
||||
if entry.0.is_empty() {
|
||||
self.store_simple_error(&EMPTY_KEY);
|
||||
None
|
||||
} else {
|
||||
Some(entry)
|
||||
}
|
||||
}
|
||||
|
||||
fn map_entries(&mut self) -> HashMap<String, NbtTag> {
|
||||
self.repeated_with_trailing_comma(Self::map_entry, HashMap::new(), |map, element| {
|
||||
map.insert(element.0, element.1);
|
||||
})
|
||||
}
|
||||
|
||||
fn map_literal(&mut self) -> Option<NbtTag> {
|
||||
let entries = self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() != Some('{') {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "{", &["}"]);
|
||||
return None;
|
||||
}
|
||||
parser.reader.skip();
|
||||
let entries = parser.map_entries();
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() != Some('}') {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "}", &["}"]);
|
||||
return None;
|
||||
}
|
||||
parser.reader.skip();
|
||||
Some(entries)
|
||||
})?;
|
||||
|
||||
Some(NbtTag::Compound(NbtCompound {
|
||||
child_tags: entries.into_iter().map(|(k, v)| (k.into(), v)).collect(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn list_entries(&mut self) -> Vec<NbtTag> {
|
||||
self.repeated_with_trailing_comma_vec(Self::literal)
|
||||
}
|
||||
|
||||
fn array_prefix(&mut self) -> Option<ArrayPrefix> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
match parser.reader.peek() {
|
||||
Some('B') => {
|
||||
parser.reader.skip();
|
||||
Some(ArrayPrefix::Byte)
|
||||
}
|
||||
Some('I') => {
|
||||
parser.reader.skip();
|
||||
Some(ArrayPrefix::Int)
|
||||
}
|
||||
Some('L') => {
|
||||
parser.reader.skip();
|
||||
Some(ArrayPrefix::Long)
|
||||
}
|
||||
_ => {
|
||||
parser.store_dynamic_error_and_suggest(
|
||||
&LITERAL_INCORRECT,
|
||||
"B",
|
||||
&["B", "I", "L"],
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn int_array_entries(&mut self) -> Vec<IntegerLiteral> {
|
||||
self.repeated_with_trailing_comma_vec(Self::integer_literal)
|
||||
}
|
||||
|
||||
fn list_literal(&mut self) -> Option<NbtTag> {
|
||||
self.parse_or_revert(|parser| {
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() != Some('[') {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "[", &["["]);
|
||||
return None;
|
||||
}
|
||||
parser.reader.skip();
|
||||
|
||||
if let Some((prefix, literals)) = parser.parse_or_revert(|parser| {
|
||||
let prefix = parser.array_prefix()?;
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() == Some(';') {
|
||||
parser.reader.skip();
|
||||
let entries = parser.int_array_entries();
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() != Some(']') {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "]", &["]"]);
|
||||
return None;
|
||||
}
|
||||
parser.reader.skip();
|
||||
|
||||
Some((prefix, entries))
|
||||
} else {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, ";", &[";"]);
|
||||
None
|
||||
}
|
||||
}) {
|
||||
parser.create_prefixed_array(&literals[..], prefix)
|
||||
} else {
|
||||
let entries = parser.list_entries();
|
||||
|
||||
parser.reader.skip_whitespace();
|
||||
if parser.reader.peek() != Some(']') {
|
||||
parser.store_dynamic_error_and_suggest(&LITERAL_INCORRECT, "]", &["]"]);
|
||||
return None;
|
||||
}
|
||||
parser.reader.skip();
|
||||
|
||||
Some(NbtOps.create_list(entries))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn literal(&mut self) -> Option<NbtTag> {
|
||||
enum Literal {
|
||||
Tag(NbtTag),
|
||||
Integer(IntegerLiteral),
|
||||
String(String),
|
||||
}
|
||||
|
||||
self.reader.skip_whitespace();
|
||||
|
||||
// This has to match the actual rules, so this code is pretty awkward.
|
||||
let mut result = None;
|
||||
|
||||
if matches!(self.reader.peek(), Some('0'..='9' | '+' | '-' | '.')) {
|
||||
if let Some(tag) = self.parse_or_revert(Self::float_literal) {
|
||||
result = Some(Literal::Tag(tag));
|
||||
} else if let Some(literal) = self.parse_or_revert(Self::integer_literal) {
|
||||
result = Some(Literal::Integer(literal));
|
||||
}
|
||||
}
|
||||
|
||||
let result = if let Some(result) = result {
|
||||
result
|
||||
} else {
|
||||
match self.reader.peek() {
|
||||
Some('"' | '\'') => Literal::String(self.quoted_string_literal()?),
|
||||
Some('{') => Literal::Tag(self.map_literal()?),
|
||||
Some('[') => Literal::Tag(self.list_literal()?),
|
||||
_ => Literal::Tag(self.unquoted_string_or_built_in()?),
|
||||
}
|
||||
};
|
||||
|
||||
Some(match result {
|
||||
Literal::Tag(tag) => tag,
|
||||
Literal::Integer(int) => {
|
||||
match self.parse_integer_literal(&int, int.suffix.1.or(TypeSuffix::Int))? {
|
||||
Number::Byte(byte) => NbtTag::Byte(byte),
|
||||
Number::Short(short) => NbtTag::Short(short),
|
||||
Number::Int(int) => NbtTag::Int(int),
|
||||
Number::Long(long) => NbtTag::Long(long),
|
||||
_ => {
|
||||
self.store_dynamic_error(
|
||||
&INVALID_CODEPOINT,
|
||||
"Expected integer".to_string(),
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Literal::String(string) => NbtTag::String(string.into()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn parse(&mut self) -> Option<NbtTag> {
|
||||
self.literal()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
use pumpkin_nbt::{compound::NbtCompound, nbt_compound_tag, tag::NbtTag};
|
||||
|
||||
const BUILT_IN_LIKE_SUGGESTIONS: &[&str] = &["(", "bool", "false", "true", "uuid"];
|
||||
|
||||
use crate::{
|
||||
errors::command_syntax_error::CommandSyntaxError, snbt::SnbtParser,
|
||||
string_reader::StringReader, suggestion::suggestions::SuggestionsBuilder,
|
||||
};
|
||||
|
||||
fn parse(snbt: &str) -> Result<NbtTag, CommandSyntaxError> {
|
||||
SnbtParser::parse_for_commands(&mut StringReader::new(snbt))
|
||||
}
|
||||
|
||||
fn suggestions(snbt: &str) -> Vec<String> {
|
||||
let builder = SuggestionsBuilder::new(snbt, 0);
|
||||
let suggestions = SnbtParser::parse_for_suggestions(builder);
|
||||
suggestions
|
||||
.suggestions
|
||||
.into_iter()
|
||||
.map(|suggestion| suggestion.text_as_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
macro_rules! assert_parse_ok {
|
||||
($snbt:expr, $tag:expr) => {
|
||||
let mut reader = StringReader::new($snbt);
|
||||
match SnbtParser::parse_for_commands(&mut reader) {
|
||||
Err(error) => {
|
||||
panic!("Expected a successful parse, but instead got error: {error:?}")
|
||||
}
|
||||
Ok(tag_parsed) => {
|
||||
assert_eq!(
|
||||
tag_parsed, $tag,
|
||||
"Parsed tag does not match the required one"
|
||||
);
|
||||
assert!(
|
||||
reader.cursor() == reader.string().len(),
|
||||
"Expected everything to get parsed, but found trailing data: {}",
|
||||
&reader.string()[reader.cursor()..]
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_parse_ok_but_trailing {
|
||||
($snbt:expr, $trailing_data:expr) => {
|
||||
let mut reader = StringReader::new($snbt);
|
||||
if let Err(error) = SnbtParser::parse_for_commands(&mut reader) {
|
||||
panic!("Expected a successful parse, but instead got error: {error:?}")
|
||||
}
|
||||
assert!(
|
||||
reader.cursor() < reader.string().len(),
|
||||
"Expected trailing data, but everything was parsed successfully"
|
||||
);
|
||||
assert_eq!(
|
||||
&reader.string()[reader.cursor()..],
|
||||
$trailing_data,
|
||||
"Trailing data don't match"
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_parse_err {
|
||||
($snbt:expr, $error_message:expr, $cursor:expr) => {
|
||||
let parsed = parse($snbt);
|
||||
match parsed {
|
||||
Ok(tag) => panic!("Expected command error, but instead got result: {tag:#?}"),
|
||||
Err(error) => {
|
||||
assert_eq!(
|
||||
error.message.get_text(),
|
||||
$error_message,
|
||||
"Error messages don't match"
|
||||
);
|
||||
// There should always be a context in SNBT parsing.
|
||||
assert_eq!(
|
||||
error
|
||||
.context
|
||||
.expect("There should always be a context in SNBT parsing")
|
||||
.cursor,
|
||||
$cursor,
|
||||
"Cursor positions for error don't match"
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Without this, we keep getting the error message: type annotations needed
|
||||
($snbt:expr, $error_message:expr, $cursor:expr, []) => {
|
||||
assert_parse_err!($snbt, $error_message, $cursor);
|
||||
let suggestions = suggestions($snbt);
|
||||
assert!(
|
||||
suggestions.is_empty(),
|
||||
"Expected no suggestions, but got one or more: {suggestions:?}"
|
||||
);
|
||||
};
|
||||
($snbt:expr, $error_message:expr, $cursor:expr, $suggestions:expr) => {
|
||||
assert_parse_err!($snbt, $error_message, $cursor);
|
||||
let suggestions = suggestions($snbt);
|
||||
assert_eq!(suggestions, $suggestions, "Suggestions don't match");
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integers() {
|
||||
assert_parse_ok!("9", NbtTag::Int(9));
|
||||
assert_parse_ok!("5_0_0_0", NbtTag::Int(5000));
|
||||
assert_parse_err!(
|
||||
"5_0_0_0_",
|
||||
"Expected literal (",
|
||||
8,
|
||||
BUILT_IN_LIKE_SUGGESTIONS
|
||||
);
|
||||
assert_parse_err!(
|
||||
"5_0_0_0_",
|
||||
"Expected literal (",
|
||||
8,
|
||||
BUILT_IN_LIKE_SUGGESTIONS
|
||||
);
|
||||
|
||||
assert_parse_ok!("3ub", NbtTag::Byte(3));
|
||||
assert_parse_ok!("-7s", NbtTag::Short(-7));
|
||||
assert_parse_ok!("255uB", NbtTag::Byte(-1));
|
||||
assert_parse_err!("256ub", "Failed to parse number: out of range: 256", 5, []);
|
||||
assert_parse_ok!("256ss", NbtTag::Short(256));
|
||||
assert_parse_ok!("256 s s", NbtTag::Short(256));
|
||||
|
||||
assert_parse_err!(
|
||||
"3_000_000_000",
|
||||
"Expected literal .",
|
||||
13,
|
||||
[
|
||||
".", "b", "B", "d", "D", "e", "E", "f", "F", "i", "I", "l", "L", "s", "S", "u", "U"
|
||||
]
|
||||
);
|
||||
|
||||
assert_parse_ok!("+3_000_000_000uI", NbtTag::Int(-1_294_967_296));
|
||||
assert_parse_ok!("+3_000_000_000s L", NbtTag::Long(3_000_000_000));
|
||||
assert_parse_ok!("-3_000_000_000 sL", NbtTag::Long(-3_000_000_000));
|
||||
|
||||
assert_parse_err!(
|
||||
"-3_000_000_000i",
|
||||
"Failed to parse number: For input string: \"-3000000000\"",
|
||||
15,
|
||||
[]
|
||||
);
|
||||
assert_parse_err!("-3_000_000_000UI", "Expected a non-negative number", 16, []);
|
||||
|
||||
assert_parse_err!(
|
||||
"00",
|
||||
"Expected literal .",
|
||||
2,
|
||||
[
|
||||
"(", ".", "bool", "d", "D", "e", "E", "f", "F", "false", "true", "uuid"
|
||||
]
|
||||
);
|
||||
assert_parse_err!(
|
||||
"0x",
|
||||
"Expected a hexadecimal number",
|
||||
2,
|
||||
BUILT_IN_LIKE_SUGGESTIONS
|
||||
);
|
||||
|
||||
assert_parse_ok!("0b", NbtTag::Byte(0));
|
||||
assert_parse_ok!("0b10101", NbtTag::Int(21));
|
||||
|
||||
assert_parse_ok!("0X111", NbtTag::Int(273));
|
||||
assert_parse_err!("0x_111", "Expected literal (", 6, BUILT_IN_LIKE_SUGGESTIONS);
|
||||
assert_parse_err!(
|
||||
"0xAbCdEfs",
|
||||
"Expected literal b|B",
|
||||
9,
|
||||
["b", "B", "i", "I", "l", "L", "s", "S"]
|
||||
);
|
||||
assert_parse_ok_but_trailing!("0xABCDEFG", "G");
|
||||
assert_parse_ok!("0xABCDUS", NbtTag::Short(-21555));
|
||||
|
||||
// Should not parse as byte of 0xAB
|
||||
assert_parse_ok!("0xABB", NbtTag::Int(2747));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floats() {
|
||||
assert_parse_ok!("0.", NbtTag::Double(0.0));
|
||||
assert_parse_ok!("0.f", NbtTag::Float(0.0));
|
||||
assert_parse_ok!("0.D", NbtTag::Double(0.0));
|
||||
|
||||
assert_parse_ok!(".0", NbtTag::Double(0.0));
|
||||
assert_parse_ok!(".0F", NbtTag::Float(0.0));
|
||||
assert_parse_ok!(".0d", NbtTag::Double(0.0));
|
||||
|
||||
assert_parse_ok!("1.024", NbtTag::Double(1.024));
|
||||
assert_parse_err!("1_.024", "Expected literal (", 6, BUILT_IN_LIKE_SUGGESTIONS);
|
||||
assert_parse_ok_but_trailing!("1._024", "_024");
|
||||
assert_parse_ok!("1.0_2_4", NbtTag::Double(1.024));
|
||||
|
||||
assert_parse_ok!("1e1", NbtTag::Double(10.0));
|
||||
assert_parse_ok!("2e+2", NbtTag::Double(200.0));
|
||||
assert_parse_ok!("4e-2", NbtTag::Double(0.04));
|
||||
|
||||
assert_parse_ok!("4e-2", NbtTag::Double(0.04));
|
||||
assert_parse_ok!("0E100_000_000", NbtTag::Double(0.0));
|
||||
assert_parse_ok_but_trailing!("0.1e100_000_000", ".1e100_000_000");
|
||||
assert_parse_ok!("0.1e-100_000_000", NbtTag::Double(0.0));
|
||||
|
||||
assert_parse_ok!("1e38f", NbtTag::Float(1e38));
|
||||
assert_parse_ok_but_trailing!("1e39f", "e39f");
|
||||
assert_parse_ok!("1e39", NbtTag::Double(1e39));
|
||||
assert_parse_ok!("0.001e41f", NbtTag::Float(1e38));
|
||||
assert_parse_ok_but_trailing!("0.01E41f", ".01E41f");
|
||||
|
||||
assert_parse_ok!("1.28E308", NbtTag::Double(1.28E308));
|
||||
assert_parse_ok_but_trailing!("1.8e308", ".8e308");
|
||||
|
||||
assert_parse_ok_but_trailing!("1.E", "E");
|
||||
|
||||
assert_parse_ok!("2000f", NbtTag::Float(2000.0));
|
||||
assert_parse_ok!("70d", NbtTag::Double(70.0));
|
||||
assert_parse_ok!("03f", NbtTag::Float(3.0));
|
||||
assert_parse_ok!("03.70", NbtTag::Double(3.7));
|
||||
assert_parse_ok!("+1e-1", NbtTag::Double(0.1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_string_literals() {
|
||||
assert_parse_ok!("''", NbtTag::String("".into()));
|
||||
assert_parse_ok!("\"\"", NbtTag::String("".into()));
|
||||
|
||||
assert_parse_ok!("\"'hello'\"", NbtTag::String("'hello'".into()));
|
||||
assert_parse_ok!("'\"hello\"'", NbtTag::String("\"hello\"".into()));
|
||||
assert_parse_ok!("'\\\\'", NbtTag::String("\\".into()));
|
||||
assert_parse_ok_but_trailing!("'\"'\"", "\"");
|
||||
|
||||
assert_parse_err!("'\\'", "Invalid string contents", 3, ["\"", "'", "\\"]);
|
||||
|
||||
assert_parse_ok!("'\\b'", NbtTag::String("\u{8}".into()));
|
||||
assert_parse_ok!("'hello\\sword'", NbtTag::String("hello word".into()));
|
||||
assert_parse_ok!("'hello\\tword\n'", NbtTag::String("hello\tword\n".into()));
|
||||
assert_parse_ok!("'\\f\\r'", NbtTag::String("\u{c}\r".into()));
|
||||
|
||||
assert_parse_ok!("'hello \\x65!'", NbtTag::String("hello e!".into()));
|
||||
assert_parse_ok!(
|
||||
"'\\x53\\x65\\u0063\\U00000072\\x65\\x74\\x21'",
|
||||
NbtTag::String("Secret!".into())
|
||||
);
|
||||
|
||||
assert_parse_err!(
|
||||
"'\\U1234567'",
|
||||
"Expected a character literal of length 8",
|
||||
3,
|
||||
[]
|
||||
);
|
||||
|
||||
assert_parse_ok!(
|
||||
"'\\uD83C\\uDF83 or \\U0001F383'",
|
||||
NbtTag::String("🎃 or 🎃".into())
|
||||
);
|
||||
|
||||
// TODO: make tests for when \N is implemented
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unquoted_string_literals() {
|
||||
assert_parse_ok!("abc", NbtTag::String("abc".into()));
|
||||
assert_parse_ok!(
|
||||
"abc-def_ghi+jkl.mno",
|
||||
NbtTag::String("abc-def_ghi+jkl.mno".into())
|
||||
);
|
||||
assert_parse_ok!("_1234", NbtTag::String("_1234".into()));
|
||||
assert_parse_ok!("x+1", NbtTag::String("x+1".into()));
|
||||
assert_parse_ok_but_trailing!("x*1", "*1");
|
||||
|
||||
assert_parse_ok!("true", NbtTag::Byte(1));
|
||||
assert_parse_ok!("false", NbtTag::Byte(0));
|
||||
assert_parse_ok!("maybe", NbtTag::String("maybe".into()));
|
||||
assert_parse_ok!("bool", NbtTag::String("bool".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operations() {
|
||||
assert_parse_ok!("bool( true)", NbtTag::Byte(1));
|
||||
assert_parse_ok!("bool (false )", NbtTag::Byte(0));
|
||||
|
||||
assert_parse_ok!("bool(0)", NbtTag::Byte(0));
|
||||
assert_parse_ok!("bool( 1 )", NbtTag::Byte(1));
|
||||
assert_parse_ok!("bool (2.5 )", NbtTag::Byte(1));
|
||||
assert_parse_ok!("bool ( -4.3412e+12 )", NbtTag::Byte(1));
|
||||
|
||||
assert_parse_err!("bool(", "Expected a valid unquoted string", 5, [")"]);
|
||||
assert_parse_err!("bool()", "No such operation: bool/0", 6, []);
|
||||
assert_parse_err!("bool(1, 2)", "No such operation: bool/2", 10, []);
|
||||
assert_parse_err!(
|
||||
"bool (1,2,3",
|
||||
"Expected literal .",
|
||||
11,
|
||||
[
|
||||
")", ",", ".", "b", "B", "d", "D", "e", "E", "f", "F", "i", "I", "l", "L", "s", "S",
|
||||
"u", "U"
|
||||
]
|
||||
);
|
||||
|
||||
assert_parse_ok!(
|
||||
"uuid('3d569d3a-93ef-44a0-9f1c-f69db9d37a56')",
|
||||
NbtTag::IntArray(vec![1029086522, -1813035872, -1625491811, -1177322922])
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"uuid(ad569d3a-93ef-44a0-9f1c-f69db9d37a56)",
|
||||
NbtTag::IntArray(vec![-1386832582, -1813035872, -1625491811, -1177322922])
|
||||
);
|
||||
assert_parse_err!(
|
||||
"uuid(3d53a-f40-c-f69db9d37a56)",
|
||||
"Expected literal ,",
|
||||
7,
|
||||
[]
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"uuid(fffffffffffffff-0-0-0-0)",
|
||||
NbtTag::IntArray(vec![-1, 0, 0, 0])
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"uuid(AaaAaaAaaAaaAaA-BBbBbbBbBbbbBB-c-D-e)",
|
||||
NbtTag::IntArray(vec![-1431655766, -1145372660, 851968, 14])
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"uuid(a1-+2-+3-+4-+5)",
|
||||
NbtTag::IntArray(vec![161, 131075, 262144, 5])
|
||||
);
|
||||
assert_parse_err!(
|
||||
"uuid(x)",
|
||||
"Expected a string representing a valid UUID",
|
||||
7,
|
||||
[]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps() {
|
||||
assert_parse_ok!(
|
||||
"{x:5}",
|
||||
nbt_compound_tag! {
|
||||
"x": NbtTag::Int(5)
|
||||
}
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"{ a:1b,B :2uS , c:3L }",
|
||||
nbt_compound_tag! {
|
||||
"a": NbtTag::Byte(1),
|
||||
"B": NbtTag::Short(2),
|
||||
"c": NbtTag::Long(3)
|
||||
}
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"{ a:1b, \"a\":2b, 'a':\"hi\" }",
|
||||
nbt_compound_tag! {
|
||||
"a": NbtTag::String("hi".into())
|
||||
}
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"{ elem: 'this', next: { elem: 'is', next: { elem: 'a', next: { elem: 'linked', next: 'list' } } } }",
|
||||
nbt_compound_tag! {
|
||||
"elem": NbtTag::String("this".into()),
|
||||
"next": nbt_compound_tag! {
|
||||
"elem": NbtTag::String("is".into()),
|
||||
"next": nbt_compound_tag! {
|
||||
"elem": NbtTag::String("a".into()),
|
||||
"next": nbt_compound_tag! {
|
||||
"elem": NbtTag::String("linked".into()),
|
||||
"next": NbtTag::String("list".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
assert_parse_err!("{'x': 5f", "Expected literal ,", 8, [",", "}"]);
|
||||
assert_parse_err!(
|
||||
"{text:\"cool\",\"color:dark_red}",
|
||||
"Invalid string contents",
|
||||
29,
|
||||
["\"", "'", "\\"]
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"{9._+._+foo:1}",
|
||||
nbt_compound_tag! {
|
||||
"9._+._+foo": NbtTag::Int(1)
|
||||
}
|
||||
);
|
||||
assert_parse_err!("{9._+._+=foo:1}", "Expected literal :", 8, []);
|
||||
|
||||
assert_parse_err!("{\"a\":b", "Expected literal (", 6, ["(", ",", "}"]);
|
||||
assert_parse_err!(
|
||||
"{\"a\":25",
|
||||
"Expected literal .",
|
||||
7,
|
||||
[
|
||||
",", ".", "b", "B", "d", "D", "e", "E", "f", "F", "i", "I", "l", "L", "s", "S", "u",
|
||||
"U", "}"
|
||||
]
|
||||
);
|
||||
assert_parse_err!("{\"a\":25,", "Expected literal \"", 8, ["\"", "'", "}"]);
|
||||
assert_parse_err!("{,}", "Expected literal \"", 1, []);
|
||||
assert_parse_err!("{{}}", "Expected literal \"", 1, []);
|
||||
|
||||
assert_parse_ok!(
|
||||
"{1:1}",
|
||||
nbt_compound_tag! {
|
||||
"1": NbtTag::Int(1)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists() {
|
||||
assert_parse_ok!("[ ]", NbtTag::List(Vec::new()));
|
||||
assert_parse_ok!(
|
||||
"[5, _]",
|
||||
NbtTag::List(vec![NbtTag::Int(5), NbtTag::String("_".into())])
|
||||
);
|
||||
assert_parse_ok!(
|
||||
"[a, [true, c], [4s, uuid(f-0-0-0-0), f, [[], 7f, [\"\\n\", [200Ub, {x: 1e1}]]]]]",
|
||||
NbtTag::List(vec![
|
||||
NbtTag::String("a".into()),
|
||||
NbtTag::List(vec![NbtTag::Byte(1), NbtTag::String("c".into())]),
|
||||
NbtTag::List(vec![
|
||||
NbtTag::Short(4),
|
||||
NbtTag::IntArray(vec![15, 0, 0, 0]),
|
||||
NbtTag::String("f".into()),
|
||||
NbtTag::List(vec![
|
||||
NbtTag::List(Vec::new()),
|
||||
NbtTag::Float(7.0),
|
||||
NbtTag::List(vec![
|
||||
NbtTag::String("\n".into()),
|
||||
NbtTag::List(vec![
|
||||
NbtTag::Byte(-56),
|
||||
nbt_compound_tag! {
|
||||
"x": NbtTag::Double(10.0)
|
||||
}
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
])
|
||||
);
|
||||
|
||||
assert_parse_err!("[1;1]", "Expected literal .", 2, []);
|
||||
|
||||
assert_parse_err!("[{]}", "Expected literal \"", 2, []);
|
||||
assert_parse_err!("{[}]", "Expected literal \"", 1, []);
|
||||
assert_parse_err!("[,]", "Expected literal B", 1, []);
|
||||
assert_parse_err!("[Z;9]", "Expected literal (", 2, []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrays() {
|
||||
assert_parse_ok!("[B;]", NbtTag::ByteArray(vec![].into()));
|
||||
assert_parse_ok!("[I ;1 ,2 , 3,]", NbtTag::IntArray(vec![1, 2, 3]));
|
||||
assert_parse_ok!("[L;1 ,2 , 3, 4]", NbtTag::LongArray(vec![1, 2, 3, 4]));
|
||||
|
||||
assert_parse_err!("[B;1i]", "Invalid array element type", 6, []);
|
||||
assert_parse_err!("[I;1L]", "Invalid array element type", 6, []);
|
||||
assert_parse_err!(
|
||||
"[B;128]",
|
||||
"Failed to parse number: Value out of range. Value:\"128\" Radix:10",
|
||||
7,
|
||||
[]
|
||||
);
|
||||
assert_parse_err!(
|
||||
"[B;3000000000]",
|
||||
"Failed to parse number: For input string: \"3000000000\"",
|
||||
14,
|
||||
[]
|
||||
);
|
||||
assert_parse_err!(
|
||||
"[I;3000000000]",
|
||||
"Failed to parse number: For input string: \"3000000000\"",
|
||||
14,
|
||||
[]
|
||||
);
|
||||
assert_parse_err!("[I; 1.0]", "Expected literal u|U", 5, []);
|
||||
assert_parse_err!("[I;{}]", "Expected literal +", 3, []);
|
||||
assert_parse_err!("[i;4]", "Expected literal (", 2, []);
|
||||
|
||||
assert_parse_ok!("[B; 0b11111111]", NbtTag::ByteArray(vec![-1].into()));
|
||||
assert_parse_ok!("[L; 0xFFFFFFFFFFFFFFFF]", NbtTag::LongArray(vec![-1]));
|
||||
assert_parse_err!(
|
||||
"[L; 0xFFFFFFFFFFFFFFFFF]",
|
||||
"Failed to parse number: String value FFFFFFFFFFFFFFFFF exceeds range of unsigned long.",
|
||||
24,
|
||||
[]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::argument_types::entity_anchor::EntityAnchor;
|
||||
use crate::errors::command_syntax_error::CommandSyntaxError;
|
||||
|
||||
pub trait ReturnValueCallable: Send + Sync {
|
||||
fn call(&self, value: ReturnValue);
|
||||
}
|
||||
|
||||
pub type ReturnValueCallback = Arc<dyn ReturnValueCallable>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ResultValueTaker(pub Vec<ReturnValueCallback>);
|
||||
|
||||
impl ResultValueTaker {
|
||||
#[must_use]
|
||||
pub fn merge(taker_1: &Self, taker_2: &Self) -> Self {
|
||||
let mut takers = Vec::with_capacity(taker_1.0.len() + taker_2.0.len());
|
||||
for taker in &taker_1.0 {
|
||||
takers.push(taker.clone());
|
||||
}
|
||||
for taker in &taker_2.0 {
|
||||
takers.push(taker.clone());
|
||||
}
|
||||
Self(takers)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self(Vec::new())
|
||||
}
|
||||
|
||||
pub fn call(&self, return_value: ReturnValue) {
|
||||
for callback in &self.0 {
|
||||
callback.call(return_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub enum ReturnValue {
|
||||
Success(i32),
|
||||
Failure,
|
||||
}
|
||||
|
||||
impl ReturnValue {
|
||||
#[must_use]
|
||||
pub const fn success_value(self) -> bool {
|
||||
match self {
|
||||
Self::Success(_) => true,
|
||||
Self::Failure => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn result_value(self) -> i32 {
|
||||
match self {
|
||||
Self::Success(value) => value,
|
||||
Self::Failure => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstract command source trait for command dispatch and execution.
|
||||
pub trait CommandSource: Clone + Send + Sync + 'static {
|
||||
/// Sends a feedback message to the command sender.
|
||||
fn send_message(&self, message: TextComponent);
|
||||
|
||||
/// Sends an error message to the command sender.
|
||||
fn send_error(&self, error: TextComponent) {
|
||||
self.send_message(error);
|
||||
}
|
||||
|
||||
/// Invokes callbacks for the command's return value.
|
||||
fn call_result(&self, _result: ReturnValue) {}
|
||||
|
||||
/// Checks if this command source has the specified permission.
|
||||
fn has_permission(&self, _permission: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns the position of this command source in the world.
|
||||
fn position(&self) -> Vector3<f64> {
|
||||
Vector3::default()
|
||||
}
|
||||
|
||||
/// Returns the rotation (pitch, yaw) of this command source.
|
||||
fn rotation(&self) -> Vector2<f32> {
|
||||
Vector2::default()
|
||||
}
|
||||
|
||||
/// Checks if the block at the given position is loaded.
|
||||
fn check_block_loaded(&self, _pos: &BlockPos) -> Result<(), CommandSyntaxError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the anchor position for the given entity anchor.
|
||||
fn anchor_position(&self, _anchor: EntityAnchor) -> Vector3<f64> {
|
||||
self.position()
|
||||
}
|
||||
|
||||
/// Returns the current entity anchor of this command source.
|
||||
fn entity_anchor(&self) -> EntityAnchor {
|
||||
EntityAnchor::Feet
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DummySource {
|
||||
pub position: Vector3<f64>,
|
||||
pub rotation: Vector2<f32>,
|
||||
pub entity_anchor: EntityAnchor,
|
||||
pub command_result_taker: ResultValueTaker,
|
||||
}
|
||||
|
||||
impl DummySource {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn dummy() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandSource for DummySource {
|
||||
fn send_message(&self, _message: TextComponent) {}
|
||||
fn send_error(&self, _error: TextComponent) {}
|
||||
fn position(&self) -> Vector3<f64> {
|
||||
self.position
|
||||
}
|
||||
fn rotation(&self) -> Vector2<f32> {
|
||||
self.rotation
|
||||
}
|
||||
fn entity_anchor(&self) -> EntityAnchor {
|
||||
self.entity_anchor
|
||||
}
|
||||
fn call_result(&self, result: ReturnValue) {
|
||||
self.command_result_taker.call(result);
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandSource for () {
|
||||
fn send_message(&self, _message: TextComponent) {}
|
||||
}
|
||||
|
||||
impl<S: CommandSource> CommandSource for Arc<S> {
|
||||
fn send_message(&self, message: TextComponent) {
|
||||
(**self).send_message(message);
|
||||
}
|
||||
|
||||
fn send_error(&self, error: TextComponent) {
|
||||
(**self).send_error(error);
|
||||
}
|
||||
|
||||
fn has_permission(&self, permission: &str) -> bool {
|
||||
(**self).has_permission(permission)
|
||||
}
|
||||
|
||||
fn position(&self) -> Vector3<f64> {
|
||||
(**self).position()
|
||||
}
|
||||
|
||||
fn rotation(&self) -> Vector2<f32> {
|
||||
(**self).rotation()
|
||||
}
|
||||
|
||||
fn entity_anchor(&self) -> EntityAnchor {
|
||||
(**self).entity_anchor()
|
||||
}
|
||||
|
||||
fn anchor_position(&self, anchor: EntityAnchor) -> Vector3<f64> {
|
||||
(**self).anchor_position(anchor)
|
||||
}
|
||||
|
||||
fn call_result(&self, result: ReturnValue) {
|
||||
(**self).call_result(result);
|
||||
}
|
||||
|
||||
fn check_block_loaded(&self, pos: &BlockPos) -> Result<(), CommandSyntaxError> {
|
||||
(**self).check_block_loaded(pos)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
use crate::errors::command_syntax_error::{
|
||||
CommandSyntaxError, CommandSyntaxErrorContext, ContextProvider,
|
||||
};
|
||||
use crate::errors::error_types::{self, CommandErrorType};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::borrow::Cow;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A structure that can read a string character by character for commands.
|
||||
///
|
||||
/// It internally uses a cursor to read them, which is
|
||||
/// very important to determine the location of the cause
|
||||
/// of a syntax error arising from this parser.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct StringReader<'a> {
|
||||
string: Cow<'a, str>,
|
||||
byte_cursor: usize,
|
||||
}
|
||||
|
||||
const SYNTAX_ESCAPE: char = '\\';
|
||||
const SYNTAX_SINGLE_QUOTE: char = '\'';
|
||||
const SYNTAX_DOUBLE_QUOTE: char = '"';
|
||||
|
||||
impl<'a> StringReader<'a> {
|
||||
/// Returns a new instance of a [`StringReader`]
|
||||
/// from a borrowed or owned string, with the cursor
|
||||
/// initially being set to the start.
|
||||
pub fn new<S>(string: S) -> Self
|
||||
where
|
||||
S: Into<Cow<'a, str>>,
|
||||
{
|
||||
Self {
|
||||
string: string.into(),
|
||||
byte_cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reference to the internal string used for parsing.
|
||||
#[must_use]
|
||||
pub fn string(&self) -> &str {
|
||||
&self.string
|
||||
}
|
||||
|
||||
/// Returns the current byte position of the internal cursor.
|
||||
#[must_use]
|
||||
pub const fn cursor(&self) -> usize {
|
||||
self.byte_cursor
|
||||
}
|
||||
|
||||
/// Sets the current byte position of the internal cursor.
|
||||
pub const fn set_cursor(&mut self, cursor: usize) {
|
||||
self.byte_cursor = cursor;
|
||||
}
|
||||
|
||||
/// Gets the total byte length of the internal string.
|
||||
#[must_use]
|
||||
pub fn total_length(&self) -> usize {
|
||||
self.string.len()
|
||||
}
|
||||
|
||||
/// Gets the remaining, unread byte length of the internal string.
|
||||
#[must_use]
|
||||
pub fn remaining_length(&self) -> usize {
|
||||
self.string.len() - self.byte_cursor
|
||||
}
|
||||
|
||||
/// Gets the read part of the internal string.
|
||||
#[must_use]
|
||||
pub fn read_part(&self) -> &str {
|
||||
&self.string[0..self.byte_cursor]
|
||||
}
|
||||
|
||||
/// Gets the remaining, unread part of the internal string.
|
||||
#[must_use]
|
||||
pub fn remaining_part(&self) -> &str {
|
||||
&self.string[self.byte_cursor..]
|
||||
}
|
||||
|
||||
/// Returns whether the reader is able to read `length` more bytes
|
||||
/// without going out of bounds.
|
||||
#[must_use]
|
||||
pub fn can_read_bytes(&self, length: usize) -> bool {
|
||||
self.byte_cursor + length <= self.string.len()
|
||||
}
|
||||
|
||||
/// Returns whether the reader is able to read 1 more byte
|
||||
/// without going out of bounds.
|
||||
#[must_use]
|
||||
pub fn can_read_byte(&self) -> bool {
|
||||
self.can_read_bytes(1)
|
||||
}
|
||||
|
||||
/// Returns whether the reader is able to read `length` more [`char`]s
|
||||
/// without going out of bounds.
|
||||
#[must_use]
|
||||
pub fn can_read_chars(&self, length: usize) -> bool {
|
||||
self.string[self.byte_cursor..].chars().take(length).count() == length
|
||||
}
|
||||
|
||||
/// Returns whether the reader is able to read 1 more [`char`]
|
||||
/// without going out of bounds.
|
||||
#[must_use]
|
||||
pub fn can_read_char(&self) -> bool {
|
||||
self.can_read_chars(1)
|
||||
}
|
||||
|
||||
/// Peeks a byte, where the cursor is at, without advancing.
|
||||
#[must_use]
|
||||
pub fn peek_byte(&self) -> Option<u8> {
|
||||
self.byte_at(self.byte_cursor)
|
||||
}
|
||||
|
||||
/// Fetches a byte, at a specific byte-index.
|
||||
#[must_use]
|
||||
pub fn byte_at(&self, i: usize) -> Option<u8> {
|
||||
self.string.as_bytes().get(i).copied()
|
||||
}
|
||||
|
||||
/// Peeks a [`char`], where the cursor is at, without advancing.
|
||||
#[must_use]
|
||||
pub fn peek(&self) -> Option<char> {
|
||||
self.string[self.byte_cursor..].chars().next()
|
||||
}
|
||||
|
||||
/// Peeks a [`char`], where the cursor is at, with an offset,
|
||||
/// specified in bytes, without advancing.
|
||||
#[must_use]
|
||||
pub fn peek_with_offset(&self, offset: usize) -> Option<char> {
|
||||
if self.byte_cursor + offset > self.string.len() {
|
||||
return None;
|
||||
}
|
||||
self.string[(self.byte_cursor + offset)..].chars().next()
|
||||
}
|
||||
|
||||
/// Reads a [`char`], where the cursor is at, before advancing.
|
||||
#[must_use = "to skip a character use `skip()` instead"]
|
||||
pub fn read(&mut self) -> Option<char> {
|
||||
let c = self.peek()?;
|
||||
self.byte_cursor += c.len_utf8();
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// Skips a [`char`], where the cursor is at.
|
||||
pub fn skip(&mut self) {
|
||||
if let Some(c) = self.peek() {
|
||||
self.byte_cursor += c.len_utf8();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the given [`char`] is allowed in a number.
|
||||
#[must_use]
|
||||
pub const fn is_allowed_in_number(c: char) -> bool {
|
||||
matches!(c, '0'..='9' | '.' | '-')
|
||||
}
|
||||
|
||||
/// Whether the given [`char`] is allowed as the start and the end of a quoted string.
|
||||
#[must_use]
|
||||
pub const fn is_allowed_as_quoted_string_start_end(c: char) -> bool {
|
||||
matches!(c, SYNTAX_SINGLE_QUOTE | SYNTAX_DOUBLE_QUOTE)
|
||||
}
|
||||
|
||||
/// Whether the given [`char`] is allowed in an unquoted string.
|
||||
#[must_use]
|
||||
pub const fn is_allowed_in_unquoted_string(c: char) -> bool {
|
||||
matches!(c, '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '-' | '.' | '+')
|
||||
}
|
||||
|
||||
/// Skips any kind of whitespace until there isn't more of it to skip.
|
||||
pub fn skip_whitespace(&mut self) {
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_whitespace() {
|
||||
self.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a given type `T`.
|
||||
fn read_and_parse<T: FromStr>(
|
||||
&mut self,
|
||||
expected_error_type: &'static CommandErrorType<0>,
|
||||
invalid_error_type: &'static CommandErrorType<1>,
|
||||
) -> Result<T, CommandSyntaxError> {
|
||||
let start = self.byte_cursor;
|
||||
while let Some(c) = self.peek() {
|
||||
if Self::is_allowed_in_number(c) {
|
||||
self.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let result = &self.string[start..self.byte_cursor];
|
||||
if result.is_empty() {
|
||||
return Err(expected_error_type.create(self));
|
||||
}
|
||||
if let Ok(value) = result.parse::<T>() {
|
||||
Ok(value)
|
||||
} else {
|
||||
self.byte_cursor = start;
|
||||
Err(invalid_error_type.create(self, TextComponent::text(result.to_owned())))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a [`bool`], resulting in a [`CommandSyntaxError`] if unsuccessful.
|
||||
pub fn read_bool(&mut self) -> Result<bool, CommandSyntaxError> {
|
||||
let start = self.byte_cursor;
|
||||
let value = self.read_string()?;
|
||||
match value.as_str() {
|
||||
"" => Err(error_types::READER_EXPECTED_BOOL.create(self)),
|
||||
"true" => Ok(true),
|
||||
"false" => Ok(false),
|
||||
_ => {
|
||||
self.byte_cursor = start;
|
||||
Err(error_types::READER_INVALID_BOOL
|
||||
.create(self, TextComponent::text(value.clone())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a [`i32`], resulting in a [`CommandSyntaxError`] if unsuccessful.
|
||||
pub fn read_int(&mut self) -> Result<i32, CommandSyntaxError> {
|
||||
self.read_and_parse(
|
||||
&error_types::READER_EXPECTED_INT,
|
||||
&error_types::READER_INVALID_INT,
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses a [`i64`], resulting in a [`CommandSyntaxError`] if unsuccessful.
|
||||
pub fn read_long(&mut self) -> Result<i64, CommandSyntaxError> {
|
||||
self.read_and_parse(
|
||||
&error_types::READER_EXPECTED_LONG,
|
||||
&error_types::READER_INVALID_LONG,
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses a [`f32`], resulting in a [`CommandSyntaxError`] if unsuccessful.
|
||||
pub fn read_float(&mut self) -> Result<f32, CommandSyntaxError> {
|
||||
self.read_and_parse(
|
||||
&error_types::READER_EXPECTED_FLOAT,
|
||||
&error_types::READER_INVALID_FLOAT,
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses a [`f64`], resulting in a [`CommandSyntaxError`] if unsuccessful.
|
||||
pub fn read_double(&mut self) -> Result<f64, CommandSyntaxError> {
|
||||
self.read_and_parse(
|
||||
&error_types::READER_EXPECTED_DOUBLE,
|
||||
&error_types::READER_INVALID_DOUBLE,
|
||||
)
|
||||
}
|
||||
|
||||
/// Reads an unquoted string (not enclosed in quotes)
|
||||
pub fn read_unquoted_string(&mut self) -> String {
|
||||
let start = self.byte_cursor;
|
||||
while let Some(c) = self.peek() {
|
||||
if Self::is_allowed_in_unquoted_string(c) {
|
||||
self.skip();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.string[start..self.byte_cursor].to_string()
|
||||
}
|
||||
|
||||
/// Reads any string, whether it be quoted or unquoted.
|
||||
pub fn read_string(&mut self) -> Result<String, CommandSyntaxError> {
|
||||
let Some(next) = self.peek() else {
|
||||
return Ok(String::new());
|
||||
};
|
||||
if Self::is_allowed_as_quoted_string_start_end(next) {
|
||||
self.skip();
|
||||
self.read_string_until(next)
|
||||
} else {
|
||||
Ok(self.read_unquoted_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a quoted string (enclosed in quotes)
|
||||
pub fn read_quoted_string(&mut self) -> Result<String, CommandSyntaxError> {
|
||||
let Some(next) = self.peek() else {
|
||||
return Ok(String::new());
|
||||
};
|
||||
if Self::is_allowed_as_quoted_string_start_end(next) {
|
||||
self.skip();
|
||||
self.read_string_until(next)
|
||||
} else {
|
||||
Err(error_types::READER_EXPECTED_START_QUOTE.create(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a string until the given character.
|
||||
pub fn read_string_until(&mut self, terminator: char) -> Result<String, CommandSyntaxError> {
|
||||
let mut result: String = String::new();
|
||||
let mut escaped: bool = false;
|
||||
while let Some(c) = self.peek() {
|
||||
if escaped {
|
||||
if c == terminator || c == SYNTAX_ESCAPE {
|
||||
result.push(c);
|
||||
self.skip();
|
||||
escaped = false;
|
||||
} else {
|
||||
return Err(error_types::READER_INVALID_ESCAPE
|
||||
.create(self, TextComponent::text(c.to_string())));
|
||||
}
|
||||
} else {
|
||||
self.skip();
|
||||
if c == SYNTAX_ESCAPE {
|
||||
escaped = true;
|
||||
} else if c == terminator {
|
||||
return Ok(result);
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error_types::READER_EXPECTED_END_QUOTE.create(self))
|
||||
}
|
||||
|
||||
/// Expects to consume a specific [`char`], or return an [`Err`].
|
||||
pub fn expect(&mut self, c: char) -> Result<(), CommandSyntaxError> {
|
||||
if self.peek() == Some(c) {
|
||||
self.skip();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(error_types::READER_EXPECTED_SYMBOL
|
||||
.create(self, TextComponent::text(c.to_string())))
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps skipping characters in the reader until a space or the end of the string is encountered.
|
||||
pub fn read_until_space(&mut self) {
|
||||
while !matches!(self.peek(), None | Some(' ')) {
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this reader into a `'static` form, which
|
||||
/// is useful for snapshotting the reader.
|
||||
#[must_use]
|
||||
pub fn into_owned(self) -> StringReader<'static> {
|
||||
StringReader {
|
||||
string: Cow::Owned(self.string.into_owned()),
|
||||
byte_cursor: self.byte_cursor,
|
||||
}
|
||||
}
|
||||
|
||||
/// Clones this reader into a `'static` form, which
|
||||
/// is useful for snapshotting the reader.
|
||||
#[must_use]
|
||||
pub fn clone_into_owned(&self) -> StringReader<'static> {
|
||||
StringReader {
|
||||
string: Cow::Owned(self.string.to_string()),
|
||||
byte_cursor: self.byte_cursor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextProvider for StringReader<'_> {
|
||||
fn context(&self) -> CommandSyntaxErrorContext {
|
||||
CommandSyntaxErrorContext {
|
||||
input: self.string.to_string(),
|
||||
cursor: self.byte_cursor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{errors::error_types, string_reader::StringReader};
|
||||
|
||||
#[test]
|
||||
fn non_parsing_methods() {
|
||||
let mut reader = StringReader::new("hello 🎃! ");
|
||||
assert_eq!(reader.read(), Some('h'));
|
||||
|
||||
assert_eq!(reader.peek(), Some('e'));
|
||||
assert_eq!(reader.read(), Some('e'));
|
||||
|
||||
assert!(reader.can_read_char());
|
||||
assert!(reader.can_read_chars(7));
|
||||
assert!(!reader.can_read_chars(8));
|
||||
|
||||
reader.expect('l').expect("Expected 'l'");
|
||||
reader.skip();
|
||||
reader.expect('o').expect("Expected 'o'");
|
||||
|
||||
// Note: 🎃 carries 4 bytes in UTF-8
|
||||
assert!(reader.can_read_bytes(6));
|
||||
assert_eq!(reader.remaining_length(), 7);
|
||||
assert!(!reader.can_read_bytes(8));
|
||||
|
||||
assert_eq!(reader.read_part(), "hello");
|
||||
reader.set_cursor(6);
|
||||
assert_eq!(reader.remaining_part(), "🎃! ");
|
||||
assert_eq!(reader.peek_byte(), Some(0xF0));
|
||||
assert_eq!(reader.read(), Some('🎃'));
|
||||
|
||||
reader.skip_whitespace(); // Should be a NO-OP
|
||||
assert_eq!(reader.read(), Some('!'));
|
||||
|
||||
reader.skip_whitespace();
|
||||
assert_ne!(reader.expect(' '), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_types() {
|
||||
let mut reader =
|
||||
StringReader::new("12 34 7890123456 1.233 1.592394582 false'false' faux");
|
||||
assert_eq!(reader.read_int(), Ok(12));
|
||||
reader.skip_whitespace();
|
||||
assert_eq!(reader.read_long(), Ok(34));
|
||||
reader.skip_whitespace();
|
||||
|
||||
assert!(
|
||||
reader
|
||||
.read_int()
|
||||
.unwrap_err()
|
||||
.is(&error_types::READER_INVALID_INT)
|
||||
);
|
||||
reader.skip_whitespace();
|
||||
assert_eq!(reader.read_long(), Ok(7890123456));
|
||||
reader.skip_whitespace();
|
||||
|
||||
assert!((reader.read_float().expect("Expected float") - 1.233f32).abs() < 1e-07);
|
||||
reader.skip_whitespace();
|
||||
|
||||
assert!((reader.read_double().expect("Expected double") - 1.592394582f64).abs() < 1e-15);
|
||||
reader.skip_whitespace();
|
||||
|
||||
assert_eq!(reader.read_bool(), Ok(false));
|
||||
assert_eq!(reader.read_bool(), Ok(false));
|
||||
reader.skip_whitespace();
|
||||
assert_ne!(reader.read_bool(), Ok(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_strings() {
|
||||
let mut reader = StringReader::new("'apple' banana orange \"orange\" 'hello\"");
|
||||
|
||||
assert_eq!(reader.read_quoted_string(), Ok("apple".to_string()));
|
||||
reader.skip_whitespace();
|
||||
assert_eq!(reader.read_unquoted_string(), "banana".to_string());
|
||||
reader.skip_whitespace();
|
||||
|
||||
assert_eq!(reader.read_string(), Ok("orange".to_string()));
|
||||
reader.skip_whitespace();
|
||||
assert_eq!(reader.read_string(), Ok("orange".to_string()));
|
||||
reader.skip_whitespace();
|
||||
|
||||
assert!(
|
||||
reader
|
||||
.read_quoted_string()
|
||||
.unwrap_err()
|
||||
.is(&error_types::READER_EXPECTED_END_QUOTE)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
pub mod provider;
|
||||
pub mod suggestions;
|
||||
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::context::string_range::StringRange;
|
||||
|
||||
/// A structure that describes the text of a suggestion.
|
||||
/// It's actual value can either be a [`String`], or an [`i32`].
|
||||
///
|
||||
/// Use the [`new`] method to create new [`SuggestionText`]s.
|
||||
///
|
||||
/// If you want to use an `i32` for a suggestion's text,
|
||||
/// go with [`SuggestionText::Integer`]. In all other cases,
|
||||
/// go with [`SuggestionText::Text`].
|
||||
///
|
||||
/// # Invariant
|
||||
/// A [`SuggestionText::Text`] **shall not exist** if it can instead
|
||||
/// be fully expressed as a [`SuggestionText::Integer`] (no leading zeros).
|
||||
/// This is important to establish proper ordering.
|
||||
/// ```
|
||||
/// use pumpkin_command::suggestion::SuggestionText;
|
||||
///
|
||||
/// let five_suggestion_1 = SuggestionText::new(5);
|
||||
/// let five_suggestion_2 = SuggestionText::new("5");
|
||||
/// let zero_five_suggestion = SuggestionText::new("05");
|
||||
///
|
||||
/// // `five_suggestion_1` and `five_suggestion_2`
|
||||
/// // are both instances of `SuggestionText::Integer`,
|
||||
/// // as guaranteed by the invariant, both having
|
||||
/// // the same integer `5`.
|
||||
/// assert_eq!(five_suggestion_1, five_suggestion_2);
|
||||
///
|
||||
/// // `zero_five_suggestion` contains a leading zero,
|
||||
/// // and hence does not have an integer representing it
|
||||
/// // fully, so it is an instance of `SuggestionText::Text`.
|
||||
/// assert_ne!(five_suggestion_1, zero_five_suggestion);
|
||||
/// ```
|
||||
/// Violating this invariant is a logic error.
|
||||
///
|
||||
/// [`new`]: SuggestionText::new
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SuggestionText {
|
||||
/// The normal one to use. Stores a [`String`].
|
||||
Text(String),
|
||||
|
||||
/// The one to use for integral suggestions. Stores an [`i32`].
|
||||
/// Note that a cached [`String`] is stored inside this value
|
||||
/// so that [`String`] allocations don't occur when this object is compared.
|
||||
Integer { cached_text: String, value: i32 },
|
||||
}
|
||||
|
||||
impl From<String> for SuggestionText {
|
||||
fn from(text: String) -> Self {
|
||||
if let Ok(integer) = text.parse::<i32>()
|
||||
&& integer.to_string() == text
|
||||
{
|
||||
Self::Integer {
|
||||
cached_text: text,
|
||||
value: integer,
|
||||
}
|
||||
} else {
|
||||
Self::Text(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for SuggestionText {
|
||||
fn from(text: &str) -> Self {
|
||||
text.to_owned().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i32> for SuggestionText {
|
||||
fn from(text: i32) -> Self {
|
||||
Self::Integer {
|
||||
cached_text: text.to_string(),
|
||||
value: text,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SuggestionText {
|
||||
/// Provides the internally cached text: this is important so that
|
||||
/// we don't allocate a new string every time we want to
|
||||
/// compare two [`SuggestionText`]s.
|
||||
#[must_use]
|
||||
pub const fn cached_text(&self) -> &String {
|
||||
match self {
|
||||
Self::Text(text) => text,
|
||||
Self::Integer { cached_text, .. } => cached_text,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new [`SuggestionText`] from a usable value.
|
||||
/// This value can be a `&str`, a [`String`], or an `i32`.
|
||||
pub fn new(value: impl Into<Self>) -> Self {
|
||||
value.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for SuggestionText {}
|
||||
impl PartialEq for SuggestionText {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cached_text() == other.cached_text()
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for SuggestionText {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.cached_text().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// A structure that describes a suggestion
|
||||
/// that may be applied to a string or
|
||||
/// expanded using a command and range.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Suggestion {
|
||||
pub range: StringRange,
|
||||
pub text: SuggestionText,
|
||||
pub tooltip: Option<TextComponent>,
|
||||
}
|
||||
|
||||
impl Suggestion {
|
||||
/// Constructs a [`Suggestion`] from its range and text (which can either be a
|
||||
/// [`String`] or an [`i32`]).
|
||||
#[must_use]
|
||||
pub fn without_tooltip<T>(range: StringRange, text: T) -> Self
|
||||
where
|
||||
T: Into<SuggestionText>,
|
||||
{
|
||||
Self {
|
||||
range,
|
||||
text: text.into(),
|
||||
tooltip: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a [`Suggestion`] from its range, text (which can either be a
|
||||
/// [`String`] or an [`i32`]), and a tooltip component.
|
||||
#[must_use]
|
||||
pub fn with_tooltip<T>(range: StringRange, text: T, tooltip: TextComponent) -> Self
|
||||
where
|
||||
T: Into<SuggestionText>,
|
||||
{
|
||||
Self {
|
||||
range,
|
||||
text: text.into(),
|
||||
tooltip: Some(tooltip),
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a [`Suggestion`] from its range, text (which can either be a
|
||||
/// [`String`] or an [`i32`]), and an [`Option`] of [`TextComponent`].
|
||||
#[must_use]
|
||||
pub fn new<T>(range: StringRange, text: T, tooltip: Option<TextComponent>) -> Self
|
||||
where
|
||||
T: Into<SuggestionText>,
|
||||
{
|
||||
Self {
|
||||
range,
|
||||
text: text.into(),
|
||||
tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the internal [`SuggestionText`] that represents the text of this suggestion,
|
||||
/// but as a String cloned from the cache.
|
||||
#[must_use]
|
||||
pub fn text_as_string(&self) -> String {
|
||||
self.text_as_string_ref().clone()
|
||||
}
|
||||
|
||||
/// Gets the internal [`SuggestionText`] that represents the text of this suggestion,
|
||||
/// but as a reference of a String taken directly from the cache without any cloning.
|
||||
#[must_use]
|
||||
pub const fn text_as_string_ref(&self) -> &String {
|
||||
self.text.cached_text()
|
||||
}
|
||||
|
||||
/// Gets the internal [`SuggestionText`] that represents the text of this suggestion,
|
||||
/// but as a `&str` taken directly from the cache without any cloning.
|
||||
#[must_use]
|
||||
pub const fn text_as_str(&self) -> &str {
|
||||
self.text.cached_text().as_str()
|
||||
}
|
||||
|
||||
/// Applies this [`Suggestion`] into a string,
|
||||
/// returning a new [`String`] with the applied suggestion.
|
||||
#[must_use]
|
||||
pub fn apply(&self, input: &str) -> String {
|
||||
let text_string = self.text_as_string_ref();
|
||||
|
||||
if self.range.start == 0 && self.range.end == input.len() {
|
||||
return text_string.clone();
|
||||
}
|
||||
let mut result: String =
|
||||
String::with_capacity(input.len() - self.range.len() + text_string.len());
|
||||
result.push_str(&input[0..self.range.start]); // usize >= 0
|
||||
result.push_str(text_string);
|
||||
if self.range.end < input.len() {
|
||||
result.push_str(&input[self.range.end..]);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Expands this [`Suggestion`] onto a command with a [`StringRange`],
|
||||
/// returning a new [`Suggestion`].
|
||||
#[must_use]
|
||||
pub fn expand(&self, command: &str, range: StringRange) -> Self {
|
||||
if self.range == range {
|
||||
return Self::new(self.range, self.text.clone(), self.tooltip.clone());
|
||||
}
|
||||
let mut result = String::new();
|
||||
if range.start < self.range.start {
|
||||
result.push_str(&command[range.start..self.range.start]);
|
||||
}
|
||||
result.push_str(&self.text_as_string());
|
||||
if range.end > self.range.end {
|
||||
result.push_str(&command[self.range.end..range.end]);
|
||||
}
|
||||
Self::new(range, result, self.tooltip.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
use crate::{context::string_range::StringRange, suggestion::Suggestion};
|
||||
use std::slice;
|
||||
|
||||
#[test]
|
||||
fn apply_insertion_start() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::at(0), "Pumpkin once said: ");
|
||||
assert_eq!(
|
||||
suggestion.apply("'Server is now running'"),
|
||||
"Pumpkin once said: 'Server is now running'".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_insertion_middle() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::at(6), "Efficient, ");
|
||||
assert_eq!(
|
||||
suggestion.apply("Fast, and User-Friendly"),
|
||||
"Fast, Efficient, and User-Friendly".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_insertion_end() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::at(10), " has stopped");
|
||||
assert_eq!(
|
||||
suggestion.apply("The server"),
|
||||
"The server has stopped".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_replacement_start() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::between(0, 5), "Goodbye");
|
||||
assert_eq!(
|
||||
suggestion.apply("Hello world!"),
|
||||
"Goodbye world!".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_replacement_middle() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::between(6, 11), "melon");
|
||||
assert_eq!(suggestion.apply("Hello world!"), "Hello melon!".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_replacement_end() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::between(13, 23), "fruit.");
|
||||
assert_eq!(
|
||||
suggestion.apply("Pumpkin is a vegetable."),
|
||||
"Pumpkin is a fruit.".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_replacement_everything() {
|
||||
let suggestion =
|
||||
Suggestion::without_tooltip(StringRange::between(0, 36), "This is a phrase.");
|
||||
assert_eq!(
|
||||
suggestion.apply("I'm not related to the other phrase."),
|
||||
"This is a phrase.".to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_unchanged() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::at(1), "oo");
|
||||
assert_eq!(suggestion.expand("f", StringRange::at(1)), suggestion);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_left() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::at(1), "oo");
|
||||
assert_eq!(
|
||||
suggestion.expand("f", StringRange::between(0, 1)),
|
||||
Suggestion::without_tooltip(StringRange::between(0, 1), "foo")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_right() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::at(0), "ba");
|
||||
assert_eq!(
|
||||
suggestion.expand("r", StringRange::between(0, 1)),
|
||||
Suggestion::without_tooltip(StringRange::between(0, 1), "bar")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_both() {
|
||||
let suggestion = Suggestion::without_tooltip(
|
||||
StringRange::at(30),
|
||||
"sheared to make a Carved Pumpkin and can be ",
|
||||
);
|
||||
assert_eq!(
|
||||
suggestion.expand(
|
||||
"A block called Pumpkin can be crafted into its seeds which can be planted",
|
||||
StringRange::between(0, 52)
|
||||
),
|
||||
Suggestion::without_tooltip(
|
||||
StringRange::between(0, 52),
|
||||
"A block called Pumpkin can be sheared to make a Carved Pumpkin and can be crafted into its seeds"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_replacement() {
|
||||
let suggestion = Suggestion::without_tooltip(StringRange::between(6, 11), "everyone");
|
||||
assert_eq!(
|
||||
suggestion.expand("Hello world!", StringRange::between(0, 12)),
|
||||
Suggestion::without_tooltip(StringRange::between(0, 12), "Hello everyone!")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_empty() {
|
||||
let merged = Suggestions::merge("foo b", &[]);
|
||||
assert!(merged.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_single() {
|
||||
let suggestions = Suggestions::new(
|
||||
StringRange::at(5),
|
||||
vec![Suggestion::without_tooltip(StringRange::at(5), "ar")],
|
||||
);
|
||||
let merged = Suggestions::merge("foo b", slice::from_ref(&suggestions));
|
||||
assert_eq!(merged, suggestions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_multiple() {
|
||||
let a = Suggestions::new(
|
||||
StringRange::at(5),
|
||||
vec![
|
||||
Suggestion::without_tooltip(StringRange::at(5), "ar"),
|
||||
Suggestion::without_tooltip(StringRange::at(5), "az"),
|
||||
Suggestion::without_tooltip(StringRange::at(5), "ars"),
|
||||
],
|
||||
);
|
||||
let b = Suggestions::new(
|
||||
StringRange::between(4, 5),
|
||||
vec![
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "foo"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "qux"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "BAR"),
|
||||
],
|
||||
);
|
||||
let merged = Suggestions::merge("foo b", &[a, b]);
|
||||
assert_eq!(
|
||||
&merged.suggestions,
|
||||
&[
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "bar"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "BAR"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "bars"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "baz"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "foo"),
|
||||
Suggestion::without_tooltip(StringRange::between(4, 5), "qux"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_append() {
|
||||
let suggestions = SuggestionsBuilder::new("Hello w", 6)
|
||||
.suggest("world!")
|
||||
.build();
|
||||
|
||||
assert_eq!(
|
||||
suggestions.suggestions,
|
||||
vec![Suggestion::without_tooltip(
|
||||
StringRange::between(6, 7),
|
||||
"world!"
|
||||
)]
|
||||
);
|
||||
assert_eq!(suggestions.range, StringRange::between(6, 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_replace() {
|
||||
let suggestions = SuggestionsBuilder::new("Hello w", 6)
|
||||
.suggest("everyone!")
|
||||
.build();
|
||||
|
||||
assert_eq!(
|
||||
suggestions.suggestions,
|
||||
vec![Suggestion::without_tooltip(
|
||||
StringRange::between(6, 7),
|
||||
"everyone!"
|
||||
)]
|
||||
);
|
||||
assert_eq!(suggestions.range, StringRange::between(6, 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_noop() {
|
||||
let suggestions = SuggestionsBuilder::new("hello", 6).build();
|
||||
|
||||
assert!(suggestions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_multiple() {
|
||||
let suggestions = SuggestionsBuilder::new("Cut a b", 6)
|
||||
.suggest("banana")
|
||||
.suggest("plum")
|
||||
.suggest("tomato")
|
||||
.build();
|
||||
|
||||
assert_eq!(
|
||||
suggestions.suggestions,
|
||||
vec![
|
||||
Suggestion::without_tooltip(StringRange::between(6, 7), "banana"),
|
||||
Suggestion::without_tooltip(StringRange::between(6, 7), "plum"),
|
||||
Suggestion::without_tooltip(StringRange::between(6, 7), "tomato")
|
||||
]
|
||||
);
|
||||
assert_eq!(suggestions.range, StringRange::between(6, 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remaining_past_end() {
|
||||
let builder = SuggestionsBuilder::new("ab", 10);
|
||||
assert_eq!(builder.remaining(), "");
|
||||
assert_eq!(builder.remaining_lowercase(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort() {
|
||||
let suggestions = SuggestionsBuilder::new("A random thing to say is foobar", 25)
|
||||
.suggest("1")
|
||||
.suggest(9)
|
||||
.suggest("4")
|
||||
.suggest(6)
|
||||
.suggest("05")
|
||||
.suggest(533)
|
||||
.suggest("x8")
|
||||
.suggest("a")
|
||||
.suggest("x")
|
||||
.suggest("6x")
|
||||
.build();
|
||||
|
||||
let internal_sorted_repr: Vec<String> = suggestions
|
||||
.suggestions
|
||||
.into_iter()
|
||||
.map(|suggestion| suggestion.text_as_string())
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
internal_sorted_repr,
|
||||
vec!["05", "1", "4", "6", "6x", "9", "533", "a", "x", "x8"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use crate::context::command_context::CommandContext;
|
||||
use crate::source::{CommandSource, DummySource};
|
||||
use crate::suggestion::suggestions::{Suggestions, SuggestionsBuilder};
|
||||
|
||||
/// The [`Suggestions`] given by a [`SuggestionProvider`].
|
||||
pub type SuggestionProviderResult = Suggestions;
|
||||
|
||||
/// A trait allowing an object to provide suggestions using a
|
||||
/// [`CommandContext`] and [`SuggestionsBuilder`].
|
||||
pub trait SuggestionProvider<S: CommandSource = DummySource>: Send + Sync {
|
||||
/// Uses a [`CommandContext`] and [`SuggestionsBuilder`] to suggest.
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `context`: The context to use for building the suggestions.
|
||||
/// - `builder`: The builder to consume for the suggestions.
|
||||
///
|
||||
/// # Returns
|
||||
/// The [`Suggestions`] representing the suggested items.
|
||||
fn suggest(
|
||||
&self,
|
||||
context: &CommandContext<S>,
|
||||
builder: SuggestionsBuilder,
|
||||
) -> SuggestionProviderResult;
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
use crate::context::string_range::StringRange;
|
||||
use crate::suggestion::{Suggestion, SuggestionText};
|
||||
use pumpkin_util::text::TextComponent;
|
||||
use std::borrow::Borrow;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Represents a builder of [`Suggestion`]s.
|
||||
pub struct SuggestionsBuilder {
|
||||
/// Represents the starting position of the [`SuggestionsBuilder`]
|
||||
/// from the start of the input string.
|
||||
pub start: usize,
|
||||
|
||||
/// Represents the input of the [`SuggestionsBuilder`].
|
||||
pub input: String,
|
||||
|
||||
/// Represents the lowercase version of the input of the [`SuggestionsBuilder`].
|
||||
pub input_lowercase: String,
|
||||
|
||||
/// The eventual result of this [`SuggestionsBuilder`].
|
||||
pub result: Vec<Suggestion>,
|
||||
}
|
||||
|
||||
impl SuggestionsBuilder {
|
||||
/// Constructs a new [`SuggestionsBuilder`] from the given
|
||||
/// input string and a starting position relative to it.
|
||||
#[must_use]
|
||||
pub fn new(input: &str, start: usize) -> Self {
|
||||
Self {
|
||||
input: input.to_string(),
|
||||
input_lowercase: input.to_lowercase(),
|
||||
start,
|
||||
result: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the remaining substring of the underlying input string.
|
||||
#[must_use]
|
||||
pub fn remaining(&self) -> &str {
|
||||
&self.input[self.start.min(self.input.len())..]
|
||||
}
|
||||
|
||||
/// Gets the remaining substring of the underlying lowercased input string.
|
||||
#[must_use]
|
||||
pub fn remaining_lowercase(&self) -> &str {
|
||||
&self.input_lowercase[self.start.min(self.input_lowercase.len())..]
|
||||
}
|
||||
|
||||
/// Builds the [`Suggestions`] object, consuming itself in the process.
|
||||
#[must_use]
|
||||
pub fn build(self) -> Suggestions {
|
||||
Suggestions::create(&self.input, self.result)
|
||||
}
|
||||
|
||||
/// Adds a suggestion without a tooltip to this builder.
|
||||
#[must_use]
|
||||
pub fn suggest<T>(mut self, text: T) -> Self
|
||||
where
|
||||
T: Into<SuggestionText>,
|
||||
{
|
||||
let text = text.into();
|
||||
if text.cached_text() != self.remaining() {
|
||||
self.result.push(Suggestion::without_tooltip(
|
||||
StringRange::between(self.start, self.input.len()),
|
||||
text,
|
||||
));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a suggestion with a tooltip to this builder.
|
||||
#[must_use]
|
||||
pub fn suggest_with_tooltip<T>(mut self, text: T, tooltip: TextComponent) -> Self
|
||||
where
|
||||
T: Into<SuggestionText>,
|
||||
{
|
||||
let text = text.into();
|
||||
if text.cached_text() != self.remaining() {
|
||||
self.result.push(Suggestion::with_tooltip(
|
||||
StringRange::between(self.start, self.input.len()),
|
||||
text,
|
||||
tooltip,
|
||||
));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds all suggestions from another [`SuggestionsBuilder`] to this one.
|
||||
#[must_use]
|
||||
pub fn append(mut self, other: Self) -> Self {
|
||||
for suggestion in other.result {
|
||||
self.result.push(suggestion);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Creates another [`SuggestionsBuilder`] from this one
|
||||
/// by copying the input and taking the starting position.
|
||||
#[must_use]
|
||||
pub fn create_offset(&self, start: usize) -> Self {
|
||||
Self {
|
||||
input: self.input.clone(),
|
||||
input_lowercase: self.input_lowercase.clone(),
|
||||
start,
|
||||
result: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes only the values that satisfy the current builder prefix, and
|
||||
/// suggests them. For this function to work currently, **all values provided
|
||||
/// must be in lowercase**.
|
||||
///
|
||||
/// Example:
|
||||
/// - If the builder has `b` and the values are `acacia_boat`, `blue`, and `stick`, only the first two will get counted,
|
||||
/// as `boat` and `blue` start with the letter `b`.
|
||||
/// - If the builder has `bl` instead, only `blue` will get counted.
|
||||
#[must_use]
|
||||
pub fn filter_and_suggest_lowercase(mut self, values: Vec<String>) -> Self {
|
||||
for value in values {
|
||||
if Self::matches_substr(self.remaining_lowercase(), &value) {
|
||||
self = self.suggest(value);
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Takes only the values that satisfy the current builder prefix, and
|
||||
/// suggests them.
|
||||
///
|
||||
/// Example:
|
||||
/// - If the builder has `b` and the values are `acacia_boat`, `blue`, and `stick`, only the first two will get counted,
|
||||
/// as `boat` and `blue` start with the letter `b`.
|
||||
/// - If the builder has `bl` instead, only `blue` will get counted.
|
||||
#[must_use]
|
||||
pub fn filter_and_suggest(mut self, values: &[&str]) -> Self {
|
||||
for value in values {
|
||||
if Self::matches_substr(self.remaining_lowercase(), &value.to_lowercase()) {
|
||||
self = self.suggest(value.to_string());
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Takes the value only if it satisfies the current builder prefix, and
|
||||
/// suggests them.
|
||||
#[must_use]
|
||||
pub fn filter_and_suggest_one(mut self, value: impl Into<SuggestionText>) -> Self {
|
||||
let value = value.into();
|
||||
if Self::matches_substr(
|
||||
self.remaining_lowercase(),
|
||||
&value.cached_text().to_lowercase(),
|
||||
) {
|
||||
self = self.suggest(value);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Takes only the values that satisfy the current builder prefix, and
|
||||
/// suggests them.
|
||||
///
|
||||
/// Example:
|
||||
/// - If the builder has `b` and the values are `acacia_boat`, `blue`, and `stick`, only the first two will get counted,
|
||||
/// as `boat` and `blue` start with the letter `b`.
|
||||
/// - If the builder has `bl` instead, only `blue` will get counted.
|
||||
#[must_use]
|
||||
pub fn filter_and_suggest_iter(
|
||||
mut self,
|
||||
values: impl IntoIterator<Item = impl Into<SuggestionText>>,
|
||||
) -> Self {
|
||||
for value in values {
|
||||
let value = value.into();
|
||||
if Self::matches_substr(
|
||||
self.remaining_lowercase(),
|
||||
&value.cached_text().to_lowercase(),
|
||||
) {
|
||||
self = self.suggest(value);
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn matches_substr(pattern: &str, input: &str) -> bool {
|
||||
let mut current_str = input;
|
||||
while !current_str.starts_with(pattern) {
|
||||
match current_str.find(['.', '_', '/', ':']) {
|
||||
Some(pos) => current_str = ¤t_str[(pos + 1)..],
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A helper method to suggest coordinate-related text.
|
||||
pub fn suggest_3d_coordinates(
|
||||
mut self,
|
||||
suggestions: TextCoordinates,
|
||||
validator: impl Fn(&str) -> bool,
|
||||
) -> Suggestions {
|
||||
let input = self.remaining();
|
||||
let coordinate = suggestions.get_coordinate();
|
||||
|
||||
if input.is_empty() {
|
||||
let full = format!("{coordinate} {coordinate} {coordinate}");
|
||||
if validator(&full) {
|
||||
self = self.filter_and_suggest_one(coordinate.to_string());
|
||||
self = self.filter_and_suggest_one(format!("{coordinate} {coordinate}"));
|
||||
self = self.filter_and_suggest_one(full);
|
||||
}
|
||||
} else {
|
||||
let mut split = input.split(' ');
|
||||
|
||||
match (split.next(), split.next(), split.next()) {
|
||||
(Some(part1), None, None) => {
|
||||
let full = format!("{part1} {coordinate} {coordinate}");
|
||||
if validator(&full) {
|
||||
let partial = format!("{part1} {coordinate}");
|
||||
self = self.filter_and_suggest_one(partial);
|
||||
self = self.filter_and_suggest_one(full);
|
||||
}
|
||||
}
|
||||
(Some(part1), Some(part2), None) => {
|
||||
let full = format!("{part1} {part2} {coordinate}");
|
||||
if validator(&full) {
|
||||
self = self.filter_and_suggest_one(full);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
self.build()
|
||||
}
|
||||
|
||||
/// A helper method to suggest coordinate-related text.
|
||||
pub fn suggest_2d_coordinates(
|
||||
mut self,
|
||||
suggestions: TextCoordinates,
|
||||
validator: impl Fn(&str) -> bool,
|
||||
) -> Suggestions {
|
||||
let input = self.remaining();
|
||||
let coordinate = suggestions.get_coordinate();
|
||||
|
||||
if input.is_empty() {
|
||||
let full = format!("{coordinate} {coordinate}");
|
||||
if validator(&full) {
|
||||
self = self.filter_and_suggest_one(coordinate.to_string());
|
||||
self = self.filter_and_suggest_one(full);
|
||||
}
|
||||
} else {
|
||||
let mut split = input.split(' ');
|
||||
|
||||
if let Some(part) = split.next()
|
||||
&& split.next().is_none()
|
||||
{
|
||||
let full = format!("{part} {coordinate}");
|
||||
if validator(&full) {
|
||||
self = self.filter_and_suggest_one(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.build()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Suggestions {
|
||||
pub range: StringRange,
|
||||
pub suggestions: Vec<Suggestion>,
|
||||
}
|
||||
|
||||
impl Suggestions {
|
||||
/// Constructs a new [`Suggestions`] structure from
|
||||
/// a range and [`Suggestion`]s.
|
||||
#[must_use]
|
||||
pub const fn new(range: StringRange, suggestions: Vec<Suggestion>) -> Self {
|
||||
Self { range, suggestions }
|
||||
}
|
||||
|
||||
/// Constructs a new [`Suggestions`] of zero size and no range.
|
||||
#[must_use]
|
||||
pub const fn empty() -> Self {
|
||||
Self::new(StringRange::at(0), vec![])
|
||||
}
|
||||
|
||||
/// Returns whether this [`Suggestions`] *is* of zero size.
|
||||
#[must_use]
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.suggestions.is_empty()
|
||||
}
|
||||
|
||||
/// Merges all [`Suggestions`] provided with a command into a single [`Suggestions`].
|
||||
#[must_use]
|
||||
pub fn merge<I, S>(command: &str, input: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: Borrow<Self>,
|
||||
{
|
||||
let input: Vec<S> = input.into_iter().collect();
|
||||
|
||||
if input.is_empty() {
|
||||
return Self::empty();
|
||||
} else if input.len() == 1 {
|
||||
return input[0].borrow().clone();
|
||||
}
|
||||
|
||||
let mut texts = Vec::new();
|
||||
|
||||
for suggestions in &input {
|
||||
for suggestion in &suggestions.borrow().suggestions {
|
||||
if !texts.contains(&suggestion) {
|
||||
texts.push(suggestion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self::create(command, texts)
|
||||
}
|
||||
|
||||
/// Creates a single [`Suggestions`] structure from
|
||||
/// many [`Suggestion`]s and a command.
|
||||
#[must_use]
|
||||
pub fn create<I, S>(command: &str, suggestions: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: Borrow<Suggestion>,
|
||||
{
|
||||
let suggestions: Vec<S> = suggestions.into_iter().collect();
|
||||
|
||||
if suggestions.is_empty() {
|
||||
return Self::empty();
|
||||
}
|
||||
|
||||
// First, we figure out the range encompassing all suggestions provided.
|
||||
let range = suggestions
|
||||
.iter()
|
||||
.map(|s| s.borrow().range)
|
||||
.reduce(StringRange::encompass)
|
||||
.expect("Suggestions list is not empty, so range should exist");
|
||||
|
||||
let mut texts = Vec::new();
|
||||
for suggestion in &suggestions {
|
||||
let suggestion = suggestion.borrow().expand(command, range);
|
||||
if !texts.contains(&suggestion) {
|
||||
texts.push(suggestion);
|
||||
}
|
||||
}
|
||||
|
||||
Self::new(range, Self::sort(texts))
|
||||
}
|
||||
|
||||
/// Sorts a set of [`Suggestion`]s, in the following precedence:
|
||||
///
|
||||
/// 1. If both suggestions are integers, their integral value is compared.
|
||||
/// 2. Otherwise, compare their text lexicographically.
|
||||
fn sort(suggestions: Vec<Suggestion>) -> Vec<Suggestion> {
|
||||
enum PushSide {
|
||||
Text,
|
||||
Integer,
|
||||
Break,
|
||||
}
|
||||
|
||||
let mut text_suggestions = Vec::new();
|
||||
let mut integer_suggestions = Vec::new();
|
||||
|
||||
let len = suggestions.len();
|
||||
|
||||
for suggestion in suggestions {
|
||||
match suggestion.text {
|
||||
SuggestionText::Text(text) => {
|
||||
let text_lowercase = text.to_lowercase();
|
||||
text_suggestions.push((
|
||||
text,
|
||||
suggestion.tooltip,
|
||||
suggestion.range,
|
||||
text_lowercase,
|
||||
));
|
||||
}
|
||||
SuggestionText::Integer { cached_text, value } => integer_suggestions.push((
|
||||
cached_text,
|
||||
value,
|
||||
suggestion.tooltip,
|
||||
suggestion.range,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
text_suggestions.sort_by(|a, b| a.3.cmp(&b.3));
|
||||
integer_suggestions.sort_unstable_by_key(|x| x.1);
|
||||
|
||||
let mut text_iter = text_suggestions.into_iter().peekable();
|
||||
let mut integer_iter = integer_suggestions.into_iter().peekable();
|
||||
|
||||
let mut suggestions = Vec::with_capacity(len);
|
||||
|
||||
loop {
|
||||
let text = text_iter.peek();
|
||||
let integer = integer_iter.peek();
|
||||
|
||||
let side = match (text, integer) {
|
||||
(Some(text), Some(integer)) => match text.0.cmp(&integer.0) {
|
||||
Ordering::Less => PushSide::Text,
|
||||
Ordering::Greater => PushSide::Integer,
|
||||
Ordering::Equal => {
|
||||
tracing::error!("Duplicate suggestion found during merge");
|
||||
PushSide::Text
|
||||
}
|
||||
},
|
||||
(Some(_), None) => PushSide::Text,
|
||||
(None, Some(_)) => PushSide::Integer,
|
||||
(None, None) => PushSide::Break,
|
||||
};
|
||||
|
||||
match side {
|
||||
PushSide::Text => {
|
||||
if let Some(text) = text_iter.next() {
|
||||
suggestions.push(Suggestion {
|
||||
text: SuggestionText::Text(text.0),
|
||||
tooltip: text.1,
|
||||
range: text.2,
|
||||
});
|
||||
}
|
||||
}
|
||||
PushSide::Integer => {
|
||||
if let Some(text) = integer_iter.next() {
|
||||
suggestions.push(Suggestion {
|
||||
text: SuggestionText::Integer {
|
||||
cached_text: text.0,
|
||||
value: text.1,
|
||||
},
|
||||
tooltip: text.2,
|
||||
range: text.3,
|
||||
});
|
||||
}
|
||||
}
|
||||
PushSide::Break => break,
|
||||
}
|
||||
}
|
||||
|
||||
suggestions
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents server-side only coordinate suggestions.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TextCoordinates {
|
||||
/// Represents `^ ^ ^`.
|
||||
Local,
|
||||
|
||||
/// Represents `~ ~ ~`.
|
||||
Global,
|
||||
}
|
||||
|
||||
impl TextCoordinates {
|
||||
/// Get the symbol of a coordinate of this suggestion set.
|
||||
#[must_use]
|
||||
pub const fn get_coordinate(self) -> &'static str {
|
||||
match self {
|
||||
Self::Local => "^",
|
||||
Self::Global => "~",
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user