cargo-kconfig 0.0.4

Kconfig macro library and user interface for the Kconfig file format from the Linux Kernel
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.
*/

use kconfig_parser::MacroLexer;
use kconfig_represent::{ConfigRegistry, LoadError};
use std::{
    collections::HashMap,
    fmt::Display,
    mem::MaybeUninit,
    path::{Path, PathBuf},
    process::exit,
    rc::Rc,
    sync::{Mutex, Once},
};

use crate::util::{lex_from_file, parse};

use super::log::log_colored;

pub(crate) struct TagRegistry {
    kconfig_path_expr: PathExpr,
    dotconfig_path_expr: PathExpr,
    config_registry: Rc<ConfigRegistry>,
    dotconfig_load_error: Option<LoadError>,
}

pub(crate) struct PathExpr {
    buf: PathBuf,
}

struct SingletonReader {
    inner: Mutex<HashMap<String, TagRegistry>>,
}

impl TagRegistry {
    pub(crate) fn register(tag: &str, kconfig_path_expr: PathExpr, dotconfig_path_expr: PathExpr) {
        let mut me = singleton().inner.lock().unwrap();
        match me.get(tag) {
            Some(_) => (),
            None => {
                let mut lexer = MacroLexer::new(lex_from_file(&kconfig_path_expr.to_string()));

                // Parses the given Kconfig file into an AST
                let ast = parse(&mut lexer);

                // Loads the menu items from the ast, and symbol table
                let mut registry = match ConfigRegistry::new(&ast, &lexer.symbol_table()) {
                    Ok(registry) => registry,
                    Err(e) => {
                        panic!("⛔ {}", e);
                    }
                };

                let load_error: Option<LoadError> =
                    load_dot_config_into_registry(&mut registry, &dotconfig_path_expr);

                me.insert(
                    tag.to_string(),
                    TagRegistry {
                        kconfig_path_expr,
                        dotconfig_path_expr,
                        config_registry: Rc::new(registry),
                        dotconfig_load_error: load_error,
                    },
                );
            }
        }
    }

    pub(crate) fn report() {
        let now = singleton().inner.lock().unwrap();
        log_colored("Tag Registry Report", "----------");
        for (tag, registry) in now.iter() {
            log_colored(
                &tag.to_string(),
                &format!(
                    "Kconfig ({}) .config ({})",
                    registry.kconfig_path_expr, registry.dotconfig_path_expr
                ),
            );
            if let Some(load_error) = &registry.dotconfig_load_error {
                print!("{}", load_error.to_string())
            }
        }
        log_colored("End Tag Registry Report", "----------");
    }

    pub(crate) fn get_config_registry(tag_name: &str) -> Rc<ConfigRegistry> {
        let me = singleton().inner.lock().unwrap();
        match me.get(tag_name) {
            Some(registry) => registry.config_registry.clone(),
            None => panic!("Tag {} not registered", tag_name),
        }
    }
}

impl PathExpr {
    pub(crate) fn new(file: String, path: String) -> PathExpr {
        let mut buf = PathBuf::new();
        buf.push(path);
        buf.push(file);
        Self { buf }
    }
}

impl Display for PathExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.buf.clone().into_os_string().into_string().unwrap()
        )
    }
}

/// Constructs a singleton of the singleton reader, containing
/// the hashmap in it.
fn singleton() -> &'static SingletonReader {
    // Create an uninitialized singleton as a static mutable variable
    static mut SINGLETON: MaybeUninit<SingletonReader> = MaybeUninit::uninit();

    // Creates a once action, which only calles the internal function
    // once in it's lifetime.
    static ONCE: Once = Once::new();

    unsafe {
        ONCE.call_once(|| {
            let singleton = SingletonReader {
                inner: Mutex::new(HashMap::new()),
            };
            // Initializes the uninitialized singleton
            SINGLETON.write(singleton);
        });
        // Rturns the reference to the content of the singleton
        SINGLETON.assume_init_ref()
    }
}

fn load_dot_config_into_registry(
    registry: &mut ConfigRegistry,
    dotconfig_path_expr: &PathExpr,
) -> Option<LoadError> {
    let path = dotconfig_path_expr.to_string();
    if Path::new(&path).exists() {
        match registry.read_dotconfig_file(&path) {
            Err(e) => Some(e),
            Ok(_) => None,
        }
    } else {
        log_colored("Severe Error", &format!("⛔ File {} not found", path));
        exit(1);
    }
}