// Generated by gir (https://github.com/gtk-rs/gir @ 8336b4ebe16f)
// from
// from gir-files (https://github.com/gtk-rs/gir-files.git @ 4d1189172a70)
// DO NOT EDIT

#![cfg(unix)]

use libxmlb_sys::*;
use std::env;
use std::error::Error;
use std::ffi::OsString;
use std::mem::{align_of, size_of};
use std::path::Path;
use std::process::{Command, Stdio};
use std::str;
use tempfile::Builder;

static PACKAGES: &[&str] = &["xmlb"];

#[derive(Clone, Debug)]
struct Compiler {
    pub args: Vec<String>,
}

impl Compiler {
    pub fn new() -> Result<Self, Box<dyn Error>> {
        let mut args = get_var("CC", "cc")?;
        args.push("-Wno-deprecated-declarations".to_owned());
        // For _Generic
        args.push("-std=c11".to_owned());
        // For %z support in printf when using MinGW.
        args.push("-D__USE_MINGW_ANSI_STDIO".to_owned());
        args.extend(get_var("CFLAGS", "")?);
        args.extend(get_var("CPPFLAGS", "")?);
        args.extend(pkg_config_cflags(PACKAGES)?);
        Ok(Self { args })
    }

    pub fn compile(&self, src: &Path, out: &Path) -> Result<(), Box<dyn Error>> {
        let mut cmd = self.to_command();
        cmd.arg(src);
        cmd.arg("-o");
        cmd.arg(out);
        let status = cmd.spawn()?.wait()?;
        if !status.success() {
            return Err(format!("compilation command {cmd:?} failed, {status}").into());
        }
        Ok(())
    }

    fn to_command(&self) -> Command {
        let mut cmd = Command::new(&self.args[0]);
        cmd.args(&self.args[1..]);
        cmd
    }
}

fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {
    match env::var(name) {
        Ok(value) => Ok(shell_words::split(&value)?),
        Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),
        Err(err) => Err(format!("{name} {err}").into()),
    }
}

