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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
/*
 Cargo KConfig - KConfig parser
 Copyright (C) 2022  Sjoerd van Leent

--------------------------------------------------------------------------------

Copyright Notice: Apache

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

   https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

--------------------------------------------------------------------------------

Copyright Notice: GPLv2

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

--------------------------------------------------------------------------------

Copyright Notice: MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

//! This file implements the registry, which is the main component of the Kconfig
//! representation module.

use kconfig_parser::ast::{parser::ConditionContainer, Container, Element};

use crate::{
    error::Error,
    expr::{Resolver, ReverseDepType},
    menu::Menu,
    Ast, Config, ConfigMutationMode, DescriptorInfo, MenuItem, MenuItemDescriptor, Symbol,
};
use std::{
    collections::{HashMap, HashSet},
    fmt::Display,
    fs::OpenOptions,
    io::{self, BufRead, BufReader, Read, Write},
};

/// The ConfigRegistry is used to create a registry, which allows reading and writing
/// a configuration to and from a .config file as defined by a Kconfig file. To
/// present the menu, a frontend is necessary to represent the state of the registry.
#[derive(Default)]
pub struct ConfigRegistry {
    config_map: HashMap<MenuItemDescriptor, Box<dyn Config>>,
    menu_map: HashMap<MenuItemDescriptor, Box<Menu>>,
    main_menu_descriptor: MenuItemDescriptor,
    is_changed: bool,
    ast: Ast,
    macro_symbols: HashSet<Symbol>,
}

/// A LoadError is returned when during loading of a .config file, errors where found.
/// Typically, this is non-destructive, but an end-user should be warned through the
/// frontend that something went wrong during loading of the .config file.
pub enum LoadError {
    IoError(io::Error),
    Error(Error),
}

impl From<io::Error> for LoadError {
    fn from(e: io::Error) -> Self {
        LoadError::IoError(e)
    }
}

impl From<Error> for LoadError {
    fn from(e: Error) -> Self {
        LoadError::Error(e)
    }
}

impl Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LoadError::IoError(e) => write!(f, "{}", e),
            LoadError::Error(e) => write!(f, "{}", e),
        }
    }
}

impl ConfigRegistry {
    /// Constructs a new configuration registry, given the Abstract syntax tree
    /// as loaded from a kconfig-parser's Ast instance, and the macro symbols
    /// discoverd by the macro lexer (if used).
    pub fn new(ref_ast: &Ast, ref_macro_symbols: &HashSet<Symbol>) -> Result<Self, Error> {
        let (main_menu, configs, mut menus) = Self::build_from_ast(ref_ast)?;
        let main_menu_descriptor = main_menu.descriptor().clone();
        menus.insert(main_menu.descriptor().clone(), Box::new(main_menu));
        let mut registry = ConfigRegistry {
            config_map: configs,
            menu_map: menus,
            main_menu_descriptor,
            is_changed: false,
            ast: ref_ast.clone(),
            macro_symbols: ref_macro_symbols.clone(),
        };
        registry.eval();
        Ok(registry)
    }

    fn build_from_ast(
        ref_ast: &Ast,
    ) -> Result<
        (
            Menu,
            HashMap<MenuItemDescriptor, Box<dyn Config>>,
            HashMap<MenuItemDescriptor, Box<Menu>>,
        ),
        Error,
    > {
        let mut main_menu = Menu {
            name: ref_ast
                .main_menu()
                .unwrap_or(&"ROOT".to_string())
                .to_string(),
            enabled: true,
            menu_items: Vec::new(),
            help: Vec::new(),
        };

        let mut configs: HashMap<MenuItemDescriptor, Box<dyn Config>> = HashMap::new();
        let mut menus: HashMap<MenuItemDescriptor, Box<Menu>> = HashMap::new();

        for name in ref_ast.element_names() {
            let elt = Self::element_from_name_from_ast(&name, &ref_ast)?;
            let (sub_configs, sub_menus) = main_menu.build_from_elt(&elt, ref_ast)?;
            configs.extend(sub_configs);
            menus.extend(sub_menus);
        }

        let (cond_configs, cond_menus) =
            main_menu.build_from_conditional_blocks(&ref_ast.conditional_blocks(), ref_ast)?;
        configs.extend(cond_configs);
        menus.extend(cond_menus);

        Ok((main_menu, configs, menus))
    }

    fn element_from_name_from_ast(name: &str, ast: &Ast) -> Result<Element, Error> {
        match ast.element(&name) {
            Some(elt) => Ok(elt.clone()),
            None => Err(Error::from(format!(
                "Element with item {} disappeared?",
                name
            ))),
        }
    }

    /// Retrieves the name of the main menu. This serves two purposes:
    /// 1.  It acquires the name for display in the User Interface
    /// 2.  It acquires a needle to find the underlying menu
    pub fn main_menu_name(&self) -> String {
        self.main_menu_descriptor.to_string()
    }

    /// Looks up an internal configuration item as mutable, boxed reference
    pub fn lookup_config_mut(&mut self, config_item_name: &str) -> Option<&mut Box<dyn Config>> {
        self.config_map
            .get_mut(&MenuItemDescriptor::Config(config_item_name.to_string()))
    }

    /// Looks up an internal configuration as boxed referende
    pub fn lookup_config(&self, config_item_name: &str) -> Option<&Box<dyn Config>> {
        self.config_map
            .get(&MenuItemDescriptor::Config(config_item_name.to_string()))
    }

    /// Looks an internal (sub)menu as mutable, boxed reference
    pub fn lookup_menu_mut(&mut self, menu_item_name: &str) -> Option<&mut Box<Menu>> {
        self.menu_map
            .get_mut(&MenuItemDescriptor::Menu(menu_item_name.to_string()))
    }

    /// Looks up an internal (sub)menu as boxed referende
    pub fn lookup_menu(&self, menu_item_name: &str) -> Option<&Box<Menu>> {
        self.menu_map
            .get(&MenuItemDescriptor::Menu(menu_item_name.to_string()))
    }

    /// Finds the prompt of the given configuration item. If no prompt is
    /// found, simply returns the content of the given configuration item
    /// name.
    pub fn config_prompt(&self, config_item_name: &str) -> String {
        self.lookup_config(config_item_name)
            .map(|c| c.prompt())
            .unwrap_or_default()
    }

    /// Returns the length of the children of the given (sub)menu
    pub fn menu_children_len(&self, menu_name: &str) -> usize {
        self.lookup_menu(menu_name)
            .map(|m| m.len())
            .unwrap_or_default()
    }

    /// Returns the length of the children of the given (sub)menu which
    /// are enabled.
    pub fn menu_enabled_children_len(&self, menu_name: &str) -> usize {
        let menu = self.lookup_menu(menu_name);
        let result = match menu {
            Some(menu) => menu
                .sub_descriptors()
                .map(|d| match d {
                    MenuItemDescriptor::Config(name) => self
                        .lookup_config(&name)
                        .map(|c| c.enabled())
                        .unwrap_or_default(),
                    MenuItemDescriptor::Menu(name) => self
                        .lookup_menu(&name)
                        .map(|c| c.enabled())
                        .unwrap_or_default(),
                })
                .filter(|m| *m == true)
                .collect::<Vec<bool>>()
                .len(),
            None => 0,
        };
        result
    }

    /// Returns if a menu item is enabled, given a descriptor of the
    /// menu item.
    pub fn menu_item_enabled(&self, descriptor: &MenuItemDescriptor) -> bool {
        match descriptor {
            MenuItemDescriptor::Config(name) => self
                .lookup_config(name)
                .map(|m| m.enabled())
                .unwrap_or_default(),
            MenuItemDescriptor::Menu(name) => self
                .lookup_menu(name)
                .map(|m| m.enabled())
                .unwrap_or_default(),
        }
    }

    /// Returns and iterator of the descriptors of children of a menu item
    /// with the given menu name, which are enabled.
    pub fn iter_enabled_sub_descriptors(
        &self,
        menu_name: &str,
    ) -> Box<dyn Iterator<Item = MenuItemDescriptor>> {
        let menu = self.lookup_menu(menu_name);
        Box::new(
            menu.map(|m| m.sub_descriptors())
                .unwrap_or(Box::new(Vec::new().into_iter()))
                .filter(|d| self.menu_item_enabled(d))
                .collect::<Vec<MenuItemDescriptor>>()
                .into_iter(),
        )
    }

    /// Returns the value as a string of the spefic menu item described by the
    /// descriptor.
    pub fn menu_item_string(&self, descriptor: &MenuItemDescriptor) -> String {
        match descriptor {
            MenuItemDescriptor::Config(name) => self
                .lookup_config(name)
                .map(|c| c.to_string())
                .unwrap_or_default(),
            MenuItemDescriptor::Menu(name) => self
                .lookup_menu(name)
                .map(|c| c.to_string())
                .unwrap_or_default(),
        }
    }

    /// Returns the menu item's descriptor information, containing the Help text
    /// belonging to the given menu item indicated by the descriptor.
    pub fn descriptor_info(&self, descriptor: &MenuItemDescriptor) -> DescriptorInfo {
        match descriptor {
            MenuItemDescriptor::Config(name) => self
                .lookup_config(name)
                .map(|c| DescriptorInfo::new(c.info(), descriptor))
                .unwrap_or_default(),
            MenuItemDescriptor::Menu(name) => self
                .lookup_menu(name)
                .map(|c| DescriptorInfo::new(c.info(), descriptor))
                .unwrap_or_default(),
        }
    }

    fn eval(&mut self) {
        let ast = self.ast.clone();
        let macro_symbols = self.macro_symbols.clone();
        let config_string_values: HashMap<String, String> = self
            .config_map
            .iter()
            .map(|(d, c)| (d.to_string(), c.to_string_value()))
            .collect();

        self.menu_map.iter_mut().for_each(|(descriptor, menu)| {
            let resolver = Resolver::new(descriptor, &ast, &&macro_symbols, &config_string_values);
            menu.enable(resolver.eval_enabled());
        });
        self.config_map.iter_mut().for_each(|(descriptor, config)| {
            let resolver = Resolver::new(descriptor, &ast, &&macro_symbols, &config_string_values);
            config.default_from_string_value(resolver.eval_default());
            config.enable(resolver.eval_enabled());
            config.select(resolver.eval_reverse_dep(ReverseDepType::Select));
            config.imply(resolver.eval_reverse_dep(ReverseDepType::Imply));
        });
    }

    /// Mutates an item by stepping to the next value, this is used for values
    /// which can easily be toggled (such as a boolean configuration item).
    pub fn mutate_through_step(&mut self, config_item_name: &str) -> Result<(), Error> {
        self.is_changed = true;
        let opt_config = self.lookup_config_mut(config_item_name);
        if let Some(config) = opt_config {
            if config.mutation_mode() == ConfigMutationMode::ThroughStep {
                config.next_step()?;
                Ok(self.eval())
            } else {
                Err(Error::from(format!(
                    "Can not configure {} through string",
                    config_item_name
                )))
            }
        } else {
            Err(Error::from(format!(
                "Configuration item {} not found",
                config_item_name
            )))
        }
    }

    /// Mutates an item by loading a string value into the configuration item.
    /// Only configuration items which support the ConfigMutationMode::ThroughString
    /// are capable of loading a configuration through a string.
    pub fn mutate_through_string(
        &mut self,
        config_item_name: &str,
        string_value: &str,
    ) -> Result<(), Error> {
        self.is_changed = true;
        let opt_config = self.lookup_config_mut(config_item_name);
        if let Some(config) = opt_config {
            if let ConfigMutationMode::ThroughString(_) = config.mutation_mode() {
                config.as_mut().from_string_value(string_value);
                Ok(self.eval())
            } else {
                Err(Error::from(format!(
                    "Can not configure {} through string",
                    config_item_name
                )))
            }
        } else {
            return Err(Error::from(format!(
                "Configuration item {} not found",
                config_item_name
            )));
        }
    }

    /// Returns the mutation mode of a specific configuration item.
    pub fn config_mutation_mode(&self, config_item_name: &str) -> ConfigMutationMode {
        let opt_config = self.lookup_config(config_item_name);
        opt_config
            .map(|c| c.mutation_mode())
            .unwrap_or(ConfigMutationMode::None)
    }

    /// Returns the value of a specific configuration item.
    pub fn config_value(&self, config_item_name: &str) -> String {
        let opt_config = self.lookup_config(config_item_name);
        opt_config.map(|c| c.to_string_value()).unwrap_or_default()
    }

    /// Called from the user interface to notify a change should be
    /// propagated to all configuration items present.
    pub fn changed(&self) -> bool {
        self.is_changed
    }

    /// Recursively gets a (sub)menu from the current menu element by
    /// looking up the menu by name
    pub fn find_parent_menu(&self, menu_item: &MenuItemDescriptor) -> Option<MenuItemDescriptor> {
        self.lookup_menu(&self.main_menu_descriptor.to_string())
            .map(|m| self.walk_menu_by_name_recursive(m, menu_item))
            .flatten()
    }

    /// Checks if the given descriptor of the given (sub)menu is using
    /// the default value or not (where applicable).
    pub fn has_default_value_set(&self, descriptor: &MenuItemDescriptor) -> Option<bool> {
        match descriptor {
            MenuItemDescriptor::Config(config_item_name) => {
                let config = self.lookup_config(config_item_name);
                match config {
                    Some(c) => Some(c.value_is_default()),
                    _ => None,
                }
            }
            _ => None,
        }
    }

    fn walk_menu_by_name_recursive(
        &self,
        current_menu: &Box<Menu>,
        menu_item: &MenuItemDescriptor,
    ) -> Option<MenuItemDescriptor> {
        for inner_descriptor in current_menu.sub_descriptors() {
            if *menu_item == inner_descriptor {
                return Some(current_menu.descriptor());
            }
            for (descriptor, menu) in &self.menu_map {
                if descriptor.clone() == inner_descriptor {
                    let result = self.walk_menu_by_name_recursive(menu, &menu_item);
                    if let Some(name) = result {
                        return Some(name);
                    }
                }
            }
        }
        None
    }

    /// Writes the current configuration known to the configuration registry
    /// into a file, typically this file has the file name ".config"
    pub fn write_dotconfig_file(&self, dotconfig_filename: &str) -> Result<(), Error> {
        let mut f = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(dotconfig_filename)?;
        f.write("#\n".as_bytes())?;
        f.write("# Automatically generated file; DO NOT EDIT\n".as_bytes())?;
        f.write("# ".as_bytes())?;
        match self.write_dotconfig(&mut f) {
            Ok(_) => Ok(()),
            Err(e) => Err(Error::from(format!(
                "Saving configuration to: {} failed - {}",
                dotconfig_filename, e
            ))),
        }
    }

    /// Writes the current configuration known to the configuration registry
    /// into a Write trait supporting type.
    pub fn write_dotconfig(&self, output: &mut dyn Write) -> Result<(), Error> {
        output.write(self.main_menu_descriptor.to_string().as_bytes())?;
        output.write("\n#\n\n".as_bytes())?;
        Ok(self.recursively_write_dotconfig(
            &self.main_menu_descriptor.to_string(),
            output,
            false,
        )?)
    }

    fn recursively_write_dotconfig(
        &self,
        menu_name: &str,
        output: &mut dyn Write,
        all_disabled: bool,
    ) -> Result<(), io::Error> {
        for descriptor in self.lookup_menu(menu_name).unwrap().sub_descriptors() {
            match descriptor {
                MenuItemDescriptor::Config(name) => {
                    let config = self.lookup_config(&name).unwrap();
                    if !config.enabled() || all_disabled {
                        output.write("#".as_bytes())?;
                        output.write(name.to_string().as_bytes())?;
                        output.write("=is not set".as_bytes())?;
                    } else {
                        output.write(name.to_string().as_bytes())?;
                        output.write("=".as_bytes())?;
                        output.write(config.as_dot_config().as_bytes())?;
                    }
                    output.write("\n".as_bytes())?;
                }
                MenuItemDescriptor::Menu(name) => {
                    let menu = self.lookup_menu(&name).unwrap();
                    if menu.enabled() {
                        output.write(format!("\n# Menu: {}\n", name).as_bytes())?;
                        self.recursively_write_dotconfig(&name, output, all_disabled)?;
                    } else {
                        output.write(format!("\n# Menu: {} is not enabled\n", name).as_bytes())?;
                        self.recursively_write_dotconfig(&name, output, true)?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Reads the saved configuration from a file, typically this file has
    /// the file name ".config", and mutates the configuration registry
    /// accordingly.
    pub fn read_dotconfig_file(&mut self, dotconfig_filename: &str) -> Result<(), LoadError> {
        let mut f = match OpenOptions::new().read(true).open(dotconfig_filename) {
            Ok(f) => f,
            Err(e) => {
                return Err(LoadError::from(Error::from(format!(
                    "⛔ Can not read {} - {}",
                    dotconfig_filename, e
                ))));
            }
        };

        self.read_dotconfig(&mut f)
    }

    /// Reads the saved configuration from a Read trait supporting type,
    /// and mutates the configuration registry accordingly.
    pub fn read_dotconfig(&mut self, input: &mut dyn Read) -> Result<(), LoadError> {
        let reader = BufReader::new(input);
        let lines = reader.lines();
        let result = self.read_dotconfig_by_line(lines);
        self.eval();
        result
    }

    fn read_dotconfig_by_line(
        &mut self,
        lines: io::Lines<BufReader<&mut dyn Read>>,
    ) -> Result<(), LoadError> {
        let mut invalid_lines: Vec<(String, String)> = Vec::new();

        for line in lines {
            // Get the actual content of the line or return an error
            let line = line?;

            // Trim the line such that it begins with a valid character
            let line = line.trim();

            // If the line is empty, skip it
            if line.is_empty() {
                continue;
            }

            // If the line starts with a pund/hash symbol, it is a comment
            // skip it.
            if line.starts_with('#') {
                continue;
            }

            // LHS receives the name of the descriptor and RHS receives
            // the actual value.
            let mut lhs = String::new();
            let mut rhs = String::new();
            let mut invalid = false;
            let mut finished = false;
            let mut in_string = false;
            let mut escape = false;

            // Altough reading a line might fail, the process will continue
            // and simply skip the current value.
            #[derive(Debug)]
            enum MachineState {
                Start,
                Lhs,
                Assign,
                StartRhs,
                Rhs,
                End,
            }

            let mut state = MachineState::Start;
            for c in line.chars() {
                if !invalid && !finished {
                    match state {
                        MachineState::Start => {
                            if !c.is_whitespace() && c != '=' && c != '#' {
                                state = MachineState::Lhs;
                                lhs.push(c);
                            } else if c.is_whitespace() {
                                // Skip the current value
                            } else {
                                // This line is illegal
                                invalid = true;
                            }
                        }
                        MachineState::Lhs => {
                            if !c.is_whitespace() && c != '=' {
                                lhs.push(c);
                            } else if c.is_whitespace() {
                                state = MachineState::Assign;
                            } else if c == '=' {
                                state = MachineState::StartRhs;
                            } else {
                                invalid = true;
                            }
                        }
                        MachineState::Assign => {
                            if c.is_whitespace() {
                                // Skip the current value
                            } else if c == '=' {
                                state = MachineState::StartRhs;
                            } else {
                                invalid = true;
                            }
                        }
                        MachineState::StartRhs => {
                            if !c.is_whitespace() && c != '#' {
                                state = MachineState::Rhs;
                                if c == '"' {
                                    in_string = true;
                                }
                                rhs.push(c);
                            } else if c.is_whitespace() {
                                // Skip the current value
                            } else {
                                // The value is empty
                                finished = true;
                            }
                        }
                        MachineState::Rhs => {
                            if c == '"' {
                                if in_string && !escape {
                                    in_string = false;
                                    rhs.push(c);
                                } else if in_string && escape {
                                    rhs.push(c);
                                } else if !in_string {
                                    in_string = true;
                                    rhs.push(c);
                                } else {
                                    invalid = true;
                                }
                            } else if c == '\\' {
                                if escape && in_string {
                                    rhs.push(c);
                                    escape = false;
                                } else if in_string {
                                    escape = true;
                                } else {
                                    rhs.push(c);
                                }
                            } else if !c.is_whitespace() && !in_string && c != '#' || in_string {
                                rhs.push(c);
                            } else if c.is_whitespace() {
                                state = MachineState::End;
                            } else if c == '#' {
                                finished = true;
                            } else {
                                invalid = true;
                            }
                        }
                        MachineState::End => {
                            if c.is_whitespace() {
                                // Ignore
                            } else if c == '#' {
                                finished = true;
                            } else {
                                invalid = true;
                            }
                        }
                    }
                }
            }

            if !escape && !invalid {
                let opt_config = self.lookup_config_mut(&lhs);
                match opt_config {
                    Some(config) => match config.from_dot_config(&rhs) {
                        Ok(_) => (),
                        Err(e) => invalid_lines.push((e, line.to_string())),
                    },
                    None => {
                        if self.main_menu_name() != line {
                            invalid_lines.push((
                                format!("Name {} not found for configuration", lhs),
                                line.to_string(),
                            ));
                        }
                    }
                }
            } else {
                invalid_lines.push(("Invalid syntax".to_owned(), line.to_string()));
            }
        }

        match invalid_lines.is_empty() {
            true => Ok(()),
            false => Err(LoadError::from(Error::from(invalid_lines))),
        }
    }
}