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
extern crate regex;

use crate::util::error::STError;

use std::collections::HashMap;

use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};

pub struct Lexer {
    regex: Regex,
}

impl Lexer {
    pub fn new(regex: &str) -> Lexer {
        Lexer {
            regex: Regex::new(regex).expect("Regexes are predefined and tested. This is safe."),
        }
    }
    pub fn tokenize<'a>(&self, string: &'a str) -> Vec<&'a str> {
        let captures = self.regex.captures(string).map(|captures| {
            captures
                .iter() // All the captured groups
                .skip(1) // Skipping the complete match
                .flatten() // Ignoring all empty optional matches
                .map(|c| c.as_str()) // Grab the original strings
                .collect::<Vec<_>>() // Create a vector
        });
        captures.unwrap_or_default()
    }
}

lazy_static! {
    pub static ref INPUT_LEX: Lexer = Lexer::new(
        r#"(?x)
           (login)\s+(\w) |
           (info) |
           (quit) |
           (licenses_print) |
           (package_info_print)\s+(\d+) |
           (app_info_print)\s+(\d+) |
           (app_status)\s+(\d+)
           "#
    );
    pub static ref ACCOUNT_LEX: Lexer = Lexer::new(
        r#"(?x)
           \s*(Account):\s*([^\s]+)\s* |
           \s*(SteamID):\s*([^\s]+)\s* |
           \s*(Language):\s*([^\s]+)\s*
           "#,
    );
    pub static ref STATUS_LEX: Lexer = Lexer::new(
        r#"(?x)
           .*install\s+(state):\s+([^,]+).* |
           .*(dir):\s+"([^"]+)".* |
           .*(disk):\s+(\d+).* |
           "#,
    );
    pub static ref LICENSE_LEX: Lexer = Lexer::new(r".*(packageID)\s+(\d+).*");
    pub static ref INSTALL_LEX: Lexer = Lexer::new(
        r#"(?x)
           .*(Update).*\((\d+)\s/\s(\d+)\)$ |
           .*(ERROR)!\s+(.*)$ |
           .*(Success).*$ |
           "#,
    );
    static ref DATA_LEX: Lexer = Lexer::new(
        r#"(?x)
           \s*"([^"]+)"\s+"([^"]*)"\s* |
           \s*"([^"]+)"\s*$ |
           \s*(})\s*$ |
           \s*[^}"].*$ |
           "#,
    );
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Datum {
    Value(String),
    Nest(HashMap<String, Datum>),
}

impl Datum {
    pub fn maybe_value(&self) -> Result<String, STError> {
        match self {
            Datum::Value(value) => Ok(value.clone()),
            _ => Err(STError::Problem("woops".to_string())),
        }
    }
    pub fn maybe_nest(&self) -> Result<HashMap<String, Datum>, STError> {
        match self {
            Datum::Nest(map) => Ok(map.clone()),
            _ => Err(STError::Problem("woops".to_string())),
        }
    }
}

pub fn parse(block: &mut dyn Iterator<Item = &str>) -> Datum {
    let mut map = HashMap::new();
    while let Some(line) = block.next() {
        match *DATA_LEX.tokenize(line).as_slice() {
            ["}"] => {
                break;
            }
            [key, value] => {
                map.insert(key.to_string(), Datum::Value(value.to_string()));
            }
            [key] => {
                block.next();
                map.insert(key.to_string(), parse(block));
            }
            // Extra lines are sometimes present but do not match the SDL format.
            // Skip them.
            _ => {}
        }
    }
    Datum::Nest(map)
}

#[cfg(test)]
mod tests {
    use crate::util::parser::{parse, Datum, INSTALL_LEX};
    #[test]
    fn test_parse_data() {
        let mut block = r#"
[0mAppID : <id>, change number : 19486115/0, last change : Mon Jul 24 13:12:25 2023
"hmm"
{
    "vdl" "format"
    "is"
    {
      "silly"
      {
          but hopefully
          this is robust
      }
      "hmm" "™️ and at least one with an accented o, ö and a registered trademark symbol, ®"
      "otherØ 天 🎉" "Do you have any games with non-standard latin characters? Ü Ø 天 🎉 ?"
    }
}
            "#
        .lines();
        let map = parse(&mut block);
        let maybe_map = map.maybe_nest();
        assert!(maybe_map.is_ok());
        let map = maybe_map.unwrap();
        assert_eq!(map.len(), 1);
        let map = map.values().next().unwrap().maybe_nest().unwrap();
        assert_eq!(map.len(), 2);
        assert_eq!(
            Some(&Datum::Value("format".to_string())),
            map.get(&"vdl".to_string())
        );
        let map = map.get(&"is".to_string()).unwrap().maybe_nest().unwrap();
        assert_eq!(map.len(), 3);
        let inner = map
            .get(&"silly".to_string())
            .expect("failed to unwrap")
            .maybe_nest()
            .expect("Failed to properly parse");
        assert_eq!(inner.len(), 0);
        let complex = map
            .get(&"otherØ 天 🎉".to_string())
            .unwrap()
            .maybe_value()
            .unwrap();
        assert!(complex.contains(&"Ü".to_string()));
    }
    #[test]
    fn test_parse_update_basic() {
        let line = "\u{1b}[0m Update state (0x3) reconfiguring, progress: 0.00 (0 / 0)";
        match *INSTALL_LEX.tokenize(line).as_slice() {
            ["Update", "0", "0"] => {}
            _ => panic!("Matched {:?}", INSTALL_LEX.tokenize(line)),
        }
    }
    #[test]
    fn test_parse_update() {
        let line =
            "\u{1b}[0m Update state (0x5) verifying install, progress: 0.00 (445476 / 12780261578)";
        match *INSTALL_LEX.tokenize(line).as_slice() {
            ["Update", "445476", "12780261578"] => {}
            _ => panic!("Matched {:?}", INSTALL_LEX.tokenize(line)),
        }
    }
    #[test]
    fn test_parse_update_continue() {
        let line =
            " Update state (0x5) verifying install, progress: 99.20 (12677647126 / 12780261578)";
        match *INSTALL_LEX.tokenize(line).as_slice() {
            ["Update", "12677647126", "12780261578"] => {}
            _ => panic!("Matched {:?}", INSTALL_LEX.tokenize(line)),
        }
    }
    #[test]
    fn test_parse_update_fail() {
        let line = "\u{1b}[0mERROR! Failed to install app '874260' (Invalid platform)";
        match *INSTALL_LEX.tokenize(line).as_slice() {
            ["ERROR", "Failed to install app '874260' (Invalid platform)"] => {}
            _ => panic!("Matched {:?}", INSTALL_LEX.tokenize(line)),
        }
    }
    #[test]
    fn test_parse_update_sucess() {
        let line = "Success! App '620' fully installed.";
        match *INSTALL_LEX.tokenize(line).as_slice() {
            ["Success"] => {}
            _ => panic!("Matched {:?}", INSTALL_LEX.tokenize(line)),
        }
    }
}