kartta-lang-python 0.0.0

Python extraction for the kartta code graph: functions, classes, fields, calls and imports
Documentation
const DOUBLE_TRIPLE_QUOTE: &[u8] = b"\"\"\"";
const SINGLE_TRIPLE_QUOTE: &[u8] = b"'''";

// constraint: the scan reads only the header, the leading run of blank, `#` comment and module docstring lines, and
// stops at the first statement, so an ordinary file costs a short header scan and allocates nothing; a marker below
// real code is ignored, because a hand-written file may mention the phrase; a UTF-8 byte order mark before the header
// is no statement
pub(crate) fn is_generated_source(source: &[u8]) -> bool {
    let source = source.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(source);
    let mut open_docstring: Option<&[u8]> = None;
    for raw in source.split(|&byte| byte == b'\n') {
        let mut line = raw.trim_ascii();

        if let Some(delimiter) = open_docstring {
            let (inside, after) = find_close(line, delimiter).map_or((line, None), |end| {
                (
                    &line[..end],
                    Some(line[end + delimiter.len()..].trim_ascii()),
                )
            });
            if marks_generated(inside) {
                return true;
            }
            let Some(after) = after else {
                continue;
            };
            open_docstring = None;
            line = after;
        }

        match header_line(line) {
            HeaderLine::Marked => return true,
            HeaderLine::Header => {}
            HeaderLine::OpensDocstring(delimiter) => open_docstring = Some(delimiter),
            HeaderLine::Code => break,
        }
    }

    false
}

enum HeaderLine {
    Marked,
    Header,
    OpensDocstring(&'static [u8]),
    Code,
}

// constraint: a one-line docstring is header up to its closing delimiter, and the rest of the line reads as a line of
// its own, so a comment after it stays header and code after it ends the header unread
fn header_line(mut line: &[u8]) -> HeaderLine {
    loop {
        if line.is_empty() {
            return HeaderLine::Header;
        }
        if line.starts_with(b"#") {
            return marked_or(line, HeaderLine::Header);
        }
        let Some((delimiter, prefix)) = opening_triple_quote(line) else {
            return HeaderLine::Code;
        };

        let body = &line[prefix + delimiter.len()..];
        let Some(end) = find_close(body, delimiter) else {
            return marked_or(body, HeaderLine::OpensDocstring(delimiter));
        };
        if marks_generated(&body[..end]) {
            return HeaderLine::Marked;
        }
        line = body[end + delimiter.len()..].trim_ascii();
    }
}

fn marked_or(text: &[u8], otherwise: HeaderLine) -> HeaderLine {
    if marks_generated(text) {
        HeaderLine::Marked
    } else {
        otherwise
    }
}

fn marks_generated(line: &[u8]) -> bool {
    announces(line, b"@generated") || announces(line, b"DO NOT EDIT")
}

// constraint: documenting the convention means quoting the marker in backticks, so an occurrence inside a code span is
// a mention, not a banner
fn announces(line: &[u8], marker: &[u8]) -> bool {
    let mut outside_span = true;
    for (at, &byte) in line.iter().enumerate() {
        if outside_span && line[at..].starts_with(marker) {
            return true;
        }
        outside_span ^= byte == b'`';
    }
    false
}

// constraint: a delimiter whose first quote an odd run of backslashes escapes closes nothing, in a raw string as in any
// other
fn find_close(haystack: &[u8], delimiter: &[u8]) -> Option<usize> {
    (haystack.windows(delimiter.len()).enumerate())
        .filter(|(_, window)| *window == delimiter)
        .map(|(at, _)| at)
        .find(|&at| {
            let backslashes = haystack[..at]
                .iter()
                .rev()
                .take_while(|&&byte| byte == b'\\')
                .count();
            backslashes % 2 == 0
        })
}

// constraint: a module docstring may carry the one-letter prefix of a raw or a unicode string, `r"""` or `U'''`, which
// the scan skips before it matches the delimiter; a bytes or a formatted string is no docstring
fn opening_triple_quote(line: &[u8]) -> Option<(&'static [u8], usize)> {
    let prefix = usize::from(
        line.first()
            .is_some_and(|byte| matches!(byte.to_ascii_lowercase(), b'r' | b'u')),
    );
    let rest = &line[prefix..];

    [DOUBLE_TRIPLE_QUOTE, SINGLE_TRIPLE_QUOTE]
        .into_iter()
        .find(|delimiter| rest.starts_with(delimiter))
        .map(|delimiter| (delimiter, prefix))
}

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

    #[test]
    fn a_banner_announces_even_when_the_line_quotes_something_else() {
        assert!(announces(
            b"# Code generated by `gen.exe`. DO NOT EDIT.",
            b"DO NOT EDIT"
        ));
        assert!(announces(b"# @generated", b"@generated"));
    }

    #[test]
    fn a_quoted_marker_only_mentions() {
        let mention = b"Emitted files carry a `@generated` / `DO NOT EDIT` header.";

        assert!(!announces(mention, b"@generated"));
        assert!(!announces(mention, b"DO NOT EDIT"));
    }

    #[test]
    fn a_marker_after_a_closed_span_still_announces() {
        assert!(announces(b"# see `docs.md`: @generated", b"@generated"));
        assert!(!announces(b"# see `docs.md: @generated", b"@generated"));
    }

    #[test]
    fn a_line_without_the_marker_never_announces() {
        assert!(!announces(b"# an ordinary header", b"@generated"));
        assert!(!announces(b"", b"@generated"));
    }

    #[test]
    fn a_docstring_prefix_is_skipped_before_its_delimiter() {
        assert!(matches!(
            opening_triple_quote(b"r'''x"),
            Some((SINGLE_TRIPLE_QUOTE, 1))
        ));
        assert!(matches!(
            opening_triple_quote(b"U\"\"\"x"),
            Some((DOUBLE_TRIPLE_QUOTE, 1))
        ));
        assert!(matches!(
            opening_triple_quote(b"\"\"\"x"),
            Some((DOUBLE_TRIPLE_QUOTE, 0))
        ));
        assert!(opening_triple_quote(b"x = 1").is_none());
    }

    #[test]
    fn a_bytes_or_formatted_string_opens_no_docstring() {
        for line in [
            b"f\"\"\"x".as_slice(),
            b"rb'''x",
            b"b'''x",
            b"Rf\"\"\"x",
            b"ur'''x",
        ] {
            assert!(
                opening_triple_quote(line).is_none(),
                "{}",
                String::from_utf8_lossy(line)
            );
        }
    }
}