Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

92.7 KB
Raw Blame
//! Effects of an export that `record` cannot see: it compares return values only, so a function
//! that changes its argument in place, prints, or returns nothing is "matched" by a port that does
//! nothing. One rule, shared by every language plugin and by `bridge`, `analyze` and `profile`
//! (through [`crate::bridge::js_only_reason`]), so the three commands cannot disagree.

use super::Lang;

/// The reason an export that returns nothing stays in the source language.
pub const RETURNS_NOTHING: &str = "returns nothing: the recording only compares return values, \
     so a port that does nothing would pass";

/// Whether the return type, as the plugins write it in the type dialect, is "no value".
pub fn returns_nothing(returns: &str) -> bool {
    let r = returns.trim();
    let inner = r
        .strip_prefix("Promise<")
        .and_then(|r| r.strip_suffix('>'))
        .unwrap_or(r)
        .trim();
    matches!(inner, "void" | "undefined" | "null" | "never")
}

/// Mutating methods of containers, in every language the bridge reads, lower case. A method of
/// this name called on a parameter changes the caller's object.
const MUTATORS: &[&str] = &[
    "push",
    "pop",
    "shift",
    "unshift",
    "splice",
    "sort",
    "reverse",
    "fill",
    "copywithin",
    "set",
    "add",
    "delete",
    "clear",
    "append",
    "extend",
    "insert",
    "remove",
    "discard",
    "update",
    "setdefault",
    "popitem",
    "popleft",
    "appendleft",
    "extendleft",
    "put",
    "putall",
    "putifabsent",
    "addall",
    "removeall",
    "retainall",
    "removeif",
    "offer",
    "poll",
    "addfirst",
    "addlast",
    "removefirst",
    "removelast",
    "addrange",
    "removeat",
    "removerange",
    "removeall",
    "setlength",
    "sortby",
    "sortwith",
    "shuffle",
    "swap",
    "prepend",
    "delete_at",
    "delete_if",
    "keep_if",
    "store",
    "write",
];

/// Print calls: output the recording does not capture.
fn prints(lang: Lang) -> &'static [&'static str] {
    match lang {
        Lang::Ts => &[
            "console.log(",
            "console.error(",
            "console.warn(",
            "console.info(",
            "console.debug(",
            "console.table(",
            "process.stdout.write(",
            "process.stderr.write(",
        ],
        Lang::Python => &["print(", "sys.stdout.write(", "sys.stderr.write("],
        Lang::C => &[
            "printf(",
            "puts(",
            "putchar(",
            "putc(",
            "fputc(",
            "fputs(",
            "fprintf(",
            "dprintf(",
            "vprintf(",
            "vfprintf(",
            "fwrite(",
            "perror(",
        ],
        Lang::Go => &[
            "fmt.Print",
            "fmt.Fprint",
            "os.Stdout",
            "os.Stderr",
            "println(",
            "log.Print",
            "log.Fatal",
            "log.Panic",
        ],
        Lang::Java => &["System.out.", "System.err."],
        Lang::Kotlin => &["println(", "print(", "System.out.", "System.err."],
        Lang::Ruby => &[
            "puts ", "puts(", "print ", "print(", "$stdout", "$stderr", "STDOUT", "STDERR",
            "warn ", "warn(", "pp ", "pp(",
        ],
        Lang::Php => &[
            "echo ",
            "print ",
            "print(",
            "printf(",
            "var_dump(",
            "print_r(",
            "error_log(",
        ],
        Lang::Csharp => &[
            "Console.Write",
            "Console.Error",
            "Debug.Write",
            "Trace.Write",
        ],
        Lang::Powershell => &[
            "write-host",
            "write-error",
            "write-warning",
            "write-verbose",
            "write-information",
            "write-debug",
            "out-host",
            "out-file",
            "[console]::",
        ],
        Lang::Swift => &["print(", "debugPrint(", "dump(", "NSLog(", "fputs("],
    }
}

/// Reads of the environment, working directory or home: the recording would hold this machine's
/// value (`ENV["HOME"]` was recorded as `/root`), and the port must read the same variable.
fn environment(lang: Lang) -> &'static [&'static str] {
    match lang {
        Lang::Ts => &[
            "process.env",
            "process.cwd(",
            "os.homedir(",
            "os.hostname(",
            "os.tmpdir(",
            "os.userInfo(",
        ],
        Lang::Python => &[
            "os.environ",
            "os.getenv(",
            "environ[",
            "environ.get(",
            "getenv(",
            "os.getcwd(",
            "Path.home(",
            "Path.cwd(",
            "expanduser(",
            "socket.gethostname(",
        ],
        Lang::Go => &[
            "os.Getenv(",
            "os.LookupEnv(",
            "os.Environ(",
            "os.Getwd(",
            "os.UserHomeDir(",
            "os.Hostname(",
            // `os.Expand(` stays out: it reads through the mapping function it is given.
            "os.ExpandEnv(",
            "os.TempDir(",
            "os.UserConfigDir(",
            "os.UserCacheDir(",
            "os.Executable(",
            "os.Getpid(",
            "os.Getppid(",
            "os.Getuid(",
            "os.Getgid(",
        ],
        Lang::Java | Lang::Kotlin => &[
            "System.getenv(",
            "System.getProperty(",
            "System.getProperties(",
            "InetAddress.getLocalHost(",
            "Locale.getDefault(",
            "TimeZone.getDefault(",
            "ZoneId.systemDefault(",
            "Charset.defaultCharset(",
        ],
        Lang::Ruby => &[
            "ENV[",
            "ENV.",
            "Dir.pwd",
            "Dir.home",
            "Etc.",
            "Dir.tmpdir",
            "Dir.mktmpdir",
            "Socket.gethostname",
            "Process.pid",
            "Process.uid",
            "Gem.user_home",
        ],
        Lang::Php => &[
            "getenv(",
            "$_ENV",
            "$_SERVER",
            "getcwd(",
            "gethostname(",
            "sys_get_temp_dir(",
            "getmypid(",
            "getmyuid(",
            "get_current_user(",
            "php_uname(",
        ],
        Lang::Csharp => &[
            "Environment.GetEnvironmentVariable",
            "Environment.CurrentDirectory",
            "Environment.MachineName",
            "Environment.UserName",
            "Environment.GetFolderPath",
            "Directory.GetCurrentDirectory(",
            "Path.GetTempPath(",
            "Environment.ProcessId",
            "Environment.ProcessorCount",
            "Environment.OSVersion",
            "Environment.UserDomainName",
            "Environment.GetCommandLineArgs",
            "AppContext.BaseDirectory",
        ],
        Lang::Powershell => &["$env:", "[environment]::", "get-location", "$pwd", "$home"],
        Lang::Swift => &[
            "ProcessInfo",
            "FileManager.default.currentDirectoryPath",
            // In full: a name after `.` is skipped, so `homeDirectoryForCurrentUser` alone never matches.
            "FileManager.default.homeDirectoryForCurrentUser",
            "FileManager.default.temporaryDirectory",
            "NSHomeDirectory(",
            "NSTemporaryDirectory(",
            "NSUserName(",
            "NSFullUserName(",
            "getenv(",
        ],
        Lang::C => &[
            "getenv(",
            "getcwd(",
            "secure_getenv(",
            "gethostname(",
            "getlogin(",
            "getlogin_r(",
            "getpid(",
            "getuid(",
            "uname(",
        ],
    }
}

/// Clock and random calls: a function that takes nothing and reads one gives a different answer
/// each call, and the single recorded case is one moment.
fn clock_and_random(lang: Lang) -> &'static [&'static str] {
    match lang {
        Lang::Ts => &[
            "Date.now(",
            "new Date(",
            "Math.random(",
            "performance.now(",
            "crypto.randomUUID(",
            "crypto.getRandomValues(",
            "crypto.randomBytes(",
            "crypto.randomInt(",
            // Also `process.hrtime.bigint()`.
            "process.hrtime",
        ],
        Lang::Python => &[
            "time.time(",
            "time.monotonic(",
            "datetime.now(",
            "datetime.utcnow(",
            "date.today(",
            // `date.today(` does not match inside `datetime.today(`, as a match starts at a name.
            "datetime.today(",
            // With no time given, these read the current time.
            "time.localtime(",
            "time.gmtime(",
            "time.strftime(",
            "time.ctime(",
            "time.asctime(",
            "random.",
            "uuid.uuid",
            "secrets.",
        ],
        Lang::Go => &["time.Now(", "rand.", "time.Since(", "time.Until("],
        Lang::Java | Lang::Kotlin => &[
            "System.currentTimeMillis(",
            "System.nanoTime(",
            ".now(",
            "new Random(",
            "Math.random(",
            "UUID.randomUUID(",
            "Random.",
            ".shuffled(",
            ".random(",
            "Collections.shuffle(",
            // `java.util.Collections.shuffle(`: a name after `.` is skipped unless the entry starts with one.
            ".Collections.shuffle(",
            // `Random.` and `new Random(` do not match inside a longer name or a full one.
            "ThreadLocalRandom.",
            "SecureRandom(",
            ".Random(",
            ".ThreadLocalRandom.",
            ".SecureRandom(",
        ],
        Lang::Ruby => &[
            "Time.now",
            "Time.new",
            "Date.today",
            "rand(",
            "Random.",
            "SecureRandom",
            ".shuffle",
            ".sample",
        ],
        Lang::Php => &[
            "time(",
            "date(",
            "rand(",
            "mt_rand(",
            "microtime(",
            "random_int(",
            "uniqid(",
            "shuffle(",
            "str_shuffle(",
            "array_rand(",
            "random_bytes(",
            "lcg_value(",
            // A match starts at a name boundary, so `date(` and `time(` miss these. Each reads
            // now when given no timestamp or a relative string.
            "gmdate(",
            "idate(",
            "getdate(",
            "localtime(",
            "mktime(",
            "gmmktime(",
            "strtotime(",
            "gettimeofday(",
        ],
        Lang::Csharp => &[
            "DateTime.Now",
            "DateTime.UtcNow",
            "DateTime.Today",
            "DateTimeOffset.Now",
            "DateTimeOffset.UtcNow",
            "Random",
            "Guid.NewGuid",
            // Also `Environment.TickCount64`.
            "Environment.TickCount",
            "Stopwatch.GetTimestamp(",
            "Stopwatch.StartNew(",
            "Stopwatch.GetElapsedTime(",
        ],
        // Only these static members of `[datetime]` read the clock; `IsLeapYear` and
        // `DaysInMonth` compute from their arguments, and so does `Parse` when the string has a
        // date. `Parse` of a time-only string (`'09:00'`) reads today's date: see
        // `powershell_time_only`.
        Lang::Powershell => &[
            "get-date",
            "get-random",
            "new-guid",
            "[datetime]::now",
            "[datetime]::utcnow",
            "[datetime]::today",
            "[system.datetime]::now",
            "[system.datetime]::utcnow",
            "[system.datetime]::today",
            "[datetimeoffset]::now",
            "[datetimeoffset]::utcnow",
            "[system.datetimeoffset]::now",
            "[system.datetimeoffset]::utcnow",
        ],
        Lang::Swift => &[
            "Date()",
            "Date.now",
            ".random",
            "UUID()",
            ".randomElement(",
            ".shuffled(",
            "arc4random(",
            "arc4random_uniform(",
            "arc4random_buf(",
            "drand48(",
            "CFAbsoluteTimeGetCurrent(",
            "DispatchTime.now(",
            "mach_absolute_time(",
        ],
        Lang::C => &[
            "time(",
            "rand(",
            "clock(",
            "clock_gettime(",
            "gettimeofday(",
            "timespec_get(",
            "random(",
            "arc4random(",
            "arc4random_uniform(",
            "arc4random_buf(",
            "drand48(",
            "erand48(",
            "lrand48(",
            "nrand48(",
            "mrand48(",
            "jrand48(",
            "rand_r(",
        ],
    }
}

