Hacker News new | ask | show | jobs
by beager 3270 days ago
I've generally found the behavior of builtin PHP methods to be less predictable and more involved than in JS, so I wonder if the best approach to writing a transpiler in this case would be to go to the C source and negotiate from there.

Having done PHP for years and years before the language itself found adequate elegance, I wouldn't want the burden of replicating all its weird behaviors for something like this, at least without seeing the source to understand what's happening.

3 comments

If you want to use an existing toolchain, you could use HPHPc (the predecessor to HHVM, which transpiled PHP to C code) and emscripten to translate from C to Javascript. It would probably require some mucking around at the emscripten layer though to get all the packages linking properly, because HPHPc has a non-trivial number of (non-optional) runtime deps for supporting all of the various php modules. You should just be able to compile them separately with emscripten into a prefix (e.g. don't use emscripten ports, which I've had a terrible time with) but YMMV.

I dockerized a working version of HPHPc (which is quite difficult to set up due to bitrot) at https://github.com/allanlw/hphpc-docker if you want to play around with the compiler. I might try to take a shot at passing it through emscripten later.

That's really cool, and seems like it would take a lot of the hassle of "understanding" PHP out of the equation. Nicely done!
I think the difference is that PHP's built-ins were originally created as a "toolset" and thus often do more than one thing in fairly specific combinations. I believe PHP has improved on that but it can still get hairy because of the sheer number of functions living in the global namespace (and horribly outdated community-provided examples in the documentation).
This doesn't appear to support the PHP built in functions, and is more of a tongue in cheek exercise.

Someone did take roughly the approach you're describing. A VM in JavaScript that groks php bytecode: https://github.com/niklasvh/php.js