//! The module handelling kernel panic.

use core::panic::PanicInfo;

use crate::println;
use crate::wait_forever;

/// Avoid nested panic
fn panic_prevent_reenter() {
    use core::sync::atomic::{AtomicBool, Ordering};
    // This code is safe to use with AArch64, if using another
    // arch, check the safety first
    #[cfg(not(target_arch = "aarch64"))]
    compile_error!(
        "The following code is safe for aarch64, \
        check the safety before using with another arch"
    );
    static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false);
    if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) {
        PANIC_IN_PROGRESS.store(true, Ordering::Relaxed);
        return;
    }
    wait_forever()
}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    panic_prevent_reenter();

    let (location, line, column) = match info.location() {
        Some(loc) => (loc.file(), loc.line(), loc.column()),
        _ => ("???", 0, 0),
    };

    println!(
        "Kernel panic!\n\n\
        Panic location:\n    File: '{location}', line {line}, column {column}\n\n\
        {}",
        info.message().unwrap_or(&format_args!(""))
    );
    wait_forever()
}
