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.

70.5 KB
Raw Blame
//! Kotlin: Gradle Kotlin DSL modules, imports, risks, the artifact-to-crate table, and the
//! JVM-visible functions a Kotlin file exposes.
//!
//! Kotlin has no `static` keyword, but it has two ways to produce a JVM static method:
//! a top-level function (compiled into `<File>Kt`) and `@JvmStatic` in an `object` or a
//! `companion object`. Both are exported here with a Java-shaped `prototype`, so the
//! existing Java JNI codegen, batch codegen, reflection driver and shadow generation can
//! be reused without changes. A Java wrapper can call a Kotlin static method directly.

use std::collections::HashMap;
use std::path::Path;

use anyhow::Result;
use tree_sitter::Node;

use super::syntax::{self, named_children, text};
use crate::risks::{Risk, regex_needs_fancy};
use crate::ts::deps::CrateMatch;
use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
use crate::ts::exports::{ExportedFn, Param};
use crate::ts::scan::{FileFacts, Import};

fn language() -> tree_sitter::Language {
    tree_sitter_kotlin_ng::LANGUAGE.into()
}

pub(crate) const SKIP_DIRS: &[&str] = &[
    "build",
    ".gradle",
    ".idea",
    "out",
    "target",
    "node_modules",
    "bin",
    ".kotlin",
];

// ---- discovery -------------------------------------------------------------------------------

pub fn discover(root: &Path) -> Result<Workspace> {
    let mut packages: Vec<Package> = Vec::new();
    let mut files = Vec::new();
    let root_buf = root.to_path_buf();
    let walker = crate::walk::filtered(root, move |e| {
        if !e.file_type().is_some_and(|t| t.is_dir())
            || !SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
        {
            return true;
        }
        // `src/main/kotlin/build/` can be a real package; other `build/` folders are output.
        e.file_name() == "build"
            && e.path()
                .strip_prefix(&root_buf)
                .unwrap_or(e.path())
                .components()
                .any(|c| c.as_os_str() == std::ffi::OsStr::new("src"))
    })
    .hidden(true)
    .require_git(false)
    .build();
    for entry in walker.flatten() {
        if !entry.file_type().is_some_and(|t| t.is_file()) {
            continue;
        }
        let Ok(rel) = entry.path().strip_prefix(root) else {
            continue;
        };
        let rel = rel.to_string_lossy().replace('\\', "/");
        let name = rel.rsplit('/').next().unwrap_or(&rel);
        let dir = rel
            .rsplit_once('/')
            .map_or(String::new(), |(d, _)| d.to_string());
        if matches!(name, "pom.xml" | "build.gradle" | "build.gradle.kts") {
            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
            let (deps, dev) = super::java::dependencies(&text);
            packages.push(Package {
                name: if dir.is_empty() {
                    root.file_name()
                        .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
                } else {
                    dir.clone()
                },
                src_root: if root.join(&dir).join("src/main/kotlin").is_dir() {
                    join(&dir, "src/main/kotlin")
                } else if root.join(&dir).join("src/main/java").is_dir() {
                    join(&dir, "src/main/java")
                } else {
                    dir.clone()
                },
                dir,
                deps,
                dev_deps: dev,
                namespaces: Vec::new(),
            });
        } else if name.ends_with(".kt") {
            let is_test = rel.contains("src/test/")
                || rel.contains("src/androidTest/")
                || name.ends_with("Test.kt");
            files.push((
                rel,
                if is_test {
                    FileKind::Test
                } else {
                    FileKind::Source
                },
            ));
        }
    }
    if packages.is_empty() {
        packages.push(Package {
            name: root
                .file_name()
                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
            dir: String::new(),
            src_root: if root.join("src/main/kotlin").is_dir() {
                "src/main/kotlin".into()
            } else if root.join("src").is_dir() {
                "src".into()
            } else {
                String::new()
            },
            deps: Vec::new(),
            dev_deps: Vec::new(),
            namespaces: Vec::new(),
        });
    }
    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
    packages.dedup_by(|a, b| {
        let same = a.dir == b.dir;
        if same {
            b.deps.append(&mut a.deps);
            b.dev_deps.append(&mut a.dev_deps);
        }
        same
    });
    files.sort_by(|a, b| a.0.cmp(&b.0));
    let files = files
        .into_iter()
        .map(|(path, kind)| {
            let package = packages
                .iter()
                .enumerate()
                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
                .max_by_key(|(_, p)| p.dir.len())
                .map_or(0, |(i, _)| i);
            SourceFile {
                path,
                package,
                kind,
            }
        })
        .collect();
    Ok(Workspace { packages, files })
}

fn join(dir: &str, rest: &str) -> String {
    if dir.is_empty() {
        rest.to_string()
    } else {
        format!("{dir}/{rest}")
    }
}

// ---- risks and imports -----------------------------------------------------------------------

/// Imports of the hash collections, matched whole: `LinkedHashMap` keeps insertion order.
const HASH_IMPORTS: [&str; 4] = [
    "java.util.HashMap",
    "java.util.HashSet",
    "kotlin.collections.HashMap",
    "kotlin.collections.HashSet",
];

/// Calls that build a collection iterated in hash order.
const HASH_BUILDERS: [&str; 4] = ["HashMap", "HashSet", "hashMapOf", "hashSetOf"];

pub fn scan(source: &str) -> FileFacts {
    let mut facts = FileFacts {
        loc: syntax::loc(source, crate::lang::Lang::Kotlin),
        ..FileFacts::default()
    };
    let Some(tree) = syntax::parse(&language(), source) else {
        return facts;
    };
    let root = tree.root_node();
    facts.parse_errors = usize::from(root.has_error());
    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
        facts
            .risks
            .entry(risk)
            .or_default()
            .push(syntax::line(node))
    };
    syntax::walk(root, |node| match node.kind() {
        "import" if node.is_named() => {
            let spec = text(node, source)
                .trim_start_matches("import")
                .trim()
                .to_string();
            match spec.as_str() {
                s if s.starts_with("kotlinx.coroutines") => {
                    add(&mut facts, Risk::Concurrency, node)
                }
                s if s.starts_with("kotlin.reflect") => add(&mut facts, Risk::Reflection, node),
                s if s.starts_with("java.util.regex") || s.starts_with("kotlin.text.Regex") => {
                    add(&mut facts, Risk::RegexSyntax, node)
                }
                s if HASH_IMPORTS.contains(
                    &s.split_whitespace()
                        .next()
                        .unwrap_or("")
                        .trim_end_matches(';'),
                ) =>
                {
                    add(&mut facts, Risk::UnorderedIteration, node)
                }
                _ => {}
            }
            facts.imports.push(Import {
                specifier: spec,
                type_only: false,
                dynamic: false,
            });
        }
        "nullable_type" => add(&mut facts, Risk::NullReferences, node),
        "throw_expression" | "try_expression" => add(&mut facts, Risk::Exceptions, node),
        "is_expression" | "type_test" | "as_expression" => {
            add(&mut facts, Risk::DynamicTyping, node)
        }
        "lambda_parameters" => add(&mut facts, Risk::Callbacks, node),
        "delegation_specifiers" => add(&mut facts, Risk::ClassInheritance, node),
        "annotation" => {
            let a = text(node, source);
            if a.contains("Synchronized") || a.contains("Volatile") {
                add(&mut facts, Risk::Concurrency, node);
            }
        }
        "binary_expression" => {
            let op = node
                .child_by_field_name("operator")
                .map_or("", |o| text(o, source));
            match op {
                "/" | "%" => add(&mut facts, Risk::DivisionSemantics, node),
                "<<" | ">>" | ">>>" | "*" => add(&mut facts, Risk::IntegerSemantics, node),
                _ => {}
            }
        }
        "for_statement" | "while_statement" | "do_while_statement" => facts.loops += 1,
        "call_expression" => {
            let callee = text(node, source);
            for (needle, risk) in [
                ("substring", Risk::StringOffsets),
                ("charAt", Risk::StringOffsets),
                ("indexOf", Risk::StringOffsets),
                ("toInt(", Risk::IntegerSemantics),
                ("toLong(", Risk::IntegerSemantics),
                ("getClass", Risk::Reflection),
                ("javaClass", Risk::Reflection),
                ("forName", Risk::Reflection),
                ("getDeclaredMethod", Risk::Reflection),
                ("newInstance", Risk::Reflection),
                ("::class", Risk::Reflection),
                ("synchronized(", Risk::Concurrency),
            ] {
                if callee.contains(needle) {
                    add(&mut facts, risk, node);
                }
            }
            if let Some(head) = named_children(node).into_iter().next() {
                let call: String = text(head, source).split_whitespace().collect();
                if super::is_singleton_call(&call) {
                    add(&mut facts, Risk::AppState, node);
                }
                // `hashSetOf<String>()`, `HashMap()`, `java.util.HashSet(xs)`: Kotlin has them
                // without an import, so the call is what to look for. A callee with a call in it
                // (`hashSetOf<Int>().toList`) is another call on the result, counted once already.
                let name = if call.contains('(') {
                    ""
                } else {
                    call.split('<').next().unwrap_or("")
                };
                let short = name
                    .strip_prefix("java.util.")
                    .or_else(|| name.strip_prefix("kotlin.collections."))
                    .unwrap_or(name);
                if HASH_BUILDERS.contains(&short) {
                    add(&mut facts, Risk::UnorderedIteration, node);
                }
            }
            if callee.contains("Regex(") {
                let pattern = callee.split("Regex(").nth(1).unwrap_or("");
                if regex_needs_fancy(pattern, "") {
                    add(&mut facts, Risk::RegexSyntax, node);
                }
            }
        }
        _ => {}
    });
    facts
}