/// Module-level state read or written from inside an export: `global counter`, `static $n`, a
/// Ruby instance variable of the module. A port owns a second copy of it.
fn shared_state(lang: Lang) -> &'static [&'static str] {
    match lang {
        Lang::Python => &["global "],
        Lang::Php => &["global ", "static $"],
        Lang::Ruby => &["@"],
        Lang::Powershell => &["$script:", "$global:"],
        _ => &[],
    }
}

/// `code` with comments and the insides of string literals blanked, so a docstring that says
/// `print(x)` is not a print. Offsets and line breaks stay.
pub fn blank(lang: Lang, code: &str) -> String {
    let b = code.as_bytes();
    let hash = matches!(
        lang,
        Lang::Python | Lang::Ruby | Lang::Php | Lang::Powershell
    );
    let slash = !matches!(lang, Lang::Python | Lang::Ruby | Lang::Powershell);
    let mut out = b.to_vec();
    let blank_range = |out: &mut Vec<u8>, from: usize, to: usize| {
        for byte in out.iter_mut().take(to).skip(from) {
            if *byte != b'\n' && *byte < 0x80 {
                *byte = b' ';
            } else if *byte >= 0x80 {
                *byte = b'?';
            }
        }
    };
    let mut i = 0;
    while i < b.len() {
        let c = b[i];
        let rest = &b[i..];
        if slash && rest.starts_with(b"//") {
            let end = rest
                .iter()
                .position(|&x| x == b'\n')
                .map_or(b.len(), |p| i + p);
            blank_range(&mut out, i, end);
            i = end;
        } else if slash && rest.starts_with(b"/*") {
            let end = code[i + 2..].find("*/").map_or(b.len(), |p| i + 2 + p + 2);
            blank_range(&mut out, i, end);
            i = end;
        } else if lang == Lang::Ts
            && c == b'/'
            && regex_can_start(&out[..i])
            && let Some(end) = regex_end(b, i)
        {
            blank_range(&mut out, i + 1, end - 1);
            i = end;
        } else if lang == Lang::Powershell && rest.starts_with(b"<#") {
            let end = code[i + 2..].find("#>").map_or(b.len(), |p| i + 2 + p + 2);
            blank_range(&mut out, i, end);
            i = end;
        } else if hash && c == b'#' && !(lang == Lang::Php && rest.starts_with(b"#[")) {
            let end = rest
                .iter()
                .position(|&x| x == b'\n')
                .map_or(b.len(), |p| i + p);
            blank_range(&mut out, i, end);
            i = end;
        } else if c == b'"' || c == b'\'' || c == b'`' {
            // Python and Swift/Kotlin triple quotes run to the matching triple.
            let triple = [c; 3];
            let long = rest.starts_with(&triple) && c != b'`';
            let quote_len = if long { 3 } else { 1 };
            let mut j = i + quote_len;
            // Code inside an interpolation (`"${System.getenv("HOME")}"`, `f"{os.environ['X']}"`)
            // runs, so it stays visible to the checks; only the literal text around it is blanked.
            let mut kept: Vec<(usize, usize)> = Vec::new();
            while j < b.len() {
                if let Some(end) = interpolation_end(lang, c, b, i, j) {
                    kept.push((j, end));
                    j = end;
                    continue;
                }
                if long {
                    if b[j..].starts_with(&triple) {
                        break;
                    }
                } else if b[j] == b'\n' && c != b'`' {
                    // An unterminated quote (an apostrophe in a comment-like text): stop at the line.
                    break;
                } else if b[j] == c {
                    break;
                }
                if b[j] == b'\\' && lang != Lang::Powershell {
                    j += 1;
                }
                j += 1;
            }
            let end = j.min(b.len());
            let mut from = i + quote_len;
            for (keep_from, keep_to) in kept {
                blank_range(&mut out, from, keep_from);
                from = keep_to;
            }
            blank_range(&mut out, from, end);
            i = (end + quote_len).min(b.len());
        } else {
            i += 1;
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Whether a `/` after `before` (already blanked) starts a JS regular expression literal rather
/// than a division.
fn regex_can_start(before: &[u8]) -> bool {
    let text = before.trim_ascii_end();
    let Some(&last) = text.last() else {
        return true;
    };
    if last.is_ascii_alphanumeric() || matches!(last, b'_' | b'$') {
        let word_start = text
            .iter()
            .rposition(|c| !(c.is_ascii_alphanumeric() || matches!(c, b'_' | b'$')))
            .map_or(0, |p| p + 1);
        return matches!(
            &text[word_start..],
            b"return"
                | b"typeof"
                | b"instanceof"
                | b"in"
                | b"of"
                | b"new"
                | b"delete"
                | b"void"
                | b"throw"
                | b"case"
                | b"do"
                | b"else"
                | b"yield"
                | b"await"
        );
    }
    if text.ends_with(b"++") || text.ends_with(b"--") {
        return false;
    }
    if last == b'!'
        && text[..text.len() - 1]
            .last()
            .is_some_and(|&c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'$' | b')' | b']'))
    {
        return false;
    }
    b"(,=:[!&|?{};+-*%<>~^".contains(&last)
}

/// The byte after the closing `/` of the regular expression literal opened at `open`, or `None`
/// when the line ends first.
fn regex_end(b: &[u8], open: usize) -> Option<usize> {
    let mut j = open + 1;
    let mut class = false;
    while j < b.len() {
        match b[j] {
            b'\n' => return None,
            b'\\' => j += 1,
            b'[' => class = true,
            b']' => class = false,
            b'/' if !class => return Some(j + 1),
            _ => {}
        }
        j += 1;
    }
    None
}

/// Where the interpolation that starts at `at` inside the string literal opened at `open` ends
/// (the byte after its closing bracket), when the language has one there: Kotlin and JS template
/// `${`, Ruby `#{`, Python f-string and C# `$"` `{`, PHP `{$`, Swift `\(`, PowerShell `$(`.
/// `None` when there is none, or when it never closes (the text is then left blanked).
fn interpolation_end(lang: Lang, quote: u8, b: &[u8], open: usize, at: usize) -> Option<usize> {
    let rest = &b[at..];
    let before = |n: usize| (open >= n).then(|| b[open - n]);
    let (code_from, close) = match lang {
        Lang::Kotlin if quote == b'"' && rest.starts_with(b"${") => (at + 2, b'}'),
        Lang::Ts if quote == b'`' && rest.starts_with(b"${") => (at + 2, b'}'),
        Lang::Ruby if quote != b'\'' && rest.starts_with(b"#{") => (at + 2, b'}'),
        Lang::Python | Lang::Csharp if quote == b'"' || quote == b'\'' => {
            let formatted = if lang == Lang::Python {
                // A prefix of letters before the quote that includes an `f` (`f`, `rf`, `Fr`).
                let mut k = open;
                while k > 0 && b[k - 1].is_ascii_alphabetic() && open - k < 3 {
                    k -= 1;
                }
                b[k..open].iter().any(|x| matches!(x, b'f' | b'F'))
            } else {
                before(1) == Some(b'$')
                    || (before(1) == Some(b'@') && before(2) == Some(b'$'))
                    || (before(1) == Some(b'$') && before(2) == Some(b'@'))
            };
            if formatted && rest.starts_with(b"{") && !rest.starts_with(b"{{") {
                (at + 1, b'}')
            } else {
                return None;
            }
        }
        Lang::Php if quote == b'"' && (rest.starts_with(b"{$") || rest.starts_with(b"${")) => {
            (at + 1, b'}')
        }
        Lang::Swift if quote == b'"' && rest.starts_with(b"\\(") => (at + 2, b')'),
        Lang::Powershell if quote == b'"' && rest.starts_with(b"$(") => (at + 2, b')'),
        _ => return None,
    };
    let open_bracket = if close == b'}' { b'{' } else { b'(' };
    // Comments inside the expression (`${ /* } */ process.env.HOME }`): a bracket in one does not
    // close it.
    let slash_comments = matches!(
        lang,
        Lang::Kotlin | Lang::Ts | Lang::Csharp | Lang::Php | Lang::Swift
    );
    let mut depth = 1;
    let mut k = code_from;
    while k < b.len() {
        if slash_comments && b[k] == b'/' && b.get(k + 1) == Some(&b'*') {
            // To the end of the comment; an unterminated one never closes the interpolation.
            // Kotlin and Swift nest block comments (`/* a /* b */ c */`).
            let nests = matches!(lang, Lang::Kotlin | Lang::Swift);
            let mut level = 1;
            k += 2;
            while level > 0 {
                match b.get(k..k + 2)? {
                    b"*/" => {
                        level -= 1;
                        k += 2;
                    }
                    b"/*" if nests => {
                        level += 1;
                        k += 2;
                    }
                    _ => k += 1,
                }
            }
            continue;
        }
        if slash_comments && b[k] == b'/' && b.get(k + 1) == Some(&b'/') {
            k += b[k..]
                .iter()
                .position(|&c| c == b'\n')
                .unwrap_or(b.len() - k);
            continue;
        }
        match b[k] {
            q @ (b'"' | b'\'') if q != quote || depth > 0 => {
                // A string inside the interpolation: skip it whole.
                k += 1;
                while k < b.len() && b[k] != q && b[k] != b'\n' {
                    if b[k] == b'\\' {
                        k += 1;
                    }
                    k += 1;
                }
            }
            c if c == open_bracket => depth += 1,
            c if c == close => {
                depth -= 1;
                if depth == 0 {
                    return Some(k + 1);
                }
            }
            b'\n' if quote != b'`' && quote != b'"' => return None,
            _ => {}
        }
        k += 1;
    }
    None
}

fn is_ident(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '$'
}

/// Calls that read the clock only with no arguments: Ruby's `Time.new` is now, `Time.new(2000, 1, 1)`
/// is a fixed date.
const NOW_WITHOUT_ARGUMENTS: &[&str] = &["Time.new"];

/// Whether `rest`, the text right after such a call, passes it an argument: `(2000, 1, 1)`, or
/// `2000, 1, 1` with no parentheses. `()`, `.year`, the end of the line and a keyword such as
/// `if` pass none.
fn passes_arguments(rest: &str) -> bool {
    let spaced = rest.trim_start_matches([' ', '\t']);
    if let Some(inside) = spaced.strip_prefix('(') {
        let inside = inside.trim_start();
        return !inside.starts_with(')') && !inside.starts_with("in:");
    }
    if spaced.len() == rest.len() || spaced.starts_with("in:") {
        return false;
    }
    if let Some(after) = spaced.strip_prefix('-') {
        return after.starts_with(|c: char| !c.is_whitespace());
    }
    let word: String = spaced.chars().take_while(|&c| is_ident(c)).collect();
    if matches!(
        word.as_str(),
        "if" | "unless" | "and" | "or" | "do" | "then" | "while" | "until" | "rescue" | "end"
    ) {
        return false;
    }
    spaced.starts_with(|c: char| is_ident(c) || matches!(c, '"' | '\'' | ':' | '-' | '['))
}

/// Positions of `needle` in `hay` that do not continue a longer name before them, nor, for a
/// method name such as `.sample`, after them (`.sample_rate`, `.samples`). A call of
/// `NOW_WITHOUT_ARGUMENTS` that passes an argument is not one.
fn find_all<'a>(hay: &'a str, needle: &'a str) -> impl Iterator<Item = usize> + 'a {
    let method = needle.starts_with('.') && needle.chars().next_back().is_some_and(is_ident);
    let now = NOW_WITHOUT_ARGUMENTS.contains(&needle);
    hay.match_indices(needle).filter_map(move |(i, _)| {
        let before = hay[..i].chars().next_back();
        let first = needle.chars().next().unwrap_or(' ');
        // `pprint(` is not `print(`, `x.print(` is not a global print, and neither are
        // `$request->date(` or `ops->time(` (#1397).
        let continues = (before.is_some_and(|c| (is_ident(first) && is_ident(c)) || c == '.')
            || after_member_operator(&hay[..i]))
            && !after_system_namespace(&hay[..i]);
        let rest = &hay[i + needle.len()..];
        let longer = (method || now) && rest.starts_with(is_ident);
        let fixed = now && passes_arguments(rest);
        ((!continues || needle.starts_with('$')) && !longer && !fixed).then_some(i)
    })
}

/// Whether `before` ends with a member operator: `->` (PHP and C), or `::` after a class name
/// (`Calendar::time(` in PHP), with or without spaces after it (`$request-> date(`). A leading
/// `::` or `\` names the global one, `global::` in C# is the root namespace, Ruby's
/// `Kernel::rand` and `Kernel::puts` are the global functions themselves and `Random::rand` is
/// `Random.rand`, and a `->` with a space before it on its line is a Kotlin or Java arrow
/// (`{ _ -> Random.nextInt(6) }`), so none of those counts.
fn after_member_operator(before: &str) -> bool {
    let before = before.trim_end();
    if let Some(head) = before.strip_suffix("->") {
        let code = head.trim_end();
        let gap = &head[code.len()..];
        return code.is_empty() || gap.is_empty() || gap.contains('\n');
    }
    let Some(head) = before.strip_suffix("::") else {
        return false;
    };
    let head = head.trim_end();
    let start = head
        .char_indices()
        .rev()
        .take_while(|&(_, c)| is_ident(c))
        .last()
        .map_or(head.len(), |(i, _)| i);
    let owner = &head[start..];
    !owner.is_empty() && !matches!(owner, "global" | "Kernel" | "Random")
}
const SYSTEM_NAMESPACES: &[&str] = &["System.IO.", "System.Diagnostics.", "System."];

/// Whether `before` ends with a .NET `System` namespace written in full (`System.`,
/// `System.IO.`, `System.Diagnostics.`, `global::System.`): `System.DateTime.Now` is
/// `DateTime.Now`, while `x.Now` and `obj.Random` after any other name are members of something
/// else.
fn after_system_namespace(before: &str) -> bool {
    SYSTEM_NAMESPACES.iter().any(|ns| {
        before.strip_suffix(ns).is_some_and(|head| {
            head.strip_suffix("global::").is_some()
                || !head
                    .chars()
                    .next_back()
                    .is_some_and(|c| is_ident(c) || c == '.' || c == ':')
        })
    })
}

fn assigns(after: &str, lang: Lang) -> bool {
    let a = after.trim_start_matches([' ', '\t']);
    let mut chars = a.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    let second = chars.next();
    match first {
        '=' => !matches!(second, Some('=' | '>' | '~')),
        '+' | '-' => matches!(second, Some('=')) || second == Some(first),
        '*' | '/' | '%' | '|' | '&' | '^' => second == Some('='),
        '<' | '>' => {
            a.starts_with("<<=")
                || a.starts_with(">>=")
                || (lang == Lang::Ruby && a.starts_with("<<"))
        }
        ':' => lang == Lang::Go && second == Some('='),
        _ => false,
    }
}

/// The part of `s` after a balanced `[ ... ]` that starts at `s[0]`.
fn after_brackets(s: &str) -> Option<&str> {
    let mut depth = 0usize;
    for (i, c) in s.char_indices() {
        match c {
            '[' => depth += 1,
            ']' => {
                depth -= 1;
                if depth == 0 {
                    return Some(&s[i + 1..]);
                }
            }
            _ => {}
        }
    }
    None
}

/// The parameter whose object `code` changes in place, if any.
fn mutated_param(lang: Lang, params: &[&str], code: &str) -> Option<String> {
    let sigil = matches!(lang, Lang::Php | Lang::Powershell);
    let fold = lang == Lang::Powershell;
    let hay = if fold {
        code.to_ascii_lowercase()
    } else {
        code.to_string()
    };
    for &p in params {
        if p.is_empty() {
            continue;
        }
        let name = p.trim_start_matches('$');
        let needle = match (sigil, fold) {
            (true, true) => format!("${}", name.to_ascii_lowercase()),
            (true, false) => format!("${name}"),
            (false, _) => name.to_string(),
        };
        let found = |what: String| Some(format!("mutates its argument `{p}` in place ({what})"));
        for at in find_all(&hay, &needle) {
            let after = &hay[at + needle.len()..];
            if after.chars().next().is_some_and(is_ident) {
                continue;
            }
            // `p.method(`, `p->field =`, `p.field =`, `p.a.b +=`
            let member = after
                .strip_prefix('.')
                .or_else(|| after.strip_prefix("->"))
                .or_else(|| after.strip_prefix("?."));
            if let Some(m) = member {
                let end = m.find(|c: char| !is_ident(c)).unwrap_or(m.len());
                let method = &m[..end];
                let tail = &m[end..];
                if tail.starts_with('(') || tail.starts_with('!') {
                    let lower = method.to_ascii_lowercase();
                    let ruby_pure = lang == Lang::Ruby
                        && matches!(
                            lower.as_str(),
                            "sort"
                                | "reverse"
                                | "set"
                                | "write"
                                | "sortby"
                                | "shuffle"
                                | "swap"
                                | "remove"
                        );
                    if (MUTATORS.contains(&lower.as_str()) && !ruby_pure)
                        || (lang == Lang::Ruby && tail.starts_with('!'))
                        || (lower.starts_with("set") && method.len() > 3 && lang != Lang::Ts)
                        || (lang == Lang::Ts
                            && method.starts_with("set")
                            && method[3..].starts_with(|c: char| c.is_ascii_uppercase()))
                    {
                        return found(format!(".{method}()"));
                    }
                } else if assigns(tail, lang) {
                    return found(format!("assigns `{method}`"));
                }
                // `p.a.b = x` and `p.a[0] = x`
                let mut rest = tail;
                while let Some(r) = rest.strip_prefix('.') {
                    let e = r.find(|c: char| !is_ident(c)).unwrap_or(r.len());
                    rest = &r[e..];
                }
                if rest.len() != tail.len() && assigns(rest, lang) {
                    return found("assigns a field".into());
                }
                if let Some(rest) = rest
                    .starts_with('[')
                    .then(|| after_brackets(rest))
                    .flatten()
                    && assigns(rest, lang)
                {
                    return found("assigns an element".into());
                }
            } else if after.starts_with('[')
                && let Some(rest) = after_brackets(after)
                && assigns(rest, lang)
            {
                return found("assigns an element".into());
            } else if lang == Lang::Ruby
                && assigns(after, lang)
                && after.trim_start().starts_with("<<")
            {
                return found("`<<`".into());
            }
        }
        // `del p[0]`, `delete p.x`, `unset($p[0])`
        for pat in [format!("del {needle}"), format!("delete {needle}")] {
            if find_all(&hay, &pat).any(|at| !hay[at + pat.len()..].starts_with(is_ident)) {
                return found("deletes from it".into());
            }
        }
    }
    // `Collections.sort(p)`, `sort.Ints(p)`, `slices.Reverse(p)`, `Arrays.fill(p, ..)`
    const FUNCTIONS: &[(Lang, &str)] = &[
        (Lang::Java, "Collections.sort("),
        (Lang::Java, "Collections.reverse("),
        (Lang::Java, "Collections.shuffle("),
        (Lang::Java, "Collections.swap("),
        (Lang::Java, "Collections.fill("),
        (Lang::Java, "Arrays.sort("),
        (Lang::Java, "Arrays.fill("),
        (Lang::Java, "Arrays.setAll("),
        (Lang::Kotlin, "Collections.sort("),
        (Lang::Kotlin, "Collections.reverse("),
        (Lang::Kotlin, "Collections.shuffle("),
        (Lang::Go, "sort.Ints("),
        (Lang::Go, "sort.Strings("),
        (Lang::Go, "sort.Float64s("),
        (Lang::Go, "sort.Slice("),
        (Lang::Go, "sort.SliceStable("),
        (Lang::Go, "sort.Sort("),
        (Lang::Go, "slices.Sort("),
        (Lang::Go, "slices.SortFunc("),
        (Lang::Go, "slices.Reverse("),
        (Lang::Go, "copy("),
        (Lang::Php, "array_push("),
        (Lang::Php, "array_pop("),
        (Lang::Php, "array_shift("),
        (Lang::Php, "array_unshift("),
        (Lang::Php, "array_splice("),
        (Lang::Php, "sort("),
        (Lang::Php, "rsort("),
        (Lang::Php, "usort("),
        (Lang::Php, "ksort("),
        (Lang::Php, "shuffle("),
        (Lang::Csharp, "Array.Sort("),
        (Lang::Csharp, "Array.Reverse("),
        (Lang::Csharp, "Array.Fill("),
        (Lang::Csharp, "Array.Copy("),
    ];
    for (_, f) in FUNCTIONS.iter().filter(|(l, _)| *l == lang) {
        for at in find_all(code, f) {
            let args = &code[at + f.len()..];
            let first: String = args
                .trim_start()
                .trim_start_matches('&')
                .chars()
                .take_while(|c| is_ident(*c))
                .collect();
            if let Some(p) = params.iter().find(|p| {
                p.trim_start_matches('$') == first.trim_start_matches('$') && !p.is_empty()
            }) {
                return Some(format!(
                    "mutates its argument `{p}` in place ({})",
                    f.trim_end_matches('(')
                ));
            }
        }
    }
    None
}

/// Whether `record` keeps what a call of a top-level function did besides returning (the
/// arguments after it, and what it wrote to standard output) and `diff` compares both with the
/// port's. For these languages an in-place mutator or a printer is bridged; the others keep it in
/// the source language ([`reason`]). A language is added here only with a test that plants a no-op
/// port of a mutator and of a printer and expects `diff` to fail (`tests/post_call_state.rs`).
pub fn observes(lang: Lang) -> bool {
    matches!(
        lang,
        Lang::Ts
            | Lang::Python
            | Lang::Ruby
            | Lang::Go
            | Lang::Java
            | Lang::Php
            | Lang::Csharp
            | Lang::Kotlin
    )
}

/// What a function does that the recording sees: the parameters it changes in place, and whether
/// it writes to standard output. Judged from the text; a miss is caught by `diff`, which compares
/// the arguments after the call whatever this says (the port then has to take the parameter by
/// `&mut`, which `refresh` reads from `port.rs`).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Observed {
    pub mutates: Vec<String>,
    pub prints: bool,
}

/// Calls whose text goes to standard output, which `record` captures. Anything else that prints
/// (standard error, a file object) is not seen and keeps the function in the source language.
fn stdout_printers(lang: Lang) -> &'static [&'static str] {
    match lang {
        Lang::Ts => &[
            "console.log(",
            "console.info(",
            "console.debug(",
            "process.stdout.write(",
        ],
        Lang::Python => &["print(", "sys.stdout.write("],
        // `STDOUT` is the constant, which swapping `$stdout` does not reach: it stays unseen.
        Lang::Ruby => &[
            "puts ", "puts(", "print ", "print(", "pp ", "pp(", "$stdout",
        ],
        // `fmt.Fprint*` goes where its writer says, `log` and `println` to standard error.
        Lang::Go => &["fmt.Print"],
        // `System.err` is standard error.
        Lang::Java => &["System.out."],
        // `println` and `print` write to `System.out`, which the driver swaps.
        Lang::Kotlin => &["println(", "print(", "System.out."],
        // `Console.Error` is standard error; `Debug` and `Trace` go to listeners.
        Lang::Csharp => &["Console.Write"],
        // `error_log` goes to the log. `print_r($x, true)` returns its text and prints nothing,
        // which only makes the function "print" for a port that need not.
        Lang::Php => &[
            "echo ",
            "print ",
            "print(",
            "printf(",
            "var_dump(",
            "print_r(",
        ],
        _ => &[],
    }
}

