azalea_brigadier/builder/
argument_builder.rs

1use std::{
2    fmt::{self, Debug},
3    sync::Arc,
4};
5
6use parking_lot::RwLock;
7
8use super::{literal_argument_builder::Literal, required_argument_builder::Argument};
9use crate::{
10    context::CommandContext,
11    errors::CommandSyntaxError,
12    modifier::RedirectModifier,
13    tree::{Command, CommandNode},
14};
15
16#[derive(Debug)]
17pub enum ArgumentBuilderType<S> {
18    Literal(Literal),
19    Argument(Argument<S>),
20}
21impl<S> Clone for ArgumentBuilderType<S> {
22    fn clone(&self) -> Self {
23        match self {
24            ArgumentBuilderType::Literal(literal) => ArgumentBuilderType::Literal(literal.clone()),
25            ArgumentBuilderType::Argument(argument) => {
26                ArgumentBuilderType::Argument(argument.clone())
27            }
28        }
29    }
30}
31
32/// A node that hasn't yet been built.
33pub struct ArgumentBuilder<S> {
34    arguments: CommandNode<S>,
35
36    command: Command<S>,
37    requirement: Arc<dyn Fn(&S) -> bool + Send + Sync>,
38    target: Option<Arc<RwLock<CommandNode<S>>>>,
39
40    forks: bool,
41    modifier: Option<Arc<RedirectModifier<S>>>,
42}
43
44/// A node that isn't yet built.
45impl<S> ArgumentBuilder<S> {
46    pub fn new(value: ArgumentBuilderType<S>) -> Self {
47        Self {
48            arguments: CommandNode {
49                value,
50                ..Default::default()
51            },
52            command: None,
53            requirement: Arc::new(|_| true),
54            forks: false,
55            modifier: None,
56            target: None,
57        }
58    }
59
60    /// Continue building this node with a child node.
61    ///
62    /// ```
63    /// # use azalea_brigadier::prelude::*;
64    /// # let mut subject = CommandDispatcher::<()>::new();
65    /// literal("foo").then(literal("bar").executes(|ctx: &CommandContext<()>| 42))
66    /// # ;
67    /// ```
68    pub fn then(self, argument: ArgumentBuilder<S>) -> Self {
69        self.then_built(argument.build())
70    }
71
72    /// Add an already built child node to this node.
73    ///
74    /// You should usually use [`Self::then`] instead.
75    pub fn then_built(mut self, argument: CommandNode<S>) -> Self {
76        self.arguments.add_child(&Arc::new(RwLock::new(argument)));
77        self
78    }
79
80    /// Set the command to be executed when this node is reached.
81    ///
82    /// If this is not present on a node, it is not a valid command.
83    ///
84    /// ```
85    /// # use azalea_brigadier::prelude::*;
86    /// # let mut subject = CommandDispatcher::<()>::new();
87    /// # subject.register(
88    /// literal("foo").executes(|ctx: &CommandContext<()>| 42)
89    /// # );
90    /// ```
91    pub fn executes<F>(mut self, f: F) -> Self
92    where
93        F: Fn(&CommandContext<S>) -> i32 + Send + Sync + 'static,
94    {
95        self.command = Some(Arc::new(move |ctx: &CommandContext<S>| Ok(f(ctx))));
96        self
97    }
98
99    /// Same as [`Self::executes`] but returns a `Result<i32,
100    /// CommandSyntaxError>`.
101    pub fn executes_result<F>(mut self, f: F) -> Self
102    where
103        F: Fn(&CommandContext<S>) -> Result<i32, CommandSyntaxError> + Send + Sync + 'static,
104    {
105        self.command = Some(Arc::new(f));
106        self
107    }
108
109    /// Set the requirement for this node to be considered.
110    ///
111    /// If this is not present on a node, it is considered to always pass.
112    ///
113    /// ```
114    /// # use azalea_brigadier::prelude::*;
115    /// # use std::sync::Arc;
116    /// # pub struct CommandSource {
117    /// #     pub opped: bool,
118    /// # }
119    /// # let mut subject = CommandDispatcher::<CommandSource>::new();
120    /// # subject.register(
121    /// literal("foo")
122    ///     .requires(|s: &CommandSource| s.opped)
123    ///     // ...
124    ///     # .executes(|ctx: &CommandContext<CommandSource>| 42)
125    /// # );
126    pub fn requires<F>(mut self, requirement: F) -> Self
127    where
128        F: Fn(&S) -> bool + Send + Sync + 'static,
129    {
130        self.requirement = Arc::new(requirement);
131        self
132    }
133
134    pub fn redirect(self, target: Arc<RwLock<CommandNode<S>>>) -> Self {
135        self.forward(target, None, false)
136    }
137
138    pub fn fork(
139        self,
140        target: Arc<RwLock<CommandNode<S>>>,
141        modifier: Arc<RedirectModifier<S>>,
142    ) -> Self {
143        self.forward(target, Some(modifier), true)
144    }
145
146    pub fn forward(
147        mut self,
148        target: Arc<RwLock<CommandNode<S>>>,
149        modifier: Option<Arc<RedirectModifier<S>>>,
150        fork: bool,
151    ) -> Self {
152        if !self.arguments.children.is_empty() {
153            panic!("Cannot forward a node with children");
154        }
155        self.target = Some(target);
156        self.modifier = modifier;
157        self.forks = fork;
158        self
159    }
160
161    pub fn arguments(&self) -> &CommandNode<S> {
162        &self.arguments
163    }
164
165    /// Manually build this node into a [`CommandNode`]. You probably don't need
166    /// to do this yourself.
167    pub fn build(self) -> CommandNode<S> {
168        let mut result = CommandNode {
169            value: self.arguments.value,
170            command: self.command,
171            requirement: self.requirement,
172            redirect: self.target,
173            modifier: self.modifier,
174            forks: self.forks,
175            arguments: Default::default(),
176            children: Default::default(),
177            literals: Default::default(),
178        };
179
180        for argument in self.arguments.children.values() {
181            result.add_child(argument);
182        }
183
184        result
185    }
186}
187
188impl<S> Debug for ArgumentBuilder<S> {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        f.debug_struct("ArgumentBuilder")
191            .field("arguments", &self.arguments)
192            // .field("command", &self.command)
193            // .field("requirement", &self.requirement)
194            .field("target", &self.target)
195            .field("forks", &self.forks)
196            // .field("modifier", &self.modifier)
197            .finish()
198    }
199}
200impl<S> Clone for ArgumentBuilder<S> {
201    fn clone(&self) -> Self {
202        Self {
203            arguments: self.arguments.clone(),
204            command: self.command.clone(),
205            requirement: self.requirement.clone(),
206            target: self.target.clone(),
207            forks: self.forks,
208            modifier: self.modifier.clone(),
209        }
210    }
211}