pub fn resolve(spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> super::Resolution {
    // `import a.b.C as Alias` keeps the dotted path, not the local alias.
    let spec = spec.split(" as ").next().unwrap_or(spec).trim();
    let wildcard = spec.ends_with(".*");
    let first = spec.split('.').next().unwrap_or("");
    if matches!(first, "kotlin" | "java" | "javax" | "jdk" | "sun") || spec.starts_with("com.sun.")
    {
        return super::Resolution::Stdlib;
    }
    let path = spec.trim_end_matches(".*").replace('.', "/");
    let find = |p: &str, packages: &[Package]| -> Option<usize> {
        for pkg in packages {
            let file = join(&pkg.src_root, &format!("{p}.kt"));
            if let Some(i) = index.get(file.as_str()) {
                return Some(*i);
            }
            // Kotlin `package a.b` maps to a folder; find any file in that folder.
            let dir = join(&pkg.src_root, p);
            if let Some((_, i)) = index
                .iter()
                .filter(|(f, _)| f.rsplit_once('/').is_some_and(|(d, _)| d == dir))
                .min_by_key(|(f, _)| **f)
            {
                return Some(*i);
            }
        }
        None
    };
    if let Some(i) = find(&path, &ws.packages) {
        return super::Resolution::File(i);
    }
    // A class import can also resolve to a file in its parent package.
    if !wildcard
        && let Some((parent, _)) = path.rsplit_once('/')
        && let Some(i) = find(parent, &ws.packages)
    {
        return super::Resolution::File(i);
    }
    let external = crate::crates::longest_prefix("kotlin", spec)
        .map(str::to_string)
        .unwrap_or_else(|| spec.split('.').take(2).collect::<Vec<_>>().join("."));
    super::Resolution::External(external)
}

pub fn lookup(name: &str) -> Option<CrateMatch> {
    let key = name.split(':').next().unwrap_or(name);
    crate::crates::find("kotlin", key)
}

// ---- types -----------------------------------------------------------------------------------

/// Split a generic argument list at top-level commas.
fn split_top(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut current = String::new();
    for c in text.chars() {
        match c {
            '<' => depth += 1,
            '>' => depth -= 1,
            ',' if depth == 0 => {
                out.push(current.trim().to_string());
                current.clear();
                continue;
            }
            _ => {}
        }
        current.push(c);
    }
    if !current.trim().is_empty() {
        out.push(current.trim().to_string());
    }
    out
}

fn strip_kw<'a>(s: &'a str, kw: &str) -> Option<&'a str> {
    let rest = s.strip_prefix(kw)?;
    if rest.starts_with(char::is_whitespace) {
        Some(rest.trim_start())
    } else {
        None
    }
}

/// A Kotlin type in the TS-like dialect (return position), or why the bridge cannot carry it.
pub fn kotlin_to_ts(t: &str) -> Result<String, String> {
    kotlin_to_ts_inner(t, false)
}

/// A Kotlin parameter type in the TS-like dialect: covariant `out T` projections read as `T`.
pub fn kotlin_to_ts_param(t: &str) -> Result<String, String> {
    kotlin_to_ts_inner(t, true)
}

fn kotlin_to_ts_inner(t: &str, in_param: bool) -> Result<String, String> {
    let t = t.trim();
    if t == "*" {
        return Err("takes or returns `Any`: values of any type".into());
    }
    if let Some(bound) = strip_kw(t, "out") {
        if in_param && !bound.is_empty() {
            return kotlin_to_ts_inner(bound, true);
        }
        return Err(format!("uses a projection `{t}`"));
    }
    if strip_kw(t, "in").is_some() {
        return Err(format!("uses a projection `{t}`"));
    }
    if let Some(inner) = t.strip_suffix('?') {
        return kotlin_to_ts_inner(inner, in_param).map(|i| format!("{i} | undefined"));
    }
    if let Some(inner) = t.strip_suffix("[]") {
        return kotlin_to_ts_inner(inner, in_param).map(|i| format!("{i}[]"));
    }
    let (head, args) = match t.find('<') {
        Some(i) if t.ends_with('>') => (&t[..i], split_top(&t[i + 1..t.len() - 1])),
        _ => (t, Vec::new()),
    };
    let head = head.trim().rsplit('.').next().unwrap_or(head);
    let arg = |i: usize| -> Result<String, String> {
        args.get(i).map_or_else(
            || Err(format!("raw `{head}`")),
            |a| kotlin_to_ts_inner(a, in_param),
        )
    };
    Ok(match head {
        "String" | "CharSequence" => "string".into(),
        "Int" | "Long" | "Short" | "Byte" => "int".into(),
        "Float" | "Double" => "number".into(),
        "Boolean" => "boolean".into(),
        "Unit" | "Nothing" => "void".into(),
        "List" | "MutableList" | "Collection" | "Iterable" | "Array" | "IntArray" | "LongArray"
        | "DoubleArray" | "BooleanArray" => {
            let inner = if head.ends_with("Array") && !matches!(head, "Array") {
                match head {
                    "IntArray" | "LongArray" => "int".into(),
                    "DoubleArray" => "number".into(),
                    "BooleanArray" => "boolean".into(),
                    _ => arg(0)?,
                }
            } else {
                arg(0)?
            };
            if inner.contains(' ') {
                format!("({inner})[]")
            } else {
                format!("{inner}[]")
            }
        }
        "Map" | "MutableMap" | "LinkedHashMap" => {
            if arg(0)? != "string" {
                return Err(format!("`{t}`: JSON object keys are strings"));
            }
            format!("Record<string, {}>", arg(1)?)
        }
        // The TS side could map these (`int[]`/`number[]`), but the Java wire only converts element
        // arrays of int, long, double and boolean: `java_ty` returns None for byte, short and float, so
        // the generated glue would have no call wrapper for the unit.
        "ByteArray" | "ShortArray" | "FloatArray" => {
            return Err(format!(
                "uses `{head}`, which the Java wire cannot carry yet"
            ));
        }
        "Char" => return Err("uses `Char`, a UTF-16 code unit".into()),
        "Any" | "Any?" => return Err("takes or returns `Any`: values of any type".into()),
        "Set" | "MutableSet" | "HashSet" => {
            return Err(format!("uses `{head}`, an unordered collection"));
        }
        "Sequence" | "Iterator" => return Err(format!("uses `{head}`, a lazy sequence")),
        "Pair" | "Triple" => return Err(format!("uses `{head}`, no tuple in the dialect")),
        "Function0" | "Function1" | "Function2" | " suspend " => {
            return Err("takes or returns a function".into());
        }
        other if other.contains(" -> ") => return Err("takes or returns a function".into()),
        other => return Err(super::uses_class(other)),
    })
}

