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 lexer
//! to lex the tokens found within a Kconfig file.

use std::fmt::Display;

/// An equality operator is used for testing two expressions. These
/// expressions should be valid expressions according to the Kconfig
/// grammar.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum EqualityOperator {
    /// Lesser than or equal to (<=)
    Lte,
    /// Greater than or equal to (>=)
    Lt,
    /// Lesser than (<)
    Gte,
    /// Greater than (>)
    Gt,
    /// Equal to (==)
    Eq,
    /// Not equal to (!=)
    Ne,
}

impl Display for EqualityOperator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EqualityOperator::Lte => f.write_str("<="),
            EqualityOperator::Lt => f.write_str("<"),
            EqualityOperator::Gte => f.write_str(">="),
            EqualityOperator::Gt => f.write_str(">"),
            EqualityOperator::Eq => f.write_str("=="),
            EqualityOperator::Ne => f.write_str("!="),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Keyword {
    /// source
    Source,

    /// mainmenu
    Mainmenu,
    /// config
    Config,
    /// menuconfig
    Menuconfig,
    /// choice
    Choice,
    /// endchoide
    Endchoice,
    /// menu
    Menu,
    /// endmenu
    Endmenu,

    /// if
    If,
    /// endif
    Endif,

    /// bool
    Bool,
    /// def_bool
    DefBool,
    /// tristate
    Tristate,
    /// def_tristate
    DefTristate,
    /// string
    String,
    /// hex
    Hex,
    /// int
    Int,

    /// default
    Default,

    /// depends
    Depends,
    /// on
    On,
    /// select
    Select,
    /// imply
    Imply,

    /// visible
    Visible,

    /// range
    Range,

    /// prompt
    Prompt,
    /// comment
    Comment,
}

impl Display for Keyword {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Keyword::Source => f.write_str("source"),
            Keyword::Mainmenu => f.write_str("mainmenu"),
            Keyword::Config => f.write_str("config"),
            Keyword::Menuconfig => f.write_str("menuconfic"),
            Keyword::Choice => f.write_str("choice"),
            Keyword::Endchoice => f.write_str("endchoice"),
            Keyword::Menu => f.write_str("menu"),
            Keyword::Endmenu => f.write_str("endmenu"),
            Keyword::If => f.write_str("if"),
            Keyword::Endif => f.write_str("endif"),
            Keyword::Bool => f.write_str("bool"),
            Keyword::DefBool => f.write_str("def_bool"),
            Keyword::Tristate => f.write_str("tristate"),
            Keyword::DefTristate => f.write_str("def_tristate"),
            Keyword::String => f.write_str("string"),
            Keyword::Hex => f.write_str("hex"),
            Keyword::Int => f.write_str("int"),
            Keyword::Default => f.write_str("default"),
            Keyword::Depends => f.write_str("depends"),
            Keyword::On => f.write_str("on"),
            Keyword::Select => f.write_str("select"),
            Keyword::Imply => f.write_str("imply"),
            Keyword::Visible => f.write_str("visible"),
            Keyword::Range => f.write_str("range"),
            Keyword::Prompt => f.write_str("prompt"),
            Keyword::Comment => f.write_str("comment"),
        }
    }
}

/// There are a certain amount of basic tokens found within a stream
/// of tokens belonging to a Kconfig configuration specification.
/// These tokens are outlined here.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Lexicon {
    /// Keywords such as config, menuconfig, if, comment, source ...
    Keyword(Keyword),
    /// Identifier, specifically used for assignment and evaluation
    Identifier(String),
    /// Strings, encapsulated in double quotes
    String(String),
    /// Help text, indented when a "Help" section was started
    Help(String),
    /// An equality operator, such as <=, ==, etc.
    EqualityOperator(EqualityOperator),
    /// An immediate assignment, e.g.: :=
    ImmediateAssignment,
    /// A normal assignment, e.g.: =
    Assignment,
    /// An appendage assignment, e.g.: +=
    AppendAssignment,
    /// An inverse of an expression
    Not,
    /// Start a macro definition with "$("
    MacroOpen,
    /// Start a normal definition with "("
    Open,
    /// Ends a definition (either macro or normal) with ")"
    Close,
    /// A comma, typically used as an argument separator
    Comma,
    /// End of transmission, used when no more tokens can be found
    EOT,
    /// Error, used when the found token is illegal
    Error(String),
    /// The '&&' expression
    And,
    /// The '||' expression
    Or,
}

