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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use core::panic;
use std::collections::HashMap;

use crate::{parser, tokens};

#[derive(Debug)]
pub enum TomlError {
    Deserializer(parser::Error),
    Tokens(tokens::Error),
    KeyRedefined(Vec<String>),
    ChangingInlineTable(Vec<String>),
    ValueTypeRedefined,
}
impl From<parser::Error> for TomlError {
    fn from(e: parser::Error) -> Self {
        Self::Deserializer(e)
    }
}
impl From<tokens::Error> for TomlError {
    fn from(e: tokens::Error) -> Self {
        Self::Tokens(e)
    }
}

// A full TOML file is a HashMap<String, TomlValue> 
/// Representation of a TOML value.
#[derive(PartialEq, Clone, Debug)]
pub enum TomlValue {
    /// Represents a TOML string
    String(String),
    /// Represents a TOML integer
    Integer(i64),
    /// Represents a TOML float
    Float(f64),
    /// Represents a TOML boolean
    Boolean(bool),
    /// Represents a TOML datetime
    Datetime(String),
    /// Represents a TOML array
    Array(Array),
    /// Represents a TOML table
    Table(Table),
}
impl TomlValue {
    pub fn get(&self, key: &str) -> Option<&TomlValue> {
        if let TomlValue::Table(table) = self {
            table.get(key)
        } else {
            None
        }
    }
    pub fn as_string(&self) -> Option<String> {
        if let TomlValue::String(s) = self {
            Some(s.clone())
        } else {
            None
        }
    }
}

/// Type representing a TOML array, payload of the `Value::Array` variant
pub type Array = Vec<TomlValue>;

/// Type representing a TOML table, payload of the `Value::Table` variant.
pub type Table = HashMap<String, TomlValue>;

fn append_table(table: &mut HashMap<String, TomlValue>, key_index: &[String]) -> Result<(), TomlError> {
    match &key_index {
        [] => {
            panic!("Trying to add a value to an empty key")
        },
        [key] => {
            if let Some(array) = table.get_mut(key) {
                match array {
                    TomlValue::Array(array) => {
                        array.push(TomlValue::Table(HashMap::new()));
                    }
                    _ => {
                        unreachable!("Should have been caught")
                    }
                }
            } else {
                table.insert(key.to_string(), TomlValue::Array(vec![TomlValue::Table(HashMap::new())]));
            }
            Ok(())
        },
        [key, rest @ ..] => {
            let subtable = table.entry(key.to_string()).or_insert_with(|| {
                TomlValue::Table(HashMap::new())
            });
            match subtable {
                // if it's an array, that's fine, take the last element
                TomlValue::Table(subtable) => {
                    append_table(subtable, rest)
                }
                TomlValue::Array(array) => {
                    if let Some(last) = array.last_mut() {
                        match last {
                            TomlValue::Table(subtable) => {
                                append_table(subtable, rest)
                            },
                            _ => {
                                Err(TomlError::ValueTypeRedefined)
                            }
                        }
                    } else {
                        unreachable!("Adding an element to the last table of an array of tables that is empty")
                    }
                }
                _ => {
                    Err(TomlError::ValueTypeRedefined)
                }
            }
        }
    }
}

fn create_table(table: &mut HashMap<String, TomlValue>, key_index: &[String]) -> Result<(), TomlError> {
    match &key_index {
        [] => {
            panic!("Trying to add a value to an empty key")
        },
        [key] => {
            table.entry(key.to_string()).or_insert_with(|| TomlValue::Table(HashMap::new()));
            Ok(())
        },
        [key, rest @ ..] => {
            let subtable = table.entry(key.to_string()).or_insert_with(|| {
                TomlValue::Table(HashMap::new())
            });
            match subtable {
                // if it's an array, that's fine, take the last element
                TomlValue::Table(subtable) => {
                    create_table(subtable, rest)
                }
                TomlValue::Array(array) => {
                    if let Some(last) = array.last_mut() {
                        match last {
                            TomlValue::Table(subtable) => {
                                create_table(subtable, rest)
                            },
                            _ => {
                                Err(TomlError::ValueTypeRedefined)
                            }
                        }
                    } else {
                        unreachable!("Adding an element to the last table of an array of tables that is empty")
                    }
                }
                _ => {
                    Err(TomlError::ValueTypeRedefined)
                }
            }
        }
    }
}