// ---- exports ---------------------------------------------------------------------------------

/// A Kotlin type as a Java type the generated wrappers can declare and reflection can read.
/// `None` when the type has no Java counterpart in the bridged subset.
fn kotlin_to_java(t: &str) -> Option<String> {
    kotlin_to_java_inner(t, false)
}

fn kotlin_to_java_param(t: &str) -> Option<String> {
    kotlin_to_java_inner(t, true)
}

fn kotlin_to_java_inner(t: &str, in_param: bool) -> Option<String> {
    let t = t.trim();
    let boxed = |s: String| match s.as_str() {
        "int" => "Integer".into(),
        "long" => "Long".into(),
        "short" => "Short".into(),
        "byte" => "Byte".into(),
        "float" => "Float".into(),
        "double" => "Double".into(),
        "boolean" => "Boolean".into(),
        "char" => "Character".into(),
        _ => s,
    };
    if t == "*" || strip_kw(t, "in").is_some() {
        return None;
    }
    if let Some(bound) = strip_kw(t, "out") {
        if !in_param || bound.is_empty() {
            return None;
        }
        return kotlin_to_java_inner(bound, true).map(|j| format!("? extends {}", boxed(j)));
    }
    if let Some(inner) = t.strip_suffix('?') {
        return kotlin_to_java_inner(inner, in_param).map(boxed);
    }
    if let Some(inner) = t.strip_suffix("[]") {
        return kotlin_to_java_inner(inner, in_param).map(|i| format!("{}[]", boxed(i)));
    }
    let (head, args) = match t.find('<') {
        Some(i) if t.ends_with('>') => (&t[..i], split_top(&t[i + 1..t.len() - 1])),
        _ => (t, Vec::new()),
    };
    let head = head.trim().rsplit('.').next().unwrap_or(head);
    let arg = |i: usize| -> Option<String> {
        args.get(i)
            .and_then(|a| kotlin_to_java_inner(a, in_param))
            .map(boxed)
    };
    Some(match head {
        "String" => "String".into(),
        "CharSequence" => "CharSequence".into(),
        "Int" => "int".into(),
        "Long" => "long".into(),
        "Short" => "short".into(),
        "Byte" => "byte".into(),
        "Float" => "float".into(),
        "Double" => "double".into(),
        "Boolean" => "boolean".into(),
        "Unit" | "Nothing" => "void".into(),
        "List" | "MutableList" | "Collection" | "Iterable" => format!("List<{}>", arg(0)?),
        "Map" | "MutableMap" | "LinkedHashMap" => {
            format!("Map<{}, {}>", arg(0)?, arg(1)?)
        }
        "Array" => {
            // Java arrays are covariant (`String[]`, not `(? extends String)[]`).
            let raw = args.first()?;
            let elem = if in_param {
                strip_kw(raw.trim(), "out").unwrap_or(raw)
            } else {
                raw
            };
            format!("{}[]", boxed(kotlin_to_java_inner(elem, in_param)?))
        }
        "IntArray" => "int[]".into(),
        "LongArray" => "long[]".into(),
        "ShortArray" => "short[]".into(),
        "ByteArray" => "byte[]".into(),
        "FloatArray" => "float[]".into(),
        "DoubleArray" => "double[]".into(),
        "BooleanArray" => "boolean[]".into(),
        _ => return None,
    })
}

fn package_name_in(root: Node<'_>, source: &str) -> Option<String> {
    let header = named_children(root)
        .into_iter()
        .find(|n| n.kind() == "package_header")?;
    named_children(header)
        .into_iter()
        .find(|n| n.kind() == "qualified_identifier")
        .map(|n| text(n, source).replace(' ', ""))
}

fn modifiers(node: Node<'_>, source: &str) -> String {
    const MODIFIER_KINDS: &[&str] = &[
        "modifiers",
        "annotation",
        "function_modifier",
        "member_modifier",
        "visibility_modifier",
        "class_modifier",
        "parameter_modifier",
    ];
    named_children(node)
        .into_iter()
        .filter(|c| MODIFIER_KINDS.contains(&c.kind()))
        .map(|m| text(m, source))
        .collect::<Vec<_>>()
        .join(" ")
}

fn modifier_words(mods: &str) -> impl Iterator<Item = &str> {
    let mut depth = 0usize;
    mods.split(move |c: char| {
        match c {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            _ => {}
        }
        c.is_whitespace() || c == '(' || c == ')' || depth > 0
    })
    .filter(|w| !w.is_empty())
}

fn type_text(node: Node<'_>, source: &str) -> String {
    // Collapse whitespace runs while keeping spaces between words (`out T`, `in T`, `->`),
    // dropping spaces next to punctuation (`<`, `>`, `,`, `.`, `?`, `[`, `]`, `(`, `)`).
    let mut out = String::new();
    let mut pending_space = false;
    for ch in text(node, source).chars() {
        if ch.is_whitespace() {
            pending_space = !out.is_empty();
            continue;
        }
        if pending_space {
            let prev = out.chars().last().unwrap_or(' ');
            if !matches!(prev, '<' | ',' | '.' | '(' | '[' | '?')
                && !matches!(ch, '<' | '>' | ',' | '.' | ')' | ']' | '?' | '[')
            {
                out.push(' ');
            }
            pending_space = false;
        }
        out.push(ch);
    }
    out
}

/// Type nodes in the Kotlin grammar: a bare `type`, plus the named variants the grammar
/// wraps around it (`user_type`, `nullable_type`, ...). Parameters and return types carry no
/// `type` field, so they are found by kind.
fn is_type_node(kind: &str) -> bool {
    matches!(
        kind,
        "type"
            | "user_type"
            | "nullable_type"
            | "non_nullable_type"
            | "parenthesized_type"
            | "function_type"
    )
}

/// Collect the exports of one Kotlin declaration container (top level or an `object`).
/// The mutable global state a Kotlin file declares: a top-level `var`, and a `var` inside an
/// `object` (a singleton) or a `companion object`. Both are one value the original owns and
/// changes, which a port cannot share with it (issue #745's remaining part).
///
/// A file-level `val` and an `object`'s `val` are not state: they cannot change after the file
/// initialises them.
struct MutableState {
    /// A top-level `var`, or an `object`'s `var` (with the object that owns it so a bare name only
    /// counts inside that object).
    vars: Vec<MutVar>,
}

struct MutVar {
    /// The name as written, and `Object.name` for the qualified form.
    name: String,
    qualified: String,
    /// The `object` that owns it, when it is not a top-level `var`.
    owner: Option<String>,
}

impl MutableState {
    fn of(root: Node<'_>, source: &str, package: Option<&str>) -> Self {
        let mut vars = Vec::new();
        for child in named_children(root) {
            match child.kind() {
                "property_declaration" if is_var(child, source) => {
                    if let Some(name) = declared_name(child, source) {
                        vars.push(MutVar {
                            qualified: name.clone(),
                            name,
                            owner: None,
                        });
                        if let Some(pkg) = package {
                            // Kotlin also resolves a top-level property by its fully qualified name.
                            vars.push(MutVar {
                                qualified: format!(
                                    "{pkg}.{}",
                                    vars.last().map(|v| v.name.clone()).unwrap_or_default()
                                ),
                                name: String::new(),
                                owner: None,
                            });
                        }
                    }
                }
                "object_declaration" | "class_declaration" => {
                    object_state(child, source, package, &mut vars);
                }
                _ => {}
            }
        }
        Self { vars }
    }

    fn is_empty(&self) -> bool {
        self.vars.is_empty()
    }

