wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Validate documented Rust fences, dependency manifests and language coverage.
//!
//! The released examples must run as shown, refer to the documented crate
//! version, and use fence languages the repository can validate.

use rstest::rstest;

use super::{
    DOCUMENTED_RELEASE,
    TestedExample,
    load_documented_examples,
    load_documents,
    parsed_manifest,
};

/// Rustdoc attributes a documented Rust fence may carry.
///
/// `ignore` is absent on purpose: an ignored fence is an untested one.
const ACCEPTED_RUST_INFO: &[&str] = &["rust", "rust,no_run", "rust,compile_fail"];

/// Return the info string of an example's fence, including rustdoc attributes.
/// For example, an indented `rust,no_run` fence still carries `rust,no_run`.
fn fence_info(example: &TestedExample) -> &str {
    example
        .opening_fence
        .trim_start()
        .trim_start_matches(['`', '~'])
        .trim()
}

/// Return the first line rustdoc would compile but hide from its rendering.
///
/// GitHub shows such a line verbatim, so a reader copying the example would not
/// get what was tested.
fn hidden_rustdoc_line(body: &str) -> Option<&str> {
    body.lines().find(|line| {
        let code = line.trim_start();
        code == "#" || code.starts_with("# ")
    })
}

/// Reject unsupported Rustdoc attributes, such as `rust,ignore`.
fn validate_rust_info(example: &TestedExample) -> Result<(), String> {
    let info = fence_info(example);
    if ACCEPTED_RUST_INFO.contains(&info) {
        return Ok(());
    }
    Err(format!(
        "{} in {} uses unsupported fence info '{info}'",
        example.id, example.document
    ))
}

#[test]
fn rust_fences_are_doctests_that_hide_nothing() -> Result<(), String> {
    for example in load_documented_examples()
        .iter()
        .filter(|example| example.language == "rust")
    {
        validate_rust_info(example)?;
        if let Some(hidden) = hidden_rustdoc_line(&example.source) {
            return Err(format!(
                "{} in {} hides {hidden:?}; readers copying it would not get what was tested",
                example.id, example.document
            ));
        }
    }
    Ok(())
}

#[rstest]
#[case::hidden_item("# fn main() {}\nlet x = 1;\n", Some("# fn main() {}"))]
#[case::hidden_indented("    # let y = 2;\n", Some("    # let y = 2;"))]
#[case::bare_hash("#\n", Some("#"))]
#[case::attribute("#[derive(Debug)]\nstruct A;\n", None)]
#[case::inner_attribute("#![allow(unused)]\n", None)]
#[case::comment("// # not hidden\nlet x = 1;\n", None)]
fn hidden_lines_are_detected(#[case] body: &str, #[case] expected: Option<&str>) {
    assert_eq!(hidden_rustdoc_line(body), expected);
}

/// Load one fixture fence through the same loader used for shipped examples.
fn marked_example(fence: &str) -> TestedExample {
    let source = format!("<!-- tested-example: fixture -->\n{fence}\n");
    load_documents(&[("guide.md", &source)])
        .expect("valid marked fence")
        .pop()
        .expect("the loader retained the example")
}

#[rstest]
#[case::indented(("   ```rust\nfn main() {}\n   ```", "rust"), true)]
#[case::no_run(("```rust,no_run\nfn main() {}\n```", "rust,no_run"), true)]
#[case::ignored(("```rust,ignore\nfn main() {}\n```", "rust,ignore"), false)]
fn rust_attributes_are_validated_after_stripping_indentation(
    #[case] fixture: (&str, &str),
    #[case] supported: bool,
) {
    let (fence, info) = fixture;
    let example = marked_example(fence);
    assert_eq!(fence_info(&example), info);
    assert_eq!(validate_rust_info(&example).is_ok(), supported);
}

/// Reject workspace crate dependencies that lack the exact documented release pin.
fn validate_versions(dependencies: &toml::Table) -> Result<(), String> {
    let expected = format!("={DOCUMENTED_RELEASE}");
    for crate_name in ["wireframe", "wireframe_testing"] {
        let Some(dependency) = dependencies.get(crate_name) else {
            continue;
        };
        let requirement = dependency
            .as_str()
            .or_else(|| dependency.get("version").and_then(toml::Value::as_str));
        if requirement != Some(expected.as_str()) {
            return Err(format!("pins {crate_name} to the wrong release"));
        }
    }
    Ok(())
}

/// Check one documented dependency table against the release and feature list.
/// For example, an exact Wireframe pin with a declared feature is accepted.
fn validate_dependencies(dependencies: &toml::Table, features: &toml::Table) -> Result<(), String> {
    validate_versions(dependencies)?;
    let requested = dependencies
        .get("wireframe")
        .and_then(|wireframe| wireframe.get("features"))
        .and_then(toml::Value::as_array);
    let unknown = requested
        .into_iter()
        .flatten()
        .filter_map(toml::Value::as_str)
        .find(|name| !features.contains_key(*name));
    if let Some(name) = unknown {
        return Err(format!("names unknown feature '{name}'"));
    }
    Ok(())
}