/// The text of the call whose name starts at `at`, up to its closing parenthesis.
fn call_text(code: &str, at: usize) -> &str {
    let rest = &code[at..];
    let mut depth = 0usize;
    for (i, c) in rest.char_indices() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return &rest[..=i];
                }
            }
            _ => {}
        }
    }
    rest
}

/// What `code` (a top-level function of a language that [`observes`]) changes and prints.
pub fn observed(lang: Lang, params: &[&str], code: &str) -> Observed {
    if !observes(lang) {
        return Observed::default();
    }
    let code = blank(lang, code);
    // A PHP array or string is a value: changing the parameter changes a copy. The parameters a
    // function changes for its caller are the ones taken by reference, which the plugin lists.
    let params: &[&str] = if lang == Lang::Php { &[] } else { params };
    let mutates = params
        .iter()
        .filter(|p| !p.is_empty() && mutated_param(lang, &[**p], &code).is_some())
        .map(|p| (*p).to_string())
        .collect();
    let prints = stdout_printers(lang)
        .iter()
        .any(|p| find_all(&code, p).any(|at| !writes_elsewhere(lang, call_text(&code, at))));
    Observed { mutates, prints }
}

/// A Python `print(x, file=f)` goes where `f` says, not to standard output.
fn writes_elsewhere(lang: Lang, call: &str) -> bool {
    lang == Lang::Python && call.starts_with("print(") && call.contains("file=")
}

