niklasvh / php.js Goto Github PK
View Code? Open in Web Editor NEWPHP to JavaScript converter and VM written in JavaScript
Home Page: http://phpjs.hertzen.com
License: MIT License
PHP to JavaScript converter and VM written in JavaScript
Home Page: http://phpjs.hertzen.com
License: MIT License
There may be a problem with operator overloading behavior in the library.
Take:
Both $a + $b and $b + $a will cause a fatal error of unsupported operand types in PHP. However, in JS neither case is true. They yield unexpected results in JS, actually as {} + [] and [] + {} result in 0 (or NaN depending on the engine), and "[object Object]", respectively. Here the code above results in:
int(0)
int(0)
Which is what I expect the library VM is doing with the operator ADD here.
The magic methods __get and __set do not work. These features are used frequently to implement things like ActiveRecord (if one of the other interfaces like ArrayIterator is not used).
RIP
<?php
// This class abuses php magic methods to create objects that feel like JS objects
class DynamicObject {
private $properties = array();
public function __construct($assoc = array()) {
if ($assoc)
$this->add($assoc);
}
public function __set($name, $value = null) {
return !$value && is_array($name) ? $this->add($name) : $this->properties[$name] = $value;
}
public function __get($prop) {
return $this->properties[$prop] ? is_callable($this->properties[$prop]) ? 'function()' : $this->properties[$prop] : false;
}
public function __call($name, $args) {
return $this->properties[$name](implode(',', $args), $this);
}
private function add($assoc) {
foreach ($assoc as $k => $v)
$this->properties[$k] = $v;
}
}
/* -----------------------------------------------------------------------------------
TEST
------------------------------------------------------------------------------------ */
$greeting = new DynamicObject();
$greeting->hello = function ($hello = 'world') {
return 'Hello, ' . $hello . "!\n";
};
echo $greeting->hello('JavaScript');
/*
* should be
* Hello, JavaScript!
*
* but gives a parse error instead
*/
?>
e.g:
<?php
$foo = "test
multiline
string"
a
?>
shows error on line 3 instead of 6.
Hi, I tried pasting the contents of one of my projects, 2233.php, into the the converty part of your website (http://phpjs.hertzen.com/console.html), and when I ran it, it grabbed a GitHub 404 page! Very interesting.
Parser freezes when you have an unclosed comment e.g:
<?php
/*
$foo = 1 + 2;
$foo = $foo;
print $foo;
?>
@danyaPostfactum can you recreate this?
First of all let me say, this is cool! fiddling a little with your console running the following code:
<?php
for ( $i = 0; $i < 10; $i++ ) {
printf("%02d\n", $i);
}
?>
Outputs
02d
12d
22d
32d
42d
52d
62d
72d
82d
92d
LABEL0:
for( $("i")._($$(0)); ($("i").$Smaller($$(10))).$Bool.$; $("i").$PostInc().$ ) { ENV.$Timer();
(ENV.$F("printf", arguments, $$("%02d\n"), $("i")));
};
lvl = lvl.replace(err, PHP.Constants[ err ]); // ---> Error undefined lvl.replace()
XMLHttpRequest cannot load ./cfg/php.ini due to access control checks. - line 15372
TypeError: undefined is not an object (evaluating 'lvl.replace') - 12108
TypeError: undefined is not an object (evaluating 'variables_order.indexOf') - line 12143
The opts.ini
contains PHP
section.
var lvl = this.$ini.error_reporting;
---> var lvl = this.$ini.PHP.error_reporting;
It is code
<html>
<head>
</head>
<body>
<script src="PHP.min.js"></script>
<label id="x"></label>
<script>
var engine = new PHP ('<?php echo "Hello world!"; ?>');
document.getElementById("x").innerHTML = console.log( engine.vm.OUTPUT_BUFFER);
</script>
</body>
</html>
Sorry I'm noob in javascript
Sorry for my bad english
mysql_query() or die();
Gives the error:
syntax error, unexpected T_STRING, expecting identifier
Logical Operators:
http://php.net/manual/en/language.operators.logical.php
I don't get this error in PHP-Parser.
I wonder if updating and regenerating the parser files will fix this.
It looks like you need "kmyacc" to achieve this.
@niklasvh
Please, try to parse next code:
<?php
$test = true;
$test &= false;
echo 'result'. ($test ? 'true' : 'false');
?>
I got an error on PHP.Parser.prototype.yyn188
for Node_Expr_AssignBitwiseAnd
This example from Readme throws. It is expecting a second parameter, opts.
var engine = new PHP ('<?php echo "Hello world!"; ?>');
This valid code (from http://php.net/manual/en/functions.anonymous.php):
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
Gives this error:
Parse error: syntax error, unexpected T_STRING, expecting identifier in /console.htm on line 2
Is it possible to use javascript members (variables, functions, objects) in php context?
Any attempt to create a callback function, anonymous function, or wrapper, generates a syntax error.
http://php.net/manual/en/functions.anonymous.php
// Case 1:
$fn = function($e) { // Undefined is not a function on line NaN
echo $e;
}
$fn("hello\n");
// Case 2:
function callme($str, $func) {
$func($str);
}
callme( "maybe", function($e) { // Undefined is not a function on line NaN
echo $e . "\n";
} );
// Case 3:
echo preg_replace_callback('~-([a-z])~', function ($match) { // Undefined is not a function on line NaN
return strtoupper($match[1]);
}, 'hello-world');
hello
maybe
hello-world
http://php.net/manual/en/book.v8js.php
For when you want to, you know, work close to the metal.
Full output here:
https://dl.dropboxusercontent.com/u/341900/paste-2819.txt
Steps to reproduce:
git clone [email protected]:niklasvh/php.js.git phpjs
cd phpjs
npm install
npm install -g grunt-cli
grunt
OS X 10.9.4 Node.js v0.10.29
echo with multiple parameters causes a syntax error
echo('foo', 'bar');
Syntax error, unexpected ','
A common format I use is:
// generate a broadsoft document XML frame
protected function getXMLBroadsoftDocument(
$command, // the broadsoft command
$commandData = array() // the command contents to use
) {
...
This allows lots of space for documentation of arguments inline. Unfortunately though the function is the then not picked up. Not sure if you want to call it a bug or feature request, but since it's perfectly valid PHP syntax, I'm leaning towards bug.
Thanks for the great work guys!
For the following code:
$matches = array();
$ret = preg_match("{^(\S+)\s+(\d+)}", "123 4", $matches);
var_dump($ret);
if ($ret > 0)
{
var_dump($matches);
}
Expected output:
int(1)
array(3) {
[0]=>
string(5) "123 4"
[1]=>
string(3) "123"
[2]=>
string(1) "4"
}
Outputs:
int(3)
array(0) {
}
Hello,
This bitwise operator "<<" is not recognised at all and generate the following message "undefined is not a function".
http://php.net/manual/en/language.operators.bitwise.php
Sincerely,
phonem
This code:
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
Causes the error:
Parse error: Object [object Object] has no method 'Node_Stmt_Goto' in /console.htm on line undefined
serialize() always seems to just return nothing or an empty string.
i created this code, first function implements the ord function and the second a uncamelize function:
function ord($j){
$e = array(' ' => 32, '!' => 33, '"' => 34, '#' => 35, '$' => 36, '%' => 37, '&' => 38, '\'' => 39, '(' => 40, ')' => 41, '*' => 42, '+' => 43, ',' => 44, '-' => 45, '.' => 46, '/' => 47, 0 => 48, 1 => 49, 2 => 50, 3 => 51, 4 => 52, 5 => 53, 6 => 54, 7 => 55, 8 => 56, 9 => 57, ':' => 58, ';' => 59, '<' => 60, '=' => 61, '>' => 62, '?' => 63, '@' => 64, 'A' => 65, 'B' => 66, 'C' => 67, 'D' => 68, 'E' => 69, 'F' => 70, 'G' => 71, 'H' => 72, 'I' => 73, 'J' => 74, 'K' => 75, 'L' => 76, 'M' => 77, 'N' => 78, 'O' => 79, 'P' => 80, 'Q' => 81, 'R' => 82, 'S' => 83, 'T' => 84, 'U' => 85, 'V' => 86, 'W' => 87, 'X' => 88, 'Y' => 89, 'Z' => 90, '[' => 91, '\\' => 92, ']' => 93, '^' => 94, '_' => 95, '`' => 96, 'a' => 97, 'b' => 98, 'c' => 99, 'd' => 100, 'e' => 101, 'f' => 102, 'g' => 103, 'h' => 104, 'i' => 105, 'j' => 106, 'k' => 107, 'l' => 108, 'm' => 109, 'n' => 110, 'o' => 111, 'p' => 112, 'q' => 113, 'r' => 114, 's' => 115, 't' => 116, 'u' => 117, 'v' => 118, 'w' => 119, 'x' => 120, 'y' => 121, 'z' => 122, '{' => 123, '|' => 124, '}' => 125, '~' => 126,);
if(isset($e[$j])) return $e[$j]; else return 0;
}
function uncamelize($str){
$x = "";
$n = 0;
$l = strlen($str);
for($i=0;$i<$l;$i++){
$ch = $str[$i];
$a = ord($ch);
if($a < 91){
if($i!=0){
$x.="_";
}
$x.=strtolower($ch);
} else {
$x.=$ch;
}
}
return $x;
}
When calling uncamelize with ZcBa in php it returns: zc_ba
echo uncamelize("ZcBa")
but in php.js it returns: _zcba
In php.js/src/parser/yyn_scalar.js, the function:
PHP.Parser.prototype.Scalar_String_parseDocString = function() {
return '"' + arguments[ 1 ].replace(/([^"\\]*(?:\\.[^"\\]*)*)"/g, '$1\\"') + '"';
return Array.prototype.join.call(arguments, "");
};
has two contiguous return statements. I assume the second one never gets called.
Syntax error, unexpected T_SL on line 2
from:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
Try:
echo 1?: 2;
Expected output: 1
Outputs: undefined
PHP Feature added in 5.5, so likely simply hasn't been reviewed yet.
http://php.net/manual/en/control-structures.foreach.php#control-structures.foreach.list
$array = new array(
"X" => ['one',2,3],
"Y" => ['two',4,5]
);
// case 1:
foreach( $array as list($a, $b )) { // Syntax error, unexpected T_LIST
echo "\n$a $b";
}
// case 2:
foreach( $array as $key => list($a, $b, $c) ) { // Syntax error, unexpected T_LIST
echo "\n$key: $a $b - $c";
}
one 2
two 4
X: one 2 - 3
Y: two 4 - 5
Hi,
I'm trying to use this in node.js. Here's a snippet of what I wrote (res being my Response object in an onRequest() binding :
res.writeHead(200, { 'Content-Type' : 'text/html' }); var p = new PHP(data); res.write(p.vm.OUTPUT_BUFFER); res.end();
I'me getting an error on the 2nd line ("Cannot read property 'filesystem' of undefined"). According to its prototype, the PHP constructor takes 2 parameters : code and opts. What am I supposed to feed it with as the 2nd, since it's supposed to be an object having filesystem as a property ?
Anyway, thanks for this, it's a pretty awesome PoC :-)
Regards,
Parse error always listed as line 1 regardless of the line it actually occurs.
e.g.
output:
Parse error: syntax error, unexpected ')', expecting identifier in /console.htm on line 1
Now after var AST = new PHP.Parser(PHP.Lexer(code));
we can see array of objects with description of line it is:
attributes: {
startLine: 4
endLine: 4
}
But what if code is dirty and there are multiple things in one line (if (a > b) { return a; } else { return b; }
, for example)? Where is information about position into line?
may be you can help me to add it by myself?
As I can see, I should start from PHP.Lexer
Notice: Use of undefined constant PHP_EOL - assumed 'PHP_EOL' in /console.htm on line 1
PHP_EOL
How can I use some functions in extension , such as "curl" and so on...
Is there any way to make it work?
Thanks a lot~
This code should be valid:
"{$object->object->hello()}";
Hi,
Do you plan to update your library to recognize PHP7 constructs?
http://php.net/manual/en/migration70.new-features.php
Thanks
When use CJK char as variable name in PHP, it would error. I found the reson is it use regular expression /^$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ to match variable , but JS string is unicode so the match would fail.
I suggest to use /^$[a-zA-Z_\u4E00-\u9FA5][a-zA-Z0-9_\u4E00-\u9FA5]*/ .
The following sort() method not working please solve this
<?php
$numbers = array(30, 71, 5, 29, 17);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
This code appears to cause an infinite loop when parsed:
<?php
$regex = "&$foo(?=[?.!,;:\"]?(\s|$))&";
php > $b = (object)array('name' => 'Pooh', 'age' => 24);
php > echo $b->name . PHP_EOL;
Pooh
php > print_r($b);
stdClass Object
(
[name] => Pooh
[age] => 24
)
In php.js, I get “Parse error: this.Node_Expr_Cast_Object is not a function in /console.htm on line undefined”.
I'm modifying zend_language_scanner.l
for javascript. Then, we can use jison to generate lexer from this file. Current lexer is buggy.
When running the command node build/build.js
it seems to be expecting a non-extant file src/include.js
. Full error is:
module.js:340
throw err;
^
Error: Cannot find module '../src/include.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/Me/projects/phpjs/build/build.js:10:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.