#[test]
fn dependency_examples_name_the_documented_release_and_real_features() -> Result<(), String> {
    let manifest = parsed_manifest();
    let features = manifest
        .get("features")
        .and_then(toml::Value::as_table)
        .expect("Cargo.toml should declare features");

    let examples = load_documented_examples();
    for example in examples.iter().filter(|example| example.language == "toml") {
        let parsed: toml::Table = example
            .source
            .parse()
            .expect("example should be valid TOML");
        let sections = ["dependencies", "dev-dependencies"]
            .iter()
            .filter_map(|section| parsed.get(*section).and_then(toml::Value::as_table));
        for dependencies in sections {
            validate_dependencies(dependencies, features)
                .map_err(|problem| format!("{} {problem}", example.id))?;
        }
    }
    Ok(())
}

#[rstest]
#[case::wrong_version(r#"wireframe = "=0.0.0""#, Some("wrong release"))]
#[case::wrong_companion(r#"wireframe_testing = { version = "=0.0.0" }"#, Some("wrong release"))]
#[case::missing_exact_pin(r#"wireframe = "{version}""#, Some("wrong release"))]
#[case::missing_version(r#"wireframe = { path = "../wireframe" }"#, Some("wrong release"))]
#[case::unknown_feature(
    r#"wireframe = { version = "={version}", features = ["unknown"] }"#,
    Some("unknown feature 'unknown'")
)]
#[case::valid(
    r#"wireframe = { version = "={version}", features = ["known"] }"#,
    None
)]
fn dependency_validation_rejects_invalid_release_requirements(
    #[case] declaration: &str,
    #[case] expected: Option<&str>,
) {
    let dependencies = declaration
        .replace("{version}", DOCUMENTED_RELEASE)
        .parse()
        .expect("fixture dependencies should parse");
    let features = "known = []".parse().expect("fixture features should parse");
    let result = validate_dependencies(&dependencies, &features);
    if let Some(problem) = expected {
        let error = result.expect_err("the invalid declaration must fail");
        assert!(error.contains(problem), "unexpected error: {error}");
    } else {
        assert_eq!(result, Ok(()));
    }
}

/// Every fence language needs an owner, so a new one cannot go unvalidated.
///
/// `rust` runs through rustdoc, `toml` and `bash` are checked by this suite,
/// `mermaid` by `make nixie`, and `text` is reserved for illustrations such as
/// sample output and code from an earlier release.
fn validate_fence_language(example: &TestedExample) -> Result<(), String> {
    match example.language.as_str() {
        "rust" | "toml" | "bash" | "text" => Ok(()),
        "mermaid" if has_nixie_delimiters(example) => Ok(()),
        "mermaid" => Err(format!(
            "{} in {} needs unindented three-backtick delimiters and plain 'mermaid' for Nixie",
            example.id, example.document
        )),
        language => Err(format!(
            "{} in {} uses unvalidated language '{language}'",
            example.id, example.document
        )),
    }
}

#[test]
fn every_fence_language_has_a_validator() -> Result<(), String> {
    load_documented_examples()
        .iter()
        .try_for_each(validate_fence_language)
}

#[test]
fn an_unknown_language_needs_a_validator() {
    let example = marked_example("```python\nprint(1)\n```");
    let error = validate_fence_language(&example).expect_err("Python has no validator");
    assert!(error.contains("unvalidated language 'python'"));
}

/// Check that Nixie 1.1's three-backtick scanner can see both fence lines.
///
/// The loader also recognizes, for example, a three-backtick Mermaid fence
/// closed by four backticks. Nixie can miss that example.
fn has_nixie_delimiters(example: &TestedExample) -> bool {
    example
        .opening_fence
        .strip_prefix("```")
        .is_some_and(|info| info.trim() == "mermaid")
        && example.closing_fence.trim_end_matches([' ', '\t']) == "```"
}

#[rstest]
#[case::backticks(("```mermaid", "```"), true)]
#[case::whitespace(("``` mermaid ", "``` \t"), true)]
#[case::longer_closer(("```mermaid", "````"), false)]
#[case::longer_pair(("````mermaid", "````"), false)]
#[case::tildes(("~~~mermaid", "~~~"), false)]
#[case::indented_opener((" ```mermaid", "```"), false)]
#[case::indented_closer(("```mermaid", " ```"), false)]
#[case::attributes(("```mermaid,ignore", "```"), false)]
fn mermaid_delimiters_must_be_visible_to_nixie(
    #[case] delimiters: (&str, &str),
    #[case] supported: bool,
) {
    let (opener, closer) = delimiters;
    let example = marked_example(&format!("{opener}\nflowchart TD\n{closer}"));
    assert_eq!(validate_fence_language(&example).is_ok(), supported);
}