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
use super::Parser;
use crate::parsers::{CommandArg, CommandArgParseError, ParseInput};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntitySelector {
    SimpleSelector(EntitySelectors),
    ComplexSelector(EntitySelectors, String),
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum EntitySelectors {
    AllEntities,
    SinglePlayer(String),
    #[default]
    AllPlayers,
    SelfPlayer,
    NearestPlayer,
    RandomPlayer,
}

impl CommandArg for EntitySelector {
    // we want to get either a simple string [`@e`, `@a`, `@p`, `@r`,
    // `<player_name>`] or a full selector: [`@e[<selector>]`, `@a[<selector>]`,
    // `@p[<selector>]`, `@r[<selector>]`] the selectors can have spaces in
    // them, so we need to be careful
    fn parse_arg(input: &mut ParseInput) -> Result<Self, CommandArgParseError> {
        input.skip_whitespace();
        let mut simple_selector = None;
        while let Some(c) = input.peek() {
            match c {
                '@' => {
                    input.pop(); // pop the '@'
                    match input.pop() {
                        Some('e') => simple_selector = Some(EntitySelectors::AllEntities),
                        Some('a') => simple_selector = Some(EntitySelectors::AllPlayers),
                        Some('p') => simple_selector = Some(EntitySelectors::NearestPlayer),
                        Some('r') => simple_selector = Some(EntitySelectors::RandomPlayer),
                        Some('s') => simple_selector = Some(EntitySelectors::SelfPlayer),
                        _ => {
                            return Err(CommandArgParseError::InvalidArgument {
                                expected: "entity selector".to_owned(),
                                got: c.to_string(),
                            })
                        }
                    }
                    if input.peek() != Some('[') {
                        // if there's no complex selector, we're done
                        return Ok(EntitySelector::SimpleSelector(simple_selector.unwrap()));
                    }
                }
                '[' => {
                    input.pop();
                    if simple_selector.is_none() {
                        return Err(CommandArgParseError::InvalidArgument {
                            expected: "entity selector".to_owned(),
                            got: c.to_string(),
                        });
                    }
                    let mut s = String::new();
                    while let Some(c) = input.pop() {
                        if c == ']' {
                            return Ok(EntitySelector::ComplexSelector(
                                simple_selector.unwrap(),
                                s.trim().to_owned(),
                            ));
                        }

                        s.push(c);
                    }
                }
                _ => {
                    return Ok(EntitySelector::SimpleSelector(
                        EntitySelectors::SinglePlayer(String::parse_arg(input)?),
                    ))
                }
            }
        }
        Err(CommandArgParseError::InvalidArgLength)
    }

    fn display() -> Parser {
        Parser::Entity {
            only_players: false,
            single: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_entity_selector() {
        let mut input = ParseInput::new("@e");
        assert_eq!(
            EntitySelector::parse_arg(&mut input).unwrap(),
            EntitySelector::SimpleSelector(EntitySelectors::AllEntities)
        );
        assert!(input.is_done());

        let mut input = ParseInput::new("@e[distance=..5]");
        assert_eq!(
            EntitySelector::parse_arg(&mut input).unwrap(),
            EntitySelector::ComplexSelector(
                EntitySelectors::AllEntities,
                "distance=..5".to_owned()
            )
        );
        assert!(input.is_done());

        let mut input = ParseInput::new("@s[distance=..5");
        assert!(EntitySelector::parse_arg(&mut input).is_err());
        assert!(input.is_done());

        let mut input = ParseInput::new("@r[distance=..5] hello");
        assert_eq!(
            EntitySelector::parse_arg(&mut input).unwrap(),
            EntitySelector::ComplexSelector(
                EntitySelectors::RandomPlayer,
                "distance=..5".to_owned()
            )
        );
        assert!(!input.is_done());

        let mut input = ParseInput::new("@p[distance=..5]hello");
        assert_eq!(
            EntitySelector::parse_arg(&mut input).unwrap(),
            EntitySelector::ComplexSelector(
                EntitySelectors::NearestPlayer,
                "distance=..5".to_owned()
            )
        );
        assert!(!input.is_done());

        let mut input = ParseInput::new("@e[distance=..5] hello world");
        assert_eq!(
            EntitySelector::parse_arg(&mut input).unwrap(),
            EntitySelector::ComplexSelector(
                EntitySelectors::AllEntities,
                "distance=..5".to_owned()
            )
        );
        assert!(!input.is_done());

        let mut input = ParseInput::new("@e[distance=..5]hello world");
        assert_eq!(
            EntitySelector::parse_arg(&mut input).unwrap(),
            EntitySelector::ComplexSelector(
                EntitySelectors::AllEntities,
                "distance=..5".to_owned()
            )
        );
        assert!(!input.is_done());
    }
}