Skip to main content

azalea_brigadier/tree/
mod.rs

1use std::{
2    collections::{BTreeMap, HashMap},
3    fmt::{self, Debug},
4    hash::{Hash, Hasher},
5    ptr,
6    sync::Arc,
7};
8
9use parking_lot::RwLock;
10
11use crate::{
12    builder::{
13        argument_builder::ArgumentBuilderType, literal_argument_builder::Literal,
14        required_argument_builder::Argument,
15    },
16    context::{CommandContext, CommandContextBuilder, ParsedArgument, StringRange},
17    errors::{BuiltInError, CommandSyntaxError},
18    modifier::RedirectModifier,
19    string_reader::StringReader,
20    suggestion::{Suggestions, SuggestionsBuilder},
21};
22
23pub type Command<S, R> =
24    Option<Arc<dyn Fn(&CommandContext<S, R>) -> Result<R, CommandSyntaxError> + Send + Sync>>;
25
26/// An ArgumentBuilder that has been built.
27#[non_exhaustive]
28pub struct CommandNode<S, R = i32> {
29    pub value: ArgumentBuilderType<S, R>,
30
31    // this is a BTreeMap because children need to be ordered when getting
32    // command suggestions
33    pub children: BTreeMap<String, Arc<RwLock<CommandNode<S, R>>>>,
34    pub literals: HashMap<String, Arc<RwLock<CommandNode<S, R>>>>,
35    pub arguments: HashMap<String, Arc<RwLock<CommandNode<S, R>>>>,
36
37    pub command: Command<S, R>,
38    pub requirement: Arc<dyn Fn(&S) -> bool + Send + Sync>,
39    pub redirect: Option<Arc<RwLock<CommandNode<S, R>>>>,
40    pub forks: bool,
41    pub modifier: Option<Arc<RedirectModifier<S, R>>>,
42}
43
44impl<S, R> Clone for CommandNode<S, R> {
45    fn clone(&self) -> Self {
46        Self {
47            value: self.value.clone(),
48            children: self.children.clone(),
49            literals: self.literals.clone(),
50            arguments: self.arguments.clone(),
51            command: self.command.clone(),
52            requirement: self.requirement.clone(),
53            redirect: self.redirect.clone(),
54            forks: self.forks,
55            modifier: self.modifier.clone(),
56        }
57    }
58}
59
60impl<S, R> CommandNode<S, R> {
61    /// Returns the value as a literal from this command node, assuming it's
62    /// already been checked.
63    ///
64    /// # Panics
65    ///
66    /// Will panic if this node is not a literal. Consider using a match
67    /// statement instead.
68    pub fn literal(&self) -> &Literal {
69        match self.value {
70            ArgumentBuilderType::Literal(ref literal) => literal,
71            _ => panic!("CommandNode::literal() called on non-literal node"),
72        }
73    }
74    /// Returns the value as an argument from this command node, assuming it's
75    /// already been checked.
76    ///
77    /// # Panics
78    ///
79    /// Will panic if this node is not an argument. Consider using a match
80    /// statement instead.
81    pub fn argument(&self) -> &Argument<S, R> {
82        match self.value {
83            ArgumentBuilderType::Argument(ref argument) => argument,
84            _ => panic!("CommandNode::argument() called on non-argument node"),
85        }
86    }
87
88    pub fn get_relevant_nodes(
89        &self,
90        input: &mut StringReader,
91    ) -> Vec<Arc<RwLock<CommandNode<S, R>>>> {
92        let literals = &self.literals;
93
94        if literals.is_empty() {
95            self.arguments.values().cloned().collect()
96        } else {
97            let cursor = input.cursor();
98            while input.can_read() && input.peek() != ' ' {
99                input.skip();
100            }
101            let text: String = input
102                .string()
103                .chars()
104                .skip(cursor)
105                .take(input.cursor() - cursor)
106                .collect();
107            input.cursor = cursor;
108            let literal = literals.get(&text);
109            if let Some(literal) = literal {
110                vec![literal.clone()]
111            } else {
112                self.arguments.values().cloned().collect()
113            }
114        }
115    }
116
117    pub fn can_use(&self, source: &S) -> bool {
118        (self.requirement)(source)
119    }
120
121    pub fn add_child(&mut self, node: &Arc<RwLock<CommandNode<S, R>>>) {
122        let child = self.children.get(node.read().name());
123        if let Some(child) = child {
124            // We've found something to merge onto
125            if let Some(command) = &node.read().command {
126                child.write().command = Some(command.clone());
127            }
128            for grandchild in node.read().children.values() {
129                child.write().add_child(grandchild);
130            }
131        } else {
132            self.children
133                .insert(node.read().name().to_owned(), node.clone());
134            match &node.read().value {
135                ArgumentBuilderType::Literal(literal) => {
136                    self.literals.insert(literal.value.clone(), node.clone());
137                }
138                ArgumentBuilderType::Argument(argument) => {
139                    self.arguments.insert(argument.name.clone(), node.clone());
140                }
141            }
142        }
143    }
144
145    pub fn name(&self) -> &str {
146        match &self.value {
147            ArgumentBuilderType::Argument(argument) => &argument.name,
148            ArgumentBuilderType::Literal(literal) => &literal.value,
149        }
150    }
151
152    pub fn usage_text(&self) -> String {
153        match &self.value {
154            ArgumentBuilderType::Argument(argument) => format!("<{}>", argument.name),
155            ArgumentBuilderType::Literal(literal) => literal.value.to_owned(),
156        }
157    }
158
159    pub fn child(&self, name: &str) -> Option<Arc<RwLock<CommandNode<S, R>>>> {
160        self.children.get(name).cloned()
161    }
162
163    pub fn parse_with_context(
164        &self,
165        reader: &mut StringReader,
166        context_builder: &mut CommandContextBuilder<S, R>,
167    ) -> Result<(), CommandSyntaxError> {
168        match self.value {
169            ArgumentBuilderType::Argument(ref argument) => {
170                let start = reader.cursor();
171                let result = argument.parse(reader)?;
172                let parsed = ParsedArgument {
173                    range: StringRange::between(start, reader.cursor()),
174                    result,
175                };
176
177                context_builder.with_argument(&argument.name, parsed.clone());
178                context_builder.with_node(Arc::new(RwLock::new(self.clone())), parsed.range);
179
180                Ok(())
181            }
182            ArgumentBuilderType::Literal(ref literal) => {
183                let start = reader.cursor();
184                let end = self.parse(reader);
185
186                if let Some(end) = end {
187                    context_builder.with_node(
188                        Arc::new(RwLock::new(self.clone())),
189                        StringRange::between(start, end),
190                    );
191                    return Ok(());
192                }
193
194                Err(BuiltInError::LiteralIncorrect {
195                    expected: literal.value.clone(),
196                }
197                .create_with_context(reader))
198            }
199        }
200    }
201
202    fn parse(&self, reader: &mut StringReader) -> Option<usize> {
203        match self.value {
204            ArgumentBuilderType::Argument(_) => {
205                panic!("Can't parse argument.")
206            }
207            ArgumentBuilderType::Literal(ref literal) => {
208                let start = reader.cursor();
209                if reader.can_read_length(literal.value.len()) {
210                    let end = start + literal.value.len();
211                    if reader
212                        .string()
213                        .get(start..end)
214                        .expect("Couldn't slice reader correctly?")
215                        == literal.value
216                    {
217                        reader.cursor = end;
218                        if !reader.can_read() || reader.peek() == ' ' {
219                            return Some(end);
220                        } else {
221                            reader.cursor = start;
222                        }
223                    }
224                }
225            }
226        }
227        None
228    }
229
230    pub fn list_suggestions(
231        &self,
232        context: CommandContext<S, R>,
233        builder: SuggestionsBuilder,
234    ) -> Suggestions {
235        match &self.value {
236            ArgumentBuilderType::Literal(literal) => {
237                if literal
238                    .value
239                    .to_lowercase()
240                    .starts_with(builder.remaining_lowercase())
241                {
242                    builder.suggest(&literal.value).build()
243                } else {
244                    Suggestions::default()
245                }
246            }
247            ArgumentBuilderType::Argument(argument) => argument.list_suggestions(context, builder),
248        }
249    }
250}
251
252impl<S, R> Debug for CommandNode<S, R> {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        f.debug_struct("CommandNode")
255            // .field("value", &self.value)
256            .field("children", &self.children)
257            .field("command", &self.command.is_some())
258            // .field("requirement", &self.requirement)
259            .field("redirect", &self.redirect)
260            .field("forks", &self.forks)
261            // .field("modifier", &self.modifier)
262            .finish()
263    }
264}
265
266impl<S, R> Default for CommandNode<S, R> {
267    fn default() -> Self {
268        Self {
269            value: ArgumentBuilderType::Literal(Literal::default()),
270
271            children: BTreeMap::new(),
272            literals: HashMap::new(),
273            arguments: HashMap::new(),
274
275            command: None,
276            requirement: Arc::new(|_| true),
277            redirect: None,
278            forks: false,
279            modifier: None,
280        }
281    }
282}
283
284impl<S, R> Hash for CommandNode<S, R> {
285    fn hash<H: Hasher>(&self, state: &mut H) {
286        // hash the children
287        for (k, v) in &self.children {
288            k.hash(state);
289            v.read().hash(state);
290        }
291        // i hope this works because if doesn't then that'll be a problem
292        ptr::hash(&self.command, state);
293    }
294}
295
296impl<S, R> PartialEq for CommandNode<S, R> {
297    fn eq(&self, other: &Self) -> bool {
298        if self.children.len() != other.children.len() {
299            return false;
300        }
301        for (k, v) in &self.children {
302            let other_child = other.children.get(k).unwrap();
303            if !Arc::ptr_eq(v, other_child) {
304                return false;
305            }
306        }
307
308        match &self.command {
309            Some(selfexecutes) => {
310                // idk how to do this better since we can't compare `dyn Fn`s
311                match &other.command {
312                    Some(otherexecutes) => {
313                        if !Arc::ptr_eq(selfexecutes, otherexecutes) {
314                            return false;
315                        }
316                    }
317                    _ => {
318                        return false;
319                    }
320                }
321            }
322            _ => {
323                if other.command.is_some() {
324                    return false;
325                }
326            }
327        }
328        true
329    }
330}
331impl<S, R> Eq for CommandNode<S, R> {}