impl Display for Lexicon {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Lexicon::Keyword(k) => f.write_str(&format!("{}", k)),
            Lexicon::Identifier(s) => f.write_str(s),
            Lexicon::String(s) => f.write_str(s),
            Lexicon::Help(s) => f.write_str(s),
            Lexicon::EqualityOperator(o) => f.write_str(&format!("{}", o)),
            Lexicon::ImmediateAssignment => f.write_str(":="),
            Lexicon::Assignment => f.write_str("="),
            Lexicon::AppendAssignment => f.write_str("+="),
            Lexicon::Not => f.write_str("+="),
            Lexicon::MacroOpen => f.write_str("$("),
            Lexicon::Open => f.write_str("("),
            Lexicon::Close => f.write_str(")"),
            Lexicon::Comma => f.write_str(","),
            Lexicon::EOT => f.write_str("[End Of Transmission/File]"),
            Lexicon::Error(s) => f.write_str(&format!("Error: {}", s)),
            Lexicon::And => f.write_str("&"),
            Lexicon::Or => f.write_str("|"),
        }
    }
}

/// A token describes the found verb, the column and line where it has
/// been found.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Token {
    /// Contains the specific token from the lexicon
    term: Lexicon,
    /// Contains the column position of the token from the current
    /// position, if line > 0, then the column position will be from
    /// the start of the line the token was found on.
    column: usize,
    /// Contains the line number of the token from the current
    /// position.
    line: usize,
    /// Contains the raw string of the token
    raw: String,
}

impl Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!("{}", self.term))
    }
}

impl Token {
    /// Creates a token, using a term from the `Lexicon`, at the given column
    /// (minus the term), at the specified line with the given string. The string
    /// is only used to determine the length of the token.
    pub(super) fn create(term: Lexicon, column: usize, line: usize, raw: &str) -> Self {
        Self {
            term,
            column,
            line,
            raw: raw.to_string(),
        }
    }

    /// Creates a token representing an error, at the given column (minus the term),
    /// at the specified line with the given string. The string is only used to
    /// determine the length of the token.
    pub(crate) fn create_error(column: usize, line: usize, s: &str) -> Self {
        Self {
            term: Lexicon::Error(s.to_string()),
            column,
            line,
            raw: s.to_string(),
        }
    }

    /// Creates a token representing end-of-transmission, typically at the end of
    /// the file, end of stream or end of buffer, at the given column and line.
    pub(super) fn create_eot(column: usize, line: usize) -> Self {
        Self {
            term: Lexicon::EOT,
            column,
            line,
            raw: "".to_owned(),
        }
    }

    pub fn term(&self) -> Lexicon {
        self.term.clone()
    }

    pub fn column(&self) -> usize {
        self.column
    }

    pub fn line(&self) -> usize {
        self.line
    }

    pub fn raw(&self) -> String {
        self.raw.clone()
    }

    /// Returns if the token's term indicates EOT (End of transmission,
    /// most likely End of file).
    pub fn eot(&self) -> bool {
        match self.term {
            Lexicon::EOT => return true,
            _ => return false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_token_creation() {
        let expected = Token {
            term: Lexicon::EOT,
            column: 0,
            line: 0,
            raw: "".to_owned(),
        };
        let got = Token::create(Lexicon::EOT, 0, 0, &"");
        assert_eq!(expected, got);
    }
}