fn add_to_table(table: &mut HashMap<String, TomlValue>, key_index: &[String], value: TomlValue) -> Result<(), TomlError> {
    match &key_index {
        [] => {
            unreachable!("Trying to add a value to an empty key")
        },
        [key] => {
            if let Some(_) = table.insert(key.to_string(), value) {
                Err(TomlError::ValueTypeRedefined)
            } else {
                Ok(())
            }
        },
        [key, rest @ ..] => {
            let subtable = table.entry(key.to_string()).or_insert_with(|| {
                TomlValue::Table(HashMap::new())
            });
            match subtable {
                // if it's an array, that's fine, take the last element
                TomlValue::Table(subtable) => {
                    add_to_table(subtable, rest, value)
                }
                TomlValue::Array(array) => {
                    if let Some(last) = array.last_mut() {
                        match last {
                            TomlValue::Table(subtable) => {
                                add_to_table(subtable, rest, value)
                            },
                            _ => {
                                Err(TomlError::ValueTypeRedefined)
                            }
                        }
                    } else {
                        unreachable!("Adding an element to the last table of an array of tables that is empty")
                    }
                }
                _ => {
                    Err(TomlError::ValueTypeRedefined)
                }
            }
        }
    }
}

fn key_is_already_created_in_table(table: &HashMap<String, TomlValue>, key_index: &[String]) -> bool {
    match key_index {
        [] => { true }
        [key] => {
            table.contains_key(key)
        }
        [key, rest @ ..] => {
            if let Some(TomlValue::Table(subtable)) = table.get(key) {
                key_is_already_created_in_table(subtable, rest)
            } else {
                false
            }
        }
    }
}

pub fn toml_value_from_parser_value(value: parser::Value) -> TomlValue {
    match value.e {
        parser::ValueKind::Integer(x) => {
            TomlValue::Integer(x)
        }
        parser::ValueKind::Float(x) => {
            TomlValue::Float(x)
        }
        parser::ValueKind::Boolean(x) => {
            TomlValue::Boolean(x)
        }
        parser::ValueKind::String(x) => {
            TomlValue::String(x.into_owned())
        }
        parser::ValueKind::Datetime(x) => {
            TomlValue::Datetime(x.to_string())
        }
        parser::ValueKind::Array(x) => {
            TomlValue::Array(x.into_iter().map(|x| toml_value_from_parser_value(x)).collect())
        }
        parser::ValueKind::InlineTable(x) | parser::ValueKind::DottedTable(x) => {
            let mut map = HashMap::new();
            for ((_, key), value) in x.into_iter() {
                map.insert(key.into_owned(), toml_value_from_parser_value(value));
            }
            TomlValue::Table(map)
        }
    }
}

