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.

PHP and C: a method reached through -> or :: is not the global function (#1429)

jakalijeyd2b40f42c281
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8d859012..706cd866 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -296,6 +296,9 @@
- PowerShell: a parameter typed `[decimal]`, `[uint64]` or `[ulong]` keeps its function in
PowerShell, with the reasons C# gives for the same types, instead of bridging it as `f64` or
`i64`. `[uint32]`, `[double]` and `[single]` bridge as before (#1341 by @jakalijey).
+- PHP and C: a method reached through `->` or `::` (`$request->date()`, `$config->getenv()`,
+ `Calendar::time()`, `ops->time(0)`) is no longer taken for the global function of that name in
+ `analyze` and `bridge` (#1397 by @jakalijey).
- `analyze` counts a Swift or PowerShell clock call once: `Date()`, `.random`, `Get-Date`,
`Get-Random` and `New-Guid` were counted by both the syntax scan and the text list, which made
one call read "Clock and random numbers (2)" (#1401 by @jakalijey).
diff --git a/src/lang/effects.rs b/src/lang/effects.rs
index a263f4ce..092a438c 100644
--- a/src/lang/effects.rs
+++ b/src/lang/effects.rs
@@ -706,8 +706,10 @@ fn find_all<'a>(hay: &'a str, needle: &'a str) -> impl Iterator<Item = usize> +
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.
- let continues = before.is_some_and(|c| (is_ident(first) && is_ident(c)) || c == '.')
+ // `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);
@@ -716,6 +718,32 @@ fn find_all<'a>(hay: &'a str, needle: &'a str) -> impl Iterator<Item = usize> +
})
}
+/// 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.`,
@@ -1601,6 +1629,45 @@ mod tests {
] {
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,
@@ -1625,6 +1692,31 @@ mod tests {
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}");
@@ -2041,6 +2133,39 @@ mod tests {
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));