Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

php: port functions in braced namespaces

Mohit Mishra45fb970b5ab7
diff --git a/src/php.rs b/src/php.rs
index 2a05ff3..8a023bc 100644
--- a/src/php.rs
+++ b/src/php.rs
@@ -7,7 +7,7 @@ use crate::native::{self, Flavor, Patches};
use crate::python::DISABLE_ENV;
use crate::state::{Ctx, Port, Verify};
use crate::util::{self, combined, output, tail};
-use anyhow::{Context, Result, bail, ensure};
+use anyhow::{Context, Result, ensure};
use serde::Deserialize;
use serde_json::Value;
use std::collections::BTreeMap;
@@ -323,17 +323,17 @@ pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
"{} ends with ?>: remove the closing tag so code can follow it",
port.file
);
- if text.contains("namespace ")
- && text.lines().any(|l| l.trim_start().starts_with("namespace ") && l.trim_end().ends_with('{'))
- {
- bail!("{} uses braced namespaces, which fast-anything can't add code to yet", port.file);
- }
+ // with braced namespaces, no code may follow them outside a namespace block: the bridge goes in
+ // a global one of its own, and the function names it from the root
+ let braced = text.lines().any(|l| l.trim_start().starts_with("namespace ") && l.trim_end().ends_with('{'));
let class = bridge_class(port);
let from = file.parent().context("file has no folder")?;
let (_, lib) = port.lang.artifact(&port.ext);
let lib_rel = util::forward_slashes(&util::relative(from, &ctx.lib_dir().join(lib)));
let lib_lit = format!("'{}'", lib_rel.replace('\\', "\\\\").replace('\'', "\\'"));
let bridge = BRIDGE.replace("/*CLASS*/", &class).replace("/*ID*/", &port.id).replace("/*LIB*/", &lib_lit);
+ let (bridge, class) =
+ if braced { (format!("namespace {{\n{bridge}\n}}"), format!("\\{class}")) } else { (bridge, class) };
let prologue =
format!("if ({class}::$on ?? {class}::load()) return {class}::call({}, func_get_args());", name_const(hs));
let patched =
@@ -354,6 +354,57 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn ports_functions_in_braced_namespaces() {
+ if !Command::new("php").arg("-v").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no php on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-php-braced-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ let app = "<?php\nnamespace Text {\n function width(string $s): int\n {\n return strlen($s);\n }\n}\n\nnamespace {\n echo \\Text\\width('h\u{e9}llo'), \"\\n\";\n}\n";
+ fs::write(dir.join("app.php"), app).unwrap();
+ let mut ctx = Ctx::open(&dir).unwrap();
+ let found = profile(&ctx, "php", &["app.php".into()]).unwrap();
+ assert!(found.functions.iter().any(|f| f.name == "width" && f.blockers.is_empty()), "{:?}", found.functions);
+ let hs = Hotspot {
+ id: "Text.width".into(),
+ file: "app.php".into(),
+ line: 3,
+ name: "width".into(),
+ ..Hotspot::default()
+ };
+ ctx.state.hotspots.push(hs);
+ let port = Port {
+ id: "Text.width".into(),
+ file: "app.php".into(),
+ module: "Text".into(),
+ func: "width".into(),
+ ext: "fa_text_width".into(),
+ crate_dir: ".fast/ports/Text.width".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Php,
+ owner: None,
+ line: 3,
+ sources: vec![],
+ };
+ enable(&ctx, &port).unwrap();
+ // without the port's library, the bridge doesn't load and the PHP version runs
+ let lint = Command::new("php").args(["-l", "app.php"]).current_dir(&dir).output().unwrap();
+ let run = Command::new("php").arg("app.php").current_dir(&dir).output().unwrap();
+ let enabled = fs::read_to_string(dir.join("app.php")).unwrap();
+ disable(&ctx, &port).unwrap();
+ let after = fs::read_to_string(dir.join("app.php")).unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(lint.status.success(), "{}{enabled}", String::from_utf8_lossy(&lint.stdout));
+ assert_eq!(String::from_utf8_lossy(&run.stdout), "6\n", "{}", String::from_utf8_lossy(&run.stderr));
+ assert!(enabled.contains("namespace {\nfinal class"), "{enabled}");
+ assert_eq!(after, app);
+ }
+
#[test]
fn php_bits() {
assert!(is_php("php") && is_php("php8.3") && is_php("C:\\php\\php.exe") && !is_php("phpunit"));
diff --git a/src/php/describe.php b/src/php/describe.php
index 7e37aa5..2838a19 100644
--- a/src/php/describe.php
+++ b/src/php/describe.php
@@ -41,14 +41,30 @@ function describe_file(string $path): array {
$out = [];
$classes = []; // stack of [name, depth]
$depth = 0;
+ $top = 0; // the depth of top-level code: 1 inside a braced namespace X { ... }
+ $nsOpen = -1; // the token that opens that namespace block
$funcs = [];
$statics = [];
$found = [];
for ($i = 0; $i < $n; $i++) {
$t = $tokens[$i];
- if ($t === '{' || in_array(id($t), [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { $depth++; continue; }
- if ($t === '}') { $depth--; if ($classes && end($classes)[1] === $depth) array_pop($classes); continue; }
+ if ($t === '{' || in_array(id($t), [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) {
+ $depth++;
+ if ($i === $nsOpen) $top = $depth;
+ continue;
+ }
+ if ($t === '}') {
+ $depth--;
+ if ($depth < $top) $top = 0;
+ if ($classes && end($classes)[1] === $depth) array_pop($classes);
+ continue;
+ }
$k = id($t);
+ if ($k === T_NAMESPACE) {
+ for ($m = $i + 1; $m < $n && $tokens[$m] !== ';' && $tokens[$m] !== '{'; $m++);
+ if ($m < $n && $tokens[$m] === '{') $nsOpen = $m;
+ continue;
+ }
if (in_array($k, [T_CLASS, T_TRAIT, T_INTERFACE, T_ENUM], true)) {
$p = $prev($i);
if ($p >= 0 && (id($tokens[$p]) === T_DOUBLE_COLON || id($tokens[$p]) === T_NEW)) continue;
@@ -64,7 +80,7 @@ function describe_file(string $path): array {
$name = $tokens[$j][1];
$class = null;
if ($classes && $depth === end($classes)[1] + 1) $class = end($classes)[0];
- elseif ($depth !== 0) continue; // declared inside a function body
+ elseif ($depth !== $top) continue; // declared inside a function body
// modifiers and the first token of the declaration
$start = $i;
$static = false;