#[derive(Default)]
struct DefinedKeys {
    defined: bool,
    children: HashMap<String, DefinedKeys>
}
impl DefinedKeys {
    fn add_key_index(&mut self, key_index: &[String]) {
        match key_index {
            [] => {
                self.defined = true;
            }
            [key] => {
                let child = self.children.entry(key.to_string()).or_insert_with(|| DefinedKeys::default() );
                child.defined = true;
            }
            [key, rest @ ..] => {
                let child = self.children.entry(key.to_string()).or_insert_with(|| DefinedKeys::default() );
                child.add_key_index(rest);
            }
        }
    }
    fn is_key_index_defined(&self, key_index: &[String]) -> bool {
        match key_index {
            [] => {
                self.defined
            }
            [key] => {
                if let Some(child) = self.children.get(key) {
                    child.defined
                } else {
                    false
                }
            }
            [key, rest @ ..] => {
                if let Some(child) = self.children.get(key) {
                    child.is_key_index_defined(rest)
                } else {
                    false
                }
            }
        }
    }
    fn is_key_or_subkey_defined(&self, key_index: &[String]) -> bool {
        self.defined || match key_index {
            [] => {
                self.defined
            }
            [key] => {
                if let Some(child) = self.children.get(key) {
                    child.defined
                } else {
                    false
                }
            }
            [key, rest @ ..] => {
                if let Some(child) = self.children.get(key) {
                    child.is_key_or_subkey_defined(rest)
                } else {
                    false
                }
            }
        }
    }
    fn forget_subdefinitions_of_key(&mut self, key_index: &[String]) {
        match key_index {
            [] => {
                self.children.clear();
            }
            [key] => {
                if let Some(child) = self.children.get_mut(key) {
                    child.forget_subdefinitions_of_key(&[]);
                } else {
                    
                }
            }
            [key, rest @ ..] => {
                if let Some(child) = self.children.get_mut(key) {
                    child.forget_subdefinitions_of_key(rest);
                } else {
                    
                }
            }
        }
    }
}

pub fn toml_value_from_lines(lines: Vec<parser::Line<'_>>) -> Result<HashMap<String, TomlValue>, TomlError> {
    let mut value = HashMap::<String, TomlValue>::new();

    let mut key_indexes_to_define_at_end_of_table: Vec<Vec<String>> = vec![];
    let mut parent_key_index: Vec<String> = vec![];

    let mut immutable_key_indexes = DefinedKeys::default();
    let mut defined_key_indexes = DefinedKeys::default();

    for line in lines {
        match line {
            parser::Line::Table { at: _, mut header, array } => {
                for key_index in key_indexes_to_define_at_end_of_table.drain(..) {
                    defined_key_indexes.add_key_index(&key_index);
                }
                let mut key_index = vec![];
                while let Some((_, part)) = header.next()? {
                    key_index.push(part.into_owned());
                }
                if immutable_key_indexes.is_key_or_subkey_defined(&key_index) {
                    return Err(TomlError::ChangingInlineTable(key_index.clone()));
                }
                if array {
                    parent_key_index = key_index;
                    immutable_key_indexes.forget_subdefinitions_of_key(&parent_key_index);
                    defined_key_indexes.forget_subdefinitions_of_key(&parent_key_index);
                    defined_key_indexes.add_key_index(&parent_key_index);
                    append_table(&mut value, &parent_key_index)?;
                } else {
                    if defined_key_indexes.is_key_index_defined(&key_index) {
                        return Err(TomlError::KeyRedefined(key_index.clone()))
                    } else {
                        parent_key_index = key_index;
                        defined_key_indexes.add_key_index(&parent_key_index);
                        create_table(&mut value, &parent_key_index)?;
                    }
                }
            
            }
            parser::Line::KeyValue(key, new_value) => {
                let mut key_index = parent_key_index.clone();
                for (_, part) in key.into_iter() {
                    key_index.push(part.into_owned());
                    key_indexes_to_define_at_end_of_table.push(key_index.clone());
                    
                    if defined_key_indexes.is_key_index_defined(&key_index) {
                        return Err(TomlError::KeyRedefined(key_index.clone()))
                    }
                }
                if key_is_already_created_in_table(&value, &key_index) {
                    return Err(TomlError::KeyRedefined(key_index.clone()))
                } else {
                    let top_key_index = key_index.clone();
                    defined_key_indexes.add_key_index(&key_index);
                    if let parser::ValueKind::InlineTable(x) | parser::ValueKind::DottedTable(x) = &new_value.e {
                        immutable_key_indexes.add_key_index(&key_index);
                        for ((_, key), _) in x {
                            key_index.push(key.to_string());
                            immutable_key_indexes.add_key_index(&key_index);
                        }
                    }
                    add_to_table(&mut value, &top_key_index, toml_value_from_parser_value(new_value))?;
                }
            }
        }
    }
    Ok(value)
}