azalea_brigadier/tree/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use std::{
    collections::{BTreeMap, HashMap},
    fmt::Debug,
    hash::Hash,
    ptr,
    sync::Arc,
};

use parking_lot::RwLock;

use crate::{
    builder::{
        argument_builder::ArgumentBuilderType, literal_argument_builder::Literal,
        required_argument_builder::Argument,
    },
    context::{CommandContext, CommandContextBuilder, ParsedArgument, StringRange},
    exceptions::{BuiltInExceptions, CommandSyntaxException},
    modifier::RedirectModifier,
    string_reader::StringReader,
    suggestion::{Suggestions, SuggestionsBuilder},
};

pub type Command<S> = Option<Arc<dyn Fn(&CommandContext<S>) -> i32 + Send + Sync>>;

/// An ArgumentBuilder that has been built.
#[non_exhaustive]
pub struct CommandNode<S> {
    pub value: ArgumentBuilderType,

    // this is a BTreeMap because children need to be ordered when getting command suggestions
    pub children: BTreeMap<String, Arc<RwLock<CommandNode<S>>>>,
    pub literals: HashMap<String, Arc<RwLock<CommandNode<S>>>>,
    pub arguments: HashMap<String, Arc<RwLock<CommandNode<S>>>>,

    pub command: Command<S>,
    pub requirement: Arc<dyn Fn(&S) -> bool + Send + Sync>,
    pub redirect: Option<Arc<RwLock<CommandNode<S>>>>,
    pub forks: bool,
    pub modifier: Option<Arc<RedirectModifier<S>>>,
}

impl<S> Clone for CommandNode<S> {
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            children: self.children.clone(),
            literals: self.literals.clone(),
            arguments: self.arguments.clone(),
            command: self.command.clone(),
            requirement: self.requirement.clone(),
            redirect: self.redirect.clone(),
            forks: self.forks,
            modifier: self.modifier.clone(),
        }
    }
}

impl<S> CommandNode<S> {
    /// Gets the literal, or panics. You should use match if you're not certain
    /// about the type.
    pub fn literal(&self) -> &Literal {
        match self.value {
            ArgumentBuilderType::Literal(ref literal) => literal,
            _ => panic!("CommandNode::literal() called on non-literal node"),
        }
    }
    /// Gets the argument, or panics. You should use match if you're not certain
    /// about the type.
    pub fn argument(&self) -> &Argument {
        match self.value {
            ArgumentBuilderType::Argument(ref argument) => argument,
            _ => panic!("CommandNode::argument() called on non-argument node"),
        }
    }

    pub fn get_relevant_nodes(&self, input: &mut StringReader) -> Vec<Arc<RwLock<CommandNode<S>>>> {
        let literals = &self.literals;

        if literals.is_empty() {
            self.arguments.values().cloned().collect()
        } else {
            let cursor = input.cursor();
            while input.can_read() && input.peek() != ' ' {
                input.skip();
            }
            let text: String = input
                .string()
                .chars()
                .skip(cursor)
                .take(input.cursor() - cursor)
                .collect();
            input.cursor = cursor;
            let literal = literals.get(&text);
            if let Some(literal) = literal {
                vec![literal.clone()]
            } else {
                self.arguments.values().cloned().collect()
            }
        }
    }

    pub fn can_use(&self, source: &S) -> bool {
        (self.requirement)(source)
    }

    pub fn add_child(&mut self, node: &Arc<RwLock<CommandNode<S>>>) {
        let child = self.children.get(node.read().name());
        if let Some(child) = child {
            // We've found something to merge onto
            if let Some(command) = &node.read().command {
                child.write().command = Some(command.clone());
            }
            for grandchild in node.read().children.values() {
                child.write().add_child(grandchild);
            }
        } else {
            self.children
                .insert(node.read().name().to_string(), node.clone());
            match &node.read().value {
                ArgumentBuilderType::Literal(literal) => {
                    self.literals.insert(literal.value.clone(), node.clone());
                }
                ArgumentBuilderType::Argument(argument) => {
                    self.arguments.insert(argument.name.clone(), node.clone());
                }
            }
        }
    }

    pub fn name(&self) -> &str {
        match &self.value {
            ArgumentBuilderType::Argument(argument) => &argument.name,
            ArgumentBuilderType::Literal(literal) => &literal.value,
        }
    }

    pub fn usage_text(&self) -> String {
        match &self.value {
            ArgumentBuilderType::Argument(argument) => format!("<{}>", argument.name),
            ArgumentBuilderType::Literal(literal) => literal.value.to_owned(),
        }
    }

