Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.ci.fence_lengths

Requirements index · View definition

evidence Valid

Requirement

A {req} opening fence MAY contain four or more colons. Habeas MUST accept opening fences of any length of at least three colons. A colon-only line with fewer colons than the opener MUST remain inside the requirement body, allowing a nested colon directive. A closing fence outside a fenced code example with at least as many colons as the opener MUST end the body.

Rationale

requirements.ci.fence_lengths is satisfied. I found no gaps.

Implementation

  • src/lib.rs#fn[definition_blocks] carries the {impl} reference. It finds each opener through colon_fence, which accepts any run of three or more colons. The opening-fence obligation therefore covers every length from three up, including four or more.
  • A body ends only at a later line that passes three checks. The line must lie outside the Markdown code blocks reported by code_block_ranges and overlaps_protected. It must be a colon-only line, meaning suffix.trim().is_empty(). Its colon count must be at least the opener’s (count >= fence_length). A colon-only line with fewer colons than the opener fails the third check, so it stays in the body. A closer inside a fenced code example is skipped, so it cannot end the body.
  • src/fenced.rs#fn[find_fences] applies the same rule to reference fences. It closes at the next unprotected colon-only line with at least as many colons. It is extra to this requirement and consistent with it.

Tests

  • Opening fence of four or more colons, and a closer at least as long: src/evidence.rs#mod[tests]/fn[validates_four_or_more_colon_fences_and_longer_closers]. It uses ::::/::::, ::::/::::: and :::::::/::::::::. The body contains a nested :::{note}…:::, and the test checks that the whole body is validated and the text after the closer is excluded.
  • A shorter colon-only line staying inside the body: src/lib.rs#mod[tests]/fn[a_longer_colon_fence_contains_a_shorter_nested_directive]. It asserts the exact body text and that “Outside.” falls after the end.
  • A closing fence inside a fenced code example not ending the body: src/evidence.rs#mod[tests]/fn[colon_requirement_span_includes_markdown_and_excludes_following_text]. Its body holds a code block containing :::, and the test requires the full body.
  • Further coverage: src/evidence.rs#mod[tests]/fn[example_bodies_keep_nested_markdown_and_trim_outer_whitespace] covers the {example} form, and src/fenced.rs#mod[tests]/fn[markdown_fences_close_with_enough_colons_and_skip_code] covers nesting and skipped code for reference fences.

The obligation to accept fences of at least three colons is exercised by the ordinary ::: fixtures in these tests. I saw no unspecified behavior beyond what other requirements cover.

Inputs

Implementation

