mln-rs-webgpu 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! The `#ifdef`, `#ifndef`, `#else` and `#endif` blocks of the WGSL
//! sources, kept or dropped by the shader's defines.

use mln_gfx::util_hash::HashMap;

/// Whether `b` is ASCII white space, vertical tab included.
pub(crate) fn is_space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r')
}

#[must_use]
fn is_directive(line: &str, directive: &str) -> bool {
    let b = line.as_bytes();
    let mut pos = 0;
    while pos < b.len() && is_space(b[pos]) {
        pos += 1;
    }
    if pos >= b.len() || b[pos] != b'#' {
        return false;
    }
    pos += 1;
    while pos < b.len() && is_space(b[pos]) {
        pos += 1;
    }
    if !line[pos..].starts_with(directive) {
        return false;
    }
    pos += directive.len();
    pos == b.len() || is_space(b[pos])
}

#[must_use]
fn directive_argument(line: &str) -> String {
    let Some(hash) = line.find('#') else {
        return String::new();
    };
    let is_blank = |c: char| c == ' ' || c == '\t';
    // The directive, then the argument after it.
    let Some(pos) = line[hash + 1..].find(|c| !is_blank(c)).map(|p| p + hash + 1) else {
        return String::new();
    };
    let Some(pos) = line[pos..].find(is_blank).map(|p| p + pos) else {
        return String::new();
    };
    let Some(pos) = line[pos..].find(|c| !is_blank(c)).map(|p| p + pos) else {
        return String::new();
    };
    let end = line[pos..].find([' ', '\t', '\r', '\n']).map(|p| p + pos);
    match end {
        Some(end) => line[pos..end].to_owned(),
        None => line[pos..].to_owned(),
    }
}

struct ConditionalFrame {
    parent_active: bool,
    condition: bool,
    else_seen: bool,
}

/// Strips `#ifdef`/`#ifndef`/`#else`/`#endif` blocks according to
/// `defines` (only key presence matters).
#[must_use]
pub(crate) fn preprocess_wgsl(source: &str, defines: &HashMap<String, bool>) -> String {
    let mut output = String::with_capacity(source.len());
    let mut stack: Vec<ConditionalFrame> = Vec::new();
    let mut current_active = true;

    // The text after the last '\n' is a line only if it is non-empty, so ""
    // and "a\n" have no trailing empty line.
    let mut lines: Vec<&str> = source.split('\n').collect();
    if lines.last() == Some(&"") {
        lines.pop();
    }
    for line in lines {
        if is_directive(line, "ifdef") {
            let condition = defines.contains_key(&directive_argument(line));
            stack.push(ConditionalFrame { parent_active: current_active, condition, else_seen: false });
            current_active = current_active && condition;
            continue;
        }
        if is_directive(line, "ifndef") {
            let condition = !defines.contains_key(&directive_argument(line));
            stack.push(ConditionalFrame { parent_active: current_active, condition, else_seen: false });
            current_active = current_active && condition;
            continue;
        }
        if is_directive(line, "else") {
            let Some(frame) = stack.last_mut() else {
                continue;
            };
            if frame.else_seen {
                current_active = false;
            } else {
                frame.else_seen = true;
                current_active = frame.parent_active && !frame.condition;
            }
            continue;
        }
        if is_directive(line, "endif") {
            let Some(frame) = stack.pop() else {
                continue;
            };
            current_active = frame.parent_active;
            continue;
        }
        if current_active {
            output.push_str(line);
            output.push('\n');
        }
    }
    output
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Each case: the source, its defines, and the lines kept.
    #[test]
    fn blocks_keep_their_lines_by_the_defines() {
        let cases: &[(&str, &[&str], &str)] = &[
            ("", &[], ""),
            ("a\nb", &[], "a\nb\n"),
            ("a\n#ifdef A\nb\n#endif\nc\n", &["A"], "a\nb\nc\n"),
            ("a\n#ifdef A\nb\n#endif\nc\n", &[], "a\nc\n"),
            ("a\n#ifndef A\nb\n#endif\nc\n", &[], "a\nb\nc\n"),
            ("a\n#ifndef A\nb\n#endif\nc\n", &["A"], "a\nc\n"),
            ("#ifdef A\na\n#else\nnot_a\n#endif\n", &["A"], "a\n"),
            ("#ifdef A\na\n#else\nnot_a\n#endif\n", &[], "not_a\n"),
            // A second `#else` ends the block's kept lines.
            ("#ifdef A\na\n#else\nnot_a\n#else\nagain\n#endif\n", &[], "not_a\n"),
            ("#ifdef A\na\n#ifdef B\nb\n#else\nnot_b\n#endif\na2\n#endif\nc\n", &["A", "B"], "a\nb\na2\nc\n"),
            ("#ifdef A\na\n#ifdef B\nb\n#else\nnot_b\n#endif\na2\n#endif\nc\n", &["A"], "a\nnot_b\na2\nc\n"),
            // An inner `#else` stays dropped inside a dropped block.
            ("#ifdef A\na\n#ifdef B\nb\n#else\nnot_b\n#endif\na2\n#endif\nc\n", &["B"], "c\n"),
            // White space around the `#`, the directive and its argument.
            ("  #  ifdef\tA  \na\n\t#endif\n", &["A"], "a\n"),
            // Only the first word names the define.
            ("#ifdef A B\na\n#endif\n", &["A"], "a\n"),
            // A directive is a whole word, and only at the start of a line.
            ("#ifdefA\n// #ifdef A\n#endif\n", &[], "#ifdefA\n// #ifdef A\n"),
            // An `#else` or `#endif` outside a block is dropped.
            ("a\n#endif\n#else\nb\n", &[], "a\nb\n"),
        ];
        for &(source, keys, kept) in cases {
            let defines = keys.iter().map(|key| ((*key).to_owned(), true)).collect();
            assert_eq!(preprocess_wgsl(source, &defines), kept, "{source:?} with {keys:?}");
        }
    }
}