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
/*
 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::Info;
use crate::Tristate;
use crate::Variant;
use crate::VariantDataType;
use crate::{
    ast_extra::AstExtra,
    dependencies::{ItemDependency, ResolvedExpr, SelectAndImplyDependencyResolver},
    ItemReference,
};
use kconfig_parser::{
    ast::{
        parser::{ConditionContainer, Container, ElementType},
        ConfigType, Dependency, Element,
    },
    Ast, Symbol,
};
use std::{
    collections::{HashMap, HashSet},
    hash::Hash,
};

#[derive(Debug, Clone)]
pub struct Item {
    /// The name (if any) of the menu item
    name: String,

    /// Whether the menu is to be enabled
    enabled: bool,

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

    /// The parent of the current item, if any
    parent: Option<String>,

    /// Registers conditions (if statements surrounding the item)
    conditions: HashSet<Dependency>,

    /// Registers the element belonging to the item (if any)
    maybe_elt: Option<Element>,

    // The macro symbols are a pre-evaluated set of symbols, which have been evaluated
    // and can be used in evaluation cycles as fixed dependencies or conditional
    // statements
    macro_symbols: HashSet<Symbol>,

    // The configuration item associated to the item, if any. If the item describes
    // a "menu", a configuration item will not be associated. if it describes a "menuconfig"
    // of "config", a configuration item will be associated.
    config_items: HashMap<ConfigType, ConfigItem>,

    // The dependency map, which contains the ItemReferences of the items
    // which the current item depends on using the "depends on" relationship.
    dependencies: HashSet<ItemDependency>,

    // Backward dependencies of which the items select me
    selects_me: HashMap<String, Option<ResolvedExpr>>,

    // Backward dependencies of which the items imply me
    imply_me: HashMap<String, Option<ResolvedExpr>>,

    // Forward dependencies of which the items are selected by me
    selected: HashMap<String, Option<ResolvedExpr>>,

    // Forward dependencies of which the items are implied by me
    implied: HashMap<String, Option<ResolvedExpr>>,
}

impl PartialEq for Item {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.enabled == other.enabled
            && self.help == other.help
            && self.parent == other.parent
            && self.conditions == other.conditions
            && self.maybe_elt == other.maybe_elt
    }
}
impl Eq for Item {}

impl Item {
    fn new(name: &str, macro_symbols: &HashSet<Symbol>) -> Self {
        let name = name.to_string();
        Self {
            name,
            enabled: true,
            help: vec![],
            conditions: HashSet::new(),
            parent: None,
            maybe_elt: None,
            macro_symbols: macro_symbols.clone(),
            config_items: HashMap::new(),
            dependencies: HashSet::new(),
            selects_me: HashMap::new(),
            imply_me: HashMap::new(),
            selected: HashMap::new(),
            implied: HashMap::new(),
        }
    }

    pub(crate) fn new_from_ast(
        main_menu_name: &str,
        macro_symbols: &HashSet<Symbol>,
        ast: &Ast,
        forward_dependency_resolver: &mut SelectAndImplyDependencyResolver,
    ) -> HashMap<ItemReference, Self> {
        let mut item = Item::new(main_menu_name, macro_symbols);
        let mut items = HashMap::new();
        let empty_conditions = HashSet::new();

        for name in ast.element_names() {
            if let Ok(elt) = ast.element_from_name(&name) {
                let child_items = item.create_child(
                    name,
                    ast,
                    elt,
                    empty_conditions.clone(),
                    forward_dependency_resolver,
                );
                items.extend(child_items.into_iter());
            }
        }

        for condition in ast.conditional_blocks() {
            for (_, elt) in condition.elements() {
                let mut additional_conditions = HashSet::new();
                additional_conditions.insert(condition.dependency());
                items.extend(item.create_child(
                    elt.name(),
                    &ast,
                    elt,
                    additional_conditions,
                    forward_dependency_resolver,
                ));
            }
        }

        items.insert(ItemReference::Menu(main_menu_name.to_string()), item);
        items
    }

    pub(crate) fn init_from_elt(
        &mut self,
        ast: &Ast,
        elt: &Element,
        conditions: HashSet<Dependency>,
        forward_dependency_resolver: &mut SelectAndImplyDependencyResolver,
    ) -> HashMap<ItemReference, Self> {
        let mut items = HashMap::new();

        for (name, elt) in elt.sub_elements() {
            let child_items = self.create_child(
                name,
                ast,
                elt,
                conditions.clone(),
                forward_dependency_resolver,
            );
            items.extend(child_items.into_iter());
        }

        for condition in elt.conditional_blocks() {
            for (_, elt) in condition.elements() {
                let mut additional_conditions = conditions.clone();
                additional_conditions.insert(condition.dependency());
                items.extend(self.create_child(
                    elt.name(),
                    &ast,
                    elt,
                    additional_conditions,
                    forward_dependency_resolver,
                ));
            }
        }

        items
    }

    fn create_child(
        &mut self,
        name: String,
        ast: &Ast,
        elt: Element,
        conditions: HashSet<Dependency>,
        forward_dependency_resolver: &mut SelectAndImplyDependencyResolver,
    ) -> HashMap<ItemReference, Self> {
        let mut item = Self::new(&name, &self.macro_symbols);
        item.conditions = conditions.clone();
        for paragraph in elt.help() {
            item.help.push(paragraph);
        }

        item.parent = Some(self.name.clone());
        let mut items = item.init_from_elt(ast, &elt, conditions, forward_dependency_resolver);

        let itemref = match &elt.elt_type() {
            ElementType::Config => ItemReference::Config(name.clone()),
            ElementType::MenuConfig => ItemReference::MenuConfig(name.clone()),
            ElementType::Menu => ItemReference::Menu(name.clone()),
        };

        item.maybe_elt = Some(elt.clone());

        if let Some(types) = elt.types() {
            for (config_type, _) in types {
                if let Some(config) = ConfigItem::new(config_type, &elt) {
                    item.config_items.insert(config_type.clone(), config);
                }
            }
        }

        if let Some(reverse_dependencies) = elt.reverse_dependencies() {
            for (selected_name, maybe_condition) in reverse_dependencies {
                forward_dependency_resolver.put_select(&itemref, selected_name, maybe_condition)
            }
        }

        if let Some(weak_dependencies) = elt.weak_dependencies() {
            for (implied_name, maybe_condition) in weak_dependencies {
                forward_dependency_resolver.put_imply(&itemref, implied_name, maybe_condition)
            }
        }

        items.insert(itemref, item);
        items
    }

    pub(crate) fn set_dependencies(&mut self, dependencies: HashSet<ItemDependency>) {
        self.dependencies = dependencies;
    }

    pub(crate) fn set_selects_me(&mut self, dependencies: HashMap<String, Option<ResolvedExpr>>) {
        self.selects_me = dependencies;
    }

    pub(crate) fn set_selected(&mut self, dependencies: HashMap<String, Option<ResolvedExpr>>) {
        self.selected = dependencies;
    }

    pub(crate) fn set_imply_me(&mut self, dependencies: HashMap<String, Option<ResolvedExpr>>) {
        self.imply_me = dependencies;
    }

    pub(crate) fn set_implied(&mut self, dependencies: HashMap<String, Option<ResolvedExpr>>) {
        self.implied = dependencies;
    }

    /// Returns the name of the item, typically, this is the same as the name of
    /// the associated ItemReference
    pub fn name<'a>(&'a self) -> &'a str {
        &self.name
    }

    /// Returns the item reference of the item, which can be used to traverse
    /// the configuration registry, or perform dependency lookups in other items
    pub fn itemref(&self) -> ItemReference {
        match &self.maybe_elt {
            Some(elt) => match elt.elt_type() {
                ElementType::Config => ItemReference::Config(self.name.clone()),
                ElementType::MenuConfig => ItemReference::MenuConfig(self.name.clone()),
                ElementType::Menu => ItemReference::Menu(self.name.clone()),
            },
            // Possibly the main menu
            None => ItemReference::Menu(self.name.clone()),
        }
    }

    pub fn config_items<'a>(&'a self) -> &'a HashMap<ConfigType, ConfigItem> {
        &self.config_items
    }

    pub fn config_items_mut<'a>(&'a mut self) -> &'a mut HashMap<ConfigType, ConfigItem> {
        &mut self.config_items
    }

    pub fn conditions(&self) -> HashSet<Dependency> {
        self.conditions.clone()
    }

    /// Returns the reverse dependencies, without evaluation
    pub fn item_dependencies(&self) -> HashSet<ItemDependency> {
        self.dependencies.clone()
    }

    /// Returns the items selected by me
    pub fn selected(&self) -> HashMap<String, Option<ResolvedExpr>> {
        self.selected.clone()
    }

    /// Returns the items implied by me
    pub fn implied<'a>(&self) -> HashMap<String, Option<ResolvedExpr>> {
        self.implied.clone()
    }

    /// Returns the items selecting me
    pub fn selects_me(&self) -> HashMap<String, Option<ResolvedExpr>> {
        self.selects_me.clone()
    }

    /// Returns the items implying me
    pub fn imply_me(&self) -> HashMap<String, Option<ResolvedExpr>> {
        self.imply_me.clone()
    }

    pub fn raw_elt<'a>(&'a self) -> &'a Option<Element> {
        &self.maybe_elt
    }

    pub fn parent<'a>(&'a self) -> &'a Option<String> {
        &self.parent
    }

    pub fn info(&self) -> Info {
        Info::new(self.help.clone(), self.itemref())
    }

    pub(crate) fn collect_all_dependencies(&self) -> HashSet<MaybeIncompleteItemReference> {
        let mut itemrefs: HashSet<MaybeIncompleteItemReference> = HashSet::new();

        for item_dependency in self.item_dependencies() {
            for itemref in item_dependency.expr().itemrefs() {
                itemrefs.insert(MaybeIncompleteItemReference::ItemReference(itemref.clone()));
            }
        }

        for (name, expr) in self.imply_me() {
            itemrefs.insert(MaybeIncompleteItemReference::String(name));
            if let Some(expr) = expr {
                for itemref in expr.itemrefs() {
                    itemrefs.insert(MaybeIncompleteItemReference::ItemReference(itemref.clone()));
                }
            }
        }

        for (name, expr) in self.selects_me() {
            itemrefs.insert(MaybeIncompleteItemReference::String(name));
            if let Some(expr) = expr {
                for itemref in expr.itemrefs() {
                    itemrefs.insert(MaybeIncompleteItemReference::ItemReference(itemref.clone()));
                }
            }
        }

        for (_, config_item) in self.config_items() {
            for itemref in config_item.collect_all_dependencies() {
                itemrefs.insert(MaybeIncompleteItemReference::ItemReference(itemref.clone()));
            }
        }

        itemrefs
    }
}

/// Represents an incomplete item reference, that is, it can contain complete
/// itemreferences, or to be resolved item references of which it is not known
/// yet whether it should be a config, menuconfig, or menu item.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum MaybeIncompleteItemReference {
    ItemReference(ItemReference),
    String(String),
}

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

    /// Describes whether the type at hand is a normal config type,
    /// or a menuconfig type. Typically, dependencies on menuconfig types,
    /// should be displayed as if the configuration item itself is a menu.
    is_menu: bool,

    /// Value of the configuration item, if set to None, it is not set,
    /// and the default should be used instead.
    value: Option<Variant>,

    /// Configuration value of the configuration item as set by reading
    /// the configuration.
    config_value: Option<Variant>,

    /// The configuration value type
    config_type: ConfigType,

    /// The default value of the configuration item, where available
    defaults: HashMap<ResolvedExpr, Option<ResolvedExpr>>,

    /// The dependencies on which the availability of the current configuration
    /// item depends.
    maybe_expr: Option<ResolvedExpr>,

    /// If the configuration type is indicating a Boolean or Tristate
    /// value, then the select and imply reverse dependencies can enforce
    /// a maximum of choices. If the choices are determined through select,
    /// then the boolean will be true, if the choices are determined through
    /// imply, then to boolean wioll be false.
    choices: Option<(bool, Tristate)>,
}

impl ConfigItem {
    pub(crate) fn new(config_type: &ConfigType, elt: &Element) -> Option<Self> {
        let maybe_is_menu = match elt.elt_type() {
            ElementType::Config => Some(false),
            ElementType::MenuConfig => Some(true),
            ElementType::Menu => None,
        };

        maybe_is_menu.map(|is_menu| Self {
            maybe_expr: None,
            is_menu,
            config_value: None,
            value: None,
            choices: match config_type {
                ConfigType::Bool | ConfigType::Tristate => Some((true, Tristate::FALSE)),
                _ => None,
            },
            config_type: config_type.clone(),
            prompt: elt.prompt(),
            defaults: HashMap::new(),
        })
    }

    /// Returns the value belonging to the configuration item, if a value is
    /// set by the user.
    pub(crate) fn value(&self) -> Option<Variant> {
        self.value.clone()
    }

    /// Sets the value for the configuration item
    pub(crate) fn set_value(&mut self, value: Variant) {
        self.value = Some(value.transform(VariantDataType::from(&self.config_type)))
    }

    /// Sets the configuration value from a .config file
    pub(crate) fn set_config_value(&mut self, value: Variant) {
        self.config_value = Some(value.transform(VariantDataType::from(&self.config_type)))
    }

    /// Returns the configuration value as read from a .config file
    pub(crate) fn config_value(&self) -> Option<Variant> {
        self.config_value.clone()
    }

    /// Returns whether the choices have been selected or implied, if at all
    /// selectable or implyable
    pub fn choice_mode(&self) -> Option<bool> {
        match self.choices {
            Some((selected, _)) => Some(selected),
            None => None,
        }
    }

    /// Returns the lower bounds of the selected value
    pub fn choice_low(&self) -> Variant {
        match self.choices {
            Some((_, bound)) => Variant::from(bound),
            None => Variant::from(false),
        }
    }

    // Sets the choice mode
    pub(crate) fn set_choice_mode(&mut self, selected: bool, low_bound: Tristate) {
        self.choices = Some((selected, low_bound));
    }

    // Removes the value, and let's the configuration item revert to the default value
    pub(crate) fn reset_value(&mut self) {
        self.value = None
    }

    // Removes the configuration value
    pub(crate) fn reset_config_value(&mut self) {
        self.config_value = None
    }

    // Removes both the value as well as the configuration value,
    // reverts the selected/implied choices, etc.
    pub(crate) fn reset_all(&mut self) {
        self.reset_value();
        self.reset_config_value();
        if let Some(_) = self.choices {
            self.choices = Some((true, Tristate::FALSE));
        }
    }

    /// Returns the configuration type of the configuration item
    pub fn config_type(&self) -> ConfigType {
        self.config_type.clone()
    }

    /// Sets the configuration item dependencies
    pub(crate) fn set_dependencies(&mut self, resolved_expr: ResolvedExpr) {
        self.maybe_expr = Some(resolved_expr);
    }

    pub(crate) fn maybe_dependencies(&self) -> Option<ResolvedExpr> {
        match &self.maybe_expr {
            Some(expr) => Some(expr.clone()),
            None => None,
        }
    }

    pub(crate) fn add_default(
        &mut self,
        default_expr: ResolvedExpr,
        dependency: Option<ResolvedExpr>,
    ) {
        self.defaults.insert(default_expr, dependency);
    }

    pub(crate) fn defaults(&self) -> HashMap<ResolvedExpr, Option<ResolvedExpr>> {
        let mut map = HashMap::new();
        for (k, v) in &self.defaults {
            let cloned = match v {
                Some(v) => Some(v.clone()),
                None => None,
            };
            map.insert(k.clone(), cloned);
        }
        map
    }

    /// Returns the prompt string, if any is avilable. If no prompt is available,
    /// the value can not be set through exterior commands, but requires to be set
    /// by dependencies only.
    pub fn prompt<'a>(&'a self) -> &'a Option<String> {
        &self.prompt
    }

    /// Returns whether the current item is also a menu
    pub fn is_menu(&self) -> bool {
        self.is_menu
    }

    /// Returns all the dependencies of the configuration item
    pub fn collect_all_dependencies(&self) -> HashSet<ItemReference> {
        let mut itemrefs: HashSet<ItemReference> = HashSet::new();
        for (k, v) in &self.defaults {
            for itemref in k.itemrefs() {
                itemrefs.insert(itemref.clone());
            }
            if let Some(expr) = v {
                for itemref in expr.itemrefs() {
                    itemrefs.insert(itemref.clone());
                }
            }
        }

        if let Some(expr) = &self.maybe_expr {
            for itemref in expr.itemrefs() {
                itemrefs.insert(itemref.clone());
            }
        }

        itemrefs
    }
}

impl Hash for Item {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.enabled.hash(state);
        self.help.hash(state);
        for parent in self.conditions.iter() {
            parent.hash(state)
        }
    }
}