Input 5: outline src/fenced.rs fn[find_fences]
/// Finds fenced references among lines. A fence closes at the next
/// unprotected colon-only line with at least as many colons; fences may nest.
// {impl}`requirements.ci.fence_lengths`
pub(crate) fn find_fences(lines: &[FenceLine<'_>]) -> Vec<Fence> {
    let mut fences = Vec::new();
    for (index, line) in lines.iter().enumerate() {
        if line.protected {
            continue;
        }
        let Some((kind, name, length)) = opening_fence(line.text) else {
            continue;
        };
        let close = (index + 1..lines.len()).find(|&candidate| {
            !lines[candidate].protected && closes(lines[candidate].text, length)
        });
        fences.push(Fence {
            kind,
            name: name.to_owned(),
            open: index,
            close,
        });
    }
    fences
}
Input 7: outline src/lib.rs fn[definition_blocks]
// {impl}`requirements.examples.definition`
// {impl}`requirements.ci.fence_lengths`
pub(crate) fn definition_blocks(content: &str) -> Vec<DefinitionBlock> {
    let code_ranges = code_block_ranges(content);
    let mut lines = Vec::new();
    let mut position = 0;
    for segment in content.split_inclusive('\n') {
        let end = position + segment.len();
        lines.push((
            position,
            end,
            segment.trim_end_matches('\n').trim_end_matches('\r'),
        ));
        position = end;
    }

    let mut blocks = Vec::new();
    let mut index = 0;
    while index < lines.len() {
        let (start, body_start, line) = lines[index];
        let Some((suffix, fence_length)) = colon_fence(line) else {
            index += 1;
            continue;
        };
        let (kind, rest) = if let Some(rest) = suffix.strip_prefix("{req}") {
            (DefinitionKind::Requirement, rest)
        } else if let Some(rest) = suffix.strip_prefix("{example}") {
            (DefinitionKind::Example, rest)
        } else if let Some(rest) = suffix.strip_prefix("{definition}") {
            (DefinitionKind::Term, rest)
        } else {
            index += 1;
            continue;
        };
        // A reserved built-in name is recognized so validation can report it.
        if overlaps_protected(start, body_start, &code_ranges)
            || !rest.chars().next().is_some_and(char::is_whitespace)
            || !(valid_name(rest.trim()) || builtins::is_builtin_name(rest.trim()))
        {
            index += 1;
            continue;
        }
        let name = rest.trim();

        let close_index = (index + 1..lines.len()).find(|&candidate| {
            !overlaps_protected(lines[candidate].0, lines[candidate].1, &code_ranges)
                && colon_fence(lines[candidate].2).is_some_and(|(suffix, count)| {
                    count >= fence_length && suffix.trim().is_empty()
                })
        });
        let (end, body_end, closed) = if let Some(close_index) = close_index {
            (lines[close_index].1, lines[close_index].0, true)
        } else {
            (content.len(), content.len(), false)
        };
        let mut options = Vec::new();
        let mut text_start = body_start;
        if kind != DefinitionKind::Term {
            let body_lines = close_index.unwrap_or(lines.len());
            for (offset, &(option_start, option_end, option)) in
                lines[index + 1..body_lines].iter().enumerate()
            {
                let Some((option_name, value)) = option_line(option) else {
                    break;
                };
                options.push(DefinitionOption {
                    start: option_start,
                    end: option_end,
                    line: index + offset + 2,
                    name: option_name.to_owned(),
                    value: value.to_owned(),
                });
                text_start = option_end;
            }
        }
        blocks.push(DefinitionBlock {
            start,
            end,
            body_start,
            text_start,
            body_end,
            name: name.to_owned(),
            kind,
            closed,
            options,
        });
        index += 1;
    }
    blocks
}

Tests

Input 2: outline src/evidence.rs mod[tests]/fn[colon_requirement_span_includes_markdown_and_excludes_following_text]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[colon_requirement_span_includes_markdown_and_excludes_following_text]
  • Kind: fn
  • src/evidence.rs:3373–3405
    // {test}`requirements.ci.span`
    // {test}`requirements.ci.fence_lengths`
    // {test}`requirements.ci.span`
    #[test]
    fn colon_requirement_span_includes_markdown_and_excludes_following_text() {
        let temp = fixture();
        let first = "First MUST work.\n\n```text\n# Example heading\n:::\n```\n\n## New section\n\nSetext section\n--------------";
        fs::write(
            temp.path().join("md/requirements.md"),
            format!(
                "# Requirements\n\n:::{{req}} first\n{first}\n:::\n\nOutside the requirement.\n\n:::{{req}} second\nSecond MUST work.\n:::\n"
            ),
        )
        .unwrap();
        for (name, requirement) in [("first", first), ("second", "Second MUST work.")] {
            fs::write(
                temp.path()
                    .join(format!("evidence/requirements.{name}.json")),
                json!({
                    "requirement": requirement,
                    "determination": true,
                    "rationale": "The fixture records the current requirement body.",
                    "inputs": []
                })
                .to_string(),
            )
            .unwrap();
        }

        let report = validate_repository(temp.path()).unwrap();
        assert_eq!(report.requirements, 2);
        assert!(report.errors.is_empty(), "{:?}", report.errors);
    }
Input 3: outline src/evidence.rs mod[tests]/fn[validates_four_or_more_colon_fences_and_longer_closers]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[validates_four_or_more_colon_fences_and_longer_closers]
  • Kind: fn
  • src/evidence.rs:3440–3474
    // {test}`requirements.ci.fence_lengths`
    // {test}`requirements.ci.span`
    #[test]
    fn validates_four_or_more_colon_fences_and_longer_closers() {
        let body = "Body MUST remain.\n\n:::{note}\nNested.\n:::\n\nStill in the requirement.";
        for (opening, closing) in [("::::", "::::"), ("::::", ":::::"), (":::::::", "::::::::")] {
            let temp = fixture();
            fs::write(
                temp.path().join("md/requirements.md"),
                format!(
                    "# Requirements\n\n{opening}{{req}} ready\n{body}\n{closing}\n\nOutside the requirement.\n"
                ),
            )
            .unwrap();
            fs::write(
                temp.path().join("evidence/requirements.ready.json"),
                json!({
                    "requirement": body,
                    "determination": true,
                    "rationale": "The entire fenced body was examined.",
                    "inputs": []
                })
                .to_string(),
            )
            .unwrap();

            let report = validate_repository(temp.path()).unwrap();
            assert_eq!(report.requirements, 1, "{opening} ... {closing}");
            assert!(
                report.errors.is_empty(),
                "{opening} ... {closing}: {:?}",
                report.errors
            );
        }
    }
Input 4: outline src/evidence.rs mod[tests]/fn[example_bodies_keep_nested_markdown_and_trim_outer_whitespace]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[example_bodies_keep_nested_markdown_and_trim_outer_whitespace]
  • Kind: fn
  • src/evidence.rs:3476–3496
    // {test}`requirements.examples.definition`
    // {test}`requirements.ci.fence_lengths`
    #[test]
    fn example_bodies_keep_nested_markdown_and_trim_outer_whitespace() {
        let temp = fixture();
        let body = "# Concrete case\n\nGiven ready, it succeeds. {cite}`rules.ready`\n\n:::{note}\nNested explanation.\n:::\n\n```text\n:::{example} literal\n```\n\nThe expected result is success.";
        for (opening, closing) in [("::::", ":::::"), ("::::::", ":::::::")] {
            fs::write(
                temp.path().join("md/rules.md"),
                format!(
                    ":::{{req}} ready\nReady.\n:::\n\n{opening}{{example}} case\n\n  {body}  \n\n{closing}\nText after the example.\n"
                ),
            )
            .unwrap();
            let definitions = super::load_definitions(temp.path()).unwrap();
            let example = &definitions["rules.case"];
            assert_eq!(example.kind, crate::DefinitionKind::Example);
            assert_eq!(example.text, body);
            assert!(!definitions.contains_key("rules.literal"));
        }
    }
Input 6: outline src/fenced.rs mod[tests]/fn[markdown_fences_close_with_enough_colons_and_skip_code]
  • File: src/fenced.rs
  • Selector: mod[tests]/fn[markdown_fences_close_with_enough_colons_and_skip_code]
  • Kind: fn
  • src/fenced.rs:332–352
    // {test}`requirements.references.roles`
    // {test}`requirements.ci.fence_lengths`
    #[test]
    fn markdown_fences_close_with_enough_colons_and_skip_code() {
        let content = "::::{cite} a.b\nouter\n:::{impl} c.d\ninner\n:::\n::::\n```text\n:::{cite} e.f\n```\n:::{test} g.h\nnever closed\n".to_owned();
        let fences = markdown_fences(&content, true);
        assert_eq!(fences.len(), 3);
        assert_eq!(fences[0].name, "a.b");
        assert!(fences[0].closed);
        assert_eq!(
            &content[fences[0].body.clone()],
            "outer\n:::{impl} c.d\ninner\n:::\n"
        );
        assert_eq!(fences[1].name, "c.d");
        assert_eq!(&content[fences[1].body.clone()], "inner\n");
        assert_eq!(fences[2].name, "g.h");
        assert!(!fences[2].closed);
        assert_eq!(fences[2].line, 10);
        // In plain text, the code fence is ordinary text.
        assert_eq!(markdown_fences(&content, false).len(), 4);
    }
Input 8: outline src/lib.rs mod[tests]/fn[a_longer_colon_fence_contains_a_shorter_nested_directive]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[a_longer_colon_fence_contains_a_shorter_nested_directive]
  • Kind: fn
  • src/lib.rs:1890–1904
    // {test}`requirements.ci.span`
    // {test}`requirements.ci.fence_lengths`
    #[test]
    fn a_longer_colon_fence_contains_a_shorter_nested_directive() {
        let content = "::::{req} ready\nIntro.\n\n:::{note}\nNested.\n:::\n::::\n\nOutside.";
        let blocks = definition_blocks(content);
        assert_eq!(blocks.len(), 1);
        assert!(blocks[0].closed);
        assert_eq!(blocks[0].kind, DefinitionKind::Requirement);
        assert_eq!(
            &content[blocks[0].body_start..blocks[0].body_end],
            "Intro.\n\n:::{note}\nNested.\n:::\n"
        );
        assert!(content[blocks[0].end..].contains("Outside."));
    }

Other sources

Input 1: requirements selection requirements.ci.fence_lengths
:::{req} fence_lengths
A `{req}` opening fence MAY contain four or more colons. Habeas MUST accept opening fences of any length of at least three colons. A colon-only line with fewer colons than the opener MUST remain inside the requirement body, allowing a nested colon directive. A closing fence outside a fenced code example with at least as many colons as the opener MUST end the body.
:::
Input 9: outline src/lib.rs fn[colon_fence]
fn colon_fence(line: &str) -> Option<(&str, usize)> {
    let trimmed = line.trim_start_matches(' ');
    if line.len() - trimmed.len() > 3 {
        return None;
    }
    let length = trimmed.bytes().take_while(|byte| *byte == b':').count();
    (length >= 3).then_some((&trimmed[length..], length))
}
Input 10: outline src/lib.rs fn[code_block_ranges]
/// The byte ranges of a Markdown text's code blocks, whose contents stay
/// literal.
pub(crate) fn code_block_ranges(content: &str) -> Vec<Range<usize>> {
    Parser::new(content)
        .into_offset_iter()
        .filter_map(|(event, range)| {
            matches!(event, Event::Start(Tag::CodeBlock(_))).then_some(range)
        })
        .collect()
}
Input 11: outline src/lib.rs fn[overlaps_protected]
fn overlaps_protected(start: usize, end: usize, ranges: &[Range<usize>]) -> bool {
    ranges
        .iter()
        .any(|range| start < range.end && range.start < end)
}