    /// Why a function that reads or writes this state stays in the original, in the shared
    /// `reads app state (…)` form the other languages use.
    ///
    /// A parameter hides the file's value for the whole body; a local declaration hides it from its
    /// own line onwards. `owner` is the `object` the function is declared in, where the object's own
    /// `var`s are reachable by bare name.
    fn touched_by(&self, function: Node<'_>, source: &str, owner: Option<&str>) -> Option<String> {
        if self.is_empty() {
            return None;
        }
        let mut parameters: Vec<String> = Vec::new();
        if let Some(list) = function.child_by_field_name("parameters") {
            syntax::walk(list, |node| {
                if node.kind() == "parameter"
                    && let Some(name) = declared_name(node, source)
                {
                    parameters.push(name);
                }
            });
        }
        // Locals declared inside the body: they hide the file's value from their own offset on.
        let mut locals: Vec<(String, usize)> = Vec::new();
        syntax::walk(function, |node| match node.kind() {
            // Only the declaration: walking its identifier would also collect the initializer's reads.
            "property_declaration" => {
                if let Some(name) = property_name(node, source) {
                    locals.push((name, node.start_byte()));
                }
            }
            "lambda_parameters" => {
                syntax::walk(node, |p| {
                    if p.kind() == "identifier" {
                        locals.push((text(p, source).to_string(), p.start_byte()));
                    }
                });
            }
            _ => {}
        });
        let hides = |name: &str, at: usize| {
            parameters.iter().any(|p| p == name)
                || locals.iter().any(|(l, offset)| l == name && *offset < at)
        };

        let mut hit = None;
        syntax::walk(function, |node| {
            if hit.is_some() {
                return;
            }
            match node.kind() {
                "navigation_expression" => {
                    let written: String = text(node, source).split_whitespace().collect();
                    let Some(receiver) = written.split_once('.').map(|(r, _)| r) else {
                        return;
                    };
                    // `this.token` inside `object Config` is that object's own variable.
                    if receiver == "this"
                        && let Some(field) = written.split_once('.').map(|(_, f)| f)
                        && let Some(var) = self.vars.iter().find(|v| {
                            v.name == field && v.owner.is_some() && v.owner.as_deref() == owner
                        })
                    {
                        hit = Some(super::reads_app_state(&format!("`{}`", var.qualified)));
                        return;
                    }
                    // `local.token` is not the object's variable when `local` is a parameter or a
                    // local declared above it.
                    if hides(receiver, node.start_byte()) {
                        return;
                    }
                    if let Some(var) = self.vars.iter().find(|v| v.qualified == written) {
                        hit = Some(super::reads_app_state(&format!("`{}`", var.qualified)));
                    }
                }
                "identifier" => {
                    // A declaration's own name is not a read of a same-named property.
                    if is_declaration_name(node) || is_call_name(node) {
                        return;
                    }
                    // A selector inside `x.name` is not a bare reference to `name`.
                    if node
                        .parent()
                        .is_some_and(|p| p.kind() == "navigation_expression")
                        && node
                            .parent()
                            .and_then(|p| named_children(p).into_iter().nth(1))
                            .is_some_and(|second| second == node)
                    {
                        return;
                    }
                    let name = text(node, source);
                    if hides(name, node.start_byte()) {
                        return;
                    }
                    if let Some(var) = self.vars.iter().find(|v| {
                        v.name == name && (v.owner.is_none() || v.owner.as_deref() == owner)
                    }) {
                        hit = Some(super::reads_app_state(&format!("`{}`", var.name)));
                    }
                }
                _ => {}
            }
        });
        hit
    }
}

/// The name a `property_declaration` declares: its `variable_declaration`'s first identifier.
fn property_name(property: Node<'_>, source: &str) -> Option<String> {
    for child in named_children(property) {
        if child.kind() != "variable_declaration" {
            continue;
        }
        return named_children(child)
            .into_iter()
            .find(|c| matches!(c.kind(), "identifier" | "simple_identifier"))
            .map(|n| text(n, source).to_string());
    }
    // With an annotation the grammar nests the declaration differently; the name is still the first
    // identifier that is not inside the annotation.
    let mut found = None;
    syntax::walk(property, |n| {
        if found.is_some() || n.kind() == "annotation" {
            return;
        }
        if matches!(n.kind(), "identifier" | "simple_identifier") {
            found = Some(text(n, source).to_string());
        }
    });
    found
}

/// Whether `node` is what a call calls: `count()` is a function, not a read of a `var count`.
fn is_call_name(node: Node<'_>) -> bool {
    node.parent().is_some_and(|parent| {
        matches!(parent.kind(), "call_expression")
            && named_children(parent)
                .first()
                .is_some_and(|callee| *callee == node)
    })
}

/// Whether `node` is the name a declaration gives its subject: `fun count()`, `var count`, or a
/// parameter. Reading such a name is not a read of a property that happens to share it.
fn is_declaration_name(node: Node<'_>) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    match parent.kind() {
        "function_declaration" | "parameter" => parent
            .child_by_field_name("name")
            .is_some_and(|name| name == node),
        // `variable_declaration` carries no `name` field: its first identifier is the name.
        "variable_declaration" => named_children(parent)
            .into_iter()
            .find(|c| matches!(c.kind(), "identifier" | "simple_identifier"))
            .is_some_and(|first| first == node),
        _ => false,
    }
}

fn object_state(container: Node<'_>, source: &str, package: Option<&str>, vars: &mut Vec<MutVar>) {
    let object = matches!(container.kind(), "object_declaration" | "companion_object")
        .then(|| object_path(container, source))
        .flatten();
    let class = (container.kind() == "companion_object")
        .then(|| container.parent().and_then(|b| b.parent()))
        .flatten()
        .and_then(|c| object_path(c, source));
    for member in named_children(container) {
        if member.kind() != "class_body" {
            continue;
        }
        for item in named_children(member) {
            match item.kind() {
                "property_declaration" if is_var(item, source) => {
                    let (Some(object), Some(field)) = (&object, declared_name(item, source)) else {
                        continue;
                    };
                    let mut paths = vec![object.clone()];
                    paths.extend(class.clone());
                    for path in paths {
                        vars.push(MutVar {
                            qualified: format!("{path}.{field}"),
                            name: field.clone(),
                            owner: Some(object.clone()),
                        });
                        if let Some(pkg) = package {
                            vars.push(MutVar {
                                qualified: format!("{pkg}.{path}.{field}"),
                                name: String::new(),
                                owner: Some(object.clone()),
                            });
                        }
                    }
                }
                "object_declaration" | "companion_object" | "class_declaration" => {
                    object_state(item, source, package, vars);
                }
                _ => {}
            }
        }
    }
}

fn object_path(node: Node<'_>, source: &str) -> Option<String> {
    let own = match (node.kind(), node.child_by_field_name("name")) {
        ("object_declaration" | "class_declaration", Some(name)) => text(name, source).to_string(),
        ("companion_object", Some(name)) => text(name, source).to_string(),
        ("companion_object", None) => "Companion".to_string(),
        _ => return None,
    };
    match node
        .parent()
        .filter(|p| p.kind() == "class_body")
        .and_then(|b| b.parent())
    {
        Some(outer) => Some(format!("{}.{own}", object_path(outer, source)?)),
        None => Some(own),
    }
}

/// The `object` a container declares its functions in, when it is one: `object Config { fun f() }`
/// reaches `Config`'s own `var`s by bare name.
fn owner_of(container: Node<'_>, source: &str) -> Option<String> {
    match container.kind() {
        "object_declaration" | "companion_object" => object_path(container, source),
        _ => None,
    }
}

/// Whether a `property_declaration` declares a `var`: the keyword comes after any modifiers and
/// annotations, so the whole line is checked, and a lone `val` is what says it cannot change.
fn is_var(property: Node<'_>, source: &str) -> bool {
    let line = text(property, source).lines().next().unwrap_or_default();
    let words: Vec<&str> = line
        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
        .filter(|w| !w.is_empty())
        .collect();
    words.contains(&"var") && !words.contains(&"val")
}