    pub fn child(&self, name: &str) -> Option<Arc<RwLock<CommandNode<S>>>> {
        self.children.get(name).cloned()
    }

    pub fn parse_with_context(
        &self,
        reader: &mut StringReader,
        context_builder: &mut CommandContextBuilder<S>,
    ) -> Result<(), CommandSyntaxException> {
        match self.value {
            ArgumentBuilderType::Argument(ref argument) => {
                let start = reader.cursor();
                let result = argument.parse(reader)?;
                let parsed = ParsedArgument {
                    range: StringRange::between(start, reader.cursor()),
                    result,
                };

                context_builder.with_argument(&argument.name, parsed.clone());
                context_builder.with_node(Arc::new(RwLock::new(self.clone())), parsed.range);

                Ok(())
            }
            ArgumentBuilderType::Literal(ref literal) => {
                let start = reader.cursor();
                let end = self.parse(reader);

                if let Some(end) = end {
                    context_builder.with_node(
                        Arc::new(RwLock::new(self.clone())),
                        StringRange::between(start, end),
                    );
                    return Ok(());
                }

                Err(BuiltInExceptions::LiteralIncorrect {
                    expected: literal.value.clone(),
                }
                .create_with_context(reader))
            }
        }
    }

    fn parse(&self, reader: &mut StringReader) -> Option<usize> {
        match self.value {
            ArgumentBuilderType::Argument(_) => {
                panic!("Can't parse argument.")
            }
            ArgumentBuilderType::Literal(ref literal) => {
                let start = reader.cursor();
                if reader.can_read_length(literal.value.len()) {
                    let end = start + literal.value.len();
                    if reader
                        .string()
                        .get(start..end)
                        .expect("Couldn't slice reader correctly?")
                        == literal.value
                    {
                        reader.cursor = end;
                        if !reader.can_read() || reader.peek() == ' ' {
                            return Some(end);
                        } else {
                            reader.cursor = start;
                        }
                    }
                }
            }
        }
        None
    }

    pub fn list_suggestions(
        &self,
        // context is here because that's how it is in mojang's brigadier, but we haven't
        // implemented custom suggestions yet so this is unused rn
        _context: CommandContext<S>,
        builder: SuggestionsBuilder,
    ) -> Suggestions {
        match &self.value {
            ArgumentBuilderType::Literal(literal) => {
                if literal
                    .value
                    .to_lowercase()
                    .starts_with(builder.remaining_lowercase())
                {
                    builder.suggest(&literal.value).build()
                } else {
                    Suggestions::default()
                }
            }
            ArgumentBuilderType::Argument(argument) => argument.list_suggestions(builder),
        }
    }
}

impl<S> Debug for CommandNode<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CommandNode")
            .field("value", &self.value)
            .field("children", &self.children)
            .field("command", &self.command.is_some())
            // .field("requirement", &self.requirement)
            .field("redirect", &self.redirect)
            .field("forks", &self.forks)
            // .field("modifier", &self.modifier)
            .finish()
    }
}

impl<S> Default for CommandNode<S> {
    fn default() -> Self {
        Self {
            value: ArgumentBuilderType::Literal(Literal::default()),

            children: BTreeMap::new(),
            literals: HashMap::new(),
            arguments: HashMap::new(),

            command: None,
            requirement: Arc::new(|_| true),
            redirect: None,
            forks: false,
            modifier: None,
        }
    }
}

impl<S> Hash for CommandNode<S> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // hash the children
        for (k, v) in &self.children {
            k.hash(state);
            v.read().hash(state);
        }
        // i hope this works because if doesn't then that'll be a problem
        ptr::hash(&self.command, state);
    }
}

impl<S> PartialEq for CommandNode<S> {
    fn eq(&self, other: &Self) -> bool {
        if self.children.len() != other.children.len() {
            return false;
        }
        for (k, v) in &self.children {
            let other_child = other.children.get(k).unwrap();
            if !Arc::ptr_eq(v, other_child) {
                return false;
            }
        }

        if let Some(selfexecutes) = &self.command {
            // idk how to do this better since we can't compare `dyn Fn`s
            if let Some(otherexecutes) = &other.command {
                #[allow(ambiguous_wide_pointer_comparisons)]
                if !Arc::ptr_eq(selfexecutes, otherexecutes) {
                    return false;
                }
            } else {
                return false;
            }
        } else if other.command.is_some() {
            return false;
        }
        true
    }
}
impl<S> Eq for CommandNode<S> {}