azalea_brigadier/context/
command_context.rs

1use std::{any::Any, collections::HashMap, fmt::Debug, rc::Rc, sync::Arc};
2
3use parking_lot::RwLock;
4
5use super::{ParsedArgument, parsed_command_node::ParsedCommandNode, string_range::StringRange};
6use crate::{
7    modifier::RedirectModifier,
8    tree::{Command, CommandNode},
9};
10
11/// A built `CommandContextBuilder`.
12pub struct CommandContext<S> {
13    pub source: Arc<S>,
14    pub input: String,
15    pub arguments: HashMap<String, ParsedArgument>,
16    pub command: Command<S>,
17    pub root_node: Arc<RwLock<CommandNode<S>>>,
18    pub nodes: Vec<ParsedCommandNode<S>>,
19    pub range: StringRange,
20    pub child: Option<Rc<CommandContext<S>>>,
21    pub modifier: Option<Arc<RedirectModifier<S>>>,
22    pub forks: bool,
23}
24
25impl<S> Clone for CommandContext<S> {
26    fn clone(&self) -> Self {
27        Self {
28            source: self.source.clone(),
29            input: self.input.clone(),
30            arguments: self.arguments.clone(),
31            command: self.command.clone(),
32            root_node: self.root_node.clone(),
33            nodes: self.nodes.clone(),
34            range: self.range,
35            child: self.child.clone(),
36            modifier: self.modifier.clone(),
37            forks: self.forks,
38        }
39    }
40}
41
42impl<S> Debug for CommandContext<S> {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("CommandContext")
45            // .field("source", &self.source)
46            .field("input", &self.input)
47            // .field("arguments", &self.arguments)
48            // .field("command", &self.command)
49            // .field("root_node", &self.root_node)
50            // .field("nodes", &self.nodes)
51            .field("range", &self.range)
52            .field("child", &self.child)
53            // .field("modifier", &self.modifier)
54            .field("forks", &self.forks)
55            .finish()
56    }
57}
58
59impl<S> CommandContext<S> {
60    pub fn copy_for(&self, source: Arc<S>) -> Self {
61        if Arc::ptr_eq(&source, &self.source) {
62            return self.clone();
63        }
64        CommandContext {
65            source,
66            input: self.input.clone(),
67            arguments: self.arguments.clone(),
68            command: self.command.clone(),
69            root_node: self.root_node.clone(),
70            nodes: self.nodes.clone(),
71            range: self.range,
72            child: self.child.clone(),
73            modifier: self.modifier.clone(),
74            forks: self.forks,
75        }
76    }
77
78    pub fn has_nodes(&self) -> bool {
79        !self.nodes.is_empty()
80    }
81
82    pub fn argument(&self, name: &str) -> Option<Arc<dyn Any>> {
83        let argument = self.arguments.get(name);
84        argument.map(|a| a.result.clone())
85    }
86}