/// The name a `property_declaration`, `variable_declaration` or `parameter` declares: its `name`
/// field when the grammar sets one, else the first identifier below it (`var topCount = 0` keeps
/// the name in a `variable_declaration`, not in a field).
fn declared_name(node: Node<'_>, source: &str) -> Option<String> {
    if let Some(name) = node.child_by_field_name("name") {
        return Some(text(name, source).to_string());
    }
    // `@JvmField var count = 0`: the first identifier of the line is inside the annotation, so the
    // name comes from the declaration itself. Modifiers and annotations carry no name.
    for child in named_children(node) {
        if matches!(child.kind(), "annotation" | "modifiers") {
            continue;
        }
        if let Some(name) = child.child_by_field_name("name") {
            return Some(text(name, source).to_string());
        }
        if matches!(child.kind(), "identifier" | "simple_identifier") {
            return Some(text(child, source).to_string());
        }
    }
    let mut found = None;
    syntax::walk(node, |n| {
        if found.is_some() || matches!(n.kind(), "annotation") {
            return;
        }
        if matches!(n.kind(), "identifier" | "simple_identifier") {
            found = Some(text(n, source).to_string());
        }
    });
    found
}

fn collect(
    container: Node<'_>,
    source: &str,
    owner: &str,
    path: &str,
    default_static: bool,
    state: &MutableState,
    out: &mut Vec<ExportedFn>,
) {
    let children = named_children(container);
    // `class_member_declaration` is a hidden supertype in this grammar, so the concrete
    // declarations appear directly under `class_body`.
    let members: Vec<Node> = children
        .iter()
        .flat_map(|n| {
            if n.kind() == "class_body" {
                named_children(*n)
                    .into_iter()
                    .filter(|m| m.kind() == "function_declaration")
                    .collect::<Vec<_>>()
            } else {
                Vec::new()
            }
        })
        .collect();
    // A top-level `function_declaration` is its own container; an `object` or `class_body`
    // holds its functions as members.
    let candidates: Vec<Node> = if container.kind() == "function_declaration" {
        vec![container]
    } else {
        members
            .into_iter()
            .filter(|n| n.kind() == "function_declaration")
            .collect()
    };
    for function in candidates {
        let mods = modifiers(function, source);
        let has = |word: &str| modifier_words(&mods).any(|w| w == word);
        if has("private") || has("protected") || has("internal") {
            continue;
        }
        if !default_static && !has("@JvmStatic") {
            continue;
        }
        let Some(name_node) = function.child_by_field_name("name") else {
            continue;
        };
        let name = text(name_node, source).to_string();
        let mut blocker = None;
        // `fun Foo.bar()` needs a dispatched receiver; the JVM owner would not be the file class.
        if source
            .get(function.start_byte()..name_node.start_byte())
            .unwrap_or_default()
            .trim_end()
            .ends_with('.')
        {
            blocker.get_or_insert_with(|| "extension functions need a receiver".into());
        }
        if mods.split_whitespace().any(|w| w == "suspend") {
            blocker = Some("suspend functions keep their continuation in Kotlin".into());
        }
        if mods.split_whitespace().any(|w| w == "inline") {
            blocker.get_or_insert_with(|| "inline functions are not callable over JNI".into());
        }
        if mods.contains("JvmName") {
            blocker.get_or_insert_with(|| "renames the JVM method with `@JvmName`".into());
        }
        if named_children(function)
            .iter()
            .any(|n| n.kind() == "type_parameters")
        {
            blocker.get_or_insert_with(|| "generic: erased types cannot be recovered".into());
        }
        let mut params = Vec::new();
        let mut signature = Vec::new();
        for child in named_children(function) {
            if child.kind() != "function_value_parameters" {
                continue;
            }
            for p in named_children(child) {
                if p.kind() != "parameter" {
                    continue;
                }
                let pchildren = named_children(p);
                let pname = pchildren
                    .iter()
                    .find(|n| n.kind() == "identifier")
                    .map_or(String::new(), |n| text(*n, source).to_string());
                let pmods = modifiers(p, source);
                if pmods.contains("vararg") || pmods.contains("noinline") {
                    blocker.get_or_insert_with(|| "is variadic or takes an inline function".into());
                }
                let ptype = pchildren
                    .iter()
                    .find(|n| is_type_node(n.kind()))
                    .map_or_else(|| "Any".to_string(), |n| type_text(*n, source));
                let ts_type = kotlin_to_ts_param(&ptype).unwrap_or_else(|reason| {
                    blocker.get_or_insert(reason);
                    "unknown".into()
                });
                let java_type = kotlin_to_java_param(&ptype).unwrap_or_else(|| {
                    blocker.get_or_insert_with(|| {
                        format!("`{ptype}` has no Java counterpart for the wrapper")
                    });
                    "Object".into()
                });
                signature.push(format!("{ptype} {pname}"));
                params.push(Param {
                    name: pname,
                    ts_type,
                    native_type: Some(java_type),
                    ..Default::default()
                });
            }
        }
        let ret = named_children(function)
            .iter()
            .find(|n| n.start_byte() > name_node.end_byte() && is_type_node(n.kind()))
            .map_or_else(
                || {
                    let is_expr_body = named_children(function)
                        .iter()
                        .find(|n| n.kind() == "function_body")
                        .is_some_and(|body| text(*body, source).trim_start().starts_with('='));
                    if is_expr_body {
                        blocker.get_or_insert_with(|| {
                            "expression body has no explicit return type".into()
                        });
                    }
                    "Unit".to_string()
                },
                |n| type_text(*n, source),
            );
        let returns = kotlin_to_ts(&ret).unwrap_or_else(|reason| {
            blocker.get_or_insert(reason);
            "unknown".into()
        });
        let native_return = kotlin_to_java(&ret).unwrap_or_else(|| {
            blocker
                .get_or_insert_with(|| format!("`{ret}` has no Java counterpart for the wrapper"));
            "Object".into()
        });
        if out.iter().any(|f: &ExportedFn| f.name == name) {
            blocker = Some(super::OVERLOADED.into());
        }
        let calls = calls(function, source);
        // A port would read the machine it runs on, as in Java (issue #1409).
        if blocker.is_none() {
            blocker =
                super::reads_default_locale(&calls).or_else(|| super::reads_singleton(&calls));
        }
        if blocker.is_none() {
            blocker = state.touched_by(function, source, owner_of(container, source).as_deref());
        }
        if blocker.is_none() {
            let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
            blocker = super::effects::function_reason(
                super::Lang::Kotlin,
                &names,
                text(function, source),
            );
        }
        let (mutates, prints) = crate::ts::exports::observed_effects(
            super::Lang::Kotlin,
            &params,
            text(function, source),
        );
        out.push(ExportedFn {
            mutates,
            prints,
            name,
            file: path.to_string(),
            line: syntax::line(function),
            params,
            returns,
            native_return: Some(native_return),
            prototype: Some(format!(
                "{owner}.{}({})",
                text(name_node, source),
                signature.join(", ")
            )),
            blocker,
            calls,
            ..Default::default()
        });
    }
}

/// The functions a declaration's body calls: `name`, or `Owner.name` through an object or class
/// (`Config.instance()`). A call on the result of another call names no export and is left out.
fn calls(function: Node, source: &str) -> Vec<String> {
    let mut out = Vec::new();
    syntax::walk(function, |node| {
        if node.kind() != "call_expression" {
            return;
        }
        let Some(callee) = named_children(node).into_iter().next() else {
            return;
        };
        let call: String = text(callee, source).split_whitespace().collect();
        if !call.is_empty()
            && call
                .chars()
                .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
            && !out.contains(&call)
        {
            out.push(call);
        }
    });
    out
}

/// `@file:JvmName("Utils")`, which renames the class a file's top-level functions live on.
fn file_jvm_name(root: Node<'_>, source: &str) -> Option<String> {
    named_children(root)
        .into_iter()
        .filter(|n| n.kind() == "file_annotation")
        .map(|n| text(n, source))
        .find_map(|t| {
            let rest = &t[t.find("JvmName")?..];
            let start = rest.find('"')? + 1;
            let end = start + rest[start..].find('"')?;
            Some(rest[start..end].to_string())
        })
}

/// Whether `name` can be a Java class name, so a wrapper can declare it.
fn is_java_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

