kconfig-parser 0.1.1

Kconfig parser for the Kconfig file format from the Linux Kernel for the Cargo Kconfig crate
Documentation
/*
 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 pub structures necessary for the Kconfig AST
//! as defined by the Kconfig language.

use std::collections::btree_set::IntoIter;
use std::collections::VecDeque;
use std::fmt::Display;
use std::{
    collections::{BTreeSet, HashMap, HashSet},
    hash::Hash,
};

/// A Config structure should have a type. Because types can change depending
/// on a dependency (typically through an if expression)
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ConfigType {
    Bool,
    Tristate,
    String,
    Int,
    Hex,
}

/// Implements the display functionality for a each configuration type
impl Display for ConfigType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigType::Bool => f.write_str("bool"),
            ConfigType::Tristate => f.write_str("tristate"),
            ConfigType::String => f.write_str("string"),
            ConfigType::Int => f.write_str("int"),
            ConfigType::Hex => f.write_str("hex"),
        }
    }
}

/// An expression can be a symbol, a comparison expression,
/// a negation, a subexpression (with parentheses) and an 'bitwise and'
/// or 'bitwise or' expression. It can also be a macro resulting into
/// a valid value.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Expr {
    Sym(String), // A symbol, typically simply an identifier
    // Macro(Macro) - not yet implemented
    Eq(BTreeSet<Expr>),
    Ne(BTreeSet<Expr>),
    Lt(BTreeSet<Expr>),
    Gt(BTreeSet<Expr>),
    Lte(BTreeSet<Expr>),
    Gte(BTreeSet<Expr>),
    And(BTreeSet<Expr>),
    Or(BTreeSet<Expr>),
    Sub(Box<Expr>),
    Not(Box<Expr>),
}

impl Expr {
    pub fn is_sym(&self) -> bool {
        match self {
            Self::Sym(_) => true,
            _ => false,
        }
    }

    pub fn is_not(&self) -> bool {
        match self {
            Self::Not(_) => true,
            _ => false,
        }
    }

    pub fn is_sub(&self) -> bool {
        match self {
            Self::Sub(_) => true,
            _ => false,
        }
    }

    pub fn is_comparison(&self) -> bool {
        match self {
            Self::Eq(_)
            | Self::Ne(_)
            | Self::Lt(_)
            | Self::Gt(_)
            | Self::Lte(_)
            | Self::Gte(_)
            | Self::And(_)
            | Self::Or(_) => true,
            _ => false,
        }
    }

    pub fn contains(&self, expr: &Expr) -> bool {
        match self {
            Self::Sym(_) => false,
            Self::Sub(b) | Self::Not(b) => b.contains(expr),
            Self::Eq(s)
            | Self::Ne(s)
            | Self::Lt(s)
            | Self::Gt(s)
            | Self::Lte(s)
            | Self::Gte(s)
            | Self::And(s)
            | Self::Or(s) => s.contains(expr),
        }
    }

    pub fn is_eq(&self) -> bool {
        match self {
            Self::Eq(_) => true,
            _ => false,
        }
    }
    pub fn is_ne(&self) -> bool {
        match self {
            Self::Ne(_) => true,
            _ => false,
        }
    }
    pub fn is_lt(&self) -> bool {
        match self {
            Self::Lt(_) => true,
            _ => false,
        }
    }
    pub fn is_gt(&self) -> bool {
        match self {
            Self::Gt(_) => true,
            _ => false,
        }
    }
    pub fn is_gte(&self) -> bool {
        match self {
            Self::Gte(_) => true,
            _ => false,
        }
    }
    pub fn is_lte(&self) -> bool {
        match self {
            Self::Lte(_) => true,
            _ => false,
        }
    }
    pub fn is_and(&self) -> bool {
        match self {
            Self::And(_) => true,
            _ => false,
        }
    }
    pub fn is_or(&self) -> bool {
        match self {
            Self::Or(_) => true,
            _ => false,
        }
    }

    pub fn get_sym(&self) -> Option<String> {
        match self {
            Self::Sym(s) => Some(s.to_string()),
            _ => None,
        }
    }

    pub fn get_not_expr(&self) -> Option<Expr> {
        match self {
            Self::Not(e) => Some(e.as_ref().clone()),
            _ => None,
        }
    }

    pub fn get_sub_expr(&self) -> Option<Expr> {
        match self {
            Self::Sub(e) => Some(e.as_ref().clone()),
            _ => None,
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Self::Eq(s)
            | Self::Ne(s)
            | Self::Lt(s)
            | Self::Gt(s)
            | Self::Lte(s)
            | Self::Gte(s)
            | Self::And(s)
            | Self::Or(s) => s.len(),
            _ => 1,
        }
    }
}

impl IntoIterator for Expr {
    type Item = Expr;
    type IntoIter = IntoIter<Self::Item>;
    fn into_iter(self) -> Self::IntoIter {
        match self {
            Self::Eq(s)
            | Self::Ne(s)
            | Self::Lt(s)
            | Self::Gt(s)
            | Self::Lte(s)
            | Self::Gte(s)
            | Self::And(s)
            | Self::Or(s) => s.into_iter(),
            Self::Sym(s) => {
                let mut set = BTreeSet::new();
                set.insert(Expr::Sym(s.to_string()));
                set.into_iter()
            }
            Self::Sub(s) | Self::Not(s) => {
                let mut set = BTreeSet::new();
                set.insert(*s.clone());
                set.into_iter()
            }
        }
    }
}

/// A dependency can be a name in the form of a string or a set of other
/// dependencies either to be orred or to be anded
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct Dependency {
    expr: Expr,
}

impl Dependency {
    pub fn expr(&self) -> Expr {
        self.expr.clone()
    }

    pub fn new(expr: &Expr) -> Self {
        Dependency { expr: expr.clone() }
    }

    pub fn len(&self) -> usize {
        return self.expr.len();
    }

    pub fn contains(&self, expr: &Expr) -> bool {
        self.expr.contains(expr)
    }
}

/// A ConfigType is part of an instance, which can also have dependencies
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConfigTypeInstance {
    config_type: ConfigType,
    dependency: Dependency,
}

/// A range is a definition where an int or hex value is not allowed to be
/// lower than LHS and not to be higher than RHS
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Range {
    pub(super) lhs: i64,
    pub(super) rhs: i64,
    pub(super) dependency: Option<Dependency>,
}

impl Range {
    pub fn lhs(&self) -> i64 {
        self.lhs
    }
    pub fn rhs(&self) -> i64 {
        self.rhs
    }
    pub fn dependency(&self) -> &Option<Dependency> {
        &self.dependency
    }
}

/// A Config structure represents the internals of the config element itself,
/// without dependencies.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Config {
    pub(super) name: String,
    pub(super) prompt: Option<String>,
    pub(super) types: HashMap<ConfigType, Option<Dependency>>,
    pub(super) defaults: HashMap<Expr, Option<Dependency>>,
    pub(super) dependencies: HashSet<Dependency>,
    pub(super) reverse_dependencies: HashMap<String, Option<Dependency>>,
    pub(super) weak_dependencies: HashMap<String, Option<Dependency>>,
    pub(super) menu_dependencies: HashSet<Dependency>,
    pub(super) range: Option<Range>,
    pub(super) help: VecDeque<String>,
}

impl Config {
    pub fn create(name: &str) -> Self {
        Self {
            name: name.to_string(),
            prompt: None,
            types: HashMap::new(),
            defaults: HashMap::new(),
            dependencies: HashSet::new(),
            reverse_dependencies: HashMap::new(),
            weak_dependencies: HashMap::new(),
            menu_dependencies: HashSet::new(),
            range: None,
            help: VecDeque::new(),
        }
    }
}