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
719
720
721
722
723
724
725
726
/*
 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 contains the implementation of a configuration item for the
//! different types of objects which can be created.

use crate::{
    Config, ConfigMutationMode, DotConfig, Error, Hex, InputMode, MenuItem, MenuItemDescriptor,
    StringValue, Tristate,
};
use kconfig_parser::{
    ast::{ConfigType, Element},
    escape_string, parse_string,
};
use std::fmt::Display;

/// Represents a configuration item as defined by the Abstract Syntax
/// Tree, received from the kconfig-parser module.
#[derive(Clone, Debug)]
pub struct ConfigItem<T> {
    /// The name of the configuration item
    name: String,

    /// The prompt (or display) of the configuration item
    prompt: String,

    /// Whether the configuration item is enabled, this can either
    /// be true because of a dependency being true or be true because
    /// of a conditional being true.
    enabled: bool,

    /// Value of the configuration item
    value: T,

    /// The default value of the configuration item, where available
    default_value: Option<T>,

    /// THe help value of the configuration item, if not available,
    /// it will be an empty vectgor.
    help: Vec<String>,
}

pub(crate) fn new_config(config_type: &ConfigType, elt: &Element) -> Box<dyn Config> {
    match config_type {
        ConfigType::Bool => new_boxed::<bool>(elt),
        ConfigType::Tristate => new_boxed::<Tristate>(elt),
        ConfigType::String => new_boxed::<String>(elt),
        ConfigType::Int => new_boxed::<i64>(elt),
        ConfigType::Hex => new_boxed::<Hex>(elt),
    }
}

fn new_boxed<T: 'static>(elt: &Element) -> Box<dyn Config>
where
    ConfigItem<T>: Config,
    T: Default,
{
    Box::new(ConfigItem::<T>::new(elt))
}

impl<T> ConfigItem<T>
where
    T: Default + 'static,
{
    pub(crate) fn new(elt: &Element) -> Self {
        Self {
            name: elt.name(),
            prompt: elt.prompt().unwrap_or(elt.name()),
            enabled: true,
            value: T::default(),
            default_value: Some(T::default()),
            help: elt.help().iter().cloned().collect(),
        }
    }
}

/// Implements the Named type generically for all generic
/// configuration item types.
impl<T> MenuItem for ConfigItem<T> {
    /// Returns the name of the configuration item
    fn descriptor(&self) -> MenuItemDescriptor {
        MenuItemDescriptor::Config(self.name.to_string())
    }

    /// Returns whether the configuration item is enabled
    fn enabled(&self) -> bool {
        return self.enabled;
    }

    /// Sets the configuration item to be enabled
    fn enable(&mut self, flag: bool) {
        self.enabled = flag;
    }

    /// Returns the item's help text (if present). If not present, should
    /// return an empty string instead.
    fn info(&self) -> Vec<String> {
        self.help.clone()
    }
}

impl StringValue for ConfigItem<String> {
    /// Formats the value of the configuration item as
    /// a string.
    fn to_string_value(&self) -> String {
        format!("{}", self.value)
    }

    fn from_string_value(&mut self, v: &str) {
        self.value = v.to_string();
    }

    fn default_from_string_value(&mut self, opt_v: Option<String>) {
        if let Some(v) = &opt_v {
            if Some(self.value.clone()) == self.default_value {
                self.value = v.clone();
            }
        }
        self.default_value = opt_v.clone();
    }

    fn default_to_string_value(&self) -> Option<String> {
        self.default_value.clone()
    }
}

/// Implements the read and write to and from a dot configuration
/// file from or to the configuration item
impl DotConfig for ConfigItem<String> {
    /// Returns the representation of the configuration item into
    /// the configuration file.
    fn as_dot_config(&self) -> String {
        eprintln!("{:?}", self);
        match self.enabled() {
            true => format!("{}", escape_string(&self.value)),
            false => format!("is not set"),
        }
    }

    /// Loads the representation in the configurtion file back
    /// into the configuration item
    fn from_dot_config(&mut self, s: &str) -> Result<(), String> {
        let result = parse_string(s)?;
        self.value = result;
        Ok(())
    }
}

/// Implements the display routine for the configuration item
impl Display for ConfigItem<String> {
    /// Formats the display for the configuration item
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.value.is_empty() {
            f.write_str(&format!("{}", self.prompt))
        } else {
            f.write_str(&format!("{}: {}", self.prompt, self.value))
        }
    }
}

impl Config for ConfigItem<String> {
    fn mutation_mode(&self) -> crate::ConfigMutationMode {
        crate::ConfigMutationMode::ThroughString(InputMode::String)
    }

    fn prompt(&self) -> String {
        self.prompt.to_string()
    }
}

impl StringValue for ConfigItem<bool> {
    /// Formats the value of the configuration item as
    /// a string.
    fn to_string_value(&self) -> String {
        match self.value {
            true => "y".to_owned(),
            false => "n".to_owned(),
        }
    }

    fn from_string_value(&mut self, v: &str) {
        self.value = v == "y";
    }

    fn default_from_string_value(&mut self, v: Option<String>) {
        if let Some(s) = v {
            if s == "y" || s == "n" {
                let new_default_value = s == "y";

                if Some(self.value.clone()) == self.default_value {
                    self.value = new_default_value;
                }

                self.default_value = Some(new_default_value);
            } else {
                self.default_value = None;
            }
        } else {
            self.default_value = None;
        }
    }

    fn default_to_string_value(&self) -> Option<String> {
        self.default_value.map(|b| match b {
            true => "y".to_owned(),
            false => "n".to_owned(),
        })
    }
}

/// Implements the read and write to and from a dot configuration
/// file from or to the configuration item
impl DotConfig for ConfigItem<bool> {
    /// Returns the representation of the configuration item into
    /// the configuration file.
    fn as_dot_config(&self) -> String {
        match self.enabled() {
            true => match self.value {
                true => "y".to_owned(),
                false => "n".to_owned(),
            },
            false => format!("is not set"),
        }
    }

    /// Loads the representation in the configurtion file back
    /// into the configuration item
    fn from_dot_config(&mut self, s: &str) -> Result<(), String> {
        self.value = s.trim() == "y";
        Ok(())
    }
}

/// Implements the display routine for the configuration item
impl Display for ConfigItem<bool> {
    /// Formats the display for the configuration item
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.value {
            true => f.write_str(&format!("{}: yes", self.prompt)),
            false => f.write_str(&format!("{}: no", self.prompt)),
        }
    }
}

impl Config for ConfigItem<bool> {
    fn mutation_mode(&self) -> ConfigMutationMode {
        ConfigMutationMode::ThroughStep
    }

    fn next_step(&mut self) -> Result<(), Error> {
        self.value = !self.value;
        Ok(())
    }

    fn prompt(&self) -> String {
        self.prompt.to_string()
    }

    /// Sets the selected flag, if the item is to be selected
    /// with the given value for flag.
    /// Only applicable to items which are of type bool or
    /// tristate.
    fn select(&mut self, flag: Option<Tristate>) {
        if let Some(tristate) = flag {
            if tristate == Tristate::TRUE || tristate == Tristate::MAYBE {
                self.value = true;
            }
        }
    }

    /// Sets the implied flag, if the item is to be implied.
    /// Only applicatie to items which are of type bool or tristate.
    /// The item's value is not force fully set, but can be set
    /// depending on the value of the flag.
    fn imply(&mut self, flag: Option<Tristate>) {
        // If the default value - where applicable - overrides
        // the implied value.

        match &self.default_value {
            None => {
                if let Some(tristate) = flag {
                    if tristate == Tristate::TRUE || tristate == Tristate::MAYBE {
                        self.value = true;
                    }
                }
            }
            Some(_) => (),
        }
    }
}

impl StringValue for ConfigItem<Tristate> {
    /// Formats the value of the configuration item as
    /// a string.
    fn to_string_value(&self) -> String {
        match self.value {
            Tristate::TRUE => "y".to_owned(),
            Tristate::FALSE => "n".to_owned(),
            Tristate::MAYBE => "m".to_owned(),
        }
    }

    fn from_string_value(&mut self, v: &str) {
        self.value = if v == "y" {
            Tristate::TRUE
        } else if v == "m" {
            Tristate::MAYBE
        } else {
            Tristate::FALSE
        }
    }

    fn default_from_string_value(&mut self, v: Option<String>) {
        if let Some(s) = v {
            let new_default_value = if s == "y" {
                Some(Tristate::TRUE)
            } else if s == "m" {
                Some(Tristate::MAYBE)
            } else if s == "n" {
                Some(Tristate::FALSE)
            } else {
                None
            };

            if let Some(v) = &new_default_value {
                if Some(self.value) == self.default_value {
                    self.value = *v;
                }
            }

            self.default_value = new_default_value;
        } else {
            self.default_value = None;
        }
    }

    fn default_to_string_value(&self) -> Option<String> {
        self.default_value.map(|b| match b {
            Tristate::TRUE => "y".to_owned(),
            Tristate::FALSE => "n".to_owned(),
            Tristate::MAYBE => "m".to_owned(),
        })
    }
}

/// Implements the read and write to and from a dot configuration
/// file from or to the configuration item
impl DotConfig for ConfigItem<Tristate> {
    /// Returns the representation of the configuration item into
    /// the configuration file.
    fn as_dot_config(&self) -> String {
        match self.enabled() {
            true => match self.value {
                Tristate::TRUE => "y".to_owned(),
                Tristate::FALSE => "n".to_owned(),
                Tristate::MAYBE => "m".to_owned(),
            },
            false => format!("is not set"),
        }
    }

    /// Loads the representation in the configurtion file back
    /// into the configuration item
    fn from_dot_config(&mut self, s: &str) -> Result<(), String> {
        match s.trim() {
            "y" => self.value = Tristate::TRUE,
            "m" => self.value = Tristate::MAYBE,
            _ => self.value = Tristate::FALSE,
        }
        Ok(())
    }
}

/// Implements the display routine for the configuration item
impl Display for ConfigItem<Tristate> {
    /// Formats the display for the configuration item
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.value {
            Tristate::TRUE => f.write_str(&format!("{}: yes", self.prompt)),
            Tristate::FALSE => f.write_str(&format!("{}: no", self.prompt)),
            Tristate::MAYBE => f.write_str(&format!("{}: maybe", self.prompt)),
        }
    }
}

impl Config for ConfigItem<Tristate> {
    fn mutation_mode(&self) -> ConfigMutationMode {
        ConfigMutationMode::ThroughStep
    }

    fn next_step(&mut self) -> Result<(), Error> {
        self.value = match self.value {
            Tristate::FALSE => Tristate::MAYBE,
            Tristate::MAYBE => Tristate::TRUE,
            Tristate::TRUE => Tristate::FALSE,
        };
        Ok(())
    }

    fn prompt(&self) -> String {
        self.prompt.to_string()
    }

    /// Sets the selected flag, if the item is to be selected
    /// with the given value for flag.
    /// Only applicable to items which are of type bool or
    /// tristate.
    fn select(&mut self, flag: Option<Tristate>) {
        if let Some(tristate) = flag {
            if tristate == Tristate::TRUE {
                self.value = Tristate::TRUE;
            } else if tristate == Tristate::MAYBE && self.value == Tristate::FALSE {
                self.value = Tristate::MAYBE;
            }
        }
    }

    /// Sets the implied flag, if the item is to be implied.
    /// Only applicatie to items which are of type bool or tristate.
    /// The item's value is not force fully set, but can be set
    /// depending on the value of the flag.
    fn imply(&mut self, flag: Option<Tristate>) {
        // If the default value - where applicable - overrides
        // the implied value.

        match &self.default_value {
            None => {
                if let Some(tristate) = flag {
                    if tristate == Tristate::TRUE {
                        self.value = Tristate::TRUE;
                    } else if tristate == Tristate::MAYBE && self.value == Tristate::FALSE {
                        self.value = Tristate::MAYBE;
                    }
                }
            }
            Some(_) => (),
        }
    }
}

// Section only applicable to configuration item for positive integers

/// Methods applicable only for configuration item for positive integers
impl ConfigItem<i64> {
    fn value_from_string_err(&mut self, s: &str) -> Result<i64, String> {
        let mut result: i64 = 0;
        let s = s.trim();

        if s.is_empty() {
            return Err("No value specified {}".to_owned());
        }

        // First check if there is a sign bit
        let chars = s.chars().collect::<Vec<char>>();
        let negative = chars[0] == '-';

        if negative && chars.len() <= 1 {
            return Err("No integer value found after negative sign".to_owned());
        };

        let mut skip = negative;

        for c in chars {
            if skip {
                skip = false;
                continue;
            }
            if c.is_ascii_digit() {
                eprintln!("Current result = {}, c = {}", result, c);
                result *= 10;

                let value = (c as u8 - ('0' as u8)) as i64;
                if negative {
                    result -= value;
                } else {
                    result += value;
                }
            } else {
                return Err(format!("Character {} not an ASCII digit", c));
            }
        }

        Ok(result)
    }
}

impl StringValue for ConfigItem<i64> {
    /// Formats the value of the configuration item as
    /// a string.
    fn to_string_value(&self) -> String {
        format!("{}", self.value)
    }

    /// Saves the value of the int configuration item from
    /// a string. If it is not representing an int, it should silently fail.
    fn from_string_value(&mut self, v: &str) {
        let result = self.value_from_string_err(&v);
        match result {
            Ok(v) => self.value = v,
            Err(_) => (),
        }
    }

    fn default_from_string_value(&mut self, v: Option<String>) {
        if let Some(s) = v {
            let new_default_value = self.value_from_string_err(&s).ok();

            if let Some(v) = &new_default_value {
                if Some(self.value.clone()) == self.default_value {
                    self.value = v.clone();
                }
            }

            self.default_value = new_default_value;
        } else {
            self.default_value = None;
        }
    }

    fn default_to_string_value(&self) -> Option<String> {
        self.default_value.map(|b| format!("{}", b))
    }
}

/// Implements the read and write to and from a dot configuration
/// file from or to the configuration item
impl DotConfig for ConfigItem<i64> {
    /// Returns the representation of the configuration item into
    /// the configuration file.
    fn as_dot_config(&self) -> String {
        match self.enabled() {
            true => format!("{}", self.value),
            false => format!("is not set"),
        }
    }

    /// Loads the representation in the configurtion file back
    /// into the configuration item
    fn from_dot_config(&mut self, s: &str) -> Result<(), String> {
        Ok(self.value = self.value_from_string_err(s)?)
    }
}

/// Implements the display routine for the configuration item
impl Display for ConfigItem<i64> {
    /// Formats the display for the configuration item
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!("{}: {}", self.prompt, self.value))
    }
}

impl Config for ConfigItem<i64> {
    fn mutation_mode(&self) -> ConfigMutationMode {
        ConfigMutationMode::ThroughString(InputMode::Int)
    }

    fn prompt(&self) -> String {
        self.prompt.to_string()
    }
}

impl StringValue for ConfigItem<Hex> {
    /// Formats the value of the configuration item as
    /// a string.
    fn to_string_value(&self) -> String {
        format!("{}", self.value)
    }

    /// Saves the value of the int configuration item from
    /// a string. If it is not representing an int, it should silently fail.
    fn from_string_value(&mut self, v: &str) {
        let result = self.value_from_string_err(v);
        match result {
            Ok(v) => self.value = v,
            Err(_) => (),
        }
    }

    fn default_from_string_value(&mut self, v: Option<String>) {
        if let Some(s) = v {
            let new_default_value = self.value_from_string_err(&s).ok();

            if let Some(v) = &new_default_value {
                if Some(self.value) == self.default_value {
                    self.value = *v;
                }
            }

            self.default_value = new_default_value;
        } else {
            self.default_value = None;
        }
    }

    fn default_to_string_value(&self) -> Option<String> {
        self.default_value.map(|b| format!("{}", b))
    }
}

/// Methods applicable only for configuration item for positive, hexadecimal integers
impl ConfigItem<Hex> {
    fn value_from_string_err(&mut self, s: &str) -> Result<Hex, String> {
        if s.len() < 2 {
            return Err(format!("Value {} does not have a hexadecimal prefix", s));
        }

        let mut chars = s.trim().chars();

        let prefix_1 = chars.nth(0);
        let prefix_2 = chars.nth(0);

        if prefix_1 != Some('0') && (prefix_2 != Some('x') || prefix_2 != Some('X')) {
            return Err(format!("Value {} does not have a hexadecimal prefix", s));
        }

        let mut result: u64 = 0;

        for c in chars {
            if c.is_ascii_hexdigit() {
                result <<= 4;
                if c.is_ascii_digit() {
                    result += (c as u8 - ('0' as u8)) as u64;
                } else if c >= 'A' && c <= 'F' {
                    result += (c as u8 - ('A' as u8) + 0xA) as u64;
                } else {
                    result += (c as u8 - ('a' as u8) + 0xA) as u64;
                }
            } else {
                return Err(format!("Character {} not an ASCII digit", c));
            }
        }
        Ok(Hex(result))
    }
}

// Implements the read and write to and from a dot configuration
/// file from or to the configuration item
impl DotConfig for ConfigItem<Hex> {
    /// Returns the representation of the configuration item into
    /// the configuration file.
    fn as_dot_config(&self) -> String {
        match self.enabled() {
            true => format!("{}", self.value),
            false => format!("is not set"),
        }
    }

    /// Loads the representation in the configurtion file back
    /// into the configuration item
    fn from_dot_config(&mut self, s: &str) -> Result<(), String> {
        Ok(self.value = self.value_from_string_err(s)?)
    }
}

/// Implements the display routine for the configuration item
impl Display for ConfigItem<Hex> {
    /// Formats the display for the configuration item
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!("{}: {}", self.prompt, self.value))
    }
}

impl Config for ConfigItem<Hex> {
    fn mutation_mode(&self) -> ConfigMutationMode {
        ConfigMutationMode::ThroughString(InputMode::Hex)
    }

    fn prompt(&self) -> String {
        self.prompt.to_string()
    }
}