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.

Swift: count Set<T>, Dictionary<K, V> and Set(...) calls as hash order (#1382)

jakalijey40a773a6b650
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 938766b9..92afbc5d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -223,6 +223,9 @@
(#1337 by @jakalijey).
from one JVM start to the next. `List.of`, `Collectors.toList`, and a `toMap` or `groupingBy`
given a `TreeMap` or `LinkedHashMap` supplier are not (#1343 by @jakalijey).
+- Swift: `Set<String>`, `Dictionary<String, Int>` and `Swift.Set<Int>`, and a set or dictionary
+ built by a call (`Set(words)`, `Set<String>(...)`, `Dictionary(grouping:by:)`), are a hash
+ iteration order risk, as a bare `Set`, `Dictionary` or `[K: V]` already were (#1344 by @jakalijey).
- PowerShell: only `[datetime]::Now`, `UtcNow` and `Today`, and `[datetimeoffset]::Now` and
`UtcNow` (with or without `System.`), count as reading the clock. `[datetime]::IsLeapYear`,
`DaysInMonth`, `Parse` and the other static members compute from their arguments, so a function
diff --git a/src/lang/swift.rs b/src/lang/swift.rs
index 87516c36..c0836a9a 100644
--- a/src/lang/swift.rs
+++ b/src/lang/swift.rs
@@ -318,9 +318,11 @@ pub fn scan(source: &str) -> FileFacts {
add(&mut facts, Risk::ClockAndRandom, node);
}
}
+ "user_type" if hashed(text(node, source)) => {
+ add(&mut facts, Risk::UnorderedIteration, node)
+ }
"user_type" => match text(node, source) {
"Character" | "String.Index" => add(&mut facts, Risk::GraphemeStrings, node),
- "Set" | "Dictionary" => add(&mut facts, Risk::UnorderedIteration, node),
"Mirror" => add(&mut facts, Risk::Reflection, node),
"NSRegularExpression" | "Regex" => add(&mut facts, Risk::RegexSyntax, node),
_ => {}
@@ -332,6 +334,9 @@ pub fn scan(source: &str) -> FileFacts {
.into_iter()
.next()
.map_or("", |c| text(c, source));
+ if hashed(callee) {
+ add(&mut facts, Risk::UnorderedIteration, node);
+ }
match callee {
"Int" | "Int32" | "Int64" | "UInt" | "UInt8" | "fatalError" | "precondition" => {
add(&mut facts, Risk::SwiftTraps, node)
@@ -782,6 +787,18 @@ pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
out
}
+/// Whether a type or the callee of a call names `Set` or `Dictionary`, with or without their
+/// generic arguments and the `Swift.` module: Swift seeds their hash per process, so their order
+/// changes from one run to the next.
+fn hashed(name: &str) -> bool {
+ let name = name.trim();
+ let name = name.strip_prefix("Swift.").unwrap_or(name);
+ let base = name.split('<').next().unwrap_or(name).trim_end();
+ let args = name[base.len()..].trim_start();
+ matches!(base, "Set" | "Dictionary")
+ && (args.is_empty() || (args.starts_with('<') && args.ends_with('>')))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -939,6 +956,43 @@ extension S { func more() {} }
);
}
+ #[test]
+ fn a_generic_set_or_dictionary_and_one_built_by_a_call_are_hash_ordered() {
+ for body in [
+ "let s: Set<String> = []\n return s.count",
+ "let d: Dictionary<String, Int> = [:]\n return d.count",
+ "let s: Swift.Set<Int> = []\n return s.count",
+ "return Array(Set(words)).count",
+ "return Set<String>(words).count",
+ "return Dictionary(grouping: words, by: { $0 }).count",
+ "return Dictionary<String, Int>().count",
+ ] {
+ let src = format!("func f(_ words: [String]) -> Int {{\n {body}\n}}\n");
+ let facts = scan(&src);
+ assert_eq!(facts.parse_errors, 0, "{body}");
+ assert!(
+ facts.risks.contains_key(&Risk::UnorderedIteration),
+ "{body}: {:?}",
+ facts.risks
+ );
+ }
+ for body in [
+ "let xs: [String] = []\n return xs.count",
+ "let n: Settings = Settings()\n return n.count",
+ "return Array(words).count",
+ "let e: Set<Int>.Element = 1\n return e",
+ "let i: Dictionary<String, Int>.Index? = nil\n return i == nil ? 0 : 1",
+ ] {
+ let src = format!("func f(_ words: [String]) -> Int {{\n {body}\n}}\n");
+ let facts = scan(&src);
+ assert!(
+ !facts.risks.contains_key(&Risk::UnorderedIteration),
+ "{body}: {:?}",
+ facts.risks
+ );
+ }
+ }
+
#[test]
fn package_dependencies_are_named_from_the_manifest() {
let manifest = r#"let package = Package(