forked from endel/js2php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
539 lines (423 loc) · 17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
var core = require('./core'),
scope = require('./scope'),
utils = require('./utils'),
espree = require('espree');
module.exports = function(code) {
var ast = espree.parse(code, {
loc : true,
range : true,
tokens : true,
comment : true,
ecmaFeatures: {
arrowFunctions: true, // enable parsing of arrow functions
blockBindings: true, // enable parsing of let/const
destructuring: true, // enable parsing of destructured arrays and objects
regexYFlag: true, // enable parsing of regular expression y flag
regexUFlag: true, // enable parsing of regular expression u flag
templateStrings: true, // enable parsing of template strings
binaryLiterals: true, // enable parsing of binary literals
octalLiterals: true, // enable parsing of ES6 octal literals
unicodeCodePointEscapes: true, // enable parsing unicode code point escape sequences
defaultParams: true, // enable parsing of default parameters
restParams: true, // enable parsing of rest parameters
forOf: true, // enable parsing of for-of statement
objectLiteralComputedProperties: true, // enable parsing computed object literal properties
objectLiteralShorthandMethods: true, // enable parsing of shorthand object literal methods
objectLiteralShorthandProperties: true, // enable parsing of shorthand object literal properties
objectLiteralDuplicateProperties: true, // Allow duplicate object literal properties (except '__proto__')
generators: true, // enable parsing of generators/yield
spread: true, // enable parsing spread operator
superInFunctions: true, // enable super in functions
classes: true, // enable parsing classes
newTarget: false, // enable parsing of new.target
modules: true, // enable parsing of modules
jsx: true, // enable React JSX parsing
globalReturn: true, // enable return in global scope
experimentalObjectRestSpread: true // allow experimental object rest/spread
}
});
var rootScope = scope.create(ast, scope.KIND_ROOT);
function visit(node, parent) {
var content = "", semicolon = false;
// set parent node
if (parent) { node.parent = parent; }
if (node.type == "Program" || node.type == "BlockStatement" || node.type == "ClassBody") {
for (var i=0,length = node.body.length;i<length;i++) {
content += visit(node.body[i], node);
}
} else if (node.type == "VariableDeclaration") {
// declaration of one or multiple variables
for (var i=0,length=node.declarations.length;i<length;i++) {
content += visit(node.declarations[i], node);
}
} else if (node.type == "VariableDeclarator") {
scope.get(node).register(node);
// declaration of one variable
content = '$' + node.id.name;
if (node.init) {
content += ' = ' + visit(node.init, node);
semicolon = true;
} else if (node.parent.parent.type !== "ForInStatement" &&
node.parent.parent.type !== "ForStatement" &&
node.parent.parent.type !== "ForOfStatement") {
content += ' = null';
semicolon = true;
}
} else if (node.type == "Identifier") {
var identifier = (node.name || node.value);
if (!node.static && !node.isCallee && !node.isMemberExpression) {
scope.get(node).getDefinition(node);
content = "$";
}
content += identifier;
} else if (node.type == "Punctuator") {
content = node.value;
} else if (node.type == "Literal") {
var value = (node.raw.match(/^["']undefined["']$/)) ? "NULL" : node.raw;
content = value;
} else if (node.type == "BinaryExpression" || node.type == "LogicalExpression") {
if (node.operator == 'in') {
content = visit({
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'isset',
},
arguments: [{
type: 'MemberExpression',
computed: true,
object: node.right,
property: node.left
}]
}, node);
} else {
content = visit(node.left, node) + " " + node.operator + " " + visit(node.right, node);
}
} else if (node.type == "AssignmentExpression" ||
node.type == "AssignmentPattern") {
scope.get(node).register(node.left);
content = visit(node.left, node) + " " + (node.operator || "=") + " " + visit(node.right, node);
} else if (node.type == "ConditionalExpression") {
content = "(" + visit(node.test, node) + ")" +
" ? " + visit(node.consequent, node) +
" : " + visit(node.alternate, node);
} else if (node.type == "UnaryExpression") {
// override typeof unary expression
if (node.operator == 'typeof') {
content = visit({
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'gettype',
},
arguments: [node.argument]
}, node);
// override delete unary expression
} else if (node.operator == 'delete') {
content = visit({
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'unset',
},
arguments: [node.argument]
}, node);
} else {
content = node.operator + visit(node.argument, node);
}
} else if (node.type == "ExpressionStatement") {
content = visit(node.expression, node);
semicolon = true;
} else if (node.type == "CallExpression") {
var calleeDefined = scope.get(node).getDefinition(node.callee);
node.callee.isCallee = (!calleeDefined || calleeDefined && (calleeDefined.type != "Identifier" &&
calleeDefined.type != "VariableDeclarator"));
content += visit(node.callee, node);
// inline anonymous call
if ((node.callee.isCallee && node.callee.type == "FunctionDeclaration") ||
node.type == "ArrowFunctionExpression") {
var identifier = null;
if (node.parent.type == "VariableDeclarator") {
// var something = (function() { return 0; })();
identifier = node.parent.id.name;
} else if (node.parent.type == "AssignmentExpression") {
// something = (function() { return 0; })();
identifier = node.parent.left.name;
}
content += ";$" + identifier + " = " + "$" + identifier;
}
if (node.arguments) {
var arguments = [];
for (var i=0, length = node.arguments.length; i < length; i++) {
arguments.push( visit(node.arguments[i], node) );
}
content += "(" + arguments.join(', ') + ")";
}
// allow semicolon if parent node isn't MemberExpression or Property
if (node.parent && node.parent.type == "ExpressionStatement") {
semicolon = true;
}
} else if (node.type == "MemberExpression") {
var newNode = core.evaluate(node);
if (node != newNode) {
// fix parent node type
content = visit(newNode, node.parent);
} else {
var object, property;
if (node.object.type == "MemberExpression" && node.object.object && node.object.property) {
object = node.object.object,
property = node.object.property;
} else {
object = node.object;
property = node.property;
}
object.static = (object.name || object.value || "").match(/^[A-Z]/);
property.static = (property.name || property.value || "").match(/^[A-Z]/);
var accessor;
if (node.property.static && object.static) {
accessor = "\\"; // namespace
} else if ((property.static || object.static) || object.type == "Super") {
accessor = "::"; // static
} else {
accessor = "->"; // instance
}
if (node.computed) {
content = visit(node.object, node) + "[" + visit(node.property, node) + "]";
} else {
node.property.isMemberExpression = true;
content = visit(node.object, node) + accessor + visit(node.property, node);
}
}
} else if (node.type == "FunctionDeclaration" ||
node.type == "ArrowFunctionExpression") {
var param,
parameters = [],
defaults = node.defaults || [];
// function declaration creates a new scope
scope.create(node);
// compute function params
for (var i=0; i < node.params.length; i++) {
if (defaults[i]) {
param = visit({
type: "BinaryExpression",
left: node.params[i],
operator: '=',
right: defaults[i]
}, node);
} else {
param = visit(node.params[i], node)
}
// register parameter identifiers
if (scope.get(node).parent) {
scope.get(node).register(node.params[i]);
}
parameters.push(param);
}
var func_contents = visit(node.body, node),
using = scope.get(node).using;
content = "function " + ((node.id) ? node.id.name : "");
content += "(" + parameters.join(", ") + ") ";
// try to use parent's variables
// http://php.net/manual/pt_BR/functions.anonymous.php
if (using.length > 0) {
content += "use (" + using.map(function(identifier) {
return "&$" + identifier;
}).join(', ') + ") ";
}
content += "{\n";
content += func_contents;
content += "}\n";
} else if (node.type == "ObjectExpression") {
var properties = [];
for (var i=0; i < node.properties.length; i++) {
properties.push( visit(node.properties[i], node) )
}
content = "array(" + properties.join(", ") + ")";
} else if (node.type == "ArrayExpression") {
var elements = [];
for (var i=0; i < node.elements.length; i++) {
elements.push( visit(node.elements[i], node) )
}
content = "array(" + elements.join(", ") + ")";
} else if (node.type == "Property") {
var property = (node.key.type == 'Identifier') ? node.key.name : node.key.value;
content = '"'+property+'" => ' + visit(node.value, node);
} else if (node.type == "ReturnStatement") {
semicolon = true;
content = "return";
if (node.argument) {
content += " " + visit(node.argument, node);
}
} else if (node.type == "ClassDeclaration") {
content = "class " + node.id.name
if (node.superClass) {
content += " extends " + node.superClass.name;
}
var s = scope.create(node);
content += "\n{\n";
content += visit(node.body, node);
if (s.getters.length > 0) {
content += "function __get($_property) {\n";
for (var i=0;i<s.getters.length;i++) {
content += "if ($_property === '"+s.getters[i].key.name+"') {\n";
content += visit(s.getters[i].value.body, node);
content += "}\n";
}
content += "}\n";
}
if (s.setters.length > 0) {
content += "function __set($_property, $value) {\n";
for (var i=0;i<s.setters.length;i++) {
content += "if ($_property === '"+s.setters[i].key.name+"') {\n";
content += visit(s.setters[i].value.body, node);
content += "}\n";
}
content += "}\n";
}
content += "\n}\n";
} else if (node.type == "MethodDefinition") {
scope.get(node).register(node);
// define getters and setters on scope
if (node.kind == "get" || node.kind == "set") {
return "";
}
var isConstructor = (node.key.name == "constructor");
if (isConstructor) { node.key.name = "__construct"; }
// Re-use FunctionDeclaration structure for method definitions
node.value.type = "FunctionDeclaration";
node.value.id = { name: node.key.name };
var tmpContent = visit(node.value, node);
// try to define public properties there were defined on constructor
if (isConstructor) {
node.key.name = "__construct";
var definitions = scope.get(node.value).definitions;
for(var i in definitions) {
if (definitions[i] && definitions[i].type == "MemberExpression") {
definitions[i].property.isMemberExpression = false;
content += "public " + visit(definitions[i].property, null) + ";\n";
}
}
}
// every method is public.
content += "public ";
if (node.static) { content += "static "; }
content += tmpContent;
} else if (node.type == "ThisExpression") {
content = "$this";
} else if (node.type == "Super") {
content = "parent";
} else if (node.type == "IfStatement") {
content = "if ("+visit(node.test, node)+") {\n";
content += visit(node.consequent, node) + "}";
if (node.alternate) {
content += " else ";
if (node.alternate.type == "BlockStatement") {
content += "{"+visit(node.alternate, node)+"}";
} else {
content += visit(node.alternate, node)
}
}
} else if (node.type == "SequenceExpression") {
var expressions = [];
for (var i=0;i<node.expressions.length;i++) {
expressions.push( visit(node.expressions[i], node) );
}
content = expressions.join(', ') + ";";
} else if (node.type == "WhileStatement") {
content = "while (" + visit(node.test, node) + ") {";
content += visit(node.body, node);
content += "}";
} else if (node.type == "DoWhileStatement") {
content = "do {";
content += visit(node.body, node);
content += "} while (" + visit(node.test, node) + ")";
semicolon = true;
} else if (node.type == "ForStatement") {
content = "for (";
content += visit(node.init, node);
content += visit(node.test, node) + ";" ;
content += visit(node.update, node);
content += ") {";
content += visit(node.body, node);
content += "}";
} else if (node.type == "ForInStatement" || node.type == "ForOfStatement") {
content = "foreach (" + visit(node.right, node) + " as " + visit(node.left, node)+ " => $___)";
content += "{" + visit(node.body, node) + "}";
} else if (node.type == "UpdateExpression") {
if (node.prefix) {
content += node.operator;
}
content += visit(node.argument, node);
if (!node.prefix) {
content += node.operator;
}
} else if (node.type == "SwitchStatement") {
content = "switch (" + visit(node.discriminant, node) + ")";
content += "{";
for (var i=0; i < node.cases.length; i++) {
content += visit(node.cases[i], node) + "\n";
}
content += "}";
} else if (node.type == "SwitchCase") {
if (node.test) {
content += "case " + visit(node.test, node) + ":\n";
} else {
content = "default:\n";
}
for (var i=0; i < node.consequent.length; i++) {
content += visit(node.consequent[i], node);
}
} else if (node.type == "BreakStatement") {
content = "break;";
} else if (node.type == "NewExpression") {
// re-use CallExpression for NewExpression's
var newNode = utils.clone(node);
newNode.type = "CallExpression";
return "new " + visit(newNode, node);
} else if (node.type == "FunctionExpression") {
// Re-use FunctionDeclaration structure for method definitions
node.type = "FunctionDeclaration";
node.id = { name: node.id || "" };
content = visit(node, node.parent);
// Modules & Export (http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples)
} else if (node.type == "ModuleDeclaration") {
content = "namespace " + utils.classize(node.id.value) + ";\n";
content += visit(node.body, node);
} else if (node.type == "ExportNamedDeclaration") {
content = visit(node.declaration, node);
} else if (node.type == "ImportDeclaration") {
for (var i=0,length = node.specifiers.length;i<length;i++) {
content += visit(node.specifiers[i], node);
}
} else if (node.type == "ImportSpecifier") {
var namespace = utils.classize(node.parent.source.value);
content += "use \\" + namespace + "\\" + node.imported.name;
// alias
if (node.local) { content += " as " + node.local.name; }
content += ";\n";
} else if (node.type == "TemplateLiteral") {
var expressions = node.expressions
, quasis = node.quasis
, nodes = quasis.concat(expressions).sort(function(a, b) {
return b.range[0] < a.range[0];
})
, cooked = "";
for (var i=0; i<nodes.length; i++) {
if (nodes[i].type == "TemplateElement") {
cooked += nodes[i].value.cooked;
} else {
cooked += '{' + visit(nodes[i], node) + '}';
}
}
content += '"' + cooked + '"';
} else {
console.log("'" + node.type + "' not implemented.", node);
}
// append semicolon when required
if (semicolon && !content.match(/;\n?$/)) {
content += ";\n";
}
return content;
}
return "<?php\n" + visit(ast);
}