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.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
Kotlin: read hash-order risk from hash collection calls, match imports whole (#1274)
jakalijeyda55039448e1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d5f5046..714e9c9d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -103,6 +103,10 @@included (`:save!` names `save!`, not `save`; `:+` and `:[]=` stay listed); before,`:soundex_str` also matched `soundex` as a substring, so the export was listed twice (foundporting the `text` gem's `soundex.rb`, by @cfreyes7).+- Kotlin: a call of `HashMap(...)`, `HashSet(...)`, `hashMapOf(...)` or `hashSetOf(...)` is a hash+ iteration order risk, with no import needed, and only `java.util.HashMap`/`HashSet` and+ `kotlin.collections.HashMap`/`HashSet` imports count. Before, only an import line was read, so+ `hashSetOf()` went unseen while `import java.util.LinkedHashMap` was reported (#1254 by @jakalijey).- The website's Shadow page names Kotlin with Java and says what PHP, C#, PowerShell and Swift doinstead of a shadow module, and the Analyze page says which languages `profile` runs and theprofiler to use for the others. `tests/skill.rs` checks both pages (#1267 by @jakalijey).diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex c0a0243e..cd063465 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -296,7 +296,7 @@ bad it usually is and gives one example. The severities are the ones `analyze` s| JSON round-trips | low | TS/JS `JSON`, Ruby, PHP, Go `encoding/json`, PowerShell `ConvertTo-Json`: key order, `undefined`, `NaN` || Integer width and overflow | medium | Python, Ruby and PHP `**` and `<<`; Java, Kotlin, C# shifts, `*` and hash codes; Go and C shifts and conversions: wrap vs panic || Division and modulo | medium | Python `//` and `%` and Ruby integer `/` and `%` floor (`div_euclid` is not it for a negative divisor); Java, Kotlin, C#, Go, C integer `/` and `%` and PHP `%`, `intdiv` and `fmod` truncate like Rust, so a zero divisor and `MIN / -1` are what is left; Python `"..." % args` is string formatting and not counted |-| Hash iteration order | high | Python `set`; Java and Kotlin `HashMap`/`HashSet` (also through `import java.util.*`); C# `Dictionary`/`HashSet`; Go `map` range (also over a variable declared as a map); PowerShell `@{}` hashtables |+| Hash iteration order | high | Python `set`; Java and Kotlin `HashMap`/`HashSet` (also through `import java.util.*`), and Kotlin `hashMapOf`/`hashSetOf`; C# `Dictionary`/`HashSet`; Go `map` range (also over a variable declared as a map); PowerShell `@{}` hashtables || Pointers and manual memory | high | C pointers, `malloc`, `memcpy`; Go `unsafe` and pointer types; C# `unsafe` || Concurrency | medium | Go goroutines and `sync`, Java and Kotlin threads and `synchronized`, C# `lock` and `System.Threading`, Python, Ruby, PHP and C threads, PowerShell `Start-ThreadJob` || Null references | medium | Java, C#, PHP `null`; Kotlin nullable types; Go and Ruby `nil`; C `NULL`; PowerShell `$null` |diff --git a/src/lang/kotlin.rs b/src/lang/kotlin.rsindex a7f80b15..da49c7b3 100644--- a/src/lang/kotlin.rs+++ b/src/lang/kotlin.rs@@ -163,6 +163,17 @@ fn join(dir: &str, rest: &str) -> String {// ---- 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),@@ -194,7 +205,13 @@ pub fn scan(source: &str) -> FileFacts {s if s.starts_with("java.util.regex") || s.starts_with("kotlin.text.Regex") => {add(&mut facts, Risk::RegexSyntax, node)}- s if s.contains("HashMap") || s.contains("HashSet") => {+ s if HASH_IMPORTS.contains(+ &s.split_whitespace()+ .next()+ .unwrap_or("")+ .trim_end_matches(';'),+ ) =>+ {add(&mut facts, Risk::UnorderedIteration, node)}_ => {}@@ -254,6 +271,21 @@ pub fn scan(source: &str) -> FileFacts {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("");@@ -1490,6 +1522,40 @@ mod tests {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");