/// JVM-visible functions of a Kotlin file, with Java-shaped prototypes so the Java JNI
/// codegen can be reused unchanged.
pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
    if !path.ends_with(".kt") {
        return Vec::new();
    }
    let Some(tree) = syntax::parse(&language(), source) else {
        return Vec::new();
    };
    let root = tree.root_node();
    let package = package_name_in(root, source);
    let stem = path
        .rsplit('/')
        .next()
        .unwrap_or(path)
        .trim_end_matches(".kt");
    let top_class = file_jvm_name(root, source).unwrap_or_else(|| {
        // Kotlin capitalizes the file's first letter for the default JVM facade:
        // `app.kt` in package `p` becomes `p.AppKt`, not `p.appKt`.
        let mut chars = stem.chars();
        let head = chars
            .next()
            .map(|c| c.to_uppercase().collect::<String>())
            .unwrap_or_default();
        format!("{head}{}Kt", chars.as_str())
    });
    let owner = |class: &str| match &package {
        Some(p) => format!("{p}.{class}"),
        None => class.to_string(),
    };
    let mut out = Vec::new();
    let package = package_name_in(root, source);
    let state = MutableState::of(root, source, package.as_deref());
    for child in named_children(root) {
        match child.kind() {
            "function_declaration" => {
                // Top-level function: JVM owner is `<File>Kt`, or `@file:JvmName`.
                collect(
                    child,
                    source,
                    &owner(&top_class),
                    path,
                    true,
                    &state,
                    &mut out,
                );
            }
            "object_declaration" => {
                let Some(name) = child.child_by_field_name("name") else {
                    continue;
                };
                collect(
                    child,
                    source,
                    &owner(text(name, source)),
                    path,
                    false,
                    &state,
                    &mut out,
                );
            }
            "class_declaration" => {
                let Some(name) = child.child_by_field_name("name") else {
                    continue;
                };
                let class_owner = owner(text(name, source));
                for member in named_children(child) {
                    if member.kind() == "class_body" {
                        for decl in named_children(member) {
                            if decl.kind() == "object_declaration" {
                                // A nested object has its own JVM class; only a companion
                                // object's statics live on the enclosing class.
                                if let Some(nested) = decl.child_by_field_name("name") {
                                    collect(
                                        decl,
                                        source,
                                        &owner(&format!(
                                            "{}${}",
                                            text(name, source),
                                            text(nested, source)
                                        )),
                                        path,
                                        false,
                                        &state,
                                        &mut out,
                                    );
                                }
                            } else if decl.kind() == "companion_object" {
                                collect(decl, source, &class_owner, path, false, &state, &mut out);
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
    // The reflection driver keys methods by name alone: an overload would pick an arbitrary
    // signature. Block every export sharing a name, not just the later declaration.
    let mut counts: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
    for f in &out {
        *counts.entry(f.name.clone()).or_default() += 1;
    }
    for f in &mut out {
        if counts.get(&f.name).copied().unwrap_or(0) > 1 {
            f.blocker = Some(super::OVERLOADED.into());
        }
    }
    for f in &mut out {
        let (class, _) = receiver(f);
        let simple = class.rsplit('.').next().unwrap_or(&class);
        if !is_java_identifier(simple) {
            f.blocker.get_or_insert_with(|| {
                format!("JVM class `{class}` is not a valid Java name; add `@file:JvmName`")
            });
        }
    }
    out
}

/// The declaring JVM class and method name of an export, e.g. `("com.x.TextKt", "slugify")`.
pub fn receiver(f: &ExportedFn) -> (String, String) {
    crate::lang::java::receiver(f)
}

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

    #[test]
    fn this_state_and_calls_are_told_apart_from_plain_reads() {
        // Third review of #1065: `this.token` inside the object, and `count()` not being a read.
        let source = "package a\n\
             \n\
             var count = 0\n\
             \n\
             object Config {\n\
             var token = \"\"\n\
             @JvmStatic fun own(): String = this.token\n\
             @JvmStatic fun call(): Int = sizeOf()\n\
             private fun sizeOf(): Int = 1\n\
             }\n";
        let fns = exports("src/a/Third.kt", source);
        let reason = |name: &str| {
            fns.iter()
                .find(|f| f.name == name)
                .and_then(|f| f.blocker.clone())
        };
        assert_eq!(
            reason("own").as_deref(),
            Some("reads app state (`Config.token`)"),
            "`this.token` is the object's variable: {fns:?}"
        );
        let call = reason("call").unwrap_or_default();
        assert!(
            !call.contains("reads app state"),
            "a call is not a read of a `var` of the same name: {call}"
        );
    }

    #[test]
    fn a_package_qualified_name_and_a_annotation_resolve_to_the_same_var() {
        // The three points of #1065's second review: `a.count`, a function named like a var, and a
        // name taken from an annotation instead of the declaration.
        let source = "package a\n\
             \n\
             var count = 0\n\
             \n\
             fun qualified(): Int = a.count\n\
             fun named(): Int { return count }\n\
";
        let fns = exports("src/a/Pkg.kt", source);
        let reason = |name: &str| {
            fns.iter()
                .find(|f| f.name == name)
                .and_then(|f| f.blocker.clone())
        };
        assert_eq!(
            reason("qualified").as_deref(),
            Some("reads app state (`a.count`)"),
            "a package-qualified top-level var: {fns:?}"
        );
        assert_eq!(
            reason("named").as_deref(),
            Some("reads app state (`count`)"),
            "a function named like a var still reads it: {fns:?}"
        );
    }

    #[test]
    fn state_is_matched_the_way_kotlin_scopes_it() {
        // The six points of #1065's review, one case each.
        let source = "package a\n\
             \n\
             var topCount = 0\n\
             private var hidden = 1\n\
             \n\
             object Config {\n\
             var token = \"\"\n\
             @JvmStatic fun stamp(): String { token = \"t\"; return token }\n\
             }\n\
             \n\
             fun later(): Int { val y = topCount; val topCount = 1; return y }\n\
             fun shadowed(): Int { val topCount = 1; return topCount }\n\
             fun other(c: Config): String { return c.token }\n\
             fun selector(): Int { return listOf(topCount).size }\n\
             fun modifier(): Int { return hidden }\n";
        let fns = exports("src/a/Scope.kt", source);
        let reason = |name: &str| {
            fns.iter()
                .find(|f| f.name == name)
                .and_then(|f| f.blocker.clone())
        };
        assert_eq!(
            reason("stamp").as_deref(),
            Some("reads app state (`token`)"),
            "a bare name inside the owning object: {fns:?}"
        );
        assert_eq!(
            reason("later").as_deref(),
            Some("reads app state (`topCount`)"),
            "a local declared after the read does not hide it: {fns:?}"
        );
        assert_eq!(
            reason("shadowed"),
            None,
            "a local declared before the read hides it: {fns:?}"
        );
        let other = reason("other").unwrap_or_default();
        assert!(
            !other.contains("reads app state"),
            "`c.token` is a parameter's field, not the object's variable: {other}"
        );
        assert_eq!(
            reason("modifier").as_deref(),
            Some("reads app state (`hidden`)"),
            "`private var` is still a var: {fns:?}"
        );
    }

    #[test]
    fn a_function_that_touches_a_top_level_or_object_var_stays_in_kotlin() {
        // Issue #745, remaining part: Kotlin top-level and `object` vars (amended by the
        // maintainer's update on the issue).
        let source = "package a\n\
             \n\
             var topCount = 0\n\
             val fixed = 1\n\
             \n\
             object Config {\n\
             var token = \"\"\n\
             val name = \"x\"\n\
             }\n\
             \n\
             fun bump(): Int { topCount = topCount + 1; return topCount }\n\
             fun stamp(): String { Config.token = \"t\"; return Config.token }\n\
             fun plain(n: Int): Int { val topCount = n; return topCount + fixed }\n";
        let fns = exports("src/a/Store.kt", source);
        let reason = |name: &str| {
            fns.iter()
                .find(|f| f.name == name)
                .and_then(|f| f.blocker.clone())
        };
        assert_eq!(
            reason("bump").as_deref(),
            Some("reads app state (`topCount`)"),
            "{fns:?}"
        );
        assert_eq!(
            reason("stamp").as_deref(),
            Some("reads app state (`Config.token`)"),
            "{fns:?}"
        );
        assert_eq!(
            reason("plain"),
            None,
            "a local `val` of the same name hides the top-level var, and a `val` is not state"
        );
    }

    #[test]
    fn a_function_that_reads_the_default_locale_stays_in_kotlin() {
        // Issue #1409: the same calls Java keeps, on the same JVM.
        let source = "import java.time.ZoneId\n\
             import java.util.Locale\n\
             \n\
             fun zone(): String = ZoneId.systemDefault().id\n\
             \n\
             fun shout(s: String): String = s.uppercase(Locale.getDefault())\n\
             \n\
             fun utf(): String = java.nio.charset.Charset.defaultCharset().name()\n\
             \n\
             fun plain(s: String): String = s.uppercase(Locale.ROOT)\n";
        let fns = exports("src/main/kotlin/When.kt", source);
        let reason = |name: &str| {
            fns.iter()
                .find(|f| f.name == name)
                .and_then(|f| f.blocker.clone())
        };
        assert_eq!(
            reason("zone").as_deref(),
            Some("reads the default locale (`ZoneId.systemDefault`)"),
            "{fns:?}"
        );
        assert_eq!(
            reason("shout").as_deref(),
            Some("reads the default locale (`Locale.getDefault`)"),
            "{fns:?}"
        );
        assert_eq!(
            reason("utf").as_deref(),
            Some("reads the default locale (`java.nio.charset.Charset.defaultCharset`)"),
            "{fns:?}"
        );
        assert_eq!(reason("plain"), None, "a fixed locale is not the machine's");
    }

    #[test]
    fn a_primitive_array_is_named_with_the_reason_the_wire_gives() {
        // int, long, double and boolean element arrays are what the Java wire converts.
        for (kotlin, ts) in [
            ("IntArray", "int[]"),
            ("LongArray", "int[]"),
            ("DoubleArray", "number[]"),
            ("BooleanArray", "boolean[]"),
        ] {
            assert_eq!(kotlin_to_ts(kotlin), Ok(ts.to_string()), "{kotlin}");
        }
        // The other three are refused, and the reason names the wire rather than a "class".
        for kotlin in ["ByteArray", "ShortArray", "FloatArray"] {
            let reason = kotlin_to_ts(kotlin).unwrap_err();
            assert!(reason.contains("Java wire"), "{kotlin}: {reason}");
            assert!(!reason.contains("uses the class"), "{kotlin}: {reason}");
        }
        // `CharArray` is UTF-16 code units, like `Char`, and keeps that reason.
        assert!(kotlin_to_ts("CharArray").is_err());
    }

    #[test]
    fn scans_risks_and_imports() {
        let src =
            "import kotlinx.coroutines.runBlocking\n\nfun f(x: String?): Int = x!!.toInt() / 2\n";
        let facts = scan(src);
        assert!(facts.risks.contains_key(&Risk::Concurrency));
        assert!(facts.risks.contains_key(&Risk::NullReferences));
        assert!(facts.risks.contains_key(&Risk::IntegerSemantics));
        assert!(facts.risks.contains_key(&Risk::DivisionSemantics));
        assert_eq!(facts.imports.len(), 1, "{:?}", facts.imports);
        assert_eq!(facts.parse_errors, 0);
    }

    #[test]
    fn hash_order_comes_from_hash_collections_only() {
        let unordered = |src: &str| scan(src).risks.contains_key(&Risk::UnorderedIteration);
        let hashed = "package demo\n\nfun uniqueTags(tags: List<String>): List<String> {\n    val seen = hashSetOf<String>()\n    for (t in tags) seen.add(t.lowercase())\n    return seen.toList()\n}\n";
        assert!(unordered(hashed), "hashSetOf needs no import");
        let linked = "package demo\n\nimport java.util.LinkedHashMap\n\nfun firstSeen(tags: List<String>): List<String> {\n    val seen = LinkedHashMap<String, Int>()\n    for (t in tags) seen.putIfAbsent(t, 1)\n    return seen.keys.toList()\n}\n";
        assert!(!unordered(linked), "LinkedHashMap keeps insertion order");
        for call in [
            "HashMap<String, Int>()",
            "HashSet<Int>()",
            "hashMapOf(\"a\" to 1)",
            "java.util.HashSet<Int>()",
        ] {
            assert!(unordered(&format!("fun f() = {call}\n")), "{call}");
        }
        for call in [
            "mutableMapOf(\"a\" to 1)",
            "mutableSetOf(1)",
            "LinkedHashSet<Int>()",
        ] {
            assert!(!unordered(&format!("fun f() = {call}\n")), "{call}");
        }
        assert!(unordered("import java.util.HashMap\n"));
        assert!(unordered("import java.util.HashMap;\n"));
        let chained = scan("fun f() = hashSetOf<Int>().toList()\n");
        assert_eq!(
            chained.risks.get(&Risk::UnorderedIteration).map(Vec::len),
            Some(1),
            "one construction, one risk: {:?}",
            chained.risks
        );
        assert!(!unordered("import java.util.LinkedHashSet\n"));
    }

    #[test]
    fn maps_types() {
        assert_eq!(kotlin_to_ts("String?").unwrap(), "string | undefined");
        assert_eq!(kotlin_to_ts("List<String>").unwrap(), "string[]");
        assert_eq!(
            kotlin_to_ts("Map<String, List<Int>>").unwrap(),
            "Record<string, int[]>"
        );
        assert_eq!(kotlin_to_ts("IntArray").unwrap(), "int[]");
        assert_eq!(kotlin_to_ts("Unit").unwrap(), "void");
        assert!(kotlin_to_ts("Char").is_err());
        assert!(kotlin_to_ts("Any").is_err());
        assert!(kotlin_to_ts("Set<String>").is_err());
    }

    #[test]
    fn maps_java_types() {
        assert_eq!(kotlin_to_java("Int").unwrap(), "int");
        assert_eq!(kotlin_to_java("String?").unwrap(), "String");
        assert_eq!(kotlin_to_java("List<Int>").unwrap(), "List<Integer>");
        assert_eq!(
            kotlin_to_java("Map<String, Long>").unwrap(),
            "Map<String, Long>"
        );
        assert_eq!(kotlin_to_java("IntArray").unwrap(), "int[]");
        assert_eq!(kotlin_to_java("Unit").unwrap(), "void");
        assert!(kotlin_to_java("Char").is_none());
        assert!(kotlin_to_java("Foo").is_none());
    }

    #[test]
    fn finds_top_level_and_jvm_static_exports() {
        let src = "package com.example\n\nexternal fun add(a: Int, b: Int): Int\n\
                   private fun hidden() {}\n\
                   object Math {\n  @JvmStatic external fun mul(a: Int, b: Int): Int\n\
                   fun instanceOnly() {}\n}\n";
        let fns = exports("src/main/kotlin/com/example/NativeLib.kt", src);
        assert_eq!(fns.len(), 2, "{fns:?}");
        let by_name = |n: &str| fns.iter().find(|f| f.name == n).unwrap();
        assert_eq!(receiver(by_name("add")).0, "com.example.NativeLibKt");
        assert_eq!(receiver(by_name("mul")).0, "com.example.Math");
    }

    #[test]
    fn annotations_do_not_count_as_modifiers() {
        let src = "package com.example\n\n@Suppress(\"private\") fun shown(a: Int): Int = a\n\
                   @InternalApi fun alsoShown(a: Int): Int = a\n\
                   object Math {\n  @JvmStaticSomething fun notStatic(a: Int): Int = a\n}\n";
        let mut names: Vec<String> = exports("src/main/kotlin/com/example/Lib.kt", src)
            .into_iter()
            .map(|f| f.name)
            .collect();
        names.sort();
        assert_eq!(names, ["alsoShown", "shown"]);
    }

    #[test]
    fn a_companion_object_static_lives_on_the_class() {
        let src = "package com.example\n\nclass Math {\n  companion object {\n    @JvmStatic fun add(a: Int, b: Int): Int = a + b\n  }\n}\n";
        let fns = exports("src/main/kotlin/com/example/Math.kt", src);
        assert_eq!(fns.len(), 1, "{fns:?}");
        assert_eq!(receiver(&fns[0]).0, "com.example.Math");
    }

    #[test]
    fn file_jvm_name_overrides_the_class() {
        let src =
            "@file:JvmName(\"Utils\")\npackage com.example\n\nfun ping(): String = \"pong\"\n";
        let fns = exports("src/main/kotlin/com/example/NativeLib.kt", src);
        assert_eq!(receiver(&fns[0]).0, "com.example.Utils");
    }

    #[test]
    fn an_invalid_jvm_class_name_is_blocked_not_guessed() {
        let src = "package com.example\n\nfun ping(): String = \"pong\"\n";
        let fns = exports("src/main/kotlin/my-file.kt", src);
        assert!(fns[0].blocker.as_deref().unwrap_or("").contains("JvmName"));
    }

    #[test]
    fn blocks_suspend_and_generic() {
        let src = "package com.example\n\nsuspend fun slow(x: String): String = x\n\
                   fun <T> identity(x: T): T = x\n\
                   @JvmName(\"renamed\") fun named(): String = \"\"\n";
        let fns = exports("src/main/kotlin/com/example/X.kt", src);
        assert!(fns.iter().all(|f| f.blocker.is_some()), "{fns:?}");
        assert!(
            fns.iter()
                .any(|f| f.blocker.as_deref().unwrap_or("").contains("JvmName")),
            "{fns:?}"
        );
    }

    #[test]
    fn out_projections_map_in_params_and_in_or_return_projections_stay_refused() {
        // Return position refuses `out T`, `in T`, and `*`.
        assert!(
            kotlin_to_ts("List<out CharSequence>")
                .unwrap_err()
                .contains("out CharSequence")
        );
        assert!(
            kotlin_to_ts("List<in String>")
                .unwrap_err()
                .contains("in String")
        );
        assert!(
            kotlin_to_ts("List<*>")
                .unwrap_err()
                .contains("values of any type")
        );
        assert!(kotlin_to_java("List<out CharSequence>").is_none());
        assert!(kotlin_to_java("List<in String>").is_none());
        assert!(kotlin_to_java("List<*>").is_none());

        // Parameter position unwraps `out T` to `T` and maps to Java `? extends T` (or `T[]` for arrays).
        assert_eq!(
            kotlin_to_ts_param("List<out CharSequence>").unwrap(),
            "string[]"
        );
        assert_eq!(
            kotlin_to_java_param("List<out CharSequence>").unwrap(),
            "List<? extends CharSequence>"
        );
        assert_eq!(
            kotlin_to_ts_param("Map<String, out Int>").unwrap(),
            "Record<string, int>"
        );
        assert_eq!(
            kotlin_to_java_param("Map<String, out Int>").unwrap(),
            "Map<String, ? extends Integer>"
        );
        assert_eq!(
            kotlin_to_ts_param("Array<out CharSequence>").unwrap(),
            "string[]"
        );
        assert_eq!(
            kotlin_to_java_param("Array<out CharSequence>").unwrap(),
            "CharSequence[]"
        );
        assert_eq!(
            kotlin_to_ts_param("List<out String?>").unwrap(),
            "(string | undefined)[]"
        );
        assert_eq!(
            kotlin_to_java_param("List<out String?>").unwrap(),
            "List<? extends String>"
        );
        assert_eq!(
            kotlin_to_ts_param("List<out Number>").unwrap_err(),
            "uses the class `Number`"
        );
        assert!(
            kotlin_to_ts_param("List<in String>")
                .unwrap_err()
                .contains("in String")
        );
        assert!(
            kotlin_to_ts_param("List<*>")
                .unwrap_err()
                .contains("values of any type")
        );
    }

    #[test]
    fn exports_accept_out_projections_in_parameters_only() {
        let src = r#"package acme

fun count(xs: List<out CharSequence>): Int = xs.size
fun arrLen(xs: Array<out String>): Int = xs.size
fun total(xs: List<out Number>): Double = 0.0
fun echo(xs: List<out CharSequence>): List<out CharSequence> = xs
fun add(xs: MutableList<in String>) {}
fun anyLen(xs: List<*>): Int = xs.size
"#;
        let fns = exports("src/main/kotlin/acme/Totals.kt", src);
        let by = |name: &str| fns.iter().find(|f| f.name == name).unwrap();

        let count = by("count");
        assert!(count.blocker.is_none(), "{count:?}");
        assert_eq!(count.params[0].ts_type, "string[]");
        assert_eq!(
            count.params[0].native_type.as_deref(),
            Some("List<? extends CharSequence>")
        );

        let arr_len = by("arrLen");
        assert!(arr_len.blocker.is_none(), "{arr_len:?}");
        assert_eq!(arr_len.params[0].ts_type, "string[]");
        assert_eq!(arr_len.params[0].native_type.as_deref(), Some("String[]"));

        let total = by("total");
        assert_eq!(total.blocker.as_deref(), Some("uses the class `Number`"));

        let echo = by("echo");
        assert_eq!(
            echo.blocker.as_deref(),
            Some("uses a projection `out CharSequence`")
        );

        let add = by("add");
        assert_eq!(
            add.blocker.as_deref(),
            Some("uses a projection `in String`")
        );

        let any_len = by("anyLen");
        assert!(
            any_len
                .blocker
                .as_deref()
                .unwrap_or("")
                .contains("values of any type")
        );
    }

    #[test]
    fn is_java_identifier_follows_javas_rules() {
        for name in ["Text", "_x", "$x", "a1$_"] {
            assert!(is_java_identifier(name), "{name}");
        }
        for name in ["1x", "a-b", "", "é"] {
            assert!(!is_java_identifier(name), "{name}");
        }
    }

    #[test]
    fn file_jvm_name_reads_the_file_annotation() {
        let jvm_name = |source: &str| {
            let tree = syntax::parse(&language(), source).unwrap();
            file_jvm_name(tree.root_node(), source)
        };
        assert_eq!(
            jvm_name("@file:JvmName(\"Utils\")\npackage text\n\nfun f() = 1\n").as_deref(),
            Some("Utils")
        );
        assert_eq!(
            jvm_name("@file:Suppress(\"unused\")\npackage text\n\nfun f() = 1\n"),
            None
        );
        assert_eq!(jvm_name("package text\n\nfun f() = 1\n"), None);
    }

    #[test]
    fn a_companion_or_nested_object_var_is_state() {
        let source = "package a\n\
             \n\
             class Counter {\n\
             companion object {\n\
             var n = 0\n\
             @JvmStatic fun next(): Int { n = n + 1; return n }\n\
             }\n\
             object Inner {\n\
             var c = 0\n\
             @JvmStatic fun bump(): Int { c = c + 1; return c }\n\
             }\n\
             }\n\
             object Top {\n\
             var t = 0\n\
             @JvmStatic fun tick(): Int { t = t + 1; return t }\n\
             @JvmStatic fun peek(): Int = Counter.n + Counter.Inner.c\n\
             }\n";
        let fns = exports("src/a/Counter.kt", source);
        let blocker = |n: &str| {
            fns.iter()
                .find(|f| f.name == n)
                .and_then(|f| f.blocker.clone())
        };
        for name in ["tick", "next", "bump", "peek"] {
            assert!(blocker(name).is_some(), "{name}: {fns:?}");
        }
    }

    #[test]
    fn a_nested_object_lives_on_its_binary_jvm_class() {
        let source = "package a\n\
             \n\
             class Counter {\n\
             object Inner {\n\
             @JvmStatic fun twice(x: Int): Int = x * 2\n\
             }\n\
             }\n";
        let fns = exports("src/a/Counter.kt", source);
        assert_eq!(
            receiver(&fns[0]),
            ("a.Counter$Inner".to_string(), "twice".to_string())
        );
    }
}