//! Generates the complete-grammar appendix from `tree-sitter-bynk/src/grammar.json`
//! and keeps it up to date.
//!
//! `docs/src/reference/grammar-appendix.md` is rendered from the compiled grammar
//! (via the `bynk-grammar` crate), so it cannot drift from the parser. The
//! annotated, per-construct reference (`reference/grammar.md`) is authored by
//! hand but embeds the same generated productions via the `{{#grammar}}`
//! preprocessor. Regenerate the appendix after a grammar change with:
//!     BYNK_BLESS=1 cargo test -p bynkc --test grammar_reference

use std::fs;
use std::path::PathBuf;

fn grammar_json() -> String {
    let path =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../tree-sitter-bynk/src/grammar.json");
    fs::read_to_string(path).expect("read grammar.json")
}

#[test]
fn generated_grammar_appendix_is_up_to_date() {
    let page =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/src/reference/grammar-appendix.md");
    let rendered = bynk_grammar::render_appendix(&grammar_json());

    if std::env::var_os("BYNK_BLESS").is_some() {
        fs::write(&page, &rendered).unwrap();
        return;
    }

    let current = fs::read_to_string(&page).unwrap_or_default();
    assert_eq!(
        current, rendered,
        "docs/src/reference/grammar-appendix.md is out of date with the grammar.\n\
         Regenerate with: BYNK_BLESS=1 cargo test -p bynkc --test grammar_reference"
    );
}
