//! Pin: the `lt__Int` / `le__Int` / `gt__Int` / `ge__Int` /
//! `ne__Int` mono symbols lower to a single direct `icmp` (no
//! `compare__Int` call, no `match` over `Ordering`), carrying the
//! `alwaysinline` attribute. The polymorphic prelude bodies are
//! `(match (app compare x y) ...)`; without the direct intercept
//! arm, each `lt`-at-Int call site goes through
//! `compare__Int` → allocate an `Ordering` ctor → match. At `-O2`
//! `alwaysinline` plus `icmp slt i64` lets clang inline the
//! comparison to the use site; without it, bench/check.py
//! regresses on bench_closure_chain (+29% bump_s, +47% rc_s,
//! +29% bump_rss_kb, +48% rc_rss_kb — observed 2026-05-21 before
//! Task 13 of iter operator-routing-eq-ord.1 added these intercept
//! arms).
//!
//! The test reads pre-optimization IR (`ail emit-ir`'s output —
//! emit-ir runs codegen without clang's opt pipeline) and
//! structurally pins the intercept body shape. Post-opt verification
//! lives in `bench/check.py`.

use std::path::PathBuf;
use std::process::Command;

fn fixture_path(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../examples")
        .join(name)
}

fn emit_ir(fixture: &str) -> String {
    let src = fixture_path(fixture);
    let out = Command::new(env!("CARGO_BIN_EXE_ail"))
        .args(["emit-ir", src.to_str().unwrap()])
        .output()
        .expect("ail emit-ir");
    assert!(
        out.status.success(),
        "ail emit-ir failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    String::from_utf8_lossy(&out.stdout).to_string()
}

/// Locate a `define ... @ail_prelude_<sym>(...) <attrs> { ... }`
/// block in the IR and return the body text between the opening
/// `{\n` and the matching closing `}\n`. Anchors on `define` so
/// call sites (which also mention `@ail_prelude_<sym>(`) don't
/// match.
fn extract_fn_body(ir: &str, sym: &str) -> (String, String) {
    let needle = "define ".to_string();
    let mut cursor = 0;
    let sym_marker = format!("@ail_prelude_{sym}(");
    loop {
        let rel = ir[cursor..]
            .find(&needle)
            .unwrap_or_else(|| panic!("no `define` line carrying @ail_prelude_{sym}"));
        let define_start = cursor + rel;
        // The `define` line runs to the next `\n`; check whether the
        // symbol marker appears on that line.
        let line_end = ir[define_start..]
            .find('\n')
            .expect("define line not terminated");
        let line = &ir[define_start..define_start + line_end];
        if line.contains(&sym_marker) {
            // Found the right define. Pull attrs (between `)` and `{`)
            // and body (between `{\n` and `\n}\n`).
            let after_paren = line
                .rfind(')')
                .expect("malformed define line: no close-paren");
            let brace = line
                .find('{')
                .expect("malformed define line: no open-brace");
            let attrs = line[after_paren + 1..brace].trim().to_string();
            let body_start = define_start + brace + 1;
            let body_end = ir[body_start..]
                .find("\n}\n")
                .expect("fn body not terminated by `\\n}\\n`");
            return (attrs, ir[body_start..body_start + body_end].to_string());
        }
        cursor = define_start + line_end + 1;
    }
}

#[test]
fn lt_int_intercept_emits_direct_icmp_slt() {
    let ir = emit_ir("bench_closure_chain.ail");
    let (attrs, body) = extract_fn_body(&ir, "lt__Int");
    assert!(
        attrs.contains("alwaysinline"),
        "lt__Int missing `alwaysinline`; got attrs `{attrs}`"
    );
    assert!(
        body.contains("icmp slt i64"),
        "lt__Int body lacks direct `icmp slt i64`; body:\n{body}"
    );
    assert!(
        !body.contains("@ail_prelude_compare__Int"),
        "lt__Int still routes through compare__Int (intercept arm missing); body:\n{body}"
    );
}

/// `le__Int`, `gt__Int`, `ge__Int`, `ne__Int` — the same intercept
/// family. They are not reachable from bench_closure_chain itself,
/// so this test uses a synthesised fixture that calls each of them
/// once on Int operands. Keeping all five intercept arms on a
/// single bench-style code path under one assertion fence guards
/// the family symmetrically.
#[test]
fn ord_int_intercept_family_emits_direct_icmp() {
    let ir = emit_ir("ord_int_intercept_smoke.ail");
    for (sym, want_op) in &[
        ("lt__Int", "icmp slt i64"),
        ("le__Int", "icmp sle i64"),
        ("gt__Int", "icmp sgt i64"),
        ("ge__Int", "icmp sge i64"),
        ("ne__Int", "icmp ne i64"),
    ] {
        let (attrs, body) = extract_fn_body(&ir, sym);
        assert!(
            attrs.contains("alwaysinline"),
            "{sym} missing `alwaysinline`; got attrs `{attrs}`"
        );
        assert!(
            body.contains(want_op),
            "{sym} body lacks `{want_op}`; body:\n{body}"
        );
        assert!(
            !body.contains("@ail_prelude_compare__Int"),
            "{sym} still routes through compare__Int; body:\n{body}"
        );
        // ne__Int specifically must not be `not (eq x y)` — the spec
        // explicitly rejected the indirection.
        if *sym == "ne__Int" {
            assert!(
                !body.contains("@ail_prelude_eq__Int"),
                "ne__Int uses `not (eq x y)` indirection (forbidden by spec); body:\n{body}"
            );
        }
    }
}
