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 source lexer, which behaves like a regular lexer,
//! but inserts the contents of source files indicated by the "source ..."
//! directive.

use std::fmt::Display;

use super::{
    structs::{Keyword, Lexicon, Token},
    LexerBase,
};
use crate::parse_string;

/// The source lexer allows the source directive to be used to load
/// additional sources as part of the (currently) loaded Kconfig file.
pub struct SourceLexer<LB>
where
    LB: LexerBase,
{
    /// This stack is composed of the name of the stream and the lexer
    /// belonging to the stream. If the lexer has been depleted, it will
    /// be removed from the stack.
    stack: Vec<Table<LB>>,

    /// The source function takes the name of the source and returns a new
    /// lexer.
    source_function: fn(&str) -> Result<LB, String>,

    /// The resolve_name_function resolves the name of the source
    /// to a canonical name understood by the system. This is primarily
    /// used to discover source recursion (which wouldn't end).
    canonical_name_function: fn(&str) -> String,
}

struct Table<LB>
where
    LB: LexerBase,
{
    stream_name: String,
    lexer: LB,
}

/// Provides a basic error message when the source function for one
/// or the other reason fails.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error {
    msg: String,
}

impl Error {
    /// Creates a new error from a source function, and allows it to
    /// be passed as part of the source lexer error conditions.
    pub fn new(s: &str) -> Error {
        Error { msg: s.to_string() }
    }
}

impl Display for Error {
    /// Formats the error
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.msg)
    }
}

impl<LB> SourceLexer<LB>
where
    LB: LexerBase,
{
    /// Creates a new source lexer, given the stream's name. This will
    /// create the first source_function call, to actually load the
    /// stream.
    pub fn new(
        stream_name: &str,
        source_function: fn(&str) -> Result<LB, String>,
        canonical_name_function: fn(&str) -> String,
    ) -> Result<Self, Error> {
        match (source_function)(stream_name) {
            Ok(lexer) => Ok(Self {
                stack: vec![Table {
                    stream_name: stream_name.to_string(),
                    lexer: lexer,
                }],
                source_function,
                canonical_name_function,
            }),
            Err(s) => {
                Err(Error::new(&s))
            }
        }
    }
}

impl<LB> LexerBase for SourceLexer<LB>
where
    LB: LexerBase,
{
    fn next_token(&mut self) -> super::structs::Token {
        let last = self.stack.last_mut();
        match last {
            Some(table) => {
                let token = table.lexer.next_token();
                match token.term() {
                    Lexicon::EOT => {
                        self.stack.pop();
                        token
                    }
                    Lexicon::Keyword(k) => match k {
                        Keyword::Source => {
                            // read the next token, which should be a string,
                            // pointing to the stream to read.
                            let token = table.lexer.next_token();
                            match token.term() {
                                Lexicon::String(stream_name) => {
                                    let stream_name = match parse_string(&stream_name) {
                                        Ok(s) => s,
                                        Err(e) => {
                                            return Token::create(
                                                Lexicon::Error(e),
                                                token.column(),
                                                token.line(),
                                                &token.raw(),
                                            )
                                        }
                                    };
                                    let canonical_name =
                                        (self.canonical_name_function)(&stream_name);
                                    // Verify whether the the stream_name
                                    // does not already exist in the stack and creates
                                    // a circular load.
                                    for needle in &self.stack {
                                        if needle.stream_name.eq(&canonical_name) {
                                            return Token::create(
                                                Lexicon::Error(
                                                    "Circular source detected, abort load"
                                                        .to_string(),
                                                ),
                                                token.column(),
                                                token.line(),
                                                &token.raw(),
                                            );
                                        }
                                    }

                                    match (self.source_function)(&stream_name) {
                                        Ok(lb) => {
                                            let t = Table {
                                                stream_name: canonical_name,
                                                lexer: lb,
                                            };
        
                                            self.stack.push(t);
                                            self.next_token()
                                        },
                                        Err(s) => {
                                            Token::create(Lexicon::Error(s), token.column(), token.line(), &token.raw())
                                        }
                                    }
                                }
                                _ => Token::create(
                                    Lexicon::Error(
                                        "Expected string indicating source file or stream"
                                            .to_string(),
                                    ),
                                    token.column(),
                                    token.line(),
                                    &token.raw(),
                                ),
                            }
                        }
                        _ => token,
                    },
                    _ => token,
                }
            }
            None => Token::create(Lexicon::EOT, 0, 0, &""),
        }
    }

    fn current_stream(&self) -> Option<String> {
        let last = self.stack.last();
        match last {
            Some(table) => Some(table.stream_name.to_string()),
            _ => None,
        }
    }
}

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

    #[test]
    fn test_keywords() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "mainmenu config menuconfig choice endchoice menu endmenu if endif bool def_bool \
                                  tristate def_tristate string hex int default depends on select imply visible range prompt comment".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();
        assert_eq!(Lexicon::Keyword(Keyword::Mainmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Config), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menuconfig), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Choice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endchoice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::If), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endif), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Bool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::DefBool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Tristate), l.next_token().term());
        assert_eq!(
            Lexicon::Keyword(Keyword::DefTristate),
            l.next_token().term()
        );
        assert_eq!(Lexicon::Keyword(Keyword::String), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Hex), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Int), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Default), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Depends), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::On), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Select), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Imply), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Visible), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Range), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Prompt), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Comment), l.next_token().term());
        assert_eq!(Lexicon::EOT, l.next_token().term());
    }

    #[test]
    fn test_keywords_sub_lexer() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "source \"bar\"".as_bytes();
                    Ok(Lexer::create(s))
                } else if stream_name == "bar" {
                    let s = &mut "mainmenu config menuconfig choice endchoice menu endmenu if endif bool def_bool \
                                  tristate def_tristate string hex int default depends on select imply visible range prompt comment".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();
        assert_eq!(Lexicon::Keyword(Keyword::Mainmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Config), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menuconfig), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Choice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endchoice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::If), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endif), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Bool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::DefBool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Tristate), l.next_token().term());
        assert_eq!(
            Lexicon::Keyword(Keyword::DefTristate),
            l.next_token().term()
        );
        assert_eq!(Lexicon::Keyword(Keyword::String), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Hex), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Int), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Default), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Depends), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::On), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Select), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Imply), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Visible), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Range), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Prompt), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Comment), l.next_token().term());
        assert_eq!(Lexicon::EOT, l.next_token().term());
    }

    #[test]
    fn test_error_wrong_syntax() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "source bla".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();

        let is_error = if let Lexicon::Error(_) = l.next_token().term() {
            true
        } else {
            false
        };
        assert_eq!(is_error, true);
    }

    #[test]
    fn test_error_circular_syntax() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "source \"bar\"".as_bytes();
                    Ok(Lexer::create(s))
                } else if stream_name == "bar" {
                    let s = &mut "source \"foo\"".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();

        let is_error = if let Lexicon::Error(_) = l.next_token().term() {
            true
        } else {
            false
        };
        assert_eq!(is_error, true);
    }
}