fn pkg_config_cflags(packages: &[&str]) -> Result<Vec<String>, Box<dyn Error>> {
    if packages.is_empty() {
        return Ok(Vec::new());
    }
    let pkg_config = env::var_os("PKG_CONFIG").unwrap_or_else(|| OsString::from("pkg-config"));
    let mut cmd = Command::new(pkg_config);
    cmd.arg("--cflags");
    cmd.args(packages);
    cmd.stderr(Stdio::inherit());
    let out = cmd.output()?;
    if !out.status.success() {
        let (status, stdout) = (out.status, String::from_utf8_lossy(&out.stdout));
        return Err(format!("command {cmd:?} failed, {status:?}\nstdout: {stdout}").into());
    }
    let stdout = str::from_utf8(&out.stdout)?;
    Ok(shell_words::split(stdout.trim())?)
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Layout {
    size: usize,
    alignment: usize,
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
struct Results {
    /// Number of successfully completed tests.
    passed: usize,
    /// Total number of failed tests (including those that failed to compile).
    failed: usize,
}

impl Results {
    fn record_passed(&mut self) {
        self.passed += 1;
    }
    fn record_failed(&mut self) {
        self.failed += 1;
    }
    fn summary(&self) -> String {
        format!("{} passed; {} failed", self.passed, self.failed)
    }
    fn expect_total_success(&self) {
        if self.failed == 0 {
            println!("OK: {}", self.summary());
        } else {
            panic!("FAILED: {}", self.summary());
        };
    }
}

#[test]
fn cross_validate_constants_with_c() {
    let mut c_constants: Vec<(String, String)> = Vec::new();

    for l in get_c_output("constant").unwrap().lines() {
        let (name, value) = l.split_once(';').expect("Missing ';' separator");
        c_constants.push((name.to_owned(), value.to_owned()));
    }

    let mut results = Results::default();

    for ((rust_name, rust_value), (c_name, c_value)) in
        RUST_CONSTANTS.iter().zip(c_constants.iter())
    {
        if rust_name != c_name {
            results.record_failed();
            eprintln!("Name mismatch:\nRust: {rust_name:?}\nC:    {c_name:?}");
            continue;
        }

        if rust_value != c_value {
            results.record_failed();
            eprintln!(
                "Constant value mismatch for {rust_name}\nRust: {rust_value:?}\nC:    {c_value:?}",
            );
            continue;
        }

        results.record_passed();
    }

    results.expect_total_success();
}

#[test]
fn cross_validate_layout_with_c() {
    let mut c_layouts = Vec::new();

    for l in get_c_output("layout").unwrap().lines() {
        let (name, value) = l.split_once(';').expect("Missing first ';' separator");
        let (size, alignment) = value.split_once(';').expect("Missing second ';' separator");
        let size = size.parse().expect("Failed to parse size");
        let alignment = alignment.parse().expect("Failed to parse alignment");
        c_layouts.push((name.to_owned(), Layout { size, alignment }));
    }

    let mut results = Results::default();

    for ((rust_name, rust_layout), (c_name, c_layout)) in RUST_LAYOUTS.iter().zip(c_layouts.iter())
    {
        if rust_name != c_name {
            results.record_failed();
            eprintln!("Name mismatch:\nRust: {rust_name:?}\nC:    {c_name:?}");
            continue;
        }

        if rust_layout != c_layout {
            results.record_failed();
            eprintln!("Layout mismatch for {rust_name}\nRust: {rust_layout:?}\nC:    {c_layout:?}",);
            continue;
        }

        results.record_passed();
    }

    results.expect_total_success();
}

fn get_c_output(name: &str) -> Result<String, Box<dyn Error>> {
    let tmpdir = Builder::new().prefix("abi").tempdir()?;
    let exe = tmpdir.path().join(name);
    let c_file = Path::new("tests").join(name).with_extension("c");

    let cc = Compiler::new().expect("configured compiler");
    cc.compile(&c_file, &exe)?;

    let mut cmd = Command::new(exe);
    cmd.stderr(Stdio::inherit());
    let out = cmd.output()?;
    if !out.status.success() {
        let (status, stdout) = (out.status, String::from_utf8_lossy(&out.stdout));
        return Err(format!("command {cmd:?} failed, {status:?}\nstdout: {stdout}").into());
    }

    Ok(String::from_utf8(out.stdout)?)
}

const RUST_LAYOUTS: &[(&str, Layout)] = &[
    (
        "XbBuilder",
        Layout {
            size: size_of::<XbBuilder>(),
            alignment: align_of::<XbBuilder>(),
        },
    ),
    (
        "XbBuilderClass",
        Layout {
            size: size_of::<XbBuilderClass>(),
            alignment: align_of::<XbBuilderClass>(),
        },
    ),
    (
        "XbBuilderCompileFlags",
        Layout {
            size: size_of::<XbBuilderCompileFlags>(),
            alignment: align_of::<XbBuilderCompileFlags>(),
        },
    ),
    (
        "XbBuilderFixup",
        Layout {
            size: size_of::<XbBuilderFixup>(),
            alignment: align_of::<XbBuilderFixup>(),
        },
    ),
    (
        "XbBuilderFixupClass",
        Layout {
            size: size_of::<XbBuilderFixupClass>(),
            alignment: align_of::<XbBuilderFixupClass>(),
        },
    ),
    (
        "XbBuilderNode",
        Layout {
            size: size_of::<XbBuilderNode>(),
            alignment: align_of::<XbBuilderNode>(),
        },
    ),
    (
        "XbBuilderNodeClass",
        Layout {
            size: size_of::<XbBuilderNodeClass>(),
            alignment: align_of::<XbBuilderNodeClass>(),
        },
    ),
    (
        "XbBuilderNodeFlags",
        Layout {
            size: size_of::<XbBuilderNodeFlags>(),
            alignment: align_of::<XbBuilderNodeFlags>(),
        },
    ),
    (
        "XbBuilderSource",
        Layout {
            size: size_of::<XbBuilderSource>(),
            alignment: align_of::<XbBuilderSource>(),
        },
    ),
    (
        "XbBuilderSourceClass",
        Layout {
            size: size_of::<XbBuilderSourceClass>(),
            alignment: align_of::<XbBuilderSourceClass>(),
        },
    ),
    (
        "XbBuilderSourceCtx",
        Layout {
            size: size_of::<XbBuilderSourceCtx>(),
            alignment: align_of::<XbBuilderSourceCtx>(),
        },
    ),
    (
        "XbBuilderSourceCtxClass",
        Layout {
            size: size_of::<XbBuilderSourceCtxClass>(),
            alignment: align_of::<XbBuilderSourceCtxClass>(),
        },
    ),
    (
        "XbBuilderSourceFlags",
        Layout {
            size: size_of::<XbBuilderSourceFlags>(),
            alignment: align_of::<XbBuilderSourceFlags>(),
        },
    ),
    (
        "XbMachine",
        Layout {
            size: size_of::<XbMachine>(),
            alignment: align_of::<XbMachine>(),
        },
    ),
    (
        "XbMachineClass",
        Layout {
            size: size_of::<XbMachineClass>(),
            alignment: align_of::<XbMachineClass>(),
        },
    ),
    (
        "XbMachineDebugFlags",
        Layout {
            size: size_of::<XbMachineDebugFlags>(),
            alignment: align_of::<XbMachineDebugFlags>(),
        },
    ),
    (
        "XbMachineParseFlags",
        Layout {
            size: size_of::<XbMachineParseFlags>(),
            alignment: align_of::<XbMachineParseFlags>(),
        },
    ),
    (
        "XbNode",
        Layout {
            size: size_of::<XbNode>(),
            alignment: align_of::<XbNode>(),
        },
    ),
    (
        "XbNodeAttrIter",
        Layout {
            size: size_of::<XbNodeAttrIter>(),
            alignment: align_of::<XbNodeAttrIter>(),
        },
    ),
    (
        "XbNodeChildIter",
        Layout {
            size: size_of::<XbNodeChildIter>(),
            alignment: align_of::<XbNodeChildIter>(),
        },
    ),
    (
        "XbNodeClass",
        Layout {
            size: size_of::<XbNodeClass>(),
            alignment: align_of::<XbNodeClass>(),
        },
    ),
    (
        "XbNodeExportFlags",
        Layout {
            size: size_of::<XbNodeExportFlags>(),
            alignment: align_of::<XbNodeExportFlags>(),
        },
    ),
    (
        "XbOpcodeFlags",
        Layout {
            size: size_of::<XbOpcodeFlags>(),
            alignment: align_of::<XbOpcodeFlags>(),
        },
    ),
    (
        "XbOpcodeKind",
        Layout {
            size: size_of::<XbOpcodeKind>(),
            alignment: align_of::<XbOpcodeKind>(),
        },
    ),
    (
        "XbQuery",
        Layout {
            size: size_of::<XbQuery>(),
            alignment: align_of::<XbQuery>(),
        },
    ),
    (
        "XbQueryClass",
        Layout {
            size: size_of::<XbQueryClass>(),
            alignment: align_of::<XbQueryClass>(),
        },
    ),
    (
        "XbQueryContext",
        Layout {
            size: size_of::<XbQueryContext>(),
            alignment: align_of::<XbQueryContext>(),
        },
    ),
    (
        "XbQueryFlags",
        Layout {
            size: size_of::<XbQueryFlags>(),
            alignment: align_of::<XbQueryFlags>(),
        },
    ),
    (
        "XbSilo",
        Layout {
            size: size_of::<XbSilo>(),
            alignment: align_of::<XbSilo>(),
        },
    ),
    (
        "XbSiloClass",
        Layout {
            size: size_of::<XbSiloClass>(),
            alignment: align_of::<XbSiloClass>(),
        },
    ),
    (
        "XbSiloLoadFlags",
        Layout {
            size: size_of::<XbSiloLoadFlags>(),
            alignment: align_of::<XbSiloLoadFlags>(),
        },
    ),
    (
        "XbSiloProfileFlags",
        Layout {
            size: size_of::<XbSiloProfileFlags>(),
            alignment: align_of::<XbSiloProfileFlags>(),
        },
    ),
    (
        "XbValueBindings",
        Layout {
            size: size_of::<XbValueBindings>(),
            alignment: align_of::<XbValueBindings>(),
        },
    ),
];

const RUST_CONSTANTS: &[(&str, &str)] = &[
    ("(guint) XB_BUILDER_COMPILE_FLAG_IGNORE_GUID", "32"),
    ("(guint) XB_BUILDER_COMPILE_FLAG_IGNORE_INVALID", "4"),
    ("(guint) XB_BUILDER_COMPILE_FLAG_NATIVE_LANGS", "2"),
    ("(guint) XB_BUILDER_COMPILE_FLAG_NONE", "0"),
    ("(guint) XB_BUILDER_COMPILE_FLAG_SINGLE_LANG", "8"),
    ("(guint) XB_BUILDER_COMPILE_FLAG_SINGLE_ROOT", "64"),
    ("(guint) XB_BUILDER_COMPILE_FLAG_WATCH_BLOB", "16"),
    ("(guint) XB_BUILDER_NODE_FLAG_HAS_TAIL", "8"),
    ("(guint) XB_BUILDER_NODE_FLAG_HAS_TEXT", "4"),
    ("(guint) XB_BUILDER_NODE_FLAG_IGNORE", "1"),
    ("(guint) XB_BUILDER_NODE_FLAG_LITERAL_TEXT", "2"),
    ("(guint) XB_BUILDER_NODE_FLAG_NONE", "0"),
    ("(guint) XB_BUILDER_NODE_FLAG_STRIP_TEXT", "32"),
    ("(guint) XB_BUILDER_NODE_FLAG_TOKENIZE_TEXT", "16"),
    ("(guint) XB_BUILDER_SOURCE_FLAG_LITERAL_TEXT", "1"),
    ("(guint) XB_BUILDER_SOURCE_FLAG_NONE", "0"),
    ("(guint) XB_BUILDER_SOURCE_FLAG_WATCH_DIRECTORY", "4"),
    ("(guint) XB_BUILDER_SOURCE_FLAG_WATCH_FILE", "2"),
    ("(guint) XB_MACHINE_DEBUG_FLAG_NONE", "0"),
    ("(guint) XB_MACHINE_DEBUG_FLAG_SHOW_OPTIMIZER", "4"),
    ("(guint) XB_MACHINE_DEBUG_FLAG_SHOW_PARSING", "2"),
    ("(guint) XB_MACHINE_DEBUG_FLAG_SHOW_SLOW_PATH", "8"),
    ("(guint) XB_MACHINE_DEBUG_FLAG_SHOW_STACK", "1"),
    ("(guint) XB_MACHINE_PARSE_FLAG_NONE", "0"),
    ("(guint) XB_MACHINE_PARSE_FLAG_OPTIMIZE", "1"),
    ("(guint) XB_NODE_EXPORT_FLAG_ADD_HEADER", "1"),
    ("(guint) XB_NODE_EXPORT_FLAG_COLLAPSE_EMPTY", "32"),
    ("(guint) XB_NODE_EXPORT_FLAG_FORMAT_INDENT", "4"),
    ("(guint) XB_NODE_EXPORT_FLAG_FORMAT_MULTILINE", "2"),
    ("(guint) XB_NODE_EXPORT_FLAG_INCLUDE_SIBLINGS", "8"),
    ("(guint) XB_NODE_EXPORT_FLAG_NONE", "0"),
    ("(guint) XB_NODE_EXPORT_FLAG_ONLY_CHILDREN", "16"),
    ("(guint) XB_OPCODE_FLAG_BOOLEAN", "16"),
    ("(guint) XB_OPCODE_FLAG_BOUND", "8"),
    ("(guint) XB_OPCODE_FLAG_FUNCTION", "4"),
    ("(guint) XB_OPCODE_FLAG_INTEGER", "1"),
    ("(guint) XB_OPCODE_FLAG_TEXT", "2"),
    ("(guint) XB_OPCODE_FLAG_TOKENIZED", "32"),
    ("(guint) XB_OPCODE_FLAG_UNKNOWN", "0"),
    ("(gint) XB_OPCODE_KIND_BOOLEAN", "17"),
    ("(gint) XB_OPCODE_KIND_BOUND_INDEXED_TEXT", "11"),
    ("(gint) XB_OPCODE_KIND_BOUND_INTEGER", "9"),
    ("(gint) XB_OPCODE_KIND_BOUND_TEXT", "10"),
    ("(gint) XB_OPCODE_KIND_BOUND_UNSET", "8"),
    ("(gint) XB_OPCODE_KIND_FUNCTION", "5"),
    ("(gint) XB_OPCODE_KIND_INDEXED_TEXT", "3"),
    ("(gint) XB_OPCODE_KIND_INTEGER", "1"),
    ("(gint) XB_OPCODE_KIND_TEXT", "2"),
    ("(gint) XB_OPCODE_KIND_UNKNOWN", "0"),
    ("(guint) XB_QUERY_FLAG_FORCE_NODE_CACHE", "8"),
    ("(guint) XB_QUERY_FLAG_NONE", "0"),
    ("(guint) XB_QUERY_FLAG_OPTIMIZE", "1"),
    ("(guint) XB_QUERY_FLAG_REVERSE", "4"),
    ("(guint) XB_QUERY_FLAG_USE_INDEXES", "2"),
    ("(guint) XB_SILO_LOAD_FLAG_NONE", "0"),
    ("(guint) XB_SILO_LOAD_FLAG_NO_MAGIC", "1"),
    ("(guint) XB_SILO_LOAD_FLAG_WATCH_BLOB", "2"),
    ("(guint) XB_SILO_PROFILE_FLAG_APPEND", "2"),
    ("(guint) XB_SILO_PROFILE_FLAG_DEBUG", "1"),
    ("(guint) XB_SILO_PROFILE_FLAG_NONE", "0"),
    ("(guint) XB_SILO_PROFILE_FLAG_OPTIMIZER", "8"),
    ("(guint) XB_SILO_PROFILE_FLAG_XPATH", "4"),
    ("XMLB_MAJOR_VERSION", "0"),
    ("XMLB_MICRO_VERSION", "19"),
    ("XMLB_MINOR_VERSION", "3"),
];