/// Why an export with these parameters and this body cannot be checked by its return value:
/// it prints, or changes an argument in place. `None` when it does neither as far as a text
/// scan of the body can tell (comments and string contents are ignored).
pub fn reason(lang: Lang, params: &[&str], code: &str) -> Option<String> {
    reason_with(lang, params, code, false)
}

/// [`reason`] for a top-level function: where the language [`observes`] a call's effects, changing
/// an argument in place and printing to standard output are not reasons to keep it.
/// `[datetime]::Parse('09:00')`, `[datetime]::ParseExact('09:00', ...)` and a
/// `[datetime]'17:30'` cast in PowerShell: a string with a time and no date takes today's date
/// from the clock (#1404). `code` is `raw` blanked and lowered byte for byte, so a quote seen in
/// `code` opens the literal at the same place in `raw`.
fn powershell_time_only(raw: &str, code: &str) -> Option<String> {
    // Arguments may continue on the next line after `(` or `,`.
    let ws = |s: &str| s.trim_start_matches(char::is_whitespace).len();
    for ty in ["[system.datetime]", "[datetime]"] {
        for (i, _) in code.match_indices(ty) {
            let after = &code[i + ty.len()..];
            let spaced = &after[after.len() - ws(after)..];
            let (what, exact, rest) = match spaced.strip_prefix("::") {
                Some(member) => {
                    let member = &member[member.len() - ws(member)..];
                    let name: String = member.chars().take_while(|&c| is_ident(c)).collect();
                    if name != "parse" && name != "parseexact" {
                        continue;
                    }
                    let tail = &member[name.len()..];
                    let Some(args) = tail[tail.len() - ws(tail)..].strip_prefix('(') else {
                        continue;
                    };
                    (
                        format!("{ty}::{name}"),
                        name == "parseexact",
                        &args[args.len() - ws(args)..],
                    )
                }
                None => (ty.to_string(), false, spaced),
            };
            let Some((value, after_value)) = literal_at(raw, code, rest) else {
                continue;
            };
            // `NoCurrentDateDefault` fills in 0001-01-01, not today (#1404 review).
            if what.contains("::") {
                let mut depth = 1;
                let end = after_value
                    .find(|c| {
                        match c {
                            '(' => depth += 1,
                            ')' => depth -= 1,
                            _ => {}
                        }
                        depth == 0
                    })
                    .unwrap_or(after_value.len());
                if after_value[..end].contains("nocurrentdatedefault") {
                    continue;
                }
            }
            // `ParseExact` says what the string holds in its format; read that when it is written.
            let time_only = if exact {
                let next = after_value
                    .trim_start_matches(char::is_whitespace)
                    .strip_prefix(',')
                    .map(|r| &r[r.len() - ws(r)..]);
                match next.and_then(|r| literal_at(raw, code, r)) {
                    Some((format, _)) => is_time_only_format(format),
                    None => is_time_only(value),
                }
            } else {
                is_time_only(value)
            };
            if time_only {
                return Some(what);
            }
        }
    }
    None
}

/// The string literal that starts `rest` (a tail of `code`), read from `raw` at the same place,
/// and the part of `code` after its closing quote.
fn literal_at<'a>(raw: &'a str, code: &'a str, rest: &'a str) -> Option<(&'a str, &'a str)> {
    let quote = rest.chars().next().filter(|c| matches!(c, '\'' | '"'))?;
    let open = code.len() - rest.len() + 1;
    let len = code[open..].find(quote)?;
    Some((raw.get(open..open + len)?, &code[open + len + 1..]))
}

/// Whether a date string holds a time and no date: `09:00`, `17:30:15`, but not `2024-02-29 09:00`,
/// `1/2/2024`, `29.02.2024`, `20240229 09:00` or `Sat, 18 Aug 2018 07:22:16 GMT`.
fn is_time_only(text: &str) -> bool {
    const MONTHS: [&str; 12] = [
        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
    ];
    let month = text
        .split(|c: char| !c.is_ascii_alphabetic())
        .map(str::to_ascii_lowercase)
        .any(|word| MONTHS.iter().any(|m| word.starts_with(m)));
    if month {
        return false;
    }
    let b = text.trim().as_bytes();
    let date_mark = b.windows(3).any(|w| {
        w[0].is_ascii_digit() && matches!(w[1], b'-' | b'/' | b'.') && w[2].is_ascii_digit()
    });
    // Six digits in a row are a compact date (`20240229`, `240229`).
    let compact_date = b.split(|c| !c.is_ascii_digit()).any(|run| run.len() >= 6);
    b.contains(&b':') && b.iter().any(u8::is_ascii_digit) && !date_mark && !compact_date
}

/// Whether a .NET date format reads a time and no date: `HH:mm`, `HHmm`, `h:mm tt`, or the
/// standard `t` and `T`. A day, month or year field (`d`, `M`, `y`) or any other standard
/// format gives a date.
fn is_time_only_format(format: &str) -> bool {
    let f = format.trim();
    if f.chars().count() == 1 {
        return matches!(f, "t" | "T");
    }
    let fields: String = f.chars().filter(char::is_ascii_alphabetic).collect();
    !fields.contains(['d', 'M', 'y', 'g']) && fields.contains(['H', 'h'])
}

/// PowerShell allows spaces between `::` and a static member (`[datetime]:: Now`); the lists
/// spell it without them.
fn squeeze_static_members(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(i) = rest.find("::") {
        out.push_str(&rest[..i + 2]);
        rest = rest[i + 2..].trim_start_matches([' ', '\t']);
    }
    out.push_str(rest);
    out
}

pub fn function_reason(lang: Lang, params: &[&str], code: &str) -> Option<String> {
    reason_with(lang, params, code, observes(lang))
}

fn reason_with(lang: Lang, params: &[&str], code: &str, observed: bool) -> Option<String> {
    let raw = code;
    let code = blank(lang, code);
    // C records its arguments back after the call (`out` and `buffer` parameters), so only
    // printing is invisible there.
    if lang != Lang::C
        && !observed
        && let Some(why) = mutated_param(lang, params, &code)
    {
        return Some(format!(
            "{why}: the recording only compares return values, not the arguments after the call"
        ));
    }
    let lowered;
    let lower_hay = code.to_ascii_lowercase();
    let squeezed;
    let state_hay = if lang == Lang::Powershell {
        squeezed = squeeze_static_members(&lower_hay);
        &squeezed
    } else {
        &code
    };
    let find = |hay: &str, needles: &[&str]| -> Option<String> {
        needles.iter().find_map(|n| {
            let n = if lang == Lang::Powershell {
                n.to_ascii_lowercase()
            } else {
                n.to_string()
            };
            find_all(hay, &n)
                .next()
                .map(|_| n.trim_end_matches(['(', ' ', '.']).to_string())
        })
    };
    if let Some(what) = find(state_hay, environment(lang)) {
        return Some(format!(
            "reads the environment (`{what}`): the recording would hold this machine's value"
        ));
    }
    if let Some(what) = find(state_hay, shared_state(lang)) {
        return Some(format!(
            "uses state outside its arguments (`{what}`): a port would own a second copy"
        ));
    }
    if params.is_empty()
        && let Some(what) = find(state_hay, clock_and_random(lang)).or_else(|| {
            (lang == Lang::Powershell)
                .then(|| powershell_time_only(raw, &lower_hay))
                .flatten()
        })
    {
        return Some(format!(
            "takes nothing and reads the clock or randomness (`{what}`): one recorded case is one moment"
        ));
    }
    let hay = if lang == Lang::Powershell {
        lowered = code.to_ascii_lowercase();
        &lowered
    } else {
        &code
    };
    for p in prints(lang) {
        // What `record` captures is not a reason: standard output, for a function of a language
        // that observes it.
        if observed
            && stdout_printers(lang).contains(p)
            && find_all(hay, p).all(|at| !writes_elsewhere(lang, call_text(hay, at)))
        {
            continue;
        }
        if find_all(hay, p).next().is_some() {
            return Some(format!(
                "prints (`{}`): the recording only compares return values, not output",
                p.trim_end_matches(['(', ' ', '.'])
            ));
        }
    }
    None
}

/// Adds the clock, randomness, environment and shared-state risks to a file's facts, by the
/// names each language reads them with (`System.getenv`, `time.Now`, `ENV[`, `$env:`), so that a
/// function that reads the machine is not "ready" with no risk listed. Python and TS/JS have their
/// own scans.
pub fn scan_risks(lang: Lang, source: &str, facts: &mut crate::ts::scan::FileFacts) {
    use crate::risks::Risk;
    if matches!(lang, Lang::Python | Lang::Ts) {
        return;
    }
    let code = blank(lang, source);
    let code = if lang == Lang::Powershell {
        code.to_ascii_lowercase()
    } else {
        code
    };
    // A Ruby `@name` is the instance state of a class, ordinary in a file: only an export of a
    // module (a `def self.`) reading one is shared state, which `reason` judges.
    let state: &[&str] = if lang == Lang::Ruby {
        &[]
    } else {
        shared_state(lang)
    };
    let lists: [(&[&str], Risk); 3] = [
        (environment(lang), Risk::SharedState),
        (state, Risk::SharedState),
        (clock_and_random(lang), Risk::ClockAndRandom),
    ];
    let raw_lines: Vec<&str> = source.lines().collect();
    for (n, line) in code.lines().enumerate() {
        let line_no = u32::try_from(n + 1).unwrap_or(u32::MAX);
        let squeezed;
        let hay = if lang == Lang::Powershell {
            squeezed = squeeze_static_members(line);
            squeezed.as_str()
        } else {
            line
        };
        let time_only = lang == Lang::Powershell
            && powershell_time_only(raw_lines.get(n).copied().unwrap_or(""), line).is_some();
        for (needles, risk) in &lists {
            let hit = needles.iter().any(|needle| {
                let needle = if lang == Lang::Powershell {
                    needle.to_ascii_lowercase()
                } else {
                    (*needle).to_string()
                };
                find_all(hay, &needle).next().is_some()
            }) || (*risk == Risk::ClockAndRandom && time_only);
            // The Swift and PowerShell syntax scans already add some of these calls (`Date(`,
            // `Get-Date`): one call is one hit, not one per pass (#1401).
            if hit {
                let lines = facts.risks.entry(*risk).or_default();
                if !lines.contains(&line_no) {
                    lines.push(line_no);
                }
            }
        }
    }
}

/// The untyped parameter that the body calls (`plugin(1)`): a function value, which a Rust port
/// can neither take nor call. Judged from the text, so only a call of the bare name counts.
pub fn called_param(lang: Lang, untyped: &[&str], code: &str) -> Option<String> {
    let code = blank(lang, code);
    // `items.map(fn)`: the callback is called by the method it is handed to.
    const HANDED_TO: &[&str] = &[
        ".map(",
        ".forEach(",
        ".filter(",
        ".reduce(",
        ".some(",
        ".every(",
        ".find(",
        ".findIndex(",
        ".flatMap(",
        ".sort(",
        ".then(",
        ".catch(",
        ".replace(",
        ".replaceAll(",
    ];
    untyped.iter().find_map(|name| {
        let handed = HANDED_TO.iter().any(|m| {
            code.match_indices(m).any(|(i, _)| {
                let arg = &code[i + m.len()..];
                arg.trim_start().starts_with(name)
                    && !arg.trim_start()[name.len()..].starts_with(is_ident)
            })
        });
        if handed {
            return Some(format!(
                "hands its parameter `{name}` to a method that calls it: a function value cannot cross the bridge"
            ));
        }
        let at = find_all(&code, name).find(|&at| {
            let after = &code[at + name.len()..];
            after.trim_start_matches([' ', '\t']).starts_with('(')
                && !after.chars().next().is_some_and(is_ident)
        })?;
        // `function f(plugin)` is the declaration, not a call.
        let line_start = code[..at].rfind('\n').map_or(0, |n| n + 1);
        let head = code[line_start..at].trim_end();
        (!head.ends_with("function") && !head.ends_with("function*")).then(|| {
            format!("calls its parameter `{name}`: a function value cannot cross the bridge")
        })
    })
}

/// Whether the text of a function body has a `return` that gives a value (`return x`, not a bare
/// `return;`). Used for languages where an unannotated function that never returns a value
/// returns nothing.
pub fn has_value_return(lang: Lang, body: &str) -> bool {
    let code = blank(lang, body);
    code.match_indices("return").any(|(i, _)| {
        let before = code[..i].chars().next_back();
        if before.is_some_and(is_ident) {
            return false;
        }
        let after = &code[i + "return".len()..];
        if after.chars().next().is_some_and(is_ident) {
            return false;
        }
        let rest = after.trim_start_matches([' ', '\t']);
        !(rest.is_empty() || rest.starts_with([';', '\n', '\r', '}']))
    })
}

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

    #[test]
    fn code_inside_an_interpolation_stays_visible_and_the_text_around_it_does_not() {
        // The environment read is in the interpolation, not in the literal text: it must be seen.
        for (lang, code) in [
            (
                Lang::Kotlin,
                "fun home(x: Int): String = \"${System.getenv(\"HOME\")}:$x\"",
            ),
            (Lang::Ts, "const f = (x) => `${process.env.HOME}/${x}`"),
            (
                Lang::Ruby,
                "def home(x)\n  \"#{ENV.fetch('HOME')}/#{x}\"\nend",
            ),
            (
                Lang::Python,
                "def home(x):\n    return f\"{os.environ['HOME']}/{x}\"",
            ),
            (
                Lang::Csharp,
                "string Home(int x) => $\"{Environment.GetEnvironmentVariable(\"HOME\")}/{x}\";",
            ),
            (
                Lang::Php,
                "function home($x) { return \"{$_SERVER['HOME']}/$x\"; }",
            ),
            (
                Lang::Swift,
                "func home(_ x: Int) -> String { \"\\(ProcessInfo.processInfo.environment[\"HOME\"]!)/\\(x)\" }",
            ),
            (
                Lang::Powershell,
                "function Home($x) { \"$($env:HOME)/$x\" }",
            ),
        ] {
            let blanked = blank(lang, code);
            let env = environment(lang).iter().any(|e| blanked.contains(e));
            assert!(
                env,
                "{lang:?}: the environment read was blanked: {blanked:?}"
            );
        }
        // Text that only looks like code, outside an interpolation, is still blanked, and a
        // plain Python string is not an f-string.
        let plain = blank(
            Lang::Python,
            "x = \"os.environ {os.environ}\"\nf = f\"os.environ {1}\"",
        );
        assert!(!plain.contains("os.environ"), "{plain:?}");
        // A bracket inside a comment in the expression does not close it, and the code after the
        // comment stays visible.
        for (lang, code) in [
            (
                Lang::Ts,
                "const f = (x) => `${ /* } */ process.env.HOME }/${x}`",
            ),
            (
                Lang::Kotlin,
                "fun f(x: Int) = \"${ /* } */ System.getenv(\"HOME\") }:$x\"",
            ),
            (
                Lang::Ts,
                "const f = (x) => `${ // }\n process.env.HOME }/${x}`",
            ),
            // Kotlin and Swift nest block comments: the first `*/` does not end this one.
            (
                Lang::Kotlin,
                "fun f(x: Int) = \"${ /* a /* b */ } */ System.getenv(\"HOME\") }:$x\"",
            ),
            (
                Lang::Swift,
                "func f(_ x: Int) -> String { \"\\( /* a /* b */ ) */ ProcessInfo.processInfo.environment[\"HOME\"]! )/\\(x)\" }",
            ),
        ] {
            let blanked = blank(lang, code);
            let env = environment(lang).iter().any(|e| blanked.contains(e));
            assert!(
                env,
                "{lang:?}: a comment closed the interpolation: {blanked:?}"
            );
        }
        // An interpolation that never closes leaves the rest of the literal blanked.
        let open = blank(
            Lang::Kotlin,
            "val s = \"${System.getenv(\"HOME\"\nval t = 1",
        );
        assert!(open.contains("val t = 1"), "{open:?}");
    }

    #[test]
    fn only_languages_with_a_post_call_test_are_observed() {
        for lang in [
            Lang::Ts,
            Lang::Python,
            Lang::Ruby,
            Lang::Go,
            Lang::Java,
            Lang::Kotlin,
            Lang::Php,
            Lang::Csharp,
        ] {
            assert!(observes(lang), "{lang:?}");
        }
        // PowerShell and Swift have no toolchain here to plant a no-op port with, and C has
        // no way to hand printed text back through its ABI.
        for lang in [Lang::Powershell, Lang::Swift, Lang::C] {
            assert!(
                !observes(lang),
                "{lang:?} has no test that plants a no-op port yet"
            );
            // Not observed: nothing is reported as seen, and the block stays.
            assert_eq!(
                observed(lang, &["xs"], "xs.sort(); print(xs)"),
                Observed::default()
            );
        }
    }

    #[test]
    fn a_top_level_function_of_an_observed_language_is_kept_only_for_what_is_not_seen() {
        let seen = observed(
            Lang::Python,
            &["xs", "s"],
            "def f(xs, s):\n    xs.append(1)\n    print(s)\n    return s",
        );
        assert_eq!(seen.mutates, ["xs"]);
        assert!(seen.prints);
        assert_eq!(
            function_reason(
                Lang::Python,
                &["xs"],
                "def f(xs):\n    xs.append(1)\n    print(xs)\n    return 1"
            ),
            None
        );
        // Standard error and a file object are not captured.
        for code in [
            "def f(s):\n    print(s, file=sys.stderr)\n    return s",
            "def f(s):\n    sys.stderr.write(s)\n    return s",
        ] {
            assert!(
                function_reason(Lang::Python, &["s"], code).is_some_and(|r| r.contains("prints")),
                "{code}"
            );
        }
        assert!(
            function_reason(
                Lang::Ts,
                &["s"],
                "function f(s) { console.error(s); return s }"
            )
            .is_some_and(|r| r.contains("prints"))
        );
        // Methods keep the old rule: `reason` is what a class method goes through.
        assert!(
            reason(
                Lang::Python,
                &["xs"],
                "def f(self, xs):\n    xs.append(1)\n    return 1"
            )
            .is_some()
        );
        // The environment is still read from this machine.
        assert!(
            function_reason(Lang::Ts, &[], "function f() { return process.env.HOME }").is_some()
        );
    }

    #[test]
    fn void_returns_are_nothing() {
        for r in ["void", "undefined", "Promise<void>", " null "] {
            assert!(returns_nothing(r), "{r}");
        }
        for r in ["number", "unknown", "string | undefined", "void[]"] {
            assert!(!returns_nothing(r), "{r}");
        }
    }

    #[test]
    fn mutation_spellings() {
        let cases: &[(Lang, &str, &str)] = &[
            (Lang::Ts, "a", "function f(a){ a.push(1); return 1 }"),
            (Lang::Ts, "o", "function f(o){ o.n = 99; return 1 }"),
            (Lang::Ts, "o", "function f(o){ o.a.b += 1; return 1 }"),
            (Lang::Ts, "a", "function f(a){ a[0] = 1; return 1 }"),
            (Lang::Ts, "d", "function f(d){ d.setHours(1); return 1 }"),
            (
                Lang::Python,
                "xs",
                "def f(xs):\n    xs.sort()\n    return 1",
            ),
            (
                Lang::Python,
                "xs",
                "def f(xs):\n    xs[0] += 1\n    return 1",
            ),
            (Lang::Python, "d", "def f(d):\n    del d['k']\n    return 1"),
            (
                Lang::Java,
                "xs",
                "int f(List<Integer> xs){ Collections.sort(xs); return 1; }",
            ),
            (
                Lang::Go,
                "xs",
                "func F(xs []int) int { sort.Ints(xs); return 1 }",
            ),
            (Lang::Ruby, "s", "def f(s)\n  s << \"!\"\n  1\nend"),
            (Lang::Ruby, "xs", "def f(xs)\n  xs.sort!\n  1\nend"),
            (
                Lang::Powershell,
                "List",
                "function F { param($List) $list.Add(1); 1 }",
            ),
            (Lang::Php, "o", "function f($o) { $o->x = 1; return 1; }"),
        ];
        for (lang, param, code) in cases {
            let why = reason(*lang, &[param], code);
            assert!(
                why.as_deref().is_some_and(|w| w.contains("mutates")),
                "{lang:?} {code}: {why:?}"
            );
        }
    }

    #[test]
    fn pure_code_has_no_effect() {
        let cases: &[(Lang, &str, &str)] = &[
            (
                Lang::Ts,
                "a",
                "function f(a){ const b = [...a]; b.sort(); return b }",
            ),
            (
                Lang::Ts,
                "a",
                "function f(a){ a = a.slice(); return a.length == 1 }",
            ),
            (
                Lang::Ts,
                "s",
                "function f(s){ return s.replace('a', 'b') } // console.log(s)",
            ),
            (
                Lang::Python,
                "xs",
                "def f(xs):\n    \"\"\"print(xs)\"\"\"\n    return sorted(xs)",
            ),
            (
                Lang::Python,
                "xs",
                "def f(xs):\n    ys = list(xs)\n    ys.append(1)\n    return ys",
            ),
            (Lang::Java, "x", "int f(int x){ int y = x << 2; return y; }"),
        ];
        for (lang, param, code) in cases {
            assert_eq!(reason(*lang, &[param], code), None, "{lang:?} {code}");
        }
    }

    #[test]
    fn prints_are_found_but_not_look_alikes() {
        assert!(reason(Lang::Ts, &[], "function f(){ console.log(1); return 2 }").is_some());
        assert!(reason(Lang::Python, &[], "def f():\n    print(1)\n    return 2").is_some());
        assert!(reason(Lang::Python, &[], "def f():\n    pprint(1)\n    return 2").is_none());
        assert!(
            reason(
                Lang::Java,
                &[],
                "int f(){ System.out.println(1); return 2; }"
            )
            .is_some()
        );
        assert!(reason(Lang::Go, &[], "func F() int { fmt.Println(1); return 2 }").is_some());
        assert!(reason(Lang::Ruby, &[], "def f\n  puts 1\n  2\nend").is_some());
        assert!(reason(Lang::Php, &[], "function f() { echo 1; return 2; }").is_some());
        assert!(reason(Lang::Powershell, &[], "function F { Write-Host 1; 2 }").is_some());
        assert!(
            reason(
                Lang::C,
                &[],
                "int f(int d) { putc('0' + d, stdout); return d; }"
            )
            .is_some()
        );
        assert!(
            reason(
                Lang::C,
                &[],
                "int f(int d) { fputc('*', stdout); return d; }"
            )
            .is_some()
        );
        assert!(
            reason(
                Lang::C,
                &[],
                "int f(int d) { dprintf(2, \"%d\\n\", d); return d; }"
            )
            .is_some()
        );
        assert!(
            reason(
                Lang::C,
                &[],
                "int f(struct ops *ops, int c) { ops->putc(c); return c; }"
            )
            .is_none()
        );
    }

    #[test]
    fn environment_clock_and_state_are_found() {
        let env: &[(Lang, &str)] = &[
            (
                Lang::Python,
                "def f(x):\n    return os.environ.get('HOME', '') + x",
            ),
            (Lang::Ts, "function f(x){ return process.env.HOME + x }"),
            (Lang::Ts, "function f(x){ return os.tmpdir() + x }"),
            (
                Lang::Go,
                "func F(x string) string { return os.Getenv(\"HOME\") + x }",
            ),
            (
                Lang::Go,
                "func F(x string) string { return os.ExpandEnv(\"$HOME/\" + x) }",
            ),
            (
                Lang::Go,
                "func F(x string) string { return os.TempDir() + x }",
            ),
            (
                Lang::Go,
                "func F(x string) string { return strconv.Itoa(os.Getpid()) + x }",
            ),
            (
                Lang::Java,
                "String f(String x){ return System.getenv(\"HOME\") + x; }",
            ),
            (
                Lang::Csharp,
                "public static int F(int x) => Environment.ProcessorCount * x;",
            ),
            (
                Lang::Csharp,
                "public static string F(string x) => Path.Combine(AppContext.BaseDirectory, x);",
            ),
            (Lang::Ruby, "def self.f(x)\n  ENV.fetch('HOME') + x\nend"),
            (Lang::Ruby, "def self.f(x)\n  File.join(Dir.tmpdir, x)\nend"),
            (Lang::Ruby, "def self.f(x)\n  Socket.gethostname + x\nend"),
            (Lang::Php, "function f($x) { return getenv('HOME') . $x; }"),
            (
                Lang::Php,
                "function f($x) { return sys_get_temp_dir() . $x; }",
            ),
            (Lang::Php, "function f($x) { return getmypid() . $x; }"),
            (
                Lang::Swift,
                "public func f(_ x: String) -> String {\n    return FileManager.default.temporaryDirectory.path + x\n}",
            ),
            (
                Lang::Swift,
                "public func f(_ x: String) -> String {\n    return NSUserName() + x\n}",
            ),
            (
                Lang::Swift,
                "public func f(_ x: String) -> String {\n    return NSFullUserName() + x\n}",
            ),
            (Lang::Powershell, "function F { param($X) $env:HOME + $X }"),
            (
                Lang::C,
                "int f(int x) {\n    return getenv(\"HOME\") ? x : 0;\n}",
            ),
            (
                Lang::C,
                "int f(int x) {\n    return secure_getenv(\"HOME\") ? x : 0;\n}",
            ),
            (
                Lang::C,
                "int f(int x) {\n    char buf[64];\n    gethostname(buf, sizeof buf);\n    return buf[0] + x;\n}",
            ),
        ];
        for (lang, code) in env {
            let why = reason(*lang, &["x"], code);
            assert!(
                why.as_deref().is_some_and(|w| w.contains("environment")),
                "{lang:?}: {why:?}"
            );
        }
        // The clock matters when nothing is passed: one recorded case is one moment.
        assert!(
            reason(
                Lang::Go,
                &[],
                "func Left() int64 {\n\treturn int64(time.Until(deadline).Seconds())\n}\n"
            )
            .is_some()
        );
        assert!(reason(Lang::Python, &[], "def f():\n    return time.time()").is_some());
        for body in ["time.strftime('%Y')", "datetime.today()"] {
            let code = format!("def f():\n    return {body}");
            assert!(reason(Lang::Python, &[], &code).is_some(), "{body}");
        }
        assert!(
            reason(
                Lang::Csharp,
                &[],
                "public static long Ticks() => global::System.DateTime.UtcNow.Ticks;"
            )
            .is_some()
        );
        for code in [
            "public static long Uptime() => Environment.TickCount64;",
            "public static long Stamp() => System.Diagnostics.Stopwatch.GetTimestamp();",
        ] {
            assert!(reason(Lang::Csharp, &[], code).is_some(), "{code}");
        }
        // A member of something else that is not the `System` namespace is not the clock.
        for code in [
            "public static long Ticks() => clock.DateTime.Now.Ticks;",
            "public static long Ticks() => MySystem.DateTime.Now.Ticks;",
        ] {
            assert_eq!(reason(Lang::Csharp, &[], code), None, "{code}");
        }
        // A method reached through `::` or `->` is not the global function (#1397).
        assert_eq!(
            reason(
                Lang::Php,
                &[],
                "function stamp(): int {\n    return Calendar::time();\n}\n"
            ),
            None
        );
        assert!(
            reason(
                Lang::Php,
                &[],
                "function stamp(): int {\n    return time();\n}\n"
            )
            .is_some()
        );
        assert!(
            reason(
                Lang::Php,
                &[],
                "function stamp(): int {\n    return \\time();\n}\n"
            )
            .is_some()
        );
        assert_eq!(
            reason(
                Lang::Php,
                &[],
                "function stamp(): int {\n    return Calendar ::time();\n}\n"
            ),
            None
        );
        // Ruby's `Kernel::` is the global function itself.
        assert!(reason(Lang::Ruby, &[], "def self.roll\n  Kernel::rand(6)\nend\n").is_some());
        assert!(
            observed(Lang::Ruby, &[], "def self.say\n  Kernel::puts(1)\nend\n").prints,
            "Kernel::puts prints"
        );
        assert!(
            reason(
                Lang::Swift,
                &[],
                "public func ticks() -> UInt64 {\n    return DispatchTime.now().uptimeNanoseconds\n}\n"
            )
            .is_some()
        );
        // C's finer clocks (#1319).
        for code in [
            "long now_ns(void) {\n    struct timespec ts;\n    clock_gettime(CLOCK_MONOTONIC, &ts);\n    return ts.tv_sec;\n}\n",
            "long now_us(void) {\n    struct timeval tv;\n    gettimeofday(&tv, 0);\n    return tv.tv_sec;\n}\n",
            "long now_c11(void) {\n    struct timespec ts;\n    timespec_get(&ts, TIME_UTC);\n    return ts.tv_sec;\n}\n",
        ] {
            assert!(reason(Lang::C, &[], code).is_some(), "{code}");
            let facts = crate::lang::scan(Lang::C, "clock.c", code);
            assert!(
                facts
                    .risks
                    .contains_key(&crate::risks::Risk::ClockAndRandom),
                "{code}: {:?}",
                facts.risks
            );
        }
        assert!(reason(Lang::Ruby, &[], "def self.roll\n  Random::rand(6)\nend\n").is_some());
        for (lang, code) in [
            (
                Lang::Kotlin,
                "fun roll(): Int = listOf(6).map { n -> Random.nextInt(n) }.first()\n",
            ),
            (
                Lang::Kotlin,
                "fun roll(): Int = when (6) {\n    0 -> 0\n    else -> Random.nextInt(6)\n}\n",
            ),
            (
                Lang::Java,
                "static long stamp() {\n    LongSupplier s = () -> System.currentTimeMillis();\n    return s.getAsLong();\n}\n",
            ),
        ] {
            assert!(reason(lang, &[], code).is_some(), "{lang:?}: {code}");
        }
        assert_eq!(
            reason(
                Lang::Php,
                &[],
                "function stamp(Request $request): string {\n    return $request\n        ->date('from');\n}\n"
            ),
            None
        );
        for body in ["process.hrtime.bigint()", "crypto.randomInt(6)"] {
            let code = format!("export function f() {{\n  return {body}\n}}\n");
            assert!(reason(Lang::Ts, &[], &code).is_some(), "{body}");
        }
        assert!(
            reason(
                Lang::C,
                &[],
                "int pick(void) {\n    return (int)arc4random_uniform(6) + 1;\n}\n"
            )
            .is_some()
        );
        assert_eq!(
            reason(
                Lang::Python,
                &["t"],
                "def f(t):\n    return t + time.time()"
            ),
            None
        );
        let state = reason(
            Lang::Python,
            &[],
            "def counter():\n    global n\n    n += 1\n    return n",
        );
        assert!(state.is_some_and(|w| w.contains("state")));
        assert!(reason(Lang::Ruby, &[], "def self.bump\n  @count += 1\nend").is_some());
        // Comments and strings mention the words without reading anything.
        assert_eq!(
            reason(
                Lang::Python,
                &["x"],
                "def f(x):\n    # os.environ\n    return 'os.environ' + x"
            ),
            None
        );
    }

    /// The same risk written the way each language spells it: listed, not silent.
    #[test]
    fn scans_list_environment_clock_and_hash_order_in_every_spelling() {
        use crate::risks::Risk;
        // A call the syntax scan and the text list both know is counted once (#1401).
        for (lang, path, code) in [
            (
                Lang::Swift,
                "T.swift",
                "func f() -> Date { return Date() }\n",
            ),
            (Lang::Powershell, "Stamp.psm1", "function F { Get-Date }\n"),
        ] {
            let facts = crate::lang::scan(lang, path, code);
            assert_eq!(
                facts.risks.get(&Risk::ClockAndRandom),
                Some(&vec![1]),
                "{lang:?}: {code}"
            );
        }
        let cases: &[(Lang, &str, &str, Risk)] = &[
            (
                Lang::Csharp,
                "Stamp.cs",
                "namespace A;\npublic static class S {\n    public static long Full() => System.DateTime.Now.Ticks;\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Csharp,
                "Stamp.cs",
                "namespace A;\npublic static class S {\n    public static string Home(string n) => System.Environment.GetEnvironmentVariable(\"HOME\") + n;\n}\n",
                Risk::SharedState,
            ),
            (
                Lang::Csharp,
                "Stamp.cs",
                "namespace A;\npublic static class S {\n    public static string Here(string n) => System.IO.Directory.GetCurrentDirectory() + n;\n}\n",
                Risk::SharedState,
            ),
            (
                Lang::Csharp,
                "Stamp.cs",
                "namespace A;\npublic static class S {\n    public static string Tmp(string n) => global::System.IO.Path.GetTempPath() + n;\n}\n",
                Risk::SharedState,
            ),
            (
                Lang::C,
                "dice.c",
                "int roll(void) {\n    return (int)(random() % 6) + 1;\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::C,
                "dice.c",
                "double unit(void) {\n    return drand48();\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Swift,
                "Deck.swift",
                "let suits = [\"hearts\", \"spades\"]\npublic func shuffledSuits() -> [String] {\n    return suits.shuffled()\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Swift,
                "Dice.swift",
                "public func roll() -> Int {\n    return Int(arc4random_uniform(6)) + 1\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Swift,
                "Stamp.swift",
                "public func stamp() -> Double {\n    return CFAbsoluteTimeGetCurrent()\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "deck.rb",
                "module Deck\n  SUITS = %w[hearts spades].freeze\n  def self.shuffled_suits\n    SUITS.shuffle\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "deck.rb",
                "module Deck\n  SUITS = %w[hearts spades].freeze\n  def self.any_suit\n    SUITS.sample\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Kotlin,
                "Deck.kt",
                "fun shuffledSuits(): List<String> = listOf(\"hearts\", \"spades\").shuffled()\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Kotlin,
                "Deck.kt",
                "fun anySuit(): String = listOf(\"hearts\", \"spades\").random()\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Kotlin,
                "When.kt",
                "fun shout(s: String): String = s.uppercase(Locale.getDefault())\n",
                Risk::SharedState,
            ),
            (
                Lang::Java,
                "When.java",
                "class When { static String language() { return Locale.getDefault().getLanguage(); } }",
                Risk::SharedState,
            ),
            (
                Lang::Java,
                "Deck.java",
                "class Deck { static void f(java.util.List<String> xs) { Collections.shuffle(xs); } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "Deck.java",
                "class Deck { static java.util.List<String> f() { java.util.List<String> xs = new java.util.ArrayList<>(java.util.List.of(\"a\", \"b\")); java.util.Collections.shuffle(xs); return xs; } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "Dice.java",
                "class Dice { static int f() { return ThreadLocalRandom.current().nextInt(1, 7); } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "Dice.java",
                "class Dice { static int f() { return new SecureRandom().nextInt(6) + 1; } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "Dice.java",
                "class Dice { static int f() { return new java.util.Random().nextInt(6) + 1; } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "Dice.java",
                "class Dice { static int f() { return java.util.concurrent.ThreadLocalRandom.current().nextInt(1, 7); } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "Dice.java",
                "class Dice { static int f() { return new java.security.SecureRandom().nextInt(6) + 1; } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Kotlin,
                "Dice.kt",
                "fun roll(): Int = ThreadLocalRandom.current().nextInt(6)\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Go,
                "x.go",
                "package x\nfunc F() string { return os.Getenv(\"A\") }\n",
                Risk::SharedState,
            ),
            (
                Lang::Go,
                "x.go",
                "package x\nfunc F() int64 { return time.Now().Unix() }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Go,
                "x.go",
                "package x\nfunc F() int {\n\tcounts := map[string]int{}\n\tn := 0\n\tfor k, v := range counts {\n\t\tn += len(k) + v\n\t}\n\treturn n\n}\n",
                Risk::UnorderedIteration,
            ),
            (
                Lang::Java,
                "X.java",
                "class X { static String f() { return System.getenv(\"A\"); } }",
                Risk::SharedState,
            ),
            (
                Lang::Java,
                "X.java",
                "class X { static long f() { return System.currentTimeMillis(); } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Java,
                "X.java",
                "import java.util.*;\nclass X { static Map<String,Integer> f() { Map<String,Integer> m = new HashMap<>(); return m; } }",
                Risk::UnorderedIteration,
            ),
            (
                Lang::Java,
                "X.java",
                "class X { static String f(String c) { return c.replaceAll(\"[\" + c + \"]\", \"\"); } }",
                Risk::DynamicRegex,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    ENV['A']\n  end\nend\n",
                Risk::SharedState,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    Time.now.year\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    Time.new.year\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    Time.new().year\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    Time.new\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    Time.new - 60\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Ruby,
                "x.rb",
                "module M\n  def self.f\n    Time.new(in: '+09:00').hour\n  end\nend\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "x.php",
                "<?php\nfunction f() { return getenv('A'); }\n",
                Risk::SharedState,
            ),
            (
                Lang::Php,
                "x.php",
                "<?php\nfunction f() { return date('Y'); }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "x.php",
                "<?php\nfunction f() { return gmdate('Y'); }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "x.php",
                "<?php\nfunction f() { return strtotime('tomorrow'); }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "deck.php",
                "<?php\nfunction f(array $a) { return $a[array_rand($a)]; }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "deck.php",
                "<?php\nfunction f(array $a) { shuffle($a); return $a; }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "deck.php",
                "<?php\nfunction f() { return str_shuffle('abcdef'); }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "deck.php",
                "<?php\nfunction f() { return bin2hex(random_bytes(8)); }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "deck.php",
                "<?php\nfunction f() { return lcg_value(); }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Csharp,
                "X.cs",
                "class X { static string F(string n) { return Path.Combine(Directory.GetCurrentDirectory(), n); } }",
                Risk::SharedState,
            ),
            (
                Lang::Csharp,
                "X.cs",
                "class X { static string F(string n) { return Path.Combine(Path.GetTempPath(), n); } }",
                Risk::SharedState,
            ),
            (
                Lang::Csharp,
                "X.cs",
                "class X { static int F() { return DateTime.Now.Year; } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Csharp,
                "X.cs",
                "class X { static long F() { return DateTimeOffset.UtcNow.ToUnixTimeSeconds(); } }",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Kotlin,
                "X.kt",
                "fun f(): String? = System.getenv(\"A\")\n",
                Risk::SharedState,
            ),
            (
                Lang::Powershell,
                "x.ps1",
                "function F { $env:HOME }\n",
                Risk::SharedState,
            ),
            (
                Lang::Powershell,
                "x.ps1",
                "function F { [datetime]::UtcNow }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Powershell,
                "x.ps1",
                "function F { [datetime]::Today.DayOfWeek.ToString() }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Powershell,
                "x.ps1",
                "function F { [DateTimeOffset]::Now }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Swift,
                "x.swift",
                "func f() -> Date { return Date() }\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Swift,
                "x.swift",
                "public func configPath(_ name: String) -> String {\n    return NSHomeDirectory() + \"/\" + name\n}\n",
                Risk::SharedState,
            ),
            (
                Lang::Swift,
                "x.swift",
                "public func home() -> String {\n    guard let value = getenv(\"HOME\") else { return \"\" }\n    return String(cString: value)\n}\n",
                Risk::SharedState,
            ),
        ];
        for (lang, path, code, risk) in cases {
            let facts = crate::lang::scan(*lang, path, code);
            assert!(
                facts.risks.contains_key(risk),
                "{lang:?} {code}: {:?}",
                facts.risks
            );
        }
        for (lang, path, code, risk) in [
            (
                Lang::Php,
                "src/report.php",
                "<?php\nfunction stamp(Request $request): string {\n    return $request->date('from')->format('Y-m-d');\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::Php,
                "src/report.php",
                "<?php\nfunction label(Config $config): string {\n    return $config->getenv('LABEL');\n}\n",
                Risk::SharedState,
            ),
            (
                Lang::Php,
                "src/report.php",
                "<?php\nfunction stamp(Request $request): string {\n    return $request-> date('from');\n}\n",
                Risk::ClockAndRandom,
            ),
            (
                Lang::C,
                "sched.c",
                "long elapsed(const struct clock_ops *ops, long start) {\n    return ops->time(0) - start;\n}\n",
                Risk::ClockAndRandom,
            ),
        ] {
            let facts = crate::lang::scan(lang, path, code);
            assert!(
                !facts.risks.contains_key(&risk),
                "{lang:?} {code}: {:?}",
                facts.risks
            );
        }
        // An instance variable is a class's own state, not a risk of the file.
        let facts = crate::lang::scan(Lang::Ruby, "x.rb", "class A\n  def f\n    @x\n  end\nend\n");
        assert!(!facts.risks.contains_key(&Risk::SharedState));
        for code in [
            "module A\n  def self.rate\n    Audio.sample_rate\n  end\nend\n",
            "module A\n  def self.n\n    DATA.samples.size\n  end\nend\n",
            "module A\n  def self.y2k_weekday\n    Time.new(2000, 1, 1).wday\n  end\nend\n",
            "module A\n  def self.weekday(y, m, d)\n    Time.new(y, m, d).wday\n  end\nend\n",
            "module A\n  def self.y2k\n    Time.new 2000, 1, 1\n  end\nend\n",
            "module A\n  def self.y2k\n    Time.new (2000)\n  end\nend\n",
        ] {
            let facts = crate::lang::scan(Lang::Ruby, "x.rb", code);
            assert!(
                !facts.risks.contains_key(&Risk::ClockAndRandom),
                "{code}: {:?}",
                facts.risks
            );
        }
        for code in [
            "function F { [datetime]::IsLeapYear(2024) }\n",
            "function F { [datetime]::DaysInMonth(2024, 2) }\n",
            "function F { [datetime]::Parse('2024-02-29') }\n",
            "function F { [datetime]::MinValue }\n",
            "function F { [datetime]::Parse('2024-02-29 09:00') }\n",
            "function F { [datetime]'1/2/2024' }\n",
            "function F($s) { [datetime]::Parse($s) }\n",
            "function F { # [datetime]::Parse('09:00')\n}\n",
            "function F { [datetime]::ParseExact('20240229 09:00', 'yyyyMMdd HH:mm', $null) }\n",
            "function F { [datetime]::ParseExact('09:00', 'HH:mm', $null, [Globalization.DateTimeStyles]::NoCurrentDateDefault) }\n",
            "function F { [datetime]::Parse('20240229 09:00') }\n",
            "function F { [datetime]::Parse('Sat, 18 Aug 2018 07:22:16 GMT') }\n",
            "function F { [datetime]::ParseExact('09:00', 'HH:mm', (Get-Culture), [Globalization.DateTimeStyles]::NoCurrentDateDefault) }\n",
        ] {
            let facts = crate::lang::scan(Lang::Powershell, "x.ps1", code);
            assert!(
                !facts.risks.contains_key(&Risk::ClockAndRandom),
                "{code}: {:?}",
                facts.risks
            );
        }
        // Arguments on the next line: `bridge` reads the whole function.
        assert!(
            reason(
                Lang::Powershell,
                &[],
                "function F {\n  [datetime]::Parse(\n    '09:00')\n}\n"
            )
            .is_some_and(|r| r.contains("clock"))
        );
        // A time with no date takes today's date, and a space after `::` is the same member (#1404).
        for code in [
            "function F { [datetime]::Parse('09:00') }\n",
            "function F { [datetime]'17:30' }\n",
            "function F { [datetime]:: Now }\n",
            "function F { [System.DateTime]::ParseExact(\"17:30:15\", 'HH:mm:ss', $null) }\n",
            "function F { [datetime]::ParseExact('0900', 'HHmm', $null) }\n",
            "function F { $t = [datetime]'17:30'; $NoCurrentDateDefault = 0; $t }\n",
        ] {
            let facts = crate::lang::scan(Lang::Powershell, "x.ps1", code);
            assert_eq!(
                facts.risks.get(&Risk::ClockAndRandom),
                Some(&vec![1]),
                "{code}"
            );
            assert!(
                reason(Lang::Powershell, &[], code).is_some_and(|r| r.contains("clock")),
                "{code}"
            );
        }
        let facts = crate::lang::scan(
            Lang::Ruby,
            "x.rb",
            "module A\n  def self.f\n    SUITS.dup.shuffle!\n  end\nend\n",
        );
        assert!(facts.risks.contains_key(&Risk::ClockAndRandom));
        assert!(reason(Lang::Ruby, &[], "def self.rate\n  Audio.sample_rate\nend\n").is_none());
        let facts = crate::lang::scan(
            Lang::Swift,
            "x.swift",
            "func f() -> String? { return [\"a\", \"b\"].randomElement() }\n",
        );
        assert!(facts.risks.contains_key(&Risk::ClockAndRandom));
    }

    #[test]
    fn value_returns() {
        assert!(has_value_return(Lang::Ts, "function f(){ return 1 }"));
        assert!(!has_value_return(
            Lang::Ts,
            "function f(){ if (x) { return; } g() }"
        ));
        assert!(!has_value_return(
            Lang::Ts,
            "function f(){ g() // return 1\n}"
        ));
        assert!(!has_value_return(Lang::Python, "def f():\n    return\n"));
        assert!(has_value_return(
            Lang::Python,
            "def f():\n    return None\n"
        ));
    }

    #[test]
    fn a_regex_literal_does_not_open_a_comment_or_a_string() {
        let cases = [
            "function f(s){ const re = /\\/*$/; return s.replace(re, '') + process.env.HOME }",
            "function f(s){ return s.split(/[/*]/).join(process.env.SEP) }",
            "function f(s){ if (/'/.test(s)) return 1; return process.env.HOME }",
            "function f(s){ return typeof s === 'string' && /\\/*/.test(s) ? process.env.A : '' }",
            "function f(x: number | undefined) { return x! / Number(process.env.N) / 2 }",
            "function f(s){ if (!/x/.test(s)) return 1; return process.env.HOME }",
        ];
        for code in cases {
            let why = reason(Lang::Ts, &["s"], code);
            assert!(
                why.as_deref().is_some_and(|w| w.contains("environment")),
                "{code}: {why:?}"
            );
        }
        assert_eq!(
            reason(
                Lang::Ts,
                &["a"],
                "function f(a){ return a / 2 + 1 / /* process.env.X */ 3 }"
            ),
            None
        );
        assert_eq!(
            reason(
                Lang::Ts,
                &["s"],
                "function f(s){ return /process.env.X/.test(s) }"
            ),
            None
        );
    }

    #[test]
    fn deleting_from_another_name_is_not_a_mutation() {
        for code in [
            "function f(a){ const aa = {...a}; delete aa.x; return aa }",
            "function f(a){ const o = {...a}; delete o.a; return o }",
        ] {
            assert_eq!(reason(Lang::Ts, &["a"], code), None, "{code}");
        }
        assert!(
            reason(Lang::Ts, &["a"], "function f(a){ delete a.x; return 1 }")
                .is_some_and(|w| w.contains("deletes"))
        );
        assert_eq!(
            reason(
                Lang::Python,
                &["d"],
                "def f(d):\n    dd = dict(d)\n    del dd['k']\n    return dd"
            ),
            None
        );
    }
}